Skip to main content

a2a_protocol_server/push/outbox/
sqlite.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`PushOutbox`] in SQLite (feature `sqlite`).
5//!
6//! The clock is the database's (`julianday('now')`, in milliseconds), which
7//! is the same for every statement step, so a claim's "due" and its lease are
8//! read from one instant. A claim is one `UPDATE ... RETURNING` statement, so
9//! two processes sharing the file cannot both claim a row.
10
11use std::sync::Arc;
12use std::time::Duration;
13
14use a2a_protocol_types::error::A2aError;
15use sqlx::Row as _;
16use sqlx::sqlite::SqlitePool;
17
18use super::body::{Body, context};
19use super::{ClaimedDelivery, Held, NewDelivery, OutboxFuture, PushOutbox};
20use crate::push::PushConfigCipher;
21
22/// Now, in milliseconds since the Unix epoch, by the database's clock: a
23/// macro, so each statement is one `&'static str` (`concat!`), never text
24/// formatted at run time.
25macro_rules! now_ms {
26    () => {
27        "CAST((julianday('now') - 2440587.5) * 86400000.0 AS INTEGER)"
28    };
29}
30
31mod record;
32use record::Reserve;
33
34const SCHEMA: [&str; 4] = [
35    "CREATE TABLE IF NOT EXISTS a2a_push_outbox (
36        seq         INTEGER PRIMARY KEY AUTOINCREMENT,
37        delivery_id TEXT    NOT NULL UNIQUE,
38        tenant      TEXT    NOT NULL,
39        caller      TEXT,
40        task_id     TEXT    NOT NULL,
41        config_id   TEXT    NOT NULL,
42        event       TEXT    NOT NULL,
43        ends_turn   INTEGER NOT NULL,
44        attempts    INTEGER NOT NULL DEFAULT 0,
45        recorded_ms INTEGER NOT NULL,
46        due_ms      INTEGER NOT NULL,
47        owner       TEXT,
48        lease_ms    INTEGER,
49        armed       INTEGER NOT NULL DEFAULT 1,
50        reservation TEXT,
51        log_seq     INTEGER,
52        hold_ms     INTEGER
53    )",
54    "CREATE INDEX IF NOT EXISTS a2a_push_outbox_webhook
55        ON a2a_push_outbox (tenant, caller, task_id, config_id, seq)",
56    "CREATE INDEX IF NOT EXISTS a2a_push_outbox_reservation
57        ON a2a_push_outbox (reservation) WHERE reservation IS NOT NULL",
58    // What `held` looks for, without reading a backlog of armed rows.
59    "CREATE INDEX IF NOT EXISTS a2a_push_outbox_unarmed
60        ON a2a_push_outbox (hold_ms) WHERE armed = 0",
61];
62
63/// The columns of the two-phase record (audit H14), added to a table an
64/// earlier build of this outbox created without them. `SQLite` has no
65/// `ADD COLUMN IF NOT EXISTS`, so each is looked for first.
66const TWO_PHASE_COLUMNS: [(&str, &str); 4] = [
67    (
68        "armed",
69        "ALTER TABLE a2a_push_outbox ADD COLUMN armed INTEGER NOT NULL DEFAULT 1",
70    ),
71    (
72        "reservation",
73        "ALTER TABLE a2a_push_outbox ADD COLUMN reservation TEXT",
74    ),
75    (
76        "log_seq",
77        "ALTER TABLE a2a_push_outbox ADD COLUMN log_seq INTEGER",
78    ),
79    (
80        "hold_ms",
81        "ALTER TABLE a2a_push_outbox ADD COLUMN hold_ms INTEGER",
82    ),
83];
84
85/// A [`PushOutbox`] in an SQLite database; see the module documentation.
86#[derive(Debug, Clone)]
87pub struct SqlitePushOutbox {
88    pub(super) pool: SqlitePool,
89    body: Body,
90}
91
92fn to_a2a_error(e: &sqlx::Error) -> A2aError {
93    crate::sql_error::sql_error(crate::sql_error::Db::Sqlite, "sqlite push outbox", e)
94}
95
96/// Milliseconds in `d`, saturating.
97fn millis(d: Duration) -> i64 {
98    i64::try_from(d.as_millis()).unwrap_or(i64::MAX)
99}
100
101impl SqlitePushOutbox {
102    /// Opens (or creates) the database at `url` and its table.
103    ///
104    /// # Errors
105    ///
106    /// The database cannot be opened, or the table created.
107    pub async fn new(url: &str) -> Result<Self, sqlx::Error> {
108        Self::from_pool(crate::sqlite_pool::sqlite_pool(url).await?).await
109    }
110
111    /// The outbox on `pool`, creating its table.
112    ///
113    /// # Errors
114    ///
115    /// The table cannot be created.
116    pub async fn from_pool(pool: SqlitePool) -> Result<Self, sqlx::Error> {
117        sqlx::query(SCHEMA[0]).execute(&pool).await?;
118        for (column, alter) in TWO_PHASE_COLUMNS {
119            let present: i64 = sqlx::query_scalar(
120                "SELECT COUNT(*) FROM pragma_table_info('a2a_push_outbox') WHERE name = ?1",
121            )
122            .bind(column)
123            .fetch_one(&pool)
124            .await?;
125            if present == 0 {
126                sqlx::query(alter).execute(&pool).await?;
127            }
128        }
129        for statement in SCHEMA.iter().skip(1).copied() {
130            sqlx::query(statement).execute(&pool).await?;
131        }
132        Ok(Self {
133            pool,
134            body: Body::default(),
135        })
136    }
137
138    /// Seals every event body with `cipher`, as the push-config stores seal
139    /// configs (`PushConfigCipher`): an event can carry what the task store
140    /// encrypts. A store that seals refuses a body it did not seal.
141    #[must_use]
142    pub fn with_cipher(mut self, cipher: Arc<dyn PushConfigCipher>) -> Self {
143        self.body = Body::with_cipher(cipher);
144        self
145    }
146
147    /// The reservations `rows` name, their events opened; one that does not open
148    /// is left in place and said so.
149    async fn read_held(&self, rows: &[sqlx::sqlite::SqliteRow]) -> Vec<Held> {
150        let mut held = Vec::with_capacity(rows.len());
151        for row in rows {
152            let (tenant, caller, task_id, delivery_id): (String, Option<String>, String, String) = (
153                row.get("tenant"),
154                row.get("caller"),
155                row.get("task_id"),
156                row.get("delivery_id"),
157            );
158            let ctx = context(&tenant, caller.as_deref(), &task_id, &delivery_id);
159            let Ok(event) = self.body.decode(row.get::<&str, _>("event"), &ctx).await else {
160                trace_warn!(
161                    task_id = %task_id,
162                    "push outbox: a reserved row's event could not be read; it is left"
163                );
164                continue;
165            };
166            held.push(Held {
167                reservation: row.get("reservation"),
168                tenant,
169                caller,
170                task_id,
171                log_seq: u64::try_from(row.get::<i64, _>("log_seq")).unwrap_or(0),
172                event,
173            });
174        }
175        held
176    }
177
178    /// One claimed row, read; `None`, said so, for a row whose event does
179    /// not open.
180    async fn read(&self, row: &sqlx::sqlite::SqliteRow) -> Option<ClaimedDelivery> {
181        let (tenant, caller, task_id, delivery_id): (String, Option<String>, String, String) = (
182            row.get("tenant"),
183            row.get("caller"),
184            row.get("task_id"),
185            row.get("delivery_id"),
186        );
187        let ctx = context(&tenant, caller.as_deref(), &task_id, &delivery_id);
188        // A body that does not open (moved from another row, or
189        // sealed under a key this store does not hold) is left
190        // leased and said so, rather than failing the claim: one bad
191        // row must not stop every other delivery.
192        let event = match self.body.decode(row.get::<&str, _>("event"), &ctx).await {
193            Ok(event) => event,
194            Err(_err) => {
195                trace_warn!(
196                    task_id = %task_id,
197                    error = %_err,
198                    "push outbox: a row's event could not be read; it is skipped"
199                );
200                return None;
201            }
202        };
203        Some(ClaimedDelivery {
204            seq: row.get("seq"),
205            attempts: u32::try_from(row.get::<i64, _>("attempts")).unwrap_or(u32::MAX),
206            age: Duration::from_millis(u64::try_from(row.get::<i64, _>("age_ms")).unwrap_or(0)),
207            delivery: NewDelivery {
208                delivery_id,
209                tenant,
210                caller,
211                task_id,
212                config_id: row.get("config_id"),
213                event,
214                ends_turn: row.get("ends_turn"),
215            },
216        })
217    }
218}
219
220impl SqlitePushOutbox {
221    /// Records `deliveries` in one transaction, reserved when `reserve` is
222    /// given; how many were dropped for the bound.
223    async fn insert(
224        &self,
225        deliveries: Vec<NewDelivery>,
226        per_webhook: usize,
227        reserve: Option<Reserve<'_>>,
228    ) -> a2a_protocol_types::error::A2aResult<usize> {
229        let mut bodies = Vec::with_capacity(deliveries.len());
230        for d in &deliveries {
231            let ctx = context(&d.tenant, d.caller.as_deref(), &d.task_id, &d.delivery_id);
232            bodies.push(self.body.encode(&d.event, &ctx).await?);
233        }
234        let mut tx = self.pool.begin().await.map_err(|e| to_a2a_error(&e))?;
235        let mut dropped = 0;
236        for (d, event) in deliveries.iter().zip(&bodies) {
237            dropped += Self::record_one(&mut tx, d, event, per_webhook, reserve.as_ref())
238                .await
239                .map_err(|e| to_a2a_error(&e))?;
240        }
241        tx.commit().await.map_err(|e| to_a2a_error(&e))?;
242        Ok(dropped)
243    }
244}
245
246impl PushOutbox for SqlitePushOutbox {
247    fn is_process_local(&self) -> bool {
248        crate::sqlite_pool::is_in_memory(&self.pool)
249    }
250
251    fn record(&self, deliveries: Vec<NewDelivery>, per_webhook: usize) -> OutboxFuture<'_, usize> {
252        Box::pin(self.insert(deliveries, per_webhook, None))
253    }
254
255    fn supports_reservations(&self) -> bool {
256        true
257    }
258
259    fn reserve<'a>(
260        &'a self,
261        reservation: &'a str,
262        log_seq: u64,
263        deliveries: Vec<NewDelivery>,
264        per_webhook: usize,
265        hold: Duration,
266    ) -> OutboxFuture<'a, usize> {
267        Box::pin(self.insert(
268            deliveries,
269            per_webhook,
270            Some(Reserve {
271                id: reservation,
272                log_seq: i64::try_from(log_seq).unwrap_or(i64::MAX),
273                hold_ms: millis(hold),
274            }),
275        ))
276    }
277
278    fn arm<'a>(&'a self, reservation: &'a str) -> OutboxFuture<'a, usize> {
279        Box::pin(async move {
280            let armed = sqlx::query("UPDATE a2a_push_outbox SET armed = 1 WHERE reservation = ?1")
281                .bind(reservation)
282                .execute(&self.pool)
283                .await
284                .map_err(|e| to_a2a_error(&e))?
285                .rows_affected();
286            Ok(usize::try_from(armed).unwrap_or(usize::MAX))
287        })
288    }
289
290    fn extend_hold<'a>(&'a self, reservation: &'a str, hold: Duration) -> OutboxFuture<'a, usize> {
291        Box::pin(async move {
292            let extended = sqlx::query(concat!(
293                "UPDATE a2a_push_outbox SET hold_ms = ",
294                now_ms!(),
295                " + ?2 WHERE reservation = ?1 AND armed = 0"
296            ))
297            .bind(reservation)
298            .bind(millis(hold))
299            .execute(&self.pool)
300            .await
301            .map_err(|e| to_a2a_error(&e))?
302            .rows_affected();
303            Ok(usize::try_from(extended).unwrap_or(usize::MAX))
304        })
305    }
306
307    fn release<'a>(&'a self, reservation: &'a str) -> OutboxFuture<'a, ()> {
308        Box::pin(async move {
309            sqlx::query("DELETE FROM a2a_push_outbox WHERE reservation = ?1 AND armed = 0")
310                .bind(reservation)
311                .execute(&self.pool)
312                .await
313                .map_err(|e| to_a2a_error(&e))?;
314            Ok(())
315        })
316    }
317
318    fn held(&self, limit: usize) -> OutboxFuture<'_, Vec<Held>> {
319        Box::pin(async move {
320            let rows = sqlx::query(concat!(
321                "SELECT delivery_id, tenant, caller, task_id, event, log_seq, reservation
322                 FROM a2a_push_outbox
323                 WHERE seq IN (
324                    SELECT MIN(seq) FROM a2a_push_outbox
325                    WHERE armed = 0 AND hold_ms <= ",
326                now_ms!(),
327                "
328                    GROUP BY reservation ORDER BY MIN(seq) LIMIT ?1)
329                 ORDER BY seq"
330            ))
331            .bind(i64::try_from(limit).unwrap_or(i64::MAX))
332            .fetch_all(&self.pool)
333            .await
334            .map_err(|e| to_a2a_error(&e))?;
335            Ok(self.read_held(&rows).await)
336        })
337    }
338
339    fn held_for_task<'a>(
340        &'a self,
341        tenant: &'a str,
342        caller: Option<&'a str>,
343        task_id: &'a str,
344    ) -> OutboxFuture<'a, Vec<Held>> {
345        Box::pin(async move {
346            let rows = sqlx::query(
347                "SELECT delivery_id, tenant, caller, task_id, event, log_seq, reservation
348                 FROM a2a_push_outbox
349                 WHERE seq IN (
350                    SELECT MIN(seq) FROM a2a_push_outbox
351                    WHERE armed = 0 AND tenant = ?1 AND caller IS ?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            .await
360            .map_err(|e| to_a2a_error(&e))?;
361            Ok(self.read_held(&rows).await)
362        })
363    }
364
365    fn supports_renewal(&self) -> bool {
366        true
367    }
368
369    fn renew<'a>(&'a self, owner: &'a str, lease: Duration) -> OutboxFuture<'a, usize> {
370        Box::pin(async move {
371            let renewed = sqlx::query(concat!(
372                "UPDATE a2a_push_outbox SET lease_ms = ",
373                now_ms!(),
374                " + ?2 WHERE owner = ?1 AND lease_ms > ",
375                now_ms!()
376            ))
377            .bind(owner)
378            .bind(millis(lease))
379            .execute(&self.pool)
380            .await
381            .map_err(|e| to_a2a_error(&e))?
382            .rows_affected();
383            Ok(usize::try_from(renewed).unwrap_or(usize::MAX))
384        })
385    }
386
387    fn claim<'a>(
388        &'a self,
389        owner: &'a str,
390        max: usize,
391        lease: Duration,
392    ) -> OutboxFuture<'a, Vec<ClaimedDelivery>> {
393        Box::pin(async move {
394            let rows = sqlx::query(concat!(
395                "UPDATE a2a_push_outbox SET owner = ?1, lease_ms = ",
396                now_ms!(),
397                " + ?2
398                 WHERE seq IN (
399                    SELECT seq FROM a2a_push_outbox o
400                    WHERE o.due_ms <= ",
401                now_ms!(),
402                "
403                      AND o.armed = 1
404                      AND (o.lease_ms IS NULL OR o.lease_ms <= ",
405                now_ms!(),
406                ")
407                      AND NOT EXISTS (
408                        SELECT 1 FROM a2a_push_outbox e
409                        WHERE e.tenant = o.tenant AND e.caller IS o.caller
410                          AND e.task_id = o.task_id AND e.config_id = o.config_id
411                          AND e.seq < o.seq)
412                    ORDER BY o.seq LIMIT ?3)
413                 RETURNING seq, delivery_id, tenant, caller, task_id, config_id, event,
414                           ends_turn, attempts, ",
415                now_ms!(),
416                " - recorded_ms AS age_ms"
417            ))
418            .bind(owner)
419            .bind(millis(lease))
420            .bind(i64::try_from(max).unwrap_or(i64::MAX))
421            .fetch_all(&self.pool)
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            sqlx::query("DELETE FROM a2a_push_outbox WHERE seq = ?1")
438                .bind(seq)
439                .execute(&self.pool)
440                .await
441                .map_err(|e| to_a2a_error(&e))?;
442            Ok(())
443        })
444    }
445
446    fn retry_after<'a>(
447        &'a self,
448        seq: i64,
449        owner: &'a str,
450        after: Duration,
451    ) -> OutboxFuture<'a, ()> {
452        Box::pin(async move {
453            sqlx::query(concat!(
454                "UPDATE a2a_push_outbox
455                 SET attempts = attempts + 1, due_ms = ",
456                now_ms!(),
457                " + ?3, owner = NULL, lease_ms = NULL
458                 WHERE seq = ?1 AND owner = ?2"
459            ))
460            .bind(seq)
461            .bind(owner)
462            .bind(millis(after))
463            .execute(&self.pool)
464            .await
465            .map_err(|e| to_a2a_error(&e))?;
466            Ok(())
467        })
468    }
469
470    fn pending(&self) -> OutboxFuture<'_, usize> {
471        Box::pin(async move {
472            let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM a2a_push_outbox")
473                .fetch_one(&self.pool)
474                .await
475                .map_err(|e| to_a2a_error(&e))?;
476            Ok(usize::try_from(n).unwrap_or(usize::MAX))
477        })
478    }
479}