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};
#[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 {
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]
pub const fn max_attempts(&self) -> u32 {
self.max_attempts
}
#[must_use]
pub const fn backoff(&self) -> BackoffConfig {
self.backoff
}
#[must_use]
pub const fn should_retry(&self, attempts_after_current_try: u32) -> bool {
attempts_after_current_try < self.max_attempts
}
#[must_use]
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
}
}
#[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 {
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]
pub const fn batch_size(&self) -> u32 {
self.batch_size
}
#[must_use]
pub const fn lease_duration(&self) -> Duration {
self.lease_duration
}
#[must_use]
pub const fn retry_policy(&self) -> OutboxRetryPolicy {
self.retry_policy
}
#[must_use]
pub const fn item_timeout(&self) -> Duration {
self.item_timeout
}
#[must_use]
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]
pub struct OutboxWorkerSettings {
#[serde(default = "default_outbox_batch_size")]
pub batch_size: u32,
#[serde(
default = "default_outbox_lease_duration",
with = "crate::settings::human_duration"
)]
pub lease_duration: Duration,
#[serde(default = "default_outbox_max_attempts")]
pub max_attempts: u32,
#[serde(default)]
pub retry_backoff: BackoffSettings,
#[serde(
default = "default_outbox_item_timeout",
with = "crate::settings::human_duration"
)]
pub item_timeout: Duration,
#[serde(
default = "default_outbox_batch_timeout",
with = "crate::settings::human_duration"
)]
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]
pub const fn with_batch_size(mut self, batch_size: u32) -> Self {
self.batch_size = batch_size;
self
}
#[must_use]
pub const fn with_lease_duration(mut self, lease_duration: Duration) -> Self {
self.lease_duration = lease_duration;
self
}
#[must_use]
pub const fn with_max_attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = max_attempts;
self
}
#[must_use]
pub const fn with_retry_backoff(mut self, retry_backoff: BackoffSettings) -> Self {
self.retry_backoff = retry_backoff;
self
}
#[must_use]
pub const fn with_item_timeout(mut self, item_timeout: Duration) -> Self {
self.item_timeout = item_timeout;
self
}
#[must_use]
pub const fn with_batch_timeout(mut self, batch_timeout: Duration) -> Self {
self.batch_timeout = batch_timeout;
self
}
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()))
}
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
}