backbone_outbox/relay.rs
1//! The relay: drain unpublished outbox rows onto the bus, at-least-once.
2
3use chrono::{DateTime, Utc};
4use sqlx::PgPool;
5use uuid::Uuid;
6
7use crate::error::{validate_schema, OutboxError, Result};
8use crate::record::OutboxRecord;
9
10#[derive(sqlx::FromRow)]
11struct OutboxRow {
12 id: Uuid,
13 event_type: String,
14 aggregate_type: String,
15 aggregate_id: String,
16 company_id: Uuid,
17 payload: serde_json::Value,
18 occurred_at: DateTime<Utc>,
19 correlation_id: Option<String>,
20 causation_id: Option<String>,
21 version: i32,
22}
23impl OutboxRow {
24 fn into_record(self) -> OutboxRecord {
25 OutboxRecord {
26 id: self.id,
27 event_type: self.event_type,
28 aggregate_type: self.aggregate_type,
29 aggregate_id: self.aggregate_id,
30 company_id: self.company_id,
31 payload: self.payload,
32 occurred_at: self.occurred_at,
33 correlation_id: self.correlation_id,
34 causation_id: self.causation_id,
35 version: self.version,
36 }
37 }
38}
39
40/// Drain up to `batch` un-published events from `schema.outbox_events`, hand each to `publish`, and mark
41/// the successfully-published ones. Returns the number published this pass.
42///
43/// **The relay never holds a transaction across `publish`.** The batch is read with a short-lived
44/// connection that is returned before any `publish` runs; each record is then published while holding
45/// *no* relay connection, and marked with an idempotent per-row UPDATE (`… WHERE id=$1 AND published_at
46/// IS NULL`). This is deliberate: the shipped consumers reborrow the *same* pool inside `publish` (their
47/// own tx), so a relay that held its connection + the outbox row locks across `publish` would need two
48/// pool connections per in-flight event and self-deadlock on a bounded pool (maturity council
49/// 2026-07-07). By not spanning `publish`, each DB step borrows and returns a connection independently —
50/// safe even at `max_connections = 1`.
51///
52/// **At-least-once**: `published_at` is set only after `publish` returns `Ok`; a crash between publish
53/// and mark redelivers the row (the consumer's inbox dedups it). Concurrent relay workers are not row-
54/// locked, so they may double-*deliver* a row — harmless (the inbox makes the *effect* exactly-once);
55/// a lease-based claim to trim duplicate deliveries is a future optimization. A `publish` error leaves
56/// the row for the next pass.
57pub async fn drain_once<F, Fut>(pool: &PgPool, schema: &str, batch: i64, publish: F) -> Result<usize>
58where
59 F: Fn(OutboxRecord) -> Fut,
60 Fut: std::future::Future<Output = std::result::Result<(), OutboxError>>,
61{
62 validate_schema(schema)?;
63 // Short-lived read: borrows a connection only for the SELECT, then returns it to the pool.
64 let rows: Vec<OutboxRow> = sqlx::query_as(&format!(
65 r#"SELECT id, event_type, aggregate_type, aggregate_id, company_id, payload, occurred_at,
66 correlation_id, causation_id, version
67 FROM {schema}.outbox_events
68 WHERE published_at IS NULL AND failed_at IS NULL
69 ORDER BY occurred_at, id
70 LIMIT $1"#
71 ))
72 .bind(batch)
73 .fetch_all(pool)
74 .await?;
75
76 let mut published = 0usize;
77 // Publish failures leave their rows for the next pass. Count them, and say so once per pass:
78 // a transport that refuses everything must be visible, without a line per record per second.
79 let mut refused = 0usize;
80 let mut first_refusal: Option<String> = None;
81 for row in rows {
82 let rec = row.into_record();
83 let id = rec.id;
84 match publish(rec).await {
85 // No relay connection is held here — the consumer may freely reborrow the pool.
86 Ok(()) => {
87 sqlx::query(&format!(
88 "UPDATE {schema}.outbox_events SET published_at=now() WHERE id=$1 AND published_at IS NULL"
89 ))
90 .bind(id)
91 .execute(pool)
92 .await?;
93 published += 1;
94 }
95 // Leave the row un-published; the next pass retries it.
96 Err(OutboxError::Publish(reason)) => {
97 refused += 1;
98 first_refusal.get_or_insert(reason);
99 }
100 // The transport gave up on this record. Marking it published would report a delivery
101 // that never happened and erase the only trace that work was dropped; leaving it pending
102 // would re-hand the same doomed record on every pass forever. Mark it dead instead:
103 // visible in the table, excluded from the drain, and re-emittable once the cause is fixed.
104 Err(OutboxError::Exhausted(reason)) => {
105 sqlx::query(&format!(
106 "UPDATE {schema}.outbox_events SET failed_at=now(), failure_reason=$2
107 WHERE id=$1 AND published_at IS NULL"
108 ))
109 .bind(id)
110 .bind(&reason)
111 .execute(pool)
112 .await?;
113 }
114 Err(e) => return Err(e),
115 }
116 }
117 if refused > 0 {
118 tracing::warn!(
119 schema,
120 refused,
121 reason = first_refusal.as_deref().unwrap_or_default(),
122 "outbox relay: the transport refused records this pass; they stay pending and retry"
123 );
124 }
125 Ok(published)
126}
127
128/// A record the transport gave up on, as an operator sees it.
129#[derive(Debug, Clone, sqlx::FromRow)]
130pub struct DeadRecord {
131 /// The outbox row id — pass it to [`reemit`].
132 pub id: Uuid,
133 /// The event that was never delivered.
134 pub event_type: String,
135 /// What it was about.
136 pub aggregate_type: String,
137 /// Which one.
138 pub aggregate_id: String,
139 /// When the transport gave up.
140 pub failed_at: DateTime<Utc>,
141 /// Why, as the transport reported it.
142 pub failure_reason: Option<String>,
143}
144
145/// List the records the transport gave up on, oldest first.
146///
147/// These are cross-module effects that did not happen. Nothing retries them on its own — that is the
148/// point of a dead letter — so an operator reads this, fixes the cause, and calls [`reemit`].
149pub async fn list_dead(pool: &PgPool, schema: &str, limit: i64) -> Result<Vec<DeadRecord>> {
150 validate_schema(schema)?;
151 let rows = sqlx::query_as::<_, DeadRecord>(&format!(
152 r#"SELECT id, event_type, aggregate_type, aggregate_id, failed_at, failure_reason
153 FROM {schema}.outbox_events
154 WHERE failed_at IS NOT NULL
155 ORDER BY failed_at, id
156 LIMIT $1"#
157 ))
158 .bind(limit)
159 .fetch_all(pool)
160 .await?;
161 Ok(rows)
162}
163
164/// Hand a dead record back to the relay. Returns whether a row was revived.
165///
166/// Clears the dead mark so the next drain offers the record to the transport again. Deliberately
167/// manual: an event is dead because delivery kept failing, and re-emitting before the cause is fixed
168/// just re-kills it. A row that was published in the meantime is left alone.
169pub async fn reemit(pool: &PgPool, schema: &str, id: Uuid) -> Result<bool> {
170 validate_schema(schema)?;
171 let done = sqlx::query(&format!(
172 "UPDATE {schema}.outbox_events SET failed_at=NULL, failure_reason=NULL
173 WHERE id=$1 AND failed_at IS NOT NULL AND published_at IS NULL"
174 ))
175 .bind(id)
176 .execute(pool)
177 .await?;
178 Ok(done.rows_affected() == 1)
179}
180
181/// Hand every dead record back to the relay. Returns how many were revived.
182///
183/// For the case where one shared cause killed a batch — the consumer was misconfigured, a downstream
184/// service was down — and the fix clears all of them at once.
185pub async fn reemit_all(pool: &PgPool, schema: &str) -> Result<u64> {
186 validate_schema(schema)?;
187 let done = sqlx::query(&format!(
188 "UPDATE {schema}.outbox_events SET failed_at=NULL, failure_reason=NULL
189 WHERE failed_at IS NOT NULL AND published_at IS NULL"
190 ))
191 .execute(pool)
192 .await?;
193 Ok(done.rows_affected())
194}
195
196/// Drain repeatedly until the outbox is empty (bounded by `max_passes`). Convenience for tests and
197/// one-shot flushes; a production relay loops `drain_once` on a `backbone-jobs` schedule instead.
198pub async fn drain_all<F, Fut>(
199 pool: &PgPool,
200 schema: &str,
201 batch: i64,
202 max_passes: usize,
203 publish: F,
204) -> Result<usize>
205where
206 F: Fn(OutboxRecord) -> Fut,
207 Fut: std::future::Future<Output = std::result::Result<(), OutboxError>>,
208{
209 let mut total = 0;
210 for _ in 0..max_passes {
211 let n = drain_once(pool, schema, batch, &publish).await?;
212 total += n;
213 if n == 0 {
214 break;
215 }
216 }
217 Ok(total)
218}