1use std::collections::HashMap;
106use std::convert::Infallible;
107use std::sync::Arc;
108
109use axum::Router;
110use axum::body::Body;
111use axum::extract::{RawQuery, State};
112use axum::response::IntoResponse;
113use axum::routing::{get, post};
114use bytes::Bytes;
115
116use crate::handler::{RequestHandler, SendMessageResult};
117use crate::streaming::build_sse_response;
118use unreadable::{refuse_unreadable, send_method};
119
120mod dispatcher;
121mod unreadable;
122mod validate;
123
124pub struct A2aRouter {
150 handler: Arc<RequestHandler>,
151 config: super::DispatchConfig,
152 #[cfg(feature = "websocket")]
153 websocket: Option<super::websocket::WebSocketUpgrades>,
154 router: std::sync::OnceLock<Router>,
157}
158
159pub type RestRouter = A2aRouter;
166
167impl std::fmt::Debug for A2aRouter {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 f.debug_struct("A2aRouter")
170 .field("config", &self.config)
171 .finish_non_exhaustive()
172 }
173}
174
175impl A2aRouter {
176 #[must_use]
178 pub fn new(handler: Arc<RequestHandler>) -> Self {
179 Self::with_config(handler, super::DispatchConfig::default())
180 }
181
182 #[must_use]
184 pub const fn with_config(handler: Arc<RequestHandler>, config: super::DispatchConfig) -> Self {
185 Self {
186 handler,
187 config,
188 #[cfg(feature = "websocket")]
189 websocket: None,
190 router: std::sync::OnceLock::new(),
191 }
192 }
193
194 #[cfg(feature = "websocket")]
202 #[must_use]
203 pub fn with_websocket(mut self, websocket: super::WebSocketDispatcher) -> Self {
204 self.websocket = Some(super::websocket::WebSocketUpgrades::new(websocket));
205 self
206 }
207
208 #[cfg(feature = "websocket")]
211 #[must_use]
212 pub fn websocket_upgrades(&self) -> Option<super::websocket::WebSocketUpgrades> {
213 self.websocket.clone()
214 }
215
216 pub fn into_router(self) -> Router {
225 self.build()
226 }
227
228 fn build(&self) -> Router {
230 let max_body = self.config.max_request_body_size;
235 let base_path = self.config.base_path.clone();
236 self.handler.warn_if_undeclared("HTTP+JSON"); #[cfg(feature = "websocket")]
238 let websocket = self.websocket.clone().map_or_else(Router::new, |upgrades| {
239 self.handler
240 .warn_if_undeclared(a2a_protocol_types::WEBSOCKET_BINDING_URI);
241 Router::new()
242 .route("/", get(handle_websocket_upgrade))
243 .with_state(upgrades)
244 });
245 #[cfg(not(feature = "websocket"))]
247 let websocket = Router::new();
248 let card_handler = card_handler(&self.handler, self.config.agent_card_max_age);
249 let state = A2aState {
250 handler: Arc::clone(&self.handler),
251 config: Arc::new(self.config.clone()),
252 card_handler,
253 };
254 let checks = state.clone();
255 let loads = Arc::clone(&state.handler);
256
257 let router = Router::new()
258 .route("/message:send", post(handle_send_message))
260 .route("/message:stream", post(handle_stream_message))
261 .route("/tasks", get(handle_list_tasks))
263 .route("/tasks/{*rest}", axum::routing::any(handle_tasks_catchall))
268 .route("/extendedAgentCard", get(handle_extended_card))
270 .route("/.well-known/agent-card.json", get(handle_agent_card))
272 .route("/health", get(handle_health))
274 .route("/ready", get(handle_ready))
275 .route("/load", get(handle_load))
276 .method_not_allowed_fallback(method_not_allowed)
279 .with_state(state)
280 .merge(websocket)
281 .layer(axum::extract::DefaultBodyLimit::max(max_body))
282 .layer(axum::middleware::from_fn_with_state(
283 checks,
284 validate::validate_a2a_request,
285 ))
286 .layer(axum::middleware::from_fn(negotiate_media_type))
287 .layer(axum::middleware::from_fn_with_state(loads, stamp_load));
288 match base_path {
292 Some(base) => Router::new().nest(&base, router.clone()).merge(router),
293 None => router,
294 }
295 }
296}
297
298impl crate::serve::Dispatcher for A2aRouter {
305 fn dispatch(
308 &self,
309 req: hyper::Request<hyper::body::Incoming>,
310 ) -> std::pin::Pin<
311 Box<dyn std::future::Future<Output = crate::serve::DispatchResponse> + Send + '_>,
312 > {
313 let mut router = self.router.get_or_init(|| self.build()).clone();
314 Box::pin(async move {
315 let Ok(()) = std::future::poll_fn(|cx| {
318 tower_service::Service::<hyper::Request<hyper::body::Incoming>>::poll_ready(
319 &mut router,
320 cx,
321 )
322 })
323 .await;
324 let Ok(response) = tower_service::Service::call(&mut router, req).await;
325 response.map(|body| {
326 http_body_util::combinators::BoxBody::new(dispatcher::Truncating::new(body))
327 })
328 })
329 }
330
331 fn request_handler(&self) -> Option<&Arc<RequestHandler>> {
334 Some(&self.handler)
335 }
336
337 fn protocol_binding(&self) -> Option<&'static str> {
340 #[cfg(feature = "websocket")]
341 if self.websocket.is_some() {
342 return None;
343 }
344 Some("HTTP+JSON")
345 }
346
347 #[cfg(feature = "websocket")]
350 fn close_upgraded(
351 &self,
352 within: std::time::Duration,
353 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + '_>> {
354 match &self.websocket {
355 Some(websocket) => Box::pin(websocket.close(within)),
356 None => Box::pin(std::future::ready(true)),
357 }
358 }
359}
360
361#[cfg(feature = "websocket")]
364async fn handle_websocket_upgrade(
365 State(upgrades): State<super::websocket::WebSocketUpgrades>,
366 req: axum::extract::Request,
367) -> axum::response::Response {
368 if !super::websocket::WebSocketUpgrades::is_upgrade(&req) {
369 return plain_error(426, "this path serves WebSocket upgrades only");
370 }
371 upgrades.upgrade(req).await.map(Body::new)
372}
373
374async fn negotiate_media_type(
377 req: axum::extract::Request,
378 next: axum::middleware::Next,
379) -> axum::response::Response {
380 use crate::dispatch::rest::media_type::{ResponseMediaType, is_negotiable_path};
381 let media = ResponseMediaType::from_headers(req.headers());
382 let negotiable = is_negotiable_path(req.uri().path());
383 let mut resp = next.run(req).await;
384 if negotiable {
385 media.apply(resp.headers_mut());
386 }
387 resp
388}
389
390pub(super) struct TimedBody(pub(super) Bytes);
412
413impl axum::extract::FromRequest<A2aState> for TimedBody {
414 type Rejection = axum::response::Response;
415
416 async fn from_request(
417 req: axum::extract::Request,
418 state: &A2aState,
419 ) -> Result<Self, Self::Rejection> {
420 let deadline = state.config.body_read_timeout;
421 match tokio::time::timeout(deadline, Bytes::from_request(req, state)).await {
422 Ok(Ok(bytes)) => Ok(Self(bytes)),
423 Ok(Err(rejection)) => Err(crate::rpc_span::refused(plain_error(
429 rejection.status().as_u16(),
430 &rejection.body_text(),
431 ))),
432 Err(_) => Err(crate::rpc_span::refused(plain_error(
433 408,
434 &format!("request body not fully received within {deadline:?}"),
435 ))),
436 }
437 }
438}
439
440#[derive(Clone)]
443struct A2aState {
444 handler: Arc<RequestHandler>,
445 config: Arc<super::DispatchConfig>,
446 card_handler: Option<Arc<crate::agent_card::StaticAgentCardHandler>>,
449}
450
451fn card_handler(
452 handler: &RequestHandler,
453 max_age: u32,
454) -> Option<Arc<crate::agent_card::StaticAgentCardHandler>> {
455 handler
456 .agent_card
457 .as_ref()
458 .and_then(|card| crate::agent_card::StaticAgentCardHandler::new(card).ok())
459 .map(|card| card.with_max_age(max_age))
460 .map(Arc::new)
461}
462
463struct CallHeaders(HashMap<String, String>);
468
469impl<S: Send + Sync> axum::extract::FromRequestParts<S> for CallHeaders {
470 type Rejection = Infallible;
471
472 fn from_request_parts(
473 parts: &mut axum::http::request::Parts,
474 _state: &S,
475 ) -> impl std::future::Future<Output = Result<Self, Self::Rejection>> + Send {
476 let mut headers = super::header_fields(&parts.headers);
477 let peer = super::peer_of(&parts.extensions).or_else(|| {
478 parts
479 .extensions
480 .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
481 .map(|info| info.0)
482 });
483 super::record_peer_addr(&mut headers, peer);
484 super::record_peer_certificate(&mut headers, super::certificate_of(&parts.extensions));
485 std::future::ready(Ok(Self(headers)))
486 }
487}
488
489fn plain_error(status: u16, message: &str) -> axum::response::Response {
498 hyper_to_axum(crate::dispatch::rest::error_json_response(status, message))
499}
500
501fn handler_error_to_response(err: &crate::error::ServerError) -> axum::response::Response {
507 hyper_to_axum(crate::dispatch::rest::server_error_to_response(err))
508}
509
510async fn method_not_allowed() -> axum::response::Response {
513 plain_error(405, "method not allowed")
514}
515
516fn a2a_json<T: serde::Serialize>(value: &T) -> axum::response::Response {
524 hyper_to_axum(crate::dispatch::rest::json_ok_response(value))
525}
526
527fn hyper_to_axum(
528 resp: hyper::Response<http_body_util::combinators::BoxBody<Bytes, Infallible>>,
529) -> axum::response::Response {
530 let (parts, body) = resp.into_parts();
531 let axum_body = Body::new(body);
532 axum::response::Response::from_parts(parts, axum_body)
533}
534
535#[allow(clippy::too_many_lines, clippy::literal_string_with_formatting_args)]
550async fn handle_tasks_catchall(
551 State(state): State<A2aState>,
552 method: axum::http::Method,
553 uri: axum::http::Uri,
554 CallHeaders(hdrs): CallHeaders,
555 TimedBody(body): TimedBody,
556) -> axum::response::Response {
557 let rest = uri.path().strip_prefix("/tasks/").unwrap_or_default();
562 let segments: Vec<&str> = rest.strip_suffix('/').unwrap_or(rest).split('/').collect();
566 let dec = super::rest::query::percent_decode_path;
567 let query = uri.query().unwrap_or_default();
570 let tenant = query_tenant(query);
571
572 match (method.as_str(), segments.as_slice()) {
573 ("GET", [id]) if !id.contains(':') => {
575 rpc_call(
579 &state.handler,
580 "GetTask",
581 (method.as_str(), "/tasks/{id}"),
582 &hdrs,
583 async {
584 match super::rest::query::parse_query_param_u32(query, "historyLength") {
585 Ok(history_length) => {
586 handle_get_task_inner(&state, &dec(id), tenant, history_length, &hdrs)
587 .await
588 }
589 Err(e) => refuse_unreadable(&state, "GetTask", &hdrs, e).await,
590 }
591 },
592 )
593 .await
594 }
595
596 ("POST", [id_action]) if id_action.ends_with(":cancel") => {
598 let id = &id_action[..id_action.len() - ":cancel".len()];
599 rpc_call(
600 &state.handler,
601 "CancelTask",
602 (method.as_str(), "/tasks/{id}:cancel"),
603 &hdrs,
604 handle_cancel_task_inner(&state, &dec(id), &hdrs, &body),
605 )
606 .await
607 }
608
609 ("GET" | "POST", [id_action]) if id_action.ends_with(":subscribe") => {
611 let id = &id_action[..id_action.len() - ":subscribe".len()];
612 rpc_call(
613 &state.handler,
614 "SubscribeToTask",
615 (method.as_str(), "/tasks/{id}:subscribe"),
616 &hdrs,
617 handle_subscribe_inner(&state, &dec(id), tenant, &hdrs, &body),
618 )
619 .await
620 }
621
622 ("POST", [task_id, "pushNotificationConfigs"]) => {
624 rpc_call(
625 &state.handler,
626 "CreateTaskPushNotificationConfig",
627 (method.as_str(), "/tasks/{task_id}/pushNotificationConfigs"),
628 &hdrs,
629 handle_create_push_config_inner(&state, &dec(task_id), &hdrs, body),
630 )
631 .await
632 }
633
634 ("GET", [task_id, "pushNotificationConfigs"]) => {
636 rpc_call(
637 &state.handler,
638 "ListTaskPushNotificationConfigs",
639 (method.as_str(), "/tasks/{task_id}/pushNotificationConfigs"),
640 &hdrs,
641 handle_list_push_configs_inner(&state, task_id, query, tenant, &hdrs),
642 )
643 .await
644 }
645
646 ("GET", [task_id, "pushNotificationConfigs", config_id]) => {
648 rpc_call(
649 &state.handler,
650 "GetTaskPushNotificationConfig",
651 (
652 method.as_str(),
653 "/tasks/{task_id}/pushNotificationConfigs/{config_id}",
654 ),
655 &hdrs,
656 handle_get_push_config_inner(&state, &dec(task_id), &dec(config_id), tenant, &hdrs),
657 )
658 .await
659 }
660
661 ("DELETE", [task_id, "pushNotificationConfigs", config_id]) => {
663 rpc_call(
664 &state.handler,
665 "DeleteTaskPushNotificationConfig",
666 (
667 method.as_str(),
668 "/tasks/{task_id}/pushNotificationConfigs/{config_id}",
669 ),
670 &hdrs,
671 handle_delete_push_config_inner(
672 &state,
673 &dec(task_id),
674 &dec(config_id),
675 tenant,
676 &hdrs,
677 ),
678 )
679 .await
680 }
681
682 _ => crate::rpc_span::refused(plain_error(404, "not found")),
683 }
684}
685
686fn rpc_call(
693 handler: &RequestHandler,
694 method: &str,
695 (http_method, route): (&str, &str),
696 hdrs: &HashMap<String, String>,
697 call: impl std::future::Future<Output = axum::response::Response> + Send,
698) -> impl std::future::Future<Output = axum::response::Response> {
699 crate::rpc_span::ServerSpan::open(
700 handler,
701 crate::rpc_span::RpcSystem::HttpJson,
702 method,
703 Some(hdrs),
704 )
705 .with_http(http_method, route)
706 .run_response(call)
707}
708
709async fn handle_send_message(
710 State(state): State<A2aState>,
711 CallHeaders(hdrs): CallHeaders,
712 TimedBody(body): TimedBody,
713) -> axum::response::Response {
714 rpc_call(
715 &state.handler,
716 "SendMessage",
717 ("POST", "/message:send"),
718 &hdrs,
719 handle_send_inner(&state, false, &hdrs, body),
720 )
721 .await
722}
723
724async fn handle_stream_message(
725 State(state): State<A2aState>,
726 CallHeaders(hdrs): CallHeaders,
727 TimedBody(body): TimedBody,
728) -> axum::response::Response {
729 rpc_call(
730 &state.handler,
731 "SendStreamingMessage",
732 ("POST", "/message:stream"),
733 &hdrs,
734 handle_send_inner(&state, true, &hdrs, body),
735 )
736 .await
737}
738
739async fn handle_list_tasks(
740 State(state): State<A2aState>,
741 RawQuery(query): RawQuery,
742 CallHeaders(hdrs): CallHeaders,
743) -> axum::response::Response {
744 let query = query.unwrap_or_default();
748 rpc_call(
749 &state.handler,
750 "ListTasks",
751 ("GET", "/tasks"),
752 &hdrs,
753 async {
754 let params = match super::rest::query::parse_list_tasks_query(
757 &query,
758 query_tenant(&query).as_deref(),
759 ) {
760 Ok(params) => params,
761 Err(e) => return refuse_unreadable(&state, "ListTasks", &hdrs, e).await,
762 };
763 match state.handler.on_list_tasks(params, Some(&hdrs)).await {
764 Ok(result) => a2a_json(&result),
765 Err(e) => handler_error_to_response(&e),
766 }
767 },
768 )
769 .await
770}
771
772async fn handle_extended_card(
773 State(state): State<A2aState>,
774 CallHeaders(hdrs): CallHeaders,
775) -> axum::response::Response {
776 rpc_call(
777 &state.handler,
778 "GetExtendedAgentCard",
779 ("GET", "/extendedAgentCard"),
780 &hdrs,
781 async {
782 match state.handler.on_get_extended_agent_card(Some(&hdrs)).await {
783 Ok(card) => {
784 hyper_to_axum(crate::dispatch::rest::extended_card_response(&card, &hdrs))
785 }
786 Err(e) => handler_error_to_response(&e),
787 }
788 },
789 )
790 .await
791}
792
793async fn handle_agent_card(
794 State(state): State<A2aState>,
795 req: axum::extract::Request,
796) -> axum::response::Response {
797 let mut connection = super::card_connection(req.extensions());
798 connection.peer = connection.peer.or_else(|| {
799 req.extensions()
800 .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
801 .map(|info| info.0)
802 });
803 let call =
804 crate::rpc_span::CardCall::start(state.handler.inbound_trace_policy, &req, connection);
805 let resp = state.card_handler.as_ref().map_or_else(
806 || plain_error(404, "agent card not configured"),
807 |h| h.handle(&req).map(Body::new),
808 );
809 call.finish(&resp);
810 resp
811}
812
813async fn handle_health() -> axum::response::Response {
820 axum::Json(serde_json::json!({"status": "ok"})).into_response()
821}
822
823async fn handle_ready(State(state): State<A2aState>) -> axum::response::Response {
841 let readiness = state.handler.readiness().await;
842 let (status, body) =
843 crate::dispatch::rest::ready_body(readiness, state.handler.is_halted_everywhere());
844 let status = axum::http::StatusCode::from_u16(status)
845 .unwrap_or(axum::http::StatusCode::SERVICE_UNAVAILABLE);
846 (status, axum::Json(body)).into_response()
847}
848
849async fn handle_load(State(state): State<A2aState>) -> axum::response::Response {
852 if !state.handler.reports_load() {
853 return axum::http::StatusCode::NOT_FOUND.into_response();
854 }
855 axum::Json(state.handler.load().to_json()).into_response()
856}
857
858async fn stamp_load(
861 State(handler): State<Arc<RequestHandler>>,
862 req: axum::extract::Request,
863 next: axum::middleware::Next,
864) -> axum::response::Response {
865 let mut resp = next.run(req).await;
866 handler.stamp_load(resp.headers_mut());
867 resp
868}
869
870async fn handle_send_inner(
873 state: &A2aState,
874 streaming: bool,
875 hdrs: &HashMap<String, String>,
876 body: Bytes,
877) -> axum::response::Response {
878 let method = send_method(streaming);
879 let params: a2a_protocol_types::params::MessageSendParams =
880 match crate::dispatch::rest::params_from_slice(&body) {
881 Ok(p) => p,
882 Err(e) => return refuse_unreadable(state, method, hdrs, e).await,
883 };
884 match state
885 .handler
886 .on_send_message(params, streaming, Some(hdrs))
887 .await
888 {
889 Ok(SendMessageResult::Response(resp)) => a2a_json(&resp),
890 Ok(SendMessageResult::Stream(reader)) => hyper_to_axum(build_sse_response(
891 reader,
892 Some(state.config.sse_keep_alive_interval),
893 Some(state.config.sse_channel_capacity),
894 None, )),
896 Err(e) => handler_error_to_response(&e),
897 }
898}
899
900fn query_tenant(query: &str) -> Option<String> {
903 super::rest::query::parse_query_param(query, "tenant").filter(|t| !t.is_empty())
904}
905
906async fn handle_get_task_inner(
907 state: &A2aState,
908 id: &str,
909 tenant: Option<String>,
910 history_length: Option<u32>,
911 hdrs: &HashMap<String, String>,
912) -> axum::response::Response {
913 let params = {
914 let mut built = a2a_protocol_types::params::TaskQueryParams::new(id.to_owned());
915 built.tenant = tenant;
916 built.history_length = history_length;
917 built
918 };
919 match state.handler.on_get_task(params, Some(hdrs)).await {
920 Ok(task) => a2a_json(&task),
921 Err(e) => handler_error_to_response(&e),
922 }
923}
924
925#[allow(clippy::result_large_err)]
931fn body_with_path_id<T: serde::de::DeserializeOwned>(
932 body: &Bytes,
933 id: &str,
934) -> Result<T, crate::dispatch::rest::Unreadable> {
935 let mut value: serde_json::Value = if body.iter().all(u8::is_ascii_whitespace) {
936 serde_json::Value::Object(serde_json::Map::new())
937 } else {
938 serde_json::from_slice(body)?
939 };
940 if let Some(obj) = value.as_object_mut() {
941 obj.insert("id".to_owned(), serde_json::Value::String(id.to_owned()));
942 }
943 crate::dispatch::rest::params_from_value(value)
944}
945
946async fn handle_cancel_task_inner(
947 state: &A2aState,
948 id: &str,
949 hdrs: &HashMap<String, String>,
950 body: &Bytes,
951) -> axum::response::Response {
952 let params: a2a_protocol_types::params::CancelTaskParams = match body_with_path_id(body, id) {
953 Ok(params) => params,
954 Err(e) => return refuse_unreadable(state, "CancelTask", hdrs, e).await,
955 };
956 match state.handler.on_cancel_task(params, Some(hdrs)).await {
957 Ok(task) => a2a_json(&task),
958 Err(e) => handler_error_to_response(&e),
959 }
960}
961
962async fn handle_subscribe_inner(
963 state: &A2aState,
964 id: &str,
965 tenant: Option<String>,
966 hdrs: &HashMap<String, String>,
967 body: &Bytes,
968) -> axum::response::Response {
969 let mut params: a2a_protocol_types::params::TaskIdParams = match body_with_path_id(body, id) {
971 Ok(params) => params,
972 Err(e) => return refuse_unreadable(state, "SubscribeToTask", hdrs, e).await,
973 };
974 if params.tenant.is_none() {
975 params.tenant = tenant;
976 }
977 match state.handler.on_subscribe_to_task(params, Some(hdrs)).await {
978 Ok(reader) => hyper_to_axum(build_sse_response(
979 reader,
980 Some(state.config.sse_keep_alive_interval),
981 Some(state.config.sse_channel_capacity),
982 None, )),
984 Err(e) => handler_error_to_response(&e),
985 }
986}
987
988async fn handle_create_push_config_inner(
989 state: &A2aState,
990 task_id: &str,
991 hdrs: &HashMap<String, String>,
992 body: Bytes,
993) -> axum::response::Response {
994 let method = "CreateTaskPushNotificationConfig";
995 let mut value: serde_json::Value = match serde_json::from_slice(&body) {
996 Ok(v) => v,
997 Err(e) => return refuse_unreadable(state, method, hdrs, e).await,
998 };
999 if let Some(obj) = value.as_object_mut() {
1002 obj.insert(
1003 "taskId".to_owned(),
1004 serde_json::Value::String(task_id.to_owned()),
1005 );
1006 }
1007 let config: a2a_protocol_types::push::TaskPushNotificationConfig =
1008 match crate::dispatch::rest::params_from_value(value) {
1009 Ok(c) => c,
1010 Err(e) => return refuse_unreadable(state, method, hdrs, e).await,
1011 };
1012 match state
1013 .handler
1014 .on_create_push_config(config, Some(hdrs))
1015 .await
1016 {
1017 Ok(result) => a2a_json(&result),
1018 Err(e) => handler_error_to_response(&e),
1019 }
1020}
1021
1022async fn handle_get_push_config_inner(
1023 state: &A2aState,
1024 task_id: &str,
1025 config_id: &str,
1026 tenant: Option<String>,
1027 hdrs: &HashMap<String, String>,
1028) -> axum::response::Response {
1029 let params = {
1030 let mut built = a2a_protocol_types::params::GetPushConfigParams::new(
1031 task_id.to_owned(),
1032 config_id.to_owned(),
1033 );
1034 built.tenant = tenant;
1035 built
1036 };
1037 match state.handler.on_get_push_config(params, Some(hdrs)).await {
1038 Ok(config) => a2a_json(&config),
1039 Err(e) => handler_error_to_response(&e),
1040 }
1041}
1042
1043async fn handle_list_push_configs_inner(
1044 state: &A2aState,
1045 task_id: &str,
1046 query: &str,
1047 tenant: Option<String>,
1048 hdrs: &HashMap<String, String>,
1049) -> axum::response::Response {
1050 let params =
1051 match super::rest::query::list_push_configs_params(task_id, query, tenant.as_deref()) {
1052 Ok(params) => params,
1053 Err(e) => {
1054 return refuse_unreadable(state, "ListTaskPushNotificationConfigs", hdrs, e).await;
1055 }
1056 };
1057 match state
1058 .handler
1059 .on_list_push_configs_page(¶ms, Some(hdrs))
1060 .await
1061 {
1062 Ok(resp) => a2a_json(&resp),
1063 Err(e) => handler_error_to_response(&e),
1064 }
1065}
1066
1067async fn handle_delete_push_config_inner(
1068 state: &A2aState,
1069 task_id: &str,
1070 config_id: &str,
1071 tenant: Option<String>,
1072 hdrs: &HashMap<String, String>,
1073) -> axum::response::Response {
1074 let params = {
1075 let mut built = a2a_protocol_types::params::DeletePushConfigParams::new(
1076 task_id.to_owned(),
1077 config_id.to_owned(),
1078 );
1079 built.tenant = tenant;
1080 built
1081 };
1082 match state
1083 .handler
1084 .on_delete_push_config(params, Some(hdrs))
1085 .await
1086 {
1087 Ok(()) => a2a_json(&serde_json::json!({})),
1088 Err(e) => handler_error_to_response(&e),
1089 }
1090}
1091
1092#[cfg(test)]
1095mod tests {
1096 use super::*;
1097
1098 fn catchall_state() -> A2aState {
1114 let handler = Arc::new(
1115 crate::builder::RequestHandlerBuilder::new({
1116 struct Noop;
1117 crate::agent_executor!(Noop, |_ctx, _q| async { Ok(()) });
1118 Noop
1119 })
1120 .without_agent_card()
1121 .build()
1122 .unwrap(),
1123 );
1124 A2aState {
1125 card_handler: card_handler(
1126 &handler,
1127 super::super::DispatchConfig::default().agent_card_max_age,
1128 ),
1129 handler,
1130 config: Arc::new(super::super::DispatchConfig::default()),
1131 }
1132 }
1133
1134 async fn seed_task(state: &A2aState, id: &str) {
1135 use a2a_protocol_types::task::{ContextId, Task, TaskId, TaskState, TaskStatus};
1136 let task = Task::new(
1137 TaskId::new(id),
1138 ContextId::new("ctx"),
1139 TaskStatus::new(TaskState::Submitted),
1140 );
1141 state.handler.task_store.save(&task).await.unwrap();
1142 }
1143
1144 async fn dispatch_tail(state: &A2aState, method: &str, rest: &str) -> axum::http::StatusCode {
1145 let response = handle_tasks_catchall(
1146 State(state.clone()),
1147 axum::http::Method::from_bytes(method.as_bytes()).unwrap(),
1148 format!("/tasks/{rest}").parse().unwrap(),
1149 CallHeaders(HashMap::new()),
1150 TimedBody(Bytes::new()),
1151 )
1152 .await;
1153 response.status()
1154 }
1155
1156 #[tokio::test]
1160 async fn catchall_routes_cancel_and_strips_the_suffix() {
1161 let state = catchall_state();
1162 seed_task(&state, "task-abc").await;
1163
1164 assert_eq!(
1166 dispatch_tail(&state, "POST", "task-abc:cancel").await,
1167 axum::http::StatusCode::OK,
1168 "POST /tasks/task-abc:cancel must cancel task-abc"
1169 );
1170 assert_eq!(
1173 dispatch_tail(&state, "POST", "missing-xyz:cancel").await,
1174 axum::http::StatusCode::NOT_FOUND,
1175 "an unknown task id must 404 rather than resolve to a truncated one"
1176 );
1177 }
1178
1179 #[tokio::test]
1183 async fn catchall_routes_subscribe_and_strips_the_suffix() {
1184 let state = catchall_state();
1185 seed_task(&state, "task-abc").await;
1186
1187 assert_eq!(
1203 dispatch_tail(&state, "GET", "task-abc:subscribe").await,
1204 axum::http::StatusCode::OK,
1205 "GET /tasks/task-abc:subscribe must subscribe to task-abc"
1206 );
1207 assert_eq!(
1208 dispatch_tail(&state, "GET", "missing-xyz:subscribe").await,
1209 axum::http::StatusCode::NOT_FOUND,
1210 "subscribe on an unknown id must still 404"
1211 );
1212 }
1213
1214 #[tokio::test]
1223 async fn catchall_post_without_a_colon_action_falls_through() {
1224 let state = catchall_state();
1225 seed_task(&state, "tid").await;
1226
1227 assert_eq!(
1229 dispatch_tail(&state, "POST", "tidZZZZZZZ").await,
1230 axum::http::StatusCode::NOT_FOUND,
1231 "a POST with no colon action must not be routed to CancelTask"
1232 );
1233 assert_eq!(
1235 dispatch_tail(&state, "POST", "tidZZZZZZZZZZ").await,
1236 axum::http::StatusCode::NOT_FOUND,
1237 "a POST with no colon action must not be routed to SubscribeToTask"
1238 );
1239 }
1240
1241 #[tokio::test]
1245 async fn catchall_plain_get_does_not_swallow_colon_actions() {
1246 let state = catchall_state();
1247 seed_task(&state, "task-abc").await;
1248
1249 assert_eq!(
1250 dispatch_tail(&state, "GET", "task-abc").await,
1251 axum::http::StatusCode::OK,
1252 "GET /tasks/task-abc must fetch the task"
1253 );
1254 assert_eq!(
1258 dispatch_tail(&state, "POST", "task-abc:cancel").await,
1259 axum::http::StatusCode::OK,
1260 "a colon action must not be captured by the plain `GetTask` arm"
1261 );
1262 }
1263
1264 #[test]
1265 fn a2a_state_is_clone() {
1266 fn assert_clone<T: Clone>() {}
1267 assert_clone::<A2aState>();
1268 }
1269
1270 #[test]
1271 fn handler_error_status_task_not_found() {
1272 use crate::error::ServerError;
1273 assert_eq!(
1274 handler_error_to_response(&ServerError::TaskNotFound("t".into()))
1275 .status()
1276 .as_u16(),
1277 404
1278 );
1279 }
1280
1281 #[test]
1282 fn handler_error_status_method_not_found() {
1283 use crate::error::ServerError;
1284 assert_eq!(
1285 handler_error_to_response(&ServerError::MethodNotFound("m".into()))
1286 .status()
1287 .as_u16(),
1288 404
1289 );
1290 }
1291
1292 #[test]
1293 fn handler_error_status_invalid_params() {
1294 use crate::error::ServerError;
1295 assert_eq!(
1296 handler_error_to_response(&ServerError::InvalidParams("p".into()))
1297 .status()
1298 .as_u16(),
1299 400
1300 );
1301 }
1302
1303 #[test]
1304 fn handler_error_status_serialization() {
1305 use crate::error::ServerError;
1306 let err = ServerError::Serialization(serde_json::from_str::<String>("bad").unwrap_err());
1307 assert_eq!(handler_error_to_response(&err).status().as_u16(), 400);
1308 }
1309
1310 #[test]
1311 fn handler_error_status_task_not_cancelable() {
1312 use crate::error::ServerError;
1313 assert_eq!(
1314 handler_error_to_response(&ServerError::TaskNotCancelable("t".into()))
1315 .status()
1316 .as_u16(),
1317 400
1318 );
1319 }
1320
1321 #[test]
1326 fn handler_error_status_agrees_with_the_shared_5_4_table() {
1327 use crate::error::ServerError;
1328 let cases = [
1329 ServerError::TaskNotFound("t".into()),
1330 ServerError::TaskNotCancelable("t".into()),
1331 ServerError::PushNotSupported,
1332 ServerError::UnsupportedOperation("op".into()),
1333 ServerError::InvalidParams("p".into()),
1334 ServerError::MethodNotFound("m".into()),
1335 ];
1336 for err in cases {
1337 assert_eq!(
1338 handler_error_to_response(&err).status().as_u16(),
1339 err.to_a2a_error().code.http_status(),
1340 "adapter disagrees with ErrorCode::http_status for {err:?}"
1341 );
1342 }
1343 }
1344
1345 #[test]
1346 fn handler_error_status_invalid_state_transition() {
1347 use crate::error::ServerError;
1348 let err = ServerError::InvalidStateTransition {
1349 task_id: "t".into(),
1350 from: a2a_protocol_types::task::TaskState::Working,
1351 to: a2a_protocol_types::task::TaskState::Submitted,
1352 };
1353 assert_eq!(handler_error_to_response(&err).status().as_u16(), 400);
1356 }
1357
1358 #[test]
1359 fn handler_error_status_push_not_supported() {
1360 use crate::error::ServerError;
1361 assert_eq!(
1365 handler_error_to_response(&ServerError::PushNotSupported)
1366 .status()
1367 .as_u16(),
1368 400
1369 );
1370 }
1371
1372 #[test]
1373 fn handler_error_status_payload_too_large() {
1374 use crate::error::ServerError;
1375 assert_eq!(
1376 handler_error_to_response(&ServerError::PayloadTooLarge("big".into()))
1377 .status()
1378 .as_u16(),
1379 413
1380 );
1381 }
1382
1383 #[test]
1384 fn handler_error_status_overloaded() {
1385 use crate::error::ServerError;
1386 assert_eq!(
1389 handler_error_to_response(&ServerError::Overloaded("at capacity".into()))
1390 .status()
1391 .as_u16(),
1392 503
1393 );
1394 }
1395
1396 #[test]
1397 fn handler_error_status_internal() {
1398 use crate::error::ServerError;
1399 assert_eq!(
1400 handler_error_to_response(&ServerError::Internal("oops".into()))
1401 .status()
1402 .as_u16(),
1403 500
1404 );
1405 }
1406
1407 async fn body_of(resp: axum::response::Response) -> serde_json::Value {
1408 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
1409 .await
1410 .unwrap();
1411 serde_json::from_slice(&bytes).unwrap()
1412 }
1413
1414 #[tokio::test]
1416 async fn a_plain_error_is_an_aip_193_status() {
1417 let resp = plain_error(404, "not found");
1418 assert_eq!(resp.status().as_u16(), 404);
1419 assert_eq!(
1420 body_of(resp).await,
1421 serde_json::json!({"error": {"code": 404, "status": "NOT_FOUND", "message": "not found"}})
1422 );
1423 }
1424
1425 #[tokio::test]
1426 async fn a_handler_error_carries_its_error_info() {
1427 use crate::error::ServerError;
1428 let body = body_of(handler_error_to_response(&ServerError::TaskNotFound(
1429 "t1".into(),
1430 )))
1431 .await;
1432 assert_eq!(body["error"]["code"], 404);
1433 assert_eq!(body["error"]["status"], "NOT_FOUND");
1434 assert_eq!(body["error"]["details"][0]["reason"], "TASK_NOT_FOUND");
1435 }
1436
1437 #[test]
1438 fn handler_error_to_response_maps_correctly() {
1439 use crate::error::ServerError;
1440 let resp = handler_error_to_response(&ServerError::TaskNotFound("t1".into()));
1441 assert_eq!(resp.status().as_u16(), 404);
1442
1443 let resp = handler_error_to_response(&ServerError::InvalidParams("bad".into()));
1444 assert_eq!(resp.status().as_u16(), 400);
1445
1446 let resp = handler_error_to_response(&ServerError::Internal("oops".into()));
1447 assert_eq!(resp.status().as_u16(), 500);
1448 }
1449
1450 #[test]
1451 fn a2a_router_new_creates_with_defaults() {
1452 use crate::builder::RequestHandlerBuilder;
1454
1455 struct NoopExecutor;
1456 impl crate::executor::AgentExecutor for NoopExecutor {
1457 fn execute<'a>(
1458 &'a self,
1459 _ctx: &'a crate::request_context::RequestContext,
1460 _queue: &'a dyn crate::streaming::EventQueueWriter,
1461 ) -> std::pin::Pin<
1462 Box<
1463 dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<()>>
1464 + Send
1465 + 'a,
1466 >,
1467 > {
1468 Box::pin(async { Ok(()) })
1469 }
1470 }
1471
1472 let handler = Arc::new(
1473 RequestHandlerBuilder::new(NoopExecutor)
1474 .without_agent_card()
1475 .build()
1476 .unwrap(),
1477 );
1478 let router = A2aRouter::new(handler);
1479 let _axum_router = router.into_router();
1481 }
1482
1483 #[test]
1484 fn a2a_router_with_config() {
1485 use crate::builder::RequestHandlerBuilder;
1486
1487 struct NoopExecutor;
1488 impl crate::executor::AgentExecutor for NoopExecutor {
1489 fn execute<'a>(
1490 &'a self,
1491 _ctx: &'a crate::request_context::RequestContext,
1492 _queue: &'a dyn crate::streaming::EventQueueWriter,
1493 ) -> std::pin::Pin<
1494 Box<
1495 dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<()>>
1496 + Send
1497 + 'a,
1498 >,
1499 > {
1500 Box::pin(async { Ok(()) })
1501 }
1502 }
1503
1504 let handler = Arc::new(
1505 RequestHandlerBuilder::new(NoopExecutor)
1506 .without_agent_card()
1507 .build()
1508 .unwrap(),
1509 );
1510 let config =
1511 super::super::DispatchConfig::default().with_max_request_body_size(8 * 1024 * 1024);
1512 let router = A2aRouter::with_config(handler, config);
1513 let _axum_router = router.into_router();
1514 }
1515}
1516
1517#[cfg(test)]
1526mod readiness_tests {
1527 use std::future::Future;
1528 use std::pin::Pin;
1529
1530 use a2a_protocol_types::error::{A2aError, A2aResult};
1531 use a2a_protocol_types::params::ListTasksParams;
1532 use a2a_protocol_types::responses::TaskListResponse;
1533 use a2a_protocol_types::task::{Task, TaskId};
1534 use axum::http::StatusCode;
1535
1536 use crate::store::TaskStore;
1537
1538 use super::*;
1539
1540 struct UnreachableStore;
1542
1543 impl TaskStore for UnreachableStore {
1544 fn save<'a>(
1545 &'a self,
1546 _task: &'a Task,
1547 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
1548 Box::pin(async { Err(A2aError::internal("connection refused")) })
1549 }
1550 fn get<'a>(
1551 &'a self,
1552 _id: &'a TaskId,
1553 ) -> Pin<Box<dyn Future<Output = A2aResult<Option<Task>>> + Send + 'a>> {
1554 Box::pin(async { Err(A2aError::internal("connection refused")) })
1555 }
1556 fn list<'a>(
1557 &'a self,
1558 _p: &'a ListTasksParams,
1559 ) -> Pin<Box<dyn Future<Output = A2aResult<TaskListResponse>> + Send + 'a>> {
1560 Box::pin(async { Err(A2aError::internal("connection refused")) })
1561 }
1562 fn insert_if_absent<'a>(
1563 &'a self,
1564 _task: &'a Task,
1565 ) -> Pin<Box<dyn Future<Output = A2aResult<bool>> + Send + 'a>> {
1566 Box::pin(async { Err(A2aError::internal("connection refused")) })
1567 }
1568 fn delete<'a>(
1569 &'a self,
1570 _id: &'a TaskId,
1571 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
1572 Box::pin(async { Err(A2aError::internal("connection refused")) })
1573 }
1574 fn count<'a>(&'a self) -> Pin<Box<dyn Future<Output = A2aResult<u64>> + Send + 'a>> {
1575 Box::pin(async { Err(A2aError::internal("connection refused")) })
1576 }
1577 }
1578
1579 fn state_with(store: Option<UnreachableStore>) -> A2aState {
1580 struct Noop;
1581 crate::agent_executor!(Noop, |_ctx, _q| async { Ok(()) });
1582
1583 let builder = crate::builder::RequestHandlerBuilder::new(Noop).without_agent_card();
1584 let builder = match store {
1585 Some(s) => builder.with_task_store(s),
1586 None => builder,
1587 };
1588 A2aState {
1589 handler: Arc::new(builder.build().expect("build handler")),
1590 config: Arc::new(super::super::DispatchConfig::default()),
1591 card_handler: None,
1592 }
1593 }
1594
1595 async fn read_response(resp: axum::response::Response) -> (StatusCode, String) {
1599 let status = resp.status();
1600 let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
1601 .await
1602 .expect("body");
1603 (status, String::from_utf8_lossy(&bytes).into_owned())
1604 }
1605
1606 #[tokio::test]
1607 async fn ready_reports_ok_when_the_store_answers() {
1608 let (status, body) = read_response(handle_ready(State(state_with(None))).await).await;
1609 assert_eq!(status, StatusCode::OK);
1610 assert!(body.contains("\"ready\""), "unexpected body: {body}");
1611 }
1612
1613 #[tokio::test]
1614 async fn ready_reports_503_when_the_store_is_unreachable() {
1615 let (status, body) =
1616 read_response(handle_ready(State(state_with(Some(UnreachableStore)))).await).await;
1617
1618 assert_eq!(
1619 status,
1620 StatusCode::SERVICE_UNAVAILABLE,
1621 "an unreachable store must drain traffic from this replica"
1622 );
1623 assert!(body.contains("not_ready"), "unexpected body: {body}");
1624 assert!(body.contains("internal_error"), "unexpected body: {body}");
1627 assert!(
1628 !body.contains("connection refused"),
1629 "the store's message must not be echoed to an unauthenticated probe: {body}"
1630 );
1631 }
1632
1633 #[tokio::test]
1636 async fn health_stays_ok_when_the_store_is_unreachable() {
1637 let (status, body) = read_response(handle_health().await).await;
1638
1639 assert_eq!(
1640 status,
1641 StatusCode::OK,
1642 "liveness must not depend on a downstream"
1643 );
1644 assert!(body.contains("\"ok\""), "unexpected body: {body}");
1645 }
1646}