footing 0.4.3

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
use std::{fmt, future::Future, marker::PhantomData};

use async_trait::async_trait;
use futures_util::{StreamExt, stream::FuturesUnordered};
use tokio::time::{self, Instant};

use super::super::{BoxWorkerError, Worker, WorkerContext, WorkerSchedule, WorkerTick};
use super::{
    BatchRunSummary, BatchWorkerJob, OutboxClaim, OutboxHandler, OutboxItem, OutboxItemState,
    OutboxRetryPolicy, OutboxStore, OutboxWorkerConfig,
};

/// Generic outbox batch job that can be wrapped in [`BatchWorker`].
///
/// Items run serially by default. [`super::OutboxWorkerSettings::max_concurrency`]
/// can opt independent items into bounded concurrency. A slot remains occupied
/// until both handling and persistence finish; completion order is unspecified
/// when concurrency is greater than one. The batch deadline includes claiming
/// and every item, while each item timeout starts when its handler begins.
///
/// At the batch deadline no queued handlers start, and active futures are
/// cancelled while their timeout outcomes are collected. Cancelling the batch
/// drops every active future. No independent tasks are spawned; stores and
/// handlers must tolerate cancellation and repeated delivery.
#[non_exhaustive]
pub struct OutboxJob<S, H, I> {
    name: String,
    store: S,
    handler: H,
    config: OutboxWorkerConfig,
    queue_scheduling: bool,
    _item: PhantomData<I>,
}

impl<S: Clone, H: Clone, I> Clone for OutboxJob<S, H, I> {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            store: self.store.clone(),
            handler: self.handler.clone(),
            config: self.config,
            queue_scheduling: self.queue_scheduling,
            _item: PhantomData,
        }
    }
}

impl<S: fmt::Debug, H: fmt::Debug, I> fmt::Debug for OutboxJob<S, H, I> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OutboxJob")
            .field("name", &self.name)
            .field("store", &self.store)
            .field("handler", &self.handler)
            .field("config", &self.config)
            .field("queue_scheduling", &self.queue_scheduling)
            .finish_non_exhaustive()
    }
}

impl<S, H, I> OutboxJob<S, H, I>
where
    I: OutboxItem,
{
    #[must_use]
    /// Creates a new instance.
    pub fn new(name: impl Into<String>, store: S, handler: H, config: OutboxWorkerConfig) -> Self {
        Self {
            name: name.into(),
            store,
            handler,
            config,
            queue_scheduling: false,
            _item: PhantomData,
        }
    }

    #[must_use]
    /// Configures config and returns the updated value.
    pub fn with_config(mut self, config: OutboxWorkerConfig) -> Self {
        self.config = config;
        self
    }

    /// Enables continuous consumption and wakeable idle waits for this job.
    ///
    /// A full claim requests another batch; a shorter claim waits for work.
    /// This is only a hint, so the store must always claim only due, available
    /// items and persist retries with their due times. Item outcomes do not
    /// decide whether more work exists. Operational errors still fail the tick.
    ///
    /// Retry delays in the current batch can request an earlier idle check;
    /// polling covers other retries and missed notifications. By default, this
    /// job uses `Poll`; a retry never postpones checking for other due items.
    #[must_use]
    pub const fn with_queue_scheduling(mut self) -> Self {
        self.queue_scheduling = true;
        self
    }

    #[must_use]
    /// Returns the store.
    pub fn store(&self) -> &S {
        &self.store
    }

    #[must_use]
    /// Returns the handler.
    pub fn handler(&self) -> &H {
        &self.handler
    }

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

    async fn process_item(
        &self,
        item: I,
        context: WorkerContext,
        batch_deadline: Instant,
    ) -> ItemCompletion
    where
        S: OutboxStore<I>,
        H: OutboxHandler<I>,
    {
        let state =
            match handle_outbox_item(&self.handler, &item, context, self.config, batch_deadline)
                .await
            {
                HandleItemResult::State(state) => state,
                HandleItemResult::BatchTimedOut => return ItemCompletion::BatchTimedOut,
            };
        match before_batch_deadline(batch_deadline, async {
            self.store
                .persist_transition(&item, state.clone(), context)
                .await
        })
        .await
        {
            Ok(Ok(())) => {
                // Start the hint at this item's commit, not when the consumer
                // happens to collect its completion among concurrent results.
                let retry_at = match &state {
                    OutboxItemState::Retry { delay, .. } if self.queue_scheduling => {
                        Instant::now().checked_add(*delay)
                    }
                    _ => None,
                };
                ItemCompletion::Persisted { state, retry_at }
            }
            result => {
                let timed_out = result.is_err();
                tracing::warn!(
                    worker = self.name,
                    error_code = if timed_out {
                        "outbox_transition_persistence_timed_out"
                    } else {
                        "outbox_transition_persistence_failed"
                    },
                    state = state.as_str(),
                    "outbox transition persistence failed"
                );
                ItemCompletion::PersistenceFailed { timed_out }
            }
        }
    }
}

