Skip to main content

a2a_protocol_server/rpc_span/
binding.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The per-call span and metric for a binding implemented outside this
5//! crate, such as `a2a-protocol-slimrpc` (ADR 0013, decision 2: "an RPC
6//! `SERVER` span per A2A method on every binding").
7//!
8//! The bindings in this crate open a [`ServerSpan`] directly. It stays
9//! private, with the per-binding status mapping beside it, so what is public
10//! is only what a binding outside needs: its own `rpc.system.name`, the
11//! status it sends for each [`ServerError`], and the call to run.
12
13use std::borrow::Cow;
14use std::collections::HashMap;
15use std::future::Future;
16
17use super::{RpcSystem, ServerSpan};
18use crate::RequestHandler;
19use crate::error::{ServerError, ServerResult};
20
21/// How a binding outside this crate names itself on its spans and in
22/// `rpc.server.call.duration`.
23#[derive(Clone, Copy)]
24pub struct CustomBinding {
25    pub(super) name: &'static str,
26    pub(super) ok_status: Option<&'static str>,
27    pub(super) error_status: fn(&ServerError) -> Cow<'static, str>,
28    pub(super) server_error: fn(&str) -> bool,
29}
30
31/// A custom binding's default rule: every failure is a server error.
32const fn every_status(_: &str) -> bool {
33    true
34}
35
36impl CustomBinding {
37    /// A binding whose `rpc.system.name` is `name` and which sends
38    /// `error_status(e)` as the status of a call that failed with `e`.
39    ///
40    /// `name` should be the binding's own name in lower case
41    /// (`"slimrpc"`): the semantic conventions name only a few RPC systems
42    /// and let others use "a custom value". `error_status` is recorded as
43    /// `rpc.status_code` and `error.type`, so it should be the binding's
44    /// error mapping itself rather than a second copy of it, or the metric
45    /// can disagree with what the peer received.
46    #[must_use]
47    pub const fn new(
48        name: &'static str,
49        error_status: fn(&ServerError) -> Cow<'static, str>,
50    ) -> Self {
51        Self {
52            name,
53            ok_status: None,
54            error_status,
55            server_error: every_status,
56        }
57    }
58
59    /// Counts a failure as an error on the span and in the metric — sets
60    /// `error.type` and `Error` status — only for gRPC's server-side
61    /// statuses (`UNKNOWN`, `DEADLINE_EXCEEDED`, `UNIMPLEMENTED`, `INTERNAL`,
62    /// `UNAVAILABLE`, `DATA_LOSS`), as the semantic conventions' gRPC server
63    /// span does, for a binding whose `error_status` returns gRPC status
64    /// names. Any other status is still recorded as `rpc.status_code`.
65    /// Without it every failure is an error, as before this existed.
66    #[must_use]
67    pub const fn with_grpc_server_errors(mut self) -> Self {
68        self.server_error = super::names::grpc_server_error;
69        self
70    }
71
72    /// The status a successful call sends, for a binding that sends one —
73    /// `"OK"` for one with gRPC's status codes. Without it a successful
74    /// call records no `rpc.status_code`, as on JSON-RPC.
75    #[must_use]
76    pub const fn with_ok_status(mut self, status: &'static str) -> Self {
77        self.ok_status = Some(status);
78        self
79    }
80}
81
82impl std::fmt::Debug for CustomBinding {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("CustomBinding")
85            .field("name", &self.name)
86            .field("ok_status", &self.ok_status)
87            .finish_non_exhaustive()
88    }
89}
90
91/// One inbound call on a binding outside this crate: the `SERVER` span it
92/// runs in, and its `rpc.server.call.duration`, exactly as the bindings in
93/// this crate record theirs.
94///
95/// The span is named `lf.a2a.v1.A2AService/{Method}` and carries the A2A
96/// attributes; the handler's
97/// [`InboundTracePolicy`](crate::InboundTracePolicy) decides whether a
98/// `traceparent` among the call's headers becomes its parent; the duration
99/// goes to the handler's [`Metrics`](crate::Metrics), failed calls with the
100/// binding's own status. Open it after the request has decoded, and run the
101/// `RequestHandler` call inside it:
102///
103/// ```rust,no_run
104/// # use std::borrow::Cow;
105/// # use std::collections::HashMap;
106/// # use a2a_protocol_server::{BindingSpan, CustomBinding, RequestHandler, ServerError};
107/// # use a2a_protocol_types::params::TaskQueryParams;
108/// const MY_BINDING: CustomBinding =
109///     CustomBinding::new("mybinding", |e: &ServerError| {
110///         Cow::Owned(e.to_a2a_error().code.as_i32().to_string())
111///     });
112///
113/// # async fn call(handler: &RequestHandler, params: TaskQueryParams, headers: HashMap<String, String>) {
114/// let task = BindingSpan::open(handler, MY_BINDING, "GetTask", Some(&headers))
115///     .run(handler.on_get_task(params, Some(&headers)))
116///     .await;
117/// # }
118/// ```
119#[derive(Debug)]
120pub struct BindingSpan(ServerSpan);
121
122impl BindingSpan {
123    /// Opens the span for one call of `method` — the A2A method as the gRPC
124    /// service spells it (`"GetTask"`); one this crate does not know is
125    /// recorded as `_OTHER`, so a peer's string never becomes a span name or
126    /// a metric attribute.
127    #[must_use]
128    pub fn open(
129        handler: &RequestHandler,
130        binding: CustomBinding,
131        method: &str,
132        headers: Option<&HashMap<String, String>>,
133    ) -> Self {
134        Self(ServerSpan::open(
135            handler,
136            RpcSystem::Custom(binding),
137            method,
138            headers,
139        ))
140    }
141
142    /// Runs `fut` inside the span, then records the call: its duration and,
143    /// for an `Err`, the binding's status for it. A call whose future is
144    /// dropped first is recorded as failed with `error.type` `cancelled`.
145    pub fn run<T, F>(self, fut: F) -> impl Future<Output = ServerResult<T>>
146    where
147        F: Future<Output = ServerResult<T>>,
148    {
149        self.0.call(fut, super::failed_with, |out| out, false)
150    }
151
152    /// [`run`](Self::run), then `then` on the outcome, inside the call: for
153    /// a call that answers with a stream. A stream `then` sets up claims the
154    /// call with [`StreamEnd::claim`](crate::StreamEnd::claim); a successful
155    /// call is then recorded when the stream ends, with the
156    /// [`StreamOutcome`](crate::StreamOutcome) passed to
157    /// [`StreamEnd::end`](crate::StreamEnd::end) — or as `cancelled` if the
158    /// claim is dropped first — so its span and duration cover the stream,
159    /// as the semantic conventions ask of a streaming call.
160    pub fn run_with<T, F, R>(
161        self,
162        fut: F,
163        then: impl FnOnce(ServerResult<T>) -> R,
164    ) -> impl Future<Output = R>
165    where
166        F: Future<Output = ServerResult<T>>,
167    {
168        self.0.call(fut, super::failed_with, then, true)
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use std::sync::{Arc, Mutex};
175
176    use super::*;
177    use crate::{Metrics, RpcCall};
178
179    /// System, method, status code and error type of each call.
180    type Calls = Arc<Mutex<Vec<[Option<String>; 4]>>>;
181
182    struct Recording(Calls);
183
184    impl Metrics for Recording {
185        fn on_rpc_call(&self, call: &RpcCall<'_>) {
186            self.0.lock().unwrap().push([
187                Some(call.system.to_owned()),
188                call.method.map(str::to_owned),
189                call.status_code.map(str::to_owned),
190                call.error_type.map(str::to_owned),
191            ]);
192        }
193    }
194
195    fn handler(calls: &Calls) -> RequestHandler {
196        struct Idle;
197        crate::agent_executor!(Idle, |_ctx, _queue| async { Ok(()) });
198        crate::RequestHandlerBuilder::new(Idle)
199            .without_agent_card()
200            .with_metrics(Recording(Arc::clone(calls)))
201            .build()
202            .unwrap()
203    }
204
205    const CODES: CustomBinding = CustomBinding::new("codes", |e| {
206        Cow::Owned(format!("E{}", e.to_a2a_error().code.as_i32()))
207    });
208
209    fn strings<const N: usize>(row: [Option<&str>; N]) -> [Option<String>; N] {
210        row.map(|s| s.map(str::to_owned))
211    }
212
213    /// A call is recorded under the binding's own name, a failure with the
214    /// binding's own status, and a success with no status unless the
215    /// binding sends one.
216    #[tokio::test]
217    async fn calls_are_recorded_with_the_bindings_name_and_statuses() {
218        let calls = Calls::default();
219        let handler = handler(&calls);
220        let _ = BindingSpan::open(&handler, CODES, "GetTask", None)
221            .run(async { Err::<(), _>(ServerError::TaskNotFound("t".into())) })
222            .await;
223        let _ = BindingSpan::open(&handler, CODES, "ListTasks", None)
224            .run(async { Ok::<_, ServerError>(()) })
225            .await;
226        let _ = BindingSpan::open(&handler, CODES.with_ok_status("FINE"), "Nonsense", None)
227            .run(async { Ok::<_, ServerError>(()) })
228            .await;
229        assert_eq!(
230            *calls.lock().unwrap(),
231            [
232                strings([
233                    Some("codes"),
234                    Some("lf.a2a.v1.A2AService/GetTask"),
235                    Some("E-32001"),
236                    Some("E-32001")
237                ]),
238                strings([
239                    Some("codes"),
240                    Some("lf.a2a.v1.A2AService/ListTasks"),
241                    None,
242                    None
243                ]),
244                strings([Some("codes"), Some("_OTHER"), Some("FINE"), None]),
245            ]
246        );
247    }
248
249    #[test]
250    fn debug_shows_the_name_and_ok_status() {
251        let shown = format!("{:?}", CODES.with_ok_status("OK"));
252        assert!(
253            shown.contains("\"codes\"") && shown.contains("\"OK\""),
254            "{shown}"
255        );
256    }
257}