puerto-eventos 0.21.0

Puerto runtime — the worker every Puerto project with domain events runs: the outbox relay, the consume loops and their delivery policy, health probes and graceful shutdown.
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
//! A consume loop: hands each delivery of one subscription to its handler and settles it with the
//! delivery policy (ADR-0018 § 4, § 6).

use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use puerto_nucleo::eventos::entrega::{
    ENTREGAS_MAXIMAS_POR_DEFECTO, Entrega, decidir, espera_para,
};
use puerto_nucleo::eventos::transporte::{
    DestinoDescartados, ErrorTransporte, RegistroDescartado, Reservado, SuscripcionEventos,
};
use puerto_nucleo::eventos::{ManejadorEvento, ResultadoManejo};

use crate::conductor::{Pasada, Progreso};

/// How many deliveries one pass claims when nothing else is configured.
pub const TAMANO_LOTE_CONSUMIDOR_POR_DEFECTO: u32 = 10;

/// One `[[consumidor]]`: its subscription, its handler and where its dead letters go.
pub struct Consumidor<S> {
    suscripcion: S,
    tamano_lote: u32,
    policy: Policy,
}

/// Everything but the subscription, which is only `Send`: what a delivery needs while it waits
/// on the handler and the sink.
struct Policy {
    handler: Arc<dyn ManejadorEvento>,
    dead_letters: Arc<dyn DestinoDescartados>,
    max_deliveries: u32,
    espera_maxima_reintento: Option<Duration>,
}

impl<S: SuscripcionEventos> Consumidor<S> {
    pub fn new(
        suscripcion: S,
        handler: impl ManejadorEvento + 'static,
        dead_letters: Arc<dyn DestinoDescartados>,
    ) -> Self {
        Self {
            tamano_lote: TAMANO_LOTE_CONSUMIDOR_POR_DEFECTO
                .min(suscripcion.lote_maximo())
                .max(1),
            suscripcion,
            policy: Policy {
                handler: Arc::new(handler),
                dead_letters,
                max_deliveries: ENTREGAS_MAXIMAS_POR_DEFECTO,
                espera_maxima_reintento: None,
            },
        }
    }

    /// Never more than the subscription hands out per batch (`lote_maximo`).
    pub fn con_tamano_lote(mut self, tamano_lote: u32) -> Self {
        self.tamano_lote = tamano_lote.max(1).min(self.suscripcion.lote_maximo());
        self
    }

    /// How many deliveries an event gets before it is dead-lettered.
    pub fn con_entregas_maximas(mut self, max_deliveries: u32) -> Self {
        self.policy.max_deliveries = max_deliveries.max(1);
        self
    }

    /// Caps the policy's backoff between redeliveries — `Some(Duration::ZERO)` retries at the
    /// next pass. For tests and development; production keeps the policy's.
    pub fn con_espera_maxima_reintento(
        mut self,
        espera_maxima_reintento: Option<Duration>,
    ) -> Self {
        self.policy.espera_maxima_reintento = espera_maxima_reintento;
        self
    }

    /// One batch. A claim left unsettled (the pass failed before it) is delivered again once its
    /// lease runs out: at-least-once, never lost.
    pub async fn consumir_una_vez(&mut self) -> Result<Progreso, ErrorTransporte> {
        let batch = self.suscripcion.siguiente_lote(self.tamano_lote).await?;
        let full = batch.len() as u64 >= u64::from(self.tamano_lote);
        let consumidor = self.suscripcion.consumidor().to_string();
        for claimed in &batch {
            let delivery = self.policy.deliver(&consumidor, claimed).await;
            self.suscripcion.resolver(claimed, &delivery).await?;
        }
        Ok(if full { Progreso::More } else { Progreso::Idle })
    }
}