#[async_trait]
impl<S, H, I> BatchWorkerJob for OutboxJob<S, H, I>
where
    S: OutboxStore<I>,
    H: OutboxHandler<I>,
    I: OutboxItem,
{
    fn name(&self) -> &str {
        &self.name
    }

    async fn run_batch(&self, context: WorkerContext) -> Result<BatchRunSummary, BoxWorkerError> {
        let claim = OutboxClaim::new(self.config.batch_size(), self.config.lease_duration());
        let mut summary = BatchRunSummary::new();
        let batch_deadline = match Instant::now().checked_add(self.config.batch_timeout()) {
            Some(deadline) => deadline,
            None => {
                summary.record_batch_timeout();
                return Ok(summary);
            }
        };
        let items =
            match before_batch_deadline(batch_deadline, self.store.claim_due(claim, context)).await
            {
                Ok(result) => result?,
                Err(()) => {
                    summary.record_batch_timeout();
                    return Ok(summary);
                }
            };
        summary = summary.with_claimed(items.len() as u64);
        let mut next_retry_at: Option<Instant> = None;
        let mut items = items.into_iter();
        let mut pending = FuturesUnordered::new();
        loop {
            while pending.len() < self.config.max_concurrency() {
                if Instant::now() >= batch_deadline {
                    if items.len() > 0 {
                        summary.record_batch_timeout();
                    }
                    break;
                }
                let Some(item) = items.next() else { break };
                pending.push(self.process_item(item, context, batch_deadline));
            }
            let Some(completion) = pending.next().await else {
                break;
            };
            match completion {
                ItemCompletion::Persisted { state, retry_at } => {
                    if let Some(deadline) = retry_at {
                        next_retry_at =
                            Some(next_retry_at.map_or(deadline, |current| current.min(deadline)));
                    }
                    summary.record_item_state(&state);
                    if matches!(state, OutboxItemState::Failed { .. }) {
                        summary.record_dead_letter();
                    }
                }
                ItemCompletion::PersistenceFailed { timed_out } => {
                    summary.record_persistence_error();
                    if timed_out {
                        summary.record_batch_timeout();
                    }
                }
                ItemCompletion::BatchTimedOut => {
                    summary.record_batch_timeout();
                }
            }
        }

        let recheck_after =
            next_retry_at.map(|deadline| deadline.saturating_duration_since(Instant::now()));
        let schedule = if self.queue_scheduling {
            if summary.claimed() >= u64::from(self.config.batch_size()) {
                WorkerSchedule::Continue
            } else {
                WorkerSchedule::WaitForWork { recheck_after }
            }
        } else {
            WorkerSchedule::Poll
        };
        Ok(summary.with_schedule(schedule))
    }
}

enum ItemCompletion {
    Persisted {
        state: OutboxItemState,
        retry_at: Option<Instant>,
    },
    PersistenceFailed {
        timed_out: bool,
    },
    BatchTimedOut,
}

