Skip to main content

lean_ctx/core/ocla/reference_adapters/
kill_switch.rs

1//! Atomic, per-capability kill switch for reference adapters.
2
3use std::sync::{
4    Mutex,
5    atomic::{AtomicBool, Ordering},
6};
7
8/// Runtime switch that disables one external capability without replacing the
9/// adapter object or changing the native execution path.
10pub struct KillSwitch {
11    pub capability_id: String,
12    pub enabled: AtomicBool,
13    /// Initial/public configuration reason.  The current concurrent reason is
14    /// available through [`KillSwitch::reason`].
15    pub reason: Option<String>,
16    current_reason: Mutex<Option<String>>,
17}
18
19impl KillSwitch {
20    #[must_use]
21    pub fn new(capability_id: impl Into<String>) -> Self {
22        Self {
23            capability_id: capability_id.into(),
24            enabled: AtomicBool::new(false),
25            reason: None,
26            current_reason: Mutex::new(None),
27        }
28    }
29
30    #[must_use]
31    pub fn is_active(&self) -> bool {
32        self.enabled.load(Ordering::SeqCst)
33    }
34
35    /// Activate before the next adapter invocation can pass the gate.
36    pub fn activate(&self, reason: &str) {
37        if let Ok(mut current) = self.current_reason.lock() {
38            *current = Some(reason.trim().to_owned());
39        }
40        self.enabled.store(true, Ordering::SeqCst);
41    }
42
43    pub fn deactivate(&self) {
44        self.enabled.store(false, Ordering::SeqCst);
45    }
46
47    /// Return the latest reason without exposing the mutex implementation.
48    #[must_use]
49    pub fn reason(&self) -> Option<String> {
50        self.current_reason
51            .lock()
52            .ok()
53            .and_then(|reason| reason.clone())
54            .or_else(|| self.reason.clone())
55    }
56}
57
58impl Default for KillSwitch {
59    fn default() -> Self {
60        Self::new("rtk-shell-output")
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::KillSwitch;
67
68    #[test]
69    fn switch_is_atomic_and_keeps_reason() {
70        let switch = KillSwitch::new("capability");
71        assert!(!switch.is_active());
72        switch.activate("maintenance");
73        assert!(switch.is_active());
74        assert_eq!(switch.reason().as_deref(), Some("maintenance"));
75        switch.deactivate();
76        assert!(!switch.is_active());
77    }
78}