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
31const DEFAULT_RETRYABLE_METHODS: &[Method] = &[Method::GET, Method::HEAD, Method::OPTIONS];
33
34#[derive(Debug, Clone)]
54pub struct RetryPolicy {
55 max_attempts: usize,
57 max_elapsed: Option<Duration>,
59 backoff: BackoffPolicy,
61 method_policy: MethodPolicy,
63 status_policy: StatusPolicy,
65 respect_retry_after: bool,
67}
68
69impl Default for RetryPolicy {
70 fn default() -> Self {
71 Self {
72 max_attempts: 1,
73 max_elapsed: None,
74 backoff: BackoffPolicy::default(),
75 method_policy: MethodPolicy::default(),
76 status_policy: StatusPolicy::default(),
77 respect_retry_after: false,
78 }
79 }
80}
81
82impl RetryPolicy {
83 #[must_use]
85 pub fn builder() -> RetryPolicyBuilder {
86 RetryPolicyBuilder::new()
87 }
88
89 #[must_use]
91 pub fn max_attempts(&self) -> usize {
92 self.max_attempts
93 }
94
95 #[must_use]
97 pub fn max_elapsed(&self) -> Option<Duration> {
98 self.max_elapsed
99 }
100
101 #[must_use]
103 pub fn backoff(&self) -> &BackoffPolicy {
104 &self.backoff
105 }
106
107 #[must_use]
109 pub fn method_policy(&self) -> &MethodPolicy {
110 &self.method_policy
111 }
112
113 #[must_use]
115 pub fn status_policy(&self) -> &StatusPolicy {
116 &self.status_policy
117 }
118
119 #[must_use]
121 pub fn respect_retry_after(&self) -> bool {
122 self.respect_retry_after
123 }
124
125 #[must_use]
127 pub fn is_enabled(&self) -> bool {
128 self.max_attempts > 1
129 }
130
131 #[must_use]
133 pub fn is_method_retryable(&self, method: &Method) -> bool {
134 self.method_policy.is_retryable(method)
135 }
136
137 #[must_use]
139 pub fn is_status_retryable(&self, status: u16) -> bool {
140 self.status_policy.is_retryable(status)
141 }
142
143 #[must_use]
145 pub fn is_error_retryable(error: &Error) -> bool {
146 #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
147 if matches!(error, Error::HyperClient(_)) {
148 return true;
149 }
150 match error {
151 Error::Connect(_)
152 | Error::Io(_)
153 | Error::Hyper(_)
154 | Error::Timeout {
155 phase: crate::timeout::TimeoutPhase::Connect,
156 ..
157 }
158 | Error::Timeout {
159 phase: crate::timeout::TimeoutPhase::Pool,
160 ..
161 }
162 | Error::Timeout {
163 phase:
164 crate::timeout::TimeoutPhase::ProxyConnect | crate::timeout::TimeoutPhase::ProxyTls,
165 ..
166 }
167 | Error::H3Connect(_) => true,
168 Error::CustomTransport(error) => matches!(
169 error.kind(),
170 crate::transport::dialer::DialErrorKind::Connection
171 | crate::transport::dialer::DialErrorKind::Timeout
172 ),
173 Error::Http2StreamReset { reason } if reason.starts_with("REFUSED_STREAM") => true,
174 _ => false,
175 }
176 }
177
178 #[must_use]
182 pub fn backoff_delay(&self, attempt: usize) -> Option<Duration> {
183 self.backoff.delay(attempt)
184 }
185
186 #[must_use]
193 pub fn retry_after_delay(&self, retry_after: &str) -> Option<Duration> {
194 if !self.respect_retry_after {
195 return None;
196 }
197 let delay = if let Ok(secs) = retry_after.trim().parse::<u64>() {
198 Duration::from_secs(secs)
199 } else if let Ok(date) = httpdate::parse_http_date(retry_after.trim()) {
200 match date.duration_since(std::time::SystemTime::now()) {
201 Ok(duration) => duration,
202 Err(_) => return None,
203 }
204 } else {
205 return None;
206 };
207 let cap = self.backoff.max_delay;
208 Some(if delay > cap { cap } else { delay })
209 }
210
211 #[must_use]
216 pub fn check_body_replayable(body: &RequestBody) -> ReplayCheck {
217 if body.is_replayable() {
218 ReplayCheck::Replayable
219 } else {
220 ReplayCheck::NotReplayable
221 }
222 }
223}
224
225pub struct RetryPolicyBuilder {
227 max_attempts: usize,
228 max_elapsed: Option<Duration>,
229 backoff: BackoffPolicyBuilder,
230 method_policy: MethodPolicy,
231 status_policy: StatusPolicy,
232 respect_retry_after: bool,
233 custom_statuses_used: bool,
234}
235
236impl RetryPolicyBuilder {
237 #[must_use]
239 pub fn new() -> Self {
240 Self {
241 max_attempts: 1,
242 max_elapsed: None,
243 backoff: BackoffPolicyBuilder::new(),
244 method_policy: MethodPolicy::default(),
245 status_policy: StatusPolicy::default(),
246 respect_retry_after: false,
247 custom_statuses_used: false,
248 }
249 }
250
251 #[must_use]
255 pub fn max_attempts(mut self, max: usize) -> Self {
256 self.max_attempts = max;
257 self
258 }
259
260 #[must_use]
264 pub fn max_elapsed(mut self, elapsed: Duration) -> Self {
265 self.max_elapsed = Some(elapsed);
266 self
267 }
268
269 #[must_use]
275 pub fn backoff_factor(mut self, factor: f64) -> Self {
276 self.backoff = self.backoff.factor(factor);
277 self
278 }
279
280 #[must_use]
282 pub fn max_delay(mut self, delay: Duration) -> Self {
283 self.backoff = self.backoff.max_delay(delay);
284 self
285 }
286
287 #[must_use]
289 pub fn initial_delay(mut self, delay: Duration) -> Self {
290 self.backoff = self.backoff.initial_delay(delay);
291 self
292 }
293
294 #[must_use]
299 pub fn retry_status(mut self, status: u16) -> Self {
300 if !self.custom_statuses_used {
301 self.status_policy = StatusPolicy::default_empty();
302 self.custom_statuses_used = true;
303 }
304 self.status_policy.add_status(status);
305 self
306 }
307
308 #[must_use]
310 pub fn retry_statuses(mut self, statuses: impl IntoIterator<Item = u16>) -> Self {
311 self.status_policy = StatusPolicy::new(statuses);
312 self.custom_statuses_used = true;
313 self
314 }
315
316 #[must_use]
318 pub fn retry_method(mut self, method: Method) -> Self {
319 self.method_policy.add_method(method);
320 self
321 }
322
323 #[must_use]
325 pub fn allow_post_retry(mut self) -> Self {
326 self.method_policy.add_method(Method::POST);
327 self
328 }
329
330 #[must_use]
332 pub fn allow_put_retry(mut self) -> Self {
333 self.method_policy.add_method(Method::PUT);
334 self
335 }
336
337 #[must_use]
339 pub fn allow_delete_retry(mut self) -> Self {
340 self.method_policy.add_method(Method::DELETE);
341 self
342 }
343
344 #[must_use]
346 pub fn allow_patch_retry(mut self) -> Self {
347 self.method_policy.add_method(Method::PATCH);
348 self
349 }
350
351 #[must_use]
353 pub fn respect_retry_after(mut self, respect: bool) -> Self {
354 self.respect_retry_after = respect;
355 self
356 }
357
358 #[must_use]
360 pub fn build(self) -> RetryPolicy {
361 RetryPolicy {
362 max_attempts: self.max_attempts,
363 max_elapsed: self.max_elapsed,
364 backoff: self.backoff.build(),
365 method_policy: self.method_policy,
366 status_policy: self.status_policy,
367 respect_retry_after: self.respect_retry_after,
368 }
369 }
370}
371
372impl Default for RetryPolicyBuilder {
373 fn default() -> Self {
374 Self::new()
375 }
376}
377
378#[derive(Debug, Clone)]
380pub struct BackoffPolicy {
381 factor: f64,
383 max_delay: Duration,
385 initial_delay: Duration,
387}
388
389impl Default for BackoffPolicy {
390 fn default() -> Self {
391 Self {
392 factor: 2.0,
393 max_delay: Duration::from_secs(30),
394 initial_delay: Duration::from_millis(500),
395 }
396 }
397}
398
399impl BackoffPolicy {
400 #[must_use]
407 #[allow(clippy::cast_precision_loss)]
408 pub fn delay(&self, attempt: usize) -> Option<Duration> {
409 if attempt <= 1 {
410 return None;
411 }
412
413 let exp = (attempt - 2) as f64;
415 let raw = self.initial_delay.as_secs_f64() * self.factor.powf(exp);
416
417 let capped = if !raw.is_finite() || raw < 0.0 || raw > self.max_delay.as_secs_f64() {
421 self.max_delay
422 } else {
423 Duration::from_secs_f64(raw)
424 };
425
426 let jittered_secs = match get_random_f64() {
432 Some(jitter) => capped.as_secs_f64() * jitter,
433 None => capped.as_secs_f64(),
434 };
435
436 let final_delay = if !jittered_secs.is_finite() || jittered_secs < 0.0 {
437 capped
438 } else {
439 Duration::from_secs_f64(jittered_secs)
440 };
441
442 Some(final_delay.max(Duration::from_millis(1).min(capped)))
446 }
447
448 #[must_use]
450 pub fn max_delay(&self) -> Duration {
451 self.max_delay
452 }
453
454 #[must_use]
456 pub fn factor(&self) -> f64 {
457 self.factor
458 }
459
460 #[must_use]
462 pub fn initial_delay(&self) -> Duration {
463 self.initial_delay
464 }
465}
466
467pub struct BackoffPolicyBuilder {
469 factor: f64,
470 max_delay: Duration,
471 initial_delay: Duration,
472}
473
474impl BackoffPolicyBuilder {
475 #[must_use]
476 fn new() -> Self {
477 Self {
478 factor: 2.0,
479 max_delay: Duration::from_secs(30),
480 initial_delay: Duration::from_millis(500),
481 }
482 }
483
484 #[must_use]
485 fn factor(mut self, factor: f64) -> Self {
486 self.factor = factor;
490 self
491 }
492
493 #[must_use]
494 fn max_delay(mut self, delay: Duration) -> Self {
495 self.max_delay = delay;
496 self
497 }
498
499 #[must_use]
500 fn initial_delay(mut self, delay: Duration) -> Self {
501 self.initial_delay = delay;
502 self
503 }
504
505 #[must_use]
506 fn build(self) -> BackoffPolicy {
507 BackoffPolicy {
508 factor: self.factor,
509 max_delay: self.max_delay,
510 initial_delay: self.initial_delay,
511 }
512 }
513}
514
515#[derive(Debug, Clone)]
517pub struct MethodPolicy {
518 methods: Vec<Method>,
520}
521
522impl Default for MethodPolicy {
523 fn default() -> Self {
524 Self {
525 methods: DEFAULT_RETRYABLE_METHODS.to_vec(),
526 }
527 }
528}
529
530impl MethodPolicy {
531 #[must_use]
533 pub fn new(methods: Vec<Method>) -> Self {
534 Self { methods }
535 }
536
537 pub fn add_method(&mut self, method: Method) {
539 if !self.methods.contains(&method) {
540 self.methods.push(method);
541 }
542 }
543
544 #[must_use]
546 pub fn is_retryable(&self, method: &Method) -> bool {
547 self.methods.contains(method)
548 }
549
550 #[must_use]
552 pub fn methods(&self) -> &[Method] {
553 &self.methods
554 }
555}
556
557#[derive(Debug, Clone)]
559pub struct StatusPolicy {
560 statuses: Vec<u16>,
562}
563
564impl Default for StatusPolicy {
565 fn default() -> Self {
566 Self {
567 statuses: DEFAULT_RETRYABLE_STATUSES.to_vec(),
568 }
569 }
570}
571
572impl StatusPolicy {
573 #[must_use]
575 pub fn new(statuses: impl IntoIterator<Item = u16>) -> Self {
576 Self {
577 statuses: statuses.into_iter().collect(),
578 }
579 }
580
581 #[must_use]
583 pub fn default_empty() -> Self {
584 Self {
585 statuses: Vec::new(),
586 }
587 }
588
589 pub fn add_status(&mut self, status: u16) {
591 if !self.statuses.contains(&status) {
592 self.statuses.push(status);
593 }
594 }
595
596 #[must_use]
598 pub fn is_retryable(&self, status: u16) -> bool {
599 self.statuses.contains(&status)
600 }
601
602 #[must_use]
604 pub fn statuses(&self) -> &[u16] {
605 &self.statuses
606 }
607}
608
609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
611pub enum ReplayCheck {
612 Replayable,
614 NotReplayable,
616}
617
618#[derive(Debug, Clone, PartialEq, Eq)]
620pub enum RetryCause {
621 TransportError(String),
623 Status(u16),
625 Timeout(String),
627}
628
629impl std::fmt::Display for RetryCause {
630 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
631 match self {
632 Self::TransportError(msg) => write!(f, "transport error: {msg}"),
633 Self::Status(status) => write!(f, "retryable status: {status}"),
634 Self::Timeout(phase) => write!(f, "timeout: {phase}"),
635 }
636 }
637}
638
639#[derive(Debug, Clone)]
641pub struct RetryContext {
642 pub attempt: usize,
644 pub method: Method,
646 pub body_replayable: bool,
648 pub cause: RetryCause,
650 pub remaining_total: Option<Duration>,
652}
653
654#[must_use]
659pub fn should_retry(
660 policy: &RetryPolicy,
661 method: &Method,
662 body: &RequestBody,
663 error: Option<&Error>,
664 status: Option<u16>,
665) -> Option<RetryCause> {
666 if !policy.is_method_retryable(method) {
668 return None;
669 }
670
671 if !body.is_replayable() {
673 return None;
674 }
675
676 if let Some(err) = error {
678 if RetryPolicy::is_error_retryable(err) {
679 return Some(RetryCause::TransportError(err.to_string()));
680 }
681 return None;
682 }
683
684 if let Some(status) = status {
686 if policy.is_status_retryable(status) {
687 return Some(RetryCause::Status(status));
688 }
689 }
690
691 None
692}
693
694#[allow(clippy::cast_precision_loss)]
699fn get_random_f64() -> Option<f64> {
700 static STATE: OnceLock<Option<AtomicU64>> = OnceLock::new();
701
702 let state = STATE.get_or_init(|| {
703 let mut buf = [0u8; 8];
704 getrandom::getrandom(&mut buf)
705 .ok()
706 .map(|()| AtomicU64::new(u64::from_le_bytes(buf).max(1)))
707 });
708 let state = state.as_ref()?;
709 let val = state
710 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |mut value| {
711 value ^= value << 13;
712 value ^= value >> 7;
713 value ^= value << 17;
714 Some(value.max(1))
715 })
716 .ok()?;
717 Some(((val >> 11) as f64) / ((1u64 << 53) as f64))
721}
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726 use proptest::prelude::*;
727
728 #[test]
729 fn retry_policy_default_disables_retries() {
730 let policy = RetryPolicy::default();
731 assert!(!policy.is_enabled());
732 assert_eq!(policy.max_attempts(), 1);
733 }
734
735 #[test]
736 fn proxy_timeout_phases_are_retryable() {
737 for phase in [
738 crate::timeout::TimeoutPhase::ProxyConnect,
739 crate::timeout::TimeoutPhase::ProxyTls,
740 ] {
741 let error = Error::Timeout {
742 phase,
743 elapsed: Duration::from_secs(1),
744 };
745 assert!(RetryPolicy::is_error_retryable(&error));
746 }
747 }
748
749 #[test]
750 fn custom_dialer_connection_and_timeout_failures_are_retryable() {
751 for kind in [
752 crate::transport::dialer::DialErrorKind::Connection,
753 crate::transport::dialer::DialErrorKind::Timeout,
754 ] {
755 let error = Error::CustomTransport(std::sync::Arc::new(
756 crate::transport::dialer::DialError::new(kind, "route failed"),
757 ));
758 assert!(RetryPolicy::is_error_retryable(&error));
759 }
760 for kind in [
761 crate::transport::dialer::DialErrorKind::Authentication,
762 crate::transport::dialer::DialErrorKind::Rejected,
763 crate::transport::dialer::DialErrorKind::Other,
764 ] {
765 let error = Error::CustomTransport(std::sync::Arc::new(
766 crate::transport::dialer::DialError::new(kind, "route failed"),
767 ));
768 assert!(!RetryPolicy::is_error_retryable(&error));
769 }
770 }
771
772 #[test]
773 fn jitter_is_strictly_below_one() {
774 for _ in 0..10_000 {
777 let Some(jitter) = get_random_f64() else {
778 return;
782 };
783 assert!((0.0..1.0).contains(&jitter));
784 }
785 }
786
787 #[test]
788 fn retry_policy_builder_basic() {
789 let policy = RetryPolicy::builder()
790 .max_attempts(3)
791 .backoff_factor(0.2)
792 .build();
793 assert!(policy.is_enabled());
794 assert_eq!(policy.max_attempts(), 3);
795 }
796
797 #[test]
798 fn retry_policy_method_default_safe() {
799 let policy = RetryPolicy::default();
800 assert!(policy.is_method_retryable(&Method::GET));
801 assert!(policy.is_method_retryable(&Method::HEAD));
802 assert!(policy.is_method_retryable(&Method::OPTIONS));
803 assert!(!policy.is_method_retryable(&Method::POST));
804 assert!(!policy.is_method_retryable(&Method::PUT));
805 assert!(!policy.is_method_retryable(&Method::DELETE));
806 assert!(!policy.is_method_retryable(&Method::PATCH));
807 }
808
809 #[test]
810 fn retry_policy_method_allow_post() {
811 let policy = RetryPolicy::builder()
812 .max_attempts(3)
813 .allow_post_retry()
814 .build();
815 assert!(policy.is_method_retryable(&Method::POST));
816 }
817
818 #[test]
819 fn retry_policy_status_default() {
820 let policy = RetryPolicy::default();
821 assert!(policy.is_status_retryable(408));
822 assert!(policy.is_status_retryable(429));
823 assert!(policy.is_status_retryable(502));
824 assert!(policy.is_status_retryable(503));
825 assert!(policy.is_status_retryable(504));
826 assert!(!policy.is_status_retryable(200));
827 assert!(!policy.is_status_retryable(404));
828 }
829
830 #[test]
831 fn retry_policy_status_custom() {
832 let policy = RetryPolicy::builder()
833 .max_attempts(3)
834 .retry_status(429)
835 .retry_status(503)
836 .build();
837 assert!(policy.is_status_retryable(429));
838 assert!(policy.is_status_retryable(503));
839 assert!(!policy.is_status_retryable(408));
840 assert!(!policy.is_status_retryable(504));
841 }
842
843 #[test]
844 fn backoff_delay_none_for_first_attempt() {
845 let backoff = BackoffPolicy::default();
846 assert!(backoff.delay(1).is_none());
847 }
848
849 #[test]
850 fn backoff_delay_bounded_for_later_attempts() {
851 let backoff = BackoffPolicy {
852 factor: 0.5,
853 max_delay: Duration::from_secs(30),
854 initial_delay: Duration::from_millis(100),
855 };
856 let d2 = backoff.delay(2).unwrap();
858 assert!(d2 <= Duration::from_millis(100));
859
860 let d3 = backoff.delay(3).unwrap();
861 assert!(d3 <= Duration::from_millis(50));
862 }
863
864 #[test]
865 fn backoff_delay_has_minimum_when_cap_is_positive() {
866 let backoff = BackoffPolicy {
867 factor: 1.0,
868 max_delay: Duration::from_millis(1),
869 initial_delay: Duration::from_millis(1),
870 };
871 assert_eq!(backoff.delay(2), Some(Duration::from_millis(1)));
872 }
873
874 #[test]
875 fn default_backoff_grows_exponentially() {
876 let backoff = BackoffPolicy::default();
880 assert!((backoff.factor() - 2.0).abs() < f64::EPSILON);
881 assert!(backoff.delay(2).unwrap() <= Duration::from_millis(500));
882 assert!(backoff.delay(3).unwrap() <= Duration::from_secs(1));
883 assert!(backoff.delay(4).unwrap() <= Duration::from_secs(2));
884 }
885
886 #[test]
887 fn backoff_delay_capped_at_max() {
888 let backoff = BackoffPolicy {
889 factor: 2.0,
890 max_delay: Duration::from_secs(5),
891 initial_delay: Duration::from_secs(1),
892 };
893 let d = backoff.delay(10).unwrap();
894 assert!(d < Duration::from_secs(5)); }
896
897 #[test]
898 fn retry_after_disabled_by_default() {
899 let policy = RetryPolicy::default();
900 assert!(policy.retry_after_delay("5").is_none());
901 }
902
903 #[test]
904 fn retry_after_respected_when_enabled() {
905 let policy = RetryPolicy::builder()
906 .max_attempts(3)
907 .respect_retry_after(true)
908 .build();
909 let delay = policy.retry_after_delay("5").unwrap();
910 assert_eq!(delay, Duration::from_secs(5));
911 }
912
913 #[test]
914 fn retry_after_capped_at_max_delay() {
915 let policy = RetryPolicy::builder()
916 .max_attempts(3)
917 .respect_retry_after(true)
918 .max_delay(Duration::from_secs(10))
919 .build();
920 let delay = policy.retry_after_delay("60").unwrap();
921 assert_eq!(delay, Duration::from_secs(10));
922 }
923
924 #[test]
925 fn retry_after_invalid_ignored() {
926 let policy = RetryPolicy::builder()
927 .max_attempts(3)
928 .respect_retry_after(true)
929 .build();
930 assert!(policy.retry_after_delay("not-a-number").is_none());
931 }
932
933 #[test]
934 fn retry_after_http_date_parses() {
935 use std::time::UNIX_EPOCH;
936
937 let policy = RetryPolicy::builder()
938 .max_attempts(3)
939 .respect_retry_after(true)
940 .build();
941 let future_time = UNIX_EPOCH
944 + Duration::from_secs(
945 std::time::SystemTime::now()
946 .duration_since(UNIX_EPOCH)
947 .unwrap()
948 .as_secs()
949 + 3600,
950 ); let formatted = httpdate::fmt_http_date(future_time);
952 let parsed = httpdate::parse_http_date(&formatted);
953 assert!(parsed.is_ok(), "round-trip parse failed: {formatted}");
954 let delay = policy.retry_after_delay(&formatted);
955 assert!(
956 delay.is_some(),
957 "retry_after_delay returned None for HTTP-date: {formatted}"
958 );
959 let d = delay.unwrap();
960 assert!(d.as_secs() > 0, "delay should be positive");
961 }
962
963 #[test]
964 fn retry_after_past_http_date_is_ignored() {
965 use std::time::UNIX_EPOCH;
966
967 let policy = RetryPolicy::builder()
968 .max_attempts(3)
969 .respect_retry_after(true)
970 .build();
971 let past_time = UNIX_EPOCH
974 + Duration::from_secs(
975 std::time::SystemTime::now()
976 .duration_since(UNIX_EPOCH)
977 .unwrap()
978 .as_secs()
979 .saturating_sub(3600),
980 );
981 let formatted = httpdate::fmt_http_date(past_time);
982 assert!(policy.retry_after_delay(&formatted).is_none());
983 }
984
985 #[test]
986 fn body_replayable_empty() {
987 let body = RequestBody::Empty;
988 assert_eq!(
989 RetryPolicy::check_body_replayable(&body),
990 ReplayCheck::Replayable
991 );
992 }
993
994 #[test]
995 fn body_replayable_bytes() {
996 let body = RequestBody::from(bytes::Bytes::from("hello"));
997 assert_eq!(
998 RetryPolicy::check_body_replayable(&body),
999 ReplayCheck::Replayable
1000 );
1001 }
1002
1003 #[test]
1004 fn body_not_replayable_stream() {
1005 let body = RequestBody::from_stream(
1006 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1007 None,
1008 );
1009 assert_eq!(
1010 RetryPolicy::check_body_replayable(&body),
1011 ReplayCheck::NotReplayable
1012 );
1013 }
1014
1015 #[test]
1016 fn should_retry_get_with_retryable_status() {
1017 let policy = RetryPolicy::builder().max_attempts(3).build();
1018 let body = RequestBody::Empty;
1019 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1020 assert_eq!(cause, Some(RetryCause::Status(503)));
1021 }
1022
1023 #[test]
1024 fn should_not_retry_post_by_default() {
1025 let policy = RetryPolicy::builder().max_attempts(3).build();
1026 let body = RequestBody::Empty;
1027 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1028 assert_eq!(cause, None);
1029 }
1030
1031 #[test]
1032 fn should_retry_post_when_allowed() {
1033 let policy = RetryPolicy::builder()
1034 .max_attempts(3)
1035 .allow_post_retry()
1036 .build();
1037 let body = RequestBody::Empty;
1038 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1039 assert_eq!(cause, Some(RetryCause::Status(503)));
1040 }
1041
1042 #[test]
1043 fn should_not_retry_non_retryable_status() {
1044 let policy = RetryPolicy::builder().max_attempts(3).build();
1045 let body = RequestBody::Empty;
1046 let cause = should_retry(&policy, &Method::GET, &body, None, Some(200));
1047 assert_eq!(cause, None);
1048 }
1049
1050 #[test]
1051 fn should_not_retry_stream_body() {
1052 let policy = RetryPolicy::builder().max_attempts(3).build();
1053 let body = RequestBody::from_stream(
1054 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1055 None,
1056 );
1057 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1058 assert_eq!(cause, None);
1059 }
1060
1061 #[test]
1062 fn should_retry_connect_error() {
1063 let policy = RetryPolicy::builder().max_attempts(3).build();
1064 let body = RequestBody::Empty;
1065 let err = Error::Connect("connection refused".into());
1066 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1067 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1068 }
1069
1070 #[test]
1071 fn should_not_retry_invalid_url() {
1072 let policy = RetryPolicy::builder().max_attempts(3).build();
1073 let body = RequestBody::Empty;
1074 let err = Error::InvalidUrl("bad url".into());
1075 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1076 assert_eq!(cause, None);
1077 }
1078
1079 #[test]
1080 #[cfg(feature = "http3")]
1081 fn should_retry_h3_connect_error() {
1082 let policy = RetryPolicy::builder().max_attempts(3).build();
1083 let body = RequestBody::Empty;
1084 let err = Error::H3Connect("QUIC handshake failed".into());
1085 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1086 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1087 }
1088
1089 #[test]
1090 #[cfg(feature = "http3")]
1091 fn should_not_retry_h3_connection_closed() {
1092 let policy = RetryPolicy::builder().max_attempts(3).build();
1093 let body = RequestBody::Empty;
1094 let err = Error::H3ConnectionClosed("peer sent GOAWAY".into());
1095 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1096 assert_eq!(cause, None);
1097 }
1098
1099 #[test]
1100 #[cfg(feature = "http3")]
1101 fn should_not_retry_h3_protocol_error() {
1102 let policy = RetryPolicy::builder().max_attempts(3).build();
1103 let body = RequestBody::Empty;
1104 let err = Error::H3Protocol("unexpected frame".into());
1105 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1106 assert_eq!(cause, None);
1107 }
1108
1109 #[test]
1110 #[cfg(feature = "http3")]
1111 fn should_not_retry_h3_stream_error() {
1112 let policy = RetryPolicy::builder().max_attempts(3).build();
1113 let body = RequestBody::Empty;
1114 let err = Error::H3Stream("stream reset".into());
1115 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1116 assert_eq!(cause, None);
1117 }
1118
1119 #[test]
1120 fn retry_cause_display() {
1121 assert_eq!(
1122 RetryCause::TransportError("refused".into()).to_string(),
1123 "transport error: refused"
1124 );
1125 assert_eq!(RetryCause::Status(503).to_string(), "retryable status: 503");
1126 assert_eq!(
1127 RetryCause::Timeout("total".into()).to_string(),
1128 "timeout: total"
1129 );
1130 }
1131
1132 #[test]
1133 fn method_policy_add_method() {
1134 let mut policy = MethodPolicy::default();
1135 assert!(!policy.is_retryable(&Method::POST));
1136 policy.add_method(Method::POST);
1137 assert!(policy.is_retryable(&Method::POST));
1138 }
1139
1140 #[test]
1141 fn status_policy_add_status() {
1142 let mut policy = StatusPolicy::default();
1143 assert!(!policy.is_retryable(418));
1144 policy.add_status(418);
1145 assert!(policy.is_retryable(418));
1146 }
1147
1148 #[test]
1149 fn retry_policy_max_elapsed() {
1150 let policy = RetryPolicy::builder()
1151 .max_attempts(3)
1152 .max_elapsed(Duration::from_secs(10))
1153 .build();
1154 assert_eq!(policy.max_elapsed(), Some(Duration::from_secs(10)));
1155 }
1156
1157 #[test]
1158 fn retry_policy_display_cause() {
1159 let cause = RetryCause::Status(429);
1160 assert_eq!(format!("{cause}"), "retryable status: 429");
1161 }
1162
1163 #[test]
1164 fn prop_backoff_delay_some_for_attempt_gt_1() {
1165 proptest::proptest!(|(attempt in 2usize..100usize)| {
1166 let backoff = BackoffPolicy::default();
1167 prop_assert!(backoff.delay(attempt).is_some());
1168 });
1169 }
1170
1171 #[test]
1172 fn prop_backoff_delay_bounded_by_max_delay() {
1173 proptest::proptest!(|(
1174 factor in 0.1f64..2.0f64,
1175 initial_ms in 1u64..1000u64,
1176 max_secs in 1u64..60u64,
1177 attempt in 2usize..20usize,
1178 )| {
1179 let backoff = BackoffPolicy {
1180 factor,
1181 max_delay: Duration::from_secs(max_secs),
1182 initial_delay: Duration::from_millis(initial_ms),
1183 };
1184 if let Some(delay) = backoff.delay(attempt) {
1185 prop_assert!(delay <= Duration::from_secs(max_secs * 2));
1186 }
1187 });
1188 }
1189
1190 #[test]
1191 fn prop_method_policy_default_contains_get_head_options() {
1192 let policy = MethodPolicy::default();
1193 assert!(policy.is_retryable(&Method::GET));
1194 assert!(policy.is_retryable(&Method::HEAD));
1195 assert!(policy.is_retryable(&Method::OPTIONS));
1196 }
1197
1198 #[test]
1199 fn prop_status_policy_default_contains_expected() {
1200 let policy = StatusPolicy::default();
1201 assert!(policy.is_retryable(408));
1202 assert!(policy.is_retryable(429));
1203 assert!(policy.is_retryable(502));
1204 assert!(policy.is_retryable(503));
1205 assert!(policy.is_retryable(504));
1206 }
1207
1208 #[test]
1209 fn prop_retry_after_delay_returns_none_for_garbage() {
1210 proptest::proptest!(|(input in ".{0,100}")| {
1211 let policy = RetryPolicy::builder()
1212 .max_attempts(3)
1213 .respect_retry_after(true)
1214 .build();
1215 let _ = policy.retry_after_delay(&input);
1216 });
1217 }
1218
1219 #[test]
1220 fn regression_fuzz_retry_crash_extreme_backoff_factor() {
1221 let backoff = BackoffPolicy {
1222 factor: 22.0,
1223 max_delay: Duration::from_secs(30),
1224 initial_delay: Duration::from_millis(500),
1225 };
1226 for attempt in 2..=20 {
1227 let delay = backoff.delay(attempt);
1228 assert!(delay.is_some());
1229 assert!(delay.unwrap() <= backoff.max_delay);
1230 }
1231 }
1232
1233 #[test]
1234 fn backoff_delay_nan_factor_returns_bounded_delay() {
1235 let backoff = BackoffPolicy {
1236 factor: f64::NAN,
1237 max_delay: Duration::from_secs(30),
1238 initial_delay: Duration::from_millis(500),
1239 };
1240 let d = backoff.delay(5).unwrap();
1241 assert!(d <= Duration::from_secs(30));
1242 }
1243
1244 #[test]
1245 fn backoff_delay_infinite_factor_returns_bounded_delay() {
1246 let backoff = BackoffPolicy {
1247 factor: f64::INFINITY,
1248 max_delay: Duration::from_secs(30),
1249 initial_delay: Duration::from_millis(500),
1250 };
1251 let d = backoff.delay(5).unwrap();
1252 assert!(d <= Duration::from_secs(30));
1253 }
1254
1255 #[test]
1256 fn prop_is_error_retryable_never_panics() {
1257 proptest::proptest!(|(msg in ".{0,200}")| {
1258 let errors = vec![
1259 Error::Connect(msg.clone()),
1260 Error::Io(std::sync::Arc::new(std::io::Error::other(msg.clone()))),
1261 Error::InvalidUrl(msg.clone()),
1262 Error::Tls(msg.clone()),
1263 Error::Protocol(msg.clone()),
1264 Error::Body(msg.clone()),
1265 ];
1266 for err in &errors {
1267 let _ = RetryPolicy::is_error_retryable(err);
1268 }
1269 });
1270 }
1271}