impl Policy {
    /// What to settle `claimed` with. A dead letter is recorded before it is answered; when it
    /// cannot be, the delivery is retried instead, so nothing is retired without one.
    async fn deliver(&self, consumidor: &str, claimed: &Reservado) -> Entrega {
        let event = &claimed.sobre;
        let outcome = self.handle(consumidor, claimed).await;
        match decidir(outcome, claimed.intento, self.max_deliveries) {
            Entrega::Ack => Entrega::Ack,
            Entrega::Reintentar { espera } => {
                tracing::warn!(consumidor, event_id = %event.id, attempt = claimed.intento, "consumidor: reintento");
                Entrega::Reintentar {
                    espera: self.cap(espera),
                }
            }
            Entrega::Descartar { motivo, detalle } => {
                let record = RegistroDescartado::para_evento(
                    consumidor,
                    event,
                    claimed.intento,
                    motivo,
                    detalle.clone(),
                );
                match self.dead_letters.registrar(&record).await {
                    Ok(()) => Entrega::Descartar { motivo, detalle },
                    Err(err) => {
                        tracing::error!(consumidor, event_id = %event.id, error = %err, "consumidor: el descartado no se registró, se reintenta");
                        Entrega::Reintentar {
                            espera: self.cap(espera_para(claimed.intento)),
                        }
                    }
                }
            }
        }
    }

    /// The handler's answer. It runs on its own task, so a panic is caught: it is a failure that
    /// may pass (`Retry`), and the loop goes on.
    async fn handle(&self, consumidor: &str, claimed: &Reservado) -> ResultadoManejo {
        let handler = Arc::clone(&self.handler);
        let event = claimed.sobre.clone();
        match tokio::spawn(async move { handler.manejar(&event).await }).await {
            Ok(outcome) => outcome,
            Err(err) => {
                tracing::error!(
                    consumidor,
                    event_id = %claimed.sobre.id,
                    error = %err,
                    "consumidor: el manejador entró en pánico"
                );
                ResultadoManejo::Reintentar
            }
        }
    }

    fn cap(&self, delay: Duration) -> Duration {
        self.espera_maxima_reintento
            .map_or(delay, |max| delay.min(max))
    }
}

