a2a_protocol_server/store/log_wake.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Waking a stream that waits on a task's event log (audit E-F25 (b), ADR
5//! 0057).
6//!
7//! A `SubscribeToTask` stream on a replica that does not run the task learns
8//! of its events by reading the store, and until this existed it read on a
9//! timer. [`TaskStore::watch_event_log`](crate::store::TaskStore::watch_event_log)
10//! lets a store say "something changed" instead, so the timer becomes the
11//! fallback it should have been. The types here are what a store hands back
12//! ([`LogWatch`], resolving to a [`LogWake`]); [`LogWakers`] is the registry
13//! the stores in this crate that can push keep their waiters in.
14
15use std::future::Future;
16use std::pin::Pin;
17
18/// Why a wait on a task's event log ended.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum LogWake {
22 /// A notification named this task: an event was appended to its log.
23 Notified,
24 /// The store lost the source of its notifications and has it again.
25 /// Whatever was sent in between is gone, so every waiter is woken to look
26 /// for itself.
27 Resynced,
28}
29
30impl LogWake {
31 /// The [`subscribe_wake`](crate::metrics::subscribe_wake) label this wake
32 /// is reported under.
33 pub(crate) const fn cause(self) -> &'static str {
34 match self {
35 Self::Notified => crate::metrics::subscribe_wake::NOTIFICATION,
36 Self::Resynced => crate::metrics::subscribe_wake::RESYNC,
37 }
38 }
39}
40
41/// A registered interest in one task's event log, from
42/// [`TaskStore::watch_event_log`](crate::store::TaskStore::watch_event_log).
43///
44/// It resolves when the log may have changed since it was created, and ends
45/// the interest when it is dropped. The interest begins when the watch is
46/// created, not when it is first polled: a stream creates one, reads the
47/// store, and only then waits on it, so a change made between the read and
48/// the wait is not lost.
49pub type LogWatch = Pin<Box<dyn Future<Output = LogWake> + Send>>;
50
51#[cfg(any(feature = "postgres", test))]
52pub use registry::{LogWakers, key};
53
54#[cfg(any(feature = "postgres", test))]
55mod registry {
56 use std::collections::HashMap;
57 use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
58
59 use tokio::sync::watch;
60
61 use super::{LogWake, LogWatch};
62
63 /// The most bytes a task's key may take, which is the payload of its
64 /// notification. `PostgreSQL` refuses one of 8,000 bytes or more; this is far
65 /// below it, because a task id is chosen by a client (a continuation names
66 /// it) and every replica reads every notification. A task whose key does
67 /// not fit is never announced and never watched: it is polled, as it was.
68 pub const MAX_KEY_BYTES: usize = 512;
69
70 /// The key a task is announced under, `{partition length}:{partition}{task}`,
71 /// or `None` when it is longer than [`MAX_KEY_BYTES`].
72 ///
73 /// The partition is the tenant (and caller) the task is stored under, `""`
74 /// for the plain stores. The length comes first so that two different pairs
75 /// never share a key, whatever characters either holds, and so that a
76 /// receiver needs no parser: the key is looked up as it arrives.
77 pub fn key(partition: &str, task: &str) -> Option<String> {
78 let key = format!("{}:{partition}{task}", partition.len());
79 (key.len() <= MAX_KEY_BYTES).then_some(key)
80 }
81
82 /// One watched task: a counter its waiters watch, and how many there are.
83 #[derive(Debug)]
84 struct Entry {
85 tx: watch::Sender<u64>,
86 waiters: usize,
87 }
88
89 #[derive(Debug)]
90 struct Inner {
91 /// Only keys with a waiter: an entry is made by the first and removed
92 /// by the last, so the map is as big as the streams waiting and a
93 /// notification for any other task is one failed lookup.
94 tasks: Mutex<HashMap<String, Entry>>,
95 /// Counts the times every waiter was told to look.
96 resync: watch::Sender<u64>,
97 }
98
99 impl Inner {
100 fn tasks(&self) -> MutexGuard<'_, HashMap<String, Entry>> {
101 // Nothing that holds the lock can panic part-way through a change.
102 self.tasks.lock().unwrap_or_else(PoisonError::into_inner)
103 }
104 }
105
106 /// The streams waiting on each task, and the means to wake them.
107 #[derive(Debug, Clone)]
108 pub struct LogWakers {
109 inner: Arc<Inner>,
110 }
111
112 /// Ends one waiter's interest when its [`LogWatch`] is dropped, finished
113 /// or not.
114 struct Interest {
115 inner: Arc<Inner>,
116 key: String,
117 }
118
119 impl Drop for Interest {
120 fn drop(&mut self) {
121 let mut tasks = self.inner.tasks();
122 if let Some(entry) = tasks.get_mut(&self.key) {
123 entry.waiters -= 1;
124 if entry.waiters == 0 {
125 tasks.remove(&self.key);
126 }
127 }
128 }
129 }
130
131 impl LogWakers {
132 pub(crate) fn new() -> Self {
133 Self {
134 inner: Arc::new(Inner {
135 tasks: Mutex::new(HashMap::new()),
136 resync: watch::channel(0).0,
137 }),
138 }
139 }
140
141 /// Registers a waiter on `key` (see [`key`]) now, and returns the
142 /// future that resolves when it is woken.
143 pub(crate) fn watch(&self, key: String) -> LogWatch {
144 let mut task = {
145 let mut tasks = self.inner.tasks();
146 let entry = tasks.entry(key.clone()).or_insert_with(|| Entry {
147 tx: watch::channel(0).0,
148 waiters: 0,
149 });
150 entry.waiters += 1;
151 let receiver = entry.tx.subscribe();
152 drop(tasks);
153 receiver
154 };
155 let mut resync = self.inner.resync.subscribe();
156 let interest = Interest {
157 inner: Arc::clone(&self.inner),
158 key,
159 };
160 Box::pin(async move {
161 let _interest = interest;
162 // Notified first when both are ready: it names the task.
163 tokio::select! {
164 biased;
165 _ = task.changed() => LogWake::Notified,
166 _ = resync.changed() => LogWake::Resynced,
167 }
168 })
169 }
170
171 /// Wakes the waiters on `key`, if any.
172 pub(crate) fn notify(&self, key: &str) {
173 if let Some(entry) = self.inner.tasks().get(key) {
174 entry.tx.send_modify(|count| *count = count.wrapping_add(1));
175 }
176 }
177
178 /// Wakes every waiter, for a loss of notifications.
179 pub(crate) fn resync(&self) {
180 self.inner
181 .resync
182 .send_modify(|count| *count = count.wrapping_add(1));
183 }
184
185 /// How many keys have a waiter, for a test of cleanup.
186 #[cfg(test)]
187 pub(crate) fn watched(&self) -> usize {
188 self.inner.tasks().len()
189 }
190 }
191}
192
193#[cfg(test)]
194pub mod testing;
195#[cfg(test)]
196mod tests;