footing 0.1.18

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

use super::{
    EndpointContract, EndpointContractRegistry, EndpointContractValidationError, EndpointMethod,
};
use crate::http::{HttpMiddlewareError, HttpMiddlewareStack};

/// Registers each handler from its contract's method and path.
///
/// Finishing the router checks middleware policies against the routes actually
/// registered here. 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;
/// handlers must still enforce permissions.
///
/// ```rust
/// use footing::http::{EndpointContract, EndpointMethod, EndpointPathPattern,
///     EndpointRateLimit, EndpointRouter, HttpMiddlewareConfig, HttpMiddlewareStack};
///
/// let health: EndpointContract = EndpointContract::new(
///     EndpointMethod::Get, EndpointPathPattern::Exact("/health"),
/// ).with_rate_limit(EndpointRateLimit::Exempt);
/// let stack = HttpMiddlewareStack::builder(HttpMiddlewareConfig::minimal()).build()?;
/// let app: axum::Router = EndpointRouter::new()
///     .route(health, || async { "ok" })?
///     .into_router(stack)?;
/// # 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)?;
        self.contracts.push(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));
        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)
    }

    /// Validates and applies the stack to the registered routes.
    pub fn into_router(self, stack: HttpMiddlewareStack) -> Result<Router<S>, HttpMiddlewareError> {
        stack.validate_endpoint_contracts(&self.contracts())?;
        Ok(stack.apply(self.router))
    }
}