Skip to main content

rust_web_utils/cronutil/
backoff.rs

1use std::sync::{Mutex, PoisonError};
2use std::time::{Duration, Instant};
3
4#[derive(Debug)]
5struct State {
6    /// 当前退避间隔; 零表示无退避
7    cur: Duration,
8    next_allowed: Option<Instant>,
9}
10
11/// 空轮指数退避闸门: 连续空轮时按指数延长下次允许执行的间隔, 有新待办立即清零恢复高频。
12/// 状态只在进程内存, 不需要跨重启持久化
13#[derive(Debug)]
14pub struct IdleBackoff {
15    base: Duration,
16    max: Duration,
17    state: Mutex<State>,
18}
19
20impl IdleBackoff {
21    /// `base` 为首次空轮后的退避间隔 (零时按 1s), `max` 为上限 (小于 `base` 时取 `base`);
22    /// 如 2s 起步、翻倍增长、封顶 60s
23    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    /// 本轮 tick 是否允许执行; 仍在退避窗口内时返回 `false`, 调用方直接返回, 不查库
41    pub fn should_run(&self) -> bool {
42        self.state().next_allowed.is_none_or(|t| Instant::now() >= t)
43    }
44
45    /// 报告本轮有待办被处理: 清零退避, 恢复高频扫描
46    pub fn hit(&self) {
47        let mut s = self.state();
48        s.cur = Duration::ZERO;
49        s.next_allowed = None;
50    }
51
52    /// 报告本轮空转: 退避间隔翻倍 (首次为 `base`, 封顶 `max`), 推迟下次允许执行的时间
53    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        // 超大 max 溢出 Instant 时退化为"约一年后", 不 panic
61        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    /// 清空退避状态, 用于管理员手动触发时绕过退避窗口强制执行
69    pub fn reset(&self) {
70        self.hit();
71    }
72
73    /// 当前退避间隔 (零表示无退避), 便于监控展示
74    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}