#[async_trait]
impl<S: SuscripcionEventos + 'static> Pasada for Consumidor<S> {
    fn name(&self) -> String {
        format!("consumidor {}", self.suscripcion.consumidor())
    }

    async fn pass(&mut self) -> Result<Progreso, ErrorTransporte> {
        self.consumir_una_vez().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pruebas::{DestinoFalso, Guion, SuscripcionFalsa, envelope};
    use puerto_nucleo::eventos::{MOTIVO_ENTREGAS_MAXIMAS_SUPERADAS, MOTIVO_PAYLOAD_INVALIDO};

    fn consumidor(
        due: Vec<Reservado>,
        handler: Guion,
        sink: &DestinoFalso,
    ) -> (Consumidor<SuscripcionFalsa>, SuscripcionFalsa) {
        let suscripcion = SuscripcionFalsa::with(due);
        let consumidor = Consumidor::new(suscripcion.clone(), handler, Arc::new(sink.clone()));
        (consumidor, suscripcion)
    }

    #[tokio::test]
    async fn should_settle_ack_when_the_handler_acks() {
        // Arrange
        let claimed = Reservado::new(envelope("product_created"), 1);
        let sink = DestinoFalso::default();
        let (mut consumidor, suscripcion) = consumidor(vec![claimed.clone()], Guion::Ack, &sink);

        // Act
        let result = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(result, Ok(Progreso::Idle));
        assert_eq!(
            suscripcion.resueltos(),
            vec![(claimed.sobre.id, Entrega::Ack)]
        );
        assert!(sink.registros().is_empty());
    }

    #[tokio::test]
    async fn should_settle_a_retry_with_the_backoff_when_below_the_cap() {
        // Arrange
        let claimed = Reservado::new(envelope("product_created"), 2);
        let sink = DestinoFalso::default();
        let (mut consumidor, suscripcion) = consumidor(vec![claimed.clone()], Guion::Retry, &sink);

        // Act
        let _ = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(
            suscripcion.resueltos(),
            vec![(
                claimed.sobre.id,
                Entrega::Reintentar {
                    espera: Duration::from_secs(5)
                }
            )]
        );
        assert!(sink.registros().is_empty());
    }

    #[tokio::test]
    async fn should_dead_letter_when_the_retry_reaches_the_cap() {
        // Arrange
        let claimed = Reservado::new(envelope("product_created"), 5);
        let sink = DestinoFalso::default();
        let (mut consumidor, suscripcion) = consumidor(vec![claimed.clone()], Guion::Retry, &sink);

        // Act
        let _ = consumidor.consumir_una_vez().await;

        // Assert
        let registros = sink.registros();
        assert_eq!(registros.len(), 1);
        assert_eq!(registros[0].id_evento, Some(claimed.sobre.id));
        assert_eq!(registros[0].consumidor, "notify_new_product");
        assert_eq!(registros[0].intentos, 5);
        assert_eq!(registros[0].motivo, MOTIVO_ENTREGAS_MAXIMAS_SUPERADAS);
        assert!(matches!(
            suscripcion.resueltos()[0].1,
            Entrega::Descartar {
                motivo: MOTIVO_ENTREGAS_MAXIMAS_SUPERADAS,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn should_record_the_dead_letter_before_settling_when_the_handler_gives_up() {
        // Arrange
        let claimed = Reservado::new(envelope("product_created"), 1);
        let sink = DestinoFalso::default();
        let suscripcion = SuscripcionFalsa::with(vec![claimed.clone()]).observando(&sink);
        let mut consumidor =
            Consumidor::new(suscripcion.clone(), Guion::DecodeAs, Arc::new(sink.clone()));

        // Act
        let _ = consumidor.consumir_una_vez().await;

        // Assert — the payload is not a number: the handler dead-letters it as invalid
        let registros = sink.registros();
        assert_eq!(registros.len(), 1);
        assert_eq!(registros[0].motivo, MOTIVO_PAYLOAD_INVALIDO);
        assert_eq!(
            suscripcion.descartados_vistos_al_resolver(),
            vec![1],
            "the dead letter was not recorded before the claim was settled"
        );
        assert!(matches!(
            suscripcion.resueltos()[0].1,
            Entrega::Descartar {
                motivo: MOTIVO_PAYLOAD_INVALIDO,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn should_retry_instead_of_retiring_when_the_dead_letter_cannot_be_recorded() {
        // Arrange
        let claimed = Reservado::new(envelope("product_created"), 5);
        let sink = DestinoFalso::fallando();
        let (mut consumidor, suscripcion) = consumidor(vec![claimed.clone()], Guion::Retry, &sink);

        // Act
        let _ = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(
            suscripcion.resueltos(),
            vec![(
                claimed.sobre.id,
                Entrega::Reintentar {
                    espera: Duration::from_secs(300)
                }
            )]
        );
    }

    #[tokio::test]
    async fn should_treat_a_panic_as_a_retry_and_go_on_when_the_handler_panics() {
        // Arrange
        let first = Reservado::new(envelope("product_created"), 1);
        let second = Reservado::new(envelope("product_created"), 1);
        let sink = DestinoFalso::default();
        let (mut consumidor, suscripcion) = consumidor(
            vec![first.clone(), second.clone()],
            Guion::PanicOnce(Default::default()),
            &sink,
        );

        // Act
        let result = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(result, Ok(Progreso::Idle));
        assert_eq!(
            suscripcion.resueltos(),
            vec![
                (
                    first.sobre.id,
                    Entrega::Reintentar {
                        espera: Duration::from_secs(1)
                    }
                ),
                (second.sobre.id, Entrega::Ack),
            ]
        );
    }

    #[tokio::test]
    async fn should_cap_the_retry_delay_when_a_maximum_is_configured() {
        // Arrange
        let claimed = Reservado::new(envelope("product_created"), 4);
        let sink = DestinoFalso::default();
        let (consumidor, suscripcion) = consumidor(vec![claimed.clone()], Guion::Retry, &sink);
        let mut consumidor =
            consumidor.con_espera_maxima_reintento(Some(Duration::from_millis(10)));

        // Act
        let _ = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(
            suscripcion.resueltos()[0].1,
            Entrega::Reintentar {
                espera: Duration::from_millis(10)
            }
        );
    }

    #[tokio::test]
    async fn should_dead_letter_earlier_when_fewer_deliveries_are_configured() {
        // Arrange
        let claimed = Reservado::new(envelope("product_created"), 2);
        let sink = DestinoFalso::default();
        let (consumidor, _) = consumidor(vec![claimed], Guion::Retry, &sink);
        let mut consumidor = consumidor.con_entregas_maximas(2);

        // Act
        let _ = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(sink.registros().len(), 1);
    }

    #[tokio::test]
    async fn should_ask_for_more_at_once_when_the_batch_was_full() {
        // Arrange
        let due = (0..3)
            .map(|_| Reservado::new(envelope("product_created"), 1))
            .collect();
        let sink = DestinoFalso::default();
        let (consumidor, suscripcion) = consumidor(due, Guion::Ack, &sink);
        let mut consumidor = consumidor.con_tamano_lote(2);

        // Act
        let first = consumidor.consumir_una_vez().await;
        let second = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!((first, second), (Ok(Progreso::More), Ok(Progreso::Idle)));
        assert_eq!(suscripcion.resueltos().len(), 3);
    }

    #[tokio::test]
    async fn should_ask_for_more_at_once_when_the_subscription_hands_out_one_claim_at_a_time() {
        // Arrange
        let due = (0..3)
            .map(|_| Reservado::new(envelope("product_created"), 1))
            .collect();
        let sink = DestinoFalso::default();
        let suscripcion = SuscripcionFalsa::with(due).de_uno_en_uno();
        let mut consumidor =
            Consumidor::new(suscripcion.clone(), Guion::Ack, Arc::new(sink.clone()));

        // Act
        let first = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(first, Ok(Progreso::More));
        assert_eq!(suscripcion.resueltos().len(), 1);
    }

    #[test]
    fn should_never_claim_more_than_the_subscription_hands_out() {
        let consumidor = Consumidor::new(
            SuscripcionFalsa::with(vec![]).de_uno_en_uno(),
            Guion::Ack,
            Arc::new(DestinoFalso::default()),
        )
        .con_tamano_lote(50);
        assert_eq!(consumidor.tamano_lote, 1);
    }

    #[tokio::test]
    async fn should_stop_the_pass_when_a_claim_cannot_be_settled() {
        // Arrange
        let due = (0..2)
            .map(|_| Reservado::new(envelope("product_created"), 1))
            .collect();
        let sink = DestinoFalso::default();
        let suscripcion = SuscripcionFalsa::with(due).fallando_al_resolver();
        let mut consumidor =
            Consumidor::new(suscripcion.clone(), Guion::Ack, Arc::new(sink.clone()));

        // Act
        let result = consumidor.consumir_una_vez().await;

        // Assert
        assert_eq!(result, Err(ErrorTransporte::NoDisponible));
        assert_eq!(suscripcion.llamadas_resolver(), 1);
    }

    #[test]
    fn should_deliver_at_least_once_when_the_cap_is_zero() {
        let consumidor = Consumidor::new(
            SuscripcionFalsa::with(vec![]),
            Guion::Ack,
            Arc::new(DestinoFalso::default()),
        )
        .con_entregas_maximas(0)
        .con_tamano_lote(0);
        assert_eq!(
            (consumidor.policy.max_deliveries, consumidor.tamano_lote),
            (1, 1)
        );
    }
}