rust_web_utils/cronutil/
guard.rs1use std::future::Future;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, Ordering};
4
5#[derive(Debug, Clone, Default)]
8pub struct TickGuard {
9 running: Arc<AtomicBool>,
10}
11
12#[derive(Debug)]
14#[must_use = "dropping the permit releases the guard immediately"]
15pub struct TickPermit {
16 running: Arc<AtomicBool>,
17}
18
19impl Drop for TickPermit {
20 fn drop(&mut self) {
21 self.running.store(false, Ordering::Release);
22 }
23}
24
25impl TickGuard {
26 pub fn new() -> Self {
28 Self::default()
29 }
30
31 pub fn try_acquire(&self) -> Option<TickPermit> {
33 self.running
34 .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
35 .ok()
36 .map(|_| TickPermit {
37 running: self.running.clone(),
38 })
39 }
40
41 pub fn is_running(&self) -> bool {
43 self.running.load(Ordering::Acquire)
44 }
45
46 pub fn try_run(&self, f: impl FnOnce()) -> bool {
49 let Some(_permit) = self.try_acquire() else {
50 return false;
51 };
52 f();
53 true
54 }
55
56 pub async fn try_run_async<F: Future<Output = ()>>(&self, fut: F) -> bool {
59 let Some(_permit) = self.try_acquire() else {
60 return false;
61 };
62 fut.await;
63 true
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use std::panic::{AssertUnwindSafe, catch_unwind};
70 use std::time::Duration;
71
72 use super::*;
73
74 #[test]
75 fn skips_overlap() {
76 let g = TickGuard::new();
77 let inner = g.clone();
78 let ran_inner = std::cell::Cell::new(false);
79 assert!(g.try_run(|| {
80 assert!(inner.is_running());
81 ran_inner.set(inner.try_run(|| {}));
82 }));
83 assert!(!ran_inner.get());
84 assert!(!g.is_running());
85 assert!(g.try_run(|| {}));
86 }
87
88 #[test]
89 fn releases_on_panic() {
90 let g = TickGuard::new();
91 let r = catch_unwind(AssertUnwindSafe(|| g.try_run(|| panic!("boom"))));
92 assert!(r.is_err());
93 assert!(!g.is_running());
94 assert!(g.try_run(|| {}));
95 }
96
97 #[test]
98 fn permit() {
99 let g = TickGuard::new();
100 let p = g.try_acquire().unwrap();
101 assert!(g.try_acquire().is_none());
102 drop(p);
103 assert!(g.try_acquire().is_some());
104 }
105
106 #[tokio::test]
107 async fn async_overlap_and_cancel() {
108 let g = TickGuard::new();
109 let g2 = g.clone();
110 let long = tokio::spawn(async move { g2.try_run_async(tokio::time::sleep(Duration::from_millis(200))).await });
111 tokio::time::sleep(Duration::from_millis(20)).await;
112 assert!(!g.try_run_async(async {}).await);
113 long.abort();
114 let _ = long.await;
115 assert!(!g.is_running());
116 assert!(g.try_run_async(async {}).await);
117 }
118}