footing 0.6.4

Feature-gated foundations for Rust backend services
Documentation
use std::time::{Duration, Instant};

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

use crate::{
    http::{
        DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES, DEFAULT_IDEMPOTENCY_PROCESSING_TTL,
        DEFAULT_IDEMPOTENCY_TTL, DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES, IdempotencyConfig,
    },
    settings::{SettingsIssues, SettingsValidationError, field_path},
};

#[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 idempotency.
pub struct HttpIdempotencySettings {
    /// Whether idempotency handling is enabled.
    pub enabled: bool,
    #[serde(with = "crate::settings::human_duration")]
    /// Retention duration for completed responses.
    pub ttl: Duration,
    #[serde(with = "crate::settings::human_duration")]
    /// Lease duration for a request currently being processed.
    pub processing_ttl: Duration,
    /// Maximum request body size eligible for idempotency hashing.
    pub max_request_body_bytes: usize,
    /// Maximum response body size retained for replay.
    pub max_response_body_bytes: usize,
    /// Additional request headers used to distinguish idempotent operations.
    /// See [`IdempotencyConfig::with_fingerprint_headers`] for value and rollout semantics.
    pub fingerprint_headers: Vec<String>,
}

impl Default for HttpIdempotencySettings {
    fn default() -> Self {
        Self {
            enabled: false,
            ttl: DEFAULT_IDEMPOTENCY_TTL,
            processing_ttl: DEFAULT_IDEMPOTENCY_PROCESSING_TTL,
            max_request_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
            max_response_body_bytes: DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES,
            fingerprint_headers: Vec::new(),
        }
    }
}

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

    /// 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]
    /// Configures enabled and returns the updated value.
    pub const fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    #[must_use]
    /// Configures TTL and returns the updated value.
    pub const fn with_ttl(mut self, ttl: Duration) -> Self {
        self.ttl = ttl;
        self
    }

    #[must_use]
    /// Configures processing TTL and returns the updated value.
    pub const fn with_processing_ttl(mut self, processing_ttl: Duration) -> Self {
        self.processing_ttl = processing_ttl;
        self
    }

    #[must_use]
    /// Configures maximum request body bytes and returns the updated value.
    pub const fn with_max_request_body_bytes(mut self, max_request_body_bytes: usize) -> Self {
        self.max_request_body_bytes = max_request_body_bytes;
        self
    }

    #[must_use]
    /// Configures maximum response body bytes and returns the updated value.
    pub const fn with_max_response_body_bytes(mut self, max_response_body_bytes: usize) -> Self {
        self.max_response_body_bytes = max_response_body_bytes;
        self
    }

    /// Selects additional headers that affect the operation or its response.
    #[must_use]
    pub fn with_fingerprint_headers(
        mut self,
        headers: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.fingerprint_headers = headers.into_iter().map(Into::into).collect();
        self
    }

    pub(in crate::http::layers) fn build_at(
        &self,
        path: &str,
    ) -> Result<Option<IdempotencyConfig>, SettingsValidationError> {
        if !self.enabled {
            return Ok(None);
        }
        let mut issues = SettingsIssues::new();
        let now = Instant::now();
        issues.require(
            !self.ttl.is_zero() && now.checked_add(self.ttl).is_some(),
            field_path(path, "ttl"),
            "must be greater than zero and fit the clock range when idempotency is enabled",
        );
        issues.require(
            !self.processing_ttl.is_zero() && now.checked_add(self.processing_ttl).is_some(),
            field_path(path, "processing_ttl"),
            "must be greater than zero and fit the clock range when idempotency is enabled",
        );
        issues.require(
            self.max_request_body_bytes > 0,
            field_path(path, "max_request_body_bytes"),
            "must be greater than zero when idempotency is enabled",
        );
        issues.require(
            self.max_response_body_bytes > 0
                && self
                    .max_response_body_bytes
                    .checked_add(DEFAULT_MAX_IDEMPOTENCY_STORED_HEADER_BYTES)
                    .is_some(),
            field_path(path, "max_response_body_bytes"),
            "must be greater than zero and fit with stored headers when idempotency is enabled",
        );
        let mut fingerprint_headers = Vec::with_capacity(self.fingerprint_headers.len());
        for (index, name) in self.fingerprint_headers.iter().enumerate() {
            match HeaderName::try_from(name.as_str()) {
                Ok(name) => fingerprint_headers.push(name),
                Err(_) => issues.push(
                    field_path(path, &format!("fingerprint_headers[{index}]")),
                    "must be a valid HTTP header name",
                ),
            }
        }
        issues.into_result()?;
        IdempotencyConfig::new(
            self.ttl,
            self.processing_ttl,
            self.max_request_body_bytes,
            self.max_response_body_bytes,
        )
        .map(|config| Some(config.with_fingerprint_headers(fingerprint_headers)))
        .map_err(|error| {
            use crate::http::IdempotencyConfigError;
            let field = match error {
                IdempotencyConfigError::InvalidTtl => "ttl",
                IdempotencyConfigError::InvalidProcessingTtl => "processing_ttl",
                IdempotencyConfigError::InvalidRequestBodyLimit => "max_request_body_bytes",
                IdempotencyConfigError::InvalidResponseBodyLimit => "max_response_body_bytes",
            };
            SettingsValidationError::single(field_path(path, field), error.to_string())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::{HttpMiddlewareSettings, HttpMiddlewareStack, MemoryIdempotencyStore};
    use axum::{
        Router,
        body::Body,
        http::{Request, StatusCode},
        routing::post,
    };
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };
    use tower::ServiceExt;

    #[test]
    fn fingerprint_settings_validate_all_names_and_canonicalize_duplicates() {
        let settings: HttpIdempotencySettings = serde_json::from_value(serde_json::json!({
            "enabled": true,
            "fingerprint_headers": ["Prefer", "If-Match", "prefer"],
        }))
        .unwrap();
        let config = settings.build_at("http.idempotency").unwrap().unwrap();
        assert_eq!(config.fingerprint_headers(), ["if-match", "prefer"]);
        let encoded = serde_json::to_value(&settings).unwrap();
        assert_eq!(
            encoded["fingerprint_headers"],
            serde_json::json!(["Prefer", "If-Match", "prefer"])
        );

        let invalid = settings.with_fingerprint_headers(["bad header", "", "if-match"]);
        let error = invalid.build_at("http.idempotency").unwrap_err();
        let paths: Vec<_> = error.issues().iter().map(|issue| issue.path()).collect();
        assert_eq!(
            paths,
            [
                "http.idempotency.fingerprint_headers[0]",
                "http.idempotency.fingerprint_headers[1]"
            ]
        );
    }

    #[tokio::test]
    async fn configured_condition_header_replays_only_the_same_request() {
        let config = HttpMiddlewareSettings::new()
            .with_idempotency(
                HttpIdempotencySettings::default()
                    .with_enabled(true)
                    .with_fingerprint_headers(["if-match"]),
            )
            .build()
            .unwrap();
        let executions = Arc::new(AtomicUsize::new(0));
        let calls = executions.clone();
        let app = HttpMiddlewareStack::builder(config)
            .with_idempotency_store(Arc::new(MemoryIdempotencyStore::default()))
            .build()
            .unwrap()
            .apply(Router::new().route(
                "/orders",
                post(move || {
                    let calls = calls.clone();
                    async move {
                        calls.fetch_add(1, Ordering::SeqCst);
                        StatusCode::CREATED
                    }
                }),
            ));
        for (condition, expected, replayed) in [
            ("\"version-1\"", StatusCode::CREATED, false),
            ("\"version-1\"", StatusCode::CREATED, true),
            ("\"version-2\"", StatusCode::CONFLICT, false),
        ] {
            let response = app
                .clone()
                .oneshot(
                    Request::post("/orders")
                        .header("idempotency-key", "same")
                        .header("if-match", condition)
                        .body(Body::from("same operation"))
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(response.status(), expected);
            assert_eq!(
                response.headers().contains_key("idempotency-replayed"),
                replayed
            );
        }
        assert_eq!(executions.load(Ordering::SeqCst), 1);
    }
}