footing 0.1.1

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

#[cfg(feature = "config")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "config")]
use crate::config::{ConfigIssues, ConfigValidationError};

#[cfg(feature = "config")]
use super::super::BackoffSettings;
use super::super::config::multiply_duration;
use super::super::{BackoffConfig, WorkerConfigError};

/// Retry policy shared by outbox-like workers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OutboxRetryPolicy {
    max_attempts: u32,
    backoff: BackoffConfig,
}

impl Default for OutboxRetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 5,
            backoff: BackoffConfig {
                initial_delay: Duration::from_secs(30),
                max_delay: Duration::from_secs(30 * 60),
                multiplier: 2,
            },
        }
    }
}

impl OutboxRetryPolicy {
    /// Creates a validated retry policy.
    pub fn new(max_attempts: u32, backoff: BackoffConfig) -> Result<Self, WorkerConfigError> {
        if max_attempts == 0 {
            return Err(WorkerConfigError::InvalidOutboxMaxAttempts);
        }
        Ok(Self {
            max_attempts,
            backoff,
        })
    }

    #[must_use]
    /// Returns the maximum attempts.
    pub const fn max_attempts(&self) -> u32 {
        self.max_attempts
    }

    #[must_use]
    /// Returns the backoff.
    pub const fn backoff(&self) -> BackoffConfig {
        self.backoff
    }

    #[must_use]
    /// Returns whether this value should retry.
    pub const fn should_retry(&self, attempts_after_current_try: u32) -> bool {
        attempts_after_current_try < self.max_attempts
    }

    #[must_use]
    /// Returns the delay for attempts.
    pub fn delay_for_attempts(&self, attempts_after_current_try: u32) -> Duration {
        let exponent = attempts_after_current_try.saturating_sub(1);
        let mut delay = self.backoff.initial_delay;
        for _ in 0..exponent {
            delay = multiply_duration(delay, self.backoff.multiplier).min(self.backoff.max_delay);
        }
        delay
    }
}

/// Runtime config for [`super::OutboxJob`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OutboxWorkerConfig {
    batch_size: u32,
    lease_duration: Duration,
    retry_policy: OutboxRetryPolicy,
    item_timeout: Option<Duration>,
    batch_timeout: Option<Duration>,
}

impl Default for OutboxWorkerConfig {
    fn default() -> Self {
        Self {
            batch_size: 50,
            lease_duration: Duration::from_secs(60),
            retry_policy: OutboxRetryPolicy::default(),
            item_timeout: None,
            batch_timeout: None,
        }
    }
}

impl OutboxWorkerConfig {
    #[must_use]
    /// Returns the batch size.
    pub const fn batch_size(&self) -> u32 {
        self.batch_size
    }

    #[must_use]
    /// Returns the lease duration.
    pub const fn lease_duration(&self) -> Duration {
        self.lease_duration
    }

    #[must_use]
    /// Returns the retry policy.
    pub const fn retry_policy(&self) -> OutboxRetryPolicy {
        self.retry_policy
    }

    #[must_use]
    /// Returns the item timeout.
    pub const fn item_timeout(&self) -> Option<Duration> {
        self.item_timeout
    }

    #[must_use]
    /// Returns the batch timeout.
    pub const fn batch_timeout(&self) -> Option<Duration> {
        self.batch_timeout
    }
}

#[cfg(feature = "config")]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for outbox worker.
pub struct OutboxWorkerSettings {
    #[serde(default = "default_outbox_batch_size")]
    /// Maximum number of outbox entries claimed per iteration.
    pub batch_size: u32,
    #[serde(
        default = "default_outbox_lease_duration",
        with = "crate::config::human_duration"
    )]
    /// Duration of an outbox claim before it may be reclaimed.
    pub lease_duration: Duration,
    #[serde(default = "default_outbox_max_attempts")]
    /// Maximum delivery attempts before dead-lettering an entry.
    pub max_attempts: u32,
    #[serde(default)]
    /// Delay policy applied between delivery attempts.
    pub retry_backoff: BackoffSettings,
    #[serde(default, with = "crate::config::human_duration::option")]
    /// Optional timeout for processing one entry.
    pub item_timeout: Option<Duration>,
    #[serde(default, with = "crate::config::human_duration::option")]
    /// Optional timeout for one claimed batch.
    pub batch_timeout: Option<Duration>,
}

