Skip to main content

weaveffi/rt/
cancel.rs

1//! Reference-counted cancel tokens and the future combinator that makes
2//! cancellation of an async call observable.
3//!
4//! A consumer creates a token with `{prefix}_cancel_token_create` and passes
5//! it to a cancellable async launcher. The launcher takes its own reference
6//! (a [`CancelToken`]), so the consumer may cancel and destroy its reference
7//! at any time afterwards, even before the call completes. Cancelling wakes
8//! every future registered on the token; the launcher's [`Cancellable`]
9//! wrapper then drops the producer's future and the call completes with
10//! [`CANCELLED_ERROR_CODE`](crate::rt::CANCELLED_ERROR_CODE).
11//!
12//! Each in-flight call registers once, when it's first polled, and keeps its
13//! current waker in a [`WakerSlot`] of its own.
14
15use std::future::Future;
16use std::pin::Pin;
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::{Arc, Mutex, PoisonError};
19use std::task::{Context, Poll, Waker};
20
21/// A waker slot that one task registers into and any thread wakes.
22///
23/// A mutex around the waker: a call touches it once per poll and the token
24/// once when cancelled, so the lock is never contended in practice, and its
25/// correctness is obvious where a lock-free slot's isn't.
26#[derive(Debug, Default)]
27pub struct WakerSlot {
28    waker: Mutex<Option<Waker>>,
29}
30
31impl WakerSlot {
32    /// Store `waker` as the one to wake, replacing any earlier one.
33    pub fn register(&self, waker: &Waker) {
34        let mut slot = self.waker.lock().unwrap_or_else(PoisonError::into_inner);
35        match &*slot {
36            Some(old) if old.will_wake(waker) => {}
37            _ => *slot = Some(waker.clone()),
38        }
39    }
40
41    /// Wake the registered waker, if any.
42    pub fn wake(&self) {
43        let woken = self
44            .waker
45            .lock()
46            .unwrap_or_else(PoisonError::into_inner)
47            .take();
48        if let Some(w) = woken {
49            w.wake();
50        }
51    }
52}
53
54/// The shared state behind a cancel token (`{prefix}_cancel_token` in C, an
55/// opaque type).
56///
57/// A `*mut FfiCancelToken` handed to C is an [`Arc`] turned into a raw
58/// pointer, so the consumer's reference and every [`CancelToken`] the
59/// producer holds keep the state alive independently.
60#[derive(Debug, Default)]
61pub struct FfiCancelToken {
62    cancelled: AtomicBool,
63    /// One slot per in-flight call; touched once when a call starts and once
64    /// when it ends, never per poll.
65    registrations: Mutex<Vec<Arc<WakerSlot>>>,
66}
67
68impl FfiCancelToken {
69    fn cancel(&self) {
70        self.cancelled.store(true, Ordering::SeqCst);
71        let registrations = std::mem::take(&mut *self.lock());
72        for r in registrations {
73            r.wake();
74        }
75    }
76
77    fn is_cancelled(&self) -> bool {
78        self.cancelled.load(Ordering::SeqCst)
79    }
80
81    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Arc<WakerSlot>>> {
82        self.registrations
83            .lock()
84            .unwrap_or_else(PoisonError::into_inner)
85    }
86
87    fn register(&self, slot: &Arc<WakerSlot>) {
88        self.lock().push(Arc::clone(slot));
89    }
90
91    fn deregister(&self, slot: &Arc<WakerSlot>) {
92        self.lock().retain(|r| !Arc::ptr_eq(r, slot));
93    }
94}
95
96/// The body of `{prefix}_cancel_token_create`: a fresh, uncancelled token
97/// holding one reference, which the consumer releases with
98/// [`cancel_token_destroy`].
99#[must_use]
100pub fn cancel_token_create() -> *mut FfiCancelToken {
101    crate::rt::leak::track(crate::rt::leak::TOKENS, 1);
102    Arc::into_raw(Arc::new(FfiCancelToken::default())).cast_mut()
103}
104
105/// The body of `{prefix}_cancel_token_cancel`: request cancellation and wake
106/// every future waiting on the token. Idempotent; a null token is a no-op.
107///
108/// # Safety
109///
110/// `token` must be null or a token from [`cancel_token_create`] whose
111/// consumer reference hasn't been destroyed.
112pub unsafe fn cancel_token_cancel(token: *mut FfiCancelToken) {
113    // SAFETY: the caller guarantees a live token or null.
114    if let Some(t) = unsafe { token.as_ref() } {
115        t.cancel();
116    }
117}
118
119/// The body of `{prefix}_cancel_token_is_cancelled`. A null token reads as
120/// never cancelled.
121///
122/// # Safety
123///
124/// Same contract as [`cancel_token_cancel`].
125#[must_use]
126pub unsafe fn cancel_token_is_cancelled(token: *const FfiCancelToken) -> bool {
127    // SAFETY: the caller guarantees a live token or null.
128    unsafe { token.as_ref() }.is_some_and(FfiCancelToken::is_cancelled)
129}
130
131/// The body of `{prefix}_cancel_token_destroy`: release the consumer's
132/// reference. In-flight calls keep their own references, so this is safe to
133/// call while a call that received the token is still running. A null token
134/// is a no-op.
135///
136/// # Safety
137///
138/// `token` must be null or a token from [`cancel_token_create`], and the
139/// consumer must not use it again.
140pub unsafe fn cancel_token_destroy(token: *mut FfiCancelToken) {
141    if token.is_null() {
142        return;
143    }
144    crate::rt::leak::track(crate::rt::leak::TOKENS, -1);
145    // SAFETY: `token` came from `Arc::into_raw` and its reference is
146    // released exactly once.
147    unsafe { Arc::decrement_strong_count(token.cast_const()) };
148}
149
150/// The producer's handle on a consumer's cancel token, accepted as the final
151/// parameter of a cancellable `async fn`.
152///
153/// The handle holds its own reference to the token, so it stays valid after
154/// the consumer destroys its reference. Cancellation is enforced by the
155/// runtime (the producer's future is dropped as soon as the token fires); a
156/// producer polls [`is_cancelled`](Self::is_cancelled) only when it wants to
157/// clean up cooperatively, for example between batches of work on another
158/// thread.
159#[derive(Debug, Default)]
160pub struct CancelToken {
161    state: Option<Arc<FfiCancelToken>>,
162}
163
164impl CancelToken {
165    /// Take a producer reference on the token a launcher received. A null
166    /// token yields a handle that's never cancelled.
167    ///
168    /// This is the entry point the `#[weaveffi::export]` expansion calls;
169    /// producers receive an already-built token.
170    ///
171    /// # Safety
172    ///
173    /// `raw` must be null or a live token from [`cancel_token_create`].
174    #[doc(hidden)]
175    #[must_use]
176    pub unsafe fn from_raw(raw: *const FfiCancelToken) -> Self {
177        if raw.is_null() {
178            return Self::default();
179        }
180        // SAFETY: `raw` came from `Arc::into_raw` and is live, so adding a
181        // reference and adopting it is sound.
182        let state = unsafe {
183            Arc::increment_strong_count(raw);
184            Arc::from_raw(raw)
185        };
186        crate::rt::leak::track(crate::rt::leak::TOKENS, 1);
187        Self { state: Some(state) }
188    }
189
190    /// Whether the consumer has requested cancellation.
191    #[must_use]
192    pub fn is_cancelled(&self) -> bool {
193        self.state
194            .as_deref()
195            .is_some_and(FfiCancelToken::is_cancelled)
196    }
197}
198
199impl Drop for CancelToken {
200    fn drop(&mut self) {
201        if self.state.is_some() {
202            crate::rt::leak::track(crate::rt::leak::TOKENS, -1);
203        }
204    }
205}
206
207impl Clone for CancelToken {
208    fn clone(&self) -> Self {
209        if self.state.is_some() {
210            crate::rt::leak::track(crate::rt::leak::TOKENS, 1);
211        }
212        Self {
213            state: self.state.clone(),
214        }
215    }
216}
217
218/// A future that resolves to `Some(output)` when `inner` completes, or to
219/// `None` as soon as the token is cancelled, dropping `inner` first.
220///
221/// Async launchers for `cancellable` functions wrap the producer's future in
222/// one of these. The waker is registered on the token before the flag is
223/// checked, so a cancellation racing a poll is never missed.
224#[derive(Debug)]
225pub struct Cancellable<F> {
226    inner: Option<Pin<Box<F>>>,
227    token: CancelToken,
228    slot: Option<Arc<WakerSlot>>,
229}
230
231impl<F: Future> Cancellable<F> {
232    /// Race `fut` against `token`. A handle on a null token never cancels.
233    pub fn new(fut: F, token: CancelToken) -> Self {
234        Self {
235            inner: Some(Box::pin(fut)),
236            token,
237            slot: None,
238        }
239    }
240}
241
242impl<F: Future> Future for Cancellable<F> {
243    type Output = Option<F::Output>;
244
245    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
246        let this = &mut *self;
247        if let Some(state) = this.token.state.as_deref() {
248            let slot = this.slot.get_or_insert_with(|| {
249                let slot = Arc::new(WakerSlot::default());
250                state.register(&slot);
251                slot
252            });
253            slot.register(cx.waker());
254            if state.is_cancelled() {
255                this.inner = None;
256                state.deregister(slot);
257                return Poll::Ready(None);
258            }
259        }
260        let Some(inner) = this.inner.as_mut() else {
261            // Already resolved; a well-behaved executor never polls again.
262            return Poll::Pending;
263        };
264        match inner.as_mut().poll(cx) {
265            Poll::Pending => Poll::Pending,
266            Poll::Ready(out) => {
267                this.inner = None;
268                if let (Some(state), Some(slot)) = (this.token.state.as_deref(), &this.slot) {
269                    state.deregister(slot);
270                }
271                Poll::Ready(Some(out))
272            }
273        }
274    }
275}
276
277impl<F> Drop for Cancellable<F> {
278    fn drop(&mut self) {
279        if let (Some(state), Some(slot)) = (self.token.state.as_deref(), &self.slot) {
280            state.deregister(slot);
281        }
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use crate::rt::spawn::block_on;
289    use std::sync::atomic::AtomicUsize;
290
291    #[test]
292    fn lifecycle_and_null_safety() {
293        let token = cancel_token_create();
294        assert!(!unsafe { cancel_token_is_cancelled(token) });
295        unsafe { cancel_token_cancel(token) };
296        unsafe { cancel_token_cancel(token) };
297        assert!(unsafe { cancel_token_is_cancelled(token) });
298        unsafe { cancel_token_destroy(token) };
299
300        unsafe {
301            cancel_token_cancel(std::ptr::null_mut());
302            assert!(!cancel_token_is_cancelled(std::ptr::null()));
303            cancel_token_destroy(std::ptr::null_mut());
304        }
305        assert!(!unsafe { CancelToken::from_raw(std::ptr::null()) }.is_cancelled());
306    }
307
308    #[test]
309    fn producer_reference_outlives_the_consumer() {
310        let token = cancel_token_create();
311        let handle = unsafe { CancelToken::from_raw(token) };
312        unsafe { cancel_token_cancel(token) };
313        unsafe { cancel_token_destroy(token) };
314        assert!(handle.is_cancelled());
315    }
316
317    #[test]
318    fn cancelling_wakes_and_drops_the_inner_future() {
319        struct Flag(Arc<AtomicBool>);
320        impl Drop for Flag {
321            fn drop(&mut self) {
322                self.0.store(true, Ordering::SeqCst);
323            }
324        }
325
326        let token = cancel_token_create();
327        let handle = unsafe { CancelToken::from_raw(token) };
328        let dropped = Arc::new(AtomicBool::new(false));
329        let guard = Flag(Arc::clone(&dropped));
330        let fut = Cancellable::new(
331            async move {
332                let _guard = guard;
333                std::future::pending::<()>().await;
334            },
335            handle,
336        );
337        let raw = crate::rt::ThreadPtr(token);
338        let canceller = std::thread::spawn(move || {
339            let raw = raw.get();
340            std::thread::sleep(std::time::Duration::from_millis(20));
341            unsafe { cancel_token_cancel(raw) };
342            unsafe { cancel_token_destroy(raw) };
343        });
344        assert!(block_on(fut).is_none());
345        assert!(dropped.load(Ordering::SeqCst));
346        canceller.join().unwrap();
347    }
348
349    #[test]
350    fn atomic_waker_wakes_the_latest_registration() {
351        struct Count(AtomicUsize);
352        impl std::task::Wake for Count {
353            fn wake(self: Arc<Self>) {
354                self.0.fetch_add(1, Ordering::SeqCst);
355            }
356        }
357        let a = Arc::new(Count(AtomicUsize::new(0)));
358        let b = Arc::new(Count(AtomicUsize::new(0)));
359        let slot = WakerSlot::default();
360        slot.wake();
361        slot.register(&Waker::from(Arc::clone(&a)));
362        slot.register(&Waker::from(Arc::clone(&b)));
363        slot.wake();
364        slot.wake();
365        assert_eq!(a.0.load(Ordering::SeqCst), 0);
366        assert_eq!(b.0.load(Ordering::SeqCst), 1);
367    }
368
369    #[test]
370    fn one_token_cancels_every_call_it_was_passed_to() {
371        let token = cancel_token_create();
372        let calls: Vec<_> = (0..3)
373            .map(|_| {
374                Cancellable::new(std::future::pending::<()>(), unsafe {
375                    CancelToken::from_raw(token)
376                })
377            })
378            .collect();
379        let raw = crate::rt::ThreadPtr(token);
380        let canceller = std::thread::spawn(move || {
381            std::thread::sleep(std::time::Duration::from_millis(20));
382            unsafe { cancel_token_cancel(raw.get()) };
383        });
384        for call in calls {
385            assert!(block_on(call).is_none());
386        }
387        canceller.join().unwrap();
388        unsafe { cancel_token_destroy(token) };
389    }
390
391    #[test]
392    fn an_uncancelled_future_completes() {
393        let handle = CancelToken::default();
394        assert_eq!(block_on(Cancellable::new(async { 3 }, handle)), Some(3));
395    }
396}