error_forge/recovery/
backoff.rs1use std::cell::Cell;
2use std::cmp::min;
3use std::collections::hash_map::RandomState;
4use std::hash::{BuildHasher, Hasher};
5use std::time::Duration;
6
7fn 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 (x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64
31 })
32}
33
34pub trait Backoff: Send + Sync + 'static {
36 fn next_delay(&self, attempt: usize) -> Duration;
38
39 fn reset(&mut self) {}
41
42 fn box_clone(&self) -> Box<dyn Backoff>;
44}
45
46#[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 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 pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
77 self.initial_delay_ms = delay_ms;
78 self
79 }
80
81 pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
83 self.max_delay_ms = delay_ms;
84 self
85 }
86
87 pub fn with_factor(mut self, factor: f64) -> Self {
89 self.factor = factor;
90 self
91 }
92
93 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 let calculated_delay = if attempt == 0 {
129 self.initial_delay_ms
130 } else {
131 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 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#[derive(Clone)]
162pub struct LinearBackoff {
163 initial_delay_ms: u64,
164 increment_ms: u64,
165 max_delay_ms: u64,
166}
167
168impl LinearBackoff {
169 pub fn new() -> Self {
176 Self {
177 initial_delay_ms: 100,
178 increment_ms: 100,
179 max_delay_ms: 10000,
180 }
181 }
182
183 pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
185 self.initial_delay_ms = delay_ms;
186 self
187 }
188
189 pub fn with_increment(mut self, increment_ms: u64) -> Self {
191 self.increment_ms = increment_ms;
192 self
193 }
194
195 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 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#[derive(Clone)]
223pub struct FixedBackoff {
224 delay_ms: u64,
225}
226
227impl FixedBackoff {
228 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
256impl 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 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}