rust_web_utils/cronutil/
backoff.rs1use std::sync::{Mutex, PoisonError};
2use std::time::{Duration, Instant};
3
4#[derive(Debug)]
5struct State {
6 cur: Duration,
8 next_allowed: Option<Instant>,
9}
10
11#[derive(Debug)]
14pub struct IdleBackoff {
15 base: Duration,
16 max: Duration,
17 state: Mutex<State>,
18}
19
20impl IdleBackoff {
21 pub fn new(base: Duration, max: Duration) -> Self {
24 let base = if base.is_zero() { Duration::from_secs(1) } else { base };
25 let max = max.max(base);
26 Self {
27 base,
28 max,
29 state: Mutex::new(State {
30 cur: Duration::ZERO,
31 next_allowed: None,
32 }),
33 }
34 }
35
36 fn state(&self) -> std::sync::MutexGuard<'_, State> {
37 self.state.lock().unwrap_or_else(PoisonError::into_inner)
38 }
39
40 pub fn should_run(&self) -> bool {
42 self.state().next_allowed.is_none_or(|t| Instant::now() >= t)
43 }
44
45 pub fn hit(&self) {
47 let mut s = self.state();
48 s.cur = Duration::ZERO;
49 s.next_allowed = None;
50 }
51
52 pub fn miss(&self) {
54 let mut s = self.state();
55 s.cur = if s.cur.is_zero() {
56 self.base
57 } else {
58 s.cur.saturating_mul(2).min(self.max)
59 };
60 let now = Instant::now();
62 s.next_allowed = Some(
63 now.checked_add(s.cur)
64 .unwrap_or_else(|| now + Duration::from_secs(365 * 86400)),
65 );
66 }
67
68 pub fn reset(&self) {
70 self.hit();
71 }
72
73 pub fn current(&self) -> Duration {
75 self.state().cur
76 }
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn grows_and_caps() {
85 let b = IdleBackoff::new(Duration::from_millis(100), Duration::from_millis(350));
86 assert!(b.should_run());
87 let mut seen = vec![];
88 for _ in 0..5 {
89 b.miss();
90 seen.push(b.current().as_millis());
91 }
92 assert_eq!(seen, [100, 200, 350, 350, 350]);
93 assert!(!b.should_run());
94 b.hit();
95 assert!(b.should_run());
96 assert_eq!(b.current(), Duration::ZERO);
97 b.miss();
98 assert_eq!(b.current(), Duration::from_millis(100));
99 b.reset();
100 assert!(b.should_run());
101 }
102
103 #[test]
104 fn window_expires() {
105 let b = IdleBackoff::new(Duration::from_millis(20), Duration::from_secs(1));
106 b.miss();
107 assert!(!b.should_run());
108 std::thread::sleep(Duration::from_millis(30));
109 assert!(b.should_run());
110 }
111
112 #[test]
113 fn normalizes_args() {
114 let b = IdleBackoff::new(Duration::ZERO, Duration::ZERO);
115 b.miss();
116 assert_eq!(b.current(), Duration::from_secs(1));
117 b.miss();
118 assert_eq!(b.current(), Duration::from_secs(1));
119 }
120}