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(clippy::cast_precision_loss)]
427 pub fn delay(&self, attempt: usize) -> Option<Duration> {
428 if attempt <= 1 {
429 return None;
430 }
431
432 let exp = (attempt - 2) as f64;
434 let raw = self.initial_delay.as_secs_f64() * self.factor.powf(exp);
435 let max_float = self.max_delay.as_secs_f64();
439 let max_secs = if Duration::try_from_secs_f64(max_float).is_ok() {
440 max_float
441 } else {
442 f64::MAX
443 };
444
445 let capped = if !raw.is_finite() || raw < 0.0 || raw > max_secs {
451 self.max_delay
452 } else {
453 Duration::try_from_secs_f64(raw).unwrap_or(self.max_delay)
454 };
455
456 let jittered_secs = match get_random_f64() {
462 Some(jitter) => capped.as_secs_f64() * jitter,
463 None => capped.as_secs_f64(),
464 };
465
466 let final_delay = if !jittered_secs.is_finite() || jittered_secs < 0.0 {
467 capped
468 } else {
469 Duration::try_from_secs_f64(jittered_secs).unwrap_or(capped)
472 };
473
474 Some(final_delay.max(Duration::from_millis(1).min(capped)))
478 }
479
480 #[must_use]
482 pub fn max_delay(&self) -> Duration {
483 self.max_delay
484 }
485
486 #[must_use]
488 pub fn factor(&self) -> f64 {
489 self.factor
490 }
491
492 #[must_use]
494 pub fn initial_delay(&self) -> Duration {
495 self.initial_delay
496 }
497}
498
499pub struct BackoffPolicyBuilder {
501 factor: f64,
502 max_delay: Duration,
503 initial_delay: Duration,
504}
505
506impl BackoffPolicyBuilder {
507 #[must_use]
508 fn new() -> Self {
509 Self {
510 factor: 2.0,
511 max_delay: Duration::from_secs(30),
512 initial_delay: Duration::from_millis(500),
513 }
514 }
515
516 #[must_use]
517 fn factor(mut self, factor: f64) -> Self {
518 self.factor = factor;
522 self
523 }
524
525 #[must_use]
526 fn max_delay(mut self, delay: Duration) -> Self {
527 self.max_delay = delay;
528 self
529 }
530
531 #[must_use]
532 fn initial_delay(mut self, delay: Duration) -> Self {
533 self.initial_delay = delay;
534 self
535 }
536
537 #[must_use]
538 fn build(self) -> BackoffPolicy {
539 BackoffPolicy {
540 factor: self.factor,
541 max_delay: self.max_delay,
542 initial_delay: self.initial_delay,
543 }
544 }
545}
546
547#[derive(Debug, Clone)]
549pub struct MethodPolicy {
550 methods: Vec<Method>,
552}
553
554impl Default for MethodPolicy {
555 fn default() -> Self {
556 Self {
557 methods: DEFAULT_RETRYABLE_METHODS.to_vec(),
558 }
559 }
560}
561
562impl MethodPolicy {
563 #[must_use]
565 pub fn new(methods: Vec<Method>) -> Self {
566 Self { methods }
567 }
568
569 pub fn add_method(&mut self, method: Method) {
571 if !self.methods.contains(&method) {
572 self.methods.push(method);
573 }
574 }
575
576 #[must_use]
578 pub fn is_retryable(&self, method: &Method) -> bool {
579 self.methods.contains(method)
580 }
581
582 #[must_use]
584 pub fn methods(&self) -> &[Method] {
585 &self.methods
586 }
587}
588
589#[derive(Debug, Clone)]
591pub struct StatusPolicy {
592 statuses: Vec<u16>,
594}
595
596impl Default for StatusPolicy {
597 fn default() -> Self {
598 Self {
599 statuses: DEFAULT_RETRYABLE_STATUSES.to_vec(),
600 }
601 }
602}
603
604impl StatusPolicy {
605 #[must_use]
607 pub fn new(statuses: impl IntoIterator<Item = u16>) -> Self {
608 Self {
609 statuses: statuses.into_iter().collect(),
610 }
611 }
612
613 #[must_use]
615 pub fn default_empty() -> Self {
616 Self {
617 statuses: Vec::new(),
618 }
619 }
620
621 pub fn add_status(&mut self, status: u16) {
623 if !self.statuses.contains(&status) {
624 self.statuses.push(status);
625 }
626 }
627
628 #[must_use]
630 pub fn is_retryable(&self, status: u16) -> bool {
631 self.statuses.contains(&status)
632 }
633
634 #[must_use]
636 pub fn statuses(&self) -> &[u16] {
637 &self.statuses
638 }
639}
640
641#[derive(Debug, Clone, Copy, PartialEq, Eq)]
643pub enum ReplayCheck {
644 Replayable,
646 NotReplayable,
648}
649
650#[derive(Debug, Clone, PartialEq, Eq)]
652pub enum RetryCause {
653 TransportError(String),
655 Status(u16),
657 Timeout(String),
659}
660
661impl std::fmt::Display for RetryCause {
662 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
663 match self {
664 Self::TransportError(msg) => write!(f, "transport error: {msg}"),
665 Self::Status(status) => write!(f, "retryable status: {status}"),
666 Self::Timeout(phase) => write!(f, "timeout: {phase}"),
667 }
668 }
669}
670
671#[derive(Debug, Clone)]
673pub struct RetryContext {
674 pub attempt: usize,
676 pub method: Method,
678 pub body_replayable: bool,
680 pub cause: RetryCause,
682 pub remaining_total: Option<Duration>,
684}
685
686#[must_use]
691pub fn should_retry(
692 policy: &RetryPolicy,
693 method: &Method,
694 body: &RequestBody,
695 error: Option<&Error>,
696 status: Option<u16>,
697) -> Option<RetryCause> {
698 if !policy.is_method_retryable(method) {
700 return None;
701 }
702
703 if !body.is_replayable() {
705 return None;
706 }
707
708 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 {
718 if policy.is_status_retryable(status) {
719 return Some(RetryCause::Status(status));
720 }
721 }
722
723 None
724}
725
726#[allow(clippy::cast_precision_loss)]
731fn get_random_f64() -> Option<f64> {
732 static STATE: OnceLock<AtomicU64> = OnceLock::new();
736
737 let state = if let Some(state) = STATE.get() {
738 state
739 } else {
740 let mut buf = [0u8; 8];
741 let seed = u64::from_le_bytes({
742 getrandom::getrandom(&mut buf).ok()?;
743 buf
744 })
745 .max(1);
746 let _ = STATE.set(AtomicU64::new(seed));
747 STATE.get()?
748 };
749 #[allow(deprecated)]
753 let val = state
754 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |mut value| {
755 value ^= value << 13;
756 value ^= value >> 7;
757 value ^= value << 17;
758 Some(value.max(1))
759 })
760 .ok()?;
761 Some(((val >> 11) as f64) / ((1u64 << 53) as f64))
765}
766
767#[cfg(test)]
768mod tests {
769 use super::*;
770 use proptest::prelude::*;
771
772 #[test]
773 fn retry_policy_default_disables_retries() {
774 let policy = RetryPolicy::default();
775 assert!(!policy.is_enabled());
776 assert_eq!(policy.max_attempts(), 1);
777 }
778
779 #[test]
780 fn proxy_timeout_phases_are_retryable() {
781 for phase in [
782 crate::timeout::TimeoutPhase::ProxyConnect,
783 crate::timeout::TimeoutPhase::ProxyTls,
784 ] {
785 let error = Error::Timeout {
786 phase,
787 elapsed: Duration::from_secs(1),
788 };
789 assert!(RetryPolicy::is_error_retryable(&error));
790 }
791 }
792
793 #[test]
794 fn custom_dialer_connection_and_timeout_failures_are_retryable() {
795 for kind in [
796 crate::transport::dialer::DialErrorKind::Connection,
797 crate::transport::dialer::DialErrorKind::Timeout,
798 ] {
799 let error = Error::CustomTransport(std::sync::Arc::new(
800 crate::transport::dialer::DialError::new(kind, "route failed"),
801 ));
802 assert!(RetryPolicy::is_error_retryable(&error));
803 }
804 for kind in [
805 crate::transport::dialer::DialErrorKind::Authentication,
806 crate::transport::dialer::DialErrorKind::Rejected,
807 crate::transport::dialer::DialErrorKind::Other,
808 ] {
809 let error = Error::CustomTransport(std::sync::Arc::new(
810 crate::transport::dialer::DialError::new(kind, "route failed"),
811 ));
812 assert!(!RetryPolicy::is_error_retryable(&error));
813 }
814 }
815
816 #[test]
817 fn jitter_is_strictly_below_one() {
818 for _ in 0..10_000 {
821 let Some(jitter) = get_random_f64() else {
822 return;
826 };
827 assert!((0.0..1.0).contains(&jitter));
828 }
829 }
830
831 #[test]
832 fn retry_policy_builder_basic() {
833 let policy = RetryPolicy::builder()
834 .max_attempts(3)
835 .backoff_factor(0.2)
836 .build();
837 assert!(policy.is_enabled());
838 assert_eq!(policy.max_attempts(), 3);
839 }
840
841 #[test]
842 fn retry_policy_method_default_safe() {
843 let policy = RetryPolicy::default();
844 assert!(policy.is_method_retryable(&Method::GET));
845 assert!(policy.is_method_retryable(&Method::HEAD));
846 assert!(policy.is_method_retryable(&Method::OPTIONS));
847 assert!(!policy.is_method_retryable(&Method::POST));
848 assert!(!policy.is_method_retryable(&Method::PUT));
849 assert!(!policy.is_method_retryable(&Method::DELETE));
850 assert!(!policy.is_method_retryable(&Method::PATCH));
851 }
852
853 #[test]
854 fn retry_policy_method_allow_post() {
855 let policy = RetryPolicy::builder()
856 .max_attempts(3)
857 .allow_post_retry()
858 .build();
859 assert!(policy.is_method_retryable(&Method::POST));
860 }
861
862 #[test]
863 fn retry_policy_status_default() {
864 let policy = RetryPolicy::default();
865 assert!(policy.is_status_retryable(408));
866 assert!(policy.is_status_retryable(429));
867 assert!(policy.is_status_retryable(502));
868 assert!(policy.is_status_retryable(503));
869 assert!(policy.is_status_retryable(504));
870 assert!(!policy.is_status_retryable(200));
871 assert!(!policy.is_status_retryable(404));
872 }
873
874 #[test]
875 fn retry_policy_status_custom() {
876 let policy = RetryPolicy::builder()
877 .max_attempts(3)
878 .retry_status(429)
879 .retry_status(503)
880 .build();
881 assert!(policy.is_status_retryable(429));
882 assert!(policy.is_status_retryable(503));
883 assert!(!policy.is_status_retryable(408));
884 assert!(!policy.is_status_retryable(504));
885 }
886
887 #[test]
888 fn backoff_delay_none_for_first_attempt() {
889 let backoff = BackoffPolicy::default();
890 assert!(backoff.delay(1).is_none());
891 }
892
893 #[test]
894 fn backoff_delay_bounded_for_later_attempts() {
895 let backoff = BackoffPolicy {
896 factor: 0.5,
897 max_delay: Duration::from_secs(30),
898 initial_delay: Duration::from_millis(100),
899 };
900 let d2 = backoff.delay(2).unwrap();
902 assert!(d2 <= Duration::from_millis(100));
903
904 let d3 = backoff.delay(3).unwrap();
905 assert!(d3 <= Duration::from_millis(50));
906 }
907
908 #[test]
909 fn backoff_delay_has_minimum_when_cap_is_positive() {
910 let backoff = BackoffPolicy {
911 factor: 1.0,
912 max_delay: Duration::from_millis(1),
913 initial_delay: Duration::from_millis(1),
914 };
915 assert_eq!(backoff.delay(2), Some(Duration::from_millis(1)));
916 }
917
918 #[test]
919 fn default_backoff_grows_exponentially() {
920 let backoff = BackoffPolicy::default();
924 assert!((backoff.factor() - 2.0).abs() < f64::EPSILON);
925 assert!(backoff.delay(2).unwrap() <= Duration::from_millis(500));
926 assert!(backoff.delay(3).unwrap() <= Duration::from_secs(1));
927 assert!(backoff.delay(4).unwrap() <= Duration::from_secs(2));
928 }
929
930 #[test]
931 fn backoff_delay_capped_at_max() {
932 let backoff = BackoffPolicy {
933 factor: 2.0,
934 max_delay: Duration::from_secs(5),
935 initial_delay: Duration::from_secs(1),
936 };
937 let d = backoff.delay(10).unwrap();
938 assert!(d < Duration::from_secs(5)); }
940
941 #[test]
942 fn retry_after_disabled_by_default() {
943 let policy = RetryPolicy::default();
944 assert!(policy.retry_after_delay("5").is_none());
945 }
946
947 #[test]
948 fn retry_after_respected_when_enabled() {
949 let policy = RetryPolicy::builder()
950 .max_attempts(3)
951 .respect_retry_after(true)
952 .build();
953 let delay = policy.retry_after_delay("5").unwrap();
954 assert_eq!(delay, Duration::from_secs(5));
955 }
956
957 #[test]
958 fn retry_after_capped_at_max_delay() {
959 let policy = RetryPolicy::builder()
960 .max_attempts(3)
961 .respect_retry_after(true)
962 .max_delay(Duration::from_secs(10))
963 .build();
964 let delay = policy.retry_after_delay("60").unwrap();
965 assert_eq!(delay, Duration::from_secs(10));
966 }
967
968 #[test]
969 fn retry_after_invalid_ignored() {
970 let policy = RetryPolicy::builder()
971 .max_attempts(3)
972 .respect_retry_after(true)
973 .build();
974 assert!(policy.retry_after_delay("not-a-number").is_none());
975 }
976
977 #[test]
978 fn retry_after_http_date_parses() {
979 use std::time::UNIX_EPOCH;
980
981 let policy = RetryPolicy::builder()
982 .max_attempts(3)
983 .respect_retry_after(true)
984 .build();
985 let future_time = UNIX_EPOCH
988 + Duration::from_secs(
989 std::time::SystemTime::now()
990 .duration_since(UNIX_EPOCH)
991 .unwrap()
992 .as_secs()
993 + 3600,
994 ); let formatted = httpdate::fmt_http_date(future_time);
996 let parsed = httpdate::parse_http_date(&formatted);
997 assert!(parsed.is_ok(), "round-trip parse failed: {formatted}");
998 let delay = policy.retry_after_delay(&formatted);
999 assert!(
1000 delay.is_some(),
1001 "retry_after_delay returned None for HTTP-date: {formatted}"
1002 );
1003 let d = delay.unwrap();
1004 assert!(d.as_secs() > 0, "delay should be positive");
1005 }
1006
1007 #[test]
1008 fn retry_after_past_http_date_is_ignored() {
1009 use std::time::UNIX_EPOCH;
1010
1011 let policy = RetryPolicy::builder()
1012 .max_attempts(3)
1013 .respect_retry_after(true)
1014 .build();
1015 let past_time = UNIX_EPOCH
1018 + Duration::from_secs(
1019 std::time::SystemTime::now()
1020 .duration_since(UNIX_EPOCH)
1021 .unwrap()
1022 .as_secs()
1023 .saturating_sub(3600),
1024 );
1025 let formatted = httpdate::fmt_http_date(past_time);
1026 assert!(policy.retry_after_delay(&formatted).is_none());
1027 }
1028
1029 #[test]
1030 fn body_replayable_empty() {
1031 let body = RequestBody::Empty;
1032 assert_eq!(
1033 RetryPolicy::check_body_replayable(&body),
1034 ReplayCheck::Replayable
1035 );
1036 }
1037
1038 #[test]
1039 fn body_replayable_bytes() {
1040 let body = RequestBody::from(bytes::Bytes::from("hello"));
1041 assert_eq!(
1042 RetryPolicy::check_body_replayable(&body),
1043 ReplayCheck::Replayable
1044 );
1045 }
1046
1047 #[test]
1048 fn body_not_replayable_stream() {
1049 let body = RequestBody::from_stream(
1050 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1051 None,
1052 );
1053 assert_eq!(
1054 RetryPolicy::check_body_replayable(&body),
1055 ReplayCheck::NotReplayable
1056 );
1057 }
1058
1059 #[test]
1060 fn should_retry_get_with_retryable_status() {
1061 let policy = RetryPolicy::builder().max_attempts(3).build();
1062 let body = RequestBody::Empty;
1063 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1064 assert_eq!(cause, Some(RetryCause::Status(503)));
1065 }
1066
1067 #[test]
1068 fn should_not_retry_post_by_default() {
1069 let policy = RetryPolicy::builder().max_attempts(3).build();
1070 let body = RequestBody::Empty;
1071 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1072 assert_eq!(cause, None);
1073 }
1074
1075 #[test]
1076 fn should_retry_post_when_allowed() {
1077 let policy = RetryPolicy::builder()
1078 .max_attempts(3)
1079 .allow_post_retry()
1080 .build();
1081 let body = RequestBody::Empty;
1082 let cause = should_retry(&policy, &Method::POST, &body, None, Some(503));
1083 assert_eq!(cause, Some(RetryCause::Status(503)));
1084 }
1085
1086 #[test]
1087 fn should_not_retry_non_retryable_status() {
1088 let policy = RetryPolicy::builder().max_attempts(3).build();
1089 let body = RequestBody::Empty;
1090 let cause = should_retry(&policy, &Method::GET, &body, None, Some(200));
1091 assert_eq!(cause, None);
1092 }
1093
1094 #[test]
1095 fn should_not_retry_stream_body() {
1096 let policy = RetryPolicy::builder().max_attempts(3).build();
1097 let body = RequestBody::from_stream(
1098 futures_util::stream::empty::<std::result::Result<bytes::Bytes, crate::Error>>(),
1099 None,
1100 );
1101 let cause = should_retry(&policy, &Method::GET, &body, None, Some(503));
1102 assert_eq!(cause, None);
1103 }
1104
1105 #[test]
1106 fn should_retry_connect_error() {
1107 let policy = RetryPolicy::builder().max_attempts(3).build();
1108 let body = RequestBody::Empty;
1109 let err = Error::Connect("connection refused".into());
1110 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1111 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1112 }
1113
1114 #[test]
1115 fn should_not_retry_invalid_url() {
1116 let policy = RetryPolicy::builder().max_attempts(3).build();
1117 let body = RequestBody::Empty;
1118 let err = Error::InvalidUrl("bad url".into());
1119 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1120 assert_eq!(cause, None);
1121 }
1122
1123 #[test]
1124 #[cfg(feature = "http3")]
1125 fn should_retry_h3_connect_error() {
1126 let policy = RetryPolicy::builder().max_attempts(3).build();
1127 let body = RequestBody::Empty;
1128 let err = Error::H3Connect("QUIC handshake failed".into());
1129 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1130 assert!(matches!(cause, Some(RetryCause::TransportError(_))));
1131 }
1132
1133 #[test]
1134 #[cfg(feature = "http3")]
1135 fn should_not_retry_h3_connection_closed() {
1136 let policy = RetryPolicy::builder().max_attempts(3).build();
1137 let body = RequestBody::Empty;
1138 let err = Error::H3ConnectionClosed("peer sent GOAWAY".into());
1139 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1140 assert_eq!(cause, None);
1141 }
1142
1143 #[test]
1144 #[cfg(feature = "http3")]
1145 fn should_not_retry_h3_protocol_error() {
1146 let policy = RetryPolicy::builder().max_attempts(3).build();
1147 let body = RequestBody::Empty;
1148 let err = Error::H3Protocol("unexpected frame".into());
1149 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1150 assert_eq!(cause, None);
1151 }
1152
1153 #[test]
1154 #[cfg(feature = "http3")]
1155 fn should_not_retry_h3_stream_error() {
1156 let policy = RetryPolicy::builder().max_attempts(3).build();
1157 let body = RequestBody::Empty;
1158 let err = Error::H3Stream("stream reset".into());
1159 let cause = should_retry(&policy, &Method::GET, &body, Some(&err), None);
1160 assert_eq!(cause, None);
1161 }
1162
1163 #[test]
1164 fn retry_cause_display() {
1165 assert_eq!(
1166 RetryCause::TransportError("refused".into()).to_string(),
1167 "transport error: refused"
1168 );
1169 assert_eq!(RetryCause::Status(503).to_string(), "retryable status: 503");
1170 assert_eq!(
1171 RetryCause::Timeout("total".into()).to_string(),
1172 "timeout: total"
1173 );
1174 }
1175
1176 #[test]
1177 fn method_policy_add_method() {
1178 let mut policy = MethodPolicy::default();
1179 assert!(!policy.is_retryable(&Method::POST));
1180 policy.add_method(Method::POST);
1181 assert!(policy.is_retryable(&Method::POST));
1182 }
1183
1184 #[test]
1185 fn status_policy_add_status() {
1186 let mut policy = StatusPolicy::default();
1187 assert!(!policy.is_retryable(418));
1188 policy.add_status(418);
1189 assert!(policy.is_retryable(418));
1190 }
1191
1192 #[test]
1193 fn retry_policy_max_elapsed() {
1194 let policy = RetryPolicy::builder()
1195 .max_attempts(3)
1196 .max_elapsed(Duration::from_secs(10))
1197 .build();
1198 assert_eq!(policy.max_elapsed(), Some(Duration::from_secs(10)));
1199 }
1200
1201 #[test]
1202 fn retry_policy_display_cause() {
1203 let cause = RetryCause::Status(429);
1204 assert_eq!(format!("{cause}"), "retryable status: 429");
1205 }
1206
1207 #[test]
1208 fn prop_backoff_delay_some_for_attempt_gt_1() {
1209 proptest::proptest!(|(attempt in 2usize..100usize)| {
1210 let backoff = BackoffPolicy::default();
1211 prop_assert!(backoff.delay(attempt).is_some());
1212 });
1213 }
1214
1215 #[test]
1216 fn prop_backoff_delay_bounded_by_max_delay() {
1217 proptest::proptest!(|(
1218 factor in 0.1f64..2.0f64,
1219 initial_ms in 1u64..1000u64,
1220 max_secs in 1u64..60u64,
1221 attempt in 2usize..20usize,
1222 )| {
1223 let backoff = BackoffPolicy {
1224 factor,
1225 max_delay: Duration::from_secs(max_secs),
1226 initial_delay: Duration::from_millis(initial_ms),
1227 };
1228 if let Some(delay) = backoff.delay(attempt) {
1229 prop_assert!(delay <= Duration::from_secs(max_secs * 2));
1230 }
1231 });
1232 }
1233
1234 #[test]
1235 fn prop_method_policy_default_contains_get_head_options() {
1236 let policy = MethodPolicy::default();
1237 assert!(policy.is_retryable(&Method::GET));
1238 assert!(policy.is_retryable(&Method::HEAD));
1239 assert!(policy.is_retryable(&Method::OPTIONS));
1240 }
1241
1242 #[test]
1243 fn prop_status_policy_default_contains_expected() {
1244 let policy = StatusPolicy::default();
1245 assert!(policy.is_retryable(408));
1246 assert!(policy.is_retryable(429));
1247 assert!(policy.is_retryable(502));
1248 assert!(policy.is_retryable(503));
1249 assert!(policy.is_retryable(504));
1250 }
1251
1252 #[test]
1253 fn prop_retry_after_delay_returns_none_for_garbage() {
1254 proptest::proptest!(|(input in ".{0,100}")| {
1255 let policy = RetryPolicy::builder()
1256 .max_attempts(3)
1257 .respect_retry_after(true)
1258 .build();
1259 let _ = policy.retry_after_delay(&input);
1260 });
1261 }
1262
1263 #[test]
1264 fn regression_fuzz_retry_crash_extreme_backoff_factor() {
1265 let backoff = BackoffPolicy {
1266 factor: 22.0,
1267 max_delay: Duration::from_secs(30),
1268 initial_delay: Duration::from_millis(500),
1269 };
1270 for attempt in 2..=20 {
1271 let delay = backoff.delay(attempt);
1272 assert!(delay.is_some());
1273 assert!(delay.unwrap() <= backoff.max_delay);
1274 }
1275 }
1276
1277 #[test]
1278 fn backoff_delay_nan_factor_returns_bounded_delay() {
1279 let backoff = BackoffPolicy {
1280 factor: f64::NAN,
1281 max_delay: Duration::from_secs(30),
1282 initial_delay: Duration::from_millis(500),
1283 };
1284 let d = backoff.delay(5).unwrap();
1285 assert!(d <= Duration::from_secs(30));
1286 }
1287
1288 #[test]
1289 fn backoff_delay_infinite_factor_returns_bounded_delay() {
1290 let backoff = BackoffPolicy {
1291 factor: f64::INFINITY,
1292 max_delay: Duration::from_secs(30),
1293 initial_delay: Duration::from_millis(500),
1294 };
1295 let d = backoff.delay(5).unwrap();
1296 assert!(d <= Duration::from_secs(30));
1297 }
1298
1299 #[test]
1300 fn backoff_delay_max_duration_does_not_panic() {
1301 let backoff = BackoffPolicy {
1304 factor: 2.0,
1305 max_delay: Duration::MAX,
1306 initial_delay: Duration::from_millis(500),
1307 };
1308 for attempt in [2, 5, 100] {
1309 let d = backoff.delay(attempt).unwrap();
1310 assert!(d <= Duration::MAX);
1311 }
1312 }
1313
1314 #[test]
1315 fn prop_is_error_retryable_never_panics() {
1316 proptest::proptest!(|(msg in ".{0,200}")| {
1317 let errors = vec![
1318 Error::Connect(msg.clone()),
1319 Error::Io(std::sync::Arc::new(std::io::Error::other(msg.clone()))),
1320 Error::InvalidUrl(msg.clone()),
1321 Error::Tls(msg.clone()),
1322 Error::Protocol(msg.clone()),
1323 Error::Body(msg.clone()),
1324 ];
1325 for err in &errors {
1326 let _ = RetryPolicy::is_error_retryable(err);
1327 }
1328 });
1329 }
1330}