footing 0.1.19

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

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

const MAX_ENDPOINT_RATE_LIMIT_LABEL_LENGTH: usize = 64;

#[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 + Copy,
    ) -> 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 + Copy,
    ) -> 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)
        || 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 EndpointRateLimit::Custom(value) = endpoint.rate_limit()
        && !valid_rate_limit_label(value)
    {
        return Err(EndpointContractValidationError::InvalidRateLimitLabel { index, value });
    }
    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 {
    let Some(path) = path.strip_prefix('/') else {
        return false;
    };

    path.split('/').all(|segment| {
        !segment.is_empty()
            && if segment.starts_with('{') || segment.ends_with('}') {
                route_segment_matches(segment, "value")
            } else {
                !segment.contains(['{', '}'])
            }
    })
}

fn valid_rate_limit_label(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= MAX_ENDPOINT_RATE_LIMIT_LABEL_LENGTH
        && value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}