a2a_protocol_server/dispatch/
combined.rs1use std::convert::Infallible;
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::Arc;
27
28use bytes::Bytes;
29use http_body_util::combinators::BoxBody;
30use hyper::body::Incoming;
31
32use super::{CorsConfig, DispatchConfig, JsonRpcDispatcher, RestDispatcher};
33use crate::error::{ServerError, ServerResult};
34use crate::handler::RequestHandler;
35use crate::serve::{DispatchResponse, Dispatcher};
36
37pub const DEFAULT_JSONRPC_PATH: &str = "/";
39
40pub struct CombinedDispatcher {
60 jsonrpc: JsonRpcDispatcher,
61 rest: RestDispatcher,
62 jsonrpc_path: String,
63 base_path: Option<String>,
67 #[cfg(feature = "websocket")]
70 websocket: Option<super::websocket::WebSocketUpgrades>,
71}
72
73impl CombinedDispatcher {
74 #[must_use]
77 pub fn new(handler: Arc<RequestHandler>) -> Self {
78 Self::with_config(handler, DispatchConfig::default())
79 }
80
81 #[must_use]
84 pub fn with_config(handler: Arc<RequestHandler>, mut config: DispatchConfig) -> Self {
85 handler.warn_if_undeclared("JSONRPC");
86 handler.warn_if_undeclared("HTTP+JSON");
87 let base_path = config.base_path.take();
88 Self {
89 jsonrpc: JsonRpcDispatcher::with_config(Arc::clone(&handler), config.clone()),
90 rest: RestDispatcher::with_config(handler, config),
91 jsonrpc_path: DEFAULT_JSONRPC_PATH.to_owned(),
92 base_path,
93 #[cfg(feature = "websocket")]
94 websocket: None,
95 }
96 }
97
98 #[cfg(feature = "websocket")]
109 #[must_use]
110 pub fn with_websocket(mut self, websocket: super::WebSocketDispatcher) -> Self {
111 if let Some(handler) = Dispatcher::request_handler(&self.rest) {
112 handler.warn_if_undeclared(a2a_protocol_types::WEBSOCKET_BINDING_URI);
113 }
114 self.websocket = Some(super::websocket::WebSocketUpgrades::new(websocket));
115 self
116 }
117
118 pub fn with_jsonrpc_path(mut self, path: impl Into<String>) -> ServerResult<Self> {
128 let path = path.into();
129 let segment = path.strip_prefix('/').unwrap_or("/");
130 let ours = matches!(
131 segment,
132 ".well-known" | "tasks" | "extendedAgentCard" | "health" | "ready"
133 );
134 if ours || segment.contains(['/', ':', '?', '#']) {
135 return Err(ServerError::InvalidParams(format!(
136 "JSON-RPC path {path:?} must be \"/\" or one segment without ':' that the \
137 HTTP+JSON binding does not route"
138 )));
139 }
140 self.jsonrpc_path = path;
141 Ok(self)
142 }
143
144 #[must_use]
146 pub fn with_cors(mut self, cors: CorsConfig) -> Self {
147 self.jsonrpc = self.jsonrpc.with_cors(cors.clone());
148 self.rest = self.rest.with_cors(cors);
149 self
150 }
151
152 fn is_jsonrpc<B>(&self, req: &hyper::Request<B>) -> bool {
154 req.uri().path() == self.jsonrpc_path
155 && matches!(*req.method(), hyper::Method::POST | hyper::Method::OPTIONS)
156 }
157
158 pub async fn dispatch(
160 &self,
161 mut req: hyper::Request<Incoming>,
162 ) -> hyper::Response<BoxBody<Bytes, Infallible>> {
163 super::strip_base_path(&mut req, self.base_path.as_deref());
164 #[cfg(feature = "websocket")]
165 if let Some(websocket) = &self.websocket
166 && req.uri().path() == self.jsonrpc_path
167 && super::websocket::WebSocketUpgrades::is_upgrade(&req)
168 {
169 return websocket.upgrade(req).await;
170 }
171 if self.is_jsonrpc(&req) {
172 self.jsonrpc.dispatch(req).await
173 } else {
174 self.rest.dispatch(req).await
175 }
176 }
177}
178
179impl std::fmt::Debug for CombinedDispatcher {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 f.debug_struct("CombinedDispatcher")
182 .field("jsonrpc_path", &self.jsonrpc_path)
183 .field("base_path", &self.base_path)
184 .finish_non_exhaustive()
185 }
186}
187
188impl Dispatcher for CombinedDispatcher {
189 fn dispatch(
190 &self,
191 req: hyper::Request<Incoming>,
192 ) -> Pin<Box<dyn Future<Output = DispatchResponse> + Send + '_>> {
193 Box::pin(self.dispatch(req))
194 }
195
196 fn request_handler(&self) -> Option<&Arc<RequestHandler>> {
197 Dispatcher::request_handler(&self.rest)
198 }
199
200 #[cfg(feature = "websocket")]
201 fn close_upgraded(
202 &self,
203 within: std::time::Duration,
204 ) -> Pin<Box<dyn Future<Output = bool> + Send + '_>> {
205 match &self.websocket {
206 Some(websocket) => Box::pin(websocket.close(within)),
207 None => Box::pin(std::future::ready(true)),
208 }
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215 use crate::agent_executor;
216 use crate::builder::RequestHandlerBuilder;
217
218 struct Idle;
219 agent_executor!(Idle, |_ctx, _queue| async { Ok(()) });
220
221 fn combined() -> CombinedDispatcher {
222 CombinedDispatcher::new(Arc::new(
223 RequestHandlerBuilder::new(Idle)
224 .without_agent_card()
225 .build()
226 .unwrap(),
227 ))
228 }
229
230 fn req(method: &str, path: &str) -> hyper::Request<()> {
231 hyper::Request::builder()
232 .method(method)
233 .uri(path)
234 .body(())
235 .unwrap()
236 }
237
238 #[test]
239 fn debug_names_the_dispatcher_and_its_paths() {
240 let text = format!("{:?}", combined());
241 assert!(text.starts_with("CombinedDispatcher {"), "{text}");
242 assert!(
243 text.contains("jsonrpc_path") && text.contains("base_path"),
244 "{text}"
245 );
246 }
247
248 #[test]
249 fn only_a_post_or_preflight_of_the_jsonrpc_path_is_jsonrpc() {
250 let d = combined();
251 assert!(d.is_jsonrpc(&req("POST", "/")));
252 assert!(d.is_jsonrpc(&req("OPTIONS", "/")));
253 assert!(!d.is_jsonrpc(&req("GET", "/")));
254 assert!(!d.is_jsonrpc(&req("POST", "/message:send")));
255 assert!(!d.is_jsonrpc(&req("POST", "/t1/message:send")));
256 assert!(!d.is_jsonrpc(&req("GET", "/.well-known/agent-card.json")));
257
258 let d = combined().with_jsonrpc_path("/a2a").unwrap();
259 assert!(d.is_jsonrpc(&req("POST", "/a2a")));
260 assert!(!d.is_jsonrpc(&req("POST", "/")));
261 assert!(!d.is_jsonrpc(&req("POST", "/a2a/message:send")));
262 }
263
264 #[test]
268 fn the_handler_is_reported_for_shutdown() {
269 let handler = Arc::new(
270 RequestHandlerBuilder::new(Idle)
271 .without_agent_card()
272 .build()
273 .unwrap(),
274 );
275 let d = CombinedDispatcher::new(Arc::clone(&handler));
276 let reported = Dispatcher::request_handler(&d).expect("a handler");
277 assert!(Arc::ptr_eq(reported, &handler));
278 }
279
280 #[test]
281 fn a_jsonrpc_path_the_rest_binding_could_route_is_refused() {
282 for path in [
283 "/a/b",
284 "/message:send",
285 "/tasks",
286 "/extendedAgentCard",
287 "/.well-known",
288 "/health",
289 "/ready",
290 "/x?y",
291 "a2a",
292 "",
293 ] {
294 assert!(
295 combined().with_jsonrpc_path(path).is_err(),
296 "{path:?} was accepted"
297 );
298 }
299 for path in ["/", "/a2a", "/jsonrpc"] {
300 assert!(combined().with_jsonrpc_path(path).is_ok(), "{path:?}");
301 }
302 }
303}