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 streamed binary HTTP 200 response with an explicit content type.
110    pub fn binary_response(self, media_type: &str) -> Self {
111        self.describe(|operation| {
112            operation.response = Some((200, None));
113            operation.binary_response = Some(media_type.into());
114        })
115    }
116
117    /// Describe a required `Json<T>` or `Validated<T>` body using deserialization semantics.
118    /// Adds the extractor's 400, 413, 415 and 422 error responses.
119    pub fn body<T: JsonSchema>(self) -> Self {
120        self.describe(|operation| {
121            operation.body = Some(SchemaType::of::<T>());
122            for status in [400, 413, 415, 422] {
123                operation
124                    .errors
125                    .entry(status)
126                    .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
127            }
128        })
129    }
130
131    /// Describe a bounded binary upload body and its content type.
132    /// Enforce the MIME type in the handler; this method only declares the contract.
133    pub fn binary_body(self, media_type: &str) -> Self {
134        self.describe(|operation| {
135            operation.binary_body = Some(media_type.into());
136            for status in [413, 415] {
137                operation
138                    .errors
139                    .entry(status)
140                    .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
141            }
142        })
143    }
144
145    /// Describe a flat query DTO, including Serde defaults and validation constraints.
146    /// Adds the query extractor's 400 error response.
147    pub fn query<T: JsonSchema>(self) -> Self {
148        self.describe(|operation| {
149            operation.query = Some(SchemaType::of::<T>());
150            operation
151                .errors
152                .entry(400)
153                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
154        })
155    }
156
157    /// Describe one named path parameter's wire type. Repeat for multiple parameters.
158    /// Adds the path extractor's 400 error response.
159    pub fn path<T: JsonSchema>(self, name: impl Into<String>) -> Self {
160        self.describe(|operation| {
161            operation.path.insert(name.into(), SchemaType::of::<T>());
162            operation
163                .errors
164                .entry(400)
165                .or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
166        })
167    }
168
169    /// Declare session authentication on the preceding operation and add its 401 response.
170    /// This is contract metadata; enforce identity with the AuthUser extractor.
171    pub fn authenticated(self) -> Self {
172        self.describe(|operation| operation.authenticated = true)
173            .error(401)
174    }
175
176    /// Add a meaningful application error response using Capy's common envelope.
177    pub fn error(self, status: u16) -> Self {
178        self.error_response::<capy_core::ApiErrorResponse>(status)
179    }
180
181    /// Describe a custom JSON error envelope, for example readiness HTTP 503.
182    pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
183        self.describe(|operation| {
184            operation.errors.insert(status, SchemaType::of::<T>());
185        })
186    }
187
188    /// Group the preceding operation in API documentation.
189    pub fn tag(self, tag: impl Into<String>) -> Self {
190        self.describe(|operation| {
191            operation.tags.insert(tag.into());
192        })
193    }
194
195    /// Add a short summary to the preceding operation.
196    pub fn summary(self, summary: impl Into<String>) -> Self {
197        self.describe(|operation| operation.summary = Some(summary.into()))
198    }
199
200    /// Add an optional Markdown description to the preceding operation.
201    pub fn description(self, description: impl Into<String>) -> Self {
202        self.describe(|operation| operation.description = Some(description.into()))
203    }
204
205    /// Return explicitly registered API metadata without opening a database connection.
206    pub fn api_inventory(&self) -> Vec<ApiRouteInfo> {
207        self.contracts
208            .iter()
209            .map(|(index, operation)| {
210                let route = &self.inventory[*index];
211                ApiRouteInfo {
212                    method: route.method,
213                    path: route.path.clone(),
214                    operation_id: operation.id.clone(),
215                    response: operation.response.as_ref().map(|(_, schema)| {
216                        schema.as_ref().map_or_else(
217                            || {
218                                operation.binary_response.as_ref().map_or_else(
219                                    || "NoContent".into(),
220                                    |media| format!("binary {media}"),
221                                )
222                            },
223                            |s| s.name.clone(),
224                        )
225                    }),
226                }
227            })
228            .collect()
229    }
230
231    /// Return the routes declared through Capy's fluent API.
232    pub fn inventory(&self) -> &[RouteInfo] {
233        &self.inventory
234    }
235
236    /// Explicitly exempt the preceding route from strict documentation coverage.
237    /// Supply a nonempty reason, for example an internal readiness probe.
238    /// Existing metadata is still exported and validated.
239    pub fn contract_exempt(mut self, reason: impl Into<String>) -> Self {
240        let reason = reason.into();
241        match self.inventory.len().checked_sub(1) {
242            Some(index) if !reason.trim().is_empty() => {
243                self.exemptions.insert(index, reason);
244            }
245            _ => {
246                self.contract_error =
247                    Some("contract_exempt needs a preceding route and a nonempty reason.".into())
248            }
249        }
250        self
251    }
252
253    /// Check public API coverage. A public route is mounted with `App::api_routes`
254    /// or has a full path equal to `/api` or beginning with `/api/`.
255    /// Native router edits need an explicit exemption because Axum has no inventory API.
256    pub fn require_documented(&self, prefix: &str) -> capy_core::Result<()> {
257        if self.native_changes.iter().any(Option::is_none) {
258            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()));
259        }
260        let missing: Vec<_> = self
261            .inventory
262            .iter()
263            .enumerate()
264            .filter_map(|(index, route)| {
265                let path = format!("{prefix}{}", route.path);
266                ((path == "/api" || path.starts_with("/api/"))
267                    && !self.contracts.contains_key(&index)
268                    && !self.exemptions.contains_key(&index))
269                .then(|| format!("{} {path}", route.method))
270            })
271            .collect();
272        if missing.is_empty() {
273            Ok(())
274        } else {
275            Err(AppError::Configuration(format!("Undocumented public API routes: {}. Add operation/response metadata or an explicit contract_exempt reason.", missing.join(", "))))
276        }
277    }
278
279    /// Compose application-owned route modules, preserving contract metadata and exemptions.
280    /// The receiving router owns the fallback; the merged module's fallback is discarded.
281    pub fn merge(mut self, other: Self) -> Self {
282        let offset = self.inventory.len();
283        self.router = self.router.merge(other.router.reset_fallback());
284        self.inventory.extend(other.inventory);
285        self.contracts.extend(
286            other
287                .contracts
288                .into_iter()
289                .map(|(index, operation)| (index + offset, operation)),
290        );
291        self.exemptions.extend(
292            other
293                .exemptions
294                .into_iter()
295                .map(|(index, reason)| (index + offset, reason)),
296        );
297        self.native_changes.extend(other.native_changes);
298        self.contract_error = self.contract_error.or(other.contract_error);
299        self
300    }
301
302    /// Access Axum directly for middleware, nesting, and other native features.
303    /// Routes added here are not included in Capy's route inventory.
304    pub fn map_router(
305        mut self,
306        map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
307    ) -> Self {
308        self.router = map(self.router);
309        self.native_changes.push(None);
310        self
311    }
312
313    /// Apply a native router change with an explicit strict-contract exemption.
314    /// Capy cannot verify routes introduced here. Use only for reviewed middleware,
315    /// non-public routes, or deliberately excluded/manual APIs; document the reason.
316    pub fn map_router_exempt(
317        mut self,
318        reason: impl Into<String>,
319        map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
320    ) -> Self {
321        let reason = reason.into();
322        if reason.trim().is_empty() {
323            self.contract_error = Some("map_router_exempt requires a nonempty reason.".into());
324        }
325        self.router = map(self.router);
326        self.native_changes.push(Some(reason));
327        self
328    }
329
330    /// Consume this wrapper and return the native Axum router, awaiting state.
331    pub fn into_router(self) -> Router<AppContext> {
332        self.router
333            .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
334    }
335}