Skip to main content

ag_ui/server/
cancel.rs

1//! Cooperative cancellation, without a runtime.
2//!
3//! A transport trips the token when the client disconnects or a deadline
4//! passes; the run notices and unwinds. There is deliberately no
5//! `tokio_util::CancellationToken` here — this crate must build for wasm and
6//! for non-tokio executors, so the token is an [`AtomicBool`] plus a waker list.
7
8use std::future::Future;
9use std::pin::Pin;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, Mutex};
12use std::task::{Context, Poll, Waker};
13
14/// A shared "stop now" flag.
15///
16/// Cloning is cheap and every clone refers to the same flag, so a transport can
17/// keep one and hand another to the run.
18#[derive(Clone, Debug, Default)]
19pub struct CancellationToken {
20    inner: Arc<Inner>,
21}
22
23#[derive(Debug, Default)]
24struct Inner {
25    cancelled: AtomicBool,
26    wakers: Mutex<Vec<Waiter>>,
27}
28
29#[derive(Debug)]
30struct Waiter {
31    registration: Arc<()>,
32    waker: Waker,
33}
34
35impl CancellationToken {
36    /// A fresh, un-cancelled token.
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// Trips the token and wakes everything waiting on it.
42    ///
43    /// Idempotent — cancelling twice is a no-op.
44    pub fn cancel(&self) {
45        if !self.inner.cancelled.swap(true, Ordering::SeqCst) {
46            // Waking can execute arbitrary executor code, including dropping
47            // another waiter. Never call it while holding the registry lock.
48            let wakers = std::mem::take(&mut *lock(&self.inner.wakers));
49            for waiter in wakers {
50                waiter.waker.wake();
51            }
52        }
53    }
54
55    /// Whether the token has been tripped.
56    pub fn is_cancelled(&self) -> bool {
57        self.inner.cancelled.load(Ordering::SeqCst)
58    }
59
60    /// Resolves once the token is tripped.
61    ///
62    /// Use it to race an in-flight model call:
63    ///
64    /// ```
65    /// # use ag_ui::server::CancellationToken;
66    /// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
67    /// # rt.block_on(async {
68    /// let token = CancellationToken::new();
69    /// token.cancel();
70    /// token.cancelled().await;
71    /// # });
72    /// ```
73    pub fn cancelled(&self) -> Cancelled {
74        Cancelled {
75            token: self.clone(),
76            registration: Arc::new(()),
77        }
78    }
79}
80
81/// The future returned by [`CancellationToken::cancelled`].
82///
83/// It owns a clone of the token rather than borrowing one, so an agent can
84/// hold this `'static` future across an await without borrowing the run
85/// context. Each future has its own waiter registration, removed on drop.
86#[derive(Debug)]
87#[must_use = "a future does nothing unless awaited"]
88pub struct Cancelled {
89    token: CancellationToken,
90    registration: Arc<()>,
91}
92
93impl Clone for Cancelled {
94    fn clone(&self) -> Self {
95        // Each future owns a separate registration even when both are polled
96        // by the same task. Dropping one must not unregister the other.
97        self.token.cancelled()
98    }
99}
100
101impl Drop for Cancelled {
102    fn drop(&mut self) {
103        let removed = {
104            let mut wakers = lock(&self.token.inner.wakers);
105            wakers
106                .iter()
107                .position(|waiter| Arc::ptr_eq(&waiter.registration, &self.registration))
108                .map(|index| wakers.swap_remove(index))
109        };
110        // A RawWaker's drop callback may also re-enter the executor.
111        drop(removed);
112    }
113}
114
115impl Future for Cancelled {
116    type Output = ();
117
118    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
119        if self.token.is_cancelled() {
120            return Poll::Ready(());
121        }
122        let candidate = cx.waker().clone();
123        let mut wakers = lock(&self.token.inner.wakers);
124        // Re-check under the lock: `cancel` may have drained the list between
125        // the load above and here, and would then never see our waker.
126        if self.token.is_cancelled() {
127            return Poll::Ready(());
128        }
129        if let Some(waiter) = wakers
130            .iter_mut()
131            .find(|waiter| Arc::ptr_eq(&waiter.registration, &self.registration))
132        {
133            if !waiter.waker.will_wake(&candidate) {
134                let previous = std::mem::replace(&mut waiter.waker, candidate);
135                drop(wakers);
136                drop(previous);
137            }
138        } else {
139            wakers.push(Waiter {
140                registration: self.registration.clone(),
141                waker: candidate,
142            });
143        }
144        Poll::Pending
145    }
146}
147
148/// A poisoned waker list is still a perfectly good waker list: the only code
149/// that touches it cannot panic while holding the guard.
150fn lock(mutex: &Mutex<Vec<Waiter>>) -> std::sync::MutexGuard<'_, Vec<Waiter>> {
151    mutex
152        .lock()
153        .unwrap_or_else(|poisoned| poisoned.into_inner())
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use std::sync::atomic::AtomicUsize;
160    use std::task::Wake;
161
162    #[derive(Default)]
163    struct CountWake(AtomicUsize);
164
165    impl Wake for CountWake {
166        fn wake(self: Arc<Self>) {
167            self.0.fetch_add(1, Ordering::SeqCst);
168        }
169    }
170
171    #[test]
172    fn dropped_waiters_release_their_wakers_before_cancellation() {
173        let token = CancellationToken::new();
174        let counter = Arc::new(CountWake::default());
175        let waker = Waker::from(counter.clone());
176        for _ in 0..1000 {
177            let mut future = token.cancelled();
178            assert!(
179                Pin::new(&mut future)
180                    .poll(&mut Context::from_waker(&waker))
181                    .is_pending()
182            );
183            drop(future);
184        }
185        assert!(lock(&token.inner.wakers).is_empty());
186        assert_eq!(Arc::strong_count(&counter), 2);
187        token.cancel();
188        assert_eq!(counter.0.load(Ordering::SeqCst), 0);
189    }
190
191    #[test]
192    fn repoll_replaces_the_waker_and_clones_register_independently() {
193        let token = CancellationToken::new();
194        let old = Arc::new(CountWake::default());
195        let current = Arc::new(CountWake::default());
196        let old_waker = Waker::from(old.clone());
197        let current_waker = Waker::from(current.clone());
198        let mut future = token.cancelled();
199        assert!(
200            Pin::new(&mut future)
201                .poll(&mut Context::from_waker(&old_waker))
202                .is_pending()
203        );
204        assert!(
205            Pin::new(&mut future)
206                .poll(&mut Context::from_waker(&current_waker))
207                .is_pending()
208        );
209        assert_eq!(lock(&token.inner.wakers).len(), 1);
210        let mut other = future.clone();
211        assert!(
212            Pin::new(&mut other)
213                .poll(&mut Context::from_waker(&current_waker))
214                .is_pending()
215        );
216        drop(future);
217        assert_eq!(lock(&token.inner.wakers).len(), 1);
218        token.cancel();
219        assert_eq!(old.0.load(Ordering::SeqCst), 0);
220        assert_eq!(current.0.load(Ordering::SeqCst), 1);
221    }
222
223    #[test]
224    fn wake_callbacks_can_reenter_the_waiter_registry() {
225        struct Reentrant(CancellationToken);
226        impl Wake for Reentrant {
227            fn wake(self: Arc<Self>) {
228                assert!(self.0.inner.wakers.try_lock().is_ok());
229            }
230        }
231        let token = CancellationToken::new();
232        let waker = Waker::from(Arc::new(Reentrant(token.clone())));
233        let mut future = token.cancelled();
234        assert!(
235            Pin::new(&mut future)
236                .poll(&mut Context::from_waker(&waker))
237                .is_pending()
238        );
239        token.cancel();
240    }
241
242    #[test]
243    fn cancel_is_visible_through_clones() {
244        let token = CancellationToken::new();
245        let clone = token.clone();
246        assert!(!clone.is_cancelled());
247        token.cancel();
248        assert!(clone.is_cancelled());
249    }
250
251    #[tokio::test]
252    async fn cancelled_future_resolves() {
253        let token = CancellationToken::new();
254        let waiter = token.clone();
255        let handle = tokio::spawn(async move { waiter.cancelled().await });
256        token.cancel();
257        handle.await.expect("waiter task panicked");
258    }
259
260    #[tokio::test]
261    async fn cancelled_future_is_ready_when_already_cancelled() {
262        let token = CancellationToken::new();
263        token.cancel();
264        token.cancelled().await;
265    }
266}