a2a_protocol_server/store/log_notify.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! `LISTEN`/`NOTIFY` for the `PostgreSQL` task stores' event logs: an append
5//! announces the task it was for, and a listener wakes the streams waiting on
6//! it (audit E-F25 (b), ADR 0057).
7//!
8//! This is the design of the halt store's listener
9//! ([`PostgresHaltStore`](crate::store::PostgresHaltStore), ADR 0024), including
10//! what it says about poolers, because the failure is the same one: `LISTEN`
11//! belongs to a session, and a pooler in transaction mode lends the session to
12//! someone else. See [`LogListen`].
13//!
14//! Three differences from the halt store, each on purpose:
15//!
16//! * **Opt-in.** The halt store listens unless told not to, and is built by an
17//! operator who names its pool. A task store is built by everyone, most of
18//! them behind a pooler, and its appends are the hottest write there is: a
19//! default that put a `NOTIFY` in every append, and a `LISTEN` on every
20//! replica, would change what an upgrade does to a deployment that did not
21//! ask. The statement an unannounced append runs is the one it ran before.
22//! * **Lazy.** The listener starts with the first stream that waits, so a
23//! replica that serves no cross-replica stream holds no connection for it.
24//! * **One notification per append, named by task.** The payload is the key
25//! of [`log_wake::key`](super::log_wake): a task and its partition, which
26//! the listener looks up as it arrives. A task whose key does not fit is
27//! not announced and is polled, as it was.
28
29use std::sync::{Arc, OnceLock};
30use std::time::Duration;
31
32use sqlx::postgres::{PgListener, PgPool};
33
34use super::LogWatch;
35use super::log_wake::{LogWakers, key};
36
37/// The channel an append is announced on. The payload is the task's key.
38pub const CHANNEL: &str = "a2a_task_log";
39
40/// How long the listener waits before reconnecting after an error.
41const RECONNECT_DELAY: Duration = Duration::from_secs(1);
42
43/// Where the listener of a store's log notifications gets its session
44/// ([`PostgresTaskStore::with_log_notifications`](crate::store::PostgresTaskStore::with_log_notifications)).
45///
46/// # Behind a connection pooler
47///
48/// `LISTEN` belongs to a session. A pooler in transaction mode (`PgBouncer`'s
49/// `pool_mode = transaction`, the usual setting) runs it on whichever server
50/// connection it lends, then lends that connection to a client that is not
51/// listening, and the next notification lands in the middle of that client's
52/// statement: sqlx fails it with `unexpected message: NotificationResponse`
53/// (seen live through `PgBouncer` 1.26.1, 2026-10-30, as the halt store's
54/// failure). So behind such a pooler, listen on a connection straight to
55/// `PostgreSQL`: [`Direct`](Self::Direct). A store built without
56/// `with_log_notifications` listens to nothing, and its streams poll.
57#[derive(Clone, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum LogListen {
60 /// A connection taken from the store's own pool, held for as long as the
61 /// store lives: size the pool one connection larger. For a pool that
62 /// reaches `PostgreSQL` directly.
63 Pool,
64 /// A connection of its own to this URL, past any pooler. The URL is a
65 /// credential and is not printed by `Debug`.
66 Direct(String),
67}
68
69impl std::fmt::Debug for LogListen {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 match self {
72 Self::Pool => f.write_str("Pool"),
73 Self::Direct(_) => f.write_str("Direct(<url>)"),
74 }
75 }
76}
77
78/// The listening task, aborted when the last store clone is dropped.
79#[derive(Debug)]
80struct Listener(tokio::task::JoinHandle<()>);
81
82impl Drop for Listener {
83 fn drop(&mut self) {
84 self.0.abort();
85 }
86}
87
88/// What a store that announces and listens holds: the waiters, the means to
89/// listen for them and the listener, once a stream has waited.
90#[derive(Debug)]
91pub struct LogNotify {
92 wakers: LogWakers,
93 pool: PgPool,
94 listen: LogListen,
95 listener: OnceLock<Listener>,
96}
97
98impl LogNotify {
99 /// Announcing and listening, over `pool` or as `listen` says.
100 pub fn new(pool: PgPool, listen: LogListen) -> Arc<Self> {
101 Arc::new(Self {
102 wakers: LogWakers::new(),
103 pool,
104 listen,
105 listener: OnceLock::new(),
106 })
107 }
108
109 /// A watch on `task` in `partition`, registered now, with the listener
110 /// started if this is the first. `None` for a task whose key does not fit
111 /// a notification (it is polled) and outside a runtime (the listener
112 /// cannot run).
113 pub fn watch(&self, partition: &str, task: &str) -> Option<LogWatch> {
114 let key = key(partition, task)?;
115 tokio::runtime::Handle::try_current().ok()?;
116 let watch = self.wakers.watch(key);
117 self.listener.get_or_init(|| {
118 Listener(tokio::spawn(listen(
119 self.pool.clone(),
120 self.listen.clone(),
121 self.wakers.clone(),
122 )))
123 });
124 Some(watch)
125 }
126}
127
128/// The key an append is announced under, for a store that announces
129/// (`log` is `Some`) and a task whose key fits a notification.
130pub fn announcement(log: Option<&Arc<LogNotify>>, partition: &str, task: &str) -> Option<String> {
131 log.and_then(|_| key(partition, task))
132}
133
134/// A watch on `task` in `partition` for a store that has opted in (`log` is
135/// `Some`); see [`LogNotify::watch`].
136pub fn watch(log: Option<&Arc<LogNotify>>, partition: &str, task: &str) -> Option<LogWatch> {
137 log?.watch(partition, task)
138}
139
140/// The append statement for a store that announces `key`, or the plain one.
141pub const fn append_sql(
142 key: Option<&str>,
143 plain: &'static str,
144 announcing: &'static str,
145) -> &'static str {
146 if key.is_some() { announcing } else { plain }
147}
148
149/// Binds the announcement, the channel and the key, to an announcing append,
150/// and nothing to a plain one.
151pub fn announce<'q>(
152 query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
153 key: Option<&'q str>,
154) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
155 match key {
156 Some(key) => query.bind(CHANNEL).bind(key),
157 None => query,
158 }
159}
160
161/// Forwards notifications to the waiters until the task is aborted. Every
162/// waiter is woken once the listener is listening, and again after a lost
163/// connection is back: whatever was announced before `LISTEN` took effect, or
164/// while the connection was down, is gone, and a read recovers it.
165async fn listen(pool: PgPool, on: LogListen, wakers: LogWakers) {
166 loop {
167 let connected = match &on {
168 LogListen::Pool => PgListener::connect_with(&pool).await,
169 LogListen::Direct(url) => PgListener::connect(url).await,
170 };
171 let mut listener = match connected {
172 Ok(l) => l,
173 Err(_e) => {
174 trace_warn!(error = %_e, "task log listener: cannot connect; retrying");
175 tokio::time::sleep(RECONNECT_DELAY).await;
176 continue;
177 }
178 };
179 if let Err(_e) = listener.listen(CHANNEL).await {
180 trace_warn!(error = %_e, "task log listener: LISTEN failed; retrying");
181 tokio::time::sleep(RECONNECT_DELAY).await;
182 continue;
183 }
184 wakers.resync();
185 loop {
186 match listener.try_recv().await {
187 Ok(Some(n)) => wakers.notify(n.payload()),
188 // The connection was lost and is being re-established.
189 Ok(None) => wakers.resync(),
190 Err(_e) => {
191 trace_warn!(error = %_e, "task log listener: receive failed; reconnecting");
192 tokio::time::sleep(RECONNECT_DELAY).await;
193 break;
194 }
195 }
196 }
197 }
198}
199
200#[cfg(test)]
201mod tests;