footing 0.1.12

Feature-gated foundations for Rust backend services
Documentation
use thiserror::Error;
use utoipa::openapi::{
    OpenApi, Required,
    path::{Operation, Parameter, ParameterIn, PathItem},
};

use crate::{
    http::{
        EndpointContract, EndpointContractRegistry, EndpointContractValidationError,
        EndpointIdempotency, EndpointPagination, IDEMPOTENCY_KEY_HEADER_NAME,
    },
    result::{ClassifyError, ErrorKind},
};

/// Operation extension containing a versioned footing endpoint contract.
pub const CONTRACT_EXTENSION: &str = "x-footing-contract";

/// Mismatch between an endpoint registry and the documented application routes.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenApiContractError {
    /// The registry itself is invalid.
    #[error(transparent)]
    InvalidContracts(#[from] EndpointContractValidationError),
    /// A registered contract has no corresponding OpenAPI operation.
    #[error("endpoint contract {method} {path} has no OpenAPI operation")]
    UndocumentedEndpoint {
        /// HTTP method of the missing operation.
        method: &'static str,
        /// Literal route pattern, including parameter names.
        path: String,
    },
    /// An OpenAPI operation has no matching contract.
    #[error("OpenAPI operation {method} {path} has no endpoint contract")]
    OperationWithoutContract {
        /// HTTP method of the unexpected operation.
        method: &'static str,
        /// Documented path.
        path: String,
    },
    /// A path item has no operations that can be reconciled.
    #[error("OpenAPI path {path} contains no operations")]
    EmptyPathItem {
        /// Documented path.
        path: String,
    },
    /// Existing footing metadata disagrees with the registry.
    #[error("OpenAPI operation {method} {path} has conflicting footing metadata")]
    ConflictingMetadata {
        /// HTTP method of the conflicting operation.
        method: &'static str,
        /// Documented path.
        path: String,
    },
    /// A parameter required by a footing contract is missing or contradictory.
    #[error("OpenAPI operation {method} {path}: parameter {name} {reason}")]
    InvalidParameter {
        /// HTTP method of the operation.
        method: &'static str,
        /// Documented path.
        path: String,
        /// Name of the contract parameter.
        name: &'static str,
        /// Description of the mismatch.
        reason: &'static str,
    },
    /// Serializing the contract metadata failed.
    #[error("failed to serialize OpenAPI contract metadata")]
    Serialization(#[from] serde_json::Error),
}

impl ClassifyError for OpenApiContractError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::Serialization(_) => ErrorKind::Internal,
            _ => ErrorKind::Validation,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidContracts(_) => "openapi_invalid_contracts",
            Self::UndocumentedEndpoint { .. } => "openapi_undocumented_endpoint",
            Self::OperationWithoutContract { .. } => "openapi_operation_without_contract",
            Self::EmptyPathItem { .. } => "openapi_empty_path_item",
            Self::ConflictingMetadata { .. } => "openapi_conflicting_metadata",
            Self::InvalidParameter { .. } => "openapi_invalid_contract_parameter",
            Self::Serialization(_) => "openapi_contract_serialization_failed",
        })
    }
}

/// Checks exact method/path coverage and documented footing request policies.
///
/// Cursor/offset contracts require their query parameters; idempotency contracts
/// require a header with the matching requiredness. Operation parameters override
/// path-level parameters, and header names are compared case-insensitively.
/// Custom pagination bounds are installed with [`super::OpenApiRoute`].
///
/// This validates documentation coverage, not the router or its authorization
/// behavior. [`crate::http::EndpointRouter`] binds contracts to actual Axum
/// registrations and validates their middleware policies. Template names
/// must match literally; `/items/{id}` and `/items/{key}` are different contracts.
/// OpenAPI TRACE operations have no counterpart in footing and are rejected.
pub fn validate_contracts<P: Copy + 'static>(
    document: &OpenApi,
    registry: &EndpointContractRegistry<'_, P>,
) -> Result<(), OpenApiContractError> {
    registry.validate()?;
    for endpoint in registry.endpoints() {
        let method = endpoint.method().as_str();
        let path = endpoint.path().as_str();
        let (item, operation) = document
            .paths
            .paths
            .get(path)
            .and_then(|item| {
                operations(item)
                    .into_iter()
                    .find_map(|(candidate, operation)| {
                        (candidate == method)
                            .then_some(operation)
                            .flatten()
                            .map(|operation| (item, operation))
                    })
            })
            .ok_or_else(|| OpenApiContractError::UndocumentedEndpoint {
                method,
                path: path.to_owned(),
            })?;
        validate_parameters(endpoint, item, operation)?;
    }
    for (path, item) in &document.paths.paths {
        let operations = operations(item);
        if operations.iter().all(|(_, operation)| operation.is_none()) {
            return Err(OpenApiContractError::EmptyPathItem { path: path.clone() });
        }
        for (method, operation) in operations {
            if operation.is_some()
                && !registry.endpoints().iter().any(|endpoint| {
                    endpoint.method().as_str() == method && endpoint.path().as_str() == path
                })
            {
                return Err(OpenApiContractError::OperationWithoutContract {
                    method,
                    path: path.clone(),
                });
            }
        }
    }
    Ok(())
}

