footing 0.5.1

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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use std::{error::Error as StdError, fmt, sync::Arc, time::Duration};

use async_trait::async_trait;

use crate::result::{ClassifyError, ErrorKind};

use super::super::{BoxWorkerError, WorkerContext, WorkerSchedule};

/// Summary shape for outbox-like batch processors.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct BatchRunSummary {
    claimed: u64,
    succeeded: u64,
    retrying: u64,
    failed: u64,
    skipped: u64,
    dead_lettered: u64,
    persistence_errors: u64,
    batch_timed_out: bool,
    schedule: WorkerSchedule,
}

impl BatchRunSummary {
    #[must_use]
    /// Creates a new instance.
    pub const fn new() -> Self {
        Self {
            claimed: 0,
            succeeded: 0,
            retrying: 0,
            failed: 0,
            skipped: 0,
            dead_lettered: 0,
            persistence_errors: 0,
            batch_timed_out: false,
            schedule: WorkerSchedule::Poll,
        }
    }

    #[must_use]
    /// Configures claimed and returns the updated value.
    pub const fn with_claimed(mut self, claimed: u64) -> Self {
        self.claimed = claimed;
        self
    }

    #[must_use]
    /// Configures succeeded and returns the updated value.
    pub const fn with_succeeded(mut self, succeeded: u64) -> Self {
        self.succeeded = succeeded;
        self
    }

    #[must_use]
    /// Configures retrying and returns the updated value.
    pub const fn with_retrying(mut self, retrying: u64) -> Self {
        self.retrying = retrying;
        self
    }

    #[must_use]
    /// Configures failed and returns the updated value.
    pub const fn with_failed(mut self, failed: u64) -> Self {
        self.failed = failed;
        self
    }

    #[must_use]
    /// Configures skipped and returns the updated value.
    pub const fn with_skipped(mut self, skipped: u64) -> Self {
        self.skipped = skipped;
        self
    }

    #[must_use]
    /// Configures dead lettered and returns the updated value.
    pub const fn with_dead_lettered(mut self, dead_lettered: u64) -> Self {
        self.dead_lettered = dead_lettered;
        self
    }

    #[must_use]
    /// Configures transition persistence errors and returns the updated value.
    pub const fn with_persistence_errors(mut self, persistence_errors: u64) -> Self {
        self.persistence_errors = persistence_errors;
        self
    }

    #[must_use]
    /// Configures batch timed out and returns the updated value.
    pub const fn with_batch_timed_out(mut self, batch_timed_out: bool) -> Self {
        self.batch_timed_out = batch_timed_out;
        self
    }

    /// Replaces the scheduling intent.
    #[must_use]
    pub const fn with_schedule(mut self, schedule: WorkerSchedule) -> Self {
        self.schedule = schedule;
        self
    }

    /// Returns the scheduling intent forwarded by `BatchWorker`.
    #[must_use]
    pub const fn schedule(&self) -> WorkerSchedule {
        self.schedule
    }

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

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

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

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

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

    #[must_use]
    /// Returns the dead lettered.
    pub const fn dead_lettered(&self) -> u64 {
        self.dead_lettered
    }

    #[must_use]
    /// Returns transition persistence errors.
    pub const fn persistence_errors(&self) -> u64 {
        self.persistence_errors
    }

    #[must_use]
    /// Returns the batch timed out.
    pub const fn batch_timed_out(&self) -> bool {
        self.batch_timed_out
    }

    #[must_use]
    /// Returns the number of claimed items that reached a handled state.
    pub const fn handled(&self) -> u64 {
        self.succeeded
            .saturating_add(self.retrying)
            .saturating_add(self.failed)
            .saturating_add(self.skipped)
            .saturating_add(self.persistence_errors)
    }

    #[must_use]
    /// Returns whether the batch contained no work or timeout.
    pub const fn is_empty(&self) -> bool {
        self.claimed == 0 && self.handled() == 0 && !self.batch_timed_out
    }

    #[must_use]
    /// Returns whether this value has failures.
    pub const fn has_failures(&self) -> bool {
        self.failed > 0 || self.persistence_errors > 0 || self.batch_timed_out
    }

    /// Returns an operational error when persistence or the batch deadline failed.
    #[must_use]
    pub const fn operational_error(&self) -> Option<OutboxBatchError> {
        if self.persistence_errors == 0 && !self.batch_timed_out {
            return None;
        }
        Some(OutboxBatchError {
            persistence_errors: self.persistence_errors,
            timed_out: self.batch_timed_out,
        })
    }

