a2a_protocol_client/delegation/journal.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! A delegation's record in a [`DelegationJournal`] (ADR 0030).
5//!
6//! The record is written before the child's message is sent, so a supervisor
7//! that dies between "sent" and "heard back" leaves something to find. The
8//! child's id and stream position follow as they become known, and the
9//! record is settled when the delegation ends, however it ends.
10
11use std::sync::Arc;
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use a2a_protocol_types::MessageSendParams;
15use a2a_protocol_types::delegation_journal::{DelegationJournal, DelegationRecord};
16use tokio::time::Instant;
17
18use super::{Delegation, DelegationOptions, Outcome};
19use crate::client::A2aClient;
20use crate::error::{ClientError, ClientResult};
21
22/// The longest a recorded position lags the stream, apart from the moment the
23/// child is first named and the moment the stream is lost, which are written
24/// at once.
25const PROGRESS_EVERY: Duration = Duration::from_secs(2);
26
27/// The longest one write to the journal may hold up the delegation (audit
28/// NEW-h-s0-3). The writes are awaited on the path events are read from, so
29/// a journal database that stops answering would otherwise stop every
30/// delegation of the supervisor, and the children's servers would see
31/// slow consumers. A write that does not answer in this time is given up on
32/// and logged, as one that fails is, and the next is tried after
33/// [`PROGRESS_EVERY`].
34pub(super) const WRITE_BOUND: Duration = Duration::from_secs(5);
35
36/// What a delegation knows about its journal record.
37pub(super) struct Journaled {
38 journal: Arc<dyn DelegationJournal>,
39 id: String,
40 noted_task: Option<String>,
41 noted_position: Option<String>,
42 last_write: Option<Instant>,
43 /// After a write failed or timed out, when the next may be tried.
44 retry_at: Option<Instant>,
45}
46
47impl std::fmt::Debug for Journaled {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 f.debug_struct("Journaled")
50 .field("id", &self.id)
51 .finish_non_exhaustive()
52 }
53}
54
55impl Journaled {
56 fn new(journal: Arc<dyn DelegationJournal>, id: String) -> Self {
57 Self {
58 journal,
59 id,
60 noted_task: None,
61 noted_position: None,
62 last_write: None,
63 retry_at: None,
64 }
65 }
66}
67
68/// Records the delegation before its message is sent. A journal that does
69/// not answer within [`WRITE_BOUND`] is an error, and nothing is sent.
70pub(super) async fn begin(
71 journal: &dyn DelegationJournal,
72 record: &DelegationRecord,
73) -> ClientResult<()> {
74 tokio::time::timeout(WRITE_BOUND, journal.begin(record))
75 .await
76 .map_or_else(
77 |_| {
78 Err(ClientError::Timeout(format!(
79 "the delegation journal did not record the delegation within \
80 {WRITE_BOUND:?}; nothing was sent"
81 )))
82 },
83 |written| written.map_err(ClientError::Protocol),
84 )
85}
86
87/// Unix milliseconds now; `0` if the clock is before the epoch.
88pub(super) fn now_ms() -> i64 {
89 SystemTime::now()
90 .duration_since(UNIX_EPOCH)
91 .ok()
92 .and_then(|d| i64::try_from(d.as_millis()).ok())
93 .unwrap_or(0)
94}
95
96/// The short label a journal stores for how a delegation ended.
97pub(super) const fn label(outcome: &Outcome) -> &'static str {
98 match outcome {
99 Outcome::Completed(_) => "completed",
100 Outcome::Failed { .. } => "failed",
101 Outcome::Canceled(_) => "canceled",
102 Outcome::Interrupted(_) => "interrupted",
103 Outcome::Message(_) => "message",
104 Outcome::Lost(_) => "lost",
105 Outcome::Unreachable => "unreachable",
106 Outcome::CancelRequested(_) => "cancel_requested",
107 Outcome::CancelFailed(_) => "cancel_failed",
108 Outcome::HandedOff => "handed_off",
109 }
110}
111
112/// A new record for a delegation about to be sent: owned by `owner`, naming
113/// `agent`, with the message's tenant and idempotency key.
114pub(super) fn new_record(
115 owner: impl Into<String>,
116 agent: impl Into<String>,
117 tenant: Option<String>,
118 key: Option<String>,
119) -> DelegationRecord {
120 DelegationRecord::new(uuid::Uuid::new_v4().to_string(), owner, agent, now_ms())
121 .with_tenant(tenant)
122 .with_idempotency_key(key)
123}
124
125impl Delegation {
126 /// [`start`](Self::start), recorded in `journal` first.
127 ///
128 /// The record (owner, the agent's URL, the tenant, the message's
129 /// idempotency key) is written **before** the message is sent. If the
130 /// journal cannot store it, nothing is sent. The child's id and stream
131 /// position are noted as events arrive, at most every two seconds, and
132 /// the record is settled with the delegation's outcome when it ends.
133 ///
134 /// A supervisor that restarts lists its open records
135 /// ([`DelegationJournal::open`]) and picks each up: with
136 /// [`reattach`](Self::reattach) and [`with_journal`](Self::with_journal)
137 /// when the record names the child, or by sending the same message again
138 /// under the record's idempotency key when it does not. The key is
139 /// recorded only when the message carries one, which [`start`](Self::start)
140 /// adds for an agent known to honour keys; set one on the message for any
141 /// other.
142 ///
143 /// # Errors
144 ///
145 /// As [`start`](Self::start); also the journal's error, as
146 /// [`ClientError::Protocol`], when the record cannot be written. When the
147 /// agent refuses the request the record is settled `not_started`: no
148 /// child exists.
149 pub async fn start_journaled(
150 client: Arc<A2aClient>,
151 params: MessageSendParams,
152 journal: Arc<dyn DelegationJournal>,
153 owner: impl Into<String> + Send,
154 agent: impl Into<String> + Send,
155 ) -> ClientResult<Self> {
156 let options = DelegationOptions::new().with_journal(journal, owner, agent);
157 Self::start_with(client, params, options).await
158 }
159
160 /// Keeps `record_id`, a record in `journal`, up to date from here on:
161 /// for a delegation picked up with [`reattach`](Self::reattach) from a
162 /// record [`DelegationJournal::open`] listed.
163 #[must_use]
164 pub fn with_journal(
165 mut self,
166 journal: Arc<dyn DelegationJournal>,
167 record_id: impl Into<String>,
168 ) -> Self {
169 self.journal = Some(Journaled::new(journal, record_id.into()));
170 self
171 }
172
173 /// The id of this delegation's journal record, if it has one.
174 #[must_use]
175 pub fn journal_id(&self) -> Option<&str> {
176 self.journal.as_ref().map(|j| j.id.as_str())
177 }
178
179 /// Writes the child's id and position if they moved: at once when `force`
180 /// or when the child was just named, otherwise at most every
181 /// [`PROGRESS_EVERY`]. A write that fails or does not answer within
182 /// [`WRITE_BOUND`] is logged and dropped, and none is tried again for
183 /// [`PROGRESS_EVERY`] unless `force`: the delegation matters more than
184 /// its record.
185 pub(super) async fn note_progress(&mut self, force: bool) {
186 self.write_progress(force, Instant::now() + WRITE_BOUND)
187 .await;
188 }
189
190 /// [`note_progress`](Self::note_progress), given up on at `deadline`.
191 async fn write_progress(&mut self, force: bool, deadline: Instant) {
192 let Some(j) = self.journal.as_mut() else {
193 return;
194 };
195 let task_moved = self.task_id != j.noted_task;
196 let position_moved = self.last_event_id != j.noted_position;
197 if !task_moved && !position_moved {
198 return;
199 }
200 let ripe = task_moved || j.last_write.is_none_or(|at| at.elapsed() >= PROGRESS_EVERY);
201 let waiting = j.retry_at.is_some_and(|at| Instant::now() < at);
202 if !force && (!ripe || waiting) {
203 return;
204 }
205 let written = tokio::time::timeout_at(
206 deadline,
207 j.journal.progress(
208 &j.id,
209 self.task_id.as_deref(),
210 self.last_event_id.as_deref(),
211 now_ms(),
212 ),
213 )
214 .await;
215 match written {
216 Ok(Ok(())) => {
217 j.noted_task.clone_from(&self.task_id);
218 j.noted_position.clone_from(&self.last_event_id);
219 j.last_write = Some(Instant::now());
220 }
221 Ok(Err(_e)) => {
222 j.retry_at = Some(Instant::now() + PROGRESS_EVERY);
223 trace_warn!(record = %j.id, error = %_e, "delegation journal: progress not recorded");
224 }
225 Err(_) => {
226 j.retry_at = Some(Instant::now() + PROGRESS_EVERY);
227 trace_warn!(record = %j.id, "delegation journal: progress not recorded in time");
228 }
229 }
230 }
231
232 /// Settles the record with `outcome`. A write that fails or does not
233 /// answer is logged: the record stays open, and a restarted supervisor
234 /// will find the child already settled when it reattaches. The two writes
235 /// at the end, the last position and the outcome, share one deadline of
236 /// [`WRITE_BOUND`] from the start, so a journal that has stopped answering
237 /// holds the delegation up for that long and no longer; a journal that
238 /// answers the outcome after a position that timed out still settles.
239 pub(super) async fn note_settled(&mut self, outcome: &Outcome) {
240 let deadline = Instant::now() + WRITE_BOUND;
241 self.write_progress(true, deadline).await;
242 let Some(j) = self.journal.take() else {
243 return;
244 };
245 match tokio::time::timeout_at(deadline, j.journal.settle(&j.id, label(outcome), now_ms()))
246 .await
247 {
248 Ok(Ok(())) => {}
249 Ok(Err(_e)) => {
250 trace_warn!(record = %j.id, error = %_e, "delegation journal: outcome not recorded");
251 }
252 Err(_) => {
253 trace_warn!(record = %j.id, "delegation journal: outcome not recorded in time");
254 }
255 }
256 }
257}
258
259#[cfg(test)]
260mod tests;