use std::{fmt::Display, future::Future, time::Duration};
use tokio::time::sleep;
pub trait Retryable {
fn is_transient(&self) -> bool;
}
#[derive(Clone, Copy, Debug)]
pub struct RetrySchedule {
pub max_attempts: u32,
pub initial_delay: Duration,
pub max_delay: Duration
}
impl RetrySchedule {
pub const fn none() -> Self {
Self {
max_attempts: 1,
initial_delay: Duration::ZERO,
max_delay: Duration::ZERO
}
}
pub const fn transient() -> Self {
Self {
max_attempts: 3,
initial_delay: Duration::from_millis(100),
max_delay: Duration::from_secs(1)
}
}
pub fn attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = max_attempts;
self
}
pub fn backoff(mut self, initial: Duration, max: Duration) -> Self {
self.initial_delay = initial;
self.max_delay = max;
self
}
pub fn delay(&self, attempt: u32) -> Duration {
let factor = 1u32.checked_shl(attempt.saturating_sub(1)).unwrap_or(u32::MAX);
self.initial_delay.saturating_mul(factor).min(self.max_delay)
}
}
impl Default for RetrySchedule {
fn default() -> Self {
Self::transient()
}
}
pub trait WithRetry<T, E>: Sized {
fn with_retry(self, schedule: RetrySchedule) -> impl Future<Output = Result<T, E>> + Send
where
Self: Send,
T: Send,
E: Send;
}
impl<F, Fut, T, E> WithRetry<T, E> for F
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<T, E>> + Send,
E: Retryable + Display
{
async fn with_retry(mut self, schedule: RetrySchedule) -> Result<T, E>
where
Self: Send,
T: Send,
E: Send
{
for attempt in 1..=schedule.max_attempts {
match self().await {
Ok(v) => return Ok(v),
Err(e) if !e.is_transient() => return Err(e),
Err(e) => {
if attempt == schedule.max_attempts {
return Err(e);
}
sleep(schedule.delay(attempt)).await;
}
}
}
unreachable!("loop exits via return on every iteration")
}
}
#[cfg(test)]
mod tests {
use std::{
fmt,
sync::atomic::{AtomicUsize, Ordering}
};
use super::*;
#[derive(Debug)]
enum FakeError {
Transient,
Permanent
}
impl Display for FakeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Transient => f.write_str("transient"),
Self::Permanent => f.write_str("permanent")
}
}
}
impl Retryable for FakeError {
fn is_transient(&self) -> bool {
matches!(self, Self::Transient)
}
}
fn fast_schedule() -> RetrySchedule {
RetrySchedule::transient()
.attempts(5)
.backoff(Duration::from_millis(1), Duration::from_millis(2))
}
#[test]
fn test_retry_backoff_doubles_then_caps() {
let schedule = RetrySchedule::transient()
.attempts(6)
.backoff(Duration::from_millis(100), Duration::from_millis(400));
assert_eq!(schedule.delay(1), Duration::from_millis(100));
assert_eq!(schedule.delay(2), Duration::from_millis(200));
assert_eq!(schedule.delay(3), Duration::from_millis(400));
assert_eq!(schedule.delay(4), Duration::from_millis(400), "capped at max_delay");
assert_eq!(schedule.delay(99), Duration::from_millis(400), "no overflow at large attempts");
}
#[test]
fn test_retry_default_is_transient() {
assert_eq!(RetrySchedule::default().max_attempts, RetrySchedule::transient().max_attempts);
}
#[tokio::test]
async fn test_retry_returns_on_first_success() {
let calls = AtomicUsize::new(0);
let result: Result<u32, FakeError> = (|| async {
calls.fetch_add(1, Ordering::SeqCst);
Ok(42)
})
.with_retry(fast_schedule())
.await;
assert_eq!(result.unwrap(), 42);
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn test_retry_eventually_succeeds_after_transient_errors() {
let calls = AtomicUsize::new(0);
let result: Result<u32, FakeError> = (|| async {
let n = calls.fetch_add(1, Ordering::SeqCst) + 1;
if n < 3 { Err(FakeError::Transient) } else { Ok(7) }
})
.with_retry(fast_schedule())
.await;
assert_eq!(result.unwrap(), 7, "succeeds on 3rd attempt");
assert_eq!(calls.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn test_retry_exhausts_attempts_and_returns_last_transient_error() {
let calls = AtomicUsize::new(0);
let result: Result<u32, FakeError> = (|| async {
calls.fetch_add(1, Ordering::SeqCst);
Err(FakeError::Transient)
})
.with_retry(fast_schedule())
.await;
assert!(matches!(result, Err(FakeError::Transient)));
assert_eq!(calls.load(Ordering::SeqCst), 5, "exhausts max_attempts");
}
#[tokio::test]
async fn test_retry_bails_immediately_on_non_transient_error() {
let calls = AtomicUsize::new(0);
let result: Result<u32, FakeError> = (|| async {
calls.fetch_add(1, Ordering::SeqCst);
Err(FakeError::Permanent)
})
.with_retry(fast_schedule())
.await;
assert!(matches!(result, Err(FakeError::Permanent)));
assert_eq!(calls.load(Ordering::SeqCst), 1, "no retry on permanent error");
}
}