use std::time::Duration;
#[derive(Debug, Clone)]
pub struct ExponentialBackoff {
current: Duration,
initial: Duration,
max: Duration,
multiplier: u32,
jitter: bool,
}
impl ExponentialBackoff {
#[must_use]
pub fn new() -> Self {
Self {
current: Duration::ZERO,
initial: Duration::from_millis(100),
max: Duration::from_secs(30),
multiplier: 2,
jitter: false,
}
}
#[must_use]
pub fn with_jitter(mut self) -> Self {
self.jitter = true;
self
}
#[must_use]
pub fn with_initial(mut self, initial: Duration) -> Self {
self.initial = initial;
self
}
#[must_use]
pub fn with_max(mut self, max: Duration) -> Self {
self.max = max;
self
}
#[must_use]
pub fn with_multiplier(mut self, multiplier: u32) -> Self {
self.multiplier = multiplier.max(1);
self
}
pub fn next_delay(&mut self) -> Duration {
if self.current.is_zero() {
self.current = self.initial;
} else {
let next_nanos = self
.current
.as_nanos()
.saturating_mul(u128::from(self.multiplier));
let max_nanos = self.max.as_nanos();
let clamped = next_nanos.min(max_nanos);
self.current = Duration::from_nanos(u64::try_from(clamped).unwrap_or(u64::MAX));
}
if self.jitter {
let nanos = u64::try_from(self.current.as_nanos()).unwrap_or(u64::MAX);
let seed = moonproof_utils::rt::SystemTime::now()
.duration_since(moonproof_utils::rt::UNIX_EPOCH)
.map_or(0, |d| u64::from(d.subsec_nanos()));
let jitter = nanos / 4;
let extra = if jitter == 0 { 0 } else { seed % jitter };
self.current
.checked_add(Duration::from_nanos(extra))
.unwrap_or(self.current)
} else {
self.current
}
}
pub fn reset(&mut self) {
self.current = Duration::ZERO;
}
#[must_use]
pub fn current(&self) -> Duration {
self.current
}
}
impl Default for ExponentialBackoff {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_call_returns_initial() {
let mut b = ExponentialBackoff::new();
assert_eq!(b.next_delay(), Duration::from_millis(100));
}
#[test]
fn doubles_each_call_up_to_cap() {
let mut b = ExponentialBackoff::new()
.with_initial(Duration::from_millis(50))
.with_max(Duration::from_millis(400));
assert_eq!(b.next_delay(), Duration::from_millis(50));
assert_eq!(b.next_delay(), Duration::from_millis(100));
assert_eq!(b.next_delay(), Duration::from_millis(200));
assert_eq!(b.next_delay(), Duration::from_millis(400));
assert_eq!(b.next_delay(), Duration::from_millis(400));
}
#[test]
fn reset_returns_to_initial() {
let mut b = ExponentialBackoff::new();
b.next_delay();
b.next_delay();
b.reset();
assert_eq!(b.current(), Duration::ZERO);
assert_eq!(b.next_delay(), Duration::from_millis(100));
}
#[test]
fn custom_multiplier_applies() {
let mut b = ExponentialBackoff::new()
.with_initial(Duration::from_millis(100))
.with_multiplier(3)
.with_max(Duration::from_secs(60));
assert_eq!(b.next_delay(), Duration::from_millis(100));
assert_eq!(b.next_delay(), Duration::from_millis(300));
assert_eq!(b.next_delay(), Duration::from_millis(900));
}
#[test]
fn jitter_stays_within_base_and_plus_25pct() {
let base = Duration::from_secs(4);
for _ in 0..64 {
let mut b = ExponentialBackoff::new()
.with_initial(base)
.with_max(base)
.with_jitter();
let d = b.next_delay();
assert!(d >= base, "jitter must not shrink the delay: {d:?}");
assert!(
d <= base + base / 4,
"jitter must not exceed +25%: {d:?} > {:?}",
base + base / 4
);
}
}
#[test]
fn jitter_still_respects_the_cap_ladder() {
let mut b = ExponentialBackoff::new()
.with_initial(Duration::from_secs(1))
.with_max(Duration::from_secs(2))
.with_jitter();
b.next_delay();
b.next_delay();
let third = b.next_delay();
assert!(third >= Duration::from_secs(2));
assert!(third <= Duration::from_secs(2) + Duration::from_millis(500));
}
}