1mod error_response;
13pub(crate) mod media_type;
14mod params;
15pub(crate) mod query;
16mod response;
17mod span;
18
19pub(crate) use error_response::{
22 error_json_response, rest_error_details, server_error_to_response,
23};
24#[cfg(feature = "axum")]
25pub(crate) use error_response::{params_from_slice, params_from_value};
26#[cfg(feature = "axum")]
27pub(crate) use params::Unreadable;
28#[cfg(feature = "axum")]
29pub(crate) use response::ready_body;
30pub(crate) use response::{extended_card_response, json_ok_response};
31
32use std::collections::HashMap;
33use std::convert::Infallible;
34use std::sync::Arc;
35
36use bytes::Bytes;
37use http_body_util::combinators::BoxBody;
38use hyper::body::Incoming;
39
40use crate::agent_card::StaticAgentCardHandler;
41use crate::dispatch::cors::CorsConfig;
42use crate::handler::{RequestHandler, SendMessageResult};
43use crate::streaming::build_sse_response;
44
45use error_response::not_found_response;
46use query::{
47 contains_path_traversal, list_push_configs_params, parse_list_tasks_query, parse_query_param,
48 parse_query_param_u32, percent_decode_path, strip_tenant_prefix_for,
49};
50use response::{health_response, load_response, ready_response};
51use span::HttpRoute;
52
53use crate::rpc_span::{RpcSystem, record_if_refused, refused};
54
55pub struct RestDispatcher {
60 handler: Arc<RequestHandler>,
61 card_handler: Option<StaticAgentCardHandler>,
62 cors: Option<CorsConfig>,
63 config: super::DispatchConfig,
64}
65
66impl RestDispatcher {
67 #[must_use]
69 pub fn new(handler: Arc<RequestHandler>) -> Self {
70 Self::with_config(handler, super::DispatchConfig::default())
71 }
72
73 #[must_use]
75 pub fn with_config(handler: Arc<RequestHandler>, config: super::DispatchConfig) -> Self {
76 let card_handler = handler
77 .agent_card
78 .as_ref()
79 .and_then(|card| StaticAgentCardHandler::new(card).ok())
80 .map(|card| card.with_max_age(config.agent_card_max_age));
81 Self {
82 handler,
83 card_handler,
84 cors: None,
85 config,
86 }
87 }
88
89 #[must_use]
94 pub fn with_cors(mut self, cors: CorsConfig) -> Self {
95 self.cors = Some(cors);
96 self
97 }
98
99 pub async fn dispatch(
107 &self,
108 mut req: hyper::Request<Incoming>,
109 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
110 super::strip_base_path(&mut req, self.config.base_path.as_deref());
111 let started = std::time::Instant::now();
112 let media = media_type::ResponseMediaType::from_headers(req.headers());
113 let negotiable = media_type::is_negotiable_path(req.uri().path());
114 let mut resp = self.dispatch_unlabelled(req).await;
115 record_if_refused(&self.handler, RpcSystem::HttpJson, started, &mut resp);
116 if negotiable {
117 media.apply(resp.headers_mut());
118 }
119 resp
120 }
121
122 #[allow(clippy::too_many_lines)]
124 async fn dispatch_unlabelled(
125 &self,
126 req: hyper::Request<Incoming>,
127 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
128 let method = req.method().clone();
129 let path = req.uri().path().to_owned();
130 let query = req.uri().query().unwrap_or("").to_owned();
131 trace_debug!(http_method = %method, %path, "dispatching REST request");
132
133 if method == "OPTIONS" {
135 if let Some(ref cors) = self.cors {
136 return cors.preflight_response();
137 }
138 return health_response();
139 }
140
141 if query.len() > self.config.max_query_string_length {
143 let mut resp = refused(error_json_response(
144 414,
145 &format!(
146 "query string too long: {} bytes exceeds {} byte limit",
147 query.len(),
148 self.config.max_query_string_length
149 ),
150 ));
151 if let Some(ref cors) = self.cors {
152 cors.apply_headers(&mut resp);
153 }
154 return resp;
155 }
156
157 if matches!(method.as_str(), "GET" | "HEAD")
162 && (path == "/health"
163 || path == "/ready"
164 || path == "/load" && self.handler.reports_load())
165 {
166 let mut resp = if path == "/ready" {
167 let readiness = self.handler.readiness().await;
168 ready_response(readiness, self.handler.is_halted_everywhere())
169 } else if path == "/load" {
170 load_response(&self.handler.load())
171 } else {
172 health_response()
173 };
174 if let Some(ref cors) = self.cors {
175 cors.apply_headers(&mut resp);
176 }
177 return resp;
178 }
179
180 if let Err(err) = super::check_request_content_type(req.method(), req.headers()) {
186 return refused(server_error_to_response(
187 &crate::error::ServerError::Protocol(err),
188 ));
189 }
190
191 if contains_path_traversal(&path) {
193 return refused(error_json_response(
194 400,
195 "invalid path: path traversal not allowed",
196 ));
197 }
198
199 if path == "/.well-known/agent-card.json" {
203 let call = crate::rpc_span::CardCall::start(
204 self.handler.inbound_trace_policy,
205 &req,
206 super::card_connection(req.extensions()),
207 );
208 let resp = self
209 .card_handler
210 .as_ref()
211 .map_or_else(not_found_response, |h| {
212 h.handle(&req).map(http_body_util::BodyExt::boxed)
213 });
214 call.finish(&resp);
215 return resp;
216 }
217
218 let version_value = super::requested_version(req.headers(), req.uri());
224 if let Err(err) = super::validate_version_header(
225 version_value.as_deref(),
226 self.config.require_version_header,
227 ) {
228 return refused(server_error_to_response(
229 &crate::error::ServerError::Protocol(err),
230 ));
231 }
232
233 let (tenant, rest_path) = strip_tenant_prefix_for(method.as_str(), &path);
241 let tenant = tenant.map(percent_decode_path);
242 let tenant = tenant.as_deref();
243
244 let mut headers = super::header_fields(req.headers());
246 headers.insert(":path".to_owned(), path.clone());
250 super::record_peer_addr(&mut headers, super::peer_of(req.extensions()));
251 super::record_peer_certificate(&mut headers, super::certificate_of(req.extensions()));
252
253 let mut resp =
258 Box::pin(self.dispatch_rest(req, method.as_str(), rest_path, &query, tenant, &headers))
259 .await;
260 if let Some(hval) = self
264 .handler
265 .activated_extensions_header_value(headers.get("a2a-extensions").map(String::as_str))
266 && let Ok(v) = hyper::header::HeaderValue::from_str(&hval)
267 {
268 resp.headers_mut()
269 .insert(a2a_protocol_types::A2A_EXTENSIONS_HEADER, v);
270 }
271 if let Some(ref cors) = self.cors {
272 cors.apply_headers(&mut resp);
273 }
274 resp
275 }
276
277 #[allow(clippy::too_many_lines, clippy::literal_string_with_formatting_args)]
281 async fn dispatch_rest(
282 &self,
283 req: hyper::Request<Incoming>,
284 method: &str,
285 path: &str,
286 query: &str,
287 tenant: Option<&str>,
288 headers: &HashMap<String, String>,
289 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
290 let http = HttpRoute {
297 method,
298 tenant_in_path: tenant.is_some(),
299 };
300 let query_tenant = if tenant.is_none() {
301 parse_query_param(query, "tenant").filter(|t| !t.is_empty())
302 } else {
303 None
304 };
305 let tenant = tenant.or(query_tenant.as_deref());
306
307 match (method, path) {
310 ("POST", "/message:send") => {
311 return self
312 .call(
313 &http,
314 "SendMessage",
315 "/message:send",
316 headers,
317 self.handle_send(req, false, tenant, headers),
318 )
319 .await;
320 }
321 ("POST", "/message:stream") => {
322 return self
323 .call(
324 &http,
325 "SendStreamingMessage",
326 "/message:stream",
327 headers,
328 self.handle_send(req, true, tenant, headers),
329 )
330 .await;
331 }
332 _ => {}
333 }
334
335 if let Some(rest) = path.strip_prefix("/tasks/")
337 && let Some((id, action)) = rest.split_once(':')
338 && !id.is_empty()
339 {
340 match (method, action) {
341 ("POST", "cancel") => {
342 return self
343 .call(
344 &http,
345 "CancelTask",
346 "/tasks/{id}:cancel",
347 headers,
348 self.handle_cancel_task(req, id, tenant, headers),
349 )
350 .await;
351 }
352 ("POST" | "GET", "subscribe") => {
361 return self
362 .call(
363 &http,
364 "SubscribeToTask",
365 "/tasks/{id}:subscribe",
366 headers,
367 self.handle_resubscribe(req, id, tenant, headers),
368 )
369 .await;
370 }
371 _ => {}
372 }
373 }
374
375 let segments = path_segments(path);
380
381 match (method, segments.as_slice()) {
382 ("GET", ["tasks"]) => {
384 self.call(
385 &http,
386 "ListTasks",
387 "/tasks",
388 headers,
389 self.handle_list_tasks(query, tenant, headers),
390 )
391 .await
392 }
393 ("GET", ["tasks", id]) => {
394 self.call(
395 &http,
396 "GetTask",
397 "/tasks/{id}",
398 headers,
399 self.handle_get_task(id, query, tenant, headers),
400 )
401 .await
402 }
403
404 ("POST", ["tasks", id, "cancel"]) => {
406 self.call(
407 &http,
408 "CancelTask",
409 "/tasks/{id}/cancel",
410 headers,
411 self.handle_cancel_task(req, id, tenant, headers),
412 )
413 .await
414 }
415
416 (
418 "POST",
419 [
420 "tasks",
421 task_id,
422 "pushNotificationConfigs" | "pushNotificationConfig",
423 ],
424 ) => {
425 self.call(
426 &http,
427 "CreateTaskPushNotificationConfig",
428 "/tasks/{task_id}/pushNotificationConfigs",
429 headers,
430 self.handle_set_push_config(req, task_id, tenant, headers),
431 )
432 .await
433 }
434 (
435 "GET",
436 [
437 "tasks",
438 task_id,
439 "pushNotificationConfigs" | "pushNotificationConfig",
440 config_id,
441 ],
442 ) => {
443 self.call(
444 &http,
445 "GetTaskPushNotificationConfig",
446 "/tasks/{task_id}/pushNotificationConfigs/{config_id}",
447 headers,
448 self.handle_get_push_config(task_id, config_id, tenant, headers),
449 )
450 .await
451 }
452 (
453 "GET",
454 [
455 "tasks",
456 task_id,
457 "pushNotificationConfigs" | "pushNotificationConfig",
458 ],
459 ) => {
460 self.call(
461 &http,
462 "ListTaskPushNotificationConfigs",
463 "/tasks/{task_id}/pushNotificationConfigs",
464 headers,
465 self.handle_list_push_configs(task_id, query, tenant, headers),
466 )
467 .await
468 }
469 (
470 "DELETE",
471 [
472 "tasks",
473 task_id,
474 "pushNotificationConfigs" | "pushNotificationConfig",
475 config_id,
476 ],
477 )
478 | (
479 "POST",
480 [
481 "tasks",
482 task_id,
483 "pushNotificationConfigs" | "pushNotificationConfig",
484 config_id,
485 "delete",
486 ],
487 ) => {
488 self.call(
489 &http,
490 "DeleteTaskPushNotificationConfig",
491 "/tasks/{task_id}/pushNotificationConfigs/{config_id}",
492 headers,
493 self.handle_delete_push_config(task_id, config_id, tenant, headers),
494 )
495 .await
496 }
497
498 ("GET", ["extendedAgentCard"]) => {
500 self.call(
501 &http,
502 "GetExtendedAgentCard",
503 "/extendedAgentCard",
504 headers,
505 self.handle_extended_card(tenant, headers),
506 )
507 .await
508 }
509
510 _ => refused(not_found_response()),
511 }
512 }
513
514 async fn handle_send(
517 &self,
518 req: hyper::Request<Incoming>,
519 streaming: bool,
520 tenant: Option<&str>,
521 headers: &HashMap<String, String>,
522 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
523 let method = if streaming {
524 "SendStreamingMessage"
525 } else {
526 "SendMessage"
527 };
528 let params: a2a_protocol_types::params::MessageSendParams =
529 match self.read_params(req, method, tenant, &[], headers).await {
530 Ok(p) => p,
531 Err(resp) => return resp,
532 };
533 match self
534 .handler
535 .on_send_message(params, streaming, Some(headers))
536 .await
537 {
538 Ok(SendMessageResult::Response(resp)) => json_ok_response(&resp),
539 Ok(SendMessageResult::Stream(reader)) => build_sse_response(
540 reader,
541 Some(self.config.sse_keep_alive_interval),
542 Some(self.config.sse_channel_capacity),
543 None, ),
545 Err(e) => server_error_to_response(&e),
546 }
547 }
548
549 async fn handle_get_task(
550 &self,
551 id: &str,
552 query: &str,
553 tenant: Option<&str>,
554 headers: &HashMap<String, String>,
555 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
556 let id = percent_decode_path(id);
557 let id = id.as_str();
558 let history_length = match parse_query_param_u32(query, "historyLength") {
559 Ok(history_length) => history_length,
560 Err(e) => return self.refuse_unreadable("GetTask", headers, e).await,
561 };
562 let params = {
563 let mut built = a2a_protocol_types::params::TaskQueryParams::new(id.to_owned());
564 built.tenant = tenant.map(str::to_owned);
565 built.history_length = history_length;
566 built
567 };
568 match self.handler.on_get_task(params, Some(headers)).await {
569 Ok(task) => json_ok_response(&task),
570 Err(e) => server_error_to_response(&e),
571 }
572 }
573
574 async fn handle_list_tasks(
575 &self,
576 query: &str,
577 tenant: Option<&str>,
578 headers: &HashMap<String, String>,
579 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
580 let params = match parse_list_tasks_query(query, tenant) {
581 Ok(params) => params,
582 Err(e) => return self.refuse_unreadable("ListTasks", headers, e).await,
583 };
584 match self.handler.on_list_tasks(params, Some(headers)).await {
585 Ok(result) => json_ok_response(&result),
586 Err(e) => server_error_to_response(&e),
587 }
588 }
589
590 async fn handle_cancel_task(
591 &self,
592 req: hyper::Request<Incoming>,
593 id: &str,
594 tenant: Option<&str>,
595 headers: &HashMap<String, String>,
596 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
597 let id = percent_decode_path(id);
598 let id = id.as_str();
599 let params: a2a_protocol_types::params::CancelTaskParams = match self
603 .read_params(req, "CancelTask", tenant, &[("id", id)], headers)
604 .await
605 {
606 Ok(p) => p,
607 Err(resp) => return resp,
608 };
609 match self.handler.on_cancel_task(params, Some(headers)).await {
610 Ok(task) => json_ok_response(&task),
611 Err(e) => server_error_to_response(&e),
612 }
613 }
614
615 async fn handle_resubscribe(
616 &self,
617 req: hyper::Request<Incoming>,
618 id: &str,
619 tenant: Option<&str>,
620 headers: &HashMap<String, String>,
621 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
622 let id = percent_decode_path(id);
623 let id = id.as_str();
624 let params: a2a_protocol_types::params::TaskIdParams = match self
628 .read_params(req, "SubscribeToTask", tenant, &[("id", id)], headers)
629 .await
630 {
631 Ok(p) => p,
632 Err(resp) => return resp,
633 };
634 match self
635 .handler
636 .on_subscribe_to_task(params, Some(headers))
637 .await
638 {
639 Ok(reader) => build_sse_response(
640 reader,
641 Some(self.config.sse_keep_alive_interval),
642 Some(self.config.sse_channel_capacity),
643 None, ),
645 Err(e) => server_error_to_response(&e),
646 }
647 }
648
649 async fn handle_set_push_config(
650 &self,
651 req: hyper::Request<Incoming>,
652 task_id: &str,
653 tenant: Option<&str>,
654 headers: &HashMap<String, String>,
655 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
656 let task_id = percent_decode_path(task_id);
657 let task_id = task_id.as_str();
658 let method = "CreateTaskPushNotificationConfig";
663 let config: a2a_protocol_types::push::TaskPushNotificationConfig = match self
664 .read_params(req, method, tenant, &[("taskId", task_id)], headers)
665 .await
666 {
667 Ok(c) => c,
668 Err(resp) => return resp,
669 };
670 match self
671 .handler
672 .on_create_push_config(config, Some(headers))
673 .await
674 {
675 Ok(result) => json_ok_response(&result),
676 Err(e) => server_error_to_response(&e),
677 }
678 }
679
680 async fn handle_get_push_config(
681 &self,
682 task_id: &str,
683 config_id: &str,
684 tenant: Option<&str>,
685 headers: &HashMap<String, String>,
686 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
687 let task_id = percent_decode_path(task_id);
688 let task_id = task_id.as_str();
689 let config_id = percent_decode_path(config_id);
690 let config_id = config_id.as_str();
691 let params = {
692 let mut built = a2a_protocol_types::params::GetPushConfigParams::new(
693 task_id.to_owned(),
694 config_id.to_owned(),
695 );
696 built.tenant = tenant.map(str::to_owned);
697 built
698 };
699 match self.handler.on_get_push_config(params, Some(headers)).await {
700 Ok(config) => json_ok_response(&config),
701 Err(e) => server_error_to_response(&e),
702 }
703 }
704
705 async fn handle_list_push_configs(
706 &self,
707 task_id: &str,
708 query: &str,
709 tenant: Option<&str>,
710 headers: &HashMap<String, String>,
711 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
712 let params = match list_push_configs_params(task_id, query, tenant) {
713 Ok(params) => params,
714 Err(e) => {
715 return self
716 .refuse_unreadable("ListTaskPushNotificationConfigs", headers, e)
717 .await;
718 }
719 };
720 match self
721 .handler
722 .on_list_push_configs_page(¶ms, Some(headers))
723 .await
724 {
725 Ok(resp) => json_ok_response(&resp),
726 Err(e) => server_error_to_response(&e),
727 }
728 }
729
730 async fn handle_delete_push_config(
731 &self,
732 task_id: &str,
733 config_id: &str,
734 tenant: Option<&str>,
735 headers: &HashMap<String, String>,
736 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
737 let task_id = percent_decode_path(task_id);
738 let task_id = task_id.as_str();
739 let config_id = percent_decode_path(config_id);
740 let config_id = config_id.as_str();
741 let params = {
742 let mut built = a2a_protocol_types::params::DeletePushConfigParams::new(
743 task_id.to_owned(),
744 config_id.to_owned(),
745 );
746 built.tenant = tenant.map(str::to_owned);
747 built
748 };
749 match self
750 .handler
751 .on_delete_push_config(params, Some(headers))
752 .await
753 {
754 Ok(()) => json_ok_response(&serde_json::json!({})),
755 Err(e) => server_error_to_response(&e),
756 }
757 }
758
759 async fn handle_extended_card(
760 &self,
761 tenant: Option<&str>,
762 headers: &HashMap<String, String>,
763 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
764 match self
765 .handler
766 .on_get_extended_agent_card_for_tenant(tenant, Some(headers))
767 .await
768 {
769 Ok(card) => extended_card_response(&card, headers),
770 Err(e) => server_error_to_response(&e),
771 }
772 }
773}
774
775impl std::fmt::Debug for RestDispatcher {
776 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
777 f.debug_struct("RestDispatcher").finish()
778 }
779}
780
781impl crate::serve::Dispatcher for RestDispatcher {
784 fn dispatch(
785 &self,
786 req: hyper::Request<Incoming>,
787 ) -> std::pin::Pin<
788 Box<dyn std::future::Future<Output = crate::serve::DispatchResponse> + Send + '_>,
789 > {
790 Box::pin(self.dispatch(req))
791 }
792
793 fn request_handler(&self) -> Option<&Arc<RequestHandler>> {
794 Some(&self.handler)
795 }
796
797 fn protocol_binding(&self) -> Option<&'static str> {
798 Some("HTTP+JSON")
799 }
800}
801
802fn path_segments(path: &str) -> Vec<&str> {
805 let path = path.strip_prefix('/').unwrap_or(path);
806 path.strip_suffix('/').unwrap_or(path).split('/').collect()
807}
808
809#[cfg(test)]
810mod tests {
811 #[test]
814 fn rest_dispatcher_debug_format() {
815 let debug_output = "RestDispatcher";
818 assert_ne!(debug_output, "");
819 }
820
821 #[test]
822 fn dispatch_config_default_query_limit() {
823 let config = super::super::DispatchConfig::default();
824 assert_eq!(config.max_query_string_length, 4096);
825 }
826}