Skip to main content

capy_http/
routes.rs

1use crate::contract::{ApiOperation, ApiRouteInfo, SchemaType};
2use axum::{handler::Handler, routing, Router};
3use capy_core::{AppContext, AppError};
4use schemars::JsonSchema;
5use std::collections::BTreeMap;
6
7/// A declared route, used by `capy routes` without connecting to a database.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct RouteInfo {
10    /// HTTP method (GET also accepts HEAD, following Axum).
11    pub method: &'static str,
12    /// Axum path, with parameters written as `{id}`.
13    pub path: String,
14}
15
16/// A native Axum router together with a small, explicit route inventory.
17#[derive(Clone)]
18pub struct Routes {
19    router: Router<AppContext>,
20    inventory: Vec<RouteInfo>,
21    pub(crate) contracts: BTreeMap<usize, ApiOperation>,
22    pub(crate) contract_error: Option<String>,
23    exemptions: BTreeMap<usize, String>,
24    native_changes: Vec<Option<String>>,
25}
26
27impl Default for Routes {
28    fn default() -> Self {
29        Self::new()
30    }
31}
32
33macro_rules! route_method {
34    ($method:ident, $name:literal, $doc:literal) => {
35        #[doc = $doc]
36        pub fn $method<H, T>(mut self, path: &str, handler: H) -> Self
37        where
38            H: Handler<T, AppContext>,
39            T: 'static,
40        {
41            self.router = self.router.route(path, routing::$method(handler));
42            self.inventory.push(RouteInfo {
43                method: $name,
44                path: path.to_owned(),
45            });
46            self
47        }
48    };
49}
50
51impl Routes {
52    /// Start an empty router with JSON 404 and 405 responses.
53    pub fn new() -> Self {
54        Self {
55            router: Router::new().fallback(|| async { AppError::NotFound }),
56            inventory: Vec::new(),
57            contracts: BTreeMap::new(),
58            contract_error: None,
59            exemptions: BTreeMap::new(),
60            native_changes: Vec::new(),
61        }
62    }
63
64    route_method!(
65        get,
66        "GET",
67        "Register a GET handler (and Axum's implicit HEAD handler)."
68    );
69    route_method!(post, "POST", "Register a POST handler.");
70    route_method!(put, "PUT", "Register a PUT handler.");
71    route_method!(patch, "PATCH", "Register a PATCH handler.");
72    route_method!(delete, "DELETE", "Register a DELETE handler.");
73
74    fn describe(mut self, change: impl FnOnce(&mut ApiOperation)) -> Self {
75        if let Some(index) = self.inventory.len().checked_sub(1) {
76            change(self.contracts.entry(index).or_default());
77        } else {
78            self.contract_error = Some("Contract metadata must follow a route: .get(path, handler).operation(\"name\").response::<ResponseDto>().".into());
79        }
80        self
81    }
82
83    /// Give the preceding route a stable, unique API operation identifier.
84    /// Handlers are not introspected; describe their actual JSON wire types explicitly.
85    pub fn operation(self, id: impl Into<String>) -> Self {
86        self.describe(|operation| operation.id = Some(id.into()))
87    }
88
89    /// Describe the preceding route's JSON 200 response using serialization semantics.
90    pub fn response<T: JsonSchema>(self) -> Self {
91        self.response_status::<T>(200)
92    }
93
94    /// Describe the preceding route's JSON 201 response.
95    pub fn created<T: JsonSchema>(self) -> Self {
96        self.response_status::<T>(201)
97    }
98
99    /// Describe another successful JSON status. Use `no_content` for HTTP 204.
100    pub fn response_status<T: JsonSchema>(self, status: u16) -> Self {
101        self.describe(|operation| operation.response = Some((status, Some(SchemaType::of::<T>()))))
102    }
103
104    /// Describe HTTP 204 with no response body.
105    pub fn no_content(self) -> Self {
106        self.describe(|operation| operation.response = Some((204, None)))
107    }
108
109    /// Describe a required `Json<T>` or `Validated<T>` body using deserialization semantics.
110    /// Adds the extractor's 400, 413, 415 and 422 error responses.
111    pub fn body<T: JsonSchema>(self) -> Self {
112        self.describe(|operation| {
113            operation.body = Some(SchemaType::of::<T>());
114            for status in [400, 413, 415, 422] {
115                operation
116                    .errors
117                    .entry(status)
118                    .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
119            }
120        })
121    }
122
123    /// Describe a flat query DTO, including Serde defaults and validation constraints.
124    /// Adds the query extractor's 400 error response.
125    pub fn query<T: JsonSchema>(self) -> Self {
126        self.describe(|operation| {
127            operation.query = Some(SchemaType::of::<T>());
128            operation
129                .errors
130                .entry(400)
131                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
132        })
133    }
134
135    /// Describe one named path parameter's wire type. Repeat for multiple parameters.
136    /// Adds the path extractor's 400 error response.
137    pub fn path<T: JsonSchema>(self, name: impl Into<String>) -> Self {
138        self.describe(|operation| {
139            operation.path.insert(name.into(), SchemaType::of::<T>());
140            operation
141                .errors
142                .entry(400)
143                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
144        })
145    }
146
147    /// Declare session authentication on the preceding operation and add its 401 response.
148    /// This is contract metadata; enforce identity with the AuthUser extractor.
149    pub fn authenticated(self) -> Self {
150        self.describe(|operation| operation.authenticated = true)
151            .error(401)
152    }
153
154    /// Add a meaningful application error response using Capy's common envelope.
155    pub fn error(self, status: u16) -> Self {
156        self.error_response::<capy_core::ApiErrorResponse>(status)
157    }
158
159    /// Describe a custom JSON error envelope, for example readiness HTTP 503.
160    pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
161        self.describe(|operation| {
162            operation.errors.insert(status, SchemaType::of::<T>());
163        })
164    }
165
166    /// Group the preceding operation in API documentation.
167    pub fn tag(self, tag: impl Into<String>) -> Self {
168        self.describe(|operation| {
169            operation.tags.insert(tag.into());
170        })
171    }
172
173    /// Add a short summary to the preceding operation.
174    pub fn summary(self, summary: impl Into<String>) -> Self {
175        self.describe(|operation| operation.summary = Some(summary.into()))
176    }
177
178    /// Add an optional Markdown description to the preceding operation.
179    pub fn description(self, description: impl Into<String>) -> Self {
180        self.describe(|operation| operation.description = Some(description.into()))
181    }
182
183    /// Return explicitly registered API metadata without opening a database connection.
184    pub fn api_inventory(&self) -> Vec<ApiRouteInfo> {
185        self.contracts
186            .iter()
187            .map(|(index, operation)| {
188                let route = &self.inventory[*index];
189                ApiRouteInfo {
190                    method: route.method,
191                    path: route.path.clone(),
192                    operation_id: operation.id.clone(),
193                    response: operation.response.as_ref().map(|(_, schema)| {
194                        schema
195                            .as_ref()
196                            .map_or_else(|| "NoContent".into(), |s| s.name.clone())
197                    }),
198                }
199            })
200            .collect()
201    }
202
203    /// Return the routes declared through Capy's fluent API.
204    pub fn inventory(&self) -> &[RouteInfo] {
205        &self.inventory
206    }
207
208    /// Explicitly exempt the preceding route from strict documentation coverage.
209    /// Supply a nonempty reason, for example an internal readiness probe.
210    /// Existing metadata is still exported and validated.
211    pub fn contract_exempt(mut self, reason: impl Into<String>) -> Self {
212        let reason = reason.into();
213        match self.inventory.len().checked_sub(1) {
214            Some(index) if !reason.trim().is_empty() => {
215                self.exemptions.insert(index, reason);
216            }
217            _ => {
218                self.contract_error =
219                    Some("contract_exempt needs a preceding route and a nonempty reason.".into())
220            }
221        }
222        self
223    }
224
225    /// Check public API coverage. A public route is mounted with `App::api_routes`
226    /// or has a full path equal to `/api` or beginning with `/api/`.
227    /// Native router edits need an explicit exemption because Axum has no inventory API.
228    pub fn require_documented(&self, prefix: &str) -> capy_core::Result<()> {
229        if self.native_changes.iter().any(Option::is_none) {
230            return Err(AppError::Configuration("Strict API contracts cannot inspect map_router changes. Use Capy route declarations or map_router_exempt with a reviewed reason for the native changes.".into()));
231        }
232        let missing: Vec<_> = self
233            .inventory
234            .iter()
235            .enumerate()
236            .filter_map(|(index, route)| {
237                let path = format!("{prefix}{}", route.path);
238                ((path == "/api" || path.starts_with("/api/"))
239                    && !self.contracts.contains_key(&index)
240                    && !self.exemptions.contains_key(&index))
241                .then(|| format!("{} {path}", route.method))
242            })
243            .collect();
244        if missing.is_empty() {
245            Ok(())
246        } else {
247            Err(AppError::Configuration(format!("Undocumented public API routes: {}. Add operation/response metadata or an explicit contract_exempt reason.", missing.join(", "))))
248        }
249    }
250
251    /// Compose application-owned route modules, preserving contract metadata and exemptions.
252    /// The receiving router owns the fallback; the merged module's fallback is discarded.
253    pub fn merge(mut self, other: Self) -> Self {
254        let offset = self.inventory.len();
255        self.router = self.router.merge(other.router.reset_fallback());
256        self.inventory.extend(other.inventory);
257        self.contracts.extend(
258            other
259                .contracts
260                .into_iter()
261                .map(|(index, operation)| (index + offset, operation)),
262        );
263        self.exemptions.extend(
264            other
265                .exemptions
266                .into_iter()
267                .map(|(index, reason)| (index + offset, reason)),
268        );
269        self.native_changes.extend(other.native_changes);
270        self.contract_error = self.contract_error.or(other.contract_error);
271        self
272    }
273
274    /// Access Axum directly for middleware, nesting, and other native features.
275    /// Routes added here are not included in Capy's route inventory.
276    pub fn map_router(
277        mut self,
278        map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
279    ) -> Self {
280        self.router = map(self.router);
281        self.native_changes.push(None);
282        self
283    }
284
285    /// Apply a native router change with an explicit strict-contract exemption.
286    /// Capy cannot verify routes introduced here. Use only for reviewed middleware,
287    /// non-public routes, or deliberately excluded/manual APIs; document the reason.
288    pub fn map_router_exempt(
289        mut self,
290        reason: impl Into<String>,
291        map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
292    ) -> Self {
293        let reason = reason.into();
294        if reason.trim().is_empty() {
295            self.contract_error = Some("map_router_exempt requires a nonempty reason.".into());
296        }
297        self.router = map(self.router);
298        self.native_changes.push(Some(reason));
299        self
300    }
301
302    /// Consume this wrapper and return the native Axum router, awaiting state.
303    pub fn into_router(self) -> Router<AppContext> {
304        self.router
305            .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
306    }
307}