beavers 0.0.2

Typed message processing for Kafka, Pulsar, RabbitMQ, SQS, Azure Service Bus, and HTTP with explicit delivery semantics
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
//! One delivery: decode, middleware, handler retries, publishing, failure routing, then ACK.
use super::{
    builder::{BoxHandler, DeadLetterRoute, Mapper},
    completion::{BoxFuture, Complete, Completion, acknowledge as ack_delivery},
    instruments::{Instruments, Stage},
};
use crate::{
    dead_letter::DeadLetter,
    error::{BoxContext, BoxError, chain},
    error_policy::{ErrorPolicy, FailureAction, FailureKind},
    handler::HandlerError,
    health::Tracker,
    message::SourceMessage,
    middleware::Flow,
    retry::RetryPolicy,
    sink::PublishRejected,
};
use metrics::Counter;
use std::{future::Future, sync::Arc, time::Instant};
use tracing::{Instrument, debug, info_span, warn};

/// Everything a job needs, shared by all jobs of one subscription run.
pub(super) struct Pipeline<M: SourceMessage, O> {
    pub(super) name: String,
    pub(super) handler: BoxHandler<M::Item, O>,
    pub(super) middleware: Vec<Mapper<M::Item, O>>,
    pub(super) output: Arc<dyn Complete<M, O>>,
    pub(super) dlq: Option<DeadLetterRoute<M::Item, M::Raw>>,
    pub(super) handler_retry: RetryPolicy,
    pub(super) publish_retry: RetryPolicy,
    pub(super) dead_letter_retry: RetryPolicy,
    pub(super) error_policy: ErrorPolicy,
    pub(super) instruments: Instruments,
}

/// Waits for submitted outputs to complete, then acknowledges the delivery.
pub(super) type PendingAck = BoxFuture<'static, Result<(), BoxError>>;

/// A routable failure; `input` is absent only when decoding failed.
struct Failure<I> {
    kind: FailureKind,
    error: BoxError,
    attempts: usize,
    input: Option<I>,
}

/// Outputs to complete, or a failure to route; errors stop the subscription.
type Handled<I, O> = Result<Result<Outputs<I, O>, Failure<I>>, BoxError>;

/// Outputs ready for the completion stage, with what failure routing needs.
struct Outputs<I, O> {
    values: Vec<O>,
    input: I,
    attempts: usize,
}

/// Processes one delivery. Returns the acknowledgement still waiting for submitted
/// outputs to complete, if any; otherwise the delivery was already settled.
pub(super) async fn process<M, O>(
    delivery: M,
    pipeline: Arc<Pipeline<M, O>>,
) -> Result<Option<PendingAck>, BoxError>
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    let started = Instant::now();
    let decoded = info_span!("decode").in_scope(|| delivery.decode());
    pipeline.instruments.record(Stage::Decode, started);
    let failure = match decoded {
        Ok(input) => match handle(input, &pipeline).await? {
            Ok(Outputs {
                values,
                input,
                attempts,
            }) => match pipeline
                .output
                .complete(
                    delivery,
                    values,
                    &pipeline.publish_retry,
                    &pipeline.instruments,
                )
                .await?
            {
                Completion::Done => return Ok(None),
                Completion::Pending(delivery, completions) => {
                    return Ok(Some(await_completions(delivery, completions, pipeline)));
                }
                Completion::Committing(committed) => {
                    return Ok(Some(await_commit(committed, pipeline)));
                }
                Completion::Encode(delivery, error) => {
                    let failure = Failure {
                        kind: FailureKind::Encode,
                        error,
                        attempts,
                        input: Some(input),
                    };
                    return route(delivery, pipeline, failure).await;
                }
                Completion::Rejected(delivery, error) => {
                    let failure = Failure {
                        kind: FailureKind::PublishRejected,
                        error,
                        attempts,
                        input: Some(input),
                    };
                    return route(delivery, pipeline, failure).await;
                }
            },
            Err(failure) => failure,
        },
        Err(error) => Failure {
            kind: FailureKind::Decode,
            error,
            attempts: 0,
            input: None,
        },
    };
    route(delivery, pipeline, failure).await
}

