use crate::contract::{ApiOperation, ApiRouteInfo, SchemaType};
use axum::{handler::Handler, routing, Router};
use capy_core::{AppContext, AppError};
use schemars::JsonSchema;
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RouteInfo {
pub method: &'static str,
pub path: String,
}
#[derive(Clone)]
pub struct Routes {
router: Router<AppContext>,
inventory: Vec<RouteInfo>,
pub(crate) contracts: BTreeMap<usize, ApiOperation>,
pub(crate) contract_error: Option<String>,
exemptions: BTreeMap<usize, String>,
native_changes: Vec<Option<String>>,
}
impl Default for Routes {
fn default() -> Self {
Self::new()
}
}
macro_rules! route_method {
($method:ident, $name:literal, $doc:literal) => {
#[doc = $doc]
pub fn $method<H, T>(mut self, path: &str, handler: H) -> Self
where
H: Handler<T, AppContext>,
T: 'static,
{
self.router = self.router.route(path, routing::$method(handler));
self.inventory.push(RouteInfo {
method: $name,
path: path.to_owned(),
});
self
}
};
}
impl Routes {
pub fn new() -> Self {
Self {
router: Router::new().fallback(|| async { AppError::NotFound }),
inventory: Vec::new(),
contracts: BTreeMap::new(),
contract_error: None,
exemptions: BTreeMap::new(),
native_changes: Vec::new(),
}
}
route_method!(
get,
"GET",
"Register a GET handler (and Axum's implicit HEAD handler)."
);
route_method!(post, "POST", "Register a POST handler.");
route_method!(put, "PUT", "Register a PUT handler.");
route_method!(patch, "PATCH", "Register a PATCH handler.");
route_method!(delete, "DELETE", "Register a DELETE handler.");
fn describe(mut self, change: impl FnOnce(&mut ApiOperation)) -> Self {
if let Some(index) = self.inventory.len().checked_sub(1) {
change(self.contracts.entry(index).or_default());
} else {
self.contract_error = Some("Contract metadata must follow a route: .get(path, handler).operation(\"name\").response::<ResponseDto>().".into());
}
self
}
pub fn operation(self, id: impl Into<String>) -> Self {
self.describe(|operation| operation.id = Some(id.into()))
}
pub fn response<T: JsonSchema>(self) -> Self {
self.response_status::<T>(200)
}
pub fn created<T: JsonSchema>(self) -> Self {
self.response_status::<T>(201)
}
pub fn response_status<T: JsonSchema>(self, status: u16) -> Self {
self.describe(|operation| operation.response = Some((status, Some(SchemaType::of::<T>()))))
}
pub fn no_content(self) -> Self {
self.describe(|operation| operation.response = Some((204, None)))
}
pub fn binary_response(self, media_type: &str) -> Self {
self.describe(|operation| {
operation.response = Some((200, None));
operation.binary_response = Some(media_type.into());
})
}
pub fn body<T: JsonSchema>(self) -> Self {
self.describe(|operation| {
operation.body = Some(SchemaType::of::<T>());
for status in [400, 413, 415, 422] {
operation
.errors
.entry(status)
.or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
}
})
}
pub fn binary_body(self, media_type: &str) -> Self {
self.describe(|operation| {
operation.binary_body = Some(media_type.into());
for status in [413, 415] {
operation
.errors
.entry(status)
.or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
}
})
}
pub fn query<T: JsonSchema>(self) -> Self {
self.describe(|operation| {
operation.query = Some(SchemaType::of::<T>());
operation
.errors
.entry(400)
.or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
})
}
pub fn path<T: JsonSchema>(self, name: impl Into<String>) -> Self {
self.describe(|operation| {
operation.path.insert(name.into(), SchemaType::of::<T>());
operation
.errors
.entry(400)
.or_insert_with(SchemaType::of::<capy_core::ApiErrorResponse>);
})
}
pub fn authenticated(self) -> Self {
self.describe(|operation| operation.authenticated = true)
.error(401)
}
pub fn error(self, status: u16) -> Self {
self.error_response::<capy_core::ApiErrorResponse>(status)
}
pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
self.describe(|operation| {
operation.errors.insert(status, SchemaType::of::<T>());
})
}
pub fn tag(self, tag: impl Into<String>) -> Self {
self.describe(|operation| {
operation.tags.insert(tag.into());
})
}
pub fn summary(self, summary: impl Into<String>) -> Self {
self.describe(|operation| operation.summary = Some(summary.into()))
}
pub fn description(self, description: impl Into<String>) -> Self {
self.describe(|operation| operation.description = Some(description.into()))
}
pub fn api_inventory(&self) -> Vec<ApiRouteInfo> {
self.contracts
.iter()
.map(|(index, operation)| {
let route = &self.inventory[*index];
ApiRouteInfo {
method: route.method,
path: route.path.clone(),
operation_id: operation.id.clone(),
response: operation.response.as_ref().map(|(_, schema)| {
schema.as_ref().map_or_else(
|| {
operation.binary_response.as_ref().map_or_else(
|| "NoContent".into(),
|media| format!("binary {media}"),
)
},
|s| s.name.clone(),
)
}),
}
})
.collect()
}
pub fn inventory(&self) -> &[RouteInfo] {
&self.inventory
}
pub fn contract_exempt(mut self, reason: impl Into<String>) -> Self {
let reason = reason.into();
match self.inventory.len().checked_sub(1) {
Some(index) if !reason.trim().is_empty() => {
self.exemptions.insert(index, reason);
}
_ => {
self.contract_error =
Some("contract_exempt needs a preceding route and a nonempty reason.".into())
}
}
self
}
pub fn require_documented(&self, prefix: &str) -> capy_core::Result<()> {
if self.native_changes.iter().any(Option::is_none) {
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()));
}
let missing: Vec<_> = self
.inventory
.iter()
.enumerate()
.filter_map(|(index, route)| {
let path = format!("{prefix}{}", route.path);
((path == "/api" || path.starts_with("/api/"))
&& !self.contracts.contains_key(&index)
&& !self.exemptions.contains_key(&index))
.then(|| format!("{} {path}", route.method))
})
.collect();
if missing.is_empty() {
Ok(())
} else {
Err(AppError::Configuration(format!("Undocumented public API routes: {}. Add operation/response metadata or an explicit contract_exempt reason.", missing.join(", "))))
}
}
pub fn merge(mut self, other: Self) -> Self {
let offset = self.inventory.len();
self.router = self.router.merge(other.router.reset_fallback());
self.inventory.extend(other.inventory);
self.contracts.extend(
other
.contracts
.into_iter()
.map(|(index, operation)| (index + offset, operation)),
);
self.exemptions.extend(
other
.exemptions
.into_iter()
.map(|(index, reason)| (index + offset, reason)),
);
self.native_changes.extend(other.native_changes);
self.contract_error = self.contract_error.or(other.contract_error);
self
}
pub fn map_router(
mut self,
map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
) -> Self {
self.router = map(self.router);
self.native_changes.push(None);
self
}
pub fn map_router_exempt(
mut self,
reason: impl Into<String>,
map: impl FnOnce(Router<AppContext>) -> Router<AppContext>,
) -> Self {
let reason = reason.into();
if reason.trim().is_empty() {
self.contract_error = Some("map_router_exempt requires a nonempty reason.".into());
}
self.router = map(self.router);
self.native_changes.push(Some(reason));
self
}
pub fn into_router(self) -> Router<AppContext> {
self.router
.method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
}
}