use std::cell::Cell;
use std::cmp::min;
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
use std::time::Duration;
fn unit_random() -> f64 {
thread_local! {
static STATE: Cell<u64> = const { Cell::new(0) };
}
STATE.with(|state| {
let mut x = state.get();
if x == 0 {
let mut hasher = RandomState::new().build_hasher();
hasher.write_usize(state as *const Cell<u64> as usize);
x = hasher.finish() | 1;
}
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
state.set(x);
(x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64
})
}
pub trait Backoff: Send + Sync + 'static {
fn next_delay(&self, attempt: usize) -> Duration;
fn reset(&mut self) {}
fn box_clone(&self) -> Box<dyn Backoff>;
}
#[derive(Clone)]
pub struct ExponentialBackoff {
initial_delay_ms: u64,
max_delay_ms: u64,
factor: f64,
jitter: bool,
}
impl ExponentialBackoff {
pub fn new() -> Self {
Self {
initial_delay_ms: 100,
max_delay_ms: 30000,
factor: 2.0,
jitter: false,
}
}
pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
self.initial_delay_ms = delay_ms;
self
}
pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
self.max_delay_ms = delay_ms;
self
}
pub fn with_factor(mut self, factor: f64) -> Self {
self.factor = factor;
self
}
pub fn with_jitter(mut self, jitter: bool) -> Self {
self.jitter = jitter;
self
}
}
impl Backoff for ExponentialBackoff {
fn next_delay(&self, attempt: usize) -> Duration {
let calculated_delay = if attempt == 0 {
self.initial_delay_ms
} else {
let exponent = i32::try_from(attempt).unwrap_or(i32::MAX);
let exp_factor = self.factor.powi(exponent);
(self.initial_delay_ms as f64 * exp_factor) as u64
};
let capped_delay = min(calculated_delay, self.max_delay_ms);
if self.jitter {
let low = capped_delay as f64 * 0.8;
let high = (capped_delay as f64 * 1.2).min(self.max_delay_ms as f64);
let jittered = low + (high - low).max(0.0) * unit_random();
return Duration::from_millis(min(jittered as u64, self.max_delay_ms));
}
Duration::from_millis(capped_delay)
}
fn box_clone(&self) -> Box<dyn Backoff> {
Box::new(self.clone())
}
}
#[derive(Clone)]
pub struct LinearBackoff {
initial_delay_ms: u64,
increment_ms: u64,
max_delay_ms: u64,
}
impl LinearBackoff {
pub fn new() -> Self {
Self {
initial_delay_ms: 100,
increment_ms: 100,
max_delay_ms: 10000,
}
}
pub fn with_initial_delay(mut self, delay_ms: u64) -> Self {
self.initial_delay_ms = delay_ms;
self
}
pub fn with_increment(mut self, increment_ms: u64) -> Self {
self.increment_ms = increment_ms;
self
}
pub fn with_max_delay(mut self, delay_ms: u64) -> Self {
self.max_delay_ms = delay_ms;
self
}
}
impl Backoff for LinearBackoff {
fn next_delay(&self, attempt: usize) -> Duration {
let attempt = u64::try_from(attempt).unwrap_or(u64::MAX);
let delay_ms = self
.initial_delay_ms
.saturating_add(attempt.saturating_mul(self.increment_ms));
let capped_delay = min(delay_ms, self.max_delay_ms);
Duration::from_millis(capped_delay)
}
fn box_clone(&self) -> Box<dyn Backoff> {
Box::new(self.clone())
}
}
#[derive(Clone)]
pub struct FixedBackoff {
delay_ms: u64,
}
impl FixedBackoff {
pub fn new(delay_ms: u64) -> Self {
Self { delay_ms }
}
}
impl Backoff for FixedBackoff {
fn next_delay(&self, _attempt: usize) -> Duration {
Duration::from_millis(self.delay_ms)
}
fn box_clone(&self) -> Box<dyn Backoff> {
Box::new(self.clone())
}
}
impl Default for ExponentialBackoff {
fn default() -> Self {
Self::new()
}
}
impl Default for LinearBackoff {
fn default() -> Self {
Self::new()
}
}
impl Backoff for Box<dyn Backoff> {
fn next_delay(&self, attempt: usize) -> Duration {
(**self).next_delay(attempt)
}
fn reset(&mut self) {
(**self).reset()
}
fn box_clone(&self) -> Box<dyn Backoff> {
(**self).box_clone()
}
}
#[cfg(test)]
mod jitter_tests {
use super::*;
#[test]
fn jitter_spreads_below_the_cap_instead_of_piling_on_it() {
let backoff = ExponentialBackoff::new()
.with_max_delay(30_000)
.with_jitter(true);
let draws: Vec<Duration> = (0..10_000).map(|_| backoff.next_delay(20)).collect();
let at_cap = draws
.iter()
.filter(|d| **d == Duration::from_millis(30_000))
.count();
assert!(at_cap < 100, "{at_cap} of 10000 draws exactly at the cap");
assert!(draws
.iter()
.all(|d| *d >= Duration::from_millis(24_000) && *d <= Duration::from_millis(30_000)));
}
#[test]
fn jitter_varies_between_draws_and_stays_in_band() {
let backoff = ExponentialBackoff::new().with_jitter(true);
let draws: std::collections::HashSet<Duration> =
(0..200).map(|_| backoff.next_delay(1)).collect();
assert!(
draws.len() > 10,
"jitter produced {} distinct delays",
draws.len()
);
for d in draws {
assert!(d >= Duration::from_millis(160) && d <= Duration::from_millis(240));
}
}
#[test]
fn unit_random_is_in_range() {
for _ in 0..10_000 {
let x = unit_random();
assert!((0.0..1.0).contains(&x));
}
}
}