    pub(super) fn record_item_state(&mut self, state: &OutboxItemState) {
        match state {
            OutboxItemState::Succeeded => {
                self.succeeded = self.succeeded.saturating_add(1);
            }
            OutboxItemState::Skipped { .. } => {
                self.skipped = self.skipped.saturating_add(1);
            }
            OutboxItemState::Retry { .. } => {
                self.retrying = self.retrying.saturating_add(1);
            }
            OutboxItemState::Failed { .. } => {
                self.failed = self.failed.saturating_add(1);
            }
        }
    }

    pub(super) fn record_persistence_error(&mut self) {
        self.persistence_errors = self.persistence_errors.saturating_add(1);
    }

    pub(super) fn record_dead_letter(&mut self) {
        self.dead_lettered = self.dead_lettered.saturating_add(1);
    }

    pub(super) fn record_batch_timeout(&mut self) {
        self.batch_timed_out = true;
    }
}

/// Redacted operational failure for one outbox batch.
#[derive(Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OutboxBatchError {
    persistence_errors: u64,
    timed_out: bool,
}

impl OutboxBatchError {
    /// Returns the number of atomic transition persistence failures.
    #[must_use]
    pub const fn persistence_errors(self) -> u64 {
        self.persistence_errors
    }

    /// Returns whether the whole-batch deadline elapsed.
    #[must_use]
    pub const fn timed_out(self) -> bool {
        self.timed_out
    }

    pub(super) const fn code(self) -> &'static str {
        match (self.persistence_errors > 0, self.timed_out) {
            (true, true) => "outbox_transition_persistence_timed_out",
            (true, false) => "outbox_transition_persistence_failed",
            (false, true) => "outbox_batch_timed_out",
            (false, false) => "outbox_batch_failed",
        }
    }
}

impl fmt::Display for OutboxBatchError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("outbox batch did not complete reliably")
    }
}

impl fmt::Debug for OutboxBatchError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OutboxBatchError")
            .field("code", &self.code())
            .field("persistence_errors", &self.persistence_errors)
            .field("timed_out", &self.timed_out)
            .finish_non_exhaustive()
    }
}

impl StdError for OutboxBatchError {}

impl ClassifyError for OutboxBatchError {
    fn error_kind(&self) -> ErrorKind {
        if self.persistence_errors > 0 {
            ErrorKind::Dependency
        } else {
            ErrorKind::Timeout
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(self.code())
    }
}

/// Application-provided batch job logic used by [`super::BatchWorker`].
///
/// Runs are at-least-once. Implementations must tolerate cancellation and a
/// subsequent retry of the same logical batch.
#[async_trait]
pub trait BatchWorkerJob: Send + Sync + 'static {
    /// Human-readable job name used in logs and metrics.
    fn name(&self) -> &str;

    /// Claims and processes one batch.
    async fn run_batch(&self, context: WorkerContext) -> Result<BatchRunSummary, BoxWorkerError>;
}

#[async_trait]
impl<T: BatchWorkerJob + ?Sized> BatchWorkerJob for Arc<T> {
    fn name(&self) -> &str {
        self.as_ref().name()
    }

    async fn run_batch(&self, context: WorkerContext) -> Result<BatchRunSummary, BoxWorkerError> {
        self.as_ref().run_batch(context).await
    }
}

/// Minimal contract for an item stored in an outbox table.
///
/// Applications keep their domain payloads and storage schema. `footing` only
/// needs the number of prior delivery attempts for retry decisions. Items should
/// carry their storage identifier and any item-level claim token needed to reject
/// stale transitions; those remain application-defined.
pub trait OutboxItem: Send + Sync + 'static {
    /// Number of attempts already recorded before the current delivery try.
    fn outbox_attempts(&self) -> u32;
}

/// Claim request passed to application outbox storage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OutboxClaim {
    limit: u32,
    lease_duration: Duration,
}

impl OutboxClaim {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(limit: u32, lease_duration: Duration) -> Self {
        Self {
            limit,
            lease_duration,
        }
    }

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

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

/// State transition requested after one outbox item is handled.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum OutboxItemState {
    /// Indicates succeeded.
    Succeeded,
    /// Indicates skipped.
    Skipped {
        #[doc = "The reason for this outcome."]
        reason: String,
    },
    /// Requests a retry with a custom delay, subject to the job's attempt limit.
    Retry {
        #[doc = "The reason for this outcome."]
        reason: String,
        #[doc = "The delay before the next action."]
        delay: Duration,
    },
    /// Indicates a terminal failure that must be dead-lettered atomically.
    Failed {
        #[doc = "The reason for this outcome."]
        reason: String,
    },
}

