rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
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 {
    /// `base` 为首次空轮后的退避间隔 (零时按 1s), `max` 为上限 (小于 `base` 时取 `base`);
    /// 如 2s 起步、翻倍增长、封顶 60s
    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)
    }

    /// 本轮 tick 是否允许执行; 仍在退避窗口内时返回 `false`, 调用方直接返回, 不查库
    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;
    }

    /// 报告本轮空转: 退避间隔翻倍 (首次为 `base`, 封顶 `max`), 推迟下次允许执行的时间
    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)
        };
        // 超大 max 溢出 Instant 时退化为"约一年后", 不 panic
        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));
    }
}