/// Validates coverage and annotates each operation with its endpoint contract.
///
/// Takes ownership so errors never expose a partially annotated document.
/// Existing operation metadata, parameters, schemas, security, and responses
/// are preserved. Conflicting `x-footing-contract` values are rejected; applying
/// the same contracts again is idempotent. Extension schema version 1 contains
/// `schema_version` and a `contract` object in the endpoint snapshot format.
pub fn annotate_contracts<P: Copy + 'static>(
    mut document: OpenApi,
    registry: &EndpointContractRegistry<'_, P>,
    permission_to_string: impl Fn(P) -> String,
) -> Result<OpenApi, OpenApiContractError> {
    validate_contracts(&document, registry)?;
    for endpoint in registry.endpoints() {
        let method = endpoint.method().as_str();
        let path = endpoint.path().as_str();
        let contract = serde_json::to_value(endpoint.document(&permission_to_string))?;
        let metadata = serde_json::json!({"schema_version": 1, "contract": contract});
        let operation = document
            .paths
            .paths
            .get_mut(path)
            .and_then(|item| operation_mut(item, method))
            .ok_or_else(|| OpenApiContractError::UndocumentedEndpoint {
                method,
                path: path.to_owned(),
            })?;
        let extensions = operation.extensions.get_or_insert_default();
        if extensions
            .get(CONTRACT_EXTENSION)
            .is_some_and(|existing| existing != &metadata)
        {
            return Err(OpenApiContractError::ConflictingMetadata {
                method,
                path: path.to_owned(),
            });
        }
        extensions.insert(CONTRACT_EXTENSION.to_owned(), metadata);
    }
    Ok(document)
}

pub(super) fn operations(item: &PathItem) -> [(&'static str, Option<&Operation>); 8] {
    [
        ("GET", item.get.as_ref()),
        ("PUT", item.put.as_ref()),
        ("POST", item.post.as_ref()),
        ("DELETE", item.delete.as_ref()),
        ("OPTIONS", item.options.as_ref()),
        ("HEAD", item.head.as_ref()),
        ("PATCH", item.patch.as_ref()),
        ("TRACE", item.trace.as_ref()),
    ]
}

pub(super) fn operations_mut(item: &mut PathItem) -> impl Iterator<Item = &mut Operation> {
    [
        &mut item.get,
        &mut item.put,
        &mut item.post,
        &mut item.delete,
        &mut item.options,
        &mut item.head,
        &mut item.patch,
        &mut item.trace,
    ]
    .into_iter()
    .filter_map(Option::as_mut)
}

fn validate_parameters<P: Copy + 'static>(
    endpoint: &EndpointContract<P>,
    item: &PathItem,
    operation: &Operation,
) -> Result<(), OpenApiContractError> {
    let check = |name: &'static str, location: ParameterIn, required: Option<Required>| {
        let invalid = |reason| OpenApiContractError::InvalidParameter {
            method: endpoint.method().as_str(),
            path: endpoint.path().as_str().to_owned(),
            name,
            reason,
        };
        let matches = |parameter: &&Parameter| {
            parameter.parameter_in == location
                && if location == ParameterIn::Header {
                    parameter.name.eq_ignore_ascii_case(name)
                } else {
                    parameter.name == name
                }
        };
        let find = |parameters: Option<&Vec<Parameter>>| {
            let mut matching = parameters.into_iter().flatten().filter(matches);
            let found = matching.next();
            if matching.next().is_some() {
                Err(invalid("is duplicated"))
            } else {
                Ok(found.cloned())
            }
        };
        let inherited = find(item.parameters.as_ref())?;
        let parameter = find(operation.parameters.as_ref())?.or(inherited);
        match (parameter, required) {
            (None, None) => Ok(()),
            (Some(_), None) => Err(invalid("is documented for a disabled contract")),
            (None, Some(_)) => Err(invalid("is missing")),
            (Some(parameter), Some(required)) if parameter.required == required => Ok(()),
            (Some(_), Some(Required::True)) => Err(invalid("must be required")),
            (Some(_), Some(Required::False)) => Err(invalid("must be optional")),
        }
    };
    let required = match endpoint.idempotency() {
        EndpointIdempotency::NotApplicable => None,
        EndpointIdempotency::Optional => Some(Required::False),
        EndpointIdempotency::Required => Some(Required::True),
    };
    check(IDEMPOTENCY_KEY_HEADER_NAME, ParameterIn::Header, required)?;
    let pagination: &[&str] = match endpoint.pagination() {
        EndpointPagination::None => &[],
        EndpointPagination::Cursor => &["page_size", "cursor", "include_total"],
        EndpointPagination::Offset => &["page", "page_size"],
    };
    for &name in pagination {
        check(name, ParameterIn::Query, Some(Required::False))?;
    }
    Ok(())
}

fn operation_mut<'a>(item: &'a mut PathItem, method: &str) -> Option<&'a mut Operation> {
    match method {
        "GET" => item.get.as_mut(),
        "PUT" => item.put.as_mut(),
        "POST" => item.post.as_mut(),
        "DELETE" => item.delete.as_mut(),
        "OPTIONS" => item.options.as_mut(),
        "HEAD" => item.head.as_mut(),
        "PATCH" => item.patch.as_mut(),
        _ => None,
    }
}