capy-http 0.10.0

Axum routing and JSON response conveniences for Capy.
Documentation
use crate::contract::{ApiOperation, ApiRouteInfo, SchemaType};
use axum::{handler::Handler, routing, Router};
use capy_core::{AppContext, AppError};
use schemars::JsonSchema;
use std::collections::BTreeMap;

/// A declared route, used by `capy routes` without connecting to a database.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RouteInfo {
    /// HTTP method (GET also accepts HEAD, following Axum).
    pub method: &'static str,
    /// Axum path, with parameters written as `{id}`.
    pub path: String,
}

/// A native Axum router together with a small, explicit route inventory.
#[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 {
    /// Start an empty router with JSON 404 and 405 responses.
    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
    }

    /// Give the preceding route a stable, unique API operation identifier.
    /// Handlers are not introspected; describe their actual JSON wire types explicitly.
    pub fn operation(self, id: impl Into<String>) -> Self {
        self.describe(|operation| operation.id = Some(id.into()))
    }

    /// Describe the preceding route's JSON 200 response using serialization semantics.
    pub fn response<T: JsonSchema>(self) -> Self {
        self.response_status::<T>(200)
    }

    /// Describe the preceding route's JSON 201 response.
    pub fn created<T: JsonSchema>(self) -> Self {
        self.response_status::<T>(201)
    }

    /// Describe another successful JSON status. Use `no_content` for HTTP 204.
    pub fn response_status<T: JsonSchema>(self, status: u16) -> Self {
        self.describe(|operation| operation.response = Some((status, Some(SchemaType::of::<T>()))))
    }

    /// Describe HTTP 204 with no response body.
    pub fn no_content(self) -> Self {
        self.describe(|operation| operation.response = Some((204, None)))
    }

    /// Describe a streamed binary HTTP 200 response with an explicit content type.
    pub fn binary_response(self, media_type: &str) -> Self {
        self.describe(|operation| {
            operation.response = Some((200, None));
            operation.binary_response = Some(media_type.into());
        })
    }

    /// Describe a required `Json<T>` or `Validated<T>` body using deserialization semantics.
    /// Adds the extractor's 400, 413, 415 and 422 error responses.
    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>);
            }
        })
    }

    /// Describe a bounded binary upload body and its content type.
    /// Enforce the MIME type in the handler; this method only declares the contract.
    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>);
            }
        })
    }

    /// Describe a flat query DTO, including Serde defaults and validation constraints.
    /// Adds the query extractor's 400 error response.
    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>);
        })
    }

    /// Describe one named path parameter's wire type. Repeat for multiple parameters.
    /// Adds the path extractor's 400 error response.
    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>);
        })
    }

    /// Declare session authentication on the preceding operation and add its 401 response.
    /// This is contract metadata; enforce identity with the AuthUser extractor.
    pub fn authenticated(self) -> Self {
        self.describe(|operation| operation.authenticated = true)
            .error(401)
    }

    /// Add a meaningful application error response using Capy's common envelope.
    pub fn error(self, status: u16) -> Self {
        self.error_response::<capy_core::ApiErrorResponse>(status)
    }

    /// Describe a custom JSON error envelope, for example readiness HTTP 503.
    pub fn error_response<T: JsonSchema>(self, status: u16) -> Self {
        self.describe(|operation| {
            operation.errors.insert(status, SchemaType::of::<T>());
        })
    }

    /// Group the preceding operation in API documentation.
    pub fn tag(self, tag: impl Into<String>) -> Self {
        self.describe(|operation| {
            operation.tags.insert(tag.into());
        })
    }

    /// Add a short summary to the preceding operation.
    pub fn summary(self, summary: impl Into<String>) -> Self {
        self.describe(|operation| operation.summary = Some(summary.into()))
    }

    /// Add an optional Markdown description to the preceding operation.
    pub fn description(self, description: impl Into<String>) -> Self {
        self.describe(|operation| operation.description = Some(description.into()))
    }

    /// Return explicitly registered API metadata without opening a database connection.
    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()
    }

    /// Return the routes declared through Capy's fluent API.
    pub fn inventory(&self) -> &[RouteInfo] {
        &self.inventory
    }

    /// Explicitly exempt the preceding route from strict documentation coverage.
    /// Supply a nonempty reason, for example an internal readiness probe.
    /// Existing metadata is still exported and validated.
    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
    }

    /// Check public API coverage. A public route is mounted with `App::api_routes`
    /// or has a full path equal to `/api` or beginning with `/api/`.
    /// Native router edits need an explicit exemption because Axum has no inventory API.
    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(", "))))
        }
    }

    /// Compose application-owned route modules, preserving contract metadata and exemptions.
    /// The receiving router owns the fallback; the merged module's fallback is discarded.
    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
    }

    /// Access Axum directly for middleware, nesting, and other native features.
    /// Routes added here are not included in Capy's route inventory.
    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
    }

    /// Apply a native router change with an explicit strict-contract exemption.
    /// Capy cannot verify routes introduced here. Use only for reviewed middleware,
    /// non-public routes, or deliberately excluded/manual APIs; document the reason.
    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
    }

    /// Consume this wrapper and return the native Axum router, awaiting state.
    pub fn into_router(self) -> Router<AppContext> {
        self.router
            .method_not_allowed_fallback(|| async { AppError::MethodNotAllowed })
    }
}