Skip to main content

agentmux_srv_core/backend/
drone_cancel.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How a Drone run is stopped. It lives in the core so the run ledger
5//! (`backend/jobs`: a job's timeout, `cancel_other`, a stop from the Jobs tab) can
6//! stop the run without reaching up into `drone/`; the executor re-exports it.
7
8use std::collections::HashMap;
9use std::sync::{Arc, LazyLock, Mutex};
10
11use tokio_util::sync::CancellationToken;
12
13/// How a run is stopped: a flag the scheduler looks at before each block and
14/// that ends the block in flight, with the reason it was set for.
15#[derive(Clone, Default)]
16pub struct Cancel {
17    token: CancellationToken,
18    reason: Arc<Mutex<Option<String>>>,
19}
20
21impl Cancel {
22    /// Stop the run, for `reason`. The first reason stays. `false` when the run
23    /// was stopped already.
24    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
47/// The runs going now, by id.
48static LIVE: LazyLock<Mutex<HashMap<String, Cancel>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
49
50/// A run has started: `cancel_run` can stop it until `forget_run`.
51pub 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
55/// A run has ended.
56pub fn forget_run(run_id: &str) {
57    LIVE.lock().unwrap_or_else(|e| e.into_inner()).remove(run_id);
58}
59
60/// Stop the run `run_id` for `reason` (a Drone run, not a ledger row). The block
61/// in flight ends, an Agent block's process with it, and the run ends
62/// `cancelled`. `false` when no such run is going.
63pub 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}