a2a_protocol_server/dispatch/
mod.rs1#[cfg(feature = "axum")]
10pub mod axum_adapter;
11pub mod combined;
12#[cfg(any(feature = "websocket", feature = "grpc"))]
13pub(crate) mod connection_limit;
14pub mod cors;
15#[cfg(feature = "grpc")]
16pub mod grpc;
17pub mod hsts;
18pub mod jsonrpc;
19mod peer;
20pub mod rest;
21mod version;
22#[cfg(feature = "websocket")]
23pub mod websocket;
24#[cfg(any(feature = "websocket", feature = "grpc"))]
25mod well_known;
26
27pub use combined::CombinedDispatcher;
28pub use cors::CorsConfig;
29#[cfg(feature = "grpc")]
30pub use grpc::{GrpcConfig, GrpcDispatcher};
31pub use hsts::Hsts;
32pub use jsonrpc::JsonRpcDispatcher;
33pub(crate) use peer::{
34 card_connection, certificate_of, peer_of, record_peer_addr, record_peer_certificate,
35};
36pub use rest::RestDispatcher;
37pub use version::{A2A_VERSION_METADATA_KEY, validate_version_metadata};
38pub(crate) use version::{requested_version, validate_version_header};
39#[cfg(feature = "websocket")]
40pub use websocket::{WebSocketDispatcher, WebSocketUpgrades};
41
42#[derive(Debug, Clone)]
62#[non_exhaustive]
63pub struct DispatchConfig {
64 pub max_request_body_size: usize,
66 pub body_read_timeout: std::time::Duration,
68 pub max_query_string_length: usize,
77 pub sse_keep_alive_interval: std::time::Duration,
82 pub sse_channel_capacity: usize,
87 pub max_batch_size: usize,
92 pub require_version_header: bool,
102 pub agent_card_max_age: u32,
106 pub base_path: Option<String>,
113}
114
115pub(crate) const DEFAULT_AGENT_CARD_MAX_AGE: u32 = 3600;
119
120impl Default for DispatchConfig {
121 fn default() -> Self {
122 Self {
123 max_request_body_size: 4 * 1024 * 1024,
124 body_read_timeout: std::time::Duration::from_secs(30),
125 max_query_string_length: 4096,
126 sse_keep_alive_interval: std::time::Duration::from_secs(30),
127 sse_channel_capacity: 64,
128 max_batch_size: 100,
129 require_version_header: true,
130 agent_card_max_age: DEFAULT_AGENT_CARD_MAX_AGE,
131 base_path: None,
132 }
133 }
134}
135
136impl DispatchConfig {
137 #[must_use]
139 pub const fn with_max_request_body_size(mut self, size: usize) -> Self {
140 self.max_request_body_size = size;
141 self
142 }
143
144 #[must_use]
146 pub const fn with_body_read_timeout(mut self, timeout: std::time::Duration) -> Self {
147 self.body_read_timeout = timeout;
148 self
149 }
150
151 #[must_use]
153 pub const fn with_max_query_string_length(mut self, length: usize) -> Self {
154 self.max_query_string_length = length;
155 self
156 }
157
158 #[must_use]
160 pub const fn with_sse_keep_alive_interval(mut self, interval: std::time::Duration) -> Self {
161 self.sse_keep_alive_interval = interval;
162 self
163 }
164
165 #[must_use]
167 pub const fn with_sse_channel_capacity(mut self, capacity: usize) -> Self {
168 self.sse_channel_capacity = capacity;
169 self
170 }
171
172 #[must_use]
174 pub const fn with_max_batch_size(mut self, size: usize) -> Self {
175 self.max_batch_size = size;
176 self
177 }
178
179 #[must_use]
184 pub const fn with_require_version_header(mut self, require: bool) -> Self {
185 self.require_version_header = require;
186 self
187 }
188
189 #[must_use]
197 pub const fn accept_missing_version_header(mut self) -> Self {
198 self.require_version_header = false;
199 self
200 }
201
202 #[must_use]
205 pub const fn with_agent_card_max_age(mut self, seconds: u32) -> Self {
206 self.agent_card_max_age = seconds;
207 self
208 }
209}
210
211mod base_path;
212pub(crate) use base_path::strip_base_path;
213
214pub(crate) fn check_request_content_type(
227 method: &hyper::Method,
228 headers: &hyper::HeaderMap,
229) -> Result<(), a2a_protocol_types::error::A2aError> {
230 if !matches!(
231 *method,
232 hyper::Method::POST | hyper::Method::PUT | hyper::Method::PATCH
233 ) {
234 return Ok(());
235 }
236 unsupported_content_type(headers).map_or(Ok(()), Err)
237}
238
239pub(crate) fn unsupported_content_type(
249 headers: &hyper::HeaderMap,
250) -> Option<a2a_protocol_types::error::A2aError> {
251 let Some(ct) = headers.get(hyper::header::CONTENT_TYPE) else {
252 return has_body(headers).then(|| {
253 a2a_protocol_types::error::A2aError::content_type_not_supported(
254 "a request body needs Content-Type: application/json or application/a2a+json",
255 )
256 });
257 };
258 let ct = ct.to_str().unwrap_or("");
259 let essence = rest::media_type::essence(ct);
260 let json = essence.eq_ignore_ascii_case("application/json")
261 || essence.eq_ignore_ascii_case(a2a_protocol_types::A2A_CONTENT_TYPE);
262 (!json).then(|| {
263 a2a_protocol_types::error::A2aError::content_type_not_supported(format!(
264 "unsupported Content-Type: {ct}; expected application/json or application/a2a+json"
265 ))
266 })
267}
268
269fn has_body(headers: &hyper::HeaderMap) -> bool {
273 headers.contains_key(hyper::header::TRANSFER_ENCODING)
274 || headers
275 .get(hyper::header::CONTENT_LENGTH)
276 .is_some_and(|len| len.as_bytes() != b"0")
277}
278
279pub(crate) fn add_auth_challenge(headers: &mut hyper::HeaderMap, err: &crate::error::ServerError) {
283 let Some(challenge) = err.challenge() else {
284 return;
285 };
286 let value = hyper::header::HeaderValue::from_str(challenge).unwrap_or_else(|_| {
290 trace_warn!(%challenge, "auth challenge is not a valid header value; sending `Bearer`");
291 hyper::header::HeaderValue::from_static("Bearer")
292 });
293 headers.insert(hyper::header::WWW_AUTHENTICATE, value);
294}
295
296pub(crate) fn header_fields(
304 headers: &hyper::HeaderMap,
305) -> std::collections::HashMap<String, String> {
306 headers
307 .keys()
308 .filter_map(|name| {
309 Some((
310 name.as_str().to_owned(),
311 field_value(headers, name.as_str())?,
312 ))
313 })
314 .collect()
315}
316
317pub(crate) fn field_value(headers: &hyper::HeaderMap, name: &str) -> Option<String> {
322 let separator = if name.eq_ignore_ascii_case("cookie") {
323 "; "
324 } else {
325 ", "
326 };
327 let lines: Vec<&str> = headers
328 .get_all(name)
329 .iter()
330 .filter_map(|line| line.to_str().ok())
331 .collect();
332 (!lines.is_empty()).then(|| lines.join(separator))
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use std::time::Duration;
339
340 fn lines(pairs: &[(&'static str, &[u8])]) -> hyper::HeaderMap {
343 let mut headers = hyper::HeaderMap::new();
344 for (name, value) in pairs {
345 headers.append(
346 *name,
347 hyper::header::HeaderValue::from_bytes(value).expect("value"),
348 );
349 }
350 headers
351 }
352
353 #[test]
354 fn header_fields_are_named_in_lowercase() {
355 let fields = header_fields(&lines(&[
356 ("Authorization", b"Bearer tok"),
357 ("X-Request-ID", b"abc"),
358 ]));
359 assert_eq!(fields.len(), 2);
360 assert_eq!(fields["authorization"], "Bearer tok");
361 assert_eq!(fields["x-request-id"], "abc");
362 assert!(header_fields(&hyper::HeaderMap::new()).is_empty());
363 }
364
365 #[test]
367 fn a_field_sent_as_several_lines_is_one_field() {
368 let fields = header_fields(&lines(&[
369 ("a2a-extensions", b"urn:b"),
370 ("A2A-Extensions", b"urn:a, urn:c"),
371 ("authorization", b"Bearer tok"),
372 ]));
373 assert_eq!(fields["a2a-extensions"], "urn:b, urn:a, urn:c");
374 assert_eq!(fields["authorization"], "Bearer tok");
375 }
376
377 #[test]
380 fn cookie_lines_are_joined_as_cookies() {
381 let headers = lines(&[("cookie", b"a=1"), ("Cookie", b"b=2")]);
382 assert_eq!(header_fields(&headers)["cookie"], "a=1; b=2");
383 assert_eq!(field_value(&headers, "Cookie").as_deref(), Some("a=1; b=2"));
384 }
385
386 #[test]
387 fn a_line_that_is_not_visible_ascii_is_left_out() {
388 let headers = lines(&[
389 ("x-name", b"caf\xe9"),
390 ("x-name", b"cafe"),
391 ("x-other", b"caf\xe9"),
392 ]);
393 let fields = header_fields(&headers);
394 assert_eq!(fields["x-name"], "cafe");
395 assert!(!fields.contains_key("x-other"), "{fields:?}");
396 assert_eq!(field_value(&headers, "x-other"), None);
397 assert_eq!(field_value(&headers, "x-absent"), None);
398 }
399
400 #[test]
401 fn default_values() {
402 let config = DispatchConfig::default();
403 assert_eq!(config.max_request_body_size, 4 * 1024 * 1024);
404 assert_eq!(config.body_read_timeout, Duration::from_secs(30));
405 assert_eq!(config.max_query_string_length, 4096);
406 assert_eq!(config.sse_keep_alive_interval, Duration::from_secs(30));
407 assert_eq!(config.sse_channel_capacity, 64);
408 assert_eq!(config.max_batch_size, 100);
409 }
410
411 #[test]
412 fn with_max_request_body_size_sets_value() {
413 let config = DispatchConfig::default().with_max_request_body_size(8 * 1024 * 1024);
414 assert_eq!(config.max_request_body_size, 8 * 1024 * 1024);
415 }
416
417 #[test]
418 fn with_body_read_timeout_sets_value() {
419 let config = DispatchConfig::default().with_body_read_timeout(Duration::from_secs(60));
420 assert_eq!(config.body_read_timeout, Duration::from_secs(60));
421 }
422
423 #[test]
424 fn with_max_query_string_length_sets_value() {
425 let config = DispatchConfig::default().with_max_query_string_length(8192);
426 assert_eq!(config.max_query_string_length, 8192);
427 }
428
429 #[test]
430 fn with_sse_keep_alive_interval_sets_value() {
431 let config =
432 DispatchConfig::default().with_sse_keep_alive_interval(Duration::from_secs(15));
433 assert_eq!(config.sse_keep_alive_interval, Duration::from_secs(15));
434 }
435
436 #[test]
437 fn with_sse_channel_capacity_sets_value() {
438 let config = DispatchConfig::default().with_sse_channel_capacity(128);
439 assert_eq!(config.sse_channel_capacity, 128);
440 }
441
442 #[test]
443 fn with_max_batch_size_sets_value() {
444 let config = DispatchConfig::default().with_max_batch_size(50);
445 assert_eq!(config.max_batch_size, 50);
446 }
447
448 #[test]
449 fn builder_chaining() {
450 let config = DispatchConfig::default()
451 .with_max_request_body_size(1024)
452 .with_body_read_timeout(Duration::from_secs(10))
453 .with_max_query_string_length(2048)
454 .with_sse_keep_alive_interval(Duration::from_secs(5))
455 .with_sse_channel_capacity(32)
456 .with_max_batch_size(25);
457
458 assert_eq!(config.max_request_body_size, 1024);
459 assert_eq!(config.body_read_timeout, Duration::from_secs(10));
460 assert_eq!(config.max_query_string_length, 2048);
461 assert_eq!(config.sse_keep_alive_interval, Duration::from_secs(5));
462 assert_eq!(config.sse_channel_capacity, 32);
463 assert_eq!(config.max_batch_size, 25);
464 }
465
466 #[test]
467 fn debug_format() {
468 let config = DispatchConfig::default();
469 let debug = format!("{config:?}");
470 assert!(debug.contains("DispatchConfig"));
471 assert!(debug.contains("max_request_body_size"));
472 assert!(debug.contains("body_read_timeout"));
473 assert!(debug.contains("max_query_string_length"));
474 assert!(debug.contains("sse_keep_alive_interval"));
475 assert!(debug.contains("sse_channel_capacity"));
476 assert!(debug.contains("max_batch_size"));
477 }
478
479 #[test]
482 fn with_require_version_header_sets_the_field() {
483 let default = DispatchConfig::default().require_version_header;
484 let cfg = DispatchConfig::default().with_require_version_header(!default);
485 assert_eq!(cfg.require_version_header, !default);
486 }
487}
488
489#[cfg(test)]
490mod axum_adapter_debug_tests;