footing 0.1.4

Feature-gated foundations for Rust backend services
Documentation
use std::time::Duration;

use serde::{Deserialize, Serialize};

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

use super::super::error::HttpLayerError;

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for HTTP idempotency.
pub struct HttpIdempotencySettings {
    #[serde(default)]
    /// Whether idempotency handling is enabled.
    pub enabled: bool,
    #[serde(
        default = "default_idempotency_ttl",
        with = "crate::settings::human_duration"
    )]
    /// Retention duration for completed responses.
    pub ttl: Duration,
    #[serde(
        default = "default_idempotency_processing_ttl",
        with = "crate::settings::human_duration"
    )]
    /// Lease duration for a request currently being processed.
    pub processing_ttl: Duration,
    #[serde(default = "default_idempotency_body_limit")]
    /// Maximum request body size eligible for idempotency hashing.
    pub max_request_body_bytes: usize,
    #[serde(default = "default_idempotency_body_limit")]
    /// Maximum response body size retained for replay.
    pub max_response_body_bytes: usize,
}

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_body_limit(),
            max_response_body_bytes: default_idempotency_body_limit(),
        }
    }
}

impl HttpIdempotencySettings {
    #[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
    }

    pub(in crate::http::layers) fn config(
        &self,
    ) -> Result<Option<IdempotencyConfig>, HttpLayerError> {
        if !self.enabled {
            return Ok(None);
        }
        IdempotencyConfig::new(
            self.ttl,
            self.processing_ttl,
            self.max_request_body_bytes,
            self.max_response_body_bytes,
        )
        .map(Some)
        .map_err(|_| HttpLayerError::InvalidIdempotencyConfig)
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        if self.enabled {
            issues.require(
                !self.ttl.is_zero(),
                format!("{path}.ttl"),
                "must be greater than zero when idempotency is enabled",
            );
            issues.require(
                !self.processing_ttl.is_zero(),
                format!("{path}.processing_ttl"),
                "must be greater than zero when idempotency is enabled",
            );
            issues.require(
                self.max_request_body_bytes > 0,
                format!("{path}.max_request_body_bytes"),
                "must be greater than zero when idempotency is enabled",
            );
            issues.require(
                self.max_response_body_bytes > 0,
                format!("{path}.max_response_body_bytes"),
                "must be greater than zero when idempotency is enabled",
            );
        }
        issues.into_result()
    }
}

fn default_idempotency_ttl() -> Duration {
    DEFAULT_IDEMPOTENCY_TTL
}

fn default_idempotency_processing_ttl() -> Duration {
    DEFAULT_IDEMPOTENCY_PROCESSING_TTL
}

fn default_idempotency_body_limit() -> usize {
    DEFAULT_IDEMPOTENCY_MAX_BODY_BYTES
}