footing 0.1.22

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

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

#[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,
}

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

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 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(),
            format!("{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(),
            format!("{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,
            format!("{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(),
            format!("{path}.max_response_body_bytes"),
            "must be greater than zero and fit with stored headers when idempotency is enabled",
        );
        issues.into_result()?;
        IdempotencyConfig::new(
            self.ttl,
            self.processing_ttl,
            self.max_request_body_bytes,
            self.max_response_body_bytes,
        )
        .map(Some)
        .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(format!("{path}.{field}"), error.to_string())
        })
    }
}