Skip to main content

error_forge/recovery/
backoff.rs

1#[cfg(feature = "jitter")]
2use rand::Rng;
3use std::cmp::min;
4use std::time::Duration;
5
6/// Trait for backoff strategies used in retry mechanisms
7pub trait Backoff: Send + Sync + 'static {
8    /// Get the next delay duration based on the current attempt
9    fn next_delay(&self, attempt: usize) -> Duration;
10
11    /// Reset the backoff state
12    fn reset(&mut self) {}
13
14    /// Create a clone of this backoff strategy
15    fn box_clone(&self) -> Box<dyn Backoff>;
16}
17
18/// Exponential backoff strategy with optional jitter
19///
20/// This strategy increases the delay exponentially with each attempt,
21/// and can add random jitter to prevent multiple retries from synchronizing.
22#[derive(Clone)]
23pub struct ExponentialBackoff {
24    initial_delay_ms: u64,
25    max_delay_ms: u64,
26    factor: f64,
27    jitter: bool,
28}
29
30impl ExponentialBackoff {
31    /// Create a new exponential backoff with default settings
32    ///
33    /// Defaults:
34    /// - Initial delay: 100ms
35    /// - Max delay: 30000ms (30 seconds)
36    /// - Factor: 2.0 (doubles with each attempt)
37    /// - Jitter: false
38    pub fn new() -> Self {
39        Self {
40            initial_delay_ms: 100,
41            max_delay_ms: 30000,
42            factor: 2.0,
43            jitter: false,
44        }
45    }
46
47    /// Set the initial delay in milliseconds
48    pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
49        self.initial_delay_ms = delay_ms;
50        self
51    }
52
53    /// Set the maximum delay in milliseconds
54    pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
55        self.max_delay_ms = delay_ms;
56        self
57    }
58
59    /// Set the multiplication factor for each attempt
60    pub fn with_factor(mut self, factor: f64) -> Self {
61        self.factor = factor;
62        self
63    }
64
65    /// Enable or disable ±20% jitter on each calculated delay.
66    ///
67    /// Jitter applies to every attempt, including the first, and the
68    /// jittered delay is still capped at the maximum delay.
69    ///
70    /// Jitter requires the `jitter` cargo feature; without it the
71    /// flag is silently ignored and every delay is the
72    /// non-jittered exponential value. Off by default.
73    pub fn with_jitter(mut self, jitter: bool) -> Self {
74        self.jitter = jitter;
75        self
76    }
77}
78
79impl Backoff for ExponentialBackoff {
80    fn next_delay(&self, attempt: usize) -> Duration {
81        // Attempt 0 is the initial delay, kept in integer arithmetic so
82        // large values do not lose precision. Like every other attempt
83        // it is capped at `max_delay_ms`.
84        let calculated_delay = if attempt == 0 {
85            self.initial_delay_ms
86        } else {
87            // Attempts beyond `i32::MAX` clamp instead of wrapping to a
88            // negative exponent. The float-to-int cast saturates, so an
89            // infinite product lands on the cap.
90            let exponent = i32::try_from(attempt).unwrap_or(i32::MAX);
91            let exp_factor = self.factor.powi(exponent);
92            (self.initial_delay_ms as f64 * exp_factor) as u64
93        };
94        let capped_delay = min(calculated_delay, self.max_delay_ms);
95
96        // Jitter is only applied when both the `jitter` cargo feature
97        // is enabled AND the caller flipped `self.jitter = true`. With
98        // the feature off, jitter is a documented no-op so users who
99        // never want jitter avoid pulling in `rand`.
100        #[cfg(feature = "jitter")]
101        if self.jitter {
102            let mut rng = rand::thread_rng();
103            let jitter_factor = rng.gen_range(0.8..1.2);
104            let jittered_delay = (capped_delay as f64 * jitter_factor) as u64;
105            // Jitter never pushes the delay past the configured cap.
106            return Duration::from_millis(min(jittered_delay, self.max_delay_ms));
107        }
108
109        Duration::from_millis(capped_delay)
110    }
111
112    fn box_clone(&self) -> Box<dyn Backoff> {
113        Box::new(self.clone())
114    }
115}
116
117/// Linear backoff strategy
118///
119/// Increases delay linearly by adding a fixed increment with each attempt.
120#[derive(Clone)]
121pub struct LinearBackoff {
122    initial_delay_ms: u64,
123    increment_ms: u64,
124    max_delay_ms: u64,
125}
126
127impl LinearBackoff {
128    /// Create a new linear backoff with default settings
129    ///
130    /// Defaults:
131    /// - Initial delay: 100ms
132    /// - Increment: 100ms (adds 100ms per attempt)
133    /// - Max delay: 10000ms (10 seconds)
134    pub fn new() -> Self {
135        Self {
136            initial_delay_ms: 100,
137            increment_ms: 100,
138            max_delay_ms: 10000,
139        }
140    }
141
142    /// Set the initial delay in milliseconds
143    pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
144        self.initial_delay_ms = delay_ms;
145        self
146    }
147
148    /// Set the increment in milliseconds
149    pub fn with_increment(mut self, increment_ms: u64) -> Self {
150        self.increment_ms = increment_ms;
151        self
152    }
153
154    /// Set the maximum delay in milliseconds
155    pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
156        self.max_delay_ms = delay_ms;
157        self
158    }
159}
160
161impl Backoff for LinearBackoff {
162    fn next_delay(&self, attempt: usize) -> Duration {
163        // Saturate so large attempts or increments hit the cap instead
164        // of overflowing (a panic in debug builds, a wrap in release).
165        let attempt = u64::try_from(attempt).unwrap_or(u64::MAX);
166        let delay_ms = self
167            .initial_delay_ms
168            .saturating_add(attempt.saturating_mul(self.increment_ms));
169        let capped_delay = min(delay_ms, self.max_delay_ms);
170        Duration::from_millis(capped_delay)
171    }
172
173    fn box_clone(&self) -> Box<dyn Backoff> {
174        Box::new(self.clone())
175    }
176}
177
178/// Fixed backoff strategy
179///
180/// Uses the same delay for all retry attempts.
181#[derive(Clone)]
182pub struct FixedBackoff {
183    delay_ms: u64,
184}
185
186impl FixedBackoff {
187    /// Create a new fixed backoff with the given delay
188    pub fn new(delay_ms: u64) -> Self {
189        Self { delay_ms }
190    }
191}
192
193impl Backoff for FixedBackoff {
194    fn next_delay(&self, _attempt: usize) -> Duration {
195        Duration::from_millis(self.delay_ms)
196    }
197
198    fn box_clone(&self) -> Box<dyn Backoff> {
199        Box::new(self.clone())
200    }
201}
202
203impl Default for ExponentialBackoff {
204    fn default() -> Self {
205        Self::new()
206    }
207}
208
209impl Default for LinearBackoff {
210    fn default() -> Self {
211        Self::new()
212    }
213}
214
215// Implement Backoff for Box<dyn Backoff> to enable boxed trait objects
216impl Backoff for Box<dyn Backoff> {
217    fn next_delay(&self, attempt: usize) -> Duration {
218        (**self).next_delay(attempt)
219    }
220
221    fn reset(&mut self) {
222        (**self).reset()
223    }
224
225    fn box_clone(&self) -> Box<dyn Backoff> {
226        (**self).box_clone()
227    }
228}