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 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 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 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 pub fn authenticated(self) -> Self {
150 self.describe(|operation| operation.authenticated = true)
151 .error(401)
152 }
153
154 pub fn error(self, status: u16) -> Self {
156 self.error_response::<capy_core::ApiErrorResponse>(status)
157 }
158
159 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 pub fn tag(self, tag: impl Into<String>) -> Self {
168 self.describe(|operation| {
169 operation.tags.insert(tag.into());
170 })
171 }
172
173 pub fn summary(self, summary: impl Into<String>) -> Self {
175 self.describe(|operation| operation.summary = Some(summary.into()))
176 }
177
178 pub fn description(self, description: impl Into<String>) -> Self {
180 self.describe(|operation| operation.description = Some(description.into()))
181 }
182
183 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 pub fn inventory(&self) -> &[RouteInfo] {
205 &self.inventory
206 }
207
208 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 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 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 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 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 pub fn into_router(self) -> Router<AppContext> {
304 self.router
305 .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
306 }
307}