Skip to main content

puerto_sqlx/
correo.rs

1//! The sent-mail log (ADR-0020): which mails a worker consumer already sent for which event. Its
2//! table is [`crate::MIGRACION_CORREOS_ENVIADOS`], which the first `puerto generate correo --on` writes
3//! into the project.
4
5use async_trait::async_trait;
6use puerto_nucleo::ErrorRepositorio;
7use puerto_nucleo::correo::CorreosEnviados;
8use sqlx::PgPool;
9use uuid::Uuid;
10
11use crate::mapear_error_sqlx;
12
13/// `correos_enviados`. Marking the same mail for the same event twice keeps one row.
14pub struct CorreosEnviadosPostgres {
15    pool: PgPool,
16}
17
18impl CorreosEnviadosPostgres {
19    pub fn new(pool: PgPool) -> Self {
20        Self { pool }
21    }
22}
23
24#[async_trait]
25impl CorreosEnviados for CorreosEnviadosPostgres {
26    async fn fue_enviado(&self, event_id: Uuid, correo: &str) -> Result<bool, ErrorRepositorio> {
27        sqlx::query_scalar(
28            "SELECT EXISTS (SELECT 1 FROM correos_enviados WHERE id_evento = $1 AND correo = $2)",
29        )
30        .bind(event_id)
31        .bind(correo)
32        .fetch_one(&self.pool)
33        .await
34        .map_err(|err| {
35            tracing::error!(error = %err, %event_id, correo, "correos_enviados: falló la lectura");
36            mapear_error_sqlx(&err)
37        })
38    }
39
40    async fn marcar_enviado(&self, event_id: Uuid, correo: &str) -> Result<(), ErrorRepositorio> {
41        sqlx::query(
42            "INSERT INTO correos_enviados (id_evento, correo) VALUES ($1, $2) \
43             ON CONFLICT (id_evento, correo) DO NOTHING",
44        )
45        .bind(event_id)
46        .bind(correo)
47        .execute(&self.pool)
48        .await
49        .map(|_| ())
50        .map_err(|err| {
51            tracing::error!(error = %err, %event_id, correo, "correos_enviados: falló el marcado");
52            mapear_error_sqlx(&err)
53        })
54    }
55}