Skip to main content

puerto_sqlx/eventos/
dead_letters.rs

1use async_trait::async_trait;
2use puerto_nucleo::eventos::transporte::{DestinoDescartados, ErrorTransporte, RegistroDescartado};
3use sqlx::PgPool;
4use uuid::Uuid;
5
6use super::unavailable;
7
8/// `descartados`, whatever the transport. Recording the same event for the same consumer twice
9/// keeps the first record (`descartados_evento_consumidor`).
10pub struct DescartadosPostgres {
11    pool: PgPool,
12}
13
14impl DescartadosPostgres {
15    pub fn new(pool: PgPool) -> Self {
16        Self { pool }
17    }
18}
19
20#[async_trait]
21impl DestinoDescartados for DescartadosPostgres {
22    async fn registrar(&self, registrar: &RegistroDescartado) -> Result<(), ErrorTransporte> {
23        let attempts = i32::try_from(registrar.intentos).unwrap_or(i32::MAX);
24        sqlx::query(
25            "INSERT INTO descartados \
26             (id, id_evento, consumidor, tipo_evento, intentos, motivo, detalle, payload) \
27             VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \
28             ON CONFLICT (id_evento, consumidor) DO NOTHING",
29        )
30        .bind(Uuid::now_v7())
31        .bind(registrar.id_evento)
32        .bind(&registrar.consumidor)
33        .bind(&registrar.tipo_evento)
34        .bind(attempts)
35        .bind(&registrar.motivo)
36        .bind(&registrar.detalle)
37        .bind(&registrar.payload)
38        .execute(&self.pool)
39        .await
40        .map_err(unavailable("descartados: registrar"))?;
41        tracing::warn!(
42            consumer = %registrar.consumidor,
43            event_id = ?registrar.id_evento,
44            reason = %registrar.motivo,
45            "descartados: registrado"
46        );
47        Ok(())
48    }
49}