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::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

/// 单实例防重叠闸门; `Default` 即可用, `Clone` 共享同一把闸门。
/// 上一轮未返回时, 下一轮直接跳过, 不排队等待
#[derive(Debug, Clone, Default)]
pub struct TickGuard {
    running: Arc<AtomicBool>,
}

/// 占用闸门的凭证; 丢弃 (含 panic 展开) 时释放
#[derive(Debug)]
#[must_use = "dropping the permit releases the guard immediately"]
pub struct TickPermit {
    running: Arc<AtomicBool>,
}

impl Drop for TickPermit {
    fn drop(&mut self) {
        self.running.store(false, Ordering::Release);
    }
}

impl TickGuard {
    /// 创建闸门
    pub fn new() -> Self {
        Self::default()
    }

    /// 尝试占用闸门; 已有轮次在执行时返回 `None`
    pub fn try_acquire(&self) -> Option<TickPermit> {
        self.running
            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
            .ok()
            .map(|_| TickPermit {
                running: self.running.clone(),
            })
    }

    /// 当前是否有轮次在执行
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::Acquire)
    }

    /// 尝试同步执行 `f`: 无其他轮次时运行并返回 `true`, 否则直接返回 `false`;
    /// `f` panic 时闸门同样释放
    pub fn try_run(&self, f: impl FnOnce()) -> bool {
        let Some(_permit) = self.try_acquire() else {
            return false;
        };
        f();
        true
    }

    /// 异步版 [`TickGuard::try_run`]: 闸门被占用时不轮询 `fut`, 直接返回 `false`;
    /// future 被取消或 panic 时闸门同样释放
    pub async fn try_run_async<F: Future<Output = ()>>(&self, fut: F) -> bool {
        let Some(_permit) = self.try_acquire() else {
            return false;
        };
        fut.await;
        true
    }
}

#[cfg(test)]
mod tests {
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::time::Duration;

    use super::*;

    #[test]
    fn skips_overlap() {
        let g = TickGuard::new();
        let inner = g.clone();
        let ran_inner = std::cell::Cell::new(false);
        assert!(g.try_run(|| {
            assert!(inner.is_running());
            ran_inner.set(inner.try_run(|| {}));
        }));
        assert!(!ran_inner.get());
        assert!(!g.is_running());
        assert!(g.try_run(|| {}));
    }

    #[test]
    fn releases_on_panic() {
        let g = TickGuard::new();
        let r = catch_unwind(AssertUnwindSafe(|| g.try_run(|| panic!("boom"))));
        assert!(r.is_err());
        assert!(!g.is_running());
        assert!(g.try_run(|| {}));
    }

    #[test]
    fn permit() {
        let g = TickGuard::new();
        let p = g.try_acquire().unwrap();
        assert!(g.try_acquire().is_none());
        drop(p);
        assert!(g.try_acquire().is_some());
    }

    #[tokio::test]
    async fn async_overlap_and_cancel() {
        let g = TickGuard::new();
        let g2 = g.clone();
        let long = tokio::spawn(async move { g2.try_run_async(tokio::time::sleep(Duration::from_millis(200))).await });
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert!(!g.try_run_async(async {}).await);
        long.abort();
        let _ = long.await;
        assert!(!g.is_running());
        assert!(g.try_run_async(async {}).await);
    }
}