Skip to main content

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    for row in rows {
78        let rec = row.into_record();
79        let id = rec.id;
80        match publish(rec).await {
81            // No relay connection is held here — the consumer may freely reborrow the pool.
82            Ok(()) => {
83                sqlx::query(&format!(
84                    "UPDATE {schema}.outbox_events SET published_at=now() WHERE id=$1 AND published_at IS NULL"
85                ))
86                .bind(id)
87                .execute(pool)
88                .await?;
89                published += 1;
90            }
91            // Leave the row un-published; the next pass retries it.
92            Err(OutboxError::Publish(_)) => {}
93            // The transport gave up on this record. Marking it published would report a delivery
94            // that never happened and erase the only trace that work was dropped; leaving it pending
95            // would re-hand the same doomed record on every pass forever. Mark it dead instead:
96            // visible in the table, excluded from the drain, and re-emittable once the cause is fixed.
97            Err(OutboxError::Exhausted(reason)) => {
98                sqlx::query(&format!(
99                    "UPDATE {schema}.outbox_events SET failed_at=now(), failure_reason=$2
100                     WHERE id=$1 AND published_at IS NULL"
101                ))
102                .bind(id)
103                .bind(&reason)
104                .execute(pool)
105                .await?;
106            }
107            Err(e) => return Err(e),
108        }
109    }
110    Ok(published)
111}
112
113/// A record the transport gave up on, as an operator sees it.
114#[derive(Debug, Clone, sqlx::FromRow)]
115pub struct DeadRecord {
116    /// The outbox row id — pass it to [`reemit`].
117    pub id: Uuid,
118    /// The event that was never delivered.
119    pub event_type: String,
120    /// What it was about.
121    pub aggregate_type: String,
122    /// Which one.
123    pub aggregate_id: String,
124    /// When the transport gave up.
125    pub failed_at: DateTime<Utc>,
126    /// Why, as the transport reported it.
127    pub failure_reason: Option<String>,
128}
129
130/// List the records the transport gave up on, oldest first.
131///
132/// These are cross-module effects that did not happen. Nothing retries them on its own — that is the
133/// point of a dead letter — so an operator reads this, fixes the cause, and calls [`reemit`].
134pub async fn list_dead(pool: &PgPool, schema: &str, limit: i64) -> Result<Vec<DeadRecord>> {
135    validate_schema(schema)?;
136    let rows = sqlx::query_as::<_, DeadRecord>(&format!(
137        r#"SELECT id, event_type, aggregate_type, aggregate_id, failed_at, failure_reason
138           FROM {schema}.outbox_events
139           WHERE failed_at IS NOT NULL
140           ORDER BY failed_at, id
141           LIMIT $1"#
142    ))
143    .bind(limit)
144    .fetch_all(pool)
145    .await?;
146    Ok(rows)
147}
148
149/// Hand a dead record back to the relay. Returns whether a row was revived.
150///
151/// Clears the dead mark so the next drain offers the record to the transport again. Deliberately
152/// manual: an event is dead because delivery kept failing, and re-emitting before the cause is fixed
153/// just re-kills it. A row that was published in the meantime is left alone.
154pub async fn reemit(pool: &PgPool, schema: &str, id: Uuid) -> Result<bool> {
155    validate_schema(schema)?;
156    let done = sqlx::query(&format!(
157        "UPDATE {schema}.outbox_events SET failed_at=NULL, failure_reason=NULL
158         WHERE id=$1 AND failed_at IS NOT NULL AND published_at IS NULL"
159    ))
160    .bind(id)
161    .execute(pool)
162    .await?;
163    Ok(done.rows_affected() == 1)
164}
165
166/// Hand every dead record back to the relay. Returns how many were revived.
167///
168/// For the case where one shared cause killed a batch — the consumer was misconfigured, a downstream
169/// service was down — and the fix clears all of them at once.
170pub async fn reemit_all(pool: &PgPool, schema: &str) -> Result<u64> {
171    validate_schema(schema)?;
172    let done = sqlx::query(&format!(
173        "UPDATE {schema}.outbox_events SET failed_at=NULL, failure_reason=NULL
174         WHERE failed_at IS NOT NULL AND published_at IS NULL"
175    ))
176    .execute(pool)
177    .await?;
178    Ok(done.rows_affected())
179}
180
181/// Drain repeatedly until the outbox is empty (bounded by `max_passes`). Convenience for tests and
182/// one-shot flushes; a production relay loops `drain_once` on a `backbone-jobs` schedule instead.
183pub async fn drain_all<F, Fut>(
184    pool: &PgPool,
185    schema: &str,
186    batch: i64,
187    max_passes: usize,
188    publish: F,
189) -> Result<usize>
190where
191    F: Fn(OutboxRecord) -> Fut,
192    Fut: std::future::Future<Output = std::result::Result<(), OutboxError>>,
193{
194    let mut total = 0;
195    for _ in 0..max_passes {
196        let n = drain_once(pool, schema, batch, &publish).await?;
197        total += n;
198        if n == 0 {
199            break;
200        }
201    }
202    Ok(total)
203}