footing 0.6.3

Feature-gated foundations for Rust backend services
Documentation
use axum::{
    Router,
    handler::Handler,
    routing::{MethodFilter, on},
};

use super::{
    EndpointContract, EndpointContractRegistry, EndpointContractValidationError, EndpointMethod,
};
#[cfg(feature = "http-stack")]
use crate::http::{HttpMiddlewareError, HttpMiddlewareStack};

/// Registers each handler from its contract's method and path.
///
/// With `http-stack`, `into_router` checks middleware policies against the routes
/// actually registered here. `into_parts` supports application-managed middleware.
/// Use final application paths when policies match paths:
/// nesting the finished router changes Axum's `MatchedPath` and requires the
/// caller to review those policies. Contracts describe authorization requirements;
/// the application enforces them through
/// an authorization hook before idempotency can replay a response.
/// A replayable route restricting identity categories or declaring permissions
/// requires this hook when finishing.
///
/// ```rust
/// use footing::http::{EndpointContract, EndpointMethod, EndpointPathPattern,
///     EndpointRouter};
///
/// let health = EndpointContract::new(
///     EndpointMethod::Get, EndpointPathPattern::exact("/health"),
/// );
/// let (app, contracts) = EndpointRouter::new()
///     .route(health, || async { "ok" })?
///     .with_api_fallbacks()
///     .into_parts();
/// # let _: axum::Router = app;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
pub struct EndpointRouter<S = (), P: Copy + 'static = &'static str> {
    router: Router<S>,
    contracts: Vec<EndpointContract<P>>,
}

impl<S, P> Default for EndpointRouter<S, P>
where
    S: Clone + Send + Sync + 'static,
    P: Copy + 'static,
{
    fn default() -> Self {
        Self {
            router: Router::new(),
            contracts: Vec::new(),
        }
    }
}

impl<S, P> EndpointRouter<S, P>
where
    S: Clone + Send + Sync + 'static,
    P: Copy + 'static,
{
    /// Starts an empty router with no detached route declarations.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a handler at the method and path specified by its contract.
    ///
    /// Duplicate contracts and invalid metadata return errors. As with Axum's
    /// `Router::route`, conflicting path captures panic during registration.
    pub fn route<H, T>(
        mut self,
        contract: EndpointContract<P>,
        handler: H,
    ) -> Result<Self, EndpointContractValidationError>
    where
        H: Handler<T, S>,
        T: 'static,
    {
        self.contracts().validate_addition(&contract)?;
        let filter = match contract.method() {
            EndpointMethod::Delete => MethodFilter::DELETE,
            EndpointMethod::Get => MethodFilter::GET,
            EndpointMethod::Head => MethodFilter::HEAD,
            EndpointMethod::Options => MethodFilter::OPTIONS,
            EndpointMethod::Patch => MethodFilter::PATCH,
            EndpointMethod::Post => MethodFilter::POST,
            EndpointMethod::Put => MethodFilter::PUT,
        };
        self.router = self
            .router
            .route(contract.path().as_str(), on(filter, handler));
        self.contracts.push(contract);
        Ok(self)
    }

    /// Returns the contracts of the registered handlers, for inspection or docs.
    #[must_use]
    pub fn contracts(&self) -> EndpointContractRegistry<'_, P> {
        EndpointContractRegistry::new(&self.contracts)
    }

    /// Installs Problem Details handlers for missing routes and unsupported methods.
    ///
    /// Call after registering all routes and before applying middleware. Axum
    /// preserves each route's `Allow` header. These API fallbacks do not serve SPA
    /// pages; see [`crate::http::routing`] for mounting an API alongside a frontend.
    #[must_use]
    pub fn with_api_fallbacks(mut self) -> Self {
        self.router = self
            .router
            .fallback(crate::http::route_not_found)
            .method_not_allowed_fallback(crate::http::method_not_allowed);
        self
    }

    /// Returns registered routes and contracts for application-managed middleware.
    /// Runtime policies are not validated by this method.
    pub fn into_parts(self) -> (Router<S>, Vec<EndpointContract<P>>) {
        (self.router, self.contracts)
    }

    /// Validates and applies the stack to the registered routes.
    #[cfg(feature = "http-stack")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
    pub fn into_router(self, stack: HttpMiddlewareStack) -> Result<Router<S>, HttpMiddlewareError> {
        stack.validate_endpoint_contracts(&self.contracts())?;
        Ok(stack.apply(self.router))
    }
}