rinne_workers/
session_gate.rs1use std::sync::atomic::{AtomicUsize, Ordering};
6
7static ACTIVE_VISIBLE: AtomicUsize = AtomicUsize::new(0);
8
9pub struct VisibleSlot {
11 _private: (),
12}
13
14impl Drop for VisibleSlot {
15 fn drop(&mut self) {
16 ACTIVE_VISIBLE.fetch_sub(1, Ordering::SeqCst);
17 }
18}
19
20fn max_visible() -> usize {
21 std::env::var("RINNE_HARNESS_STAGE_MAX")
22 .ok()
23 .and_then(|s| s.parse::<usize>().ok())
24 .filter(|&n| n > 0)
25 .unwrap_or(3)
26}
27
28pub fn try_acquire_visible() -> Option<VisibleSlot> {
31 let max = max_visible();
32 loop {
33 let cur = ACTIVE_VISIBLE.load(Ordering::SeqCst);
34 if cur >= max {
35 return None;
36 }
37 if ACTIVE_VISIBLE
38 .compare_exchange(cur, cur + 1, Ordering::SeqCst, Ordering::SeqCst)
39 .is_ok()
40 {
41 return Some(VisibleSlot { _private: () });
42 }
43 }
44}
45
46#[cfg(test)]
48pub fn active_count() -> usize {
49 ACTIVE_VISIBLE.load(Ordering::SeqCst)
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 static GATE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
59
60 #[test]
61 fn gate_enforces_cap() {
62 let _guard = GATE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
63 std::env::set_var("RINNE_HARNESS_STAGE_MAX", "2");
64 assert_eq!(active_count(), 0, "another test leaked a slot");
65
66 let a = try_acquire_visible();
67 let b = try_acquire_visible();
68 assert!(a.is_some() && b.is_some(), "both slots must be grantable");
69 assert_eq!(active_count(), 2);
70
71 assert!(
73 try_acquire_visible().is_none(),
74 "a third visible session must be refused at max = 2"
75 );
76
77 drop(a);
78 assert_eq!(active_count(), 1, "dropping a slot must release it");
79 let c = try_acquire_visible();
80 assert!(c.is_some(), "a freed slot must be reusable");
81
82 drop(b);
83 drop(c);
84 assert_eq!(active_count(), 0, "every slot must be returned");
85 std::env::remove_var("RINNE_HARNESS_STAGE_MAX");
86 }
87}