Skip to main content

error_forge/recovery/
backoff.rs

1use std::cell::Cell;
2use std::cmp::min;
3use std::collections::hash_map::RandomState;
4use std::hash::{BuildHasher, Hasher};
5use std::time::Duration;
6
7/// A uniform value in `[0, 1)` from a per-thread xorshift64* generator.
8///
9/// Delays only need to differ between processes and threads, not to be
10/// unpredictable, so no cryptographic source is needed. Each thread seeds
11/// its generator once from the standard library's randomly keyed hasher
12/// (seeded from the operating system once per process), so two processes
13/// or threads do not share a schedule.
14fn unit_random() -> f64 {
15    thread_local! {
16        static STATE: Cell<u64> = const { Cell::new(0) };
17    }
18    STATE.with(|state| {
19        let mut x = state.get();
20        if x == 0 {
21            let mut hasher = RandomState::new().build_hasher();
22            hasher.write_usize(state as *const Cell<u64> as usize);
23            x = hasher.finish() | 1;
24        }
25        x ^= x >> 12;
26        x ^= x << 25;
27        x ^= x >> 27;
28        state.set(x);
29        // The top 53 bits of the scrambled value, as a fraction.
30        (x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64
31    })
32}
33
34/// Trait for backoff strategies used in retry mechanisms
35pub trait Backoff: Send + Sync + 'static {
36    /// Get the next delay duration based on the current attempt
37    fn next_delay(&self, attempt: usize) -> Duration;
38
39    /// Reset the backoff state
40    fn reset(&mut self) {}
41
42    /// Create a clone of this backoff strategy
43    fn box_clone(&self) -> Box<dyn Backoff>;
44}
45
46/// Exponential backoff strategy with optional jitter
47///
48/// This strategy increases the delay exponentially with each attempt,
49/// and can add random jitter to prevent multiple retries from synchronizing.
50#[derive(Clone)]
51pub struct ExponentialBackoff {
52    initial_delay_ms: u64,
53    max_delay_ms: u64,
54    factor: f64,
55    jitter: bool,
56}
57
58impl ExponentialBackoff {
59    /// Create a new exponential backoff with default settings
60    ///
61    /// Defaults:
62    /// - Initial delay: 100ms
63    /// - Max delay: 30000ms (30 seconds)
64    /// - Factor: 2.0 (doubles with each attempt)
65    /// - Jitter: false
66    pub fn new() -> Self {
67        Self {
68            initial_delay_ms: 100,
69            max_delay_ms: 30000,
70            factor: 2.0,
71            jitter: false,
72        }
73    }
74
75    /// Set the initial delay in milliseconds
76    pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
77        self.initial_delay_ms = delay_ms;
78        self
79    }
80
81    /// Set the maximum delay in milliseconds
82    pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
83        self.max_delay_ms = delay_ms;
84        self
85    }
86
87    /// Set the multiplication factor for each attempt
88    pub fn with_factor(mut self, factor: f64) -> Self {
89        self.factor = factor;
90        self
91    }
92
93    /// Enable or disable ±20% jitter on each calculated delay.
94    ///
95    /// Jitter applies to every attempt, including the first. Each delay
96    /// is drawn uniformly from 80% to 120% of the calculated delay, and
97    /// never above the maximum delay: once the calculated delay nears the
98    /// maximum, the upper end of the range is the maximum itself, so
99    /// delays at the cap stay spread out instead of landing on it.
100    ///
101    /// Off by default. Since 1.2.0 jitter works with or without the
102    /// `jitter` cargo feature (it no longer needs `rand`); the feature
103    /// now turns jitter on by default for the exponential
104    /// [`RetryExecutor`](crate::recovery::RetryExecutor) and
105    /// [`RetryPolicy`](crate::recovery::RetryPolicy).
106    ///
107    /// # Example
108    ///
109    /// ```
110    /// use error_forge::recovery::{Backoff, ExponentialBackoff};
111    /// use std::time::Duration;
112    ///
113    /// let backoff = ExponentialBackoff::new().with_jitter(true);
114    /// let delay = backoff.next_delay(0); // around the 100 ms initial delay
115    /// assert!(delay >= Duration::from_millis(80) && delay <= Duration::from_millis(120));
116    /// ```
117    pub fn with_jitter(mut self, jitter: bool) -> Self {
118        self.jitter = jitter;
119        self
120    }
121}
122
123impl Backoff for ExponentialBackoff {
124    fn next_delay(&self, attempt: usize) -> Duration {
125        // Attempt 0 is the initial delay, kept in integer arithmetic so
126        // large values do not lose precision. Like every other attempt
127        // it is capped at `max_delay_ms`.
128        let calculated_delay = if attempt == 0 {
129            self.initial_delay_ms
130        } else {
131            // Attempts beyond `i32::MAX` clamp instead of wrapping to a
132            // negative exponent. The float-to-int cast saturates, so an
133            // infinite product lands on the cap.
134            let exponent = i32::try_from(attempt).unwrap_or(i32::MAX);
135            let exp_factor = self.factor.powi(exponent);
136            (self.initial_delay_ms as f64 * exp_factor) as u64
137        };
138        let capped_delay = min(calculated_delay, self.max_delay_ms);
139
140        if self.jitter {
141            // Uniform over [0.8 x delay, min(1.2 x delay, max)]: below the
142            // cap rather than clamped onto it, so delays at the cap do not
143            // pile up on one instant.
144            let low = capped_delay as f64 * 0.8;
145            let high = (capped_delay as f64 * 1.2).min(self.max_delay_ms as f64);
146            let jittered = low + (high - low).max(0.0) * unit_random();
147            return Duration::from_millis(min(jittered as u64, self.max_delay_ms));
148        }
149
150        Duration::from_millis(capped_delay)
151    }
152
153    fn box_clone(&self) -> Box<dyn Backoff> {
154        Box::new(self.clone())
155    }
156}
157
158/// Linear backoff strategy
159///
160/// Increases delay linearly by adding a fixed increment with each attempt.
161#[derive(Clone)]
162pub struct LinearBackoff {
163    initial_delay_ms: u64,
164    increment_ms: u64,
165    max_delay_ms: u64,
166}
167
168impl LinearBackoff {
169    /// Create a new linear backoff with default settings
170    ///
171    /// Defaults:
172    /// - Initial delay: 100ms
173    /// - Increment: 100ms (adds 100ms per attempt)
174    /// - Max delay: 10000ms (10 seconds)
175    pub fn new() -> Self {
176        Self {
177            initial_delay_ms: 100,
178            increment_ms: 100,
179            max_delay_ms: 10000,
180        }
181    }
182
183    /// Set the initial delay in milliseconds
184    pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
185        self.initial_delay_ms = delay_ms;
186        self
187    }
188
189    /// Set the increment in milliseconds
190    pub fn with_increment(mut self, increment_ms: u64) -> Self {
191        self.increment_ms = increment_ms;
192        self
193    }
194
195    /// Set the maximum delay in milliseconds
196    pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
197        self.max_delay_ms = delay_ms;
198        self
199    }
200}
201
202impl Backoff for LinearBackoff {
203    fn next_delay(&self, attempt: usize) -> Duration {
204        // Saturate so large attempts or increments hit the cap instead
205        // of overflowing (a panic in debug builds, a wrap in release).
206        let attempt = u64::try_from(attempt).unwrap_or(u64::MAX);
207        let delay_ms = self
208            .initial_delay_ms
209            .saturating_add(attempt.saturating_mul(self.increment_ms));
210        let capped_delay = min(delay_ms, self.max_delay_ms);
211        Duration::from_millis(capped_delay)
212    }
213
214    fn box_clone(&self) -> Box<dyn Backoff> {
215        Box::new(self.clone())
216    }
217}
218
219/// Fixed backoff strategy
220///
221/// Uses the same delay for all retry attempts.
222#[derive(Clone)]
223pub struct FixedBackoff {
224    delay_ms: u64,
225}
226
227impl FixedBackoff {
228    /// Create a new fixed backoff with the given delay
229    pub fn new(delay_ms: u64) -> Self {
230        Self { delay_ms }
231    }
232}
233
234impl Backoff for FixedBackoff {
235    fn next_delay(&self, _attempt: usize) -> Duration {
236        Duration::from_millis(self.delay_ms)
237    }
238
239    fn box_clone(&self) -> Box<dyn Backoff> {
240        Box::new(self.clone())
241    }
242}
243
244impl Default for ExponentialBackoff {
245    fn default() -> Self {
246        Self::new()
247    }
248}
249
250impl Default for LinearBackoff {
251    fn default() -> Self {
252        Self::new()
253    }
254}
255
256// Implement Backoff for Box<dyn Backoff> to enable boxed trait objects
257impl Backoff for Box<dyn Backoff> {
258    fn next_delay(&self, attempt: usize) -> Duration {
259        (**self).next_delay(attempt)
260    }
261
262    fn reset(&mut self) {
263        (**self).reset()
264    }
265
266    fn box_clone(&self) -> Box<dyn Backoff> {
267        (**self).box_clone()
268    }
269}
270
271#[cfg(test)]
272mod jitter_tests {
273    use super::*;
274
275    #[test]
276    fn jitter_spreads_below_the_cap_instead_of_piling_on_it() {
277        let backoff = ExponentialBackoff::new()
278            .with_max_delay(30_000)
279            .with_jitter(true);
280        let draws: Vec<Duration> = (0..10_000).map(|_| backoff.next_delay(20)).collect();
281        let at_cap = draws
282            .iter()
283            .filter(|d| **d == Duration::from_millis(30_000))
284            .count();
285        // 1.1.0 put about half of all draws exactly on the cap.
286        assert!(at_cap < 100, "{at_cap} of 10000 draws exactly at the cap");
287        assert!(draws
288            .iter()
289            .all(|d| *d >= Duration::from_millis(24_000) && *d <= Duration::from_millis(30_000)));
290    }
291
292    #[test]
293    fn jitter_varies_between_draws_and_stays_in_band() {
294        let backoff = ExponentialBackoff::new().with_jitter(true);
295        let draws: std::collections::HashSet<Duration> =
296            (0..200).map(|_| backoff.next_delay(1)).collect();
297        assert!(
298            draws.len() > 10,
299            "jitter produced {} distinct delays",
300            draws.len()
301        );
302        for d in draws {
303            assert!(d >= Duration::from_millis(160) && d <= Duration::from_millis(240));
304        }
305    }
306
307    #[test]
308    fn unit_random_is_in_range() {
309        for _ in 0..10_000 {
310            let x = unit_random();
311            assert!((0.0..1.0).contains(&x));
312        }
313    }
314}