puerto_sqlx/eventos/
outbox.rs1use async_trait::async_trait;
2use puerto_nucleo::SobreEvento;
3use puerto_nucleo::eventos::transporte::{ErrorTransporte, Outbox};
4use sqlx::{PgConnection, PgPool};
5use tokio::sync::Mutex;
6use uuid::Uuid;
7
8use super::{ENVELOPE_COLUMNS, envelope_from_pg, unavailable};
9
10pub const CLAVE_BLOQUEO_RELAY: i64 = 0x7075_6572_746f;
13
14pub struct OutboxPostgres {
16 pool: PgPool,
17 lock_key: i64,
18 leader: Mutex<Option<PgConnection>>,
21}
22
23impl OutboxPostgres {
24 pub fn new(pool: PgPool) -> Self {
25 Self {
26 pool,
27 lock_key: CLAVE_BLOQUEO_RELAY,
28 leader: Mutex::new(None),
29 }
30 }
31
32 pub fn con_clave_bloqueo(mut self, key: i64) -> Self {
34 self.lock_key = key;
35 self
36 }
37}
38
39#[async_trait]
40impl Outbox for OutboxPostgres {
41 async fn intentar_liderar(&self) -> Result<bool, ErrorTransporte> {
42 let mut leader = self.leader.lock().await;
43 if let Some(conn) = leader.as_mut() {
44 if sqlx::query("SELECT 1").execute(&mut *conn).await.is_ok() {
45 return Ok(true);
46 }
47 tracing::warn!("outbox: se perdió la conexión del bloqueo del relay");
49 *leader = None;
50 }
51 let mut conn = self
52 .pool
53 .acquire()
54 .await
55 .map_err(unavailable("outbox: intentar_liderar"))?
56 .detach();
57 let leads: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
58 .bind(self.lock_key)
59 .fetch_one(&mut conn)
60 .await
61 .map_err(unavailable("outbox: intentar_liderar"))?;
62 if leads {
63 tracing::info!("outbox: este worker hace el relay");
64 *leader = Some(conn);
65 }
66 Ok(leads)
67 }
68
69 async fn buscar_sin_publicar(&self, limit: u32) -> Result<Vec<SobreEvento>, ErrorTransporte> {
70 let rows = sqlx::query(&format!(
71 "SELECT {ENVELOPE_COLUMNS} FROM outbox o \
72 WHERE o.publicado_en IS NULL ORDER BY o.secuencia LIMIT $1"
73 ))
74 .bind(i64::from(limit))
75 .fetch_all(&self.pool)
76 .await
77 .map_err(unavailable("outbox: buscar_sin_publicar"))?;
78 rows.iter()
79 .map(|row| envelope_from_pg(row, "outbox: buscar_sin_publicar"))
80 .collect()
81 }
82
83 async fn marcar_publicados(&self, ids: &[Uuid]) -> Result<(), ErrorTransporte> {
84 sqlx::query(
85 "UPDATE outbox SET publicado_en = now() \
86 WHERE id = ANY($1) AND publicado_en IS NULL",
87 )
88 .bind(ids)
89 .execute(&self.pool)
90 .await
91 .map_err(unavailable("outbox: marcar_publicados"))?;
92 Ok(())
93 }
94}