footing 0.1.12

Feature-gated foundations for Rust backend services
Documentation
use std::{collections::BTreeMap, fmt};

use axum::{
    Extension, Router,
    handler::Handler,
    http::Method,
    routing::{MethodFilter, MethodRouter, on},
};
use thiserror::Error;
use utoipa::openapi::{
    OpenApi,
    path::{Parameter, ParameterIn, PathItem},
};

use crate::{
    pagination::PageLimits,
    result::{ClassifyError, ErrorKind},
};

use super::{
    contracts::{operations, operations_mut},
    cursor_pagination_parameters, offset_pagination_parameters,
};

/// Invalid or conflicting documented route registration.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenApiRouteError {
    /// The document does not describe the expected route set.
    #[error("invalid OpenAPI route document: {reason}")]
    InvalidDocument {
        /// Description of the violated registration requirement.
        reason: &'static str,
    },
    /// Registering an operation twice would overwrite its documentation.
    #[error("OpenAPI operation {method} {path} is already registered")]
    DuplicateOperation {
        /// Duplicated HTTP method.
        method: &'static str,
        /// Duplicated path.
        path: String,
    },
    /// Two routes assign different definitions to the same component name.
    #[error("conflicting OpenAPI {kind} component {name}")]
    ConflictingComponent {
        /// Kind of component.
        kind: &'static str,
        /// Component name that must be disambiguated.
        name: String,
    },
    /// Routes disagree on metadata shared by all operations at a path.
    #[error("conflicting OpenAPI {field} for path {path}")]
    ConflictingPathMetadata {
        /// Shared metadata field.
        field: &'static str,
        /// Path whose metadata conflicts.
        path: String,
    },
    /// Multiple pagination layers could override each other at runtime.
    #[error("pagination is already configured for this route")]
    PaginationAlreadyConfigured,
}

impl ClassifyError for OpenApiRouteError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidDocument { .. } => "openapi_invalid_route_document",
            Self::DuplicateOperation { .. } => "openapi_duplicate_operation",
            Self::ConflictingComponent { .. } => "openapi_conflicting_component",
            Self::ConflictingPathMetadata { .. } => "openapi_conflicting_path_metadata",
            Self::PaginationAlreadyConfigured => "openapi_pagination_already_configured",
        })
    }
}

/// An Axum handler and its generated operation metadata.
///
/// Construct with [`super::route!`] so the handler, methods, paths and schemas
/// come from the same `utoipa::path` annotation. Axum's normal route-pattern
/// validation applies when the route is registered.
#[must_use]
pub struct OpenApiRoute<S = ()> {
    router: MethodRouter<S>,
    document: OpenApi,
    path: String,
    pagination_configured: bool,
}

impl<S> fmt::Debug for OpenApiRoute<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OpenApiRoute")
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

