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<AtomicU64> = OnceLock::new();
704
705 let state = if let Some(state) = STATE.get() {
706 state
707 } else {
708 let mut buf = [0u8; 8];
709 let seed = u64::from_le_bytes({
710 getrandom::getrandom(&mut buf).ok()?;
711 buf
712 })
713 .max(1);
714 let _ = STATE.set(AtomicU64::new(seed));
715 STATE.get()?
716 };
717 let val = state
718 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |mut value| {
719 value ^= value << 13;
720 value ^= value >> 7;
721 value ^= value << 17;
722 Some(value.max(1))
723 })
724 .ok()?;
725 Some(((val >> 11) as f64) / ((1u64 << 53) as f64))
729}
730
731#[cfg(test)]
732mod tests {
733 use super::*;
734 use proptest::prelude::*;
735
736 #[test]
737 fn retry_policy_default_disables_retries() {
738 let policy = RetryPolicy::default();
739 assert!(!policy.is_enabled());
740 assert_eq!(policy.max_attempts(), 1);
741 }
742
743 #[test]
744 fn proxy_timeout_phases_are_retryable() {
745 for phase in [
746 crate::timeout::TimeoutPhase::ProxyConnect,
747 crate::timeout::TimeoutPhase::ProxyTls,
748 ] {
749 let error = Error::Timeout {
750 phase,
751 elapsed: Duration::from_secs(1),
752 };
753 assert!(RetryPolicy::is_error_retryable(&error));
754 }
755 }
756
757 #[test]
758 fn custom_dialer_connection_and_timeout_failures_are_retryable() {
759 for kind in [
760 crate::transport::dialer::DialErrorKind::Connection,
761 crate::transport::dialer::DialErrorKind::Timeout,
762 ] {
763 let error = Error::CustomTransport(std::sync::Arc::new(
764 crate::transport::dialer::DialError::new(kind, "route failed"),
765 ));
766 assert!(RetryPolicy::is_error_retryable(&error));
767 }
768 for kind in [
769 crate::transport::dialer::DialErrorKind::Authentication,
770 crate::transport::dialer::DialErrorKind::Rejected,
771 crate::transport::dialer::DialErrorKind::Other,
772 ] {
773 let error = Error::CustomTransport(std::sync::Arc::new(
774 crate::transport::dialer::DialError::new(kind, "route failed"),
775 ));
776 assert!(!RetryPolicy::is_error_retryable(&error));
777 }
778 }
779
780 #[test]
781 fn jitter_is_strictly_below_one() {
782 for _ in 0..10_000 {
785 let Some(jitter) = get_random_f64() else {
786 return;
790 };
791 assert!((0.0..1.0).contains(&jitter));
792 }
793 }
794
795 #[test]
796 fn retry_policy_builder_basic() {
797 let policy = RetryPolicy::builder()
798 .max_attempts(3)
799 .backoff_factor(0.2)
800 .build();
801 assert!(policy.is_enabled());
802 assert_eq!(policy.max_attempts(), 3);
803 }
804
805 #[test]
806 fn retry_policy_method_default_safe() {
807 let policy = RetryPolicy::default();
808 assert!(policy.is_method_retryable(&Method::GET));
809 assert!(policy.is_method_retryable(&Method::HEAD));
810 assert!(policy.is_method_retryable(&Method::OPTIONS));
811 assert!(!policy.is_method_retryable(&Method::POST));
812 assert!(!policy.is_method_retryable(&Method::PUT));
813 assert!(!policy.is_method_retryable(&Method::DELETE));
814 assert!(!policy.is_method_retryable(&Method::PATCH));
815 }
816
817 #[test]
818 fn retry_policy_method_allow_post() {
819 let policy = RetryPolicy::builder()
820 .max_attempts(3)
821 .allow_post_retry()
822 .build();
823 assert!(policy.is_method_retryable(&Method::POST));
824 }
825
826 #[test]
827 fn retry_policy_status_default() {
828 let policy = RetryPolicy::default();
829 assert!(policy.is_status_retryable(408));
830 assert!(policy.is_status_retryable(429));
831 assert!(policy.is_status_retryable(502));
832 assert!(policy.is_status_retryable(503));
833 assert!(policy.is_status_retryable(504));
834 assert!(!policy.is_status_retryable(200));
835 assert!(!policy.is_status_retryable(404));
836 }
837
838 #[test]
839 fn retry_policy_status_custom() {
840 let policy = RetryPolicy::builder()
841 .max_attempts(3)
842 .retry_status(429)
843 .retry_status(503)
844 .build();
845 assert!(policy.is_status_retryable(429));
846 assert!(policy.is_status_retryable(503));
847 assert!(!policy.is_status_retryable(408));
848 assert!(!policy.is_status_retryable(504));
849 }
850
851 #[test]
852 fn backoff_delay_none_for_first_attempt() {
853 let backoff = BackoffPolicy::default();
854 assert!(backoff.delay(1).is_none());
855 }
856
857 #[test]
858 fn backoff_delay_bounded_for_later_attempts() {
859 let backoff = BackoffPolicy {
860 factor: 0.5,
861 max_delay: Duration::from_secs(30),
862 initial_delay: Duration::from_millis(100),
863 };
864 let d2 = backoff.delay(2).unwrap();
866 assert!(d2 <= Duration::from_millis(100));
867
868 let d3 = backoff.delay(3).unwrap();
869 assert!(d3 <= Duration::from_millis(50));
870 }
871
872 #[test]
873 fn backoff_delay_has_minimum_when_cap_is_positive() {
874 let backoff = BackoffPolicy {
875 factor: 1.0,
876 max_delay: Duration::from_millis(1),
877 initial_delay: Duration::from_millis(1),
878 };
879 assert_eq!(backoff.delay(2), Some(Duration::from_millis(1)));
880 }
881
882 #[test]
883 fn default_backoff_grows_exponentially() {
884 let backoff = BackoffPolicy::default();
888 assert!((backoff.factor() - 2.0).abs() < f64::EPSILON);
889 assert!(backoff.delay(2).unwrap() <= Duration::from_millis(500));
890 assert!(backoff.delay(3).unwrap() <= Duration::from_secs(1));
891 assert!(backoff.delay(4).unwrap() <= Duration::from_secs(2));
892 }
893
894 #[test]
895 fn backoff_delay_capped_at_max() {
896 let backoff = BackoffPolicy {
897 factor: 2.0,
898 max_delay: Duration::from_secs(5),
899 initial_delay: Duration::from_secs(1),
900 };
901 let d = backoff.delay(10).unwrap();
902 assert!(d < Duration::from_secs(5)); }
904
905 #[test]
906 fn retry_after_disabled_by_default() {
907 let policy = RetryPolicy::default();
908 assert!(policy.retry_after_delay("5").is_none());
909 }
910
911 #[test]
912 fn retry_after_respected_when_enabled() {
913 let policy = RetryPolicy::builder()
914 .max_attempts(3)
915 .respect_retry_after(true)
916 .build();
917 let delay = policy.retry_after_delay("5").unwrap();
918 assert_eq!(delay, Duration::from_secs(5));
919 }
920
921 #[test]
922 fn retry_after_capped_at_max_delay() {
923 let policy = RetryPolicy::builder()
924 .max_attempts(3)
925 .respect_retry_after(true)
926 .max_delay(Duration::from_secs(10))
927 .build();
928 let delay = policy.retry_after_delay("60").unwrap();
929 assert_eq!(delay, Duration::from_secs(10));
930 }
931
932 #[test]
933 fn retry_after_invalid_ignored() {
934 let policy = RetryPolicy::builder()
935 .max_attempts(3)
936 .respect_retry_after(true)
937 .build();
938 assert!(policy.retry_after_delay("not-a-number").is_none());
939 }
940
941 #[test]
942 fn retry_after_http_date_parses() {
943 use std::time::UNIX_EPOCH;
944
945 let policy = RetryPolicy::builder()
946 .max_attempts(3)
947 .respect_retry_after(true)
948 .build();
949 let future_time = UNIX_EPOCH
952 + Duration::from_secs(
953 std::time::SystemTime::now()
954 .duration_since(UNIX_EPOCH)
955 .unwrap()
956 .as_secs()
957 + 3600,
958 ); let formatted = httpdate::fmt_http_date(future_time);
960 let parsed = httpdate::parse_http_date(&formatted);
961 assert!(parsed.is_ok(), "round-trip parse failed: {formatted}");
962 let delay = policy.retry_after_delay(&formatted);
963 assert!(
964 delay.is_some(),
965 "retry_after_delay returned None for HTTP-date: {formatted}"
966 );
967 let d = delay.unwrap();
968 assert!(d.as_secs() > 0, "delay should be positive");
969 }
970
971 #[test]
972 fn retry_after_past_http_date_is_ignored() {
973 use std::time::UNIX_EPOCH;
974
975 let policy = RetryPolicy::builder()
976 .max_attempts(3)
977 .respect_retry_after(true)
978 .build();
979 let past_time = UNIX_EPOCH
982 + Duration::from_secs(
983 std::time::SystemTime::now()
984 .duration_since(UNIX_EPOCH)
985 .unwrap()
986 .as_secs()
987 .saturating_sub(3600),
988 );
989 let formatted = httpdate::fmt_http_date(past_time);
990 assert!(policy.retry_after_delay(&formatted).is_none());
991 }
992
993 #[test]
994 fn body_replayable_empty() {
995 let body = RequestBody::Empty;
996 assert_eq!(
997 RetryPolicy::check_body_replayable(&body),
998 ReplayCheck::Replayable
999 );
1000 }
1001
1002 #[test]
1003 fn body_replayable_bytes() {
1004 let body = RequestBody::from(bytes::Bytes::from("hello"));
1005 assert_eq!(
1006 RetryPolicy::check_body_replayable(&body),
1007 ReplayCheck::Replayable
1008 );
1009 }
1010
1011 #[test]
1012 fn body_not_replayable_stream() {
1013 let body = RequestBody::from_stream(
1014 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1015 None,
1016 );
1017 assert_eq!(
1018 RetryPolicy::check_body_replayable(&body),
1019 ReplayCheck::NotReplayable
1020 );
1021 }
1022
1023 #[test]
1024 fn should_retry_get_with_retryable_status() {
1025 let policy = RetryPolicy::builder().max_attempts(3).build();
1026 let body = RequestBody::Empty;
1027 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1028 assert_eq!(cause, Some(RetryCause::Status(503)));
1029 }
1030
1031 #[test]
1032 fn should_not_retry_post_by_default() {
1033 let policy = RetryPolicy::builder().max_attempts(3).build();
1034 let body = RequestBody::Empty;
1035 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1036 assert_eq!(cause, None);
1037 }
1038
1039 #[test]
1040 fn should_retry_post_when_allowed() {
1041 let policy = RetryPolicy::builder()
1042 .max_attempts(3)
1043 .allow_post_retry()
1044 .build();
1045 let body = RequestBody::Empty;
1046 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1047 assert_eq!(cause, Some(RetryCause::Status(503)));
1048 }
1049
1050 #[test]
1051 fn should_not_retry_non_retryable_status() {
1052 let policy = RetryPolicy::builder().max_attempts(3).build();
1053 let body = RequestBody::Empty;
1054 let cause = should_retry(&policy, &Method::GET, &body, None, Some(200));
1055 assert_eq!(cause, None);
1056 }
1057
1058 #[test]
1059 fn should_not_retry_stream_body() {
1060 let policy = RetryPolicy::builder().max_attempts(3).build();
1061 let body = RequestBody::from_stream(
1062 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1063 None,
1064 );
1065 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1066 assert_eq!(cause, None);
1067 }
1068
1069 #[test]
1070 fn should_retry_connect_error() {
1071 let policy = RetryPolicy::builder().max_attempts(3).build();
1072 let body = RequestBody::Empty;
1073 let err = Error::Connect("connection refused".into());
1074 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1075 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1076 }
1077
1078 #[test]
1079 fn should_not_retry_invalid_url() {
1080 let policy = RetryPolicy::builder().max_attempts(3).build();
1081 let body = RequestBody::Empty;
1082 let err = Error::InvalidUrl("bad url".into());
1083 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1084 assert_eq!(cause, None);
1085 }
1086
1087 #[test]
1088 #[cfg(feature = "http3")]
1089 fn should_retry_h3_connect_error() {
1090 let policy = RetryPolicy::builder().max_attempts(3).build();
1091 let body = RequestBody::Empty;
1092 let err = Error::H3Connect("QUIC handshake failed".into());
1093 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1094 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1095 }
1096
1097 #[test]
1098 #[cfg(feature = "http3")]
1099 fn should_not_retry_h3_connection_closed() {
1100 let policy = RetryPolicy::builder().max_attempts(3).build();
1101 let body = RequestBody::Empty;
1102 let err = Error::H3ConnectionClosed("peer sent GOAWAY".into());
1103 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1104 assert_eq!(cause, None);
1105 }
1106
1107 #[test]
1108 #[cfg(feature = "http3")]
1109 fn should_not_retry_h3_protocol_error() {
1110 let policy = RetryPolicy::builder().max_attempts(3).build();
1111 let body = RequestBody::Empty;
1112 let err = Error::H3Protocol("unexpected frame".into());
1113 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1114 assert_eq!(cause, None);
1115 }
1116
1117 #[test]
1118 #[cfg(feature = "http3")]
1119 fn should_not_retry_h3_stream_error() {
1120 let policy = RetryPolicy::builder().max_attempts(3).build();
1121 let body = RequestBody::Empty;
1122 let err = Error::H3Stream("stream reset".into());
1123 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1124 assert_eq!(cause, None);
1125 }
1126
1127 #[test]
1128 fn retry_cause_display() {
1129 assert_eq!(
1130 RetryCause::TransportError("refused".into()).to_string(),
1131 "transport error: refused"
1132 );
1133 assert_eq!(RetryCause::Status(503).to_string(), "retryable status: 503");
1134 assert_eq!(
1135 RetryCause::Timeout("total".into()).to_string(),
1136 "timeout: total"
1137 );
1138 }
1139
1140 #[test]
1141 fn method_policy_add_method() {
1142 let mut policy = MethodPolicy::default();
1143 assert!(!policy.is_retryable(&Method::POST));
1144 policy.add_method(Method::POST);
1145 assert!(policy.is_retryable(&Method::POST));
1146 }
1147
1148 #[test]
1149 fn status_policy_add_status() {
1150 let mut policy = StatusPolicy::default();
1151 assert!(!policy.is_retryable(418));
1152 policy.add_status(418);
1153 assert!(policy.is_retryable(418));
1154 }
1155
1156 #[test]
1157 fn retry_policy_max_elapsed() {
1158 let policy = RetryPolicy::builder()
1159 .max_attempts(3)
1160 .max_elapsed(Duration::from_secs(10))
1161 .build();
1162 assert_eq!(policy.max_elapsed(), Some(Duration::from_secs(10)));
1163 }
1164
1165 #[test]
1166 fn retry_policy_display_cause() {
1167 let cause = RetryCause::Status(429);
1168 assert_eq!(format!("{cause}"), "retryable status: 429");
1169 }
1170
1171 #[test]
1172 fn prop_backoff_delay_some_for_attempt_gt_1() {
1173 proptest::proptest!(|(attempt in 2usize..100usize)| {
1174 let backoff = BackoffPolicy::default();
1175 prop_assert!(backoff.delay(attempt).is_some());
1176 });
1177 }
1178
1179 #[test]
1180 fn prop_backoff_delay_bounded_by_max_delay() {
1181 proptest::proptest!(|(
1182 factor in 0.1f64..2.0f64,
1183 initial_ms in 1u64..1000u64,
1184 max_secs in 1u64..60u64,
1185 attempt in 2usize..20usize,
1186 )| {
1187 let backoff = BackoffPolicy {
1188 factor,
1189 max_delay: Duration::from_secs(max_secs),
1190 initial_delay: Duration::from_millis(initial_ms),
1191 };
1192 if let Some(delay) = backoff.delay(attempt) {
1193 prop_assert!(delay <= Duration::from_secs(max_secs * 2));
1194 }
1195 });
1196 }
1197
1198 #[test]
1199 fn prop_method_policy_default_contains_get_head_options() {
1200 let policy = MethodPolicy::default();
1201 assert!(policy.is_retryable(&Method::GET));
1202 assert!(policy.is_retryable(&Method::HEAD));
1203 assert!(policy.is_retryable(&Method::OPTIONS));
1204 }
1205
1206 #[test]
1207 fn prop_status_policy_default_contains_expected() {
1208 let policy = StatusPolicy::default();
1209 assert!(policy.is_retryable(408));
1210 assert!(policy.is_retryable(429));
1211 assert!(policy.is_retryable(502));
1212 assert!(policy.is_retryable(503));
1213 assert!(policy.is_retryable(504));
1214 }
1215
1216 #[test]
1217 fn prop_retry_after_delay_returns_none_for_garbage() {
1218 proptest::proptest!(|(input in ".{0,100}")| {
1219 let policy = RetryPolicy::builder()
1220 .max_attempts(3)
1221 .respect_retry_after(true)
1222 .build();
1223 let _ = policy.retry_after_delay(&input);
1224 });
1225 }
1226
1227 #[test]
1228 fn regression_fuzz_retry_crash_extreme_backoff_factor() {
1229 let backoff = BackoffPolicy {
1230 factor: 22.0,
1231 max_delay: Duration::from_secs(30),
1232 initial_delay: Duration::from_millis(500),
1233 };
1234 for attempt in 2..=20 {
1235 let delay = backoff.delay(attempt);
1236 assert!(delay.is_some());
1237 assert!(delay.unwrap() <= backoff.max_delay);
1238 }
1239 }
1240
1241 #[test]
1242 fn backoff_delay_nan_factor_returns_bounded_delay() {
1243 let backoff = BackoffPolicy {
1244 factor: f64::NAN,
1245 max_delay: Duration::from_secs(30),
1246 initial_delay: Duration::from_millis(500),
1247 };
1248 let d = backoff.delay(5).unwrap();
1249 assert!(d <= Duration::from_secs(30));
1250 }
1251
1252 #[test]
1253 fn backoff_delay_infinite_factor_returns_bounded_delay() {
1254 let backoff = BackoffPolicy {
1255 factor: f64::INFINITY,
1256 max_delay: Duration::from_secs(30),
1257 initial_delay: Duration::from_millis(500),
1258 };
1259 let d = backoff.delay(5).unwrap();
1260 assert!(d <= Duration::from_secs(30));
1261 }
1262
1263 #[test]
1264 fn prop_is_error_retryable_never_panics() {
1265 proptest::proptest!(|(msg in ".{0,200}")| {
1266 let errors = vec![
1267 Error::Connect(msg.clone()),
1268 Error::Io(std::sync::Arc::new(std::io::Error::other(msg.clone()))),
1269 Error::InvalidUrl(msg.clone()),
1270 Error::Tls(msg.clone()),
1271 Error::Protocol(msg.clone()),
1272 Error::Body(msg.clone()),
1273 ];
1274 for err in &errors {
1275 let _ = RetryPolicy::is_error_retryable(err);
1276 }
1277 });
1278 }
1279}