/// Worker adapter for outbox-like batch jobs.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct BatchWorker<J> {
    job: J,
    log_empty_batches: bool,
}

impl<J> BatchWorker<J> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(job: J) -> Self {
        Self {
            job,
            log_empty_batches: false,
        }
    }

    #[must_use]
    /// Configures empty batch logging and returns the updated value.
    pub const fn with_empty_batch_logging(mut self, enabled: bool) -> Self {
        self.log_empty_batches = enabled;
        self
    }

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

#[async_trait]
impl<J> Worker for BatchWorker<J>
where
    J: BatchWorkerJob,
{
    fn name(&self) -> &str {
        self.job.name()
    }

    async fn run_once(&self, context: WorkerContext) -> Result<WorkerTick, BoxWorkerError> {
        let summary = self.job.run_batch(context).await?;
        if self.log_empty_batches || !summary.is_empty() {
            tracing::info!(
                worker = self.name(),
                claimed = summary.claimed(),
                succeeded = summary.succeeded(),
                retrying = summary.retrying(),
                failed = summary.failed(),
                skipped = summary.skipped(),
                dead_lettered = summary.dead_lettered(),
                persistence_errors = summary.persistence_errors(),
                batch_timed_out = summary.batch_timed_out(),
                handled = summary.handled(),
                "batch worker completed"
            );
        }

        if let Some(error) = summary.operational_error() {
            return Err(error.into());
        }
        Ok(WorkerTick::new(summary.handled()).with_schedule(summary.schedule()))
    }
}

fn retry_or_fail_state(
    retry_policy: &OutboxRetryPolicy,
    prior_attempts: u32,
    reason: String,
) -> OutboxItemState {
    let attempts_after_current_try = prior_attempts.saturating_add(1);
    if retry_policy.should_retry(attempts_after_current_try) {
        OutboxItemState::retry(
            reason,
            retry_policy.delay_for_attempts(attempts_after_current_try),
        )
    } else {
        OutboxItemState::failed(reason)
    }
}

async fn handle_outbox_item<H, I>(
    handler: &H,
    item: &I,
    context: WorkerContext,
    config: OutboxWorkerConfig,
    batch_deadline: Instant,
) -> HandleItemResult
where
    H: OutboxHandler<I>,
    I: OutboxItem,
{
    let now = Instant::now();
    if batch_deadline <= now {
        return HandleItemResult::BatchTimedOut;
    }
    let item_deadline = match now.checked_add(config.item_timeout()) {
        Some(deadline) => deadline,
        None => {
            return HandleItemResult::State(retry_or_fail_state(
                &config.retry_policy(),
                item.outbox_attempts(),
                "outbox_item_timed_out".to_owned(),
            ));
        }
    };
    let deadline = batch_deadline.min(item_deadline);
    let result = match time::timeout_at(deadline, handler.handle(item, context)).await {
        Ok(Ok(state)) => Ok(state),
        Ok(Err(_)) => Err("outbox_handler_failed"),
        Err(_) if batch_deadline <= item_deadline => {
            return HandleItemResult::BatchTimedOut;
        }
        Err(_) => Err("outbox_item_timed_out"),
    };

    HandleItemResult::State(match result {
        Ok(OutboxItemState::Retry { reason, .. })
            if !config
                .retry_policy()
                .should_retry(item.outbox_attempts().saturating_add(1)) =>
        {
            OutboxItemState::failed(reason)
        }
        Ok(state) => state,
        Err(reason) => retry_or_fail_state(
            &config.retry_policy(),
            item.outbox_attempts(),
            reason.to_owned(),
        ),
    })
}

enum HandleItemResult {
    State(OutboxItemState),
    BatchTimedOut,
}

async fn before_batch_deadline<F, T>(deadline: Instant, future: F) -> Result<T, ()>
where
    F: Future<Output = T>,
{
    if deadline <= Instant::now() {
        return Err(());
    }
    time::timeout_at(deadline, future).await.map_err(|_| ())
}