impl<S: Clone + Send + Sync + 'static> OpenApiRoute<S> {
    /// Associates a handler with its generated single-path document.
    ///
    /// Prefer [`super::route!`], which supplies the matching document automatically.
    pub fn from_handler<H, T>(handler: H, mut document: OpenApi) -> Result<Self, OpenApiRouteError>
    where
        H: Handler<T, S>,
        T: 'static,
    {
        if document.paths.paths.len() != 1 {
            return Err(OpenApiRouteError::InvalidDocument {
                reason: "a handler must describe exactly one path",
            });
        }
        let (path, item) =
            document
                .paths
                .paths
                .iter_mut()
                .next()
                .ok_or(OpenApiRouteError::InvalidDocument {
                    reason: "missing handler path",
                })?;
        if !path.starts_with('/') {
            return Err(OpenApiRouteError::InvalidDocument {
                reason: "handler paths must start with /",
            });
        }
        let mut filter: Option<MethodFilter> = None;
        for (method, operation) in operations(item) {
            if operation.is_some() {
                let method = Method::from_bytes(method.as_bytes()).map_err(|_| {
                    OpenApiRouteError::InvalidDocument {
                        reason: "invalid HTTP method",
                    }
                })?;
                let next = MethodFilter::try_from(method).map_err(|_| {
                    OpenApiRouteError::InvalidDocument {
                        reason: "unsupported HTTP method",
                    }
                })?;
                filter = Some(filter.map_or(next, |filter| filter.or(next)));
            }
        }
        let filter = filter.ok_or(OpenApiRouteError::InvalidDocument {
            reason: "a handler must describe at least one operation",
        })?;
        normalize_path_inheritance(item)?;
        Ok(Self {
            path: path.clone(),
            router: on(filter, handler),
            document,
            pagination_configured: false,
        })
    }

    /// Installs cursor pagination limits and updates the documented parameters.
    ///
    /// This replaces pagination schemas/defaults while retaining unrelated query
    /// parameters and existing descriptions. Use this instead of installing an
    /// independent `Extension<PageLimits>` on a documented route.
    pub fn with_cursor_pagination(self, limits: PageLimits) -> Result<Self, OpenApiRouteError> {
        self.with_pagination(limits, cursor_pagination_parameters(limits))
    }

    /// Installs offset pagination limits and updates the documented parameters.
    pub fn with_offset_pagination(self, limits: PageLimits) -> Result<Self, OpenApiRouteError> {
        self.with_pagination(limits, offset_pagination_parameters(limits))
    }

    fn with_pagination(
        mut self,
        limits: PageLimits,
        parameters: Vec<Parameter>,
    ) -> Result<Self, OpenApiRouteError> {
        if self.pagination_configured {
            return Err(OpenApiRouteError::PaginationAlreadyConfigured);
        }
        for item in self.document.paths.paths.values_mut() {
            for operation in operations_mut(item) {
                let target = operation.parameters.get_or_insert_default();
                for parameter in &parameters {
                    // The route configuration owns the wire constraints. Keep user
                    // descriptions and unrelated metadata when overriding defaults.
                    if let Some(existing) = target
                        .iter_mut()
                        .find(|existing| same_parameter(existing, parameter))
                    {
                        existing.schema = parameter.schema.clone();
                        existing.required = parameter.required.clone();
                    } else {
                        target.push(parameter.clone());
                    }
                }
            }
        }
        self.router = self.router.layer(Extension(limits));
        self.pagination_configured = true;
        Ok(self)
    }
}

/// Registers Axum routes and OpenAPI operations together.
///
/// Start with a document containing API metadata and reusable components, then
/// add handlers with [`super::route!`]. Split into the native types when finished
/// to install application middleware, state and documentation routes.
#[must_use]
pub struct OpenApiRouter<S = ()> {
    router: Router<S>,
    document: OpenApi,
}

impl<S> fmt::Debug for OpenApiRouter<S> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OpenApiRouter")
            .field("paths", &self.document.paths.paths.len())
            .finish_non_exhaustive()
    }
}

impl<S: Clone + Send + Sync + 'static> OpenApiRouter<S> {
    /// Starts with metadata/components, rejecting paths without registered handlers.
    pub fn new(document: OpenApi) -> Result<Self, OpenApiRouteError> {
        if !document.paths.paths.is_empty() {
            return Err(OpenApiRouteError::InvalidDocument {
                reason: "register paths through route! instead of the base document",
            });
        }
        Ok(Self {
            router: Router::new(),
            document,
        })
    }

    /// Registers the generated methods/path and merges their schemas.
    ///
    /// Path parameters and servers retain their per-operation inheritance.
    /// Conflicting operations, components or shared path metadata return errors.
    /// Invalid or ambiguous route patterns follow Axum's startup panic behavior.
    pub fn route(mut self, mut route: OpenApiRoute<S>) -> Result<Self, OpenApiRouteError> {
        for (path, item) in &mut route.document.paths.paths {
            if let Some(existing) = self.document.paths.paths.get_mut(path) {
                for (method, operation) in operations(item) {
                    if operation.is_some()
                        && operations(existing)
                            .iter()
                            .any(|(other, operation)| *other == method && operation.is_some())
                    {
                        return Err(OpenApiRouteError::DuplicateOperation {
                            method,
                            path: path.clone(),
                        });
                    }
                }
                merge_path_metadata(path, "summary", &mut existing.summary, item.summary.take())?;
                merge_path_metadata(
                    path,
                    "description",
                    &mut existing.description,
                    item.description.take(),
                )?;
                if let Some(incoming) = item.extensions.take() {
                    let target = existing.extensions.get_or_insert_default();
                    if incoming.iter().any(|(key, value)| {
                        target.get(key).is_some_and(|existing| existing != value)
                    }) {
                        return Err(OpenApiRouteError::ConflictingPathMetadata {
                            field: "extensions",
                            path: path.clone(),
                        });
                    }
                    target.merge(incoming);
                }
            }
        }
        if let (Some(existing), Some(incoming)) =
            (&self.document.components, &route.document.components)
        {
            check_components("schema", &existing.schemas, &incoming.schemas)?;
            check_components("response", &existing.responses, &incoming.responses)?;
            check_components(
                "security scheme",
                &existing.security_schemes,
                &incoming.security_schemes,
            )?;
        }
        self.router = self.router.route(&route.path, route.router);
        self.document.merge(route.document);
        Ok(self)
    }

    /// Returns the native router and its complete document.
    pub fn into_parts(self) -> (Router<S>, OpenApi) {
        (self.router, self.document)
    }
}

