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#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct RouteInfo {
10 pub method: &'static str,
12 pub path: String,
14}
15
16#[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 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 pub fn operation(self, id: impl Into<String>) -> Self {
86 self.describe(|operation| operation.id = Some(id.into()))
87 }
88
89 pub fn response<T: JsonSchema>(self) -> Self {
91 self.response_status::<T>(200)
92 }
93
94 pub fn created<T: JsonSchema>(self) -> Self {
96 self.response_status::<T>(201)
97 }
98
99 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 pub fn no_content(self) -> Self {
106 self.describe(|operation| operation.response = Some((204, None)))
107 }
108
109 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 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 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 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 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 pub fn authenticated(self) -> Self {
172 self.describe(|operation| operation.authenticated = true)
173 .error(401)
174 }
175
176 pub fn error(self, status: u16) -> Self {
178 self.error_response::<capy_core::ApiErrorResponse>(status)
179 }
180
181 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 pub fn tag(self, tag: impl Into<String>) -> Self {
190 self.describe(|operation| {
191 operation.tags.insert(tag.into());
192 })
193 }
194
195 pub fn summary(self, summary: impl Into<String>) -> Self {
197 self.describe(|operation| operation.summary = Some(summary.into()))
198 }
199
200 pub fn description(self, description: impl Into<String>) -> Self {
202 self.describe(|operation| operation.description = Some(description.into()))
203 }
204
205 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 pub fn inventory(&self) -> &[RouteInfo] {
233 &self.inventory
234 }
235
236 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 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 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 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 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 pub fn into_router(self) -> Router<AppContext> {
332 self.router
333 .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
334 }
335}