footing 0.1.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
use std::{fmt, time::Duration};

use async_trait::async_trait;

use super::super::BoxWorkerError;

/// 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,
    state_errors: u64,
    dead_letter_errors: u64,
    batch_timed_out: bool,
    next_delay: Option<Duration>,
}

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,
            state_errors: 0,
            dead_letter_errors: 0,
            batch_timed_out: false,
            next_delay: None,
        }
    }

    #[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 state errors and returns the updated value.
    pub const fn with_state_errors(mut self, state_errors: u64) -> Self {
        self.state_errors = state_errors;
        self
    }

    #[must_use]
    /// Configures dead letter errors and returns the updated value.
    pub const fn with_dead_letter_errors(mut self, dead_letter_errors: u64) -> Self {
        self.dead_letter_errors = dead_letter_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
    }

    #[must_use]
    /// Configures next delay and returns the updated value.
    pub const fn with_next_delay(mut self, next_delay: Duration) -> Self {
        self.next_delay = Some(next_delay);
        self
    }

    #[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 the state errors.
    pub const fn state_errors(&self) -> u64 {
        self.state_errors
    }

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

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

    #[must_use]
    /// Returns the next delay.
    pub const fn next_delay(&self) -> Option<Duration> {
        self.next_delay
    }

    #[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.state_errors)
    }

    #[must_use]
    /// Returns whether the batch contained no work or timeout.
    pub const fn 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.state_errors > 0
            || self.dead_letter_errors > 0
            || 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 { delay, .. } => {
                self.retrying = self.retrying.saturating_add(1);
                self.record_next_delay(*delay);
            }
            OutboxItemState::Failed { .. } => {
                self.failed = self.failed.saturating_add(1);
            }
        }
    }

    pub(super) fn record_state_error(&mut self) {
        self.state_errors = self.state_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_dead_letter_error(&mut self) {
        self.dead_letter_errors = self.dead_letter_errors.saturating_add(1);
    }

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

    fn record_next_delay(&mut self, delay: Duration) {
        self.next_delay = Some(self.next_delay.map_or(delay, |current| current.min(delay)));
    }
}

/// Application-provided batch job logic used by [`super::BatchWorker`].
#[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) -> Result<BatchRunSummary, BoxWorkerError>;
}

/// Minimal contract for an item stored in an outbox table.
///
/// Applications keep their domain payloads and storage schema. `footing` only
/// needs a stable identifier for logging/state updates and the number of prior
/// delivery attempts for retry decisions.
pub trait OutboxItem: Send + Sync + 'static {
    /// Stable item identifier used for logs and state updates.
    fn outbox_id(&self) -> String;

    /// 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,
    },
    /// Indicates retry.
    Retry {
        #[doc = "The reason for this outcome."]
        reason: String,
        #[doc = "The delay before the next action."]
        delay: Duration,
    },
    /// Indicates failed.
    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(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Enumerates the supported outbox failure class values.
pub enum OutboxFailureClass {
    /// Indicates retryable.
    Retryable,
    /// Indicates terminal.
    Terminal,
}

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",
        }
    }

    #[must_use]
    /// Returns the failure class.
    pub const fn failure_class(&self) -> Option<OutboxFailureClass> {
        match self {
            Self::Retry { .. } => Some(OutboxFailureClass::Retryable),
            Self::Failed { .. } => Some(OutboxFailureClass::Terminal),
            Self::Succeeded | Self::Skipped { .. } => None,
        }
    }
}

/// Application storage needed by [`super::OutboxJob`].
#[async_trait]
pub trait OutboxStore<I>: Send + Sync + 'static
where
    I: OutboxItem,
{
    /// Claims due items for this worker tick.
    async fn claim_due(&self, claim: OutboxClaim) -> Result<Vec<I>, BoxWorkerError>;

    /// Persists the state transition for a handled item.
    async fn record_state(&self, item: &I, state: OutboxItemState) -> Result<(), BoxWorkerError>;

    /// Optional hook called after a terminal failure has been recorded.
    async fn record_dead_letter(&self, _item: &I, _reason: &str) -> Result<(), BoxWorkerError> {
        Ok(())
    }
}

/// Application delivery logic for one outbox item.
#[async_trait]
pub trait OutboxHandler<I>: Send + Sync + 'static
where
    I: OutboxItem,
{
    /// Delivers or handles one claimed item.
    async fn handle(&self, item: &I) -> Result<OutboxItemState, BoxWorkerError>;
}

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(MAX_REASON_LEN);
    while !reason.is_char_boundary(reason.len()) {
        reason.pop();
    }
    reason
}