Skip to main content

a2a_protocol_server/steering/
inbox.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The inbox of a running turn: where steering messages wait for the executor
5//! to read them (ADR 0036).
6
7use std::collections::VecDeque;
8use std::sync::{Mutex, MutexGuard, PoisonError};
9
10use a2a_protocol_types::message::Message;
11use serde::{Deserialize, Serialize};
12use tokio::sync::Notify;
13
14/// A steering message as the executor receives it: the message, and who sent
15/// it as authentication established.
16///
17/// The text has no more authority than its sender has over the task, which is
18/// the authority of any other message sent to it
19/// ([`docs/injection-containment.md`]): it does not cancel, and it is not an
20/// approval. Treat it as the user text it is.
21///
22/// [`docs/injection-containment.md`]: https://github.com/tomtom215/a2a-rust/blob/main/docs/injection-containment.md
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25#[non_exhaustive]
26pub struct Steered {
27    /// The message, as sent and validated.
28    pub message: Message,
29    /// The caller's authenticated identity
30    /// ([`CallContext::caller_identity`](crate::CallContext::caller_identity)),
31    /// when authentication established one.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub from: Option<String>,
34}
35
36impl Steered {
37    /// A steering message from `from`.
38    #[must_use]
39    pub const fn new(message: Message, from: Option<String>) -> Self {
40        Self { message, from }
41    }
42}
43
44/// Why [`Inbox::try_push`] did not take a message.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum Refused {
48    /// The inbox already holds as many messages as it may.
49    Full,
50    /// The turn the inbox belongs to has ended.
51    Closed,
52}
53
54/// The messages sent to a running turn, oldest first, bounded.
55///
56/// The server holds one per turn when steering is on
57/// ([`RequestContext::inbox`](crate::RequestContext::inbox)) and closes it
58/// when the executor returns. An executor that never reads it is unaffected:
59/// what is in it is dropped with the turn, and counted as `unread`.
60///
61/// Built directly ([`new`](Self::new)) for an executor driven without a
62/// server, as in a test; pass it to the context with
63/// [`RequestContext::with_inbox`](crate::RequestContext::with_inbox).
64///
65/// ```rust
66/// use a2a_protocol_server::{Inbox, Steered};
67/// use a2a_protocol_types::message::Message;
68///
69/// let inbox = Inbox::new(2);
70/// let steered = Steered::new(Message::user_text("m-1", "use the cheaper index"), None);
71/// inbox.try_push(steered.clone()).unwrap();
72/// assert_eq!(inbox.try_recv(), Some(steered));
73/// assert_eq!(inbox.try_recv(), None);
74/// ```
75#[derive(Debug)]
76pub struct Inbox {
77    capacity: usize,
78    state: Mutex<State>,
79    ready: Notify,
80}
81
82#[derive(Debug, Default)]
83struct State {
84    queue: VecDeque<Steered>,
85    closed: bool,
86}
87
88impl Inbox {
89    /// An empty inbox that holds at most `capacity` messages.
90    #[must_use]
91    pub fn new(capacity: usize) -> Self {
92        Self {
93            capacity,
94            state: Mutex::new(State::default()),
95            ready: Notify::new(),
96        }
97    }
98
99    fn lock(&self) -> MutexGuard<'_, State> {
100        self.state.lock().unwrap_or_else(PoisonError::into_inner)
101    }
102
103    /// Adds `steered` at the end, waking a reader waiting in
104    /// [`recv`](Self::recv). Never waits.
105    ///
106    /// # Errors
107    ///
108    /// [`Refused::Closed`] once the turn has ended, [`Refused::Full`] when the
109    /// inbox holds its capacity. Nothing is added then.
110    pub fn try_push(&self, steered: Steered) -> Result<(), Refused> {
111        let mut state = self.lock();
112        if state.closed {
113            return Err(Refused::Closed);
114        }
115        if state.queue.len() >= self.capacity {
116            return Err(Refused::Full);
117        }
118        state.queue.push_back(steered);
119        drop(state);
120        self.ready.notify_one();
121        Ok(())
122    }
123
124    /// The oldest message, if there is one. Never waits.
125    #[must_use]
126    pub fn try_recv(&self) -> Option<Steered> {
127        self.lock().queue.pop_front()
128    }
129
130    /// The oldest message, waiting for one to arrive; `None` once the turn
131    /// has ended and nothing is left. Safe to cancel: a message is taken only
132    /// when this returns it.
133    pub async fn recv(&self) -> Option<Steered> {
134        loop {
135            {
136                let mut state = self.lock();
137                if let Some(steered) = state.queue.pop_front() {
138                    return Some(steered);
139                }
140                if state.closed {
141                    return None;
142                }
143            }
144            // A permit stored by a push or a close that came after the check
145            // above is taken here, so nothing is missed between the two.
146            self.ready.notified().await;
147        }
148    }
149
150    /// How many messages wait.
151    #[must_use]
152    pub fn len(&self) -> usize {
153        self.lock().queue.len()
154    }
155
156    /// Whether no message waits.
157    #[must_use]
158    pub fn is_empty(&self) -> bool {
159        self.lock().queue.is_empty()
160    }
161
162    /// Ends the inbox: later pushes are refused as [`Refused::Closed`], and a
163    /// reader waiting in [`recv`](Self::recv) is woken. What is already in it
164    /// can still be read. Returns how many messages were left unread.
165    pub fn close(&self) -> usize {
166        let mut state = self.lock();
167        state.closed = true;
168        let unread = state.queue.len();
169        drop(state);
170        self.ready.notify_waiters();
171        self.ready.notify_one();
172        unread
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use std::sync::Arc;
179    use std::time::Duration;
180
181    use super::*;
182
183    fn steered(id: &str) -> Steered {
184        Steered::new(Message::user_text(id, id), Some("alice".to_owned()))
185    }
186
187    fn id(steered: &Steered) -> String {
188        steered.message.id.0.clone()
189    }
190
191    #[test]
192    fn messages_come_out_in_the_order_they_went_in() {
193        let inbox = Inbox::new(3);
194        for m in ["a", "b", "c"] {
195            inbox.try_push(steered(m)).expect("room");
196        }
197        let order: Vec<String> = std::iter::from_fn(|| inbox.try_recv())
198            .map(|s| id(&s))
199            .collect();
200        assert_eq!(order, ["a", "b", "c"]);
201        assert_eq!(inbox.try_recv(), None);
202    }
203
204    /// One below, at and past the capacity, with the exact refusal each time.
205    #[test]
206    fn the_inbox_takes_its_capacity_and_not_one_more() {
207        let inbox = Inbox::new(2);
208        assert_eq!(inbox.try_push(steered("a")), Ok(()));
209        assert_eq!(inbox.len(), 1);
210        assert_eq!(inbox.try_push(steered("b")), Ok(()));
211        assert_eq!(inbox.len(), 2);
212        assert_eq!(inbox.try_push(steered("c")), Err(Refused::Full));
213        assert_eq!(inbox.len(), 2, "a refused message is not kept");
214        // Reading one makes room for exactly one.
215        assert_eq!(inbox.try_recv().map(|s| id(&s)).as_deref(), Some("a"));
216        assert_eq!(inbox.try_push(steered("d")), Ok(()));
217        assert_eq!(inbox.try_push(steered("e")), Err(Refused::Full));
218    }
219
220    #[test]
221    fn an_inbox_of_nothing_refuses_everything() {
222        let inbox = Inbox::new(0);
223        assert_eq!(inbox.try_push(steered("a")), Err(Refused::Full));
224        assert!(inbox.is_empty());
225    }
226
227    #[test]
228    fn len_and_is_empty_say_how_many_wait() {
229        let inbox = Inbox::new(5);
230        assert_eq!((inbox.len(), inbox.is_empty()), (0, true));
231        inbox.try_push(steered("a")).expect("room");
232        assert_eq!((inbox.len(), inbox.is_empty()), (1, false));
233        inbox.try_push(steered("b")).expect("room");
234        inbox.try_push(steered("c")).expect("room");
235        assert_eq!((inbox.len(), inbox.is_empty()), (3, false));
236    }
237
238    #[test]
239    fn closing_refuses_later_messages_and_reports_the_unread() {
240        let inbox = Inbox::new(5);
241        inbox.try_push(steered("a")).expect("room");
242        inbox.try_push(steered("b")).expect("room");
243        assert_eq!(inbox.close(), 2);
244        assert_eq!(inbox.try_push(steered("c")), Err(Refused::Closed));
245        assert_eq!(inbox.len(), 2, "a refused message is not kept");
246        // What was there can still be read.
247        assert_eq!(inbox.try_recv().map(|s| id(&s)).as_deref(), Some("a"));
248        assert_eq!(inbox.close(), 1, "closing again reports what is left");
249    }
250
251    /// A closed inbox that is also full says it is closed.
252    #[test]
253    fn closed_is_reported_before_full() {
254        let inbox = Inbox::new(1);
255        inbox.try_push(steered("a")).expect("room");
256        inbox.close();
257        assert_eq!(inbox.try_push(steered("b")), Err(Refused::Closed));
258    }
259
260    #[tokio::test(start_paused = true)]
261    async fn recv_waits_for_a_message_and_takes_it() {
262        let inbox = Arc::new(Inbox::new(2));
263        let mut reader = {
264            let inbox = Arc::clone(&inbox);
265            tokio::spawn(async move { inbox.recv().await })
266        };
267        // Nothing is there yet: with the clock paused, a second passes at
268        // once and the reader is still waiting.
269        let waiting = tokio::time::timeout(Duration::from_secs(1), &mut reader).await;
270        assert!(waiting.is_err(), "recv returned with nothing to return");
271        inbox.try_push(steered("late")).expect("room");
272        let got = reader.await.expect("joins");
273        assert_eq!(got.map(|s| id(&s)).as_deref(), Some("late"));
274        assert!(inbox.is_empty(), "the message was taken, not copied");
275    }
276
277    #[tokio::test]
278    async fn recv_returns_what_is_already_there_without_waiting() {
279        let inbox = Inbox::new(2);
280        inbox.try_push(steered("a")).expect("room");
281        assert_eq!(inbox.recv().await.map(|s| id(&s)).as_deref(), Some("a"));
282    }
283
284    #[tokio::test]
285    async fn close_wakes_a_waiting_reader_with_none() {
286        let inbox = Arc::new(Inbox::new(2));
287        let reader = {
288            let inbox = Arc::clone(&inbox);
289            tokio::spawn(async move { inbox.recv().await })
290        };
291        // The reader may or may not be waiting yet; the answer is the same.
292        assert_eq!(inbox.close(), 0);
293        let got = tokio::time::timeout(Duration::from_secs(10), reader)
294            .await
295            .expect("a closed inbox does not leave a reader waiting")
296            .expect("joins");
297        assert_eq!(got, None);
298    }
299
300    #[tokio::test]
301    async fn a_closed_inbox_hands_out_what_is_left_then_none() {
302        let inbox = Inbox::new(2);
303        inbox.try_push(steered("a")).expect("room");
304        inbox.close();
305        assert_eq!(inbox.recv().await.map(|s| id(&s)).as_deref(), Some("a"));
306        assert_eq!(inbox.recv().await, None);
307    }
308
309    #[tokio::test(start_paused = true)]
310    async fn a_recv_that_is_dropped_takes_nothing() {
311        let inbox = Inbox::new(2);
312        let timed_out = tokio::time::timeout(Duration::from_secs(1), inbox.recv()).await;
313        assert!(timed_out.is_err());
314        inbox.try_push(steered("a")).expect("room");
315        assert_eq!(inbox.len(), 1);
316        assert_eq!(inbox.recv().await.map(|s| id(&s)).as_deref(), Some("a"));
317    }
318
319    #[test]
320    fn a_message_serializes_with_its_sender_and_reads_back() {
321        let with = steered("a");
322        let wire = serde_json::to_value(&with).expect("serializes");
323        assert_eq!(wire["from"], "alice");
324        assert_eq!(wire["message"]["messageId"], "a");
325        assert_eq!(
326            serde_json::from_value::<Steered>(wire).expect("reads"),
327            with
328        );
329
330        let anonymous = Steered::new(Message::user_text("b", "b"), None);
331        let wire = serde_json::to_value(&anonymous).expect("serializes");
332        assert!(wire.get("from").is_none(), "no sender, no key: {wire}");
333        assert_eq!(
334            serde_json::from_value::<Steered>(wire).expect("reads"),
335            anonymous
336        );
337    }
338}