use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};
#[derive(Debug)]
struct State {
cur: Duration,
next_allowed: Option<Instant>,
}
#[derive(Debug)]
pub struct IdleBackoff {
base: Duration,
max: Duration,
state: Mutex<State>,
}
impl IdleBackoff {
pub fn new(base: Duration, max: Duration) -> Self {
let base = if base.is_zero() { Duration::from_secs(1) } else { base };
let max = max.max(base);
Self {
base,
max,
state: Mutex::new(State {
cur: Duration::ZERO,
next_allowed: None,
}),
}
}
fn state(&self) -> std::sync::MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn should_run(&self) -> bool {
self.state().next_allowed.is_none_or(|t| Instant::now() >= t)
}
pub fn hit(&self) {
let mut s = self.state();
s.cur = Duration::ZERO;
s.next_allowed = None;
}
pub fn miss(&self) {
let mut s = self.state();
s.cur = if s.cur.is_zero() {
self.base
} else {
s.cur.saturating_mul(2).min(self.max)
};
let now = Instant::now();
s.next_allowed = Some(
now.checked_add(s.cur)
.unwrap_or_else(|| now + Duration::from_secs(365 * 86400)),
);
}
pub fn reset(&self) {
self.hit();
}
pub fn current(&self) -> Duration {
self.state().cur
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grows_and_caps() {
let b = IdleBackoff::new(Duration::from_millis(100), Duration::from_millis(350));
assert!(b.should_run());
let mut seen = vec![];
for _ in 0..5 {
b.miss();
seen.push(b.current().as_millis());
}
assert_eq!(seen, [100, 200, 350, 350, 350]);
assert!(!b.should_run());
b.hit();
assert!(b.should_run());
assert_eq!(b.current(), Duration::ZERO);
b.miss();
assert_eq!(b.current(), Duration::from_millis(100));
b.reset();
assert!(b.should_run());
}
#[test]
fn window_expires() {
let b = IdleBackoff::new(Duration::from_millis(20), Duration::from_secs(1));
b.miss();
assert!(!b.should_run());
std::thread::sleep(Duration::from_millis(30));
assert!(b.should_run());
}
#[test]
fn normalizes_args() {
let b = IdleBackoff::new(Duration::ZERO, Duration::ZERO);
b.miss();
assert_eq!(b.current(), Duration::from_secs(1));
b.miss();
assert_eq!(b.current(), Duration::from_secs(1));
}
}