Skip to main content

a2a_protocol_server/rpc_span/
stream.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! A streaming call ends when its stream does.
5//!
6//! `docs/rpc/rpc-spans.md` (semantic conventions at `55c98cf`): "For
7//! streaming RPCs, the span SHOULD cover the full lifetime of the request
8//! and/or response streams until they are closed or terminated", and
9//! `rpc-metrics.md` asks that `rpc.server.call.duration` "be the same as the
10//! RPC server span duration". A `SendStreamingMessage` or `SubscribeToTask`
11//! handler returns as soon as the stream is open, so a call recorded when
12//! its handler returned ended at the handshake, reported a stream that later
13//! failed as a success, and never showed a client that went away.
14//!
15//! So the code that forwards a stream to the wire claims the call it runs
16//! for ([`StreamEnd::claim`], [`spanning_stream`]) while it is being set up
17//! inside that call. The call, when its handler returns successfully, hands
18//! itself to the claim rather than recording itself; the stream records it
19//! when it ends — completed, failed with the error its last frame carried,
20//! or abandoned — and re-enters the span as it does, which is what moves the
21//! exported end time (`tracing-opentelemetry` ends a span at its last exit).
22//! The two can finish in either order.
23
24use std::borrow::Cow;
25use std::future::Future;
26use std::sync::{Arc, Mutex, PoisonError};
27use std::time::Instant;
28
29use a2a_protocol_types::error::A2aError;
30
31use super::{CANCELLED, RpcSystem, ServerSpan, WireStatus};
32
33/// How a response stream ended.
34#[derive(Debug)]
35#[non_exhaustive]
36pub enum StreamOutcome {
37    /// It ran to its end: the task's last event was sent.
38    Completed,
39    /// It ended with this error, sent to the peer as its last frame or
40    /// status.
41    Failed(A2aError),
42    /// It stopped before its end: the peer went away, or the server dropped
43    /// it. Recorded as `cancelled`, like a call dropped in flight.
44    Abandoned,
45}
46
47impl StreamOutcome {
48    /// The wire status this outcome records, `None` for success.
49    fn status(&self, system: RpcSystem) -> Option<Cow<'static, str>> {
50        match self {
51            Self::Completed => None,
52            Self::Failed(e) => Some(e.wire_status(system)),
53            Self::Abandoned => Some(Cow::Borrowed(CANCELLED)),
54        }
55    }
56}
57
58tokio::task_local! {
59    /// The call whose future, or whose response-building step, is running;
60    /// `None` for one that cannot answer with a stream.
61    static SLOT: Option<Arc<Slot>>;
62}
63
64/// Where a call and the stream it opened meet.
65#[derive(Debug)]
66pub(super) struct Slot(Mutex<State>);
67
68#[derive(Debug)]
69enum State {
70    /// No stream has claimed the call.
71    Open,
72    /// A stream claimed the call, which is still running.
73    Claimed,
74    /// The stream ended before the call finished.
75    Ended(StreamOutcome),
76    /// The call finished and waits for its stream.
77    Handed(ServerSpan, Instant),
78    /// Recorded.
79    Done,
80}
81
82impl Slot {
83    pub(super) fn new() -> Arc<Self> {
84        Arc::new(Self(Mutex::new(State::Open)))
85    }
86
87    fn state(&self) -> std::sync::MutexGuard<'_, State> {
88        self.0.lock().unwrap_or_else(PoisonError::into_inner)
89    }
90
91    /// The call finished with `status` after `started`: recorded now, or
92    /// when the stream it opened ends.
93    pub(super) fn settle(&self, call: ServerSpan, started: Instant, status: Option<&str>) {
94        let mut state = self.state();
95        match std::mem::replace(&mut *state, State::Done) {
96            // Only a call that succeeded is a stream; a refused one ends here.
97            State::Claimed if status.is_none() => *state = State::Handed(call, started),
98            State::Ended(outcome) => {
99                drop(state);
100                let status = outcome.status(call.system);
101                call.enter(|| call.finish(started.elapsed(), status.as_deref()));
102            }
103            _ => {
104                drop(state);
105                call.finish(started.elapsed(), status);
106            }
107        }
108    }
109}
110
111/// Runs `f` as the call `slot` belongs to, so a stream it sets up can claim
112/// the call.
113pub(super) fn scope<R>(slot: Option<&Arc<Slot>>, f: impl FnOnce() -> R) -> R {
114    SLOT.sync_scope(slot.cloned(), f)
115}
116
117/// A future run as a call's.
118pub(super) type Scoped<F> = tokio::task::futures::TaskLocalFuture<Option<Arc<Slot>>, F>;
119
120/// `fut`, run as the call `slot` belongs to.
121pub(super) fn scope_future<F: Future>(slot: Option<&Arc<Slot>>, fut: F) -> Scoped<F> {
122    SLOT.scope(slot.cloned(), fut)
123}
124
125/// The claim a response stream holds on the call it answers. Dropped
126/// without [`end`](Self::end), the stream was abandoned.
127#[derive(Debug)]
128pub struct StreamEnd(Option<Arc<Slot>>);
129
130impl StreamEnd {
131    /// Claims the call running now, if it can answer with a stream and no
132    /// stream has claimed it yet. Call it while setting the stream up —
133    /// synchronously, inside the call — not from a task spawned for it.
134    pub fn claim() -> Option<Self> {
135        let slot = SLOT.try_with(Option::clone).ok().flatten()?;
136        let mut state = slot.state();
137        if !matches!(*state, State::Open) {
138            return None;
139        }
140        *state = State::Claimed;
141        drop(state);
142        Some(Self(Some(slot)))
143    }
144
145    /// Records how the stream ended, and with it the call.
146    pub fn end(mut self, outcome: StreamOutcome) {
147        if let Some(slot) = self.0.take() {
148            finish(&slot, outcome);
149        }
150    }
151}
152
153impl Drop for StreamEnd {
154    fn drop(&mut self) {
155        if let Some(slot) = self.0.take() {
156            finish(&slot, StreamOutcome::Abandoned);
157        }
158    }
159}
160
161fn finish(slot: &Slot, outcome: StreamOutcome) {
162    let mut state = slot.state();
163    match std::mem::replace(&mut *state, State::Done) {
164        State::Handed(call, started) => {
165            drop(state);
166            let status = outcome.status(call.system);
167            // Entered, so the span's exported end is now.
168            call.enter(|| call.finish(started.elapsed(), status.as_deref()));
169        }
170        State::Claimed => *state = State::Ended(outcome),
171        other => *state = other,
172    }
173}
174
175/// Runs `stream` — a stream's forwarding loop — and records the call it
176/// answers when it ends, with the outcome it returns. Claims the call when
177/// called, so call it inside the call, not inside the task spawned for it.
178pub fn spanning_stream<F>(stream: F) -> impl Future<Output = ()>
179where
180    F: Future<Output = StreamOutcome>,
181{
182    let end = StreamEnd::claim();
183    async move {
184        let outcome = stream.await;
185        if let Some(end) = end {
186            end.end(outcome);
187        }
188    }
189}