1use std::fmt;
13
14use crate::auth_rejection::AuthRejection;
15use serde::{Deserialize, Serialize};
16
17pub const A2A_ERROR_DOMAIN: &str = "a2a-protocol.org";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(into = "i32", try_from = "i32")]
31#[non_exhaustive]
32pub enum ErrorCode {
33 ParseError = -32700,
36 InvalidRequest = -32600,
38 MethodNotFound = -32601,
40 InvalidParams = -32602,
42 InternalError = -32603,
44
45 TaskNotFound = -32001,
48 TaskNotCancelable = -32002,
50 PushNotificationNotSupported = -32003,
52 UnsupportedOperation = -32004,
54 ContentTypeNotSupported = -32005,
56 InvalidAgentResponse = -32006,
58 ExtendedAgentCardNotConfigured = -32007,
60 ExtensionSupportRequired = -32008,
62 VersionNotSupported = -32009,
64}
65
66impl ErrorCode {
67 #[must_use]
69 pub const fn as_i32(self) -> i32 {
70 self as i32
71 }
72
73 #[must_use]
75 pub const fn default_message(self) -> &'static str {
76 match self {
77 Self::ParseError => "Parse error",
78 Self::InvalidRequest => "Invalid request",
79 Self::MethodNotFound => "Method not found",
80 Self::InvalidParams => "Invalid params",
81 Self::InternalError => "Internal error",
82 Self::TaskNotFound => "Task not found",
83 Self::TaskNotCancelable => "Task not cancelable",
84 Self::PushNotificationNotSupported => "Push notification not supported",
85 Self::UnsupportedOperation => "Unsupported operation",
86 Self::ContentTypeNotSupported => "Content type not supported",
87 Self::InvalidAgentResponse => "Invalid agent response",
88 Self::ExtendedAgentCardNotConfigured => "Extended agent card not configured",
89 Self::ExtensionSupportRequired => "Extension support required",
90 Self::VersionNotSupported => "Version not supported",
91 }
92 }
93
94 #[must_use]
99 pub const fn a2a_reason(self) -> Option<&'static str> {
100 match self {
101 Self::TaskNotFound => Some("TASK_NOT_FOUND"),
102 Self::TaskNotCancelable => Some("TASK_NOT_CANCELABLE"),
103 Self::PushNotificationNotSupported => Some("PUSH_NOTIFICATION_NOT_SUPPORTED"),
104 Self::UnsupportedOperation => Some("UNSUPPORTED_OPERATION"),
105 Self::ContentTypeNotSupported => Some("CONTENT_TYPE_NOT_SUPPORTED"),
106 Self::InvalidAgentResponse => Some("INVALID_AGENT_RESPONSE"),
107 Self::ExtendedAgentCardNotConfigured => Some("EXTENDED_AGENT_CARD_NOT_CONFIGURED"),
108 Self::ExtensionSupportRequired => Some("EXTENSION_SUPPORT_REQUIRED"),
109 Self::VersionNotSupported => Some("VERSION_NOT_SUPPORTED"),
110 _ => None,
111 }
112 }
113
114 #[must_use]
130 pub const fn metric_label(self) -> &'static str {
131 match self {
132 Self::ParseError => "parse_error",
133 Self::InvalidRequest => "invalid_request",
134 Self::MethodNotFound => "method_not_found",
135 Self::InvalidParams => "invalid_params",
136 Self::InternalError => "internal_error",
137 Self::TaskNotFound => "task_not_found",
138 Self::TaskNotCancelable => "task_not_cancelable",
139 Self::PushNotificationNotSupported => "push_notification_not_supported",
140 Self::UnsupportedOperation => "unsupported_operation",
141 Self::ContentTypeNotSupported => "content_type_not_supported",
142 Self::InvalidAgentResponse => "invalid_agent_response",
143 Self::ExtendedAgentCardNotConfigured => "extended_agent_card_not_configured",
144 Self::ExtensionSupportRequired => "extension_support_required",
145 Self::VersionNotSupported => "version_not_supported",
146 }
147 }
148
149 #[must_use]
156 pub fn from_a2a_reason(reason: &str) -> Option<Self> {
157 match reason {
158 "TASK_NOT_FOUND" => Some(Self::TaskNotFound),
159 "TASK_NOT_CANCELABLE" => Some(Self::TaskNotCancelable),
160 "PUSH_NOTIFICATION_NOT_SUPPORTED" => Some(Self::PushNotificationNotSupported),
161 "UNSUPPORTED_OPERATION" => Some(Self::UnsupportedOperation),
162 "CONTENT_TYPE_NOT_SUPPORTED" => Some(Self::ContentTypeNotSupported),
163 "INVALID_AGENT_RESPONSE" => Some(Self::InvalidAgentResponse),
164 "EXTENDED_AGENT_CARD_NOT_CONFIGURED" => Some(Self::ExtendedAgentCardNotConfigured),
165 "EXTENSION_SUPPORT_REQUIRED" => Some(Self::ExtensionSupportRequired),
166 "VERSION_NOT_SUPPORTED" => Some(Self::VersionNotSupported),
167 _ => None,
168 }
169 }
170
171 #[must_use]
198 pub const fn http_status(self) -> u16 {
199 match self {
200 Self::TaskNotFound | Self::MethodNotFound => 404,
201 Self::TaskNotCancelable
202 | Self::ContentTypeNotSupported
203 | Self::PushNotificationNotSupported
204 | Self::UnsupportedOperation
205 | Self::ExtendedAgentCardNotConfigured
206 | Self::ExtensionSupportRequired
207 | Self::VersionNotSupported
208 | Self::ParseError
209 | Self::InvalidRequest
210 | Self::InvalidParams => 400,
211 Self::InvalidAgentResponse | Self::InternalError => 500,
212 }
213 }
214
215 #[must_use]
217 pub const fn grpc_status(self) -> &'static str {
218 match self {
219 Self::TaskNotFound => "NOT_FOUND",
220 Self::TaskNotCancelable
221 | Self::ExtendedAgentCardNotConfigured
222 | Self::ExtensionSupportRequired
223 | Self::PushNotificationNotSupported
232 | Self::UnsupportedOperation
233 | Self::VersionNotSupported => "FAILED_PRECONDITION",
234 Self::MethodNotFound => "UNIMPLEMENTED",
235 Self::ContentTypeNotSupported
236 | Self::InvalidParams
237 | Self::InvalidRequest
238 | Self::ParseError => "INVALID_ARGUMENT",
239 Self::InvalidAgentResponse | Self::InternalError => "INTERNAL",
240 }
241 }
242}
243
244impl From<ErrorCode> for i32 {
245 fn from(code: ErrorCode) -> Self {
246 code as Self
247 }
248}
249
250impl TryFrom<i32> for ErrorCode {
251 type Error = i32;
252
253 fn try_from(v: i32) -> Result<Self, Self::Error> {
254 match v {
255 -32700 => Ok(Self::ParseError),
256 -32600 => Ok(Self::InvalidRequest),
257 -32601 => Ok(Self::MethodNotFound),
258 -32602 => Ok(Self::InvalidParams),
259 -32603 => Ok(Self::InternalError),
260 -32001 => Ok(Self::TaskNotFound),
261 -32002 => Ok(Self::TaskNotCancelable),
262 -32003 => Ok(Self::PushNotificationNotSupported),
263 -32004 => Ok(Self::UnsupportedOperation),
264 -32005 => Ok(Self::ContentTypeNotSupported),
265 -32006 => Ok(Self::InvalidAgentResponse),
266 -32007 => Ok(Self::ExtendedAgentCardNotConfigured),
267 -32008 => Ok(Self::ExtensionSupportRequired),
268 -32009 => Ok(Self::VersionNotSupported),
269 other => Err(other),
270 }
271 }
272}
273
274impl fmt::Display for ErrorCode {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 write!(f, "{} ({})", self.default_message(), self.as_i32())
277 }
278}
279
280pub const STREAM_LAGGED_MARKER: &str = "streamLagged";
289
290#[derive(Debug, Clone, Serialize, Deserialize)]
295#[non_exhaustive]
296pub struct A2aError {
297 pub code: ErrorCode,
299 pub message: String,
301 #[serde(skip_serializing_if = "Option::is_none")]
303 pub data: Option<serde_json::Value>,
304 #[serde(skip)]
307 auth_rejection: Option<Box<AuthRejection>>,
308 #[serde(skip)]
317 retry_after_secs: Option<std::num::NonZeroU32>,
318 #[serde(skip)]
322 unavailable: bool,
323}
324
325impl A2aError {
326 #[must_use]
332 pub const fn metric_label(&self) -> &'static str {
333 self.code.metric_label()
334 }
335
336 #[must_use]
338 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
339 Self {
340 code,
341 message: message.into(),
342 data: None,
343 auth_rejection: None,
344 retry_after_secs: None,
345 unavailable: false,
346 }
347 }
348
349 #[must_use]
351 pub fn with_data(code: ErrorCode, message: impl Into<String>, data: serde_json::Value) -> Self {
352 Self {
353 code,
354 message: message.into(),
355 data: Some(data),
356 auth_rejection: None,
357 retry_after_secs: None,
358 unavailable: false,
359 }
360 }
361
362 #[must_use]
374 pub fn unauthenticated(message: impl Into<String>, challenge: impl Into<String>) -> Self {
375 let mut err = Self::new(ErrorCode::InvalidRequest, message);
376 err.auth_rejection = Some(AuthRejection::unauthenticated(challenge.into()).into());
377 err
378 }
379
380 #[must_use]
384 pub fn permission_denied(message: impl Into<String>) -> Self {
385 let mut err = Self::new(ErrorCode::InvalidRequest, message);
386 err.auth_rejection = Some(AuthRejection::permission_denied().into());
387 err
388 }
389
390 #[must_use]
402 pub fn insufficient_scope<S: AsRef<str>>(
403 message: impl Into<String>,
404 scopes: impl IntoIterator<Item = S>,
405 ) -> Self {
406 let mut err = Self::new(ErrorCode::InvalidRequest, message);
407 err.auth_rejection = Some(AuthRejection::insufficient_scope(scopes).into());
408 err
409 }
410
411 #[must_use]
424 pub fn rate_limited(message: impl Into<String>, retry_after: std::time::Duration) -> Self {
425 let secs = retry_after
426 .as_secs()
427 .saturating_add(u64::from(retry_after.subsec_nanos() > 0));
428 let secs = u32::try_from(secs).unwrap_or(u32::MAX);
429 let mut err = Self::internal(message);
430 err.retry_after_secs =
431 Some(std::num::NonZeroU32::new(secs).unwrap_or(std::num::NonZeroU32::MIN));
432 err
433 }
434
435 #[must_use]
453 pub fn unavailable(message: impl Into<String>) -> Self {
454 let mut err = Self::internal(message);
455 err.unavailable = true;
456 err
457 }
458
459 #[must_use]
475 pub fn with_retry_after(mut self, retry_after: std::time::Duration) -> Self {
476 self.retry_after_secs = Self::rate_limited("", retry_after).retry_after_secs;
477 self
478 }
479
480 #[must_use]
484 pub const fn is_unavailable(&self) -> bool {
485 self.unavailable
486 }
487
488 #[must_use]
494 pub const fn retry_after(&self) -> Option<std::time::Duration> {
495 match self.retry_after_secs {
496 Some(secs) => Some(std::time::Duration::from_secs(secs.get() as u64)),
497 None => None,
498 }
499 }
500
501 #[must_use]
514 pub fn with_retry_info_from_details(mut self) -> Self {
515 if self.retry_after_secs.is_none() {
516 self.retry_after_secs = self.data.as_ref().and_then(retry_info_secs);
517 }
518 self
519 }
520
521 #[must_use]
526 pub const fn auth_rejection(&self) -> Option<&AuthRejection> {
527 match &self.auth_rejection {
528 Some(rejection) => Some(rejection),
529 None => None,
530 }
531 }
532
533 #[must_use]
535 pub fn task_not_found(task_id: impl fmt::Display) -> Self {
536 Self::new(
537 ErrorCode::TaskNotFound,
538 format!("Task not found: {task_id}"),
539 )
540 }
541
542 #[must_use]
544 pub fn task_not_cancelable(task_id: impl fmt::Display) -> Self {
545 Self::new(
546 ErrorCode::TaskNotCancelable,
547 format!("Task cannot be canceled: {task_id}"),
548 )
549 }
550
551 #[must_use]
553 pub fn internal(msg: impl Into<String>) -> Self {
554 Self::new(ErrorCode::InternalError, msg)
555 }
556
557 #[must_use]
559 pub fn invalid_params(msg: impl Into<String>) -> Self {
560 Self::new(ErrorCode::InvalidParams, msg)
561 }
562
563 #[must_use]
594 pub fn is_stream_lagged(&self) -> bool {
595 self.lag_marker().is_some()
596 }
597
598 fn lag_marker(&self) -> Option<&serde_json::Value> {
607 match self.data.as_ref()? {
608 serde_json::Value::Array(details) => details.iter().find_map(|d| {
609 d.get(STREAM_LAGGED_MARKER)
610 .or_else(|| d.get("value")?.get(STREAM_LAGGED_MARKER))
611 }),
612 data => data.get(STREAM_LAGGED_MARKER),
613 }
614 }
615
616 #[must_use]
619 pub fn dropped_event_count(&self) -> Option<u64> {
620 self.lag_marker()?.as_u64()
621 }
622
623 #[must_use]
630 pub fn stream_lagged(dropped: u64) -> Self {
631 let mut err = Self::internal(format!(
632 "event stream lagged: {dropped} events were dropped because this consumer read too \
633 slowly; resubscribe to resynchronize from a fresh task snapshot"
634 ));
635 err.data = Some(serde_json::json!({ STREAM_LAGGED_MARKER: dropped }));
636 err
637 }
638
639 #[must_use]
641 pub fn unsupported_operation(msg: impl Into<String>) -> Self {
642 Self::new(ErrorCode::UnsupportedOperation, msg)
643 }
644
645 #[must_use]
647 pub fn parse_error(msg: impl Into<String>) -> Self {
648 Self::new(ErrorCode::ParseError, msg)
649 }
650
651 #[must_use]
653 pub fn invalid_agent_response(msg: impl Into<String>) -> Self {
654 Self::new(ErrorCode::InvalidAgentResponse, msg)
655 }
656
657 #[must_use]
659 pub fn extended_card_not_configured(msg: impl Into<String>) -> Self {
660 Self::new(ErrorCode::ExtendedAgentCardNotConfigured, msg)
661 }
662
663 #[must_use]
665 pub fn push_not_supported(msg: impl Into<String>) -> Self {
666 Self::new(ErrorCode::PushNotificationNotSupported, msg)
667 }
668
669 #[must_use]
671 pub fn content_type_not_supported(msg: impl Into<String>) -> Self {
672 Self::new(ErrorCode::ContentTypeNotSupported, msg)
673 }
674
675 #[must_use]
677 pub fn extension_support_required(msg: impl Into<String>) -> Self {
678 Self::new(ErrorCode::ExtensionSupportRequired, msg)
679 }
680
681 #[must_use]
683 pub fn version_not_supported(msg: impl Into<String>) -> Self {
684 Self::new(ErrorCode::VersionNotSupported, msg)
685 }
686
687 #[must_use]
697 pub fn error_info_data(&self, metadata: Option<serde_json::Value>) -> serde_json::Value {
698 let mut details = Vec::new();
699 if let Some(reason) = self.code.a2a_reason() {
700 let mut info = serde_json::json!({
701 "@type": "type.googleapis.com/google.rpc.ErrorInfo",
702 "reason": reason,
703 "domain": A2A_ERROR_DOMAIN
704 });
705 if let Some(meta) = metadata {
706 info["metadata"] = meta;
707 }
708 details.push(info);
709 }
710 if let Some(secs) = self.retry_after_secs {
711 details.push(serde_json::json!({
713 "@type": RETRY_INFO_TYPE,
714 "retryDelay": format!("{secs}s")
715 }));
716 }
717 if details.is_empty() {
718 serde_json::Value::Null
719 } else {
720 serde_json::Value::Array(details)
721 }
722 }
723}
724
725const RETRY_INFO_TYPE: &str = "type.googleapis.com/google.rpc.RetryInfo";
727
728fn retry_info_secs(data: &serde_json::Value) -> Option<std::num::NonZeroU32> {
731 let details = data
732 .as_array()
733 .map_or_else(|| std::slice::from_ref(data), Vec::as_slice);
734 let delay = details
735 .iter()
736 .filter(|d| d.get("@type").and_then(serde_json::Value::as_str) == Some(RETRY_INFO_TYPE))
737 .find_map(|d| d.get("retryDelay").and_then(serde_json::Value::as_str))?;
738 let digits = delay.strip_suffix('s')?;
739 let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
740 if whole.is_empty()
741 || !whole.bytes().all(|b| b.is_ascii_digit())
742 || !fraction.bytes().all(|b| b.is_ascii_digit())
743 {
744 return None;
745 }
746 let secs = whole
748 .parse::<u64>()
749 .unwrap_or(u64::MAX)
750 .saturating_add(u64::from(fraction.bytes().any(|b| b != b'0')));
751 let secs = u32::try_from(secs).unwrap_or(u32::MAX);
752 Some(std::num::NonZeroU32::new(secs).unwrap_or(std::num::NonZeroU32::MIN))
753}
754
755impl fmt::Display for A2aError {
756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757 write!(f, "[{}] {}", self.code.as_i32(), self.message)
758 }
759}
760
761impl std::error::Error for A2aError {}
762
763pub type A2aResult<T> = Result<T, A2aError>;
767
768#[cfg(test)]
771mod tests {
772 use super::*;
773
774 #[test]
775 fn error_code_roundtrip() {
776 let code = ErrorCode::TaskNotFound;
777 let n: i32 = code.into();
778 assert_eq!(n, -32001);
779 assert_eq!(ErrorCode::try_from(n), Ok(ErrorCode::TaskNotFound));
780 }
781
782 #[test]
783 fn error_code_unknown_value() {
784 assert!(ErrorCode::try_from(-99999).is_err());
785 }
786
787 #[test]
788 fn a2a_error_display() {
789 let err = A2aError::task_not_found("abc123");
790 let s = err.to_string();
791 assert!(s.contains("-32001"), "expected code in display: {s}");
792 assert!(s.contains("abc123"), "expected task id in display: {s}");
793 }
794
795 #[test]
796 fn a2a_error_serialization() {
797 let err = A2aError::internal("something went wrong");
798 let json = serde_json::to_string(&err).expect("serialize");
799 let back: A2aError = serde_json::from_str(&json).expect("deserialize");
800 assert_eq!(back.code, ErrorCode::InternalError);
801 assert_eq!(back.message, "something went wrong");
802 assert!(back.data.is_none());
803 }
804
805 #[test]
806 fn a2a_error_with_data() {
807 let data = serde_json::json!({"detail": "extra info"});
808 let err = A2aError::with_data(ErrorCode::InvalidParams, "bad input", data.clone());
809 let json = serde_json::to_string(&err).expect("serialize");
810 assert!(json.contains("\"data\""), "data field should be present");
811 let back: A2aError = serde_json::from_str(&json).expect("deserialize");
812 assert_eq!(back.data, Some(data));
813 }
814
815 #[test]
820 #[allow(clippy::too_many_lines)]
821 fn error_code_roundtrip_all_variants() {
822 let cases: &[(ErrorCode, i32, &str)] = &[
823 (ErrorCode::ParseError, -32700, "Parse error"),
824 (ErrorCode::InvalidRequest, -32600, "Invalid request"),
825 (ErrorCode::MethodNotFound, -32601, "Method not found"),
826 (ErrorCode::InvalidParams, -32602, "Invalid params"),
827 (ErrorCode::InternalError, -32603, "Internal error"),
828 (ErrorCode::TaskNotFound, -32001, "Task not found"),
829 (ErrorCode::TaskNotCancelable, -32002, "Task not cancelable"),
830 (
831 ErrorCode::PushNotificationNotSupported,
832 -32003,
833 "Push notification not supported",
834 ),
835 (
836 ErrorCode::UnsupportedOperation,
837 -32004,
838 "Unsupported operation",
839 ),
840 (
841 ErrorCode::ContentTypeNotSupported,
842 -32005,
843 "Content type not supported",
844 ),
845 (
846 ErrorCode::InvalidAgentResponse,
847 -32006,
848 "Invalid agent response",
849 ),
850 (
851 ErrorCode::ExtendedAgentCardNotConfigured,
852 -32007,
853 "Extended agent card not configured",
854 ),
855 (
856 ErrorCode::ExtensionSupportRequired,
857 -32008,
858 "Extension support required",
859 ),
860 (
861 ErrorCode::VersionNotSupported,
862 -32009,
863 "Version not supported",
864 ),
865 ];
866
867 for &(code, expected_i32, expected_msg) in cases {
868 assert_eq!(code.as_i32(), expected_i32, "as_i32 mismatch for {code:?}");
870
871 let n: i32 = code.into();
873 assert_eq!(n, expected_i32, "Into<i32> mismatch for {code:?}");
874
875 let back = ErrorCode::try_from(expected_i32).expect("try_from should succeed");
877 assert_eq!(back, code, "TryFrom roundtrip mismatch for {code:?}");
878
879 assert_eq!(
881 code.default_message(),
882 expected_msg,
883 "default_message mismatch for {code:?}"
884 );
885
886 let display = code.to_string();
888 assert!(
889 display.contains(expected_msg),
890 "Display missing message for {code:?}: {display}"
891 );
892 assert!(
893 display.contains(&expected_i32.to_string()),
894 "Display missing code for {code:?}: {display}"
895 );
896 }
897 }
898
899 #[test]
902 fn error_code_rejects_adjacent_values() {
903 let invalid: &[i32] = &[
904 -32701,
905 -32699, -32599,
907 -32601 + 1, -32000,
909 -32010, 0,
911 1,
912 -1,
913 i32::MIN,
914 i32::MAX,
915 ];
916 for &v in invalid {
917 if ErrorCode::try_from(v).is_ok() {
919 continue;
920 }
921 assert_eq!(
922 ErrorCode::try_from(v),
923 Err(v),
924 "value {v} should not convert to ErrorCode"
925 );
926 }
927 }
928
929 #[test]
932 fn named_constructors_use_correct_codes() {
933 assert_eq!(A2aError::task_not_found("t1").code, ErrorCode::TaskNotFound);
934 assert_eq!(
935 A2aError::task_not_cancelable("t1").code,
936 ErrorCode::TaskNotCancelable
937 );
938 assert_eq!(A2aError::internal("x").code, ErrorCode::InternalError);
939 assert_eq!(A2aError::invalid_params("x").code, ErrorCode::InvalidParams);
940 assert_eq!(
941 A2aError::unsupported_operation("x").code,
942 ErrorCode::UnsupportedOperation
943 );
944 assert_eq!(A2aError::parse_error("x").code, ErrorCode::ParseError);
945 assert_eq!(
946 A2aError::invalid_agent_response("x").code,
947 ErrorCode::InvalidAgentResponse
948 );
949 assert_eq!(
950 A2aError::extended_card_not_configured("x").code,
951 ErrorCode::ExtendedAgentCardNotConfigured
952 );
953 }
954
955 #[test]
956 fn named_constructors_include_argument_in_message() {
957 let err = A2aError::task_not_found("my-task-id");
958 assert!(
959 err.message.contains("my-task-id"),
960 "task_not_found should include task_id: {}",
961 err.message
962 );
963
964 let err = A2aError::task_not_cancelable("cancel-me");
965 assert!(
966 err.message.contains("cancel-me"),
967 "task_not_cancelable should include task_id: {}",
968 err.message
969 );
970 }
971
972 #[test]
973 fn a2a_error_new_has_no_data() {
974 let err = A2aError::new(ErrorCode::InternalError, "msg");
975 assert!(err.data.is_none());
976 }
977
978 #[test]
979 fn a2a_error_with_data_has_some_data() {
980 let err = A2aError::with_data(
981 ErrorCode::InternalError,
982 "msg",
983 serde_json::json!("details"),
984 );
985 assert!(err.data.is_some());
986 assert_eq!(err.data.unwrap(), serde_json::json!("details"));
987 }
988
989 #[test]
990 fn a2a_error_is_std_error() {
991 let err = A2aError::internal("test");
992 let _: &dyn std::error::Error = &err;
993 }
994
995 #[test]
996 fn a2a_error_display_format() {
997 let err = A2aError::new(ErrorCode::ParseError, "bad json");
998 let s = err.to_string();
999 assert_eq!(s, "[-32700] bad json");
1000 }
1001
1002 #[test]
1010 fn a2a_reason_task_not_found() {
1011 assert_eq!(ErrorCode::TaskNotFound.a2a_reason(), Some("TASK_NOT_FOUND"));
1012 }
1013
1014 #[test]
1015 fn a2a_reason_task_not_cancelable() {
1016 assert_eq!(
1017 ErrorCode::TaskNotCancelable.a2a_reason(),
1018 Some("TASK_NOT_CANCELABLE")
1019 );
1020 }
1021
1022 #[test]
1023 fn a2a_reason_push_notification_not_supported() {
1024 assert_eq!(
1025 ErrorCode::PushNotificationNotSupported.a2a_reason(),
1026 Some("PUSH_NOTIFICATION_NOT_SUPPORTED")
1027 );
1028 }
1029
1030 #[test]
1031 fn a2a_reason_unsupported_operation() {
1032 assert_eq!(
1033 ErrorCode::UnsupportedOperation.a2a_reason(),
1034 Some("UNSUPPORTED_OPERATION")
1035 );
1036 }
1037
1038 #[test]
1039 fn a2a_reason_content_type_not_supported() {
1040 assert_eq!(
1041 ErrorCode::ContentTypeNotSupported.a2a_reason(),
1042 Some("CONTENT_TYPE_NOT_SUPPORTED")
1043 );
1044 }
1045
1046 #[test]
1047 fn a2a_reason_invalid_agent_response() {
1048 assert_eq!(
1049 ErrorCode::InvalidAgentResponse.a2a_reason(),
1050 Some("INVALID_AGENT_RESPONSE")
1051 );
1052 }
1053
1054 #[test]
1055 fn a2a_reason_extended_agent_card_not_configured() {
1056 assert_eq!(
1057 ErrorCode::ExtendedAgentCardNotConfigured.a2a_reason(),
1058 Some("EXTENDED_AGENT_CARD_NOT_CONFIGURED")
1059 );
1060 }
1061
1062 #[test]
1063 fn a2a_reason_extension_support_required() {
1064 assert_eq!(
1065 ErrorCode::ExtensionSupportRequired.a2a_reason(),
1066 Some("EXTENSION_SUPPORT_REQUIRED")
1067 );
1068 }
1069
1070 #[test]
1071 fn a2a_reason_version_not_supported() {
1072 assert_eq!(
1073 ErrorCode::VersionNotSupported.a2a_reason(),
1074 Some("VERSION_NOT_SUPPORTED")
1075 );
1076 }
1077
1078 #[test]
1079 fn a2a_reason_none_for_standard_jsonrpc_errors() {
1080 assert_eq!(ErrorCode::ParseError.a2a_reason(), None);
1081 assert_eq!(ErrorCode::InvalidRequest.a2a_reason(), None);
1082 assert_eq!(ErrorCode::MethodNotFound.a2a_reason(), None);
1083 assert_eq!(ErrorCode::InvalidParams.a2a_reason(), None);
1084 assert_eq!(ErrorCode::InternalError.a2a_reason(), None);
1085 }
1086
1087 #[test]
1088 fn from_a2a_reason_is_exact_inverse_of_a2a_reason() {
1089 let all = [
1090 ErrorCode::TaskNotFound,
1091 ErrorCode::TaskNotCancelable,
1092 ErrorCode::PushNotificationNotSupported,
1093 ErrorCode::UnsupportedOperation,
1094 ErrorCode::ContentTypeNotSupported,
1095 ErrorCode::InvalidAgentResponse,
1096 ErrorCode::ExtendedAgentCardNotConfigured,
1097 ErrorCode::ExtensionSupportRequired,
1098 ErrorCode::VersionNotSupported,
1099 ];
1100 for code in all {
1101 let reason = code.a2a_reason().expect("A2A code must have a reason");
1102 assert_eq!(
1103 ErrorCode::from_a2a_reason(reason),
1104 Some(code),
1105 "round-trip failed for {reason}"
1106 );
1107 }
1108 assert_eq!(ErrorCode::from_a2a_reason("NOT_A_REAL_REASON"), None);
1109 assert_eq!(ErrorCode::from_a2a_reason(""), None);
1110 }
1111
1112 #[test]
1113 fn a2a_reason_all_a2a_variants_distinct_and_non_empty() {
1114 let reasons: &[&str] = &[
1115 ErrorCode::TaskNotFound.a2a_reason().unwrap(),
1116 ErrorCode::TaskNotCancelable.a2a_reason().unwrap(),
1117 ErrorCode::PushNotificationNotSupported
1118 .a2a_reason()
1119 .unwrap(),
1120 ErrorCode::UnsupportedOperation.a2a_reason().unwrap(),
1121 ErrorCode::ContentTypeNotSupported.a2a_reason().unwrap(),
1122 ErrorCode::InvalidAgentResponse.a2a_reason().unwrap(),
1123 ErrorCode::ExtendedAgentCardNotConfigured
1124 .a2a_reason()
1125 .unwrap(),
1126 ErrorCode::ExtensionSupportRequired.a2a_reason().unwrap(),
1127 ErrorCode::VersionNotSupported.a2a_reason().unwrap(),
1128 ];
1129 for r in reasons {
1131 assert!(!r.is_empty(), "a2a_reason must not be empty: {r}");
1132 }
1133 let mut sorted: Vec<&str> = reasons.to_vec();
1135 sorted.sort_unstable();
1136 sorted.dedup();
1137 assert_eq!(
1138 sorted.len(),
1139 reasons.len(),
1140 "a2a_reason values must be distinct across variants"
1141 );
1142 }
1143
1144 #[test]
1147 fn http_status_task_not_found_is_404() {
1148 assert_eq!(ErrorCode::TaskNotFound.http_status(), 404);
1149 }
1150
1151 #[test]
1152 fn http_status_method_not_found_is_404() {
1153 assert_eq!(ErrorCode::MethodNotFound.http_status(), 404);
1154 }
1155
1156 #[test]
1157 fn http_status_task_not_cancelable_is_400() {
1158 assert_eq!(ErrorCode::TaskNotCancelable.http_status(), 400);
1159 }
1160
1161 #[test]
1162 fn http_status_content_type_not_supported_is_400() {
1163 assert_eq!(ErrorCode::ContentTypeNotSupported.http_status(), 400);
1166 }
1167
1168 #[test]
1169 fn http_status_invalid_agent_response_is_500() {
1170 assert_eq!(ErrorCode::InvalidAgentResponse.http_status(), 500);
1171 }
1172
1173 #[test]
1174 fn http_status_push_not_supported_is_400() {
1175 assert_eq!(ErrorCode::PushNotificationNotSupported.http_status(), 400);
1176 }
1177
1178 #[test]
1179 fn http_status_unsupported_operation_is_400() {
1180 assert_eq!(ErrorCode::UnsupportedOperation.http_status(), 400);
1181 }
1182
1183 #[test]
1184 fn http_status_extended_card_not_configured_is_400() {
1185 assert_eq!(ErrorCode::ExtendedAgentCardNotConfigured.http_status(), 400);
1186 }
1187
1188 #[test]
1189 fn http_status_extension_support_required_is_400() {
1190 assert_eq!(ErrorCode::ExtensionSupportRequired.http_status(), 400);
1191 }
1192
1193 #[test]
1194 fn http_status_version_not_supported_is_400() {
1195 assert_eq!(ErrorCode::VersionNotSupported.http_status(), 400);
1196 }
1197
1198 #[test]
1199 fn http_status_parse_error_is_400() {
1200 assert_eq!(ErrorCode::ParseError.http_status(), 400);
1201 }
1202
1203 #[test]
1204 fn http_status_invalid_request_is_400() {
1205 assert_eq!(ErrorCode::InvalidRequest.http_status(), 400);
1206 }
1207
1208 #[test]
1209 fn http_status_invalid_params_is_400() {
1210 assert_eq!(ErrorCode::InvalidParams.http_status(), 400);
1211 }
1212
1213 #[test]
1214 fn http_status_internal_error_is_500() {
1215 assert_eq!(ErrorCode::InternalError.http_status(), 500);
1216 }
1217
1218 #[test]
1221 fn grpc_status_task_not_found_is_not_found() {
1222 assert_eq!(ErrorCode::TaskNotFound.grpc_status(), "NOT_FOUND");
1223 }
1224
1225 #[test]
1226 fn grpc_status_task_not_cancelable_is_failed_precondition() {
1227 assert_eq!(
1228 ErrorCode::TaskNotCancelable.grpc_status(),
1229 "FAILED_PRECONDITION"
1230 );
1231 }
1232
1233 #[test]
1234 fn grpc_status_extended_card_not_configured_is_failed_precondition() {
1235 assert_eq!(
1236 ErrorCode::ExtendedAgentCardNotConfigured.grpc_status(),
1237 "FAILED_PRECONDITION"
1238 );
1239 }
1240
1241 #[test]
1242 fn grpc_status_extension_support_required_is_failed_precondition() {
1243 assert_eq!(
1244 ErrorCode::ExtensionSupportRequired.grpc_status(),
1245 "FAILED_PRECONDITION"
1246 );
1247 }
1248
1249 #[test]
1250 fn grpc_status_push_not_supported_is_failed_precondition() {
1251 assert_eq!(
1252 ErrorCode::PushNotificationNotSupported.grpc_status(),
1253 "FAILED_PRECONDITION"
1254 );
1255 }
1256
1257 #[test]
1258 fn grpc_status_unsupported_operation_is_failed_precondition() {
1259 assert_eq!(
1260 ErrorCode::UnsupportedOperation.grpc_status(),
1261 "FAILED_PRECONDITION"
1262 );
1263 }
1264
1265 #[test]
1266 fn grpc_status_version_not_supported_is_failed_precondition() {
1267 assert_eq!(
1268 ErrorCode::VersionNotSupported.grpc_status(),
1269 "FAILED_PRECONDITION"
1270 );
1271 }
1272
1273 #[test]
1277 fn grpc_status_method_not_found_stays_unimplemented_while_refusals_move() {
1278 assert_eq!(ErrorCode::MethodNotFound.grpc_status(), "UNIMPLEMENTED");
1279 for refusal in [
1280 ErrorCode::PushNotificationNotSupported,
1281 ErrorCode::UnsupportedOperation,
1282 ErrorCode::VersionNotSupported,
1283 ] {
1284 assert_ne!(refusal.grpc_status(), "UNIMPLEMENTED");
1285 }
1286 }
1287
1288 #[test]
1289 fn grpc_status_method_not_found_is_unimplemented() {
1290 assert_eq!(ErrorCode::MethodNotFound.grpc_status(), "UNIMPLEMENTED");
1291 }
1292
1293 #[test]
1294 fn grpc_status_content_type_not_supported_is_invalid_argument() {
1295 assert_eq!(
1296 ErrorCode::ContentTypeNotSupported.grpc_status(),
1297 "INVALID_ARGUMENT"
1298 );
1299 }
1300
1301 #[test]
1302 fn grpc_status_invalid_params_is_invalid_argument() {
1303 assert_eq!(ErrorCode::InvalidParams.grpc_status(), "INVALID_ARGUMENT");
1304 }
1305
1306 #[test]
1307 fn grpc_status_invalid_request_is_invalid_argument() {
1308 assert_eq!(ErrorCode::InvalidRequest.grpc_status(), "INVALID_ARGUMENT");
1309 }
1310
1311 #[test]
1312 fn grpc_status_parse_error_is_invalid_argument() {
1313 assert_eq!(ErrorCode::ParseError.grpc_status(), "INVALID_ARGUMENT");
1314 }
1315
1316 #[test]
1317 fn grpc_status_invalid_agent_response_is_internal() {
1318 assert_eq!(ErrorCode::InvalidAgentResponse.grpc_status(), "INTERNAL");
1319 }
1320
1321 #[test]
1322 fn grpc_status_internal_error_is_internal() {
1323 assert_eq!(ErrorCode::InternalError.grpc_status(), "INTERNAL");
1324 }
1325
1326 #[test]
1327 fn grpc_status_never_empty() {
1328 let all = [
1329 ErrorCode::ParseError,
1330 ErrorCode::InvalidRequest,
1331 ErrorCode::MethodNotFound,
1332 ErrorCode::InvalidParams,
1333 ErrorCode::InternalError,
1334 ErrorCode::TaskNotFound,
1335 ErrorCode::TaskNotCancelable,
1336 ErrorCode::PushNotificationNotSupported,
1337 ErrorCode::UnsupportedOperation,
1338 ErrorCode::ContentTypeNotSupported,
1339 ErrorCode::InvalidAgentResponse,
1340 ErrorCode::ExtendedAgentCardNotConfigured,
1341 ErrorCode::ExtensionSupportRequired,
1342 ErrorCode::VersionNotSupported,
1343 ];
1344 for code in all {
1345 assert!(
1346 !code.grpc_status().is_empty(),
1347 "grpc_status must never be empty for {code:?}"
1348 );
1349 }
1350 }
1351
1352 #[test]
1355 fn error_info_data_for_a2a_error_has_expected_shape() {
1356 let err = A2aError::task_not_found("t1");
1357 let data = err.error_info_data(None);
1358
1359 let arr = data.as_array().expect("error_info_data must be an array");
1361 assert_eq!(arr.len(), 1);
1362 let info = &arr[0];
1363 assert_eq!(info["@type"], "type.googleapis.com/google.rpc.ErrorInfo");
1364 assert_eq!(info["reason"], "TASK_NOT_FOUND");
1365 assert_eq!(info["domain"], "a2a-protocol.org");
1366 assert!(
1367 info.get("metadata").is_none(),
1368 "metadata must be absent when None is passed"
1369 );
1370 }
1371
1372 #[test]
1373 fn error_info_data_with_metadata_includes_metadata() {
1374 let err = A2aError::task_not_cancelable("t2");
1375 let meta = serde_json::json!({"task_id": "t2", "current_state": "completed"});
1376 let data = err.error_info_data(Some(meta.clone()));
1377
1378 let arr = data.as_array().expect("error_info_data must be an array");
1379 let info = &arr[0];
1380 assert_eq!(info["reason"], "TASK_NOT_CANCELABLE");
1381 assert_eq!(info["metadata"], meta);
1382 }
1383
1384 #[test]
1385 fn error_info_data_for_standard_jsonrpc_error_is_null() {
1386 let err = A2aError::parse_error("bad json");
1392 let data = err.error_info_data(None);
1393 assert!(data.is_null(), "expected null, got {data}");
1394 }
1395
1396 #[test]
1397 fn error_info_data_mutation_not_default_value() {
1398 let err = A2aError::unsupported_operation("nope");
1402 let data = err.error_info_data(None);
1403 assert_ne!(
1404 data,
1405 serde_json::Value::default(),
1406 "A2A error must not produce default serde_json::Value"
1407 );
1408 assert!(data.is_array(), "A2A error must produce an array");
1409 }
1410
1411 #[test]
1412 fn error_info_data_metadata_not_added_when_none() {
1413 let err = A2aError::version_not_supported("old");
1416 let data = err.error_info_data(None);
1417 let info = &data[0];
1418 assert!(info.get("metadata").is_none());
1419 let with = err.error_info_data(Some(serde_json::json!({"x": 1})));
1421 assert_eq!(with[0]["metadata"], serde_json::json!({"x": 1}));
1422 }
1423
1424 #[test]
1442 fn stream_lagged_reports_the_dropped_count() {
1443 let err = A2aError::stream_lagged(42);
1444
1445 assert!(
1446 err.is_stream_lagged(),
1447 "a stream_lagged error must identify as one"
1448 );
1449 assert_eq!(
1453 err.dropped_event_count(),
1454 Some(42),
1455 "the dropped count must round-trip through the marker"
1456 );
1457 }
1458
1459 #[test]
1463 fn the_lag_marker_is_found_in_either_data_shape() {
1464 let array = A2aError::with_data(
1465 ErrorCode::InternalError,
1466 "lagged",
1467 serde_json::json!([
1468 {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "X"},
1469 {"@type": "type.googleapis.com/google.protobuf.Struct", "streamLagged": 42}
1470 ]),
1471 );
1472 assert!(array.is_stream_lagged());
1473 assert_eq!(array.dropped_event_count(), Some(42));
1474
1475 let any = A2aError::with_data(
1478 ErrorCode::InternalError,
1479 "lagged",
1480 serde_json::json!([
1481 {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "X"},
1482 {"@type": "type.googleapis.com/google.protobuf.Struct", "value": {"streamLagged": 42}}
1483 ]),
1484 );
1485 assert!(any.is_stream_lagged());
1486 assert_eq!(any.dropped_event_count(), Some(42));
1487
1488 let object = A2aError::with_data(
1489 ErrorCode::InternalError,
1490 "lagged",
1491 serde_json::json!({"streamLagged": 42}),
1492 );
1493 assert!(object.is_stream_lagged());
1494 assert_eq!(object.dropped_event_count(), Some(42));
1495
1496 let unmarked = A2aError::with_data(
1497 ErrorCode::InternalError,
1498 "boom",
1499 serde_json::json!([{"@type": "type.googleapis.com/google.protobuf.Struct"}]),
1500 );
1501 assert!(!unmarked.is_stream_lagged());
1502 assert_eq!(unmarked.dropped_event_count(), None);
1503 }
1504
1505 #[test]
1509 fn retry_info_is_read_from_received_details() {
1510 use std::time::Duration;
1511 let received = |data: serde_json::Value| {
1512 A2aError::with_data(ErrorCode::InternalError, "slow down", data)
1513 .with_retry_info_from_details()
1514 .retry_after()
1515 };
1516 let retry = |delay: &str| {
1517 serde_json::json!([
1518 {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "X"},
1519 {"@type": RETRY_INFO_TYPE, "retryDelay": delay}
1520 ])
1521 };
1522 assert_eq!(received(retry("12s")), Some(Duration::from_secs(12)));
1523 assert_eq!(received(retry("1.5s")), Some(Duration::from_secs(2)));
1524 assert_eq!(received(retry("3.000s")), Some(Duration::from_secs(3)));
1525 assert_eq!(received(retry("0s")), Some(Duration::from_secs(1)));
1526 assert_eq!(
1527 received(retry("99999999999999999999999s")),
1528 Some(Duration::from_secs(u64::from(u32::MAX)))
1529 );
1530 assert_eq!(
1532 received(serde_json::json!({"@type": RETRY_INFO_TYPE, "retryDelay": "4s"})),
1533 Some(Duration::from_secs(4))
1534 );
1535 for malformed in ["12", "-1s", "1.5.2s", "s", ".5s", "1e3s", " 2s"] {
1536 assert_eq!(received(retry(malformed)), None, "{malformed:?}");
1537 }
1538 assert_eq!(
1539 received(
1540 serde_json::json!([{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "retryDelay": "5s"}])
1541 ),
1542 None,
1543 "only a RetryInfo detail counts"
1544 );
1545 assert_eq!(
1546 A2aError::internal("no data")
1547 .with_retry_info_from_details()
1548 .retry_after(),
1549 None
1550 );
1551 let mut own = A2aError::rate_limited("own", Duration::from_secs(7));
1553 own.data = Some(retry("30s"));
1554 assert_eq!(
1555 own.with_retry_info_from_details().retry_after(),
1556 Some(Duration::from_secs(7))
1557 );
1558 let written = A2aError::rate_limited("slow down", Duration::from_secs(9));
1560 assert_eq!(
1561 received(written.error_info_data(None)),
1562 Some(Duration::from_secs(9))
1563 );
1564 }
1565
1566 #[test]
1570 fn a_rate_limited_error_carries_retry_info() {
1571 let err = A2aError::rate_limited("slow down", std::time::Duration::from_secs(12));
1572 assert_eq!(err.code, ErrorCode::InternalError);
1573 assert_eq!(err.retry_after(), Some(std::time::Duration::from_secs(12)));
1574 assert_eq!(
1575 err.error_info_data(None),
1576 serde_json::json!([{
1577 "@type": "type.googleapis.com/google.rpc.RetryInfo",
1578 "retryDelay": "12s"
1579 }])
1580 );
1581 let fractional =
1583 A2aError::rate_limited("slow down", std::time::Duration::from_millis(1500));
1584 assert_eq!(
1585 fractional.retry_after(),
1586 Some(std::time::Duration::from_secs(2))
1587 );
1588 assert_eq!(fractional.error_info_data(None)[0]["retryDelay"], "2s");
1589 let zero = A2aError::rate_limited("slow down", std::time::Duration::ZERO);
1590 assert_eq!(zero.retry_after(), Some(std::time::Duration::from_secs(1)));
1591
1592 let plain = A2aError::internal("boom");
1593 assert_eq!(plain.retry_after(), None);
1594 assert!(plain.error_info_data(None).is_null());
1595 let round_trip: A2aError =
1598 serde_json::from_str(&serde_json::to_string(&err).unwrap()).unwrap();
1599 assert_eq!(round_trip.retry_after(), None);
1600 }
1601
1602 #[test]
1606 fn an_unavailable_error_is_marked_temporary() {
1607 let busy = A2aError::unavailable("database busy");
1608 assert!(busy.is_unavailable());
1609 assert_eq!(busy.code, ErrorCode::InternalError);
1610 assert_eq!(busy.message, "database busy");
1611 assert!(!A2aError::internal("database busy").is_unavailable());
1612
1613 let wire = serde_json::to_value(&busy).unwrap();
1614 assert_eq!(
1615 wire,
1616 serde_json::to_value(A2aError::internal("database busy")).unwrap()
1617 );
1618 let round_trip: A2aError = serde_json::from_value(wire).unwrap();
1619 assert!(!round_trip.is_unavailable());
1620 }
1621
1622 #[test]
1623 fn ordinary_errors_are_not_lag_signals() {
1624 let internal = A2aError::internal("boom");
1627 assert!(!internal.is_stream_lagged());
1628 assert_eq!(internal.dropped_event_count(), None);
1629
1630 let typed = A2aError::new(ErrorCode::TaskNotFound, "gone");
1632 assert!(!typed.is_stream_lagged());
1633 assert_eq!(typed.dropped_event_count(), None);
1634 }
1635
1636 #[test]
1647 fn metric_label_is_pinned_for_every_variant() {
1648 let expected = [
1649 (ErrorCode::ParseError, "parse_error"),
1650 (ErrorCode::InvalidRequest, "invalid_request"),
1651 (ErrorCode::MethodNotFound, "method_not_found"),
1652 (ErrorCode::InvalidParams, "invalid_params"),
1653 (ErrorCode::InternalError, "internal_error"),
1654 (ErrorCode::TaskNotFound, "task_not_found"),
1655 (ErrorCode::TaskNotCancelable, "task_not_cancelable"),
1656 (
1657 ErrorCode::PushNotificationNotSupported,
1658 "push_notification_not_supported",
1659 ),
1660 (ErrorCode::UnsupportedOperation, "unsupported_operation"),
1661 (
1662 ErrorCode::ContentTypeNotSupported,
1663 "content_type_not_supported",
1664 ),
1665 (ErrorCode::InvalidAgentResponse, "invalid_agent_response"),
1666 (
1667 ErrorCode::ExtendedAgentCardNotConfigured,
1668 "extended_agent_card_not_configured",
1669 ),
1670 (
1671 ErrorCode::ExtensionSupportRequired,
1672 "extension_support_required",
1673 ),
1674 (ErrorCode::VersionNotSupported, "version_not_supported"),
1675 ];
1676
1677 for (code, label) in expected {
1678 assert_eq!(code.metric_label(), label, "wrong label for {code:?}");
1679 }
1680 }
1681
1682 #[test]
1689 fn metric_labels_are_distinct_and_bounded() {
1690 let codes = [
1691 ErrorCode::ParseError,
1692 ErrorCode::InvalidRequest,
1693 ErrorCode::MethodNotFound,
1694 ErrorCode::InvalidParams,
1695 ErrorCode::InternalError,
1696 ErrorCode::TaskNotFound,
1697 ErrorCode::TaskNotCancelable,
1698 ErrorCode::PushNotificationNotSupported,
1699 ErrorCode::UnsupportedOperation,
1700 ErrorCode::ContentTypeNotSupported,
1701 ErrorCode::InvalidAgentResponse,
1702 ErrorCode::ExtendedAgentCardNotConfigured,
1703 ErrorCode::ExtensionSupportRequired,
1704 ErrorCode::VersionNotSupported,
1705 ];
1706
1707 let mut seen = std::collections::BTreeSet::new();
1708 for code in codes {
1709 let label = code.metric_label();
1710 assert!(!label.is_empty(), "{code:?} has an empty metric label");
1711 assert!(
1712 label.bytes().all(|b| b.is_ascii_lowercase() || b == b'_'),
1713 "{code:?} label {label:?} is not lower_snake_case"
1714 );
1715 assert!(seen.insert(label), "duplicate metric label {label:?}");
1716 }
1717 assert_eq!(seen.len(), codes.len());
1718 }
1719
1720 #[test]
1726 fn a2a_error_metric_label_delegates_to_its_code() {
1727 let err = A2aError::new(ErrorCode::TaskNotFound, "no such task: <client text>");
1728 assert_eq!(err.metric_label(), "task_not_found");
1729 assert_eq!(err.metric_label(), err.code.metric_label());
1730
1731 let noisy = A2aError::new(ErrorCode::InternalError, "user-id=42 secret=hunter2");
1733 assert_eq!(noisy.metric_label(), "internal_error");
1734 assert!(!noisy.metric_label().contains("hunter2"));
1735 }
1736}