footing 0.1.22

Feature-gated foundations for Rust backend services
Documentation
use axum::{extract::MatchedPath, http::Method};

use super::{
    EndpointAuth, EndpointContract, EndpointContractDocument, EndpointContractSnapshot,
    EndpointContractValidationError, EndpointMethod, EndpointPathPattern,
};

#[derive(Debug, Clone, Copy)]
/// Registry for endpoint contract.
pub struct EndpointContractRegistry<'a, P: Copy + 'static = &'static str> {
    endpoints: &'a [EndpointContract<P>],
}

impl<'a, P: Copy + 'static> EndpointContractRegistry<'a, P> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(endpoints: &'a [EndpointContract<P>]) -> Self {
        Self { endpoints }
    }

    #[must_use]
    /// Returns the endpoints.
    pub const fn endpoints(&self) -> &'a [EndpointContract<P>] {
        self.endpoints
    }

    #[must_use]
    /// Looks up Axum's selected route without independently matching URL paths.
    /// HEAD inherits the GET contract unless an explicit HEAD contract exists.
    pub fn find(&self, method: &Method, path: &MatchedPath) -> Option<&'a EndpointContract<P>> {
        let method = EndpointMethod::try_from(method).ok()?;
        let find = |method| {
            self.endpoints.iter().find(|contract| {
                contract.method() == method && contract.path().as_str() == path.as_str()
            })
        };
        find(method).or_else(|| {
            (method == EndpointMethod::Head)
                .then(|| find(EndpointMethod::Get))
                .flatten()
        })
    }

    /// Validates this value.
    pub fn validate(&self) -> Result<(), EndpointContractValidationError> {
        for (index, endpoint) in self.endpoints.iter().enumerate() {
            Self::new(&self.endpoints[..index]).validate_addition(endpoint)?;
        }
        Ok(())
    }

    pub(super) fn validate_addition(
        &self,
        endpoint: &EndpointContract<P>,
    ) -> Result<(), EndpointContractValidationError> {
        validate_endpoint(self.endpoints.len(), endpoint)?;
        for (index, other) in self.endpoints.iter().enumerate() {
            if endpoint.method() == other.method()
                && endpoint.path().as_str() == other.path().as_str()
            {
                return Err(EndpointContractValidationError::DuplicateRoute {
                    first_index: index,
                    second_index: self.endpoints.len(),
                    method: endpoint.method(),
                    path: endpoint.path().as_str(),
                });
            }
        }
        Ok(())
    }

    #[must_use]
    /// Returns the documents.
    pub fn documents(
        &self,
        permission_to_string: impl Fn(P) -> String,
    ) -> Vec<EndpointContractDocument> {
        self.endpoints
            .iter()
            .map(|endpoint| endpoint.document(&permission_to_string))
            .collect()
    }

    #[must_use]
    /// Returns an immutable snapshot.
    pub fn snapshot(&self, permission_to_string: impl Fn(P) -> String) -> EndpointContractSnapshot {
        EndpointContractSnapshot::from_contracts(self.endpoints, permission_to_string)
    }
}

fn validate_endpoint<P: Copy + 'static>(
    index: usize,
    endpoint: &EndpointContract<P>,
) -> Result<(), EndpointContractValidationError> {
    let path = endpoint.path().as_str();
    if path.is_empty() {
        return Err(EndpointContractValidationError::EmptyPath { index });
    }
    if !path.starts_with('/') {
        return Err(EndpointContractValidationError::RelativePath { index, path });
    }
    if !crate::http::is_valid_route_path(path)
        || path
            .split('/')
            .any(|segment| segment.starts_with([':', '*']))
        || matches!(endpoint.path(), EndpointPathPattern::Exact(_)) && path.contains(['{', '}'])
    {
        return Err(EndpointContractValidationError::InvalidPath { index, path });
    }
    if matches!(endpoint.path(), EndpointPathPattern::Template(_)) && !valid_template_path(path) {
        return Err(EndpointContractValidationError::InvalidTemplate { index, path });
    }
    if let Some(mode) = endpoint.permissions().empty_requirement_mode() {
        return Err(EndpointContractValidationError::EmptyPermissions { index, mode });
    }
    if endpoint.auth() == EndpointAuth::Public && !endpoint.permissions().is_none() {
        return Err(EndpointContractValidationError::PublicEndpointRequiresPermissions { index });
    }
    Ok(())
}

fn valid_template_path(path: &str) -> bool {
    path.split('/').all(|segment| {
        if let Some(parameter) = segment
            .strip_prefix('{')
            .and_then(|segment| segment.strip_suffix('}'))
        {
            !parameter.is_empty()
                && parameter
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
        } else {
            !segment.contains(['{', '}'])
        }
    })
}