Skip to main content

eclipse_core/
cancel.rs

1//! Cooperative cancellation for a run.
2//!
3//! A [`Cancel`] is a cloneable flag plus a wakeup. The caller (a CLI signal handler, the
4//! dashboard) sets it; the agent checks it at its own boundaries — before each provider
5//! request, before each tool call, and between iterations — and returns
6//! [`Error::Cancelled`](crate::Error::Cancelled) when it sees the flag.
7//!
8//! It is cooperative on purpose: the run stops at the next check point rather than being
9//! aborted mid-write, so a cancelled run never leaves half-written records behind. What
10//! has already been written (the user message, any completed tool results) stays in the
11//! session, and the next run repairs an unanswered tool call.
12
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::Arc;
15use tokio::sync::Notify;
16
17#[derive(Clone, Debug, Default)]
18pub struct Cancel {
19    inner: Arc<Inner>,
20}
21
22#[derive(Debug, Default)]
23struct Inner {
24    flag: AtomicBool,
25    notify: Notify,
26}
27
28impl Cancel {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    /// Request cancellation. Calling it more than once, or after the run finished, is
34    /// harmless.
35    pub fn cancel(&self) {
36        self.inner.flag.store(true, Ordering::SeqCst);
37        self.inner.notify.notify_waiters();
38    }
39
40    pub fn is_cancelled(&self) -> bool {
41        self.inner.flag.load(Ordering::SeqCst)
42    }
43
44    /// Resolves as soon as [`cancel`](Self::cancel) has been called; immediately if it
45    /// already was, and never if it is not.
46    pub async fn cancelled(&self) {
47        // Registered before the check: a `cancel` between the two cannot be missed.
48        let notified = self.inner.notify.notified();
49        if self.is_cancelled() {
50            return;
51        }
52        notified.await;
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59    use std::time::Duration;
60
61    #[test]
62    fn starts_uncancelled_and_latches() {
63        let c = Cancel::new();
64        assert!(!c.is_cancelled());
65        c.cancel();
66        assert!(c.is_cancelled());
67        c.cancel();
68        assert!(c.is_cancelled());
69    }
70
71    #[test]
72    fn clones_share_one_flag() {
73        let a = Cancel::new();
74        let b = a.clone();
75        b.cancel();
76        assert!(a.is_cancelled());
77    }
78
79    #[tokio::test]
80    async fn cancelled_wakes_a_waiter() {
81        let c = Cancel::new();
82        let woken = {
83            let c = c.clone();
84            tokio::spawn(async move { c.cancelled().await })
85        };
86        tokio::time::sleep(Duration::from_millis(20)).await;
87        assert!(!woken.is_finished());
88        c.cancel();
89        tokio::time::timeout(Duration::from_secs(1), woken)
90            .await
91            .expect("waiter should wake")
92            .unwrap();
93    }
94
95    #[tokio::test]
96    async fn cancelled_returns_at_once_when_already_set() {
97        let c = Cancel::new();
98        c.cancel();
99        tokio::time::timeout(Duration::from_millis(200), c.cancelled())
100            .await
101            .expect("an already-cancelled token must not wait");
102    }
103}