agentmux_srv_core/backend/
drone_cancel.rs1use std::collections::HashMap;
9use std::sync::{Arc, LazyLock, Mutex};
10
11use tokio_util::sync::CancellationToken;
12
13#[derive(Clone, Default)]
16pub struct Cancel {
17 token: CancellationToken,
18 reason: Arc<Mutex<Option<String>>>,
19}
20
21impl Cancel {
22 pub fn cancel(&self, reason: &str) -> bool {
25 let mut slot = self.reason.lock().unwrap_or_else(|e| e.into_inner());
26 if self.token.is_cancelled() {
27 return false;
28 }
29 *slot = Some(reason.to_string());
30 self.token.cancel();
31 true
32 }
33
34 pub fn is_cancelled(&self) -> bool {
35 self.token.is_cancelled()
36 }
37
38 pub async fn cancelled(&self) {
39 self.token.cancelled().await;
40 }
41
42 pub fn reason(&self) -> String {
43 self.reason.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_else(|| "stopped".to_string())
44 }
45}
46
47static LIVE: LazyLock<Mutex<HashMap<String, Cancel>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
49
50pub fn register_run(run_id: &str, cancel: &Cancel) {
52 LIVE.lock().unwrap_or_else(|e| e.into_inner()).insert(run_id.to_string(), cancel.clone());
53}
54
55pub fn forget_run(run_id: &str) {
57 LIVE.lock().unwrap_or_else(|e| e.into_inner()).remove(run_id);
58}
59
60pub fn cancel_run(run_id: &str, reason: &str) -> bool {
64 let cancel = LIVE.lock().unwrap_or_else(|e| e.into_inner()).get(run_id).cloned();
65 cancel.is_some_and(|c| c.cancel(reason))
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 #[test]
73 fn a_run_is_stopped_once_and_the_first_reason_stays() {
74 let cancel = Cancel::default();
75 assert!(!cancel.is_cancelled());
76 assert!(cancel.cancel("a person"));
77 assert!(!cancel.cancel("the timeout"));
78 assert!(cancel.is_cancelled());
79 assert_eq!(cancel.reason(), "a person");
80 }
81
82 #[test]
83 fn only_a_registered_run_can_be_cancelled_by_id() {
84 let cancel = Cancel::default();
85 assert!(!cancel_run("core-test-run", "x"), "not registered yet");
86 register_run("core-test-run", &cancel);
87 assert!(cancel_run("core-test-run", "x"));
88 assert!(cancel.is_cancelled());
89 forget_run("core-test-run");
90 assert!(!cancel_run("core-test-run", "again"), "a forgotten run is not kept");
91 }
92}