Skip to main content

a2a_protocol_server/push/outbox/
postgres.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`PushOutbox`] in PostgreSQL (feature `postgres`), shared by every replica
5//! that opens it.
6//!
7//! The clock is the database's (`now()`), so replicas whose clocks disagree
8//! agree on what is due and whose lease has run out (audit E-F16, E-F17). A
9//! claim is one `UPDATE` over a `FOR UPDATE SKIP LOCKED` selection: two
10//! replicas claiming at once take different rows, and neither waits for the
11//! other. A webhook's later row is not claimable while an earlier one exists,
12//! locked or not, so its events go out in order from whichever replica.
13//!
14//! Every statement runs under `store::pg_retry`: a claim and a record are
15//! `checked` (a second run could claim or record twice), the rest `retry`.
16
17use std::sync::Arc;
18use std::time::Duration;
19
20use a2a_protocol_types::error::A2aError;
21use sqlx::Row as _;
22use sqlx::postgres::PgPool;
23
24use super::body::{Body, context};
25use super::{ClaimedDelivery, Held, NewDelivery, OutboxFuture, PushOutbox};
26use crate::metrics::{Metrics, NoopMetrics};
27use crate::push::PushConfigCipher;
28use crate::store::pg_retry;
29
30mod record;
31use record::Reserve;
32
33const SCHEMA: [&str; 9] = [
34    "CREATE TABLE IF NOT EXISTS a2a_push_outbox (
35        seq         BIGSERIAL   PRIMARY KEY,
36        delivery_id TEXT        NOT NULL UNIQUE,
37        tenant      TEXT        NOT NULL,
38        caller      TEXT,
39        task_id     TEXT        NOT NULL,
40        config_id   TEXT        NOT NULL,
41        event       TEXT        NOT NULL,
42        ends_turn   BOOLEAN     NOT NULL,
43        attempts    INTEGER     NOT NULL DEFAULT 0,
44        recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
45        due_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
46        owner       TEXT,
47        lease_until TIMESTAMPTZ,
48        armed       BOOLEAN     NOT NULL DEFAULT TRUE,
49        reservation TEXT,
50        log_seq     BIGINT,
51        hold_until  TIMESTAMPTZ
52    )",
53    // A table an earlier build created has none of the two-phase columns
54    // (audit H14); rows it holds are armed.
55    "ALTER TABLE a2a_push_outbox ADD COLUMN IF NOT EXISTS armed BOOLEAN NOT NULL DEFAULT TRUE",
56    "ALTER TABLE a2a_push_outbox ADD COLUMN IF NOT EXISTS reservation TEXT",
57    "ALTER TABLE a2a_push_outbox ADD COLUMN IF NOT EXISTS log_seq BIGINT",
58    "ALTER TABLE a2a_push_outbox ADD COLUMN IF NOT EXISTS hold_until TIMESTAMPTZ",
59    "CREATE INDEX IF NOT EXISTS a2a_push_outbox_reservation
60        ON a2a_push_outbox (reservation) WHERE reservation IS NOT NULL",
61    // What `held` looks for, without reading a backlog of armed rows.
62    "CREATE INDEX IF NOT EXISTS a2a_push_outbox_unarmed
63        ON a2a_push_outbox (hold_until) WHERE NOT armed",
64    "CREATE INDEX IF NOT EXISTS a2a_push_outbox_webhook
65        ON a2a_push_outbox (tenant, caller, task_id, config_id, seq)",
66    "CREATE INDEX IF NOT EXISTS a2a_push_outbox_due ON a2a_push_outbox (due_at)",
67];
68
69/// A [`PushOutbox`] in a PostgreSQL database; see the module documentation.
70#[derive(Clone)]
71pub struct PostgresPushOutbox {
72    pub(super) pool: PgPool,
73    body: Body,
74    metrics: Arc<dyn Metrics>,
75}
76
77impl std::fmt::Debug for PostgresPushOutbox {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("PostgresPushOutbox")
80            .field("body", &self.body)
81            .finish_non_exhaustive()
82    }
83}
84
85fn to_a2a_error(e: &sqlx::Error) -> A2aError {
86    crate::sql_error::sql_error(crate::sql_error::Db::Postgres, "postgres push outbox", e)
87}
88
89const fn seconds(d: Duration) -> f64 {
90    d.as_secs_f64()
91}
92
93impl PostgresPushOutbox {
94    /// Opens a pool of [`DEFAULT_POOL_SIZE`](crate::store::DEFAULT_POOL_SIZE)
95    /// connections to `url`, with the task stores' options
96    /// (`store::pg_retry`), and creates the table under the crate's schema
97    /// lock.
98    ///
99    /// # Errors
100    ///
101    /// The database cannot be reached, or the table created.
102    pub async fn new(url: &str) -> Result<Self, sqlx::Error> {
103        // sqlx's default pool size, 10: `DEFAULT_POOL_SIZE`, as every store's.
104        let pool = pg_retry::pool_options().connect(url).await?;
105        Self::from_pool(pool).await
106    }
107
108    /// The outbox on `pool`, creating its table. The pool should have the
109    /// task stores' options (`pg_retry::pool_options`), as
110    /// [`new`](Self::new)'s does, or a ping before every statement.
111    ///
112    /// # Errors
113    ///
114    /// The table cannot be created.
115    pub async fn from_pool(pool: PgPool) -> Result<Self, sqlx::Error> {
116        crate::store::pg_schema::apply(&pool, &SCHEMA).await?;
117        Ok(Self {
118            pool,
119            body: Body::default(),
120            metrics: Arc::new(NoopMetrics),
121        })
122    }
123
124    /// Seals every event body with `cipher`; see
125    /// [`SqlitePushOutbox::with_cipher`](super::SqlitePushOutbox).
126    #[must_use]
127    pub fn with_cipher(mut self, cipher: Arc<dyn PushConfigCipher>) -> Self {
128        self.body = Body::with_cipher(cipher);
129        self
130    }
131
132    /// Reports a statement run again after a lost connection to `metrics`
133    /// (`Metrics::on_store_retry`).
134    #[must_use]
135    pub fn with_metrics(mut self, metrics: Arc<dyn Metrics>) -> Self {
136        self.metrics = metrics;
137        self
138    }
139
140    /// The reservations `rows` name, their events opened; one that does not open
141    /// is left in place and said so.
142    async fn read_held(&self, rows: &[sqlx::postgres::PgRow]) -> Vec<Held> {
143        let mut held = Vec::with_capacity(rows.len());
144        for row in rows {
145            let (tenant, caller, task_id, delivery_id): (String, Option<String>, String, String) = (
146                row.get("tenant"),
147                row.get("caller"),
148                row.get("task_id"),
149                row.get("delivery_id"),
150            );
151            let ctx = context(&tenant, caller.as_deref(), &task_id, &delivery_id);
152            let Ok(event) = self.body.decode(row.get::<&str, _>("event"), &ctx).await else {
153                trace_warn!(
154                    task_id = %task_id,
155                    "push outbox: a reserved row's event could not be read; it is left"
156                );
157                continue;
158            };
159            held.push(Held {
160                reservation: row.get("reservation"),
161                tenant,
162                caller,
163                task_id,
164                log_seq: u64::try_from(row.get::<i64, _>("log_seq")).unwrap_or(0),
165                event,
166            });
167        }
168        held
169    }
170
171    /// One claimed row, read; `None`, said so, for a row whose event does
172    /// not open.
173    async fn read(&self, row: &sqlx::postgres::PgRow) -> Option<ClaimedDelivery> {
174        let (tenant, caller, task_id, delivery_id): (String, Option<String>, String, String) = (
175            row.get("tenant"),
176            row.get("caller"),
177            row.get("task_id"),
178            row.get("delivery_id"),
179        );
180        let ctx = context(&tenant, caller.as_deref(), &task_id, &delivery_id);
181        // A body that does not open (moved from another row, or
182        // sealed under a key this store does not hold) is left
183        // leased and said so, rather than failing the claim: one bad
184        // row must not stop every other delivery.
185        let event = match self.body.decode(row.get::<&str, _>("event"), &ctx).await {
186            Ok(event) => event,
187            Err(_err) => {
188                trace_warn!(
189                    task_id = %task_id,
190                    error = %_err,
191                    "push outbox: a row's event could not be read; it is skipped"
192                );
193                return None;
194            }
195        };
196        Some(ClaimedDelivery {
197            seq: row.get("seq"),
198            attempts: u32::try_from(row.get::<i32, _>("attempts")).unwrap_or(0),
199            age: Duration::try_from_secs_f64(row.get::<f64, _>("age_secs")).unwrap_or_default(),
200            delivery: NewDelivery {
201                delivery_id,
202                tenant,
203                caller,
204                task_id,
205                config_id: row.get("config_id"),
206                event,
207                ends_turn: row.get("ends_turn"),
208            },
209        })
210    }
211}
212
213impl PostgresPushOutbox {
214    /// Records `deliveries` in one transaction, reserved when `reserve` is
215    /// given; how many were dropped for the bound.
216    async fn insert(
217        &self,
218        deliveries: Vec<NewDelivery>,
219        per_webhook: usize,
220        reserve: Option<Reserve<'_>>,
221    ) -> a2a_protocol_types::error::A2aResult<usize> {
222        let mut bodies = Vec::with_capacity(deliveries.len());
223        for d in &deliveries {
224            let ctx = context(&d.tenant, d.caller.as_deref(), &d.task_id, &d.delivery_id);
225            bodies.push(self.body.encode(&d.event, &ctx).await?);
226        }
227        pg_retry::checked(async {
228            let mut tx = self.pool.begin().await?;
229            let dropped =
230                Self::record_in(&mut tx, &deliveries, &bodies, per_webhook, reserve.as_ref())
231                    .await?;
232            tx.commit().await?;
233            Ok::<_, sqlx::Error>(dropped)
234        })
235        .await
236        .map_err(|e| to_a2a_error(&e))
237    }
238}
239
240impl PushOutbox for PostgresPushOutbox {
241    fn record(&self, deliveries: Vec<NewDelivery>, per_webhook: usize) -> OutboxFuture<'_, usize> {
242        Box::pin(self.insert(deliveries, per_webhook, None))
243    }
244
245    fn supports_reservations(&self) -> bool {
246        true
247    }
248
249    fn reserve<'a>(
250        &'a self,
251        reservation: &'a str,
252        log_seq: u64,
253        deliveries: Vec<NewDelivery>,
254        per_webhook: usize,
255        hold: Duration,
256    ) -> OutboxFuture<'a, usize> {
257        Box::pin(self.insert(
258            deliveries,
259            per_webhook,
260            Some(Reserve {
261                id: reservation,
262                log_seq: i64::try_from(log_seq).unwrap_or(i64::MAX),
263                hold_secs: seconds(hold),
264            }),
265        ))
266    }
267
268    fn arm<'a>(&'a self, reservation: &'a str) -> OutboxFuture<'a, usize> {
269        Box::pin(async move {
270            // Idempotent: a second run matches the same rows.
271            let armed = pg_retry::retry(self.metrics.as_ref(), || {
272                sqlx::query("UPDATE a2a_push_outbox SET armed = TRUE WHERE reservation = $1")
273                    .bind(reservation)
274                    .execute(&self.pool)
275            })
276            .await
277            .map_err(|e| to_a2a_error(&e))?
278            .rows_affected();
279            Ok(usize::try_from(armed).unwrap_or(usize::MAX))
280        })
281    }
282
283    fn extend_hold<'a>(&'a self, reservation: &'a str, hold: Duration) -> OutboxFuture<'a, usize> {
284        Box::pin(async move {
285            // Idempotent: a second run moves the same rows to a later time.
286            let extended = pg_retry::retry(self.metrics.as_ref(), || {
287                sqlx::query(
288                    "UPDATE a2a_push_outbox
289                     SET hold_until = now() + make_interval(secs => $2::float8)
290                     WHERE reservation = $1 AND NOT armed",
291                )
292                .bind(reservation)
293                .bind(seconds(hold))
294                .execute(&self.pool)
295            })
296            .await
297            .map_err(|e| to_a2a_error(&e))?
298            .rows_affected();
299            Ok(usize::try_from(extended).unwrap_or(usize::MAX))
300        })
301    }
302
303    fn release<'a>(&'a self, reservation: &'a str) -> OutboxFuture<'a, ()> {
304        Box::pin(async move {
305            pg_retry::retry(self.metrics.as_ref(), || {
306                sqlx::query("DELETE FROM a2a_push_outbox WHERE reservation = $1 AND NOT armed")
307                    .bind(reservation)
308                    .execute(&self.pool)
309            })
310            .await
311            .map_err(|e| to_a2a_error(&e))?;
312            Ok(())
313        })
314    }
315
316    fn held(&self, limit: usize) -> OutboxFuture<'_, Vec<Held>> {
317        Box::pin(async move {
318            let rows = pg_retry::retry(self.metrics.as_ref(), || {
319                sqlx::query(
320                    "SELECT delivery_id, tenant, caller, task_id, event, log_seq, reservation
321                     FROM a2a_push_outbox
322                     WHERE seq IN (
323                        SELECT MIN(seq) FROM a2a_push_outbox
324                        WHERE NOT armed AND hold_until <= now()
325                        GROUP BY reservation ORDER BY MIN(seq) LIMIT $1)
326                     ORDER BY seq",
327                )
328                .bind(i64::try_from(limit).unwrap_or(i64::MAX))
329                .fetch_all(&self.pool)
330            })
331            .await
332            .map_err(|e| to_a2a_error(&e))?;
333            Ok(self.read_held(&rows).await)
334        })
335    }
336
337    fn held_for_task<'a>(
338        &'a self,
339        tenant: &'a str,
340        caller: Option<&'a str>,
341        task_id: &'a str,
342    ) -> OutboxFuture<'a, Vec<Held>> {
343        Box::pin(async move {
344            let rows = pg_retry::retry(self.metrics.as_ref(), || {
345                sqlx::query(
346                    "SELECT delivery_id, tenant, caller, task_id, event, log_seq, reservation
347                     FROM a2a_push_outbox
348                     WHERE seq IN (
349                        SELECT MIN(seq) FROM a2a_push_outbox
350                        WHERE NOT armed AND tenant = $1
351                          AND caller IS NOT DISTINCT FROM $2 AND task_id = $3
352                        GROUP BY reservation)
353                     ORDER BY seq",
354                )
355                .bind(tenant)
356                .bind(caller)
357                .bind(task_id)
358                .fetch_all(&self.pool)
359            })
360            .await
361            .map_err(|e| to_a2a_error(&e))?;
362            Ok(self.read_held(&rows).await)
363        })
364    }
365
366    fn supports_renewal(&self) -> bool {
367        true
368    }
369
370    fn renew<'a>(&'a self, owner: &'a str, lease: Duration) -> OutboxFuture<'a, usize> {
371        Box::pin(async move {
372            // Idempotent: a second run sets the same end.
373            let renewed = pg_retry::retry(self.metrics.as_ref(), || {
374                sqlx::query(
375                    "UPDATE a2a_push_outbox
376                     SET lease_until = now() + make_interval(secs => $2)
377                     WHERE owner = $1 AND lease_until > now()",
378                )
379                .bind(owner)
380                .bind(seconds(lease))
381                .execute(&self.pool)
382            })
383            .await
384            .map_err(|e| to_a2a_error(&e))?
385            .rows_affected();
386            Ok(usize::try_from(renewed).unwrap_or(usize::MAX))
387        })
388    }
389
390    fn claim<'a>(
391        &'a self,
392        owner: &'a str,
393        max: usize,
394        lease: Duration,
395    ) -> OutboxFuture<'a, Vec<ClaimedDelivery>> {
396        Box::pin(async move {
397            let rows = pg_retry::checked(
398                sqlx::query(
399                    "UPDATE a2a_push_outbox
400                     SET owner = $1, lease_until = now() + make_interval(secs => $2)
401                     WHERE seq IN (
402                        SELECT seq FROM a2a_push_outbox o
403                        WHERE o.due_at <= now() AND o.armed
404                          AND (o.lease_until IS NULL OR o.lease_until <= now())
405                          AND NOT EXISTS (
406                            SELECT 1 FROM a2a_push_outbox e
407                            WHERE e.tenant = o.tenant
408                              AND e.caller IS NOT DISTINCT FROM o.caller
409                              AND e.task_id = o.task_id AND e.config_id = o.config_id
410                              AND e.seq < o.seq)
411                        ORDER BY o.seq LIMIT $3
412                        FOR UPDATE SKIP LOCKED)
413                     RETURNING seq, delivery_id, tenant, caller, task_id, config_id, event,
414                               ends_turn, attempts,
415                               EXTRACT(EPOCH FROM now() - recorded_at)::float8 AS age_secs",
416                )
417                .bind(owner)
418                .bind(seconds(lease))
419                .bind(i64::try_from(max).unwrap_or(i64::MAX))
420                .fetch_all(&self.pool),
421            )
422            .await
423            .map_err(|e| to_a2a_error(&e))?;
424            let mut claimed = Vec::with_capacity(rows.len());
425            for row in &rows {
426                if let Some(read) = self.read(row).await {
427                    claimed.push(read);
428                }
429            }
430            claimed.sort_by_key(|c| c.seq);
431            Ok(claimed)
432        })
433    }
434
435    fn complete(&self, seq: i64) -> OutboxFuture<'_, ()> {
436        Box::pin(async move {
437            pg_retry::retry(self.metrics.as_ref(), || {
438                sqlx::query("DELETE FROM a2a_push_outbox WHERE seq = $1")
439                    .bind(seq)
440                    .execute(&self.pool)
441            })
442            .await
443            .map_err(|e| to_a2a_error(&e))?;
444            Ok(())
445        })
446    }
447
448    fn retry_after<'a>(
449        &'a self,
450        seq: i64,
451        owner: &'a str,
452        after: Duration,
453    ) -> OutboxFuture<'a, ()> {
454        Box::pin(async move {
455            // A second run finds the row released and changes nothing.
456            pg_retry::retry(self.metrics.as_ref(), || {
457                sqlx::query(
458                    "UPDATE a2a_push_outbox
459                     SET attempts = attempts + 1,
460                         due_at = now() + make_interval(secs => $3),
461                         owner = NULL, lease_until = NULL
462                     WHERE seq = $1 AND owner = $2",
463                )
464                .bind(seq)
465                .bind(owner)
466                .bind(seconds(after))
467                .execute(&self.pool)
468            })
469            .await
470            .map_err(|e| to_a2a_error(&e))?;
471            Ok(())
472        })
473    }
474
475    fn pending(&self) -> OutboxFuture<'_, usize> {
476        Box::pin(async move {
477            let n: i64 = pg_retry::retry(self.metrics.as_ref(), || {
478                sqlx::query_scalar("SELECT COUNT(*) FROM a2a_push_outbox").fetch_one(&self.pool)
479            })
480            .await
481            .map_err(|e| to_a2a_error(&e))?;
482            Ok(usize::try_from(n).unwrap_or(usize::MAX))
483        })
484    }
485}