a2a_protocol_server/push/outbox.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! A durable queue of webhook deliveries (ADR 0037, audit H14).
5//!
6//! Without one, push delivery is a few tries held in memory: a delivery
7//! waiting in a task's lane, or being retried, when the process stops is not
8//! delivered by this replica or any other, terminal events included, and
9//! nothing records that it was lost. With
10//! [`RequestHandlerBuilder::with_push_outbox`](crate::RequestHandlerBuilder::with_push_outbox),
11//! each event's delivery to each of its task's webhooks is a row: written by
12//! the task's lane once the event is stored, claimed by a worker on whichever
13//! replica gets to it first, retried with backoff until the webhook answers
14//! or the row is older than
15//! [`push_outbox_max_age`](crate::handler::HandlerLimits::push_outbox_max_age),
16//! and removed when it is done.
17//!
18//! # What a receiver sees
19//!
20//! At least once: a delivery whose answer was lost, or whose replica stopped
21//! after sending it, is sent again, from any replica, with the same
22//! `A2A-Delivery-Id` ([`webhook::DELIVERY_ID_HEADER`](super::webhook::DELIVERY_ID_HEADER)),
23//! which is the row's. A webhook sees a task's events in the order they were
24//! stored: a row is claimed only when no earlier row of the same webhook and
25//! task is unfinished.
26//!
27//! # Stores
28//!
29//! [`InMemoryPushOutbox`] keeps nothing across a restart, and is the same
30//! code path for a deployment whose other stores are in memory;
31//! `SqlitePushOutbox` and `PostgresPushOutbox` (features `sqlite`,
32//! `postgres`) keep the rows in a table of their own, `a2a_push_outbox`, and
33//! the PostgreSQL one is shared by every replica that opens it.
34
35use std::future::Future;
36use std::pin::Pin;
37use std::time::Duration;
38
39use a2a_protocol_types::error::A2aResult;
40use a2a_protocol_types::events::StreamResponse;
41
42mod memory;
43pub use memory::InMemoryPushOutbox;
44
45#[cfg(any(feature = "sqlite", feature = "postgres"))]
46mod body;
47#[cfg(feature = "postgres")]
48mod postgres;
49#[cfg(feature = "sqlite")]
50mod sqlite;
51#[cfg(feature = "postgres")]
52pub use postgres::PostgresPushOutbox;
53#[cfg(feature = "sqlite")]
54pub use sqlite::SqlitePushOutbox;
55
56/// A boxed future, as every [`PushOutbox`] method returns.
57pub type OutboxFuture<'a, T> = Pin<Box<dyn Future<Output = A2aResult<T>> + Send + 'a>>;
58
59/// One event's delivery to one webhook, to be recorded.
60#[derive(Debug, Clone)]
61pub struct NewDelivery {
62 /// Sent as `A2A-Delivery-Id` on every attempt.
63 pub delivery_id: String,
64 /// The tenant the delivery runs as.
65 pub tenant: String,
66 /// The caller the delivery runs as, where callers are isolated.
67 pub caller: Option<String>,
68 /// The task the event belongs to.
69 pub task_id: String,
70 /// The push config's id; the config itself is read when the delivery is
71 /// made, so its credentials stay in the config store.
72 pub config_id: String,
73 /// The event.
74 pub event: StreamResponse,
75 /// It carries a terminal or interrupted status: never dropped to make
76 /// room.
77 pub ends_turn: bool,
78}
79
80/// A delivery a worker has claimed.
81#[derive(Debug, Clone)]
82pub struct ClaimedDelivery {
83 /// The row's position: what [`PushOutbox::complete`] and
84 /// [`PushOutbox::retry_after`] name it by. Increasing in the order rows
85 /// were recorded.
86 pub seq: i64,
87 /// What was recorded.
88 pub delivery: NewDelivery,
89 /// Attempts made before this claim.
90 pub attempts: u32,
91 /// How long ago it was recorded, by the store's clock.
92 pub age: Duration,
93}
94
95/// A reservation whose hold has run out.
96///
97/// The deliveries of one event were reserved before the event was stored and
98/// never armed or released. The replica that reserved them stopped, or is
99/// stalled, so something else has to decide whether the event was stored (see
100/// [`PushOutbox::reserve`]).
101#[derive(Debug, Clone)]
102pub struct Held {
103 /// The reservation's id: what [`PushOutbox::arm`] and
104 /// [`PushOutbox::release`] name it by.
105 pub reservation: String,
106 /// The tenant the deliveries run as.
107 pub tenant: String,
108 /// The caller they run as, where callers are isolated.
109 pub caller: Option<String>,
110 /// The task the event belongs to.
111 pub task_id: String,
112 /// The event's position in its task's log.
113 pub log_seq: u64,
114 /// The event.
115 pub event: StreamResponse,
116}
117
118/// Where webhook deliveries wait until they are delivered; see the module
119/// documentation.
120///
121/// A row is claimed by one owner at a time, under a lease: until the lease
122/// runs out no other claim returns it, and once it has, any may. An owner
123/// that stops mid-delivery leaves its rows to the next claim after their
124/// leases.
125pub trait PushOutbox: Send + Sync + 'static {
126 /// Whether this outbox keeps its rows in this process alone, so that a
127 /// delivery owed when the process stops is never made.
128 ///
129 /// The default is `false`, as for the store traits: an outbox this crate
130 /// cannot see into is taken to be durable. [`InMemoryPushOutbox`] answers
131 /// `true`, and so does a `SqlitePushOutbox` over `sqlite::memory:`.
132 /// [`Profile::DurableProduction`](crate::profile::Profile::DurableProduction)
133 /// refuses an outbox that answers `true`.
134 fn is_process_local(&self) -> bool {
135 false
136 }
137
138 /// Records `deliveries`, in order. A delivery whose `delivery_id` is already
139 /// in the outbox is left as it is (recording the same delivery twice keeps
140 /// one row, so a caller can record again what it is unsure was recorded);
141 /// one that was delivered and removed is recorded again, and delivered again
142 /// under the same id, which a receiver sees as a retry. At most `per_webhook` rows wait for one
143 /// webhook of one task: past that, recording one drops the oldest of them
144 /// that is not claimed and does not end a turn, or, when there is none,
145 /// the new one unless it ends a turn (kept past the bound). Returns how
146 /// many were dropped.
147 fn record(&self, deliveries: Vec<NewDelivery>, per_webhook: usize) -> OutboxFuture<'_, usize>;
148
149 /// Claims up to `max` rows that are due, not under another owner's lease,
150 /// and have no earlier unfinished row of the same tenant, caller, task and
151 /// config, for `owner`, for `lease`. In record order.
152 fn claim<'a>(
153 &'a self,
154 owner: &'a str,
155 max: usize,
156 lease: Duration,
157 ) -> OutboxFuture<'a, Vec<ClaimedDelivery>>;
158
159 /// Removes row `seq`: delivered, refused for good, expired, or its config
160 /// is gone. Harmless when it is already gone.
161 fn complete(&self, seq: i64) -> OutboxFuture<'_, ()>;
162
163 /// Makes row `seq` due again `after` from now, one attempt more, and
164 /// releases it, when `owner` still holds its lease; otherwise does
165 /// nothing (another owner has it, and will finish it).
166 fn retry_after<'a>(&'a self, seq: i64, owner: &'a str, after: Duration)
167 -> OutboxFuture<'a, ()>;
168
169 /// How many rows wait, claimed or not, reserved or not: for a gauge.
170 fn pending(&self) -> OutboxFuture<'_, usize>;
171
172 /// Whether this outbox renews leases ([`renew`](Self::renew)). With renewal a
173 /// worker claims for a short lease and renews it while it works, so the
174 /// rows of a worker that died are free after one short lease, not after the
175 /// longest a delivery can take; without it (the default) the worker takes
176 /// the long lease.
177 fn supports_renewal(&self) -> bool {
178 false
179 }
180
181 /// Extends to `lease` from now every unexpired lease `owner` holds: the
182 /// worker's heartbeat. Returns how many rows it renewed.
183 ///
184 /// # Errors
185 ///
186 /// The outbox cannot be written, or does not renew.
187 fn renew<'a>(&'a self, owner: &'a str, lease: Duration) -> OutboxFuture<'a, usize> {
188 let _ = (owner, lease);
189 Box::pin(async {
190 Err(a2a_protocol_types::error::A2aError::unsupported_operation(
191 "this push outbox does not renew leases",
192 ))
193 })
194 }
195
196 /// Whether this outbox keeps reservations ([`reserve`](Self::reserve)).
197 /// One that does not (the default) is recorded in only after an event is
198 /// stored, and a crash between the two loses that event's deliveries.
199 fn supports_reservations(&self) -> bool {
200 false
201 }
202
203 /// Phase one of recording an event's deliveries *before* the event is
204 /// stored (audit H14): `deliveries`, all of one event at position
205 /// `log_seq` of its task's log, are written **unarmed**.
206 ///
207 /// An unarmed row is not claimed, but it holds its webhook's place: no
208 /// later row of the same webhook is claimed past it, so the order of a
209 /// webhook's deliveries is the order of the events whether or not they
210 /// have been stored yet. It is never dropped to make room for another
211 /// row. The caller then either [`arm`](Self::arm)s the reservation once
212 /// the event is stored, or [`release`](Self::release)s it if it was not.
213 ///
214 /// If the caller stops between the two, the rows are left with a `hold`
215 /// that runs out; [`held`](Self::held) then lists the reservation, and
216 /// whoever settles it decides from the task store whether the event was
217 /// stored. Like [`record`](Self::record), returns how many rows were
218 /// dropped for the `per_webhook` bound.
219 ///
220 /// # Errors
221 ///
222 /// The outbox cannot be written, or keeps no reservations.
223 fn reserve<'a>(
224 &'a self,
225 reservation: &'a str,
226 log_seq: u64,
227 deliveries: Vec<NewDelivery>,
228 per_webhook: usize,
229 hold: Duration,
230 ) -> OutboxFuture<'a, usize> {
231 let _ = (reservation, log_seq, deliveries, per_webhook, hold);
232 Box::pin(async {
233 Err(a2a_protocol_types::error::A2aError::unsupported_operation(
234 "this push outbox keeps no reservations",
235 ))
236 })
237 }
238
239 /// Phase two, the event was stored: the rows of `reservation` become
240 /// claimable. Returns how many rows the reservation has, armed by this
241 /// call or already; `0` means there is nothing of it left (it was
242 /// released, or settled by another replica as not stored, or already
243 /// delivered), and the caller records the deliveries afresh.
244 ///
245 /// # Errors
246 ///
247 /// The outbox cannot be written, or keeps no reservations.
248 fn arm<'a>(&'a self, reservation: &'a str) -> OutboxFuture<'a, usize> {
249 let _ = reservation;
250 Box::pin(async {
251 Err(a2a_protocol_types::error::A2aError::unsupported_operation(
252 "this push outbox keeps no reservations",
253 ))
254 })
255 }
256
257 /// The event was not stored: removes the rows of `reservation` that are
258 /// not armed. Armed rows, and a reservation that is gone, are left
259 /// alone.
260 ///
261 /// # Errors
262 ///
263 /// The outbox cannot be written, or keeps no reservations.
264 fn release<'a>(&'a self, reservation: &'a str) -> OutboxFuture<'a, ()> {
265 let _ = reservation;
266 Box::pin(async {
267 Err(a2a_protocol_types::error::A2aError::unsupported_operation(
268 "this push outbox keeps no reservations",
269 ))
270 })
271 }
272
273 /// Extends to `hold` from now the hold of `reservation`, if it is still
274 /// held (not armed, not released): the heartbeat of a reserver that is
275 /// still alive and whose event is still being written (adversarial review
276 /// R3). Returns how many rows it extended; `0` means nothing of it is left
277 /// to extend (it was settled by a replica whose worker saw the hold run
278 /// out, or released).
279 ///
280 /// Without a heartbeat a hold is a wall-clock guess that no write outlasts;
281 /// with one, a worker settles only a reservation whose reserver has stopped
282 /// renewing it, which a live writer, however slow its store, does not.
283 ///
284 /// # Errors
285 ///
286 /// The outbox cannot be written, keeps no reservations, or does not extend
287 /// a hold (the default): the reserver then relies on the hold it set.
288 fn extend_hold<'a>(&'a self, reservation: &'a str, hold: Duration) -> OutboxFuture<'a, usize> {
289 let _ = (reservation, hold);
290 Box::pin(async {
291 Err(a2a_protocol_types::error::A2aError::unsupported_operation(
292 "this push outbox does not extend the hold of a reservation",
293 ))
294 })
295 }
296
297 /// Every reservation of one task that is not armed, whether or not its hold
298 /// has run out: for a caller that knows the reserver can write no more, such
299 /// as the reaper once it holds the task's turn claim (a store refuses a
300 /// writer whose claim was taken over, so what the task store holds is final).
301 ///
302 /// # Errors
303 ///
304 /// The outbox cannot be read, or keeps no reservations.
305 fn held_for_task<'a>(
306 &'a self,
307 tenant: &'a str,
308 caller: Option<&'a str>,
309 task_id: &'a str,
310 ) -> OutboxFuture<'a, Vec<Held>> {
311 let _ = (tenant, caller, task_id);
312 Box::pin(async {
313 Err(a2a_protocol_types::error::A2aError::unsupported_operation(
314 "this push outbox keeps no reservations",
315 ))
316 })
317 }
318
319 /// Up to `limit` reservations that are not armed and whose hold has run
320 /// out, oldest first, one entry each however many webhooks it has rows
321 /// for.
322 ///
323 /// # Errors
324 ///
325 /// The outbox cannot be read, or keeps no reservations.
326 fn held(&self, limit: usize) -> OutboxFuture<'_, Vec<Held>> {
327 let _ = limit;
328 Box::pin(async {
329 Err(a2a_protocol_types::error::A2aError::unsupported_operation(
330 "this push outbox keeps no reservations",
331 ))
332 })
333 }
334}
335
336/// The denominator of a jitter: [`jitter`] is a fraction of it.
337pub const JITTER_ONE: u32 = 65_536;
338
339/// How long a delivery that failed `attempts` times waits before the next.
340///
341/// 1 s doubled per attempt, at most `max`, less up to a fifth of jitter
342/// (`jitter` out of [`JITTER_ONE`]), so retries of many rows that failed
343/// together do not arrive together. In whole nanoseconds, so it is exact.
344#[must_use]
345pub fn backoff(attempts: u32, max: Duration, jitter: u32) -> Duration {
346 let full = Duration::from_secs(1)
347 .checked_mul(
348 1u32.checked_shl(attempts.saturating_sub(1))
349 .unwrap_or(u32::MAX),
350 )
351 .unwrap_or(max)
352 .min(max);
353 let fifths = JITTER_ONE * 5;
354 full * (fifths - jitter.min(JITTER_ONE)) / fifths
355}
356
357/// A jitter out of [`JITTER_ONE`], from a fresh random UUID: no new
358/// dependency for a number that needs to be spread, not unpredictable.
359#[must_use]
360pub fn jitter() -> u32 {
361 let [a, b, ..] = *uuid::Uuid::new_v4().as_bytes();
362 u32::from(u16::from_be_bytes([a, b]))
363}
364
365#[cfg(test)]
366mod contract;
367#[cfg(test)]
368mod postgres_tests;
369#[cfg(test)]
370mod sqlite_tests;
371#[cfg(test)]
372mod tests;