impl fmt::Debug for OutboxItemState {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Succeeded => formatter.write_str("OutboxItemState::Succeeded"),
            Self::Skipped { .. } => formatter
                .debug_struct("OutboxItemState::Skipped")
                .field("reason", &"[REDACTED]")
                .finish(),
            Self::Retry { delay, .. } => formatter
                .debug_struct("OutboxItemState::Retry")
                .field("reason", &"[REDACTED]")
                .field("delay", delay)
                .finish(),
            Self::Failed { .. } => formatter
                .debug_struct("OutboxItemState::Failed")
                .field("reason", &"[REDACTED]")
                .finish(),
        }
    }
}

impl OutboxItemState {
    #[must_use]
    /// Creates retry.
    pub fn retry(reason: impl Into<String>, delay: Duration) -> Self {
        Self::Retry {
            reason: bounded_outbox_reason(reason),
            delay,
        }
    }

    #[must_use]
    /// Creates failed.
    pub fn failed(reason: impl Into<String>) -> Self {
        Self::Failed {
            reason: bounded_outbox_reason(reason),
        }
    }

    #[must_use]
    /// Creates skipped.
    pub fn skipped(reason: impl Into<String>) -> Self {
        Self::Skipped {
            reason: bounded_outbox_reason(reason),
        }
    }

    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Succeeded => "succeeded",
            Self::Skipped { .. } => "skipped",
            Self::Retry { .. } => "retry",
            Self::Failed { .. } => "failed",
        }
    }
}

/// Application storage needed by [`super::OutboxJob`].
///
/// The runtime is deliberately at-least-once: a claim may be handled again
/// after cancellation, timeout, lease loss, or an ambiguous storage result.
/// Implementations must make both methods cancellation-safe and use conditional
/// writes or fencing tokens to reject stale workers. A lease alone cannot fence
/// external side effects.
#[async_trait]
pub trait OutboxStore<I>: Send + Sync + 'static
where
    I: OutboxItem,
{
    /// Claims due items for this worker tick.
    ///
    /// Return at most `claim.limit()` available items. Future retries and items
    /// with an active claim must not be returned, even after a wakeup signal.
    /// The claim must be durable for `claim.lease_duration()` and safe to retry
    /// if this future is dropped before its result is observed.
    /// `context` carries the runner fencing token, independently of item claims.
    async fn claim_due(
        &self,
        claim: OutboxClaim,
        context: WorkerContext,
    ) -> Result<Vec<I>, BoxWorkerError>;

    /// Atomically persists the transition for a handled item.
    ///
    /// For [`OutboxItemState::Failed`], this single operation must commit both
    /// the terminal item state and its dead-letter record in one transaction.
    /// It must never expose a terminal item without the corresponding dead
    /// letter. The write should also condition on the item's claim/fencing token
    /// and be idempotent because a timeout leaves the commit result ambiguous.
    /// Enforce the runner fencing token from `context` when storage supports it.
    async fn persist_transition(
        &self,
        item: &I,
        state: OutboxItemState,
        context: WorkerContext,
    ) -> Result<(), BoxWorkerError>;
}

#[async_trait]
impl<I: OutboxItem, T: OutboxStore<I> + ?Sized> OutboxStore<I> for Arc<T> {
    async fn claim_due(
        &self,
        claim: OutboxClaim,
        context: WorkerContext,
    ) -> Result<Vec<I>, BoxWorkerError> {
        self.as_ref().claim_due(claim, context).await
    }

    async fn persist_transition(
        &self,
        item: &I,
        state: OutboxItemState,
        context: WorkerContext,
    ) -> Result<(), BoxWorkerError> {
        self.as_ref().persist_transition(item, state, context).await
    }
}

/// Application delivery logic for one outbox item.
///
/// Delivery is at-least-once. Handlers must be idempotent and cancellation-safe:
/// the future may be dropped at an item or batch deadline and the same item may
/// later be delivered again. Use downstream idempotency keys or an application
/// fencing protocol for effects that the outbox claim itself cannot protect.
#[async_trait]
pub trait OutboxHandler<I>: Send + Sync + 'static
where
    I: OutboxItem,
{
    /// Delivers or handles one claimed item, with the current runner fencing token.
    async fn handle(
        &self,
        item: &I,
        context: WorkerContext,
    ) -> Result<OutboxItemState, BoxWorkerError>;
}

#[async_trait]
impl<I: OutboxItem, T: OutboxHandler<I> + ?Sized> OutboxHandler<I> for Arc<T> {
    async fn handle(
        &self,
        item: &I,
        context: WorkerContext,
    ) -> Result<OutboxItemState, BoxWorkerError> {
        self.as_ref().handle(item, context).await
    }
}

fn bounded_outbox_reason(reason: impl Into<String>) -> String {
    const MAX_REASON_LEN: usize = 1024;

    let mut reason = reason.into().trim().to_owned();
    if reason.len() <= MAX_REASON_LEN {
        return reason;
    }
    reason.truncate(reason.floor_char_boundary(MAX_REASON_LEN));
    reason
}