footing 0.5.3

Feature-gated foundations for Rust backend services
Documentation
use std::collections::BTreeMap;

use serde::{Deserialize, Deserializer, Serialize};

use super::{EndpointContract, EndpointPathPattern, EndpointPermissions};

impl<P: Copy + 'static> EndpointContract<P> {
    #[must_use]
    /// Returns the document.
    pub fn document(&self, permission_to_string: impl Fn(P) -> String) -> EndpointContractDocument {
        EndpointContractDocument {
            method: self.method().as_str().to_owned(),
            path: self.path().as_str().to_owned(),
            path_kind: match self.path() {
                EndpointPathPattern::Exact(_) => "exact",
                EndpointPathPattern::Template(_) => "template",
            }
            .to_owned(),
            auth: self.auth().as_str().to_owned(),
            permissions: document_permissions(self.permissions(), permission_to_string),
            risk: self.risk().as_str().to_owned(),
            idempotency: self.idempotency().as_str().to_owned(),
            pagination: self.pagination().as_str().to_owned(),
            rate_limit: self.rate_limit().as_str().to_owned(),
            audit: self.audit().as_str().to_owned(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[non_exhaustive]
/// Represents endpoint contract document.
pub struct EndpointContractDocument {
    /// HTTP method accepted by the endpoint.
    pub method: String,
    /// Route path registered by the endpoint.
    pub path: String,
    /// Whether `path` is an exact path or a route pattern.
    pub path_kind: String,
    /// Authentication requirement.
    pub auth: String,
    /// Permission policy applied after authentication.
    pub permissions: EndpointPermissionsDocument,
    /// Operational risk classification.
    pub risk: String,
    /// Idempotency requirement.
    pub idempotency: String,
    /// Pagination contract.
    pub pagination: String,
    /// Rate-limit enablement: `enabled` or `disabled`.
    pub rate_limit: String,
    /// Audit policy applied to requests.
    pub audit: String,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[non_exhaustive]
/// Represents endpoint permissions document.
pub struct EndpointPermissionsDocument {
    /// Permission matching mode.
    pub mode: String,
    /// Stable permission identifiers required by the mode.
    pub values: Vec<String>,
}

/// Deterministic route-contract snapshot for tooling and startup diagnostics.
///
/// Endpoints and aggregate counts are immutable. Deserialization normalizes
/// ordering and rejects unsupported schema versions or inconsistent counts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct EndpointContractSnapshot {
    schema_version: u32,
    summary: EndpointContractSnapshotSummary,
    endpoints: Vec<EndpointContractDocument>,
}

impl EndpointContractSnapshot {
    /// Schema version shared with OpenAPI contract metadata.
    /// Version 3 uses the same idempotency and rate-limit names as runtime policies.
    pub const SCHEMA_VERSION: u32 = 3;

    #[must_use]
    /// Sorts contracts by path and method and computes their aggregate counts.
    pub fn new(mut endpoints: Vec<EndpointContractDocument>) -> Self {
        endpoints.sort_by(|left, right| {
            (&left.path, &left.method)
                .cmp(&(&right.path, &right.method))
                .then_with(|| left.cmp(right))
        });
        Self {
            schema_version: Self::SCHEMA_VERSION,
            summary: EndpointContractSnapshotSummary::from_documents(&endpoints),
            endpoints,
        }
    }

    #[must_use]
    /// Creates a value from contracts.
    pub fn from_contracts<P: Copy + 'static>(
        endpoints: &[EndpointContract<P>],
        permission_to_string: impl Fn(P) -> String,
    ) -> Self {
        Self::new(
            endpoints
                .iter()
                .map(|endpoint| endpoint.document(&permission_to_string))
                .collect(),
        )
    }

    /// Returns the serialized schema version.
    #[must_use]
    pub const fn schema_version(&self) -> u32 {
        self.schema_version
    }

    /// Returns the derived aggregate counts.
    #[must_use]
    pub const fn summary(&self) -> &EndpointContractSnapshotSummary {
        &self.summary
    }

    /// Returns contracts sorted by path and method.
    #[must_use]
    pub fn endpoints(&self) -> &[EndpointContractDocument] {
        &self.endpoints
    }

    /// Converts this value to pretty JSON.
    pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

impl<'de> Deserialize<'de> for EndpointContractSnapshot {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct Wire {
            schema_version: u32,
            summary: EndpointContractSnapshotSummary,
            endpoints: Vec<EndpointContractDocument>,
        }
        let wire = Wire::deserialize(deserializer)?;
        if wire.schema_version != Self::SCHEMA_VERSION {
            return Err(serde::de::Error::custom(
                "unsupported endpoint snapshot schema version",
            ));
        }
        let snapshot = Self::new(wire.endpoints);
        if snapshot.summary != wire.summary {
            return Err(serde::de::Error::custom(
                "endpoint snapshot summary does not match its endpoints",
            ));
        }
        Ok(snapshot)
    }
}

/// Aggregated endpoint contract counts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EndpointContractSnapshotSummary {
    /// Total number of endpoints.
    pub total: usize,
    /// Endpoint counts grouped by authentication policy.
    pub by_auth: BTreeMap<String, usize>,
    /// Endpoint counts grouped by risk classification.
    pub by_risk: BTreeMap<String, usize>,
    /// Endpoint counts grouped by audit policy.
    pub by_audit: BTreeMap<String, usize>,
    /// Endpoint counts grouped by rate-limit policy.
    pub by_rate_limit: BTreeMap<String, usize>,
    /// Number of endpoints requiring permissions.
    pub permissioned: usize,
    /// Number of paginated endpoints.
    pub paginated: usize,
    /// Number of endpoints requiring idempotency.
    pub idempotency_required: usize,
}

impl EndpointContractSnapshotSummary {
    #[must_use]
    /// Creates a value from documents.
    pub fn from_documents(endpoints: &[EndpointContractDocument]) -> Self {
        let mut summary = Self::new(endpoints.len());

        for endpoint in endpoints {
            increment(&mut summary.by_auth, &endpoint.auth);
            increment(&mut summary.by_risk, &endpoint.risk);
            increment(&mut summary.by_audit, &endpoint.audit);
            increment(&mut summary.by_rate_limit, &endpoint.rate_limit);
            if endpoint.permissions.mode != "none" {
                summary.permissioned += 1;
            }
            if endpoint.pagination != "none" {
                summary.paginated += 1;
            }
            if endpoint.idempotency == "required" {
                summary.idempotency_required += 1;
            }
        }

        summary
    }

    fn new(total: usize) -> Self {
        Self {
            total,
            by_auth: BTreeMap::new(),
            by_risk: BTreeMap::new(),
            by_audit: BTreeMap::new(),
            by_rate_limit: BTreeMap::new(),
            permissioned: 0,
            paginated: 0,
            idempotency_required: 0,
        }
    }
}

fn document_permissions<P: Copy + 'static>(
    permissions: EndpointPermissions<P>,
    permission_to_string: impl Fn(P) -> String,
) -> EndpointPermissionsDocument {
    let (mode, values): (&str, &[P]) = match &permissions {
        EndpointPermissions::None => ("none", &[]),
        EndpointPermissions::One(permission) => ("one", std::slice::from_ref(permission)),
        EndpointPermissions::Any(values) => ("any", values),
        EndpointPermissions::All(values) => ("all", values),
    };
    EndpointPermissionsDocument {
        mode: mode.to_owned(),
        values: values.iter().copied().map(permission_to_string).collect(),
    }
}

fn increment(values: &mut BTreeMap<String, usize>, key: &str) {
    *values.entry(key.to_owned()).or_default() += 1;
}