footing 0.5.3

Feature-gated foundations for Rust backend services
Documentation
//! Serializable route-policy settings and policy materialization.

use axum::http::Method;
use serde::{Deserialize, Serialize};

use crate::{
    http::{IdempotencyRequestPolicy, RateLimitRequestPolicy},
    settings::{SettingsIssues, SettingsValidationError, field_path},
};

use super::{
    error::HttpMiddlewareError,
    policy::{
        HttpRequestPolicy, HttpRouteRule, RequestBodyLimitPolicy, RouteMatcher, RouteMatcherKind,
    },
};

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
#[non_exhaustive]
/// Serializable settings for route matcher.
pub enum RouteMatcherSettings {
    #[default]
    /// Indicates any.
    Any,
    /// Indicates exact.
    Exact(String),
    /// Indicates prefix.
    Prefix(String),
    /// Indicates raw prefix.
    RawPrefix(String),
}

impl TryFrom<&RouteMatcherSettings> for RouteMatcher {
    type Error = HttpMiddlewareError;

    fn try_from(value: &RouteMatcherSettings) -> Result<Self, Self::Error> {
        match value {
            RouteMatcherSettings::Any => Ok(Self::any()),
            RouteMatcherSettings::Exact(path) => Self::exact(path.clone()),
            RouteMatcherSettings::Prefix(path) => Self::prefix(path.clone()),
            RouteMatcherSettings::RawPrefix(path) => Self::raw_prefix(path.clone()),
        }
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case", tag = "mode", content = "bytes")]
#[non_exhaustive]
/// Serializable settings for request body limit.
pub enum RequestBodyLimitSettings {
    #[default]
    /// The capability is disabled.
    Disabled,
    /// Indicates bytes.
    Bytes(usize),
}

impl TryFrom<RequestBodyLimitSettings> for RequestBodyLimitPolicy {
    type Error = HttpMiddlewareError;

    fn try_from(value: RequestBodyLimitSettings) -> Result<Self, Self::Error> {
        match value {
            RequestBodyLimitSettings::Disabled => Ok(Self::Disabled),
            RequestBodyLimitSettings::Bytes(bytes) => Self::bytes(bytes),
        }
    }
}

impl From<RequestBodyLimitPolicy> for RequestBodyLimitSettings {
    fn from(value: RequestBodyLimitPolicy) -> Self {
        match value {
            RequestBodyLimitPolicy::Disabled => Self::Disabled,
            RequestBodyLimitPolicy::Bytes(bytes) => Self::Bytes(bytes.get()),
        }
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for HTTP route rule.
pub struct HttpRouteRuleSettings {
    /// Route pattern matched by this rule.
    pub matcher: RouteMatcherSettings,
    /// Optional HTTP method filter; an empty list matches every method.
    pub methods: Vec<String>,
    /// Per-route rate-limit override.
    pub rate_limit: Option<RateLimitRequestPolicy>,
    /// Per-route idempotency override.
    pub idempotency: Option<IdempotencyRequestPolicy>,
    /// Per-route request body limit override.
    pub request_body_limit: Option<RequestBodyLimitSettings>,
}

impl TryFrom<&HttpRouteRuleSettings> for HttpRouteRule {
    type Error = SettingsValidationError;

    fn try_from(value: &HttpRouteRuleSettings) -> Result<Self, Self::Error> {
        value.build_at("http.request_policy.rule")
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for HTTP request policy.
pub struct HttpRequestPolicySettings {
    /// Rate-limit policy used when no route rule overrides it.
    pub default_rate_limit: RateLimitRequestPolicy,
    /// Idempotency policy used when no route rule overrides it.
    pub default_idempotency: IdempotencyRequestPolicy,
    /// Request body limit used when no route rule overrides it.
    pub default_request_body_limit: RequestBodyLimitSettings,
    /// Ordered route-specific policy overrides.
    pub rules: Vec<HttpRouteRuleSettings>,
}

impl Default for HttpRequestPolicySettings {
    fn default() -> Self {
        Self::from(HttpRequestPolicy::default())
    }
}

impl From<HttpRequestPolicy> for HttpRequestPolicySettings {
    fn from(value: HttpRequestPolicy) -> Self {
        Self {
            default_rate_limit: value.default_rate_limit(),
            default_idempotency: value.default_idempotency(),
            default_request_body_limit: value.default_request_body_limit().into(),
            rules: value
                .rules()
                .iter()
                .map(|rule| HttpRouteRuleSettings {
                    matcher: match &rule.matcher().0 {
                        RouteMatcherKind::Any => RouteMatcherSettings::Any,
                        RouteMatcherKind::Exact(path) => RouteMatcherSettings::Exact(path.clone()),
                        RouteMatcherKind::Prefix(path) => {
                            RouteMatcherSettings::Prefix(path.clone())
                        }
                        RouteMatcherKind::RawPrefix(path) => {
                            RouteMatcherSettings::RawPrefix(path.clone())
                        }
                    },
                    methods: rule
                        .methods_slice()
                        .iter()
                        .map(ToString::to_string)
                        .collect(),
                    rate_limit: rule.rate_limit,
                    idempotency: rule.idempotency,
                    request_body_limit: rule.request_body_limit.map(Into::into),
                })
                .collect(),
        }
    }
}

impl TryFrom<&HttpRequestPolicySettings> for HttpRequestPolicy {
    type Error = SettingsValidationError;

    fn try_from(value: &HttpRequestPolicySettings) -> Result<Self, Self::Error> {
        value.build_at("http.request_policy")
    }
}

impl HttpRequestPolicySettings {
    /// Validates settings beneath `http.request_policy`.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("http.request_policy")
    }

    /// Validates settings using their location in the application configuration.
    ///
    /// `path` prefixes every reported field. An empty path reports fields at the
    /// document root; the supplied path is otherwise used unchanged.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        self.build_at(path).map(|_| ())
    }

    #[must_use]
    /// Creates disabled.
    pub fn disabled() -> Self {
        Self::from(HttpRequestPolicy::disabled())
    }

    #[must_use]
    /// Configures rule and returns the updated value.
    pub fn with_rule(mut self, rule: HttpRouteRuleSettings) -> Self {
        self.rules.push(rule);
        self
    }

    pub(super) fn build_at(
        &self,
        path: &str,
    ) -> Result<HttpRequestPolicy, SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        let body_limit =
            RequestBodyLimitPolicy::try_from(self.default_request_body_limit).map_err(|_| {
                SettingsValidationError::single(
                    field_path(path, "default_request_body_limit"),
                    "must be greater than zero when enabled",
                )
            });
        if let Err(error) = &body_limit {
            issues.extend(error.clone());
        }
        let mut rules = Vec::with_capacity(self.rules.len());
        for (index, rule) in self.rules.iter().enumerate() {
            match rule.build_at(&field_path(path, &format!("rules.{index}"))) {
                Ok(rule) => rules.push(rule),
                Err(error) => issues.extend(error),
            }
        }
        issues.into_result()?;
        Ok(HttpRequestPolicy::default()
            .with_default_rate_limit(self.default_rate_limit)
            .with_default_idempotency(self.default_idempotency)
            .with_default_request_body_limit(body_limit?)
            .with_rules(rules))
    }
}

impl HttpRouteRuleSettings {
    /// Validates settings beneath `http.request_policy.rule`.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("http.request_policy.rule")
    }

    /// Validates settings using their location in the application configuration.
    ///
    /// `path` prefixes every reported field. An empty path reports fields at the
    /// document root; the supplied path is otherwise used unchanged.
    pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        self.build_at(path).map(|_| ())
    }

    fn build_at(&self, path: &str) -> Result<HttpRouteRule, SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        let matcher = RouteMatcher::try_from(&self.matcher).map_err(|_| {
            SettingsValidationError::single(
                field_path(path, "matcher.value"),
                "must be an absolute ASCII path without whitespace, controls, query, fragment or backslash",
            )
        });
        if let Err(error) = &matcher {
            issues.extend(error.clone());
        }
        let mut methods = Vec::with_capacity(self.methods.len());
        for (index, method) in self.methods.iter().enumerate() {
            match parse_method(method) {
                Ok(method) => methods.push(method),
                Err(_) => issues.push(
                    field_path(path, &format!("methods.{index}")),
                    "must be a valid HTTP method",
                ),
            }
        }
        let body_limit = self
            .request_body_limit
            .map(RequestBodyLimitPolicy::try_from)
            .transpose()
            .map_err(|_| {
                SettingsValidationError::single(
                    field_path(path, "request_body_limit"),
                    "must be greater than zero when enabled",
                )
            });
        if let Err(error) = &body_limit {
            issues.extend(error.clone());
        }
        issues.into_result()?;
        Ok(HttpRouteRule {
            matcher: matcher?,
            methods,
            rate_limit: self.rate_limit,
            idempotency: self.idempotency,
            request_body_limit: body_limit?,
        })
    }
}

pub(super) fn parse_method(value: &str) -> Result<Method, axum::http::method::InvalidMethod> {
    value.trim().parse()
}