1use crate::config::{ExponentialBackoff, RetryConfig, RetryTrigger};
2use crate::error::HttpError;
3use crate::response::{ResponseBody, parse_retry_after};
4use bytes::Bytes;
5use http::{HeaderValue, Request, Response};
6use http_body_util::{BodyExt, Full};
7use rand::RngExt;
8use std::future::Future;
9use std::pin::Pin;
10use std::task::{Context, Poll};
11use std::time::Duration;
12use tower::{Layer, Service, ServiceExt};
13
14pub const RETRY_ATTEMPT_HEADER: &str = "X-Retry-Attempt";
17
18#[derive(Clone)]
23pub struct RetryLayer {
24 config: RetryConfig,
25 total_timeout: Option<Duration>,
26}
27
28impl RetryLayer {
29 #[must_use]
31 pub fn new(config: RetryConfig) -> Self {
32 Self {
33 config,
34 total_timeout: None,
35 }
36 }
37
38 #[must_use]
40 pub fn with_total_timeout(config: RetryConfig, total_timeout: Option<Duration>) -> Self {
41 Self {
42 config,
43 total_timeout,
44 }
45 }
46}
47
48impl<S> Layer<S> for RetryLayer {
49 type Service = RetryService<S>;
50
51 fn layer(&self, inner: S) -> Self::Service {
52 RetryService {
53 inner,
54 config: self.config.clone(),
55 total_timeout: self.total_timeout,
56 }
57 }
58}
59
60#[derive(Clone)]
75pub struct RetryService<S> {
76 inner: S,
77 config: RetryConfig,
78 total_timeout: Option<Duration>,
79}
80
81impl<S> Service<Request<Full<Bytes>>> for RetryService<S>
82where
83 S: Service<Request<Full<Bytes>>, Response = Response<ResponseBody>, Error = HttpError>
84 + Clone
85 + Send
86 + 'static,
87 S::Future: Send,
88{
89 type Response = S::Response;
90 type Error = HttpError;
91 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
92
93 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
94 self.inner.poll_ready(cx)
95 }
96
97 fn call(&mut self, req: Request<Full<Bytes>>) -> Self::Future {
98 let clone = self.inner.clone();
101 let inner = std::mem::replace(&mut self.inner, clone);
102 let config = self.config.clone();
103 let total_timeout = self.total_timeout;
104
105 let (parts, body_bytes) = req.into_parts();
106
107 let http_version = parts.version;
109
110 let extensions = parts.extensions.clone();
114
115 let has_idempotency_key = config
118 .idempotency_key_header
119 .as_ref()
120 .is_some_and(|name| parts.headers.contains_key(name));
121
122 let parts = std::sync::Arc::new(parts);
123
124 Box::pin(async move {
125 let method = parts.method.clone();
126
127 let url_host = parts
130 .uri
131 .authority()
132 .map(ToString::to_string)
133 .or_else(|| parts.uri.host().map(ToOwned::to_owned))
134 .unwrap_or_else(|| "unknown".to_owned());
135 let request_id = parts
136 .headers
137 .get("x-request-id")
138 .or_else(|| parts.headers.get("x-correlation-id"))
139 .and_then(|v| v.to_str().ok())
140 .map(String::from);
141
142 let deadline_info = total_timeout.map(|t| (tokio::time::Instant::now() + t, t));
145
146 let mut attempt = 0usize;
147 loop {
148 if let Some((deadline, timeout_duration)) = deadline_info
150 && tokio::time::Instant::now() >= deadline
151 {
152 return Err(HttpError::DeadlineExceeded(timeout_duration));
153 }
154
155 let mut req = Request::from_parts((*parts).clone(), body_bytes.clone());
157
158 *req.version_mut() = http_version;
160
161 *req.extensions_mut() = extensions.clone();
164
165 if attempt > 0 {
167 if let Ok(value) = HeaderValue::try_from(attempt.to_string()) {
169 req.headers_mut().insert(RETRY_ATTEMPT_HEADER, value);
170 }
171 }
172
173 let mut svc = inner.clone();
174 svc.ready().await?;
175
176 match svc.call(req).await {
177 Ok(resp) => {
178 let status_code = resp.status().as_u16();
180 let trigger = RetryTrigger::Status(status_code);
181
182 if config.max_retries > 0
183 && attempt < config.max_retries
184 && config.should_retry(trigger, &method, has_idempotency_key)
185 {
186 let retry_after = parse_retry_after(resp.headers())
190 .map(|d| d.min(config.backoff.max));
191 let backoff_duration = if config.ignore_retry_after {
192 calculate_backoff(&config.backoff, attempt)
193 } else {
194 retry_after
195 .unwrap_or_else(|| calculate_backoff(&config.backoff, attempt))
196 };
197
198 let drain_limit = config.retry_response_drain_limit;
200 let should_drain = if config.skip_drain_on_retry {
201 tracing::trace!("Skipping drain: skip_drain_on_retry enabled");
203 false
204 } else if let Some(content_length) = resp
205 .headers()
206 .get(http::header::CONTENT_LENGTH)
207 .and_then(|v| v.to_str().ok())
208 .and_then(|s| s.parse::<u64>().ok())
209 {
210 if content_length > drain_limit as u64 {
211 tracing::debug!(
214 content_length,
215 drain_limit,
216 "Skipping drain: Content-Length exceeds limit"
217 );
218 false
219 } else {
220 true
221 }
222 } else {
223 true
225 };
226
227 if should_drain
228 && let Err(e) = drain_response_body(resp, drain_limit).await
229 {
230 tracing::debug!(
232 error = %e,
233 "Failed to drain response body before retry; connection may not be reused"
234 );
235 }
236
237 let effective_backoff =
239 if let Some((deadline, timeout_duration)) = deadline_info {
240 let remaining = deadline
241 .saturating_duration_since(tokio::time::Instant::now());
242 if remaining.is_zero() {
243 return Err(HttpError::DeadlineExceeded(timeout_duration));
244 }
245 backoff_duration.min(remaining)
246 } else {
247 backoff_duration
248 };
249
250 tracing::debug!(
251 retry = attempt + 1,
252 max_retries = config.max_retries,
253 status = status_code,
254 trigger = ?trigger,
255 method = %method,
256 host = %url_host,
257 request_id = ?request_id,
258 backoff_ms = effective_backoff.as_millis(),
259 retry_after_used = retry_after.is_some() && !config.ignore_retry_after,
260 "Retrying request after status code"
261 );
262 tokio::time::sleep(effective_backoff).await;
263 attempt += 1;
264 continue;
265 }
266
267 return Ok(resp);
269 }
270 Err(err) => {
271 if config.max_retries == 0 || attempt >= config.max_retries {
272 return Err(err);
273 }
274
275 let trigger = get_retry_trigger(&err);
276 if !config.should_retry(trigger, &method, has_idempotency_key) {
277 return Err(err);
278 }
279
280 let backoff_duration = calculate_backoff(&config.backoff, attempt);
282
283 let effective_backoff =
285 if let Some((deadline, timeout_duration)) = deadline_info {
286 let remaining =
287 deadline.saturating_duration_since(tokio::time::Instant::now());
288 if remaining.is_zero() {
289 return Err(HttpError::DeadlineExceeded(timeout_duration));
290 }
291 backoff_duration.min(remaining)
292 } else {
293 backoff_duration
294 };
295
296 tracing::debug!(
297 retry = attempt + 1,
298 max_retries = config.max_retries,
299 error = %err,
300 trigger = ?trigger,
301 method = %method,
302 host = %url_host,
303 request_id = ?request_id,
304 backoff_ms = effective_backoff.as_millis(),
305 "Retrying request after error"
306 );
307 tokio::time::sleep(effective_backoff).await;
308 attempt += 1;
309 }
310 }
311 }
312 })
313 }
314}
315
316async fn drain_response_body(
340 response: Response<ResponseBody>,
341 limit: usize,
342) -> Result<(), HttpError> {
343 let (_parts, body) = response.into_parts();
344 let mut body = std::pin::pin!(body);
345 let mut drained = 0usize;
346
347 while let Some(frame) = body.frame().await {
348 let frame = frame.map_err(HttpError::Transport)?;
349 if let Some(chunk) = frame.data_ref() {
350 drained += chunk.len();
351 if drained >= limit {
352 break;
354 }
355 }
356 }
357
358 Ok(())
359}
360
361fn get_retry_trigger(err: &HttpError) -> RetryTrigger {
363 match err {
364 HttpError::Transport(_)
368 | HttpError::Proxy {
369 kind: crate::error::ProxyErrorKind::TunnelRejected,
370 ..
371 } => RetryTrigger::TransportError,
372 HttpError::Timeout(_) => RetryTrigger::Timeout,
373 _ => RetryTrigger::NonRetryable,
375 }
376}
377
378pub fn calculate_backoff(backoff: &ExponentialBackoff, attempt: usize) -> Duration {
382 const MAX_BACKOFF_SECS: f64 = 86400.0;
384
385 let attempt_i32 = i32::try_from(attempt).unwrap_or(i32::MAX);
388
389 let multiplier = if backoff.multiplier.is_finite() && backoff.multiplier >= 0.0 {
391 backoff.multiplier
392 } else {
393 1.0
394 };
395
396 let initial_secs = backoff.initial.as_secs_f64();
398 let initial_secs = if initial_secs.is_finite() && initial_secs >= 0.0 {
399 initial_secs
400 } else {
401 0.0
402 };
403
404 let max_secs = backoff.max.as_secs_f64();
406 let max_secs = if max_secs.is_finite() && max_secs >= 0.0 {
407 max_secs.min(MAX_BACKOFF_SECS)
408 } else {
409 MAX_BACKOFF_SECS
410 };
411
412 let base_duration = initial_secs * multiplier.powi(attempt_i32);
414
415 let clamped = if base_duration.is_finite() {
417 base_duration.min(max_secs).max(0.0)
418 } else {
419 max_secs
420 };
421 let duration = Duration::from_secs_f64(clamped);
422
423 let duration = if backoff.jitter {
425 let mut rng = rand::rng();
426 let jitter_factor = rng.random_range(0.0..=0.25);
427 let jitter = duration.mul_f64(jitter_factor);
428 duration + jitter
429 } else {
430 duration
431 };
432
433 let max_duration = Duration::from_secs_f64(max_secs);
435 duration.min(max_duration)
436}
437
438#[cfg(test)]
439#[cfg_attr(coverage_nightly, coverage(off))]
440mod tests {
441 use super::*;
442 use crate::config::IDEMPOTENCY_KEY_HEADER;
443 use bytes::Bytes;
444 use http::{Method, Request, Response, StatusCode};
445 use http_body_util::Full;
446
447 fn make_response_body(data: &[u8]) -> ResponseBody {
449 let body = Full::new(Bytes::from(data.to_vec()));
450 body.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })
451 .boxed()
452 }
453
454 #[tokio::test]
455 async fn test_retry_layer_successful_request() {
456 use std::sync::{Arc, Mutex};
457
458 #[derive(Clone)]
459 struct CountingService {
460 call_count: Arc<Mutex<usize>>,
461 }
462
463 impl Service<Request<Full<Bytes>>> for CountingService {
464 type Response = Response<ResponseBody>;
465 type Error = HttpError;
466 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
467
468 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
469 Poll::Ready(Ok(()))
470 }
471
472 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
473 let count = self.call_count.clone();
474 Box::pin(async move {
475 *count.lock().unwrap() += 1;
476 let response = Response::builder()
477 .status(StatusCode::OK)
478 .body(make_response_body(b""))
479 .unwrap();
480 Ok(response)
481 })
482 }
483 }
484
485 let call_count = Arc::new(Mutex::new(0));
486 let service = CountingService {
487 call_count: call_count.clone(),
488 };
489
490 let retry_config = RetryConfig::default();
491 let layer = RetryLayer::new(retry_config);
492 let mut retry_service = layer.layer(service);
493
494 let req = Request::builder()
495 .method(Method::GET)
496 .uri("http://example.com")
497 .body(Full::new(Bytes::new()))
498 .unwrap();
499
500 let result = retry_service.call(req).await;
501 assert!(result.is_ok());
502 assert_eq!(*call_count.lock().unwrap(), 1); }
504
505 #[tokio::test]
508 async fn test_retry_layer_post_not_retried_on_5xx() {
509 use std::sync::{Arc, Mutex};
510
511 #[derive(Clone)]
512 struct ServerErrorService {
513 call_count: Arc<Mutex<usize>>,
514 }
515
516 impl Service<Request<Full<Bytes>>> for ServerErrorService {
517 type Response = Response<ResponseBody>;
518 type Error = HttpError;
519 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
520
521 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
522 Poll::Ready(Ok(()))
523 }
524
525 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
526 let count = self.call_count.clone();
527 Box::pin(async move {
528 *count.lock().unwrap() += 1;
529 Ok(Response::builder()
531 .status(StatusCode::INTERNAL_SERVER_ERROR)
532 .body(make_response_body(b"Internal Server Error"))
533 .unwrap())
534 })
535 }
536 }
537
538 let call_count = Arc::new(Mutex::new(0));
539 let service = ServerErrorService {
540 call_count: call_count.clone(),
541 };
542
543 let retry_config = RetryConfig {
544 backoff: ExponentialBackoff::fast(),
545 ..RetryConfig::default()
546 };
547 let layer = RetryLayer::new(retry_config);
548 let mut retry_service = layer.layer(service);
549
550 let req = Request::builder()
551 .method(Method::POST)
552 .uri("http://example.com")
553 .body(Full::new(Bytes::new()))
554 .unwrap();
555
556 let result = retry_service.call(req).await;
557 assert!(result.is_ok());
559 let resp = result.unwrap();
560 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
561 assert_eq!(*call_count.lock().unwrap(), 1); }
563
564 #[tokio::test]
567 async fn test_retry_layer_get_retried_on_5xx() {
568 use std::sync::{Arc, Mutex};
569
570 #[derive(Clone)]
571 struct FailThenSucceedService {
572 call_count: Arc<Mutex<usize>>,
573 }
574
575 impl Service<Request<Full<Bytes>>> for FailThenSucceedService {
576 type Response = Response<ResponseBody>;
577 type Error = HttpError;
578 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
579
580 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
581 Poll::Ready(Ok(()))
582 }
583
584 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
585 let count = self.call_count.clone();
586 Box::pin(async move {
587 let mut c = count.lock().unwrap();
588 *c += 1;
589 if *c < 3 {
590 Ok(Response::builder()
592 .status(StatusCode::INTERNAL_SERVER_ERROR)
593 .body(make_response_body(b"Internal Server Error"))
594 .unwrap())
595 } else {
596 Ok(Response::builder()
597 .status(StatusCode::OK)
598 .body(make_response_body(b""))
599 .unwrap())
600 }
601 })
602 }
603 }
604
605 let call_count = Arc::new(Mutex::new(0));
606 let service = FailThenSucceedService {
607 call_count: call_count.clone(),
608 };
609
610 let retry_config = RetryConfig {
611 backoff: ExponentialBackoff::fast(),
612 ..RetryConfig::default()
613 };
614 let layer = RetryLayer::new(retry_config);
615 let mut retry_service = layer.layer(service);
616
617 let req = Request::builder()
618 .method(Method::GET)
619 .uri("http://example.com")
620 .body(Full::new(Bytes::new()))
621 .unwrap();
622
623 let result = retry_service.call(req).await;
624 assert!(result.is_ok());
625 assert_eq!(result.unwrap().status(), StatusCode::OK);
626 assert_eq!(*call_count.lock().unwrap(), 3); }
628
629 #[tokio::test]
631 async fn test_retry_layer_always_retries_429() {
632 use std::sync::{Arc, Mutex};
633
634 #[derive(Clone)]
635 struct RateLimitThenSucceedService {
636 call_count: Arc<Mutex<usize>>,
637 }
638
639 impl Service<Request<Full<Bytes>>> for RateLimitThenSucceedService {
640 type Response = Response<ResponseBody>;
641 type Error = HttpError;
642 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
643
644 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
645 Poll::Ready(Ok(()))
646 }
647
648 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
649 let count = self.call_count.clone();
650 Box::pin(async move {
651 let mut c = count.lock().unwrap();
652 *c += 1;
653 if *c < 2 {
654 Ok(Response::builder()
656 .status(StatusCode::TOO_MANY_REQUESTS)
657 .body(make_response_body(b"Rate limited"))
658 .unwrap())
659 } else {
660 Ok(Response::builder()
661 .status(StatusCode::OK)
662 .body(make_response_body(b""))
663 .unwrap())
664 }
665 })
666 }
667 }
668
669 let call_count = Arc::new(Mutex::new(0));
670 let service = RateLimitThenSucceedService {
671 call_count: call_count.clone(),
672 };
673
674 let retry_config = RetryConfig {
675 backoff: ExponentialBackoff::fast(),
676 ..RetryConfig::default()
677 };
678 let layer = RetryLayer::new(retry_config);
679 let mut retry_service = layer.layer(service);
680
681 let req = Request::builder()
683 .method(Method::POST)
684 .uri("http://example.com")
685 .body(Full::new(Bytes::new()))
686 .unwrap();
687
688 let result = retry_service.call(req).await;
689 assert!(result.is_ok());
690 assert_eq!(result.unwrap().status(), StatusCode::OK);
691 assert_eq!(*call_count.lock().unwrap(), 2); }
693
694 #[tokio::test]
695 async fn test_retry_layer_retries_transport_errors() {
696 use std::sync::{Arc, Mutex};
697
698 #[derive(Clone)]
699 struct FailThenSucceedService {
700 call_count: Arc<Mutex<usize>>,
701 }
702
703 impl Service<Request<Full<Bytes>>> for FailThenSucceedService {
704 type Response = Response<ResponseBody>;
705 type Error = HttpError;
706 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
707
708 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
709 Poll::Ready(Ok(()))
710 }
711
712 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
713 let count = self.call_count.clone();
714 Box::pin(async move {
715 let mut c = count.lock().unwrap();
716 *c += 1;
717 if *c < 3 {
718 Err(HttpError::Transport(Box::new(std::io::Error::new(
719 std::io::ErrorKind::ConnectionReset,
720 "connection reset",
721 ))))
722 } else {
723 Ok(Response::builder()
724 .status(StatusCode::OK)
725 .body(make_response_body(b""))
726 .unwrap())
727 }
728 })
729 }
730 }
731
732 let call_count = Arc::new(Mutex::new(0));
733 let service = FailThenSucceedService {
734 call_count: call_count.clone(),
735 };
736
737 let retry_config = RetryConfig {
738 backoff: ExponentialBackoff::fast(),
739 ..RetryConfig::default()
740 };
741 let layer = RetryLayer::new(retry_config);
742 let mut retry_service = layer.layer(service);
743
744 let req = Request::builder()
745 .method(Method::GET)
746 .uri("http://example.com")
747 .body(Full::new(Bytes::new()))
748 .unwrap();
749
750 let result = retry_service.call(req).await;
751 assert!(result.is_ok());
752 assert_eq!(*call_count.lock().unwrap(), 3); }
754
755 #[tokio::test]
757 async fn test_retry_layer_post_not_retried_on_transport_error() {
758 use std::sync::{Arc, Mutex};
759
760 #[derive(Clone)]
761 struct TransportErrorService {
762 call_count: Arc<Mutex<usize>>,
763 }
764
765 impl Service<Request<Full<Bytes>>> for TransportErrorService {
766 type Response = Response<ResponseBody>;
767 type Error = HttpError;
768 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
769
770 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
771 Poll::Ready(Ok(()))
772 }
773
774 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
775 let count = self.call_count.clone();
776 Box::pin(async move {
777 *count.lock().unwrap() += 1;
778 Err(HttpError::Transport(Box::new(std::io::Error::new(
779 std::io::ErrorKind::ConnectionReset,
780 "connection reset",
781 ))))
782 })
783 }
784 }
785
786 let call_count = Arc::new(Mutex::new(0));
787 let service = TransportErrorService {
788 call_count: call_count.clone(),
789 };
790
791 let retry_config = RetryConfig {
792 backoff: ExponentialBackoff::fast(),
793 ..RetryConfig::default()
794 };
795 let layer = RetryLayer::new(retry_config);
796 let mut retry_service = layer.layer(service);
797
798 let req = Request::builder()
800 .method(Method::POST)
801 .uri("http://example.com")
802 .body(Full::new(Bytes::new()))
803 .unwrap();
804
805 let result = retry_service.call(req).await;
806 assert!(result.is_err()); assert_eq!(*call_count.lock().unwrap(), 1); }
809
810 #[tokio::test]
812 async fn test_retry_layer_post_with_idempotency_key_retried() {
813 use std::sync::{Arc, Mutex};
814
815 #[derive(Clone)]
816 struct FailThenSucceedService {
817 call_count: Arc<Mutex<usize>>,
818 }
819
820 impl Service<Request<Full<Bytes>>> for FailThenSucceedService {
821 type Response = Response<ResponseBody>;
822 type Error = HttpError;
823 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
824
825 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
826 Poll::Ready(Ok(()))
827 }
828
829 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
830 let count = self.call_count.clone();
831 Box::pin(async move {
832 let mut c = count.lock().unwrap();
833 *c += 1;
834 if *c < 3 {
835 Err(HttpError::Transport(Box::new(std::io::Error::new(
836 std::io::ErrorKind::ConnectionReset,
837 "connection reset",
838 ))))
839 } else {
840 Ok(Response::builder()
841 .status(StatusCode::OK)
842 .body(make_response_body(b""))
843 .unwrap())
844 }
845 })
846 }
847 }
848
849 let call_count = Arc::new(Mutex::new(0));
850 let service = FailThenSucceedService {
851 call_count: call_count.clone(),
852 };
853
854 let retry_config = RetryConfig {
855 backoff: ExponentialBackoff::fast(),
856 ..RetryConfig::default()
857 };
858 let layer = RetryLayer::new(retry_config);
859 let mut retry_service = layer.layer(service);
860
861 let req = Request::builder()
863 .method(Method::POST)
864 .uri("http://example.com")
865 .header(IDEMPOTENCY_KEY_HEADER, "unique-key-123")
866 .body(Full::new(Bytes::new()))
867 .unwrap();
868
869 let result = retry_service.call(req).await;
870 assert!(result.is_ok()); assert_eq!(*call_count.lock().unwrap(), 3); }
873
874 #[tokio::test]
875 async fn test_retry_layer_does_not_retry_json_errors() {
876 use std::sync::{Arc, Mutex};
877
878 #[derive(Clone)]
879 struct JsonErrorService {
880 call_count: Arc<Mutex<usize>>,
881 }
882
883 impl Service<Request<Full<Bytes>>> for JsonErrorService {
884 type Response = Response<ResponseBody>;
885 type Error = HttpError;
886 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
887
888 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
889 Poll::Ready(Ok(()))
890 }
891
892 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
893 let count = self.call_count.clone();
894 Box::pin(async move {
895 *count.lock().unwrap() += 1;
896 let err: serde_json::Error =
898 serde_json::from_str::<serde_json::Value>("invalid").unwrap_err();
899 Err(HttpError::Json(err))
900 })
901 }
902 }
903
904 let call_count = Arc::new(Mutex::new(0));
905 let service = JsonErrorService {
906 call_count: call_count.clone(),
907 };
908
909 let retry_config = RetryConfig::default();
910 let layer = RetryLayer::new(retry_config);
911 let mut retry_service = layer.layer(service);
912
913 let req = Request::builder()
914 .method(Method::GET)
915 .uri("http://example.com")
916 .body(Full::new(Bytes::new()))
917 .unwrap();
918
919 let result = retry_service.call(req).await;
920 assert!(result.is_err());
921 assert_eq!(*call_count.lock().unwrap(), 1); }
923
924 #[test]
925 fn test_calculate_backoff_no_jitter() {
926 let backoff = ExponentialBackoff {
927 initial: Duration::from_millis(100),
928 max: Duration::from_secs(10),
929 multiplier: 2.0,
930 jitter: false,
931 };
932
933 let backoff0 = calculate_backoff(&backoff, 0);
934 assert_eq!(backoff0, Duration::from_millis(100));
935
936 let backoff1 = calculate_backoff(&backoff, 1);
937 assert_eq!(backoff1, Duration::from_millis(200));
938
939 let backoff2 = calculate_backoff(&backoff, 2);
940 assert_eq!(backoff2, Duration::from_millis(400));
941
942 let backoff_capped = calculate_backoff(&backoff, 10);
944 assert_eq!(backoff_capped, Duration::from_secs(10));
945 }
946
947 #[test]
948 fn test_calculate_backoff_with_jitter() {
949 let backoff = ExponentialBackoff {
950 initial: Duration::from_millis(100),
951 max: Duration::from_secs(10),
952 multiplier: 2.0,
953 jitter: true,
954 };
955
956 let backoff0 = calculate_backoff(&backoff, 0);
957 assert!(backoff0 >= Duration::from_millis(100));
959 assert!(backoff0 <= Duration::from_millis(125));
960 }
961
962 #[test]
963 fn test_calculate_backoff_with_nan_multiplier() {
964 let backoff = ExponentialBackoff {
966 initial: Duration::from_millis(100),
967 max: Duration::from_secs(10),
968 multiplier: f64::NAN,
969 jitter: false,
970 };
971
972 let result = calculate_backoff(&backoff, 0);
974 assert_eq!(result, Duration::from_millis(100));
975
976 let result1 = calculate_backoff(&backoff, 1);
977 assert_eq!(result1, Duration::from_millis(100));
979 }
980
981 #[test]
982 fn test_calculate_backoff_with_infinity_multiplier() {
983 let backoff = ExponentialBackoff {
985 initial: Duration::from_millis(100),
986 max: Duration::from_secs(10),
987 multiplier: f64::INFINITY,
988 jitter: false,
989 };
990
991 let result = calculate_backoff(&backoff, 0);
993 assert_eq!(result, Duration::from_millis(100));
994 }
995
996 #[test]
997 fn test_calculate_backoff_with_negative_multiplier() {
998 let backoff = ExponentialBackoff {
1000 initial: Duration::from_millis(100),
1001 max: Duration::from_secs(10),
1002 multiplier: -2.0,
1003 jitter: false,
1004 };
1005
1006 let result = calculate_backoff(&backoff, 0);
1008 assert_eq!(result, Duration::from_millis(100));
1009 }
1010
1011 #[test]
1012 fn test_calculate_backoff_with_huge_attempt() {
1013 let backoff = ExponentialBackoff {
1015 initial: Duration::from_millis(100),
1016 max: Duration::from_secs(10),
1017 multiplier: 2.0,
1018 jitter: false,
1019 };
1020
1021 let result = calculate_backoff(&backoff, usize::MAX);
1023 assert_eq!(result, Duration::from_secs(10));
1025 }
1026
1027 #[tokio::test]
1029 async fn test_retry_layer_uses_retry_after_header() {
1030 use std::sync::{Arc, Mutex};
1031
1032 #[derive(Clone)]
1033 struct RetryAfterService {
1034 call_count: Arc<Mutex<usize>>,
1035 }
1036
1037 impl Service<Request<Full<Bytes>>> for RetryAfterService {
1038 type Response = Response<ResponseBody>;
1039 type Error = HttpError;
1040 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1041
1042 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1043 Poll::Ready(Ok(()))
1044 }
1045
1046 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
1047 let count = self.call_count.clone();
1048 Box::pin(async move {
1049 let mut c = count.lock().unwrap();
1050 *c += 1;
1051 if *c < 2 {
1052 Ok(Response::builder()
1054 .status(StatusCode::TOO_MANY_REQUESTS)
1055 .header(http::header::RETRY_AFTER, "0")
1056 .body(make_response_body(b"Rate limited"))
1057 .unwrap())
1058 } else {
1059 Ok(Response::builder()
1060 .status(StatusCode::OK)
1061 .body(make_response_body(b""))
1062 .unwrap())
1063 }
1064 })
1065 }
1066 }
1067
1068 let call_count = Arc::new(Mutex::new(0));
1069 let service = RetryAfterService {
1070 call_count: call_count.clone(),
1071 };
1072
1073 let retry_config = RetryConfig {
1074 backoff: ExponentialBackoff {
1075 initial: Duration::from_secs(10), jitter: false,
1077 ..ExponentialBackoff::default()
1078 },
1079 ignore_retry_after: false, ..RetryConfig::default()
1081 };
1082 let layer = RetryLayer::new(retry_config);
1083 let mut retry_service = layer.layer(service);
1084
1085 let req = Request::builder()
1086 .method(Method::POST)
1087 .uri("http://example.com")
1088 .body(Full::new(Bytes::new()))
1089 .unwrap();
1090
1091 let start = std::time::Instant::now();
1092 let result = retry_service.call(req).await;
1093 let elapsed = start.elapsed();
1094
1095 assert!(result.is_ok());
1096 assert_eq!(*call_count.lock().unwrap(), 2);
1097
1098 assert!(
1100 elapsed < Duration::from_secs(1),
1101 "Expected quick retry using Retry-After, but took {elapsed:?}",
1102 );
1103 }
1104
1105 #[tokio::test]
1107 async fn test_retry_layer_ignores_retry_after_when_configured() {
1108 use std::sync::{Arc, Mutex};
1109
1110 #[derive(Clone)]
1111 struct RetryAfterService {
1112 call_count: Arc<Mutex<usize>>,
1113 }
1114
1115 impl Service<Request<Full<Bytes>>> for RetryAfterService {
1116 type Response = Response<ResponseBody>;
1117 type Error = HttpError;
1118 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1119
1120 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1121 Poll::Ready(Ok(()))
1122 }
1123
1124 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
1125 let count = self.call_count.clone();
1126 Box::pin(async move {
1127 let mut c = count.lock().unwrap();
1128 *c += 1;
1129 if *c < 2 {
1130 Ok(Response::builder()
1132 .status(StatusCode::TOO_MANY_REQUESTS)
1133 .header(http::header::RETRY_AFTER, "10")
1134 .body(make_response_body(b"Rate limited"))
1135 .unwrap())
1136 } else {
1137 Ok(Response::builder()
1138 .status(StatusCode::OK)
1139 .body(make_response_body(b""))
1140 .unwrap())
1141 }
1142 })
1143 }
1144 }
1145
1146 let call_count = Arc::new(Mutex::new(0));
1147 let service = RetryAfterService {
1148 call_count: call_count.clone(),
1149 };
1150
1151 let retry_config = RetryConfig {
1152 backoff: ExponentialBackoff::fast(), ignore_retry_after: true, ..RetryConfig::default()
1155 };
1156 let layer = RetryLayer::new(retry_config);
1157 let mut retry_service = layer.layer(service);
1158
1159 let req = Request::builder()
1160 .method(Method::POST)
1161 .uri("http://example.com")
1162 .body(Full::new(Bytes::new()))
1163 .unwrap();
1164
1165 let start = std::time::Instant::now();
1166 let result = retry_service.call(req).await;
1167 let elapsed = start.elapsed();
1168
1169 assert!(result.is_ok());
1170 assert_eq!(*call_count.lock().unwrap(), 2);
1171
1172 assert!(
1174 elapsed < Duration::from_secs(1),
1175 "Expected quick retry using backoff policy (1ms), but took {elapsed:?}",
1176 );
1177 }
1178
1179 #[tokio::test]
1182 async fn test_retry_after_clamped_to_backoff_max() {
1183 use std::sync::{Arc, Mutex};
1184
1185 #[derive(Clone)]
1186 struct LargeRetryAfterService {
1187 call_count: Arc<Mutex<usize>>,
1188 }
1189
1190 impl Service<Request<Full<Bytes>>> for LargeRetryAfterService {
1191 type Response = Response<ResponseBody>;
1192 type Error = HttpError;
1193 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1194
1195 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1196 Poll::Ready(Ok(()))
1197 }
1198
1199 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
1200 let count = self.call_count.clone();
1201 Box::pin(async move {
1202 let mut c = count.lock().unwrap();
1203 *c += 1;
1204 if *c < 2 {
1205 Ok(Response::builder()
1207 .status(StatusCode::TOO_MANY_REQUESTS)
1208 .header(http::header::RETRY_AFTER, "3600")
1209 .body(make_response_body(b"Rate limited"))
1210 .unwrap())
1211 } else {
1212 Ok(Response::builder()
1213 .status(StatusCode::OK)
1214 .body(make_response_body(b""))
1215 .unwrap())
1216 }
1217 })
1218 }
1219 }
1220
1221 let call_count = Arc::new(Mutex::new(0));
1222 let service = LargeRetryAfterService {
1223 call_count: call_count.clone(),
1224 };
1225
1226 let retry_config = RetryConfig {
1227 backoff: ExponentialBackoff {
1228 initial: Duration::from_millis(1),
1229 max: Duration::from_millis(50), jitter: false,
1231 ..ExponentialBackoff::default()
1232 },
1233 ignore_retry_after: false, ..RetryConfig::default()
1235 };
1236 let layer = RetryLayer::new(retry_config);
1237 let mut retry_service = layer.layer(service);
1238
1239 let req = Request::builder()
1240 .method(Method::POST)
1241 .uri("http://example.com")
1242 .body(Full::new(Bytes::new()))
1243 .unwrap();
1244
1245 let start = std::time::Instant::now();
1246 let result = retry_service.call(req).await;
1247 let elapsed = start.elapsed();
1248
1249 assert!(result.is_ok());
1250 assert_eq!(*call_count.lock().unwrap(), 2);
1251
1252 assert!(
1255 elapsed < Duration::from_secs(1),
1256 "Retry-After should be clamped to backoff.max (50ms), but took {elapsed:?}",
1257 );
1258 }
1259
1260 #[tokio::test]
1261 async fn test_retry_attempt_header_added_on_retry() {
1262 use std::sync::{Arc, Mutex};
1263
1264 #[derive(Clone)]
1265 struct HeaderCapturingService {
1266 call_count: Arc<Mutex<usize>>,
1267 captured_headers: Arc<Mutex<Vec<Option<String>>>>,
1268 }
1269
1270 impl Service<Request<Full<Bytes>>> for HeaderCapturingService {
1271 type Response = Response<ResponseBody>;
1272 type Error = HttpError;
1273 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1274
1275 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1276 Poll::Ready(Ok(()))
1277 }
1278
1279 fn call(&mut self, req: Request<Full<Bytes>>) -> Self::Future {
1280 let count = self.call_count.clone();
1281 let captured_headers = self.captured_headers.clone();
1282
1283 let retry_header = req
1285 .headers()
1286 .get(RETRY_ATTEMPT_HEADER)
1287 .map(|v| v.to_str().unwrap_or("invalid").to_owned());
1288
1289 Box::pin(async move {
1290 let mut c = count.lock().unwrap();
1291 *c += 1;
1292 captured_headers.lock().unwrap().push(retry_header);
1293
1294 if *c < 3 {
1295 Err(HttpError::Transport(Box::new(std::io::Error::new(
1297 std::io::ErrorKind::ConnectionReset,
1298 "connection reset",
1299 ))))
1300 } else {
1301 Ok(Response::builder()
1302 .status(StatusCode::OK)
1303 .body(make_response_body(b""))
1304 .unwrap())
1305 }
1306 })
1307 }
1308 }
1309
1310 let call_count = Arc::new(Mutex::new(0));
1311 let captured_headers = Arc::new(Mutex::new(Vec::new()));
1312 let service = HeaderCapturingService {
1313 call_count: call_count.clone(),
1314 captured_headers: captured_headers.clone(),
1315 };
1316
1317 let retry_config = RetryConfig {
1318 backoff: ExponentialBackoff::fast(),
1319 ..RetryConfig::default()
1320 };
1321 let layer = RetryLayer::new(retry_config);
1322 let mut retry_service = layer.layer(service);
1323
1324 let req = Request::builder()
1325 .method(Method::GET)
1326 .uri("http://example.com")
1327 .body(Full::new(Bytes::new()))
1328 .unwrap();
1329
1330 let result = retry_service.call(req).await;
1331 assert!(result.is_ok());
1332 assert_eq!(*call_count.lock().unwrap(), 3);
1333
1334 let headers = captured_headers.lock().unwrap();
1336 assert_eq!(headers.len(), 3);
1337 assert_eq!(headers[0], None);
1339 assert_eq!(headers[1], Some("1".to_owned()));
1341 assert_eq!(headers[2], Some("2".to_owned()));
1343 }
1344
1345 #[tokio::test]
1347 async fn test_retry_layer_exhausted_returns_ok_with_status() {
1348 use std::sync::{Arc, Mutex};
1349
1350 #[derive(Clone)]
1351 struct AlwaysFailService {
1352 call_count: Arc<Mutex<usize>>,
1353 }
1354
1355 impl Service<Request<Full<Bytes>>> for AlwaysFailService {
1356 type Response = Response<ResponseBody>;
1357 type Error = HttpError;
1358 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1359
1360 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1361 Poll::Ready(Ok(()))
1362 }
1363
1364 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
1365 let count = self.call_count.clone();
1366 Box::pin(async move {
1367 *count.lock().unwrap() += 1;
1368 Ok(Response::builder()
1370 .status(StatusCode::INTERNAL_SERVER_ERROR)
1371 .body(make_response_body(b"error"))
1372 .unwrap())
1373 })
1374 }
1375 }
1376
1377 let call_count = Arc::new(Mutex::new(0));
1378 let service = AlwaysFailService {
1379 call_count: call_count.clone(),
1380 };
1381
1382 let retry_config = RetryConfig {
1383 max_retries: 2,
1384 backoff: ExponentialBackoff::fast(),
1385 ..RetryConfig::default()
1386 };
1387 let layer = RetryLayer::new(retry_config);
1388 let mut retry_service = layer.layer(service);
1389
1390 let req = Request::builder()
1391 .method(Method::GET)
1392 .uri("http://example.com")
1393 .body(Full::new(Bytes::new()))
1394 .unwrap();
1395
1396 let result = retry_service.call(req).await;
1397
1398 assert!(result.is_ok());
1400 let resp = result.unwrap();
1401 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1402
1403 assert_eq!(*call_count.lock().unwrap(), 3);
1405 }
1406
1407 #[tokio::test]
1409 async fn test_retry_layer_non_retryable_status_passes_through() {
1410 use std::sync::{Arc, Mutex};
1411
1412 #[derive(Clone)]
1413 struct NotFoundService {
1414 call_count: Arc<Mutex<usize>>,
1415 }
1416
1417 impl Service<Request<Full<Bytes>>> for NotFoundService {
1418 type Response = Response<ResponseBody>;
1419 type Error = HttpError;
1420 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1421
1422 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1423 Poll::Ready(Ok(()))
1424 }
1425
1426 fn call(&mut self, _req: Request<Full<Bytes>>) -> Self::Future {
1427 let count = self.call_count.clone();
1428 Box::pin(async move {
1429 *count.lock().unwrap() += 1;
1430 Ok(Response::builder()
1431 .status(StatusCode::NOT_FOUND)
1432 .body(make_response_body(b"not found"))
1433 .unwrap())
1434 })
1435 }
1436 }
1437
1438 let call_count = Arc::new(Mutex::new(0));
1439 let service = NotFoundService {
1440 call_count: call_count.clone(),
1441 };
1442
1443 let retry_config = RetryConfig {
1444 max_retries: 3,
1445 backoff: ExponentialBackoff::fast(),
1446 ..RetryConfig::default()
1447 };
1448 let layer = RetryLayer::new(retry_config);
1449 let mut retry_service = layer.layer(service);
1450
1451 let req = Request::builder()
1452 .method(Method::GET)
1453 .uri("http://example.com")
1454 .body(Full::new(Bytes::new()))
1455 .unwrap();
1456
1457 let result = retry_service.call(req).await;
1458
1459 assert!(result.is_ok());
1461 let resp = result.unwrap();
1462 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1463
1464 assert_eq!(*call_count.lock().unwrap(), 1);
1466 }
1467}