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]
pub enum RouteMatcherSettings {
#[default]
Any,
Exact(String),
Prefix(String),
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]
pub enum RequestBodyLimitSettings {
#[default]
Disabled,
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]
pub struct HttpRouteRuleSettings {
pub matcher: RouteMatcherSettings,
pub methods: Vec<String>,
pub rate_limit: Option<RateLimitRequestPolicy>,
pub idempotency: Option<IdempotencyRequestPolicy>,
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]
pub struct HttpRequestPolicySettings {
pub default_rate_limit: RateLimitRequestPolicy,
pub default_idempotency: IdempotencyRequestPolicy,
pub default_request_body_limit: RequestBodyLimitSettings,
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 {
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("http.request_policy")
}
pub fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
self.build_at(path).map(|_| ())
}
#[must_use]
pub fn disabled() -> Self {
Self::from(HttpRequestPolicy::disabled())
}
#[must_use]
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 {
pub fn validate(&self) -> Result<(), SettingsValidationError> {
self.validate_at("http.request_policy.rule")
}
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()
}