use std::time::Duration;
use crate::transport::{Response, TransportError};
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct RetryPolicy {
pub(crate) max_retries: u32,
pub(crate) base_delay: Duration,
pub(crate) max_delay: Duration,
}
impl Default for RetryPolicy {
fn default() -> Self {
Self {
max_retries: 3,
base_delay: Duration::from_secs(1),
max_delay: Duration::from_secs(30),
}
}
}
impl RetryPolicy {
pub(super) fn delay(&self, attempt: u32, retry_after: Option<Duration>) -> Duration {
retry_after.unwrap_or_else(|| {
let backoff = self
.base_delay
.saturating_mul(2_u32.saturating_pow(attempt))
.min(self.max_delay);
backoff.mul_f64(fastrand::f64().mul_add(0.5, 0.5))
})
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Outcome {
Sent,
Rejected,
Retry(Option<Duration>),
}
pub(super) fn classify(result: &Result<Response, TransportError>) -> Outcome {
match result {
Ok(response) if (200..300).contains(&response.status) => Outcome::Sent,
Ok(response) if matches!(response.status, 429 | 502 | 503 | 504) => {
Outcome::Retry(response.retry_after)
}
Ok(_) => Outcome::Rejected,
Err(_) => Outcome::Retry(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::secs;
#[test]
fn backoff_doubles_with_jitter() {
let policy = RetryPolicy::default();
for (attempt, full) in [(0, 1), (1, 2), (2, 4), (10, 30)] {
let delay = policy.delay(attempt, None);
assert!(
delay >= secs(full) / 2 && delay <= secs(full),
"attempt {attempt}: {delay:?}"
);
}
}
#[test]
fn retry_after_overrides_the_backoff() {
assert_eq!(RetryPolicy::default().delay(0, Some(secs(60))), secs(60));
}
fn outcomes(codes: &[u16]) -> Vec<Outcome> {
codes
.iter()
.map(|code| classify(&Ok(Response::new(*code))))
.collect()
}
#[test]
fn success_codes_are_sent() {
assert_eq!(outcomes(&[200, 201]), [Outcome::Sent, Outcome::Sent]);
}
#[test]
fn other_client_and_server_errors_are_rejected() {
assert_eq!(outcomes(&[400, 401, 422, 500]), [Outcome::Rejected; 4]);
}
#[test]
fn throttling_and_gateway_errors_are_retried() {
assert_eq!(outcomes(&[429, 502, 503, 504]), [Outcome::Retry(None); 4]);
}
#[test]
fn retries_wait_for_retry_after() {
assert_eq!(
classify(&Ok(Response::new(429).with_retry_after_header("60"))),
Outcome::Retry(Some(secs(60)))
);
}
#[test]
fn connection_errors_are_retried() {
assert_eq!(
classify(&Err(TransportError::new("connection refused"))),
Outcome::Retry(None)
);
}
}