footing 0.1.5

Feature-gated foundations for Rust backend services
Documentation
use axum::http::Method;

use super::model::route_segment_matches;
use super::{
    EndpointAuth, EndpointContract, EndpointContractDocument, EndpointContractSnapshot,
    EndpointContractValidationError, 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]
    /// Returns the find.
    pub fn find(&self, method: &Method, path: &str) -> Option<&'a EndpointContract<P>> {
        self.endpoints
            .iter()
            .find(|contract| contract.matches(method, path))
    }

    /// Validates this value.
    pub fn validate(&self) -> Result<(), EndpointContractValidationError> {
        for (index, endpoint) in self.endpoints.iter().enumerate() {
            validate_endpoint(index, endpoint)?;
            for (other_index, other) in self.endpoints.iter().enumerate().skip(index + 1) {
                if endpoint.method() == other.method() && endpoint.path() == other.path() {
                    return Err(EndpointContractValidationError::DuplicateRoute {
                        first_index: index,
                        second_index: other_index,
                        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 !valid_contract_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_public() {
        return Err(EndpointContractValidationError::PublicEndpointRequiresPermissions { index });
    }
    if endpoint.auth().requires_identity() && endpoint.permissions().is_public() {
        return Err(EndpointContractValidationError::PrivateEndpointWithoutPermissions { index });
    }
    Ok(())
}

fn valid_contract_path(path: &str) -> bool {
    path.is_ascii()
        && !path.bytes().any(|byte| {
            byte.is_ascii_control()
                || byte.is_ascii_whitespace()
                || matches!(byte, b'?' | b'#' | b'\\')
        })
}

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'_')
}