#[cfg(feature = "config")]
impl Default for OutboxWorkerSettings {
    fn default() -> Self {
        Self::from(OutboxWorkerConfig::default())
    }
}

#[cfg(feature = "config")]
impl From<OutboxWorkerConfig> for OutboxWorkerSettings {
    fn from(value: OutboxWorkerConfig) -> Self {
        Self {
            batch_size: value.batch_size,
            lease_duration: value.lease_duration,
            max_attempts: value.retry_policy.max_attempts,
            retry_backoff: BackoffSettings::from(value.retry_policy.backoff),
            item_timeout: value.item_timeout,
            batch_timeout: value.batch_timeout,
        }
    }
}

#[cfg(feature = "config")]
impl OutboxWorkerSettings {
    #[must_use]
    /// Configures batch size and returns the updated value.
    pub const fn with_batch_size(mut self, batch_size: u32) -> Self {
        self.batch_size = batch_size;
        self
    }

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

    #[must_use]
    /// Configures maximum attempts and returns the updated value.
    pub const fn with_max_attempts(mut self, max_attempts: u32) -> Self {
        self.max_attempts = max_attempts;
        self
    }

    #[must_use]
    /// Configures retry backoff and returns the updated value.
    pub const fn with_retry_backoff(mut self, retry_backoff: BackoffSettings) -> Self {
        self.retry_backoff = retry_backoff;
        self
    }

    #[must_use]
    /// Configures item timeout and returns the updated value.
    pub const fn with_item_timeout(mut self, item_timeout: Option<Duration>) -> Self {
        self.item_timeout = item_timeout;
        self
    }

    #[must_use]
    /// Configures batch timeout and returns the updated value.
    pub const fn with_batch_timeout(mut self, batch_timeout: Option<Duration>) -> Self {
        self.batch_timeout = batch_timeout;
        self
    }

    /// Builds validated outbox worker configuration.
    pub fn build(self) -> Result<OutboxWorkerConfig, ConfigValidationError> {
        self.validate()?;
        Ok(OutboxWorkerConfig {
            batch_size: self.batch_size,
            lease_duration: self.lease_duration,
            retry_policy: OutboxRetryPolicy {
                max_attempts: self.max_attempts,
                backoff: BackoffConfig {
                    initial_delay: self.retry_backoff.initial_delay,
                    max_delay: self.retry_backoff.max_delay,
                    multiplier: self.retry_backoff.multiplier,
                },
            },
            item_timeout: self.item_timeout,
            batch_timeout: self.batch_timeout,
        })
    }

    /// Validates all outbox worker settings.
    pub fn validate(&self) -> Result<(), ConfigValidationError> {
        self.validate_at("outbox")
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), ConfigValidationError> {
        let mut issues = ConfigIssues::new();
        issues.require(
            self.batch_size > 0,
            format!("{path}.batch_size"),
            "must be greater than zero",
        );
        issues.require(
            !self.lease_duration.is_zero(),
            format!("{path}.lease_duration"),
            "must be greater than zero",
        );
        issues.require(
            self.max_attempts > 0,
            format!("{path}.max_attempts"),
            "must be greater than zero",
        );
        if let Some(timeout) = self.item_timeout {
            issues.require(
                !timeout.is_zero(),
                format!("{path}.item_timeout"),
                "must be greater than zero when set",
            );
        }
        if let Some(timeout) = self.batch_timeout {
            issues.require(
                !timeout.is_zero(),
                format!("{path}.batch_timeout"),
                "must be greater than zero when set",
            );
        }
        issues.extend_result(
            self.retry_backoff
                .validate_at(&format!("{path}.retry_backoff")),
        );
        issues.into_result()
    }
}

#[cfg(feature = "config")]
fn default_outbox_batch_size() -> u32 {
    OutboxWorkerConfig::default().batch_size
}

#[cfg(feature = "config")]
fn default_outbox_lease_duration() -> Duration {
    OutboxWorkerConfig::default().lease_duration
}

#[cfg(feature = "config")]
fn default_outbox_max_attempts() -> u32 {
    OutboxWorkerConfig::default().retry_policy.max_attempts
}