a2a_protocol_server/push/request.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! One webhook delivery's request, minus the address it goes to, and how an
5//! attempt's outcome is judged. Moved out of `sender.rs`, which is over the
6//! 500-line limit, when the delivery id was added.
7
8use std::time::Duration;
9
10use a2a_protocol_types::error::{A2aError, A2aResult};
11use a2a_protocol_types::events::StreamResponse;
12use a2a_protocol_types::push::TaskPushNotificationConfig;
13use bytes::Bytes;
14use http_body_util::Full;
15
16use super::sender::{authorization_header, validate_header_value};
17use super::webhook::{
18 DELIVERY_ID_HEADER, NOTIFICATION_TOKEN_HEADER, NOTIFICATION_TOKEN_HEADER_UNPREFIXED,
19};
20
21tokio::task_local! {
22 /// The delivery id the request being prepared is to carry, set by
23 /// [`with_delivery_id`] (the outbox's worker); absent, a new one.
24 static DELIVERY_ID: String;
25}
26
27/// Runs `f` with `id` as the `A2A-Delivery-Id` of the deliveries it makes.
28///
29/// It is the outbox's row id, the same from every replica and across a
30/// restart (ADR 0037). The bundled sender sends it; a custom sender reads it
31/// with [`current_delivery_id`].
32pub async fn with_delivery_id<F: std::future::Future>(id: String, f: F) -> F::Output {
33 DELIVERY_ID.scope(id, f).await
34}
35
36/// The delivery id [`with_delivery_id`] set for the delivery being made, if
37/// any: what a custom [`PushSender`](super::PushSender) sends as
38/// `A2A-Delivery-Id` to keep the outbox's guarantee.
39#[must_use]
40pub fn current_delivery_id() -> Option<String> {
41 DELIVERY_ID.try_with(Clone::clone).ok()
42}
43
44/// What every attempt of one delivery sends: the checked credentials, the
45/// serialised event and the id that tells a receiver two attempts are one
46/// delivery.
47pub(super) struct Prepared {
48 authorization: Option<String>,
49 token: Option<String>,
50 body: Bytes,
51 delivery_id: String,
52}
53
54impl Prepared {
55 /// Checks the config's credentials and serialises `event`.
56 ///
57 /// # Errors
58 ///
59 /// A credential with CR/LF in it, an authentication scheme this sender
60 /// cannot send, or an event that does not serialise.
61 pub(super) fn new(
62 config: &TaskPushNotificationConfig,
63 event: &StreamResponse,
64 ) -> A2aResult<Self> {
65 // Header injection protection: validate credentials.
66 if let Some(ref auth) = config.authentication {
67 if let Some(ref credentials) = auth.credentials {
68 validate_header_value(credentials, "authentication credentials")?;
69 }
70 validate_header_value(&auth.scheme, "authentication scheme")?;
71 }
72 if let Some(ref token) = config.token {
73 validate_header_value(token, "notification token")?;
74 }
75 // Spec §13.2: agents MUST include the credentials
76 // `config.authentication` specifies. One this sender cannot send
77 // refuses the delivery; until 2026-10-23 it delivered without
78 // any `Authorization` header.
79 let authorization = authorization_header(config)?;
80
81 let body = serde_json::to_vec(event)
82 .map(Bytes::from)
83 .map_err(|e| A2aError::internal(format!("push serialization: {e}")))?;
84
85 Ok(Self {
86 authorization,
87 token: config.token.clone(),
88 body,
89 // One per delivery, the same on every attempt of it (audit D-05),
90 // and on every attempt from every replica when the delivery is an
91 // outbox row's (ADR 0037).
92 delivery_id: DELIVERY_ID
93 .try_with(Clone::clone)
94 .unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()),
95 })
96 }
97
98 /// The id sent as `A2A-Delivery-Id`.
99 #[cfg(test)]
100 pub(super) fn delivery_id(&self) -> &str {
101 &self.delivery_id
102 }
103
104 /// The request for one attempt: to `uri` when the caller has rewritten
105 /// the address (with `host` as the `Host` header that goes with it), and
106 /// to `url` as it stands otherwise.
107 pub(super) fn request(
108 &self,
109 url: &str,
110 uri: Option<hyper::Uri>,
111 host: Option<&str>,
112 ) -> A2aResult<hyper::Request<Full<Bytes>>> {
113 // §4.3.3 fixes the webhook request's Content-Type as
114 // `application/a2a+json`, and unlike §9's JSON-RPC binding —
115 // which specifies `application/json` — this one is the A2A
116 // media type. It read `application/json` until 2026-08-30,
117 // from the same stale vendored specification that put six
118 // §5.4 error mappings wrong.
119 //
120 // Named through the constant rather than spelled again: the
121 // REST dispatcher already accepts this media type by the same
122 // name, and a webhook receiver written against §4.3.3 matches
123 // on it.
124 let mut builder = hyper::Request::builder()
125 .method(hyper::Method::POST)
126 .header("content-type", a2a_protocol_types::A2A_CONTENT_TYPE)
127 .header(DELIVERY_ID_HEADER, self.delivery_id.as_str());
128
129 if let Some(uri) = uri {
130 builder = builder.uri(uri);
131 if let Some(host) = host {
132 builder = builder.header("host", host);
133 }
134 } else {
135 builder = builder.uri(url);
136 }
137
138 if let Some(value) = self.authorization.as_deref() {
139 builder = builder.header("authorization", value);
140 }
141
142 // Set the notification token header if present — under both
143 // spellings, the same value in each.
144 //
145 // The specification names no token header: §4.3.3's request
146 // example carries only `Authorization` and `Content-Type`. The
147 // reference SDKs disagree. a2a-sdk (Python) 1.1.5 sends
148 // `headers = {'X-A2A-Notification-Token': push_info.token}`
149 // (`base_push_notification_sender.py`); a2a-go v2.5.0 sends
150 // `http.CanonicalHeaderKey("A2A-Notification-Token")`
151 // (`a2asrv/push/sender.go`). This comment used to say the X-
152 // name is what "official-SDK webhook receivers look for",
153 // which is true of Python and false of Go: a Go webhook read
154 // no token from this sender. 0.8 had dropped the unprefixed
155 // name as this SDK's own invention; it is a2a-go's, so it is
156 // back. Sending both costs one header line, and a receiver
157 // reading either finds the token (`webhook::notification_token`
158 // reads both).
159 if let Some(ref token) = self.token {
160 builder = builder
161 .header(NOTIFICATION_TOKEN_HEADER, token.as_str())
162 .header(NOTIFICATION_TOKEN_HEADER_UNPREFIXED, token.as_str());
163 }
164
165 builder
166 .body(Full::new(self.body.clone()))
167 .map_err(|e| A2aError::internal(format!("push request build: {e}")))
168 }
169}
170
171/// What one attempt came to.
172#[derive(Debug, PartialEq, Eq)]
173pub(super) enum Attempt {
174 /// The webhook answered `2xx`.
175 Delivered,
176 /// The webhook answered in a way no retry will change: the message to
177 /// report and the status it answered with.
178 Rejected { why: String, status: u16 },
179 /// The attempt failed in a way worth another: the message to report if
180 /// none succeeds.
181 Retry(String),
182}
183
184/// Judges an attempt's `result` (a response, a transport error, or the
185/// request timeout), logging a failure against `target`.
186pub(super) fn judge<B>(
187 target: &str,
188 attempt: usize,
189 request_timeout: Duration,
190 result: Result<Result<hyper::Response<B>, impl std::error::Error + 'static>, impl Sized>,
191) -> Attempt {
192 let _ = (target, attempt);
193 match result {
194 Ok(Ok(resp)) if resp.status().is_success() => {
195 trace_debug!(target = %target, "push notification delivered");
196 Attempt::Delivered
197 }
198 Ok(Ok(resp)) => {
199 let status = resp.status();
200 // A non-retryable client error (400/401/403/404/…) will
201 // fail identically on every attempt — retrying it only
202 // hammers the webhook and delays the failure signal.
203 // Retry is reserved for transient statuses: 408
204 // (request timeout), 429 (rate limited), and 5xx.
205 let retryable = status.is_server_error()
206 || status == hyper::StatusCode::REQUEST_TIMEOUT
207 || status == hyper::StatusCode::TOO_MANY_REQUESTS;
208 if !retryable {
209 trace_warn!(target = %target, attempt, status = %status, "push delivery rejected; not retrying");
210 return Attempt::Rejected {
211 why: format!("push notification got non-retryable HTTP {status}"),
212 status: status.as_u16(),
213 };
214 }
215 trace_warn!(target = %target, attempt, status = %status, "push delivery failed");
216 Attempt::Retry(format!("push notification got HTTP {status}"))
217 }
218 Ok(Err(e)) => {
219 trace_warn!(target = %target, attempt, error = %e, "push delivery error");
220 Attempt::Retry(format!(
221 "push notification failed: {}",
222 crate::causes::with_causes(&e)
223 ))
224 }
225 Err(_) => {
226 trace_warn!(target = %target, attempt, "push delivery timed out");
227 Attempt::Retry(format!(
228 "push notification timed out after {}s",
229 request_timeout.as_secs()
230 ))
231 }
232 }
233}
234
235#[cfg(test)]
236mod tests;