1use std::collections::HashMap;
42use std::future::Future;
43use std::pin::Pin;
44use std::time::Duration;
45
46use a2a_protocol_types::idempotency::{IDEMPOTENCY_METADATA_KEY, validate_key};
47
48use tokio::time::Instant;
49
50use crate::error::{ClientError, ClientResult};
51use crate::streaming::EventStream;
52use crate::transport::Transport;
53
54pub(crate) mod budget;
55pub use budget::RetryBudget;
56
57#[derive(Debug, Clone)]
104#[non_exhaustive]
105pub struct RetryPolicy {
106 pub max_retries: u32,
108 pub initial_backoff: Duration,
110 pub max_backoff: Duration,
112 pub backoff_multiplier: f64,
114 pub budget: Option<RetryBudget>,
118 pub max_elapsed: Option<Duration>,
124}
125
126impl Default for RetryPolicy {
127 fn default() -> Self {
128 Self {
129 max_retries: 3,
130 initial_backoff: Duration::from_millis(500),
131 max_backoff: Duration::from_secs(30),
132 backoff_multiplier: 2.0,
133 budget: None,
134 max_elapsed: None,
135 }
136 }
137}
138
139impl RetryPolicy {
140 #[must_use]
142 pub const fn with_max_retries(mut self, max_retries: u32) -> Self {
143 self.max_retries = max_retries;
144 self
145 }
146
147 #[must_use]
149 pub const fn with_initial_backoff(mut self, backoff: Duration) -> Self {
150 self.initial_backoff = backoff;
151 self
152 }
153
154 #[must_use]
156 pub const fn with_max_backoff(mut self, max: Duration) -> Self {
157 self.max_backoff = max;
158 self
159 }
160
161 #[must_use]
163 pub const fn with_backoff_multiplier(mut self, multiplier: f64) -> Self {
164 self.backoff_multiplier = multiplier;
165 self
166 }
167
168 #[must_use]
172 pub const fn with_budget(mut self, budget: RetryBudget) -> Self {
173 self.budget = Some(budget);
174 self
175 }
176
177 #[must_use]
180 pub const fn with_max_elapsed(mut self, max_elapsed: Duration) -> Self {
181 self.max_elapsed = Some(max_elapsed);
182 self
183 }
184}
185
186impl ClientError {
189 #[must_use]
205 pub const fn is_retryable(&self) -> bool {
206 match self {
207 Self::Http(_)
208 | Self::HttpClient(_)
209 | Self::Timeout(_)
210 | Self::IncompleteStream { .. }
211 | Self::TooManyPendingRequests { .. }
212 | Self::CircuitOpen { .. } => true,
213 Self::UnexpectedStatus { status, .. } => {
214 matches!(status, 429 | 502 | 503 | 504)
215 }
216 Self::Protocol(e) => e.retry_after().is_some(),
217 Self::Serialization(_)
220 | Self::Transport(_)
221 | Self::Config(_)
222 | Self::InvalidEndpoint(_)
223 | Self::AuthRequired { .. }
224 | Self::CapabilityNotDeclared { .. }
225 | Self::ProtocolBindingMismatch(_)
226 | Self::InvalidAuthScheme(_)
227 | Self::InsecureWebhook(_)
228 | Self::InsecureTransport(_)
229 | Self::ContentNotVerified(_)
230 | Self::InvalidAgentResponse(_) => false,
231 }
232 }
233}
234
235pub(crate) fn is_idempotent_method(method: &str) -> bool {
251 matches!(
252 method,
253 "GetTask"
254 | "ListTasks"
255 | "CancelTask"
256 | "SubscribeToTask"
257 | "GetExtendedAgentCard"
258 | "GetTaskPushNotificationConfig"
259 | "ListTaskPushNotificationConfigs"
260 | "DeleteTaskPushNotificationConfig"
261 )
262}
263
264pub(crate) fn carries_idempotency_key(
297 method: &str,
298 params: &serde_json::Value,
299 peer_honours_idempotency: bool,
300) -> bool {
301 if !peer_honours_idempotency {
302 return false;
303 }
304 if !matches!(method, "SendMessage" | "SendStreamingMessage") {
305 return false;
306 }
307 params
308 .get("message")
309 .and_then(|message| message.get("metadata"))
310 .and_then(|metadata| metadata.get(IDEMPOTENCY_METADATA_KEY))
311 .and_then(serde_json::Value::as_str)
312 .is_some_and(|key| validate_key(key).is_ok())
313}
314
315const fn safe_to_retry_non_idempotent(error: &ClientError) -> bool {
333 match error {
334 ClientError::UnexpectedStatus { status: 429, .. }
336 | ClientError::UnexpectedStatus {
337 status: 503,
338 retry_after: Some(_),
339 ..
340 }
341 | ClientError::CircuitOpen { .. } => true,
342 ClientError::Protocol(e) => e.retry_after().is_some(),
345 _ => false,
346 }
347}
348
349fn retry_delay(
359 last_err: Option<&ClientError>,
360 backoff: Duration,
361 max_backoff: Duration,
362) -> Duration {
363 last_err
364 .and_then(ClientError::retry_after)
365 .map_or_else(|| jittered(backoff), |after| spread(after).min(max_backoff))
366}
367
368#[allow(clippy::cast_precision_loss)] fn spread_factor_from_bits(random_bits: u64) -> f64 {
372 (random_bits as f64 / u64::MAX as f64).mul_add(0.25, 1.0)
373}
374
375fn spread(after: Duration) -> Duration {
377 use std::hash::{BuildHasher, Hasher};
378 let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
379 hasher.write_u128(after.as_nanos());
380 apply_jitter(after, spread_factor_from_bits(hasher.finish()))
381}
382
383pub(crate) struct RetryTransport {
388 inner: Box<dyn Transport>,
389 policy: RetryPolicy,
390 peer_honours_idempotency: bool,
396 ledger: Option<budget::Ledger>,
398 shared: Option<std::sync::Arc<crate::origin::OriginState>>,
401}
402
403impl RetryTransport {
404 pub(crate) fn new(inner: Box<dyn Transport>, policy: RetryPolicy) -> Self {
406 let ledger = policy.budget.map(budget::Ledger::new);
407 Self {
408 inner,
409 policy,
410 peer_honours_idempotency: false,
411 ledger,
412 shared: None,
413 }
414 }
415
416 #[must_use]
419 pub(crate) fn with_shared_budget(
420 mut self,
421 origin: std::sync::Arc<crate::origin::OriginState>,
422 ) -> Self {
423 self.shared = Some(origin);
424 self
425 }
426
427 fn shared_ledger(&self) -> Option<&budget::Ledger> {
429 self.shared
430 .as_deref()
431 .and_then(crate::origin::OriginState::budget)
432 }
433
434 fn call_made(&self) {
436 if let Some(ledger) = &self.ledger {
437 ledger.deposit();
438 }
439 if let Some(ledger) = self.shared_ledger() {
440 ledger.deposit();
441 }
442 }
443
444 fn retry_in(
454 &self,
455 started: Instant,
456 backoff: Duration,
457 last_err: Option<&ClientError>,
458 ) -> Option<Duration> {
459 let policy = &self.policy;
460 if last_err
461 .and_then(ClientError::retry_after)
462 .is_some_and(|after| after > policy.max_backoff)
463 {
464 trace_warn!("not retrying: the server asked for a delay longer than max_backoff");
465 return None;
466 }
467 let delay = retry_delay(last_err, backoff, policy.max_backoff);
468 if policy
469 .max_elapsed
470 .is_some_and(|max| started.elapsed().saturating_add(delay) > max)
471 {
472 trace_warn!("not retrying: the next attempt would start after max_elapsed");
473 return None;
474 }
475 if self.ledger.as_ref().is_some_and(|l| !l.withdraw()) {
476 trace_warn!("not retrying: the retry budget is spent");
477 return None;
478 }
479 if self.shared_ledger().is_some_and(|l| !l.withdraw()) {
480 if let Some(own) = &self.ledger {
482 own.refund();
483 }
484 trace_warn!("not retrying: the pool's retry budget for this origin is spent");
485 return None;
486 }
487 Some(delay)
488 }
489
490 #[must_use]
492 pub(crate) const fn with_peer_honouring_idempotency(mut self, honours: bool) -> Self {
493 self.peer_honours_idempotency = honours;
494 self
495 }
496}
497
498impl Transport for RetryTransport {
499 fn send_request<'a>(
500 &'a self,
501 method: &'a str,
502 params: serde_json::Value,
503 extra_headers: &'a HashMap<String, String>,
504 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>> {
505 self.send_request_with_query(method, params, extra_headers, &[])
506 }
507
508 fn send_streaming_request<'a>(
509 &'a self,
510 method: &'a str,
511 params: serde_json::Value,
512 extra_headers: &'a HashMap<String, String>,
513 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
514 self.send_streaming_request_with_query(method, params, extra_headers, &[])
515 }
516
517 fn send_request_with_query<'a>(
521 &'a self,
522 method: &'a str,
523 params: serde_json::Value,
524 extra_headers: &'a HashMap<String, String>,
525 query: &'a [(String, String)],
526 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>> {
527 Box::pin(async move {
528 let mut last_err: Option<ClientError> = None;
529 let mut backoff = self.policy.initial_backoff;
530 let idempotent = is_idempotent_method(method)
531 || carries_idempotency_key(method, ¶ms, self.peer_honours_idempotency);
532
533 let serialized = serde_json::to_vec(¶ms).map_err(ClientError::Serialization)?;
536 let started = Instant::now();
537 self.call_made();
538
539 for attempt in 0..=self.policy.max_retries {
540 if attempt > 0 {
541 let Some(delay) = self.retry_in(started, backoff, last_err.as_ref()) else {
542 return Err(last_err.expect("a retry follows an error"));
543 };
544 trace_info!(method, attempt, ?delay, "retrying after backoff");
545 tokio::time::sleep(delay).await;
546 backoff = cap_backoff(
547 backoff,
548 self.policy.backoff_multiplier,
549 self.policy.max_backoff,
550 );
551 }
552
553 let attempt_params: serde_json::Value =
554 serde_json::from_slice(&serialized).map_err(ClientError::Serialization)?;
555
556 match self
557 .inner
558 .send_request_with_query(method, attempt_params, extra_headers, query)
559 .await
560 {
561 Ok(result) => return Ok(result),
562 Err(e)
570 if e.is_retryable() && (idempotent || safe_to_retry_non_idempotent(&e)) =>
571 {
572 trace_warn!(method, attempt, error = %e, "transient error, will retry");
573 last_err = Some(e);
574 }
575 Err(e) => return Err(e),
576 }
577 }
578
579 Err(last_err.expect("at least one attempt was made"))
580 })
581 }
582
583 fn send_streaming_request_with_query<'a>(
584 &'a self,
585 method: &'a str,
586 params: serde_json::Value,
587 extra_headers: &'a HashMap<String, String>,
588 query: &'a [(String, String)],
589 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
590 Box::pin(async move {
591 let mut last_err: Option<ClientError> = None;
592 let mut backoff = self.policy.initial_backoff;
593 let idempotent = is_idempotent_method(method)
594 || carries_idempotency_key(method, ¶ms, self.peer_honours_idempotency);
595
596 let serialized = serde_json::to_vec(¶ms).map_err(ClientError::Serialization)?;
599 let started = Instant::now();
600 self.call_made();
601
602 for attempt in 0..=self.policy.max_retries {
603 if attempt > 0 {
604 let Some(delay) = self.retry_in(started, backoff, last_err.as_ref()) else {
605 return Err(last_err.expect("a retry follows an error"));
606 };
607 trace_info!(
608 method,
609 attempt,
610 ?delay,
611 "retrying stream connect after backoff"
612 );
613 tokio::time::sleep(delay).await;
614 backoff = cap_backoff(
615 backoff,
616 self.policy.backoff_multiplier,
617 self.policy.max_backoff,
618 );
619 }
620
621 let attempt_params: serde_json::Value =
622 serde_json::from_slice(&serialized).map_err(ClientError::Serialization)?;
623
624 match self
625 .inner
626 .send_streaming_request_with_query(method, attempt_params, extra_headers, query)
627 .await
628 {
629 Ok(stream) => return Ok(stream),
630 Err(e)
634 if e.is_retryable() && (idempotent || safe_to_retry_non_idempotent(&e)) =>
635 {
636 trace_warn!(method, attempt, error = %e, "transient error, will retry");
637 last_err = Some(e);
638 }
639 Err(e) => return Err(e),
640 }
641 }
642
643 Err(last_err.expect("at least one attempt was made"))
644 })
645 }
646}
647
648fn cap_backoff(current: Duration, multiplier: f64, max: Duration) -> Duration {
655 let next_secs = current.as_secs_f64() * multiplier;
656 Duration::try_from_secs_f64(next_secs).map_or(max, |next| {
661 std::cmp::min(next, max)
666 })
667}
668
669#[allow(clippy::cast_precision_loss)] fn jitter_factor_from_bits(random_bits: u64) -> f64 {
676 (random_bits as f64 / u64::MAX as f64).mul_add(0.5, 0.5)
677}
678
679fn apply_jitter(backoff: Duration, factor: f64) -> Duration {
684 let jittered_secs = backoff.as_secs_f64() * factor;
685 Duration::try_from_secs_f64(jittered_secs).unwrap_or(backoff)
691}
692
693pub(crate) fn jittered(backoff: Duration) -> Duration {
700 use std::hash::{BuildHasher, Hasher};
701 let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
702 hasher.write_u128(backoff.as_nanos());
704 let factor = jitter_factor_from_bits(hasher.finish());
705 apply_jitter(backoff, factor)
706}
707
708#[cfg(test)]
711mod limits_tests;
712
713#[cfg(test)]
714mod shared_budget_tests;
715
716#[cfg(test)]
717mod tests {
718 use super::*;
719
720 #[test]
721 fn http_errors_are_retryable() {
722 let e = ClientError::HttpClient("connection refused".into());
723 assert!(e.is_retryable());
724 }
725
726 #[test]
727 fn timeout_is_retryable() {
728 let e = ClientError::Timeout("request timed out".into());
729 assert!(e.is_retryable());
730 }
731
732 #[test]
734 fn incomplete_stream_is_retryable() {
735 let e = ClientError::IncompleteStream {
736 last_event_id: Some("7".into()),
737 detail: "cut off".into(),
738 };
739 assert!(e.is_retryable());
740 assert_eq!(
741 e.to_string(),
742 "stream ended before its final event: cut off"
743 );
744 }
745
746 #[test]
747 fn status_503_is_retryable() {
748 let e = ClientError::UnexpectedStatus {
749 status: 503,
750 body: "Service Unavailable".into(),
751 retry_after: None,
752 };
753 assert!(e.is_retryable());
754 }
755
756 #[test]
757 fn status_429_is_retryable() {
758 let e = ClientError::UnexpectedStatus {
759 status: 429,
760 body: "Too Many Requests".into(),
761 retry_after: None,
762 };
763 assert!(e.is_retryable());
764 }
765
766 #[test]
767 fn status_404_is_not_retryable() {
768 let e = ClientError::UnexpectedStatus {
769 status: 404,
770 body: "Not Found".into(),
771 retry_after: None,
772 };
773 assert!(!e.is_retryable());
774 }
775
776 #[test]
777 fn serialization_error_is_not_retryable() {
778 let e = ClientError::Serialization(serde_json::from_str::<String>("not json").unwrap_err());
779 assert!(!e.is_retryable());
780 }
781
782 #[test]
783 fn protocol_error_is_not_retryable() {
784 let e = ClientError::Protocol(a2a_protocol_types::A2aError::task_not_found("t1"));
785 assert!(!e.is_retryable());
786 }
787
788 #[test]
789 fn default_retry_policy() {
790 let p = RetryPolicy::default();
791 assert_eq!(p.max_retries, 3);
792 assert_eq!(p.initial_backoff, Duration::from_millis(500));
793 assert_eq!(p.max_backoff, Duration::from_secs(30));
794 assert!((p.backoff_multiplier - 2.0).abs() < f64::EPSILON);
795 }
796
797 #[test]
798 fn cap_backoff_works() {
799 let result = cap_backoff(Duration::from_secs(1), 2.0, Duration::from_secs(5));
800 assert_eq!(result, Duration::from_secs(2));
801
802 let result = cap_backoff(Duration::from_secs(4), 2.0, Duration::from_secs(5));
803 assert_eq!(result, Duration::from_secs(5));
804 }
805
806 #[test]
807 fn status_502_is_retryable() {
808 let e = ClientError::UnexpectedStatus {
809 status: 502,
810 body: "Bad Gateway".into(),
811 retry_after: None,
812 };
813 assert!(e.is_retryable());
814 }
815
816 #[test]
817 fn status_504_is_retryable() {
818 let e = ClientError::UnexpectedStatus {
819 status: 504,
820 body: "Gateway Timeout".into(),
821 retry_after: None,
822 };
823 assert!(e.is_retryable());
824 }
825
826 #[test]
828 fn status_boundary_not_retryable() {
829 for status in [428, 430, 500, 501, 505] {
830 let e = ClientError::UnexpectedStatus {
831 status,
832 body: String::new(),
833 retry_after: None,
834 };
835 assert!(!e.is_retryable(), "status {status} should not be retryable");
836 }
837 }
838
839 #[test]
840 fn retry_policy_builder_methods() {
841 let p = RetryPolicy::default()
842 .with_max_retries(5)
843 .with_initial_backoff(Duration::from_secs(1))
844 .with_max_backoff(Duration::from_secs(60))
845 .with_backoff_multiplier(3.0);
846 assert_eq!(p.max_retries, 5);
847 assert_eq!(p.initial_backoff, Duration::from_secs(1));
848 assert_eq!(p.max_backoff, Duration::from_secs(60));
849 assert!((p.backoff_multiplier - 3.0).abs() < f64::EPSILON);
850 }
851
852 #[test]
853 fn cap_backoff_exact_boundary() {
854 let result = cap_backoff(Duration::from_secs(5), 1.0, Duration::from_secs(5));
856 assert_eq!(result, Duration::from_secs(5));
857
858 let result = cap_backoff(Duration::from_millis(1), 2.0, Duration::from_secs(5));
860 assert_eq!(result, Duration::from_millis(2));
861 }
862
863 #[test]
864 fn cap_backoff_infinity_returns_max() {
865 let max = Duration::from_secs(30);
867 let result = cap_backoff(Duration::from_secs(u64::MAX / 2), f64::MAX, max);
868 assert_eq!(result, max, "infinity should clamp to max");
869 }
870
871 #[test]
872 fn cap_backoff_finite_overflow_returns_max() {
873 let max = Duration::from_secs(30);
878 let result = cap_backoff(Duration::from_secs(10_000_000_000_000_000_000), 10.0, max);
879 assert_eq!(
880 result, max,
881 "finite-but-overflowing backoff should clamp to max"
882 );
883 }
884
885 #[test]
887 fn jittered_backoff_in_expected_range() {
888 let backoff = Duration::from_secs(2);
889 for _ in 0..100 {
891 let result = jittered(backoff);
892 assert!(
893 result >= Duration::from_secs(1),
894 "jittered backoff should be >= backoff/2, got {result:?}"
895 );
896 assert!(
897 result <= backoff,
898 "jittered backoff should be <= backoff, got {result:?}"
899 );
900 }
901 }
902
903 #[test]
905 fn jittered_zero_backoff() {
906 let result = jittered(Duration::ZERO);
907 assert_eq!(result, Duration::ZERO);
908 }
909
910 #[test]
911 fn cap_backoff_nan_returns_max() {
912 let max = Duration::from_secs(30);
913 let result = cap_backoff(Duration::from_secs(0), f64::NAN, max);
914 assert_eq!(result, max, "NaN should clamp to max");
915 }
916
917 #[test]
922 fn jitter_factor_from_bits_zero() {
923 let f = jitter_factor_from_bits(0);
924 assert!(
925 (f - 0.5).abs() < f64::EPSILON,
926 "factor(0) should be 0.5, got {f}"
927 );
928 }
929
930 #[test]
932 fn jitter_factor_from_bits_midpoint() {
933 let f = jitter_factor_from_bits(u64::MAX / 2);
934 assert!(
936 (0.74..=0.76).contains(&f),
937 "factor(u64::MAX/2) should be ~0.75, got {f}"
938 );
939 }
940
941 #[test]
943 fn jitter_factor_from_bits_max() {
944 let f = jitter_factor_from_bits(u64::MAX);
945 assert!(
948 (0.9..=1.0).contains(&f),
949 "factor(u64::MAX) should be ~1.0, got {f}"
950 );
951 }
952
953 #[test]
957 fn jitter_factor_from_bits_always_in_half_to_one() {
958 for bits in [
959 0_u64,
960 1,
961 7,
962 42,
963 1 << 20,
964 1 << 50,
965 u64::MAX / 4,
966 u64::MAX / 2,
967 u64::MAX,
968 ] {
969 let f = jitter_factor_from_bits(bits);
970 assert!(
971 (0.5..=1.0).contains(&f),
972 "factor({bits}) = {f} out of [0.5, 1.0]"
973 );
974 }
975 }
976
977 #[test]
986 fn apply_jitter_normal_factor() {
987 assert_eq!(
989 apply_jitter(Duration::from_secs(2), 0.5),
990 Duration::from_secs(1)
991 );
992 assert_eq!(
994 apply_jitter(Duration::from_secs(4), 0.75),
995 Duration::from_secs(3)
996 );
997 assert_eq!(
999 apply_jitter(Duration::from_secs(5), 1.0),
1000 Duration::from_secs(5)
1001 );
1002 }
1003
1004 #[test]
1008 fn apply_jitter_zero_factor_returns_zero() {
1009 assert_eq!(
1010 apply_jitter(Duration::from_secs(5), 0.0),
1011 Duration::ZERO,
1012 "factor=0.0 must produce Duration::ZERO via from_secs_f64 path"
1013 );
1014 }
1015
1016 #[test]
1020 fn apply_jitter_negative_factor_returns_backoff() {
1021 assert_eq!(
1022 apply_jitter(Duration::from_secs(3), -0.5),
1023 Duration::from_secs(3),
1024 "negative factor must short-circuit to backoff"
1025 );
1026 }
1027
1028 #[test]
1037 fn apply_jitter_infinite_factor_returns_backoff() {
1038 assert_eq!(
1039 apply_jitter(Duration::from_secs(2), f64::INFINITY),
1040 Duration::from_secs(2),
1041 "infinite factor must short-circuit to backoff"
1042 );
1043 }
1044
1045 #[test]
1046 fn apply_jitter_nan_factor_returns_backoff() {
1047 assert_eq!(
1048 apply_jitter(Duration::from_secs(4), f64::NAN),
1049 Duration::from_secs(4),
1050 "NaN factor must short-circuit to backoff"
1051 );
1052 }
1053
1054 use std::collections::HashMap;
1057 use std::future::Future;
1058 use std::pin::Pin;
1059 use std::sync::Arc;
1060 use std::sync::atomic::{AtomicUsize, Ordering};
1061
1062 use crate::streaming::EventStream;
1063
1064 #[tokio::test(start_paused = true)]
1081 async fn the_documented_backoff_arithmetic_is_what_it_does() {
1082 let inner = FailNTransport::new(usize::MAX, serde_json::json!(null));
1083 let calls = Arc::clone(&inner.call_count);
1084 let retry = RetryTransport::new(
1085 Box::new(inner),
1086 RetryPolicy {
1087 max_retries: 3,
1088 initial_backoff: Duration::from_millis(500),
1089 max_backoff: Duration::from_secs(30),
1090 backoff_multiplier: 1.0,
1093 ..RetryPolicy::default()
1094 },
1095 );
1096
1097 let started = tokio::time::Instant::now();
1098 let result = retry
1102 .send_request("GetTask", serde_json::json!({}), &HashMap::new())
1103 .await;
1104 let elapsed = started.elapsed();
1105
1106 assert!(
1107 result.is_err(),
1108 "every attempt fails, so the call must fail"
1109 );
1110 assert_eq!(
1111 calls.load(Ordering::SeqCst),
1112 4,
1113 "max_retries 3 must mean 4 attempts — the formula's (max_retries + 1)"
1114 );
1115
1116 assert!(
1127 elapsed >= Duration::from_millis(750) && elapsed < Duration::from_millis(1_500),
1128 "three fully-jittered 500ms gaps must total in [750ms, 1500ms), got {elapsed:?}"
1129 );
1130 }
1131
1132 struct FailNTransport {
1134 failures_remaining: Arc<AtomicUsize>,
1135 success_response: serde_json::Value,
1136 call_count: Arc<AtomicUsize>,
1137 }
1138
1139 impl FailNTransport {
1140 fn new(fail_count: usize, response: serde_json::Value) -> Self {
1141 Self {
1142 failures_remaining: Arc::new(AtomicUsize::new(fail_count)),
1143 success_response: response,
1144 call_count: Arc::new(AtomicUsize::new(0)),
1145 }
1146 }
1147 }
1148
1149 impl crate::transport::Transport for FailNTransport {
1150 fn send_request<'a>(
1151 &'a self,
1152 _method: &'a str,
1153 _params: serde_json::Value,
1154 _extra_headers: &'a HashMap<String, String>,
1155 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>> {
1156 self.call_count.fetch_add(1, Ordering::SeqCst);
1157 let remaining = self.failures_remaining.fetch_sub(1, Ordering::SeqCst);
1158 let resp = self.success_response.clone();
1159 Box::pin(async move {
1160 if remaining > 0 {
1161 Err(ClientError::Timeout("transient".into()))
1162 } else {
1163 Ok(resp)
1164 }
1165 })
1166 }
1167
1168 fn send_streaming_request<'a>(
1169 &'a self,
1170 _method: &'a str,
1171 _params: serde_json::Value,
1172 _extra_headers: &'a HashMap<String, String>,
1173 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
1174 self.call_count.fetch_add(1, Ordering::SeqCst);
1175 let remaining = self.failures_remaining.fetch_sub(1, Ordering::SeqCst);
1176 Box::pin(async move {
1177 if remaining > 0 {
1178 Err(ClientError::Timeout("transient".into()))
1179 } else {
1180 Err(ClientError::Transport("streaming not mocked".into()))
1181 }
1182 })
1183 }
1184 }
1185
1186 struct NonRetryableErrorTransport {
1188 call_count: Arc<AtomicUsize>,
1189 }
1190
1191 impl NonRetryableErrorTransport {
1192 fn new() -> Self {
1193 Self {
1194 call_count: Arc::new(AtomicUsize::new(0)),
1195 }
1196 }
1197 }
1198
1199 impl crate::transport::Transport for NonRetryableErrorTransport {
1200 fn send_request<'a>(
1201 &'a self,
1202 _method: &'a str,
1203 _params: serde_json::Value,
1204 _extra_headers: &'a HashMap<String, String>,
1205 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>> {
1206 self.call_count.fetch_add(1, Ordering::SeqCst);
1207 Box::pin(async move { Err(ClientError::InvalidEndpoint("bad url".into())) })
1208 }
1209
1210 fn send_streaming_request<'a>(
1211 &'a self,
1212 _method: &'a str,
1213 _params: serde_json::Value,
1214 _extra_headers: &'a HashMap<String, String>,
1215 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
1216 self.call_count.fetch_add(1, Ordering::SeqCst);
1217 Box::pin(async move { Err(ClientError::InvalidEndpoint("bad url".into())) })
1218 }
1219 }
1220
1221 #[tokio::test]
1222 async fn retry_transport_retries_on_transient_error() {
1223 let inner = FailNTransport::new(2, serde_json::json!({"ok": true}));
1224 let call_count = Arc::clone(&inner.call_count);
1225 let transport = RetryTransport::new(
1226 Box::new(inner),
1227 RetryPolicy::default()
1228 .with_initial_backoff(Duration::from_millis(1))
1229 .with_max_retries(3),
1230 );
1231
1232 let headers = HashMap::new();
1233 let result = transport
1234 .send_request("GetTask", serde_json::Value::Null, &headers)
1235 .await;
1236 assert!(result.is_ok(), "should succeed after retries");
1237 assert_eq!(
1238 call_count.load(Ordering::SeqCst),
1239 3,
1240 "should have made 3 attempts (2 failures + 1 success)"
1241 );
1242 }
1243
1244 #[tokio::test]
1245 async fn retry_transport_gives_up_after_max_retries() {
1246 let inner = FailNTransport::new(10, serde_json::json!({"ok": true}));
1248 let call_count = Arc::clone(&inner.call_count);
1249 let transport = RetryTransport::new(
1250 Box::new(inner),
1251 RetryPolicy::default()
1252 .with_initial_backoff(Duration::from_millis(1))
1253 .with_max_retries(2),
1254 );
1255
1256 let headers = HashMap::new();
1257 let result = transport
1258 .send_request("GetTask", serde_json::Value::Null, &headers)
1259 .await;
1260 assert!(result.is_err(), "should fail after exhausting retries");
1261 assert_eq!(
1262 call_count.load(Ordering::SeqCst),
1263 3,
1264 "should have made 3 attempts (initial + 2 retries)"
1265 );
1266 }
1267
1268 #[tokio::test]
1269 async fn retry_transport_no_retry_on_non_retryable() {
1270 let inner = NonRetryableErrorTransport::new();
1271 let call_count = Arc::clone(&inner.call_count);
1272 let transport = RetryTransport::new(
1273 Box::new(inner),
1274 RetryPolicy::default()
1275 .with_initial_backoff(Duration::from_millis(1))
1276 .with_max_retries(3),
1277 );
1278
1279 let headers = HashMap::new();
1280 let result = transport
1281 .send_request("GetTask", serde_json::Value::Null, &headers)
1282 .await;
1283 assert!(result.is_err());
1284 assert!(matches!(
1285 result.unwrap_err(),
1286 ClientError::InvalidEndpoint(_)
1287 ));
1288 assert_eq!(
1289 call_count.load(Ordering::SeqCst),
1290 1,
1291 "non-retryable error should not be retried"
1292 );
1293 }
1294
1295 #[tokio::test]
1296 async fn retry_transport_streaming_retries() {
1297 let inner = FailNTransport::new(1, serde_json::json!(null));
1298 let call_count = Arc::clone(&inner.call_count);
1299 let transport = RetryTransport::new(
1300 Box::new(inner),
1301 RetryPolicy::default()
1302 .with_initial_backoff(Duration::from_millis(1))
1303 .with_max_retries(2),
1304 );
1305
1306 let headers = HashMap::new();
1307 let result = transport
1308 .send_streaming_request("SubscribeToTask", serde_json::Value::Null, &headers)
1309 .await;
1310 assert!(result.is_err());
1313 assert_eq!(
1314 call_count.load(Ordering::SeqCst),
1315 2,
1316 "should have retried once for streaming"
1317 );
1318 }
1319
1320 #[tokio::test]
1321 async fn retry_transport_streaming_no_retry_on_non_retryable() {
1322 let inner = NonRetryableErrorTransport::new();
1323 let call_count = Arc::clone(&inner.call_count);
1324 let transport = RetryTransport::new(
1325 Box::new(inner),
1326 RetryPolicy::default()
1327 .with_initial_backoff(Duration::from_millis(1))
1328 .with_max_retries(3),
1329 );
1330
1331 let headers = HashMap::new();
1332 let result = transport
1333 .send_streaming_request("SubscribeToTask", serde_json::Value::Null, &headers)
1334 .await;
1335 assert!(matches!(
1336 result.unwrap_err(),
1337 ClientError::InvalidEndpoint(_)
1338 ));
1339 assert_eq!(
1340 call_count.load(Ordering::SeqCst),
1341 1,
1342 "non-retryable streaming error should not be retried"
1343 );
1344 }
1345
1346 #[tokio::test]
1349 async fn retry_transport_streaming_succeeds_after_retry() {
1350 use tokio::sync::mpsc;
1351
1352 struct FailThenStreamTransport {
1354 call_count: Arc<AtomicUsize>,
1355 }
1356
1357 impl crate::transport::Transport for FailThenStreamTransport {
1358 fn send_request<'a>(
1359 &'a self,
1360 _method: &'a str,
1361 _params: serde_json::Value,
1362 _extra_headers: &'a HashMap<String, String>,
1363 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>>
1364 {
1365 Box::pin(async move { Ok(serde_json::Value::Null) })
1366 }
1367
1368 fn send_streaming_request<'a>(
1369 &'a self,
1370 _method: &'a str,
1371 _params: serde_json::Value,
1372 _extra_headers: &'a HashMap<String, String>,
1373 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
1374 let attempt = self.call_count.fetch_add(1, Ordering::SeqCst);
1375 Box::pin(async move {
1376 if attempt == 0 {
1377 Err(ClientError::Timeout("transient timeout".into()))
1378 } else {
1379 let (tx, rx) = mpsc::channel(8);
1381 drop(tx); Ok(EventStream::new(rx))
1383 }
1384 })
1385 }
1386 }
1387
1388 let call_count = Arc::new(AtomicUsize::new(0));
1389 let inner = FailThenStreamTransport {
1390 call_count: Arc::clone(&call_count),
1391 };
1392 let transport = RetryTransport::new(
1393 Box::new(inner),
1394 RetryPolicy::default()
1395 .with_initial_backoff(Duration::from_millis(1))
1396 .with_max_retries(2),
1397 );
1398
1399 let headers = HashMap::new();
1400 let result = transport
1401 .send_streaming_request("SubscribeToTask", serde_json::Value::Null, &headers)
1402 .await;
1403 assert!(result.is_ok(), "streaming should succeed after retry");
1404 assert_eq!(
1405 call_count.load(Ordering::SeqCst),
1406 2,
1407 "should have made 2 attempts (1 failure + 1 success)"
1408 );
1409 }
1410
1411 #[tokio::test]
1412 async fn retry_transport_streaming_exhausts_retries() {
1413 let inner = FailNTransport::new(10, serde_json::json!(null));
1414 let call_count = Arc::clone(&inner.call_count);
1415 let transport = RetryTransport::new(
1416 Box::new(inner),
1417 RetryPolicy::default()
1418 .with_initial_backoff(Duration::from_millis(1))
1419 .with_max_retries(2),
1420 );
1421
1422 let headers = HashMap::new();
1423 let result = transport
1424 .send_streaming_request("SubscribeToTask", serde_json::Value::Null, &headers)
1425 .await;
1426 assert!(result.is_err());
1427 assert_eq!(
1428 call_count.load(Ordering::SeqCst),
1429 3,
1430 "should make 3 attempts total for streaming"
1431 );
1432 }
1433
1434 #[tokio::test]
1435 async fn retry_transport_succeeds_without_retry_on_first_attempt() {
1436 let inner = FailNTransport::new(0, serde_json::json!({"ok": true}));
1437 let call_count = Arc::clone(&inner.call_count);
1438 let transport = RetryTransport::new(
1439 Box::new(inner),
1440 RetryPolicy::default()
1441 .with_initial_backoff(Duration::from_millis(1))
1442 .with_max_retries(3),
1443 );
1444
1445 let headers = HashMap::new();
1446 let result = transport
1447 .send_request("GetTask", serde_json::Value::Null, &headers)
1448 .await;
1449 assert!(result.is_ok());
1450 assert_eq!(
1451 call_count.load(Ordering::SeqCst),
1452 1,
1453 "should succeed on first try"
1454 );
1455 }
1456
1457 #[tokio::test(start_paused = true)]
1463 async fn no_backoff_before_first_attempt() {
1464 let inner = FailNTransport::new(0, serde_json::json!({"ok": true}));
1465 let transport = RetryTransport::new(
1466 Box::new(inner),
1467 RetryPolicy::default()
1468 .with_initial_backoff(Duration::from_secs(100))
1469 .with_max_retries(1),
1470 );
1471
1472 let start = tokio::time::Instant::now();
1473 let headers = HashMap::new();
1474 let result = transport
1475 .send_request("GetTask", serde_json::Value::Null, &headers)
1476 .await;
1477 assert!(result.is_ok());
1478 assert!(
1479 start.elapsed() < Duration::from_secs(1),
1480 "first attempt must not sleep, elapsed: {:?}",
1481 start.elapsed()
1482 );
1483 }
1484
1485 #[tokio::test(start_paused = true)]
1489 async fn backoff_applied_on_retry() {
1490 let inner = FailNTransport::new(1, serde_json::json!({"ok": true}));
1491 let transport = RetryTransport::new(
1492 Box::new(inner),
1493 RetryPolicy::default()
1494 .with_initial_backoff(Duration::from_secs(100))
1495 .with_max_retries(2),
1496 );
1497
1498 let start = tokio::time::Instant::now();
1499 let headers = HashMap::new();
1500 let result = transport
1501 .send_request("GetTask", serde_json::Value::Null, &headers)
1502 .await;
1503 assert!(result.is_ok());
1504 assert!(
1505 start.elapsed() >= Duration::from_secs(50),
1506 "retry should sleep (jittered backoff), elapsed: {:?}",
1507 start.elapsed()
1508 );
1509 }
1510
1511 #[tokio::test(start_paused = true)]
1513 async fn no_backoff_before_first_streaming_attempt() {
1514 use tokio::sync::mpsc;
1515
1516 struct ImmediateStreamTransport;
1517 impl crate::transport::Transport for ImmediateStreamTransport {
1518 fn send_request<'a>(
1519 &'a self,
1520 _method: &'a str,
1521 _params: serde_json::Value,
1522 _extra_headers: &'a HashMap<String, String>,
1523 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>>
1524 {
1525 Box::pin(async { Ok(serde_json::Value::Null) })
1526 }
1527 fn send_streaming_request<'a>(
1528 &'a self,
1529 _method: &'a str,
1530 _params: serde_json::Value,
1531 _extra_headers: &'a HashMap<String, String>,
1532 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
1533 Box::pin(async {
1534 let (tx, rx) = mpsc::channel(1);
1535 drop(tx);
1536 Ok(EventStream::new(rx))
1537 })
1538 }
1539 }
1540
1541 let transport = RetryTransport::new(
1542 Box::new(ImmediateStreamTransport),
1543 RetryPolicy::default()
1544 .with_initial_backoff(Duration::from_secs(100))
1545 .with_max_retries(1),
1546 );
1547
1548 let start = tokio::time::Instant::now();
1549 let headers = HashMap::new();
1550 let result = transport
1551 .send_streaming_request("SubscribeToTask", serde_json::Value::Null, &headers)
1552 .await;
1553 assert!(result.is_ok());
1554 assert!(
1555 start.elapsed() < Duration::from_secs(1),
1556 "first streaming attempt must not sleep, elapsed: {:?}",
1557 start.elapsed()
1558 );
1559 }
1560
1561 #[tokio::test(start_paused = true)]
1563 async fn backoff_applied_on_streaming_retry() {
1564 let inner = FailNTransport::new(1, serde_json::json!(null));
1565 let transport = RetryTransport::new(
1566 Box::new(inner),
1567 RetryPolicy::default()
1568 .with_initial_backoff(Duration::from_secs(100))
1569 .with_max_retries(2),
1570 );
1571
1572 let start = tokio::time::Instant::now();
1573 let headers = HashMap::new();
1574 let _result = transport
1575 .send_streaming_request("SubscribeToTask", serde_json::Value::Null, &headers)
1576 .await;
1577 assert!(
1580 start.elapsed() >= Duration::from_secs(50),
1581 "streaming retry should sleep, elapsed: {:?}",
1582 start.elapsed()
1583 );
1584 }
1585
1586 #[test]
1591 fn cap_backoff_zero_multiplier_returns_zero() {
1592 let max = Duration::from_secs(30);
1593 let result = cap_backoff(Duration::from_secs(5), 0.0, max);
1594 assert_eq!(
1595 result,
1596 Duration::ZERO,
1597 "0 * any = 0, should not clamp to max"
1598 );
1599 }
1600
1601 #[test]
1604 fn method_idempotency_classification() {
1605 for m in [
1606 "GetTask",
1607 "ListTasks",
1608 "CancelTask",
1609 "SubscribeToTask",
1610 "GetExtendedAgentCard",
1611 "GetTaskPushNotificationConfig",
1612 "ListTaskPushNotificationConfigs",
1613 "DeleteTaskPushNotificationConfig",
1614 ] {
1615 assert!(is_idempotent_method(m), "{m} should be idempotent");
1616 }
1617 for m in [
1618 "SendMessage",
1619 "SendStreamingMessage",
1620 "CreateTaskPushNotificationConfig",
1621 "SomethingBrandNew",
1622 ] {
1623 assert!(!is_idempotent_method(m), "{m} must be non-idempotent");
1624 }
1625 }
1626
1627 #[test]
1630 fn only_429_and_503_with_retry_after_are_safe_for_non_idempotent() {
1631 let mk = |status| ClientError::UnexpectedStatus {
1632 status,
1633 body: String::new(),
1634 retry_after: None,
1635 };
1636 assert!(safe_to_retry_non_idempotent(&mk(429)));
1637 assert!(
1638 !safe_to_retry_non_idempotent(&mk(503)),
1639 "a bare 503 is ambiguous"
1640 );
1641 assert!(safe_to_retry_non_idempotent(
1642 &ClientError::UnexpectedStatus {
1643 status: 503,
1644 body: String::new(),
1645 retry_after: Some(Duration::from_secs(1)),
1646 }
1647 ));
1648 assert!(!safe_to_retry_non_idempotent(&mk(502)));
1650 assert!(!safe_to_retry_non_idempotent(&mk(504)));
1651 assert!(!safe_to_retry_non_idempotent(&ClientError::Timeout(
1652 "t".into()
1653 )));
1654 assert!(!safe_to_retry_non_idempotent(&ClientError::HttpClient(
1655 "reset".into()
1656 )));
1657 }
1658
1659 #[tokio::test]
1662 async fn non_idempotent_not_retried_on_timeout() {
1663 let inner = FailNTransport::new(5, serde_json::json!({"ok": true}));
1664 let call_count = Arc::clone(&inner.call_count);
1665 let transport = RetryTransport::new(
1666 Box::new(inner),
1667 RetryPolicy::default()
1668 .with_initial_backoff(Duration::from_millis(1))
1669 .with_max_retries(3),
1670 );
1671 let headers = HashMap::new();
1672 let result = transport
1673 .send_request("SendMessage", serde_json::Value::Null, &headers)
1674 .await;
1675 assert!(result.is_err());
1676 assert_eq!(
1677 call_count.load(Ordering::SeqCst),
1678 1,
1679 "SendMessage must not be re-sent on an ambiguous timeout"
1680 );
1681 }
1682
1683 fn keyed_send_params(key: &str) -> serde_json::Value {
1687 serde_json::json!({
1688 "message": {
1689 "id": "msg-1",
1690 "role": "user",
1691 "parts": [{"kind": "text", "text": "hi"}],
1692 "metadata": { IDEMPOTENCY_METADATA_KEY: key },
1693 }
1694 })
1695 }
1696
1697 const GOOD_KEY: &str = "8f14e45fceea167a5a36dedd4bea2543";
1698
1699 #[test]
1700 fn a_keyed_send_is_recognised_as_safe_to_retry() {
1701 for method in ["SendMessage", "SendStreamingMessage"] {
1702 assert!(
1703 carries_idempotency_key(method, &keyed_send_params(GOOD_KEY), true),
1704 "{method} with a key should be retryable"
1705 );
1706 }
1707 }
1708
1709 #[test]
1710 fn an_unkeyed_send_is_not() {
1711 let bare = serde_json::json!({"message": {"id": "m", "role": "user", "parts": []}});
1712 assert!(!carries_idempotency_key("SendMessage", &bare, true));
1713 assert!(!carries_idempotency_key(
1714 "SendMessage",
1715 &serde_json::Value::Null,
1716 true
1717 ));
1718 assert!(!carries_idempotency_key(
1719 "SendMessage",
1720 &serde_json::json!({"message": {"metadata": {"trace": "abc"}}}),
1721 true
1722 ));
1723 }
1724
1725 #[test]
1726 fn a_key_on_a_method_that_is_not_a_send_changes_nothing() {
1727 assert!(!carries_idempotency_key(
1730 "CreateTaskPushNotificationConfig",
1731 &keyed_send_params(GOOD_KEY),
1732 true
1733 ));
1734 }
1735
1736 #[test]
1737 fn a_malformed_key_does_not_make_a_send_retryable() {
1738 for bad in ["short", "", "has a space in it here"] {
1742 assert!(
1743 !carries_idempotency_key("SendMessage", &keyed_send_params(bad), true),
1744 "{bad:?} should not count as a key"
1745 );
1746 }
1747 assert!(!carries_idempotency_key(
1748 "SendMessage",
1749 &serde_json::json!({"message": {"metadata": {IDEMPOTENCY_METADATA_KEY: 42}}}),
1750 true
1751 ));
1752 }
1753
1754 #[tokio::test]
1758 async fn a_keyed_send_is_retried_on_an_ambiguous_timeout() {
1759 let inner = FailNTransport::new(2, serde_json::json!({"ok": true}));
1760 let call_count = Arc::clone(&inner.call_count);
1761 let transport = RetryTransport::new(
1762 Box::new(inner),
1763 RetryPolicy::default()
1764 .with_initial_backoff(Duration::from_millis(1))
1765 .with_max_retries(3),
1766 )
1767 .with_peer_honouring_idempotency(true);
1768 let headers = HashMap::new();
1769 let result = transport
1770 .send_request("SendMessage", keyed_send_params(GOOD_KEY), &headers)
1771 .await;
1772
1773 assert!(
1774 result.is_ok(),
1775 "the retry should have succeeded: {result:?}"
1776 );
1777 assert_eq!(
1778 call_count.load(Ordering::SeqCst),
1779 3,
1780 "two ambiguous failures then a success"
1781 );
1782 }
1783
1784 #[tokio::test]
1787 async fn an_unkeyed_send_is_still_not_retried_on_a_timeout() {
1788 let inner = FailNTransport::new(2, serde_json::json!({"ok": true}));
1789 let call_count = Arc::clone(&inner.call_count);
1790 let transport = RetryTransport::new(
1791 Box::new(inner),
1792 RetryPolicy::default()
1793 .with_initial_backoff(Duration::from_millis(1))
1794 .with_max_retries(3),
1795 );
1796 let headers = HashMap::new();
1797 let bare = serde_json::json!({"message": {"id": "m", "role": "user", "parts": []}});
1798 let result = transport.send_request("SendMessage", bare, &headers).await;
1799
1800 assert!(result.is_err());
1801 assert_eq!(call_count.load(Ordering::SeqCst), 1);
1802 }
1803
1804 #[tokio::test]
1810 async fn non_idempotent_retried_on_503_only_with_retry_after() {
1811 struct Fail503 {
1813 remaining: Arc<AtomicUsize>,
1814 calls: Arc<AtomicUsize>,
1815 retry_after: Option<Duration>,
1816 }
1817 impl crate::transport::Transport for Fail503 {
1818 fn send_request<'a>(
1819 &'a self,
1820 _m: &'a str,
1821 _p: serde_json::Value,
1822 _h: &'a HashMap<String, String>,
1823 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>>
1824 {
1825 self.calls.fetch_add(1, Ordering::SeqCst);
1826 let left = self.remaining.fetch_sub(1, Ordering::SeqCst);
1827 let retry_after = self.retry_after;
1828 Box::pin(async move {
1829 if left > 0 {
1830 Err(ClientError::UnexpectedStatus {
1831 status: 503,
1832 body: String::new(),
1833 retry_after,
1834 })
1835 } else {
1836 Ok(serde_json::json!({"ok": true}))
1837 }
1838 })
1839 }
1840 fn send_streaming_request<'a>(
1841 &'a self,
1842 _m: &'a str,
1843 _p: serde_json::Value,
1844 _h: &'a HashMap<String, String>,
1845 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
1846 Box::pin(async { Err(ClientError::Transport("n/a".into())) })
1847 }
1848 }
1849 for (retry_after, calls_made) in [(None, 1), (Some(Duration::from_millis(1)), 2)] {
1850 let calls = Arc::new(AtomicUsize::new(0));
1851 let inner = Fail503 {
1852 remaining: Arc::new(AtomicUsize::new(1)),
1853 calls: Arc::clone(&calls),
1854 retry_after,
1855 };
1856 let transport = RetryTransport::new(
1857 Box::new(inner),
1858 RetryPolicy::default()
1859 .with_initial_backoff(Duration::from_millis(1))
1860 .with_max_retries(3),
1861 );
1862 let result = transport
1863 .send_request("SendMessage", serde_json::Value::Null, &HashMap::new())
1864 .await;
1865 assert_eq!(result.is_ok(), calls_made == 2, "{result:?}");
1866 assert_eq!(calls.load(Ordering::SeqCst), calls_made, "{retry_after:?}");
1867 }
1868 }
1869
1870 #[tokio::test(start_paused = true)]
1872 async fn retry_after_header_is_honored() {
1873 struct RetryAfter429 {
1875 calls: Arc<AtomicUsize>,
1876 }
1877 impl crate::transport::Transport for RetryAfter429 {
1878 fn send_request<'a>(
1879 &'a self,
1880 _m: &'a str,
1881 _p: serde_json::Value,
1882 _h: &'a HashMap<String, String>,
1883 ) -> Pin<Box<dyn Future<Output = ClientResult<serde_json::Value>> + Send + 'a>>
1884 {
1885 let n = self.calls.fetch_add(1, Ordering::SeqCst);
1886 Box::pin(async move {
1887 if n == 0 {
1888 Err(ClientError::UnexpectedStatus {
1889 status: 429,
1890 body: String::new(),
1891 retry_after: Some(Duration::from_secs(20)),
1892 })
1893 } else {
1894 Ok(serde_json::json!({"ok": true}))
1895 }
1896 })
1897 }
1898 fn send_streaming_request<'a>(
1899 &'a self,
1900 _m: &'a str,
1901 _p: serde_json::Value,
1902 _h: &'a HashMap<String, String>,
1903 ) -> Pin<Box<dyn Future<Output = ClientResult<EventStream>> + Send + 'a>> {
1904 Box::pin(async { Err(ClientError::Transport("n/a".into())) })
1905 }
1906 }
1907 let calls = Arc::new(AtomicUsize::new(0));
1908 let transport = RetryTransport::new(
1909 Box::new(RetryAfter429 {
1910 calls: Arc::clone(&calls),
1911 }),
1912 RetryPolicy::default()
1915 .with_initial_backoff(Duration::from_millis(1))
1916 .with_max_backoff(Duration::from_secs(30)),
1917 );
1918 let start = tokio::time::Instant::now();
1919 let headers = HashMap::new();
1920 let result = transport
1921 .send_request("GetTask", serde_json::Value::Null, &headers)
1922 .await;
1923 assert!(result.is_ok());
1924 assert!(
1925 start.elapsed() >= Duration::from_secs(20),
1926 "should have waited the server-requested 20s, waited {:?}",
1927 start.elapsed()
1928 );
1929 }
1930
1931 #[test]
1935 fn spread_factor_covers_one_to_one_and_a_quarter() {
1936 assert!((spread_factor_from_bits(0) - 1.0).abs() < f64::EPSILON);
1937 assert!((spread_factor_from_bits(u64::MAX) - 1.25).abs() < 1e-12);
1938 let mid = spread_factor_from_bits(u64::MAX / 2);
1939 assert!((mid - 1.125).abs() < 1e-9, "{mid}");
1940 }
1941
1942 #[test]
1943 fn a_server_directed_delay_is_never_shortened_and_spread_by_at_most_a_quarter() {
1944 let after = Duration::from_secs(8);
1945 let mut distinct = std::collections::HashSet::new();
1946 for _ in 0..200 {
1947 let d = retry_delay(
1948 Some(&ClientError::UnexpectedStatus {
1949 status: 503,
1950 body: String::new(),
1951 retry_after: Some(after),
1952 }),
1953 Duration::from_millis(1),
1954 Duration::from_secs(30),
1955 );
1956 assert!(d >= after, "shortened to {d:?}");
1957 assert!(
1958 d <= Duration::from_secs(10),
1959 "lengthened past a quarter: {d:?}"
1960 );
1961 distinct.insert(d);
1962 }
1963 assert!(
1964 distinct.len() > 100,
1965 "clients refused together must not return together: {} distinct delays in 200",
1966 distinct.len()
1967 );
1968 }
1969
1970 #[test]
1972 fn the_spread_never_passes_max_backoff() {
1973 for _ in 0..50 {
1974 let d = retry_delay(
1975 Some(&ClientError::UnexpectedStatus {
1976 status: 503,
1977 body: String::new(),
1978 retry_after: Some(Duration::from_secs(29)),
1979 }),
1980 Duration::from_millis(1),
1981 Duration::from_secs(30),
1982 );
1983 assert!(
1984 d >= Duration::from_secs(29) && d <= Duration::from_secs(30),
1985 "{d:?}"
1986 );
1987 }
1988 }
1989
1990 #[test]
1991 fn retry_after_clamped_to_max_backoff() {
1992 let err = ClientError::UnexpectedStatus {
1993 status: 503,
1994 body: String::new(),
1995 retry_after: Some(Duration::from_secs(9999)),
1996 };
1997 let delay = retry_delay(Some(&err), Duration::from_secs(1), Duration::from_secs(30));
1998 assert_eq!(
1999 delay,
2000 Duration::from_secs(30),
2001 "retry-after must be clamped"
2002 );
2003 }
2004 #[tokio::test]
2013 async fn a_keyed_send_is_not_retried_against_a_peer_that_never_advertised_it() {
2014 let inner = FailNTransport::new(2, serde_json::json!({"ok": true}));
2015 let call_count = Arc::clone(&inner.call_count);
2016 let transport = RetryTransport::new(
2019 Box::new(inner),
2020 RetryPolicy::default()
2021 .with_initial_backoff(Duration::from_millis(1))
2022 .with_max_retries(3),
2023 );
2024 let headers = HashMap::new();
2025 let result = transport
2026 .send_request("SendMessage", keyed_send_params(GOOD_KEY), &headers)
2027 .await;
2028
2029 assert!(result.is_err(), "the ambiguous failure must surface");
2030 assert_eq!(
2031 call_count.load(Ordering::SeqCst),
2032 1,
2033 "a key the peer never claimed to honour must not make the send retryable"
2034 );
2035 }
2036
2037 #[test]
2040 fn the_predicate_requires_both_the_key_and_the_advertisement() {
2041 assert!(
2042 carries_idempotency_key("SendMessage", &keyed_send_params(GOOD_KEY), true),
2043 "a valid key against an advertising peer is retryable"
2044 );
2045 assert!(
2046 !carries_idempotency_key("SendMessage", &keyed_send_params(GOOD_KEY), false),
2047 "the identical send against a peer that did not advertise is not"
2048 );
2049 }
2050}