1use std::sync::atomic::{AtomicU64, Ordering};
20use std::sync::OnceLock;
21use std::time::Duration;
22
23use http::Method;
24
25use crate::body::RequestBody;
26use crate::error::Error;
27
28const DEFAULT_RETRYABLE_STATUSES: &[u16] = &[408, 429, 502, 503, 504];
30
31#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
38fn is_hyper_canceled(inner: &hyper_util::client::legacy::Error) -> bool {
39 crate::error::hyper_legacy_is_canceled(inner)
40}
41
42const DEFAULT_RETRYABLE_METHODS: &[Method] = &[Method::GET, Method::HEAD, Method::OPTIONS];
44
45#[derive(Debug, Clone)]
65pub struct RetryPolicy {
66 max_attempts: usize,
68 max_elapsed: Option<Duration>,
70 backoff: BackoffPolicy,
72 method_policy: MethodPolicy,
74 status_policy: StatusPolicy,
76 respect_retry_after: bool,
78}
79
80impl Default for RetryPolicy {
81 fn default() -> Self {
82 Self {
83 max_attempts: 1,
84 max_elapsed: None,
85 backoff: BackoffPolicy::default(),
86 method_policy: MethodPolicy::default(),
87 status_policy: StatusPolicy::default(),
88 respect_retry_after: false,
89 }
90 }
91}
92
93impl RetryPolicy {
94 #[must_use]
96 pub fn builder() -> RetryPolicyBuilder {
97 RetryPolicyBuilder::new()
98 }
99
100 #[must_use]
102 pub fn max_attempts(&self) -> usize {
103 self.max_attempts
104 }
105
106 #[must_use]
108 pub fn max_elapsed(&self) -> Option<Duration> {
109 self.max_elapsed
110 }
111
112 #[must_use]
114 pub fn backoff(&self) -> &BackoffPolicy {
115 &self.backoff
116 }
117
118 #[must_use]
120 pub fn method_policy(&self) -> &MethodPolicy {
121 &self.method_policy
122 }
123
124 #[must_use]
126 pub fn status_policy(&self) -> &StatusPolicy {
127 &self.status_policy
128 }
129
130 #[must_use]
132 pub fn respect_retry_after(&self) -> bool {
133 self.respect_retry_after
134 }
135
136 #[must_use]
138 pub fn is_enabled(&self) -> bool {
139 self.max_attempts > 1
140 }
141
142 #[must_use]
144 pub fn is_method_retryable(&self, method: &Method) -> bool {
145 self.method_policy.is_retryable(method)
146 }
147
148 #[must_use]
150 pub fn is_status_retryable(&self, status: u16) -> bool {
151 self.status_policy.is_retryable(status)
152 }
153
154 #[must_use]
156 pub fn is_error_retryable(error: &Error) -> bool {
157 #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
158 if let Error::HyperClient(inner) = error {
159 return inner.is_connect() || is_hyper_canceled(inner.as_ref());
168 }
169 match error {
170 Error::Connect(_)
171 | Error::Io(_)
172 | Error::Hyper(_)
173 | Error::Timeout {
174 phase: crate::timeout::TimeoutPhase::Connect,
175 ..
176 }
177 | Error::Timeout {
178 phase: crate::timeout::TimeoutPhase::Pool,
179 ..
180 }
181 | Error::Timeout {
182 phase:
183 crate::timeout::TimeoutPhase::ProxyConnect | crate::timeout::TimeoutPhase::ProxyTls,
184 ..
185 }
186 | Error::H3Connect(_) => true,
187 Error::CustomTransport(error) => matches!(
188 error.kind(),
189 crate::transport::dialer::DialErrorKind::Connection
190 | crate::transport::dialer::DialErrorKind::Timeout
191 ),
192 Error::Http2StreamReset { reason } if reason.starts_with("REFUSED_STREAM") => true,
193 _ => false,
194 }
195 }
196
197 #[must_use]
201 pub fn backoff_delay(&self, attempt: usize) -> Option<Duration> {
202 self.backoff.delay(attempt)
203 }
204
205 #[must_use]
212 pub fn retry_after_delay(&self, retry_after: &str) -> Option<Duration> {
213 if !self.respect_retry_after {
214 return None;
215 }
216 let delay = if let Ok(secs) = retry_after.trim().parse::<u64>() {
217 Duration::from_secs(secs)
218 } else if let Ok(date) = httpdate::parse_http_date(retry_after.trim()) {
219 match date.duration_since(std::time::SystemTime::now()) {
220 Ok(duration) => duration,
221 Err(_) => return None,
222 }
223 } else {
224 return None;
225 };
226 let cap = self.backoff.max_delay;
227 Some(if delay > cap { cap } else { delay })
228 }
229
230 #[must_use]
235 pub fn check_body_replayable(body: &RequestBody) -> ReplayCheck {
236 if body.is_replayable() {
237 ReplayCheck::Replayable
238 } else {
239 ReplayCheck::NotReplayable
240 }
241 }
242}
243
244pub struct RetryPolicyBuilder {
246 max_attempts: usize,
247 max_elapsed: Option<Duration>,
248 backoff: BackoffPolicyBuilder,
249 method_policy: MethodPolicy,
250 status_policy: StatusPolicy,
251 respect_retry_after: bool,
252 custom_statuses_used: bool,
253}
254
255impl RetryPolicyBuilder {
256 #[must_use]
258 pub fn new() -> Self {
259 Self {
260 max_attempts: 1,
261 max_elapsed: None,
262 backoff: BackoffPolicyBuilder::new(),
263 method_policy: MethodPolicy::default(),
264 status_policy: StatusPolicy::default(),
265 respect_retry_after: false,
266 custom_statuses_used: false,
267 }
268 }
269
270 #[must_use]
274 pub fn max_attempts(mut self, max: usize) -> Self {
275 self.max_attempts = max;
276 self
277 }
278
279 #[must_use]
283 pub fn max_elapsed(mut self, elapsed: Duration) -> Self {
284 self.max_elapsed = Some(elapsed);
285 self
286 }
287
288 #[must_use]
294 pub fn backoff_factor(mut self, factor: f64) -> Self {
295 self.backoff = self.backoff.factor(factor);
296 self
297 }
298
299 #[must_use]
301 pub fn max_delay(mut self, delay: Duration) -> Self {
302 self.backoff = self.backoff.max_delay(delay);
303 self
304 }
305
306 #[must_use]
308 pub fn initial_delay(mut self, delay: Duration) -> Self {
309 self.backoff = self.backoff.initial_delay(delay);
310 self
311 }
312
313 #[must_use]
318 pub fn retry_status(mut self, status: u16) -> Self {
319 if !self.custom_statuses_used {
320 self.status_policy = StatusPolicy::default_empty();
321 self.custom_statuses_used = true;
322 }
323 self.status_policy.add_status(status);
324 self
325 }
326
327 #[must_use]
329 pub fn retry_statuses(mut self, statuses: impl IntoIterator<Item = u16>) -> Self {
330 self.status_policy = StatusPolicy::new(statuses);
331 self.custom_statuses_used = true;
332 self
333 }
334
335 #[must_use]
337 pub fn retry_method(mut self, method: Method) -> Self {
338 self.method_policy.add_method(method);
339 self
340 }
341
342 #[must_use]
344 pub fn allow_post_retry(mut self) -> Self {
345 self.method_policy.add_method(Method::POST);
346 self
347 }
348
349 #[must_use]
351 pub fn allow_put_retry(mut self) -> Self {
352 self.method_policy.add_method(Method::PUT);
353 self
354 }
355
356 #[must_use]
358 pub fn allow_delete_retry(mut self) -> Self {
359 self.method_policy.add_method(Method::DELETE);
360 self
361 }
362
363 #[must_use]
365 pub fn allow_patch_retry(mut self) -> Self {
366 self.method_policy.add_method(Method::PATCH);
367 self
368 }
369
370 #[must_use]
372 pub fn respect_retry_after(mut self, respect: bool) -> Self {
373 self.respect_retry_after = respect;
374 self
375 }
376
377 #[must_use]
379 pub fn build(self) -> RetryPolicy {
380 RetryPolicy {
381 max_attempts: self.max_attempts,
382 max_elapsed: self.max_elapsed,
383 backoff: self.backoff.build(),
384 method_policy: self.method_policy,
385 status_policy: self.status_policy,
386 respect_retry_after: self.respect_retry_after,
387 }
388 }
389}
390
391impl Default for RetryPolicyBuilder {
392 fn default() -> Self {
393 Self::new()
394 }
395}
396
397#[derive(Debug, Clone)]
399pub struct BackoffPolicy {
400 factor: f64,
402 max_delay: Duration,
404 initial_delay: Duration,
406}
407
408impl Default for BackoffPolicy {
409 fn default() -> Self {
410 Self {
411 factor: 2.0,
412 max_delay: Duration::from_secs(30),
413 initial_delay: Duration::from_millis(500),
414 }
415 }
416}
417
418impl BackoffPolicy {
419 #[must_use]
426 #[allow(
427 clippy::cast_precision_loss,
428 reason = "the attempt counter is only used as an f64 exponent, so rounding beyond 2^53 attempts cannot change the delay"
429 )]
430 pub fn delay(&self, attempt: usize) -> Option<Duration> {
431 if attempt <= 1 {
432 return None;
433 }
434
435 let exp = (attempt - 2) as f64;
437 let raw = self.initial_delay.as_secs_f64() * self.factor.powf(exp);
438 let max_float = self.max_delay.as_secs_f64();
442 let max_secs = if Duration::try_from_secs_f64(max_float).is_ok() {
443 max_float
444 } else {
445 f64::MAX
446 };
447
448 let capped = if !raw.is_finite() || raw < 0.0 || raw > max_secs {
454 self.max_delay
455 } else {
456 Duration::try_from_secs_f64(raw).unwrap_or(self.max_delay)
457 };
458
459 let jittered_secs = match get_random_f64() {
465 Some(jitter) => capped.as_secs_f64() * jitter,
466 None => capped.as_secs_f64(),
467 };
468
469 let final_delay = if !jittered_secs.is_finite() || jittered_secs < 0.0 {
470 capped
471 } else {
472 Duration::try_from_secs_f64(jittered_secs).unwrap_or(capped)
475 };
476
477 Some(final_delay.max(Duration::from_millis(1).min(capped)))
481 }
482
483 #[must_use]
485 pub fn max_delay(&self) -> Duration {
486 self.max_delay
487 }
488
489 #[must_use]
491 pub fn factor(&self) -> f64 {
492 self.factor
493 }
494
495 #[must_use]
497 pub fn initial_delay(&self) -> Duration {
498 self.initial_delay
499 }
500}
501
502pub struct BackoffPolicyBuilder {
504 factor: f64,
505 max_delay: Duration,
506 initial_delay: Duration,
507}
508
509impl BackoffPolicyBuilder {
510 #[must_use]
511 fn new() -> Self {
512 Self {
513 factor: 2.0,
514 max_delay: Duration::from_secs(30),
515 initial_delay: Duration::from_millis(500),
516 }
517 }
518
519 #[must_use]
520 fn factor(mut self, factor: f64) -> Self {
521 self.factor = factor;
525 self
526 }
527
528 #[must_use]
529 fn max_delay(mut self, delay: Duration) -> Self {
530 self.max_delay = delay;
531 self
532 }
533
534 #[must_use]
535 fn initial_delay(mut self, delay: Duration) -> Self {
536 self.initial_delay = delay;
537 self
538 }
539
540 #[must_use]
541 fn build(self) -> BackoffPolicy {
542 BackoffPolicy {
543 factor: self.factor,
544 max_delay: self.max_delay,
545 initial_delay: self.initial_delay,
546 }
547 }
548}
549
550#[derive(Debug, Clone)]
552pub struct MethodPolicy {
553 methods: Vec<Method>,
555}
556
557impl Default for MethodPolicy {
558 fn default() -> Self {
559 Self {
560 methods: DEFAULT_RETRYABLE_METHODS.to_vec(),
561 }
562 }
563}
564
565impl MethodPolicy {
566 #[must_use]
568 pub fn new(methods: Vec<Method>) -> Self {
569 Self { methods }
570 }
571
572 pub fn add_method(&mut self, method: Method) {
574 if !self.methods.contains(&method) {
575 self.methods.push(method);
576 }
577 }
578
579 #[must_use]
581 pub fn is_retryable(&self, method: &Method) -> bool {
582 self.methods.contains(method)
583 }
584
585 #[must_use]
587 pub fn methods(&self) -> &[Method] {
588 &self.methods
589 }
590}
591
592#[derive(Debug, Clone)]
594pub struct StatusPolicy {
595 statuses: Vec<u16>,
597}
598
599impl Default for StatusPolicy {
600 fn default() -> Self {
601 Self {
602 statuses: DEFAULT_RETRYABLE_STATUSES.to_vec(),
603 }
604 }
605}
606
607impl StatusPolicy {
608 #[must_use]
610 pub fn new(statuses: impl IntoIterator<Item = u16>) -> Self {
611 Self {
612 statuses: statuses.into_iter().collect(),
613 }
614 }
615
616 #[must_use]
618 pub fn default_empty() -> Self {
619 Self {
620 statuses: Vec::new(),
621 }
622 }
623
624 pub fn add_status(&mut self, status: u16) {
626 if !self.statuses.contains(&status) {
627 self.statuses.push(status);
628 }
629 }
630
631 #[must_use]
633 pub fn is_retryable(&self, status: u16) -> bool {
634 self.statuses.contains(&status)
635 }
636
637 #[must_use]
639 pub fn statuses(&self) -> &[u16] {
640 &self.statuses
641 }
642}
643
644#[derive(Debug, Clone, Copy, PartialEq, Eq)]
646pub enum ReplayCheck {
647 Replayable,
649 NotReplayable,
651}
652
653#[derive(Debug, Clone, PartialEq, Eq)]
655pub enum RetryCause {
656 TransportError(String),
658 Status(u16),
660 Timeout(String),
662}
663
664impl std::fmt::Display for RetryCause {
665 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
666 match self {
667 Self::TransportError(msg) => write!(f, "transport error: {msg}"),
668 Self::Status(status) => write!(f, "retryable status: {status}"),
669 Self::Timeout(phase) => write!(f, "timeout: {phase}"),
670 }
671 }
672}
673
674#[derive(Debug, Clone)]
676pub struct RetryContext {
677 pub attempt: usize,
679 pub method: Method,
681 pub body_replayable: bool,
683 pub cause: RetryCause,
685 pub remaining_total: Option<Duration>,
687}
688
689#[must_use]
694pub fn should_retry(
695 policy: &RetryPolicy,
696 method: &Method,
697 body: &RequestBody,
698 error: Option<&Error>,
699 status: Option<u16>,
700) -> Option<RetryCause> {
701 if !policy.is_method_retryable(method) {
702 return None;
703 }
704
705 if !body.is_replayable() {
706 return None;
707 }
708
709 if let Some(err) = error {
710 if RetryPolicy::is_error_retryable(err) {
711 return Some(RetryCause::TransportError(err.to_string()));
712 }
713 return None;
714 }
715
716 if let Some(status) = status {
717 if policy.is_status_retryable(status) {
718 return Some(RetryCause::Status(status));
719 }
720 }
721
722 None
723}
724
725#[allow(
730 clippy::cast_precision_loss,
731 reason = "the 53 high bits of the PRNG state are exactly representable in f64, so the conversion is lossless"
732)]
733fn get_random_f64() -> Option<f64> {
734 static STATE: OnceLock<AtomicU64> = OnceLock::new();
738
739 let state = if let Some(state) = STATE.get() {
740 state
741 } else {
742 let mut buf = [0u8; 8];
743 let seed = u64::from_le_bytes({
744 getrandom::getrandom(&mut buf).ok()?;
745 buf
746 })
747 .max(1);
748 let _ = STATE.set(AtomicU64::new(seed));
749 STATE.get()?
750 };
751 #[allow(
755 deprecated,
756 reason = "fetch_update is deprecated in favour of try_update, which is still unstable on the MSRV toolchain"
757 )]
758 let val = state
759 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |mut value| {
760 value ^= value << 13;
761 value ^= value >> 7;
762 value ^= value << 17;
763 Some(value.max(1))
764 })
765 .ok()?;
766 Some(((val >> 11) as f64) / ((1u64 << 53) as f64))
770}
771
772#[cfg(test)]
773mod tests {
774 use super::*;
775 use proptest::prelude::*;
776
777 #[test]
778 fn retry_policy_default_disables_retries() {
779 let policy = RetryPolicy::default();
780 assert!(!policy.is_enabled());
781 assert_eq!(policy.max_attempts(), 1);
782 }
783
784 #[test]
785 fn proxy_timeout_phases_are_retryable() {
786 for phase in [
787 crate::timeout::TimeoutPhase::ProxyConnect,
788 crate::timeout::TimeoutPhase::ProxyTls,
789 ] {
790 let error = Error::Timeout {
791 phase,
792 elapsed: Duration::from_secs(1),
793 };
794 assert!(RetryPolicy::is_error_retryable(&error));
795 }
796 }
797
798 #[test]
799 fn custom_dialer_connection_and_timeout_failures_are_retryable() {
800 for kind in [
801 crate::transport::dialer::DialErrorKind::Connection,
802 crate::transport::dialer::DialErrorKind::Timeout,
803 ] {
804 let error = Error::CustomTransport(std::sync::Arc::new(
805 crate::transport::dialer::DialError::new(kind, "route failed"),
806 ));
807 assert!(RetryPolicy::is_error_retryable(&error));
808 }
809 for kind in [
810 crate::transport::dialer::DialErrorKind::Authentication,
811 crate::transport::dialer::DialErrorKind::Rejected,
812 crate::transport::dialer::DialErrorKind::Other,
813 ] {
814 let error = Error::CustomTransport(std::sync::Arc::new(
815 crate::transport::dialer::DialError::new(kind, "route failed"),
816 ));
817 assert!(!RetryPolicy::is_error_retryable(&error));
818 }
819 }
820
821 #[test]
822 fn jitter_is_strictly_below_one() {
823 for _ in 0..10_000 {
826 let Some(jitter) = get_random_f64() else {
827 return;
831 };
832 assert!((0.0..1.0).contains(&jitter));
833 }
834 }
835
836 #[test]
837 fn retry_policy_builder_basic() {
838 let policy = RetryPolicy::builder()
839 .max_attempts(3)
840 .backoff_factor(0.2)
841 .build();
842 assert!(policy.is_enabled());
843 assert_eq!(policy.max_attempts(), 3);
844 }
845
846 #[test]
847 fn retry_policy_method_default_safe() {
848 let policy = RetryPolicy::default();
849 assert!(policy.is_method_retryable(&Method::GET));
850 assert!(policy.is_method_retryable(&Method::HEAD));
851 assert!(policy.is_method_retryable(&Method::OPTIONS));
852 assert!(!policy.is_method_retryable(&Method::POST));
853 assert!(!policy.is_method_retryable(&Method::PUT));
854 assert!(!policy.is_method_retryable(&Method::DELETE));
855 assert!(!policy.is_method_retryable(&Method::PATCH));
856 }
857
858 #[test]
859 fn retry_policy_method_allow_post() {
860 let policy = RetryPolicy::builder()
861 .max_attempts(3)
862 .allow_post_retry()
863 .build();
864 assert!(policy.is_method_retryable(&Method::POST));
865 }
866
867 #[test]
868 fn retry_policy_status_default() {
869 let policy = RetryPolicy::default();
870 assert!(policy.is_status_retryable(408));
871 assert!(policy.is_status_retryable(429));
872 assert!(policy.is_status_retryable(502));
873 assert!(policy.is_status_retryable(503));
874 assert!(policy.is_status_retryable(504));
875 assert!(!policy.is_status_retryable(200));
876 assert!(!policy.is_status_retryable(404));
877 }
878
879 #[test]
880 fn retry_policy_status_custom() {
881 let policy = RetryPolicy::builder()
882 .max_attempts(3)
883 .retry_status(429)
884 .retry_status(503)
885 .build();
886 assert!(policy.is_status_retryable(429));
887 assert!(policy.is_status_retryable(503));
888 assert!(!policy.is_status_retryable(408));
889 assert!(!policy.is_status_retryable(504));
890 }
891
892 #[test]
893 fn backoff_delay_none_for_first_attempt() {
894 let backoff = BackoffPolicy::default();
895 assert!(backoff.delay(1).is_none());
896 }
897
898 #[test]
899 fn backoff_delay_bounded_for_later_attempts() {
900 let backoff = BackoffPolicy {
901 factor: 0.5,
902 max_delay: Duration::from_secs(30),
903 initial_delay: Duration::from_millis(100),
904 };
905 let d2 = backoff.delay(2).unwrap();
907 assert!(d2 <= Duration::from_millis(100));
908
909 let d3 = backoff.delay(3).unwrap();
910 assert!(d3 <= Duration::from_millis(50));
911 }
912
913 #[test]
914 fn backoff_delay_has_minimum_when_cap_is_positive() {
915 let backoff = BackoffPolicy {
916 factor: 1.0,
917 max_delay: Duration::from_millis(1),
918 initial_delay: Duration::from_millis(1),
919 };
920 assert_eq!(backoff.delay(2), Some(Duration::from_millis(1)));
921 }
922
923 #[test]
924 fn default_backoff_grows_exponentially() {
925 let backoff = BackoffPolicy::default();
929 assert!((backoff.factor() - 2.0).abs() < f64::EPSILON);
930 assert!(backoff.delay(2).unwrap() <= Duration::from_millis(500));
931 assert!(backoff.delay(3).unwrap() <= Duration::from_secs(1));
932 assert!(backoff.delay(4).unwrap() <= Duration::from_secs(2));
933 }
934
935 #[test]
936 fn backoff_delay_capped_at_max() {
937 let backoff = BackoffPolicy {
938 factor: 2.0,
939 max_delay: Duration::from_secs(5),
940 initial_delay: Duration::from_secs(1),
941 };
942 let d = backoff.delay(10).unwrap();
943 assert!(d < Duration::from_secs(5)); }
945
946 #[test]
947 fn retry_after_disabled_by_default() {
948 let policy = RetryPolicy::default();
949 assert!(policy.retry_after_delay("5").is_none());
950 }
951
952 #[test]
953 fn retry_after_respected_when_enabled() {
954 let policy = RetryPolicy::builder()
955 .max_attempts(3)
956 .respect_retry_after(true)
957 .build();
958 let delay = policy.retry_after_delay("5").unwrap();
959 assert_eq!(delay, Duration::from_secs(5));
960 }
961
962 #[test]
963 fn retry_after_capped_at_max_delay() {
964 let policy = RetryPolicy::builder()
965 .max_attempts(3)
966 .respect_retry_after(true)
967 .max_delay(Duration::from_secs(10))
968 .build();
969 let delay = policy.retry_after_delay("60").unwrap();
970 assert_eq!(delay, Duration::from_secs(10));
971 }
972
973 #[test]
974 fn retry_after_invalid_ignored() {
975 let policy = RetryPolicy::builder()
976 .max_attempts(3)
977 .respect_retry_after(true)
978 .build();
979 assert!(policy.retry_after_delay("not-a-number").is_none());
980 }
981
982 #[test]
983 fn retry_after_http_date_parses() {
984 use std::time::UNIX_EPOCH;
985
986 let policy = RetryPolicy::builder()
987 .max_attempts(3)
988 .respect_retry_after(true)
989 .build();
990 let future_time = UNIX_EPOCH
993 + Duration::from_secs(
994 std::time::SystemTime::now()
995 .duration_since(UNIX_EPOCH)
996 .unwrap()
997 .as_secs()
998 + 3600,
999 ); let formatted = httpdate::fmt_http_date(future_time);
1001 let parsed = httpdate::parse_http_date(&formatted);
1002 assert!(parsed.is_ok(), "round-trip parse failed: {formatted}");
1003 let delay = policy.retry_after_delay(&formatted);
1004 assert!(
1005 delay.is_some(),
1006 "retry_after_delay returned None for HTTP-date: {formatted}"
1007 );
1008 let d = delay.unwrap();
1009 assert!(d.as_secs() > 0, "delay should be positive");
1010 }
1011
1012 #[test]
1013 fn retry_after_past_http_date_is_ignored() {
1014 use std::time::UNIX_EPOCH;
1015
1016 let policy = RetryPolicy::builder()
1017 .max_attempts(3)
1018 .respect_retry_after(true)
1019 .build();
1020 let past_time = UNIX_EPOCH
1023 + Duration::from_secs(
1024 std::time::SystemTime::now()
1025 .duration_since(UNIX_EPOCH)
1026 .unwrap()
1027 .as_secs()
1028 .saturating_sub(3600),
1029 );
1030 let formatted = httpdate::fmt_http_date(past_time);
1031 assert!(policy.retry_after_delay(&formatted).is_none());
1032 }
1033
1034 #[test]
1035 fn body_replayable_empty() {
1036 let body = RequestBody::Empty;
1037 assert_eq!(
1038 RetryPolicy::check_body_replayable(&body),
1039 ReplayCheck::Replayable
1040 );
1041 }
1042
1043 #[test]
1044 fn body_replayable_bytes() {
1045 let body = RequestBody::from(bytes::Bytes::from("hello"));
1046 assert_eq!(
1047 RetryPolicy::check_body_replayable(&body),
1048 ReplayCheck::Replayable
1049 );
1050 }
1051
1052 #[test]
1053 fn body_not_replayable_stream() {
1054 let body = RequestBody::from_stream(
1055 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1056 None,
1057 );
1058 assert_eq!(
1059 RetryPolicy::check_body_replayable(&body),
1060 ReplayCheck::NotReplayable
1061 );
1062 }
1063
1064 #[test]
1065 fn should_retry_get_with_retryable_status() {
1066 let policy = RetryPolicy::builder().max_attempts(3).build();
1067 let body = RequestBody::Empty;
1068 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1069 assert_eq!(cause, Some(RetryCause::Status(503)));
1070 }
1071
1072 #[test]
1073 fn should_not_retry_post_by_default() {
1074 let policy = RetryPolicy::builder().max_attempts(3).build();
1075 let body = RequestBody::Empty;
1076 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1077 assert_eq!(cause, None);
1078 }
1079
1080 #[test]
1081 fn should_retry_post_when_allowed() {
1082 let policy = RetryPolicy::builder()
1083 .max_attempts(3)
1084 .allow_post_retry()
1085 .build();
1086 let body = RequestBody::Empty;
1087 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1088 assert_eq!(cause, Some(RetryCause::Status(503)));
1089 }
1090
1091 #[test]
1092 fn should_not_retry_non_retryable_status() {
1093 let policy = RetryPolicy::builder().max_attempts(3).build();
1094 let body = RequestBody::Empty;
1095 let cause = should_retry(&policy, &Method::GET, &body, None, Some(200));
1096 assert_eq!(cause, None);
1097 }
1098
1099 #[test]
1100 fn should_not_retry_stream_body() {
1101 let policy = RetryPolicy::builder().max_attempts(3).build();
1102 let body = RequestBody::from_stream(
1103 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1104 None,
1105 );
1106 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1107 assert_eq!(cause, None);
1108 }
1109
1110 #[test]
1111 fn should_retry_connect_error() {
1112 let policy = RetryPolicy::builder().max_attempts(3).build();
1113 let body = RequestBody::Empty;
1114 let err = Error::Connect("connection refused".into());
1115 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1116 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1117 }
1118
1119 #[test]
1120 fn should_not_retry_invalid_url() {
1121 let policy = RetryPolicy::builder().max_attempts(3).build();
1122 let body = RequestBody::Empty;
1123 let err = Error::InvalidUrl("bad url".into());
1124 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1125 assert_eq!(cause, None);
1126 }
1127
1128 #[test]
1129 #[cfg(feature = "http3")]
1130 fn should_retry_h3_connect_error() {
1131 let policy = RetryPolicy::builder().max_attempts(3).build();
1132 let body = RequestBody::Empty;
1133 let err = Error::H3Connect("QUIC handshake failed".into());
1134 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1135 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1136 }
1137
1138 #[test]
1139 #[cfg(feature = "http3")]
1140 fn should_not_retry_h3_connection_closed() {
1141 let policy = RetryPolicy::builder().max_attempts(3).build();
1142 let body = RequestBody::Empty;
1143 let err = Error::H3ConnectionClosed("peer sent GOAWAY".into());
1144 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1145 assert_eq!(cause, None);
1146 }
1147
1148 #[test]
1149 #[cfg(feature = "http3")]
1150 fn should_not_retry_h3_protocol_error() {
1151 let policy = RetryPolicy::builder().max_attempts(3).build();
1152 let body = RequestBody::Empty;
1153 let err = Error::H3Protocol("unexpected frame".into());
1154 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1155 assert_eq!(cause, None);
1156 }
1157
1158 #[test]
1159 #[cfg(feature = "http3")]
1160 fn should_not_retry_h3_stream_error() {
1161 let policy = RetryPolicy::builder().max_attempts(3).build();
1162 let body = RequestBody::Empty;
1163 let err = Error::H3Stream("stream reset".into());
1164 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1165 assert_eq!(cause, None);
1166 }
1167
1168 #[test]
1169 fn retry_cause_display() {
1170 assert_eq!(
1171 RetryCause::TransportError("refused".into()).to_string(),
1172 "transport error: refused"
1173 );
1174 assert_eq!(RetryCause::Status(503).to_string(), "retryable status: 503");
1175 assert_eq!(
1176 RetryCause::Timeout("total".into()).to_string(),
1177 "timeout: total"
1178 );
1179 }
1180
1181 #[test]
1182 fn method_policy_add_method() {
1183 let mut policy = MethodPolicy::default();
1184 assert!(!policy.is_retryable(&Method::POST));
1185 policy.add_method(Method::POST);
1186 assert!(policy.is_retryable(&Method::POST));
1187 }
1188
1189 #[test]
1190 fn status_policy_add_status() {
1191 let mut policy = StatusPolicy::default();
1192 assert!(!policy.is_retryable(418));
1193 policy.add_status(418);
1194 assert!(policy.is_retryable(418));
1195 }
1196
1197 #[test]
1198 fn retry_policy_max_elapsed() {
1199 let policy = RetryPolicy::builder()
1200 .max_attempts(3)
1201 .max_elapsed(Duration::from_secs(10))
1202 .build();
1203 assert_eq!(policy.max_elapsed(), Some(Duration::from_secs(10)));
1204 }
1205
1206 #[test]
1207 fn retry_policy_display_cause() {
1208 let cause = RetryCause::Status(429);
1209 assert_eq!(format!("{cause}"), "retryable status: 429");
1210 }
1211
1212 #[test]
1213 fn prop_backoff_delay_some_for_attempt_gt_1() {
1214 proptest::proptest!(|(attempt in 2usize..100usize)| {
1215 let backoff = BackoffPolicy::default();
1216 prop_assert!(backoff.delay(attempt).is_some());
1217 });
1218 }
1219
1220 #[test]
1221 fn prop_backoff_delay_bounded_by_max_delay() {
1222 proptest::proptest!(|(
1223 factor in 0.1f64..2.0f64,
1224 initial_ms in 1u64..1000u64,
1225 max_secs in 1u64..60u64,
1226 attempt in 2usize..20usize,
1227 )| {
1228 let backoff = BackoffPolicy {
1229 factor,
1230 max_delay: Duration::from_secs(max_secs),
1231 initial_delay: Duration::from_millis(initial_ms),
1232 };
1233 if let Some(delay) = backoff.delay(attempt) {
1234 prop_assert!(delay <= Duration::from_secs(max_secs * 2));
1235 }
1236 });
1237 }
1238
1239 #[test]
1240 fn prop_method_policy_default_contains_get_head_options() {
1241 let policy = MethodPolicy::default();
1242 assert!(policy.is_retryable(&Method::GET));
1243 assert!(policy.is_retryable(&Method::HEAD));
1244 assert!(policy.is_retryable(&Method::OPTIONS));
1245 }
1246
1247 #[test]
1248 fn prop_status_policy_default_contains_expected() {
1249 let policy = StatusPolicy::default();
1250 assert!(policy.is_retryable(408));
1251 assert!(policy.is_retryable(429));
1252 assert!(policy.is_retryable(502));
1253 assert!(policy.is_retryable(503));
1254 assert!(policy.is_retryable(504));
1255 }
1256
1257 #[test]
1258 fn prop_retry_after_delay_returns_none_for_garbage() {
1259 proptest::proptest!(|(input in ".{0,100}")| {
1260 let policy = RetryPolicy::builder()
1261 .max_attempts(3)
1262 .respect_retry_after(true)
1263 .build();
1264 let _ = policy.retry_after_delay(&input);
1265 });
1266 }
1267
1268 #[test]
1269 fn regression_fuzz_retry_crash_extreme_backoff_factor() {
1270 let backoff = BackoffPolicy {
1271 factor: 22.0,
1272 max_delay: Duration::from_secs(30),
1273 initial_delay: Duration::from_millis(500),
1274 };
1275 for attempt in 2..=20 {
1276 let delay = backoff.delay(attempt);
1277 assert!(delay.is_some());
1278 assert!(delay.unwrap() <= backoff.max_delay);
1279 }
1280 }
1281
1282 #[test]
1283 fn backoff_delay_nan_factor_returns_bounded_delay() {
1284 let backoff = BackoffPolicy {
1285 factor: f64::NAN,
1286 max_delay: Duration::from_secs(30),
1287 initial_delay: Duration::from_millis(500),
1288 };
1289 let d = backoff.delay(5).unwrap();
1290 assert!(d <= Duration::from_secs(30));
1291 }
1292
1293 #[test]
1294 fn backoff_delay_infinite_factor_returns_bounded_delay() {
1295 let backoff = BackoffPolicy {
1296 factor: f64::INFINITY,
1297 max_delay: Duration::from_secs(30),
1298 initial_delay: Duration::from_millis(500),
1299 };
1300 let d = backoff.delay(5).unwrap();
1301 assert!(d <= Duration::from_secs(30));
1302 }
1303
1304 #[test]
1305 fn backoff_delay_max_duration_does_not_panic() {
1306 let backoff = BackoffPolicy {
1309 factor: 2.0,
1310 max_delay: Duration::MAX,
1311 initial_delay: Duration::from_millis(500),
1312 };
1313 for attempt in [2, 5, 100] {
1314 let d = backoff.delay(attempt).unwrap();
1315 assert!(d <= Duration::MAX);
1316 }
1317 }
1318
1319 #[test]
1320 fn prop_is_error_retryable_never_panics() {
1321 proptest::proptest!(|(msg in ".{0,200}")| {
1322 let errors = vec![
1323 Error::Connect(msg.clone()),
1324 Error::Io(std::sync::Arc::new(std::io::Error::other(msg.clone()))),
1325 Error::InvalidUrl(msg.clone()),
1326 Error::Tls(msg.clone()),
1327 Error::Protocol(msg.clone()),
1328 Error::Body(msg.clone()),
1329 ];
1330 for err in &errors {
1331 let _ = RetryPolicy::is_error_retryable(err);
1332 }
1333 });
1334 }
1335}