/// The job ends before this runs and frees its slot; the acknowledgement follows
/// completion of every submitted output.
fn await_completions<M, O>(
    delivery: M,
    completions: Vec<crate::sink::Completion>,
    pipeline: Arc<Pipeline<M, O>>,
) -> PendingAck
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    Box::pin(async move {
        let started = Instant::now();
        async {
            for completion in completions {
                completion.wait().await?;
            }
            Ok::<_, BoxError>(())
        }
        .instrument(info_span!("complete"))
        .await
        .map_err(|error| error.context("output completion failed"))?;
        pipeline.instruments.record(Stage::Complete, started);
        ack_delivery(delivery, &pipeline.instruments).await
    })
}

/// The job ends before this runs and frees its slot; the delivery counts as
/// acknowledged once the transaction containing it commits.
fn await_commit<M, O>(
    committed: crate::sink::Completion,
    pipeline: Arc<Pipeline<M, O>>,
) -> PendingAck
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    Box::pin(async move {
        committed
            .wait()
            .await
            .map_err(|error| error.context("transaction commit failed"))?;
        pipeline.instruments.acknowledged.increment(1);
        Ok(())
    })
}

/// Acknowledges a delivery without output through the completion stage, so a
/// transactional subscription commits it in a transaction as well.
async fn acknowledge<M, O>(
    delivery: M,
    pipeline: Arc<Pipeline<M, O>>,
) -> Result<Option<PendingAck>, BoxError>
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    match pipeline
        .output
        .complete(
            delivery,
            Vec::new(),
            &pipeline.publish_retry,
            &pipeline.instruments,
        )
        .await?
    {
        Completion::Done => Ok(None),
        // Without outputs nothing is submitted, so nothing can be pending.
        Completion::Pending(delivery, _) => ack_delivery(delivery, &pipeline.instruments)
            .await
            .map(|()| None),
        Completion::Committing(committed) => Ok(Some(await_commit(committed, pipeline))),
        Completion::Encode(_, error) | Completion::Rejected(_, error) => Err(error),
    }
}

async fn handle<M, O>(input: M::Item, pipeline: &Pipeline<M, O>) -> Handled<M::Item, O>
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    // Pre-handler hooks transform the handler input or intercept the delivery;
    // `input` stays as decoded for post-handler hooks and dead letters.
    let mut flow = Flow::Continue(input.clone());
    for middleware in &pipeline.middleware {
        let Flow::Continue(value) = flow else { break };
        flow = match middleware.pre_handler(value).await {
            Ok(next) => next,
            Err(HandlerError::Reject(error)) => {
                return Ok(Err(Failure {
                    kind: FailureKind::Rejected,
                    error: error.context("rejected before the handler"),
                    attempts: 0,
                    input: Some(input),
                }));
            }
            Err(HandlerError::Retry(error) | HandlerError::Fatal(error)) => {
                return Err(error.context("pre-handler middleware failed"));
            }
        };
    }
    let handler_input = match flow {
        Flow::Continue(value) => value,
        Flow::Intercept(values) => return finish(values.values(), input, 0, pipeline).await,
    };
    let policy = &pipeline.handler_retry;
    let mut attempts = 0;
    let outputs = loop {
        attempts += 1;
        let started = Instant::now();
        let result = (pipeline.handler)(handler_input.clone())
            .instrument(info_span!("handler", attempt = attempts))
            .await;
        pipeline.instruments.record(Stage::Handler, started);
        let (kind, error) = match result {
            Ok(values) => break values.values(),
            Err(HandlerError::Retry(error)) if attempts >= policy.max_attempts => {
                (FailureKind::RetryExhausted, error)
            }
            Err(HandlerError::Retry(error)) => {
                pipeline.instruments.handler_retries.increment(1);
                debug!(
                    attempt = attempts,
                    error = chain(error.as_ref()),
                    "retrying handler"
                );
                tokio::time::sleep(policy.delay(attempts)).await;
                continue;
            }
            Err(HandlerError::Reject(error)) => (FailureKind::Rejected, error),
            Err(HandlerError::Fatal(error)) => return Err(error.context("fatal handler error")),
        };
        return Ok(Err(Failure {
            kind,
            error,
            attempts,
            input: Some(input),
        }));
    };
    finish(outputs, input, attempts, pipeline).await
}

