footing 0.1.12

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},
};

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 = HttpMiddlewareError;

    fn try_from(value: &HttpRouteRuleSettings) -> Result<Self, Self::Error> {
        let mut rule = HttpRouteRule::new(RouteMatcher::try_from(&value.matcher)?);
        if !value.methods.is_empty() {
            rule = rule.methods(parse_methods("methods", &value.methods)?);
        }
        if let Some(policy) = value.rate_limit {
            rule = rule.rate_limit(policy);
        }
        if let Some(policy) = value.idempotency {
            rule = rule.idempotency(policy);
        }
        if let Some(policy) = value.request_body_limit {
            rule = rule.request_body_limit(policy.try_into()?);
        }
        Ok(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 = HttpMiddlewareError;

    fn try_from(value: &HttpRequestPolicySettings) -> Result<Self, Self::Error> {
        let mut policy = HttpRequestPolicy::default()
            .with_default_rate_limit(value.default_rate_limit)
            .with_default_idempotency(value.default_idempotency)
            .with_default_request_body_limit(value.default_request_body_limit.try_into()?);
        for rule in &value.rules {
            policy = policy.with_rule(HttpRouteRule::try_from(rule)?);
        }
        Ok(policy)
    }
}

impl HttpRequestPolicySettings {
    #[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(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        validate_request_body_limit_setting(
            &mut issues,
            format!("{path}.default_request_body_limit"),
            self.default_request_body_limit,
        );
        for (index, rule) in self.rules.iter().enumerate() {
            rule.validate_at(&format!("{path}.rules.{index}"), &mut issues);
        }
        issues.into_result()
    }
}

impl HttpRouteRuleSettings {
    pub(crate) fn validate_at(&self, path: &str, issues: &mut SettingsIssues) {
        match &self.matcher {
            RouteMatcherSettings::Any => {}
            RouteMatcherSettings::Exact(path_value)
            | RouteMatcherSettings::Prefix(path_value)
            | RouteMatcherSettings::RawPrefix(path_value) => {
                issues.require(
                    path_value.starts_with('/'),
                    format!("{path}.matcher.value"),
                    "must be an absolute path",
                );
            }
        }
        for (index, method) in self.methods.iter().enumerate() {
            issues.require(
                parse_method(method).is_ok(),
                format!("{path}.methods.{index}"),
                "must be a valid HTTP method",
            );
        }
        if let Some(limit) = self.request_body_limit {
            validate_request_body_limit_setting(
                issues,
                format!("{path}.request_body_limit"),
                limit,
            );
        }
    }
}

fn validate_request_body_limit_setting(
    issues: &mut SettingsIssues,
    path: impl Into<String>,
    value: RequestBodyLimitSettings,
) {
    if let RequestBodyLimitSettings::Bytes(bytes) = value {
        issues.require(bytes > 0, path, "must be greater than zero when enabled");
    }
}

pub(super) fn parse_methods(
    field: &'static str,
    values: &[String],
) -> Result<Vec<Method>, HttpMiddlewareError> {
    values
        .iter()
        .map(|value| {
            parse_method(value).map_err(|_| HttpMiddlewareError::InvalidMethod {
                field,
                value: value.trim().to_owned(),
            })
        })
        .collect()
}

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