footing 0.4.4

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

use serde::{Deserialize, Serialize};
use tokio::time;

use crate::settings::{SettingsIssues, SettingsValidationError};

use super::super::{BackoffConfig, BackoffSettings, 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 {
            // Once fixed or capped, further attempts cannot change the delay.
            if self.backoff.multiplier == 1 || delay == self.backoff.max_delay {
                break;
            }
            delay = delay
                .saturating_mul(self.backoff.multiplier)
                .min(self.backoff.max_delay);
        }
        delay
    }
}

/// Runtime config for [`super::OutboxJob`].
/// Build customized configurations with [`OutboxWorkerSettings::build`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OutboxWorkerConfig {
    batch_size: u32,
    max_concurrency: usize,
    lease_duration: Duration,
    retry_policy: OutboxRetryPolicy,
    item_timeout: Duration,
    batch_timeout: Duration,
}

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

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

    /// Returns the maximum number of items being handled or persisted at once.
    #[must_use]
    pub const fn max_concurrency(&self) -> usize {
        self.max_concurrency
    }

    #[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_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for outbox worker.
pub struct OutboxWorkerSettings {
    /// Maximum number of outbox entries claimed per iteration.
    pub batch_size: u32,
    /// Maximum concurrent items, including result persistence; defaults to one.
    /// Values above one require independent items and do not preserve completion order.
    pub max_concurrency: usize,
    #[serde(with = "crate::settings::human_duration")]
    /// Duration of an outbox claim before it may be reclaimed.
    pub lease_duration: Duration,
    /// Maximum delivery attempts before dead-lettering an entry.
    pub max_attempts: u32,
    #[serde(deserialize_with = "deserialize_outbox_retry_backoff")]
    /// Delay policy applied between delivery attempts.
    /// Missing nested fields inherit the outbox defaults (30 seconds to 30 minutes).
    pub retry_backoff: BackoffSettings,
    #[serde(with = "crate::settings::human_duration")]
    /// Mandatory timeout for processing one entry.
    pub item_timeout: Duration,
    #[serde(with = "crate::settings::human_duration")]
    /// Mandatory timeout for one claimed batch.
    pub batch_timeout: Duration,
}

impl Default for OutboxWorkerSettings {
    fn default() -> Self {
        Self::from(OutboxWorkerConfig::default())
    }
}

impl From<OutboxWorkerConfig> for OutboxWorkerSettings {
    fn from(value: OutboxWorkerConfig) -> Self {
        Self {
            batch_size: value.batch_size,
            max_concurrency: value.max_concurrency,
            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,
        }
    }
}

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
    }

    /// Sets the nonzero concurrency limit for each batch.
    #[must_use]
    pub const fn with_max_concurrency(mut self, max_concurrency: usize) -> Self {
        self.max_concurrency = max_concurrency;
        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()?;
        Ok(OutboxWorkerConfig {
            batch_size: self.batch_size,
            max_concurrency: self.max_concurrency,
            lease_duration: self.lease_duration,
            retry_policy: OutboxRetryPolicy {
                max_attempts: self.max_attempts,
                backoff: self.retry_backoff.into_config(),
            },
            item_timeout: self.item_timeout,
            batch_timeout: self.batch_timeout,
        })
    }

    /// 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.max_concurrency > 0,
            format!("{path}.max_concurrency"),
            "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()
    }
}

fn default_outbox_retry_backoff() -> BackoffSettings {
    BackoffSettings::from(OutboxRetryPolicy::default().backoff())
}

fn deserialize_outbox_retry_backoff<'de, D>(deserializer: D) -> Result<BackoffSettings, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(default, deny_unknown_fields)]
    struct Wire {
        #[serde(with = "crate::settings::human_duration")]
        initial_delay: Duration,
        #[serde(with = "crate::settings::human_duration")]
        max_delay: Duration,
        multiplier: u32,
    }
    impl Default for Wire {
        fn default() -> Self {
            let defaults = default_outbox_retry_backoff();
            Self {
                initial_delay: defaults.initial_delay,
                max_delay: defaults.max_delay,
                multiplier: defaults.multiplier,
            }
        }
    }
    let wire = Wire::deserialize(deserializer)?;
    Ok(BackoffSettings::new(
        wire.initial_delay,
        wire.max_delay,
        wire.multiplier,
    ))
}