/// Runs post-handler hooks over every output.
async fn finish<M, O>(
    outputs: Vec<O>,
    input: M::Item,
    attempts: usize,
    pipeline: &Pipeline<M, O>,
) -> Handled<M::Item, O>
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    // Resolve every output before publishing any; middleware errors never rerun the handler.
    let mut mapped = Vec::with_capacity(outputs.len());
    for output in outputs {
        match post_handlers(output, &input, pipeline).await {
            Ok(output) => mapped.push(output),
            Err(HandlerError::Reject(error)) => {
                return Ok(Err(Failure {
                    kind: FailureKind::Rejected,
                    error: error.context("rejected after the handler"),
                    attempts,
                    input: Some(input),
                }));
            }
            Err(HandlerError::Retry(error) | HandlerError::Fatal(error)) => {
                return Err(error.context("post-handler middleware failed"));
            }
        }
    }
    Ok(Ok(Outputs {
        values: mapped,
        input,
        attempts,
    }))
}

/// Passes one output through every middleware's post-handler hook in registration order.
async fn post_handlers<M, O>(
    mut output: O,
    input: &M::Item,
    pipeline: &Pipeline<M, O>,
) -> crate::handler::Result<O>
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    for middleware in &pipeline.middleware {
        output = middleware.post_handler(input, output).await?;
    }
    Ok(output)
}

/// Routes a failure; returns the acknowledgement still waiting for a
/// transaction to commit, if any.
async fn route<M, O>(
    delivery: M,
    pipeline: Arc<Pipeline<M, O>>,
    failure: Failure<M::Item>,
) -> Result<Option<PendingAck>, BoxError>
where
    M: SourceMessage,
    O: Send + Sync + 'static,
{
    let Failure {
        kind,
        error,
        attempts,
        input,
    } = failure;
    let instruments = &pipeline.instruments;
    instruments.failure(kind).increment(1);
    match pipeline.error_policy.action(kind) {
        FailureAction::Stop => Err(error.context(kind.to_string())),
        FailureAction::Discard => {
            warn!(
                failure = %kind,
                attempts,
                error = chain(error.as_ref()),
                "discarding delivery"
            );
            acknowledge(delivery, pipeline).await
        }
        FailureAction::DeadLetter => {
            let Some(dlq) = &pipeline.dlq else {
                return Err(error
                    .context(kind.to_string())
                    .context("no dead-letter sink configured"));
            };
            let dead_letter = DeadLetter::new(
                pipeline.name.clone(),
                kind,
                &error,
                attempts,
                input,
                delivery.raw(),
            );
            let started = Instant::now();
            dlq(
                dead_letter,
                pipeline.dead_letter_retry.clone(),
                instruments.dead_letter_publish_failures.clone(),
            )
            .instrument(info_span!("dead_letter"))
            .await
            .map_err(|dlq_error| dlq_error.context(format!("{kind}: {error:#}")))?;
            instruments.record(Stage::DeadLetter, started);
            warn!(
                failure = %kind,
                attempts,
                error = chain(error.as_ref()),
                "dead-lettered delivery"
            );
            acknowledge(delivery, pipeline).await
        }
    }
}

/// Publishes with retries. With `health`, the delivery counts as retrying its
/// publication from the first failure until it succeeds or gives up. A rejection
/// is returned without retrying.
pub(super) async fn retry_publish<T, F, Fut>(
    policy: &RetryPolicy,
    failures: &Counter,
    health: Option<&Tracker>,
    mut publish: F,
) -> Result<T, BoxError>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, BoxError>>,
{
    let mut retrying = None;
    let mut attempt = 1;
    loop {
        let result = publish().await;
        if result.is_err() {
            failures.increment(1);
        }
        match result {
            Ok(value) => return Ok(value),
            Err(error) if PublishRejected::is(error.as_ref()) => return Err(error),
            Err(error) if attempt >= policy.max_attempts => {
                return Err(error.context("publish retry exhausted"));
            }
            Err(error) => {
                debug!(attempt, error = chain(error.as_ref()), "retrying publish");
                if retrying.is_none() {
                    retrying = health.map(Tracker::publish_retry);
                }
                tokio::time::sleep(policy.delay(attempt)).await;
                attempt += 1;
            }
        }
    }
}