footing 0.1.6

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

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

#[cfg(feature = "settings")]
use crate::settings::{SettingsIssues, SettingsValidationError};

#[cfg(feature = "settings")]
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: Duration,
    batch_timeout: Duration,
}

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

impl OutboxWorkerConfig {
    /// Creates a validated, deadline-bounded outbox configuration.
    pub fn new(
        batch_size: u32,
        lease_duration: Duration,
        retry_policy: OutboxRetryPolicy,
        item_timeout: Duration,
        batch_timeout: Duration,
    ) -> Result<Self, WorkerConfigError> {
        if batch_size == 0 {
            return Err(WorkerConfigError::InvalidOutboxBatchSize);
        }
        if lease_duration.is_zero() || time::Instant::now().checked_add(lease_duration).is_none() {
            return Err(WorkerConfigError::InvalidOutboxLeaseDuration);
        }
        if item_timeout.is_zero()
            || item_timeout >= batch_timeout
            || time::Instant::now().checked_add(item_timeout).is_none()
        {
            return Err(WorkerConfigError::InvalidOutboxItemTimeout);
        }
        if batch_timeout.is_zero()
            || batch_timeout >= lease_duration
            || time::Instant::now().checked_add(batch_timeout).is_none()
        {
            return Err(WorkerConfigError::InvalidOutboxBatchTimeout);
        }
        Ok(Self {
            batch_size,
            lease_duration,
            retry_policy,
            item_timeout,
            batch_timeout,
        })
    }

    #[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 mandatory per-item deadline.
    pub const fn item_timeout(&self) -> Duration {
        self.item_timeout
    }

    #[must_use]
    /// Returns the mandatory whole-batch deadline.
    pub const fn batch_timeout(&self) -> Duration {
        self.batch_timeout
    }
}

#[cfg(feature = "settings")]
#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[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::settings::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 = "default_outbox_item_timeout",
        with = "crate::settings::human_duration"
    )]
    /// Mandatory timeout for processing one entry.
    pub item_timeout: Duration,
    #[serde(
        default = "default_outbox_batch_timeout",
        with = "crate::settings::human_duration"
    )]
    /// Mandatory timeout for one claimed batch.
    pub batch_timeout: Duration,
}

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

#[cfg(feature = "settings")]
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 = "settings")]
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 the mandatory item deadline and returns the updated value.
    pub const fn with_item_timeout(mut self, item_timeout: Duration) -> Self {
        self.item_timeout = item_timeout;
        self
    }

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

    /// Builds validated outbox worker configuration.
    pub fn build(self) -> Result<OutboxWorkerConfig, SettingsValidationError> {
        self.validate()?;
        OutboxWorkerConfig::new(
            self.batch_size,
            self.lease_duration,
            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,
                },
            },
            self.item_timeout,
            self.batch_timeout,
        )
        .map_err(|error| SettingsValidationError::single("outbox", error.to_string()))
    }

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

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        issues.require(
            self.batch_size > 0,
            format!("{path}.batch_size"),
            "must be greater than zero",
        );
        issues.require(
            !self.lease_duration.is_zero()
                && time::Instant::now()
                    .checked_add(self.lease_duration)
                    .is_some(),
            format!("{path}.lease_duration"),
            "must be greater than zero and fit the runtime timer range",
        );
        issues.require(
            self.max_attempts > 0,
            format!("{path}.max_attempts"),
            "must be greater than zero",
        );
        issues.require(
            !self.item_timeout.is_zero()
                && self.item_timeout < self.batch_timeout
                && time::Instant::now()
                    .checked_add(self.item_timeout)
                    .is_some(),
            format!("{path}.item_timeout"),
            "must be greater than zero, fit the runtime timer range, and be less than batch_timeout",
        );
        issues.require(
            !self.batch_timeout.is_zero()
                && self.batch_timeout < self.lease_duration
                && time::Instant::now()
                    .checked_add(self.batch_timeout)
                    .is_some(),
            format!("{path}.batch_timeout"),
            "must be greater than zero, fit the runtime timer range, and be less than lease_duration",
        );
        issues.extend_result(
            self.retry_backoff
                .validate_at(&format!("{path}.retry_backoff")),
        );
        issues.into_result()
    }
}

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

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

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

#[cfg(feature = "settings")]
fn default_outbox_item_timeout() -> Duration {
    OutboxWorkerConfig::default().item_timeout
}

#[cfg(feature = "settings")]
fn default_outbox_batch_timeout() -> Duration {
    OutboxWorkerConfig::default().batch_timeout
}