fn normalize_path_inheritance(item: &mut PathItem) -> Result<(), OpenApiRouteError> {
    let parameters = item.parameters.take().unwrap_or_default();
    if parameters.iter().enumerate().any(|(index, parameter)| {
        parameters[..index]
            .iter()
            .any(|other| same_parameter(parameter, other))
    }) {
        return Err(OpenApiRouteError::InvalidDocument {
            reason: "path parameters must be unique by name and location",
        });
    }
    let servers = item.servers.take();
    for operation in operations_mut(item) {
        if operation.servers.is_none() {
            operation.servers = servers.clone();
        }
        if !parameters.is_empty() {
            let target = operation.parameters.get_or_insert_default();
            for parameter in &parameters {
                if !target
                    .iter()
                    .any(|existing| same_parameter(existing, parameter))
                {
                    target.push(parameter.clone());
                }
            }
        }
    }
    Ok(())
}

fn same_parameter(left: &Parameter, right: &Parameter) -> bool {
    left.parameter_in == right.parameter_in
        && if left.parameter_in == ParameterIn::Header {
            left.name.eq_ignore_ascii_case(&right.name)
        } else {
            left.name == right.name
        }
}

fn merge_path_metadata<T: PartialEq>(
    path: &str,
    field: &'static str,
    existing: &mut Option<T>,
    incoming: Option<T>,
) -> Result<(), OpenApiRouteError> {
    if let Some(value) = incoming {
        if existing.as_ref().is_some_and(|existing| *existing != value) {
            return Err(OpenApiRouteError::ConflictingPathMetadata {
                field,
                path: path.to_owned(),
            });
        }
        *existing = Some(value);
    }
    Ok(())
}

fn check_components<T: PartialEq>(
    kind: &'static str,
    existing: &BTreeMap<String, T>,
    incoming: &BTreeMap<String, T>,
) -> Result<(), OpenApiRouteError> {
    for (name, value) in incoming {
        if existing.get(name).is_some_and(|existing| existing != value) {
            return Err(OpenApiRouteError::ConflictingComponent {
                kind,
                name: name.clone(),
            });
        }
    }
    Ok(())
}

/// Collects a handler's route and schemas from its `utoipa::path` annotation.
///
/// Returns `Result<OpenApiRoute<S>, OpenApiRouteError>`. Qualified handler paths
/// are supported. No separate `get(handler)` or `#[openapi(paths(handler))]`
/// registration is needed.
#[macro_export]
macro_rules! openapi_route {
    ($handler:path $(,)?) => {{
        use $crate::http::openapi::utoipa;
        #[derive(utoipa::OpenApi)]
        #[openapi(paths($handler))]
        struct RouteDocument;
        $crate::http::openapi::OpenApiRoute::from_handler(
            $handler,
            <RouteDocument as utoipa::OpenApi>::openapi(),
        )
    }};
}