footing 0.1.8

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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 {
            // Once fixed or capped, further attempts cannot change the delay.
            if self.backoff.multiplier == 1 || delay == self.backoff.max_delay {
                break;
            }
            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 = "default_outbox_retry_backoff",
        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(
        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_retry_backoff() -> BackoffSettings {
    BackoffSettings::from(OutboxRetryPolicy::default().backoff())
}

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

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