1use std::collections::HashMap;
39use std::future::Future;
40use std::pin::Pin;
41use std::sync::Arc;
42use std::time::Duration;
43
44use a2a_protocol_types::proto as apb;
45use a2a_protocol_types::proto::convert::ConvertError;
46use tokio::sync::mpsc;
47use tonic::transport::Channel;
48
49pub use crate::config::GrpcBareAddressScheme;
50use crate::error::{ClientError, ClientResult};
51use crate::streaming::EventStream;
52use crate::transport::Transport;
53#[cfg(feature = "grpc-tls")]
56pub use tonic::transport::{Certificate, ClientTlsConfig, Identity};
57
58mod proto {
61 #![allow(
62 clippy::all,
63 clippy::pedantic,
64 clippy::nursery,
65 missing_docs,
66 unused_qualifications
67 )]
68 tonic::include_proto!("lf.a2a.v1");
69}
70
71use proto::a2a_service_client::A2aServiceClient;
72
73#[cfg(feature = "grpc-tls")]
84fn default_client_tls() -> ClientTlsConfig {
85 #[allow(unused_mut)]
86 let mut tls = ClientTlsConfig::new().with_enabled_roots();
87 #[cfg(feature = "tls-rustls")]
88 for pem in crate::tls::env_roots_pem() {
89 tls = tls.ca_certificate(Certificate::from_pem(pem));
90 }
91 tls
92}
93
94#[cfg(feature = "grpc-tls")]
107#[must_use]
108pub fn tls_config_from_pem(
109 extra_roots_pem: Option<&[u8]>,
110 client_identity_pem: Option<(&[u8], &[u8])>,
111) -> ClientTlsConfig {
112 let mut tls = default_client_tls();
113 if let Some(pem) = extra_roots_pem {
114 tls = tls.ca_certificate(Certificate::from_pem(pem));
115 }
116 if let Some((chain, key)) = client_identity_pem {
117 tls = tls.identity(Identity::from_pem(chain, key));
118 }
119 tls
120}
121
122const DEADLINE_GRACE: Duration = Duration::from_millis(500);
132
133#[derive(Debug, Clone)]
150#[non_exhaustive]
151pub struct GrpcTransportConfig {
152 pub timeout: Duration,
154 pub send_timeout: Duration,
157 pub connect_timeout: Duration,
159 pub max_message_size: usize,
161 pub stream_channel_capacity: usize,
163 pub http2_keep_alive_interval: Option<Duration>,
171 pub http2_keep_alive_timeout: Duration,
176 pub bare_address_scheme: GrpcBareAddressScheme,
179 #[cfg(feature = "grpc-tls")]
184 pub tls_config: Option<tonic::transport::ClientTlsConfig>,
185}
186
187impl Default for GrpcTransportConfig {
188 fn default() -> Self {
189 Self {
190 timeout: Duration::from_secs(30),
191 send_timeout: super::DEFAULT_SEND_TIMEOUT,
192 connect_timeout: Duration::from_secs(10),
193 max_message_size: 4 * 1024 * 1024,
194 stream_channel_capacity: 64,
195 http2_keep_alive_interval: None,
196 http2_keep_alive_timeout: Duration::from_secs(20),
197 bare_address_scheme: GrpcBareAddressScheme::default(),
198 #[cfg(feature = "grpc-tls")]
199 tls_config: None,
200 }
201 }
202}
203
204impl GrpcTransportConfig {
205 #[must_use]
209 pub const fn with_http2_keep_alive(mut self, interval: Duration, timeout: Duration) -> Self {
210 self.http2_keep_alive_interval = Some(interval);
211 self.http2_keep_alive_timeout = timeout;
212 self
213 }
214
215 #[must_use]
217 pub const fn with_timeout(mut self, timeout: Duration) -> Self {
218 self.timeout = timeout;
219 self
220 }
221
222 #[must_use]
224 pub const fn with_send_timeout(mut self, timeout: Duration) -> Self {
225 self.send_timeout = timeout;
226 self
227 }
228
229 #[must_use]
231 pub const fn with_connect_timeout(mut self, timeout: Duration) -> Self {
232 self.connect_timeout = timeout;
233 self
234 }
235
236 #[must_use]
238 pub const fn with_max_message_size(mut self, size: usize) -> Self {
239 self.max_message_size = size;
240 self
241 }
242
243 #[must_use]
245 pub const fn with_stream_channel_capacity(mut self, capacity: usize) -> Self {
246 self.stream_channel_capacity = capacity;
247 self
248 }
249
250 #[must_use]
252 pub const fn with_bare_address_scheme(mut self, scheme: GrpcBareAddressScheme) -> Self {
253 self.bare_address_scheme = scheme;
254 self
255 }
256
257 #[cfg(feature = "grpc-tls")]
259 #[must_use]
260 pub fn with_tls_config(mut self, tls: tonic::transport::ClientTlsConfig) -> Self {
261 self.tls_config = Some(tls);
262 self
263 }
264}
265
266pub(crate) fn normalize_endpoint(
274 endpoint: &str,
275 policy: GrpcBareAddressScheme,
276) -> ClientResult<String> {
277 if endpoint.is_empty() {
278 return Err(ClientError::InvalidEndpoint(
279 "gRPC address must not be empty".into(),
280 ));
281 }
282 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
283 return Ok(endpoint.to_owned());
284 }
285 if endpoint.contains("://") {
286 return Err(ClientError::InvalidEndpoint(format!(
287 "gRPC address must be `host:port` or an http(s) URL, got a `{}` URL: {endpoint}",
288 endpoint.split("://").next().unwrap_or_default()
289 )));
290 }
291 let authority: hyper::http::uri::Authority = endpoint.parse().map_err(|e| {
294 ClientError::InvalidEndpoint(format!(
295 "gRPC address must be `host:port` or an http(s) URL: {endpoint}: {e}"
296 ))
297 })?;
298 if endpoint.contains('@') {
299 return Err(ClientError::InvalidEndpoint(format!(
300 "gRPC address must not carry userinfo: {endpoint}"
301 )));
302 }
303 let scheme = match policy {
304 GrpcBareAddressScheme::Http => "http",
305 GrpcBareAddressScheme::Https => "https",
306 GrpcBareAddressScheme::HttpsExceptLoopback => {
307 if crate::loopback::is_loopback_host(authority.host()) {
308 "http"
309 } else {
310 "https"
311 }
312 }
313 };
314 Ok(format!("{scheme}://{authority}"))
315}
316
317#[derive(Clone, Debug)]
325pub struct GrpcTransport {
326 inner: Arc<Inner>,
327}
328
329#[derive(Debug)]
330struct Inner {
331 channel: Channel,
335 endpoint: String,
336 config: GrpcTransportConfig,
337 stream_connect_timeout: Option<Duration>,
349}
350
351impl GrpcTransport {
352 pub async fn connect(endpoint: impl Into<String>) -> ClientResult<Self> {
366 Self::connect_with_config(endpoint, GrpcTransportConfig::default()).await
367 }
368
369 pub async fn connect_with_config(
375 endpoint: impl Into<String>,
376 config: GrpcTransportConfig,
377 ) -> ClientResult<Self> {
378 let raw = endpoint.into();
379 let endpoint_str = normalize_endpoint(&raw, config.bare_address_scheme)?;
380 let tls_by_policy = !raw.contains("://") && endpoint_str.starts_with("https://");
383
384 let endpoint = tonic::transport::Channel::from_shared(endpoint_str.clone())
385 .map_err(|e| ClientError::InvalidEndpoint(format!("invalid gRPC endpoint: {e}")))?
386 .connect_timeout(config.connect_timeout)
387 .tcp_keepalive(Some(super::connector::TCP_KEEPALIVE_TIME))
399 .tcp_keepalive_interval(Some(super::connector::TCP_KEEPALIVE_INTERVAL))
400 .tcp_keepalive_retries(Some(super::connector::TCP_KEEPALIVE_RETRIES));
401 let endpoint = match config.http2_keep_alive_interval {
402 Some(every) => endpoint
403 .http2_keep_alive_interval(every)
404 .keep_alive_timeout(config.http2_keep_alive_timeout)
405 .keep_alive_while_idle(true),
406 None => endpoint,
407 };
408 let endpoint = Self::apply_tls(endpoint, &endpoint_str, &config)?;
409 let channel = Self::dial(&endpoint, &endpoint_str, &config)
410 .await
411 .map_err(|e| {
412 if tls_by_policy {
413 ClientError::Transport(format!(
414 "gRPC connect failed: {e} (`{raw}` was dialled with TLS by \
415 {:?}; if this peer speaks plaintext, set \
416 GrpcBareAddressScheme::Http)",
417 config.bare_address_scheme
418 ))
419 } else {
420 ClientError::Transport(format!("gRPC connect failed: {e}"))
421 }
422 })?;
423
424 Ok(Self {
425 inner: Arc::new(Inner {
426 channel,
427 endpoint: endpoint_str,
428 config,
429 stream_connect_timeout: None,
430 }),
431 })
432 }
433
434 fn apply_tls(
450 endpoint: tonic::transport::Endpoint,
451 endpoint_str: &str,
452 config: &GrpcTransportConfig,
453 ) -> ClientResult<tonic::transport::Endpoint> {
454 if !endpoint_str.starts_with("https://") {
455 return Ok(endpoint);
456 }
457 #[cfg(feature = "grpc-tls")]
458 {
459 let tls = config.tls_config.clone().unwrap_or_else(default_client_tls);
467 endpoint.tls_config(tls).map_err(|e| {
468 ClientError::Transport(format!("gRPC TLS configuration rejected: {e}"))
469 })
470 }
471 #[cfg(not(feature = "grpc-tls"))]
472 {
473 let _ = (endpoint, config);
474 Err(ClientError::Transport(format!(
475 "gRPC over TLS needs the `grpc-tls` feature of a2a-protocol-client; \
476 this build has no TLS connector for {endpoint_str}"
477 )))
478 }
479 }
480
481 #[must_use]
502 pub fn with_stream_connect_timeout(mut self, timeout: Duration) -> Self {
503 let inner = Arc::new(Inner {
507 channel: self.inner.channel.clone(),
508 endpoint: self.inner.endpoint.clone(),
509 config: self.inner.config.clone(),
510 stream_connect_timeout: Some(timeout),
511 });
512 self.inner = inner;
513 self
514 }
515
516 fn stream_open_bound(&self) -> Duration {
522 self.inner
523 .stream_connect_timeout
524 .unwrap_or(self.inner.config.timeout)
525 }
526
527 #[must_use]
529 pub fn endpoint(&self) -> &str {
530 &self.inner.endpoint
531 }
532
533 fn client(&self) -> A2aServiceClient<Channel> {
536 A2aServiceClient::new(self.inner.channel.clone())
540 .max_decoding_message_size(self.inner.config.max_message_size)
541 .max_encoding_message_size(self.inner.config.max_message_size)
542 }
543
544 fn request<T>(
545 &self,
546 message: T,
547 extra_headers: &HashMap<String, String>,
548 with_deadline: bool,
549 ) -> ClientResult<tonic::Request<T>> {
550 let mut req = tonic::Request::new(message);
551 if with_deadline {
552 req.set_timeout(self.inner.config.timeout + DEADLINE_GRACE);
553 }
554 Self::add_metadata(&mut req, extra_headers)?;
555 Ok(req)
556 }
557
558 fn add_metadata<T>(
559 req: &mut tonic::Request<T>,
560 extra_headers: &HashMap<String, String>,
561 ) -> ClientResult<()> {
562 let md = req.metadata_mut();
563 md.insert(
564 "a2a-version",
565 a2a_protocol_types::A2A_VERSION
566 .parse()
567 .unwrap_or_else(|_| tonic::metadata::MetadataValue::from_static("")),
568 );
569 for (k, v) in extra_headers {
570 let key = k.parse::<tonic::metadata::MetadataKey<_>>().map_err(|e| {
577 ClientError::Transport(format!("invalid gRPC metadata key {k:?}: {e}"))
578 })?;
579 let val = v
580 .parse::<tonic::metadata::MetadataValue<_>>()
581 .map_err(|_| {
582 ClientError::Transport(format!("invalid gRPC metadata value for key {k:?}"))
583 })?;
584 md.insert(key, val);
585 }
586 Ok(())
587 }
588
589 fn parse_params<T: serde::de::DeserializeOwned>(params: serde_json::Value) -> ClientResult<T> {
590 serde_json::from_value(params).map_err(ClientError::Serialization)
591 }
592
593 fn to_json<T: serde::Serialize>(value: &T) -> ClientResult<serde_json::Value> {
594 serde_json::to_value(value).map_err(ClientError::Serialization)
595 }
596
597 fn unavailable_to_error(status: &tonic::Status) -> ClientError {
603 use tonic_types::StatusExt as _;
604 let halted = with_detail_data(
607 a2a_protocol_types::A2aError::new(
608 a2a_protocol_types::ErrorCode::InternalError,
609 status.message(),
610 ),
611 status,
612 );
613 if a2a_protocol_types::halt::is_halted(&halted) {
614 return ClientError::Protocol(halted);
615 }
616 status
617 .get_details_retry_info()
618 .and_then(|i| i.retry_delay)
619 .map_or_else(
620 || ClientError::HttpClient(format!("gRPC unavailable: {}", status.message())),
621 |delay| ClientError::UnexpectedStatus {
622 status: 503,
623 body: status.message().to_owned(),
624 retry_after: Some(delay.min(std::time::Duration::from_secs(3600))),
625 },
626 )
627 }
628
629 async fn dial(
634 endpoint: &tonic::transport::Endpoint,
635 endpoint_str: &str,
636 config: &GrpcTransportConfig,
637 ) -> Result<tonic::transport::Channel, tonic::transport::Error> {
638 #[cfg(feature = "tls-rustls")]
639 if let Ok(dst) = endpoint_str.parse::<hyper::Uri>() {
640 let tcp = super::connector::http_connector(config.connect_timeout);
641 if let Some(tunnel) = crate::proxy::grpc_tunnel(&dst, tcp) {
642 return endpoint.connect_with_connector(tunnel).await;
643 }
644 }
645 #[cfg(not(feature = "tls-rustls"))]
646 let _ = (endpoint_str, config);
647 endpoint.connect().await
648 }
649
650 fn status_to_error(status: &tonic::Status) -> ClientError {
651 if is_truncation(status) {
652 return ClientError::HttpClient(format!("gRPC {}", status.message()));
657 }
658 match status.code() {
659 tonic::Code::DeadlineExceeded => {
662 ClientError::Timeout(format!("gRPC deadline exceeded: {}", status.message()))
663 }
664 tonic::Code::Unauthenticated => ClientError::UnexpectedStatus {
672 status: 401,
673 body: status.message().to_owned(),
674 retry_after: None,
675 },
676 tonic::Code::PermissionDenied => ClientError::UnexpectedStatus {
677 status: 403,
678 body: status.message().to_owned(),
679 retry_after: None,
680 },
681 tonic::Code::Unavailable => Self::unavailable_to_error(status),
682 tonic::Code::ResourceExhausted => {
693 use tonic_types::StatusExt as _;
694 ClientError::UnexpectedStatus {
695 status: 429,
696 body: status.message().to_owned(),
697 retry_after: status
698 .get_details_retry_info()
699 .and_then(|info| info.retry_delay)
700 .map(|d| d.min(std::time::Duration::from_secs(3600))),
701 }
702 }
703 _ => {
709 use tonic_types::StatusExt as _;
715 let code = status
716 .get_details_error_info()
717 .and_then(|info| a2a_protocol_types::ErrorCode::from_a2a_reason(&info.reason))
718 .unwrap_or_else(|| grpc_code_to_error_code(status.code()));
719 let message = if status.code() == tonic::Code::Cancelled {
720 format!("gRPC call cancelled by the peer: {}", status.message())
721 } else {
722 status.message().to_owned()
723 };
724 ClientError::Protocol(with_detail_data(
725 a2a_protocol_types::A2aError::new(code, message),
726 status,
727 ))
728 }
729 }
730 }
731
732 async fn execute_unary(
733 &self,
734 method: &str,
735 params: serde_json::Value,
736 extra_headers: &HashMap<String, String>,
737 ) -> ClientResult<serde_json::Value> {
738 trace_info!(
739 method,
740 endpoint = %self.inner.endpoint,
741 "sending gRPC request"
742 );
743
744 let mut client = self.client();
745 let waits = super::waits_for_turn(method, ¶ms);
746 let budget = if waits {
747 self.inner.config.send_timeout
748 } else {
749 self.inner.config.timeout
750 };
751 tokio::time::timeout(
752 budget,
753 self.dispatch_unary(&mut client, method, params, extra_headers),
754 )
755 .await
756 .map_err(|_| {
757 trace_error!(method, "gRPC request timed out");
758 super::timed_out(waits, budget)
759 })?
760 }
761
762 #[allow(clippy::too_many_lines)]
768 async fn dispatch_unary(
769 &self,
770 client: &mut A2aServiceClient<Channel>,
771 method: &str,
772 params: serde_json::Value,
773 extra_headers: &HashMap<String, String>,
774 ) -> ClientResult<serde_json::Value> {
775 match method {
776 "SendMessage" => {
777 let waits = super::waits_for_turn(method, ¶ms);
778 let p: a2a_protocol_types::params::MessageSendParams = Self::parse_params(params)?;
779 let req = apb::SendMessageRequest::try_from(p).map_err(convert_error)?;
780 let mut req = self.request(req, extra_headers, true)?;
781 if waits {
785 req.set_timeout(self.inner.config.send_timeout + DEADLINE_GRACE);
786 }
787 let resp = client
788 .send_message(req)
789 .await
790 .map_err(|s| Self::status_to_error(&s))?;
791 let domain: a2a_protocol_types::responses::SendMessageResponse = resp
792 .into_inner()
793 .try_into()
794 .map_err(|e| invalid_response(method, &e))?;
795 Self::to_json(&domain)
796 }
797 "GetTask" => {
798 let p: a2a_protocol_types::params::TaskQueryParams = Self::parse_params(params)?;
799 let req = apb::GetTaskRequest::try_from(p).map_err(convert_error)?;
800 let resp = client
801 .get_task(self.request(req, extra_headers, true)?)
802 .await
803 .map_err(|s| Self::status_to_error(&s))?;
804 let domain: a2a_protocol_types::task::Task = resp
805 .into_inner()
806 .try_into()
807 .map_err(|e| invalid_response(method, &e))?;
808 Self::to_json(&domain)
809 }
810 "ListTasks" => {
811 let p: a2a_protocol_types::params::ListTasksParams = Self::parse_params(params)?;
812 let req = apb::ListTasksRequest::try_from(p).map_err(convert_error)?;
813 let resp = client
814 .list_tasks(self.request(req, extra_headers, true)?)
815 .await
816 .map_err(|s| Self::status_to_error(&s))?;
817 let domain: a2a_protocol_types::responses::TaskListResponse = resp
818 .into_inner()
819 .try_into()
820 .map_err(|e| invalid_response(method, &e))?;
821 Self::to_json(&domain)
822 }
823 "CancelTask" => {
824 let p: a2a_protocol_types::params::CancelTaskParams = Self::parse_params(params)?;
825 let req = apb::CancelTaskRequest::try_from(p).map_err(convert_error)?;
826 let resp = client
827 .cancel_task(self.request(req, extra_headers, true)?)
828 .await
829 .map_err(|s| Self::status_to_error(&s))?;
830 let domain: a2a_protocol_types::task::Task = resp
831 .into_inner()
832 .try_into()
833 .map_err(|e| invalid_response(method, &e))?;
834 Self::to_json(&domain)
835 }
836 "CreateTaskPushNotificationConfig" => {
837 let p: a2a_protocol_types::push::TaskPushNotificationConfig =
838 Self::parse_params(params)?;
839 let req = apb::TaskPushNotificationConfig::from(p);
840 let resp = client
841 .create_task_push_notification_config(self.request(req, extra_headers, true)?)
842 .await
843 .map_err(|s| Self::status_to_error(&s))?;
844 let domain: a2a_protocol_types::push::TaskPushNotificationConfig =
845 resp.into_inner().into();
846 Self::to_json(&domain)
847 }
848 "GetTaskPushNotificationConfig" => {
849 let p: a2a_protocol_types::params::GetPushConfigParams =
850 Self::parse_params(params)?;
851 let req = apb::GetTaskPushNotificationConfigRequest::from(p);
852 let resp = client
853 .get_task_push_notification_config(self.request(req, extra_headers, true)?)
854 .await
855 .map_err(|s| Self::status_to_error(&s))?;
856 let domain: a2a_protocol_types::push::TaskPushNotificationConfig =
857 resp.into_inner().into();
858 Self::to_json(&domain)
859 }
860 "ListTaskPushNotificationConfigs" => {
861 let p: a2a_protocol_types::params::ListPushConfigsParams =
862 Self::parse_params(params)?;
863 let req = apb::ListTaskPushNotificationConfigsRequest::try_from(p)
864 .map_err(convert_error)?;
865 let resp = client
866 .list_task_push_notification_configs(self.request(req, extra_headers, true)?)
867 .await
868 .map_err(|s| Self::status_to_error(&s))?;
869 let domain: a2a_protocol_types::responses::ListPushConfigsResponse =
870 resp.into_inner().into();
871 Self::to_json(&domain)
872 }
873 "DeleteTaskPushNotificationConfig" => {
874 let p: a2a_protocol_types::params::DeletePushConfigParams =
875 Self::parse_params(params)?;
876 let req = apb::DeleteTaskPushNotificationConfigRequest::from(p);
877 client
878 .delete_task_push_notification_config(self.request(req, extra_headers, true)?)
879 .await
880 .map_err(|s| Self::status_to_error(&s))?;
881 Ok(serde_json::json!({}))
882 }
883 "GetExtendedAgentCard" => {
884 let params = if params.is_null() {
886 serde_json::json!({})
887 } else {
888 params
889 };
890 let p: a2a_protocol_types::params::GetExtendedAgentCardParams =
891 Self::parse_params(params)?;
892 let req = apb::GetExtendedAgentCardRequest::from(p);
893 let resp = client
894 .get_extended_agent_card(self.request(req, extra_headers, true)?)
895 .await
896 .map_err(|s| Self::status_to_error(&s))?;
897 let domain: a2a_protocol_types::agent_card::AgentCard = resp
898 .into_inner()
899 .try_into()
900 .map_err(|e| invalid_response(method, &e))?;
901 Self::to_json(&domain)
902 }
903 other => Err(ClientError::Protocol(a2a_protocol_types::A2aError::new(
904 a2a_protocol_types::ErrorCode::MethodNotFound,
905 format!("unknown gRPC method: {other}"),
906 ))),
907 }
908 }
909
910 async fn execute_streaming(
911 &self,
912 method: &str,
913 params: serde_json::Value,
914 extra_headers: &HashMap<String, String>,
915 ) -> ClientResult<EventStream> {
916 trace_info!(
917 method,
918 endpoint = %self.inner.endpoint,
919 "opening gRPC stream"
920 );
921
922 let mut client = self.client();
923 let stream = tokio::time::timeout(self.stream_open_bound(), async {
924 match method {
925 "SendStreamingMessage" => {
926 let p: a2a_protocol_types::params::MessageSendParams =
927 Self::parse_params(params)?;
928 let req = apb::SendMessageRequest::try_from(p).map_err(convert_error)?;
929 client
930 .send_streaming_message(self.request(req, extra_headers, false)?)
933 .await
934 .map(tonic::Response::into_inner)
935 .map_err(|s| Self::status_to_error(&s))
936 }
937 "SubscribeToTask" => {
938 let p: a2a_protocol_types::params::TaskIdParams = Self::parse_params(params)?;
939 let req = apb::SubscribeToTaskRequest::from(p);
940 client
941 .subscribe_to_task(self.request(req, extra_headers, false)?)
942 .await
943 .map(tonic::Response::into_inner)
944 .map_err(|s| Self::status_to_error(&s))
945 }
946 other => Err(ClientError::Protocol(a2a_protocol_types::A2aError::new(
947 a2a_protocol_types::ErrorCode::MethodNotFound,
948 format!("unknown streaming gRPC method: {other}"),
949 ))),
950 }
951 })
952 .await
953 .map_err(|_| {
954 trace_error!(method, "gRPC stream connect timed out");
955 ClientError::Timeout("gRPC stream connect timed out".into())
956 })??;
957
958 let cap = self.inner.config.stream_channel_capacity;
959 let (tx, rx) = mpsc::channel::<crate::streaming::event_stream::BodyChunk>(cap);
960
961 let task_handle = tokio::spawn(async move {
962 grpc_stream_reader_task(stream, tx).await;
963 });
964
965 Ok(
974 EventStream::with_status(rx, task_handle.abort_handle(), 200)
975 .with_first_event_timeout(crate::config::DEFAULT_STREAM_FIRST_EVENT_TIMEOUT),
976 )
977 }
978}
979
980impl Transport for GrpcTransport {
981 fn rpc_system(&self) -> Option<&'static str> {
985 Some("grpc")
986 }
987
988 fn server_url(&self) -> Option<&str> {
991 Some(&self.inner.endpoint)
992 }
993
994 fn send_request<'a>(
995 &'a self,
996 method: &'a str,
997 params: serde_json::Value,
998 extra_headers: &'a HashMap<String, String>,
999 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>> {
1000 Box::pin(self.execute_unary(method, params, extra_headers))
1001 }
1002
1003 fn send_streaming_request<'a>(
1004 &'a self,
1005 method: &'a str,
1006 params: serde_json::Value,
1007 extra_headers: &'a HashMap<String, String>,
1008 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
1009 Box::pin(self.execute_streaming(method, params, extra_headers))
1010 }
1011}
1012
1013async fn grpc_stream_reader_task<S>(
1023 mut stream: S,
1024 tx: mpsc::Sender<crate::streaming::event_stream::BodyChunk>,
1025) where
1026 S: tonic::codegen::tokio_stream::Stream<Item = Result<apb::StreamResponse, tonic::Status>>
1027 + Unpin,
1028{
1029 use tonic::codegen::tokio_stream::StreamExt;
1030
1031 loop {
1032 match stream.next().await {
1033 Some(Ok(pb_event)) => {
1034 let event: a2a_protocol_types::events::StreamResponse = match pb_event
1035 .try_into()
1036 .map_err(|e| invalid_response("streamed event", &e))
1037 {
1038 Ok(e) => e,
1039 Err(err) => {
1040 let _ = tx.send(Err(err)).await;
1041 break;
1042 }
1043 };
1044 let json_str = match serde_json::to_string(&event) {
1045 Ok(s) => s,
1046 Err(e) => {
1047 let _ = tx.send(Err(ClientError::Serialization(e))).await;
1048 break;
1049 }
1050 };
1051 let envelope =
1054 format!("data: {{\"jsonrpc\":\"2.0\",\"id\":null,\"result\":{json_str}}}\n\n");
1055 if tx
1056 .send(Ok(hyper::body::Bytes::from(envelope)))
1057 .await
1058 .is_err()
1059 {
1060 break;
1061 }
1062 }
1063 Some(Err(status)) if is_truncation(&status) => break,
1070 Some(Err(status)) => {
1071 let _ = tx.send(Err(GrpcTransport::status_to_error(&status))).await;
1076 break;
1077 }
1078 None => break,
1079 }
1080 }
1081}
1082
1083const STRUCT_DETAIL_TYPE: &str = "type.googleapis.com/google.protobuf.Struct";
1088
1089fn with_detail_data(
1096 mut err: a2a_protocol_types::A2aError,
1097 status: &tonic::Status,
1098) -> a2a_protocol_types::A2aError {
1099 use a2a_protocol_types::proto::prost_types;
1100 use prost::Message as _;
1101 use tonic_types::StatusExt as _;
1102 let object = tonic_types::pb::Status::decode(status.details())
1103 .ok()
1104 .and_then(|carried| {
1105 carried
1106 .details
1107 .into_iter()
1108 .find(|d| d.type_url == STRUCT_DETAIL_TYPE)
1109 })
1110 .and_then(|d| prost_types::Struct::decode(d.value.as_slice()).ok())
1111 .and_then(|s| a2a_protocol_types::proto::convert::struct_to_json(s).ok());
1112 if object.is_some() {
1113 err.data = object;
1114 } else if let Some(bad) = status.get_details_bad_request() {
1115 let violations: Vec<_> = bad
1116 .field_violations
1117 .iter()
1118 .map(|v| serde_json::json!({ "field": v.field, "description": v.description }))
1119 .collect();
1120 err.data = Some(serde_json::json!({
1121 "@type": "type.googleapis.com/google.rpc.BadRequest",
1122 "fieldViolations": violations,
1123 }));
1124 }
1125 err
1126}
1127
1128fn is_truncation(status: &tonic::Status) -> bool {
1135 status.code() == tonic::Code::Unknown
1136 && status
1137 .message()
1138 .starts_with("protocol error: missing grpc-status trailer")
1139}
1140
1141#[allow(clippy::needless_pass_by_value)]
1144fn convert_error(err: ConvertError) -> ClientError {
1145 ClientError::Transport(format!("protobuf conversion failed: {err}"))
1146}
1147
1148fn invalid_response(what: &str, err: &ConvertError) -> ClientError {
1154 ClientError::InvalidAgentResponse(format!("{what} over gRPC: {err}"))
1155}
1156
1157const fn grpc_code_to_error_code(code: tonic::Code) -> a2a_protocol_types::ErrorCode {
1158 match code {
1162 tonic::Code::NotFound => a2a_protocol_types::ErrorCode::TaskNotFound,
1163 tonic::Code::InvalidArgument => a2a_protocol_types::ErrorCode::InvalidParams,
1167 tonic::Code::Unimplemented => a2a_protocol_types::ErrorCode::MethodNotFound,
1168 tonic::Code::FailedPrecondition => a2a_protocol_types::ErrorCode::TaskNotCancelable,
1169 _ => a2a_protocol_types::ErrorCode::InternalError,
1170 }
1171}
1172
1173#[cfg(test)]
1176mod tests {
1177 use super::*;
1178 use a2a_protocol_types::events::TaskStatusUpdateEvent;
1179 use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};
1180
1181 use GrpcBareAddressScheme as Scheme;
1184
1185 fn norm(endpoint: &str, policy: Scheme) -> ClientResult<String> {
1186 normalize_endpoint(endpoint, policy)
1187 }
1188
1189 #[test]
1190 fn normalize_rejects_empty() {
1191 assert!(matches!(
1192 norm("", Scheme::default()),
1193 Err(ClientError::InvalidEndpoint(_))
1194 ));
1195 }
1196
1197 #[test]
1198 fn normalize_rejects_other_schemes_by_name() {
1199 for bad in [
1200 "ftp://example.com",
1201 "ws://example.com:1",
1202 "grpc://example.com:443",
1203 ] {
1204 let err = norm(bad, Scheme::default()).unwrap_err();
1205 let msg = err.to_string();
1206 assert!(
1207 matches!(err, ClientError::InvalidEndpoint(_)) && msg.contains(bad),
1208 "{bad}: expected InvalidEndpoint naming the input, got {msg}"
1209 );
1210 }
1211 }
1212
1213 #[test]
1214 fn normalize_passes_http_and_https_urls_through_unchanged() {
1215 for url in [
1216 "http://localhost:50051",
1217 "https://agent.example.com:443",
1218 "http://10.0.0.5:9",
1219 ] {
1220 for policy in [Scheme::HttpsExceptLoopback, Scheme::Https, Scheme::Http] {
1221 assert_eq!(
1222 norm(url, policy).unwrap(),
1223 url,
1224 "policy must not touch a URL"
1225 );
1226 }
1227 }
1228 }
1229
1230 #[test]
1232 fn normalize_bare_address_default_is_tls_for_a_remote_host() {
1233 assert_eq!(
1234 norm("grpc.example.com:443", Scheme::default()).unwrap(),
1235 "https://grpc.example.com:443"
1236 );
1237 assert_eq!(
1238 norm("grpc.example.com", Scheme::default()).unwrap(),
1239 "https://grpc.example.com",
1240 "a target without a port keeps the scheme's default port"
1241 );
1242 }
1243
1244 #[test]
1245 fn normalize_bare_address_default_is_plaintext_for_loopback() {
1246 for local in [
1247 "localhost:50051",
1248 "LOCALHOST:50051",
1249 "127.0.0.1:9998",
1250 "127.9.8.7:1",
1251 "[::1]:50051",
1252 ] {
1253 let got = norm(local, Scheme::default()).unwrap();
1254 assert_eq!(got, format!("http://{local}"), "{local} is loopback");
1255 }
1256 for remote in [
1258 "10.0.0.5:50051",
1259 "[fe80::1]:50051",
1260 "0.0.0.0:50051",
1261 "127.example.com:1",
1262 ] {
1263 let got = norm(remote, Scheme::default()).unwrap();
1264 assert_eq!(got, format!("https://{remote}"), "{remote} is not loopback");
1265 }
1266 }
1267
1268 #[test]
1269 fn normalize_explicit_policies_override_the_loopback_rule() {
1270 assert_eq!(
1271 norm("localhost:1", Scheme::Https).unwrap(),
1272 "https://localhost:1"
1273 );
1274 assert_eq!(
1275 norm("agent:50051", Scheme::Http).unwrap(),
1276 "http://agent:50051",
1277 "a Compose service name on a private network"
1278 );
1279 }
1280
1281 #[test]
1282 fn normalize_rejects_paths_and_userinfo() {
1283 for bad in [
1284 "agent:50051/a2a",
1285 "user:pw@agent:50051",
1286 "agent:50051?x=1",
1287 "a b:1",
1288 ] {
1289 assert!(
1290 matches!(
1291 norm(bad, Scheme::default()),
1292 Err(ClientError::InvalidEndpoint(_))
1293 ),
1294 "{bad} is not a gRPC target"
1295 );
1296 }
1297 }
1298
1299 #[test]
1300 fn config_default_timeout() {
1301 let cfg = GrpcTransportConfig::default();
1302 assert_eq!(cfg.timeout, Duration::from_secs(30));
1303 }
1304
1305 #[test]
1306 fn config_builder() {
1307 let cfg = GrpcTransportConfig::default()
1308 .with_timeout(Duration::from_secs(60))
1309 .with_max_message_size(8 * 1024 * 1024)
1310 .with_stream_channel_capacity(128);
1311 assert_eq!(cfg.timeout, Duration::from_secs(60));
1312 assert_eq!(cfg.max_message_size, 8 * 1024 * 1024);
1313 assert_eq!(cfg.stream_channel_capacity, 128);
1314 }
1315
1316 #[cfg(feature = "grpc-tls")]
1319 #[test]
1320 fn with_tls_config_stores_it_and_keeps_the_rest() {
1321 let cfg = GrpcTransportConfig::default()
1322 .with_timeout(Duration::from_secs(60))
1323 .with_tls_config(
1324 tonic::transport::ClientTlsConfig::new().domain_name("agent.internal"),
1325 );
1326 assert!(cfg.tls_config.is_some(), "the TLS config must be stored");
1327 assert_eq!(
1328 cfg.timeout,
1329 Duration::from_secs(60),
1330 "fields set before with_tls_config must not be reset"
1331 );
1332 }
1333
1334 #[test]
1335 fn convert_error_maps_to_non_retryable_transport() {
1336 let err = convert_error(ConvertError::new("part.raw", "invalid base64"));
1337 assert!(
1338 matches!(err, ClientError::Transport(_)),
1339 "conversion failures must be non-retryable: {err:?}"
1340 );
1341 assert!(!err.is_retryable());
1342 }
1343
1344 #[test]
1345 fn grpc_code_not_found_maps_to_task_not_found() {
1346 assert_eq!(
1347 grpc_code_to_error_code(tonic::Code::NotFound),
1348 a2a_protocol_types::ErrorCode::TaskNotFound,
1349 );
1350 }
1351
1352 #[test]
1353 fn grpc_code_invalid_argument_maps_to_invalid_params() {
1354 assert_eq!(
1355 grpc_code_to_error_code(tonic::Code::InvalidArgument),
1356 a2a_protocol_types::ErrorCode::InvalidParams,
1357 );
1358 }
1359
1360 #[test]
1361 fn grpc_code_unimplemented_maps_to_method_not_found() {
1362 assert_eq!(
1363 grpc_code_to_error_code(tonic::Code::Unimplemented),
1364 a2a_protocol_types::ErrorCode::MethodNotFound,
1365 );
1366 }
1367
1368 #[test]
1369 fn grpc_code_failed_precondition_maps_to_task_not_cancelable() {
1370 assert_eq!(
1371 grpc_code_to_error_code(tonic::Code::FailedPrecondition),
1372 a2a_protocol_types::ErrorCode::TaskNotCancelable,
1373 );
1374 }
1375
1376 #[test]
1377 fn grpc_code_deadline_exceeded_maps_to_internal() {
1378 assert_eq!(
1379 grpc_code_to_error_code(tonic::Code::DeadlineExceeded),
1380 a2a_protocol_types::ErrorCode::InternalError,
1381 );
1382 }
1383
1384 #[test]
1385 fn grpc_code_cancelled_maps_to_internal() {
1386 assert_eq!(
1387 grpc_code_to_error_code(tonic::Code::Cancelled),
1388 a2a_protocol_types::ErrorCode::InternalError,
1389 );
1390 }
1391
1392 #[test]
1393 fn grpc_code_unknown_maps_to_internal() {
1394 assert_eq!(
1395 grpc_code_to_error_code(tonic::Code::Unknown),
1396 a2a_protocol_types::ErrorCode::InternalError,
1397 );
1398 }
1399
1400 #[test]
1401 fn add_metadata_injects_a2a_version() {
1402 let mut req = tonic::Request::new(());
1403 let headers = HashMap::new();
1404 GrpcTransport::add_metadata(&mut req, &headers).expect("valid headers");
1405 let md = req.metadata();
1406 let version_value = md
1407 .get("a2a-version")
1408 .expect("a2a-version header should be present");
1409 assert_eq!(
1410 version_value.to_str().unwrap(),
1411 a2a_protocol_types::A2A_VERSION,
1412 );
1413 }
1414
1415 #[test]
1416 fn add_metadata_injects_extra_headers() {
1417 let mut req = tonic::Request::new(());
1418 let mut headers = HashMap::new();
1419 headers.insert("x-custom".to_string(), "value123".to_string());
1420 GrpcTransport::add_metadata(&mut req, &headers).expect("valid headers");
1421 let md = req.metadata();
1422 assert_eq!(md.get("x-custom").unwrap().to_str().unwrap(), "value123",);
1423 }
1424
1425 #[test]
1426 fn add_metadata_fails_closed_on_invalid_header() {
1427 let mut req = tonic::Request::new(());
1431 let mut headers = HashMap::new();
1432 headers.insert("authorization".to_string(), "Bearer bad\nvalue".to_string());
1433 let result = GrpcTransport::add_metadata(&mut req, &headers);
1434 assert!(
1435 matches!(result, Err(ClientError::Transport(_))),
1436 "invalid metadata must fail closed, got: {result:?}"
1437 );
1438 if let Err(ClientError::Transport(msg)) = result {
1440 assert!(!msg.contains("Bearer bad"), "value leaked in error: {msg}");
1441 }
1442 }
1443
1444 #[test]
1445 fn resource_exhausted_maps_to_retryable_429() {
1446 let status = tonic::Status::resource_exhausted("slow down");
1447 let err = GrpcTransport::status_to_error(&status);
1448 assert!(
1449 matches!(err, ClientError::UnexpectedStatus { status: 429, .. }),
1450 "ResourceExhausted should map to 429, got {err:?}"
1451 );
1452 assert!(
1453 err.is_retryable(),
1454 "gRPC ResourceExhausted must be retryable"
1455 );
1456 }
1457
1458 #[test]
1463 fn only_the_missing_trailer_status_is_a_truncation() {
1464 let truncated = tonic::Status::unknown(
1465 "protocol error: missing grpc-status trailer, stream was terminated without a final status",
1466 );
1467 assert!(is_truncation(&truncated));
1468 assert!(matches!(
1469 GrpcTransport::status_to_error(&truncated),
1470 ClientError::HttpClient(_)
1471 ));
1472 let peer_unknown = tonic::Status::unknown("the agent did not say why");
1473 assert!(!is_truncation(&peer_unknown));
1474 assert!(matches!(
1475 GrpcTransport::status_to_error(&peer_unknown),
1476 ClientError::Protocol(_)
1477 ));
1478 let same_words = tonic::Status::internal(
1479 "protocol error: missing grpc-status trailer, stream was terminated without a final status",
1480 );
1481 assert!(!is_truncation(&same_words));
1482 }
1483
1484 #[test]
1487 fn status_to_error_deadline_exceeded_is_timeout() {
1488 let status = tonic::Status::deadline_exceeded("test deadline");
1489 let err = GrpcTransport::status_to_error(&status);
1490 assert!(
1491 matches!(err, ClientError::Timeout(_)),
1492 "DeadlineExceeded should map to Timeout, got: {err:?}"
1493 );
1494 }
1495
1496 #[test]
1497 fn status_to_error_cancelled_is_a_non_retryable_protocol_error() {
1498 let status = tonic::Status::cancelled("test cancel");
1499 let err = GrpcTransport::status_to_error(&status);
1500 match &err {
1501 ClientError::Protocol(e) => {
1502 assert_eq!(e.code, a2a_protocol_types::ErrorCode::InternalError);
1503 assert!(e.message.contains("cancelled by the peer"), "{e:?}");
1504 assert!(e.message.contains("test cancel"), "{e:?}");
1505 }
1506 other => panic!("Cancelled should map to Protocol, got: {other:?}"),
1507 }
1508 assert!(!err.is_retryable());
1509 }
1510
1511 #[test]
1512 fn status_to_error_cancelled_keeps_an_error_info_reason() {
1513 use tonic_types::StatusExt as _;
1514 let mut details = tonic_types::ErrorDetails::new();
1515 details.set_error_info(
1516 "TASK_NOT_FOUND",
1517 a2a_protocol_types::error::A2A_ERROR_DOMAIN,
1518 std::collections::HashMap::<String, String>::new(),
1519 );
1520 let status = tonic::Status::with_error_details(tonic::Code::Cancelled, "gone", details);
1521 match GrpcTransport::status_to_error(&status) {
1522 ClientError::Protocol(e) => {
1523 assert_eq!(e.code, a2a_protocol_types::ErrorCode::TaskNotFound);
1524 }
1525 other => panic!("expected Protocol, got: {other:?}"),
1526 }
1527 }
1528
1529 #[test]
1530 fn status_to_error_unauthenticated_is_401() {
1531 let err = GrpcTransport::status_to_error(&tonic::Status::unauthenticated("bad token"));
1532 match &err {
1533 ClientError::UnexpectedStatus {
1534 status,
1535 body,
1536 retry_after,
1537 } => {
1538 assert_eq!(*status, 401);
1539 assert_eq!(body, "bad token");
1540 assert!(retry_after.is_none());
1541 }
1542 other => panic!("expected a 401, got: {other:?}"),
1543 }
1544 assert!(!err.is_retryable());
1545 }
1546
1547 #[test]
1548 fn status_to_error_permission_denied_is_403() {
1549 let err = GrpcTransport::status_to_error(&tonic::Status::permission_denied("no"));
1550 match &err {
1551 ClientError::UnexpectedStatus { status, body, .. } => {
1552 assert_eq!(*status, 403);
1553 assert_eq!(body, "no");
1554 }
1555 other => panic!("expected a 403, got: {other:?}"),
1556 }
1557 assert!(!err.is_retryable());
1558 }
1559
1560 #[test]
1561 fn status_to_error_unavailable_is_http_client() {
1562 let status = tonic::Status::unavailable("test unavailable");
1563 let err = GrpcTransport::status_to_error(&status);
1564 assert!(
1565 matches!(err, ClientError::HttpClient(_)),
1566 "Unavailable should map to HttpClient, got: {err:?}"
1567 );
1568 }
1569
1570 #[test]
1571 fn status_to_error_other_is_protocol() {
1572 let status = tonic::Status::internal("test internal");
1573 let err = GrpcTransport::status_to_error(&status);
1574 assert!(
1575 matches!(err, ClientError::Protocol(_)),
1576 "other codes should map to Protocol, got: {err:?}"
1577 );
1578 }
1579
1580 #[test]
1585 fn status_to_error_keeps_a_struct_detail_as_data() {
1586 use a2a_protocol_types::proto::prost_types;
1587 use prost::Message as _;
1588 let data = a2a_protocol_types::proto::convert::json_to_struct(
1589 serde_json::json!({ "streamLagged": 3 }),
1590 )
1591 .expect("a Struct");
1592 let carried = tonic_types::pb::Status {
1593 code: tonic::Code::Internal as i32,
1594 message: "lagged".into(),
1595 details: vec![prost_types::Any {
1596 type_url: STRUCT_DETAIL_TYPE.into(),
1597 value: data.encode_to_vec(),
1598 }],
1599 };
1600 let status = tonic::Status::with_details(
1601 tonic::Code::Internal,
1602 "lagged",
1603 carried.encode_to_vec().into(),
1604 );
1605 let ClientError::Protocol(err) = GrpcTransport::status_to_error(&status) else {
1606 panic!("a Protocol error");
1607 };
1608 assert!(err.is_stream_lagged(), "{err:?}");
1609 assert_eq!(err.dropped_event_count(), Some(3));
1610 }
1611
1612 #[test]
1616 fn resource_exhausted_keeps_the_servers_retry_delay() {
1617 use tonic_types::StatusExt as _;
1618 let delay = |d: Option<std::time::Duration>| {
1619 let status = d.map_or_else(
1620 || tonic::Status::new(tonic::Code::ResourceExhausted, "slow down"),
1621 |d| {
1622 tonic::Status::with_error_details(
1623 tonic::Code::ResourceExhausted,
1624 "slow down",
1625 tonic_types::ErrorDetails::with_retry_info(Some(d)),
1626 )
1627 },
1628 );
1629 match GrpcTransport::status_to_error(&status) {
1630 ClientError::UnexpectedStatus {
1631 status: 429,
1632 retry_after,
1633 ..
1634 } => retry_after,
1635 other => panic!("a 429, got {other:?}"),
1636 }
1637 };
1638 let secs = std::time::Duration::from_secs;
1639 assert_eq!(delay(Some(secs(7))), Some(secs(7)));
1640 assert_eq!(delay(Some(secs(86_400))), Some(secs(3600)));
1641 assert_eq!(delay(None), None);
1642 }
1643
1644 #[test]
1648 fn unavailable_with_a_delay_is_a_refusal_a_send_may_repeat() {
1649 use tonic_types::StatusExt as _;
1650 let status = tonic::Status::with_error_details(
1651 tonic::Code::Unavailable,
1652 "shutting down",
1653 tonic_types::ErrorDetails::with_retry_info(Some(std::time::Duration::from_secs(1))),
1654 );
1655 let err = GrpcTransport::status_to_error(&status);
1656 assert!(
1657 matches!(
1658 err,
1659 ClientError::UnexpectedStatus { status: 503, retry_after: Some(d), .. }
1660 if d == std::time::Duration::from_secs(1)
1661 ),
1662 "{err:?}"
1663 );
1664 assert!(err.is_retryable());
1665 let bare = GrpcTransport::status_to_error(&tonic::Status::unavailable("gone"));
1666 assert!(matches!(bare, ClientError::HttpClient(_)), "{bare:?}");
1667 }
1668
1669 #[test]
1670 fn status_to_error_keeps_field_violations_as_data() {
1671 use tonic_types::StatusExt as _;
1672 let details =
1673 tonic_types::ErrorDetails::with_bad_request_violation("message.parts", "empty");
1674 let status =
1675 tonic::Status::with_error_details(tonic::Code::InvalidArgument, "bad", details);
1676 let ClientError::Protocol(err) = GrpcTransport::status_to_error(&status) else {
1677 panic!("a Protocol error");
1678 };
1679 assert_eq!(
1680 err.data,
1681 Some(serde_json::json!({
1682 "@type": "type.googleapis.com/google.rpc.BadRequest",
1683 "fieldViolations": [{ "field": "message.parts", "description": "empty" }],
1684 }))
1685 );
1686 }
1687
1688 #[test]
1689 fn status_to_error_prefers_error_info_reason() {
1690 use tonic_types::StatusExt as _;
1691 let mut details = tonic_types::ErrorDetails::new();
1692 details.set_error_info(
1693 "TASK_NOT_CANCELABLE",
1694 "a2a-protocol.org",
1695 std::collections::HashMap::<String, String>::new(),
1696 );
1697 let status = tonic::Status::with_error_details(
1699 tonic::Code::FailedPrecondition,
1700 "task done",
1701 details,
1702 );
1703 let err = GrpcTransport::status_to_error(&status);
1704 match err {
1705 ClientError::Protocol(a2a) => assert_eq!(
1706 a2a.code,
1707 a2a_protocol_types::ErrorCode::TaskNotCancelable,
1708 "ErrorInfo reason must resolve the exact A2A code"
1709 ),
1710 other => panic!("expected Protocol error, got: {other:?}"),
1711 }
1712 }
1713
1714 #[test]
1716 fn status_to_error_unknown_reason_falls_back_to_code() {
1717 use tonic_types::StatusExt as _;
1718 let mut details = tonic_types::ErrorDetails::new();
1719 details.set_error_info(
1720 "SOMETHING_NOVEL",
1721 "a2a-protocol.org",
1722 std::collections::HashMap::<String, String>::new(),
1723 );
1724 let status = tonic::Status::with_error_details(tonic::Code::NotFound, "missing", details);
1725 let err = GrpcTransport::status_to_error(&status);
1726 match err {
1727 ClientError::Protocol(a2a) => assert_eq!(
1728 a2a.code,
1729 a2a_protocol_types::ErrorCode::TaskNotFound,
1730 "unknown reason must fall back to code-based mapping"
1731 ),
1732 other => panic!("expected Protocol error, got: {other:?}"),
1733 }
1734 }
1735
1736 fn status_update_event() -> apb::StreamResponse {
1744 let event = TaskStatusUpdateEvent::new(
1745 TaskId("t-1".into()),
1746 ContextId("c-1".into()),
1747 TaskStatus::new(TaskState::Working),
1748 );
1749 apb::StreamResponse {
1750 payload: Some(apb::stream_response::Payload::StatusUpdate(
1751 event.try_into().unwrap(),
1752 )),
1753 }
1754 }
1755
1756 #[tokio::test]
1757 async fn grpc_stream_reader_task_forwards_typed_event_as_sse() {
1758 let payloads = vec![Ok(status_update_event())];
1759 let stream = tonic::codegen::tokio_stream::iter(payloads);
1760 let (tx, mut rx) = mpsc::channel::<crate::streaming::event_stream::BodyChunk>(8);
1761
1762 grpc_stream_reader_task(stream, tx).await;
1763
1764 let first = rx.recv().await.expect("expected one chunk");
1765 let bytes = first.expect("expected Ok chunk");
1766 let text = std::str::from_utf8(&bytes).expect("utf8");
1767 assert!(
1768 text.starts_with("data: "),
1769 "chunk must be SSE-framed: {text}"
1770 );
1771 assert!(
1772 text.contains("\"jsonrpc\":\"2.0\""),
1773 "chunk must be JSON-RPC envelope: {text}"
1774 );
1775 assert!(
1776 text.contains("\"statusUpdate\""),
1777 "typed event must serialize as the domain union: {text}"
1778 );
1779 assert!(
1780 text.contains("TASK_STATE_WORKING"),
1781 "state must use canonical wire encoding: {text}"
1782 );
1783 assert!(rx.recv().await.is_none());
1785 }
1786
1787 #[tokio::test]
1788 async fn grpc_stream_reader_task_forwards_multiple_payloads() {
1789 let payloads = vec![
1790 Ok(status_update_event()),
1791 Ok(status_update_event()),
1792 Ok(status_update_event()),
1793 ];
1794 let stream = tonic::codegen::tokio_stream::iter(payloads);
1795 let (tx, mut rx) = mpsc::channel::<crate::streaming::event_stream::BodyChunk>(8);
1796
1797 grpc_stream_reader_task(stream, tx).await;
1798
1799 let mut received = 0;
1800 while let Some(item) = rx.recv().await {
1801 assert!(item.is_ok());
1802 received += 1;
1803 }
1804 assert_eq!(received, 3, "all three payloads must be forwarded");
1805 }
1806
1807 #[tokio::test]
1808 async fn grpc_stream_reader_task_maps_status_error_to_protocol_error() {
1809 let payloads: Vec<Result<apb::StreamResponse, tonic::Status>> =
1810 vec![Err(tonic::Status::not_found("missing"))];
1811 let stream = tonic::codegen::tokio_stream::iter(payloads);
1812 let (tx, mut rx) = mpsc::channel::<crate::streaming::event_stream::BodyChunk>(8);
1813
1814 grpc_stream_reader_task(stream, tx).await;
1815
1816 let chunk = rx.recv().await.expect("expected an error chunk");
1817 match chunk {
1818 Err(ClientError::Protocol(a2a)) => {
1819 assert_eq!(a2a.code, a2a_protocol_types::ErrorCode::TaskNotFound);
1820 assert!(a2a.message.contains("missing"));
1821 }
1822 other => panic!("expected Protocol(TaskNotFound), got {other:?}"),
1823 }
1824 }
1825
1826 #[tokio::test]
1827 async fn grpc_stream_reader_task_rejects_empty_payload() {
1828 let payloads = vec![Ok(apb::StreamResponse { payload: None })];
1833 let stream = tonic::codegen::tokio_stream::iter(payloads);
1834 let (tx, mut rx) = mpsc::channel::<crate::streaming::event_stream::BodyChunk>(8);
1835
1836 grpc_stream_reader_task(stream, tx).await;
1837
1838 let chunk = rx.recv().await.expect("expected an error chunk");
1839 match chunk {
1840 Err(e @ ClientError::InvalidAgentResponse(_)) => {
1841 assert!(!e.is_retryable());
1842 assert!(
1843 e.to_string().contains("streamResponse.payload"),
1844 "msg should name the field: {e}"
1845 );
1846 }
1847 other => panic!("expected InvalidAgentResponse, got {other:?}"),
1848 }
1849 }
1850
1851 #[tokio::test]
1859 async fn grpc_transport_endpoint_returns_input_url() {
1860 let endpoint_str = "http://localhost:50055".to_string();
1861 let channel = tonic::transport::Channel::from_shared(endpoint_str.clone())
1862 .expect("valid endpoint")
1863 .connect_lazy();
1864 let transport = GrpcTransport {
1865 inner: Arc::new(Inner {
1866 channel,
1867 endpoint: endpoint_str.clone(),
1868 config: GrpcTransportConfig::default(),
1869 stream_connect_timeout: None,
1870 }),
1871 };
1872 assert_eq!(transport.endpoint(), endpoint_str);
1873 }
1874
1875 #[tokio::test]
1884 async fn the_stream_open_bound_follows_stream_connect_timeout_when_set() {
1885 let endpoint = "http://example.com:1234".to_string();
1886 let mk = || {
1887 let channel = tonic::transport::Channel::from_shared(endpoint.clone())
1888 .expect("valid endpoint")
1889 .connect_lazy();
1890 GrpcTransport {
1891 inner: Arc::new(Inner {
1892 channel,
1893 endpoint: endpoint.clone(),
1894 config: GrpcTransportConfig::default().with_timeout(Duration::from_secs(30)),
1895 stream_connect_timeout: None,
1896 }),
1897 }
1898 };
1899
1900 assert_eq!(
1901 mk().stream_open_bound(),
1902 Duration::from_secs(30),
1903 "unset must fall back to the unary timeout, so a caller who \
1904 constructs this transport directly sees no change"
1905 );
1906 assert_eq!(
1907 mk().with_stream_connect_timeout(Duration::from_secs(3))
1908 .stream_open_bound(),
1909 Duration::from_secs(3),
1910 "and a set stream_connect_timeout must win over the unary timeout"
1911 );
1912 }
1913
1914 #[tokio::test]
1915 async fn grpc_transport_endpoint_preserves_distinct_urls() {
1916 let a = "http://example.com:1234".to_string();
1917 let b = "https://other.test:9000".to_string();
1918 let mk = |s: String| {
1919 let ch = tonic::transport::Channel::from_shared(s.clone())
1920 .unwrap()
1921 .connect_lazy();
1922 GrpcTransport {
1923 inner: Arc::new(Inner {
1924 channel: ch,
1925 endpoint: s,
1926 config: GrpcTransportConfig::default(),
1927 stream_connect_timeout: None,
1928 }),
1929 }
1930 };
1931 let ta = mk(a.clone());
1932 let tb = mk(b.clone());
1933 assert_eq!(ta.endpoint(), a);
1934 assert_eq!(tb.endpoint(), b);
1935 assert_ne!(ta.endpoint(), tb.endpoint());
1936 }
1937}