Skip to main content

one/
retry.rs

1use std::{fmt::Display, future::Future, time::Duration};
2
3use tokio::time::sleep;
4
5/// Marker trait for errors that can be classified as transient — eligible for
6/// automatic retry — versus structural, where retrying is wasted work. This is
7/// the *general* classifier used by [`WithRetry`]; HTTP status classification
8/// (`retry_on`, `Retry-After`) is a separate concern that lives on the call.
9pub trait Retryable {
10    /// `true` if the failure is expected to resolve on a fresh attempt
11    /// (network drop, timeout, 5xx, 429); `false` if structural (4xx, decode).
12    fn is_transient(&self) -> bool;
13}
14
15/// Bounded exponential-backoff schedule — the shared *timing* vocabulary for
16/// retries, used by both the call engine and (later) webhook handler retry.
17/// It holds no HTTP concepts: per-attempt delay doubles up to `max_delay` and
18/// total attempts are capped by `max_attempts`.
19#[derive(Clone, Copy, Debug)]
20pub struct RetrySchedule {
21    pub max_attempts:  u32,
22    pub initial_delay: Duration,
23    pub max_delay:     Duration
24}
25
26impl RetrySchedule {
27    /// No retries: a single attempt.
28    pub const fn none() -> Self {
29        Self {
30            max_attempts:  1,
31            initial_delay: Duration::ZERO,
32            max_delay:     Duration::ZERO
33        }
34    }
35
36    /// Conservative default for transient errors: 3 attempts, 100ms → 200ms →
37    /// 400ms (cap 1s).
38    pub const fn transient() -> Self {
39        Self {
40            max_attempts:  3,
41            initial_delay: Duration::from_millis(100),
42            max_delay:     Duration::from_secs(1)
43        }
44    }
45
46    /// Sets the maximum number of attempts — a chainable tweak over a preset.
47    pub fn attempts(mut self, max_attempts: u32) -> Self {
48        self.max_attempts = max_attempts;
49        self
50    }
51
52    /// Sets the initial and maximum backoff delays.
53    pub fn backoff(mut self, initial: Duration, max: Duration) -> Self {
54        self.initial_delay = initial;
55        self.max_delay = max;
56        self
57    }
58
59    /// The backoff delay before retrying after the given 1-based `attempt`:
60    /// `initial_delay * 2^(attempt - 1)`, capped at `max_delay`.
61    pub fn delay(&self, attempt: u32) -> Duration {
62        let factor = 1u32.checked_shl(attempt.saturating_sub(1)).unwrap_or(u32::MAX);
63        self.initial_delay.saturating_mul(factor).min(self.max_delay)
64    }
65}
66
67impl Default for RetrySchedule {
68    fn default() -> Self {
69        Self::transient()
70    }
71}
72
73/// Postfix retry combinator over an async operation **factory** — the general
74/// retry engine (e.g. for retrying a whole webhook handler). The receiver must
75/// be a factory (`FnMut() -> Future`) rather than a `Future`, because a
76/// `Future` is single-use — every retry attempt needs a freshly-produced one.
77///
78/// ```ignore
79/// (|| handler())
80///     .with_retry(RetrySchedule::transient())
81///     .await
82/// ```
83///
84/// Behaviour: up to `schedule.max_attempts` attempts. On `Ok`, returns
85/// immediately. On `Err` whose [`Retryable::is_transient`] is `false`, returns
86/// immediately. On transient `Err`, sleeps the schedule's backoff and retries;
87/// the last attempt's error is returned if all fail.
88pub trait WithRetry<T, E>: Sized {
89    fn with_retry(self, schedule: RetrySchedule) -> impl Future<Output = Result<T, E>> + Send
90    where
91        Self: Send,
92        T: Send,
93        E: Send;
94}
95
96impl<F, Fut, T, E> WithRetry<T, E> for F
97where
98    F: FnMut() -> Fut,
99    Fut: Future<Output = Result<T, E>> + Send,
100    E: Retryable + Display
101{
102    async fn with_retry(mut self, schedule: RetrySchedule) -> Result<T, E>
103    where
104        Self: Send,
105        T: Send,
106        E: Send
107    {
108        for attempt in 1..=schedule.max_attempts {
109            match self().await {
110                Ok(v) => return Ok(v),
111                Err(e) if !e.is_transient() => return Err(e),
112                Err(e) => {
113                    if attempt == schedule.max_attempts {
114                        return Err(e);
115                    }
116                    sleep(schedule.delay(attempt)).await;
117                }
118            }
119        }
120        unreachable!("loop exits via return on every iteration")
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use std::{
127        fmt,
128        sync::atomic::{AtomicUsize, Ordering}
129    };
130
131    use super::*;
132
133    #[derive(Debug)]
134    enum FakeError {
135        Transient,
136        Permanent
137    }
138
139    impl Display for FakeError {
140        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141            match self {
142                Self::Transient => f.write_str("transient"),
143                Self::Permanent => f.write_str("permanent")
144            }
145        }
146    }
147
148    impl Retryable for FakeError {
149        fn is_transient(&self) -> bool {
150            matches!(self, Self::Transient)
151        }
152    }
153
154    fn fast_schedule() -> RetrySchedule {
155        RetrySchedule::transient()
156            .attempts(5)
157            .backoff(Duration::from_millis(1), Duration::from_millis(2))
158    }
159
160    #[test]
161    fn test_retry_backoff_doubles_then_caps() {
162        let schedule = RetrySchedule::transient()
163            .attempts(6)
164            .backoff(Duration::from_millis(100), Duration::from_millis(400));
165        assert_eq!(schedule.delay(1), Duration::from_millis(100));
166        assert_eq!(schedule.delay(2), Duration::from_millis(200));
167        assert_eq!(schedule.delay(3), Duration::from_millis(400));
168        assert_eq!(schedule.delay(4), Duration::from_millis(400), "capped at max_delay");
169        assert_eq!(schedule.delay(99), Duration::from_millis(400), "no overflow at large attempts");
170    }
171
172    #[test]
173    fn test_retry_default_is_transient() {
174        assert_eq!(RetrySchedule::default().max_attempts, RetrySchedule::transient().max_attempts);
175    }
176
177    #[tokio::test]
178    async fn test_retry_returns_on_first_success() {
179        let calls = AtomicUsize::new(0);
180        let result: Result<u32, FakeError> = (|| async {
181            calls.fetch_add(1, Ordering::SeqCst);
182            Ok(42)
183        })
184        .with_retry(fast_schedule())
185        .await;
186        assert_eq!(result.unwrap(), 42);
187        assert_eq!(calls.load(Ordering::SeqCst), 1);
188    }
189
190    #[tokio::test]
191    async fn test_retry_eventually_succeeds_after_transient_errors() {
192        let calls = AtomicUsize::new(0);
193        let result: Result<u32, FakeError> = (|| async {
194            let n = calls.fetch_add(1, Ordering::SeqCst) + 1;
195            if n < 3 { Err(FakeError::Transient) } else { Ok(7) }
196        })
197        .with_retry(fast_schedule())
198        .await;
199        assert_eq!(result.unwrap(), 7, "succeeds on 3rd attempt");
200        assert_eq!(calls.load(Ordering::SeqCst), 3);
201    }
202
203    #[tokio::test]
204    async fn test_retry_exhausts_attempts_and_returns_last_transient_error() {
205        let calls = AtomicUsize::new(0);
206        let result: Result<u32, FakeError> = (|| async {
207            calls.fetch_add(1, Ordering::SeqCst);
208            Err(FakeError::Transient)
209        })
210        .with_retry(fast_schedule())
211        .await;
212        assert!(matches!(result, Err(FakeError::Transient)));
213        assert_eq!(calls.load(Ordering::SeqCst), 5, "exhausts max_attempts");
214    }
215
216    #[tokio::test]
217    async fn test_retry_bails_immediately_on_non_transient_error() {
218        let calls = AtomicUsize::new(0);
219        let result: Result<u32, FakeError> = (|| async {
220            calls.fetch_add(1, Ordering::SeqCst);
221            Err(FakeError::Permanent)
222        })
223        .with_retry(fast_schedule())
224        .await;
225        assert!(matches!(result, Err(FakeError::Permanent)));
226        assert_eq!(calls.load(Ordering::SeqCst), 1, "no retry on permanent error");
227    }
228}