Skip to main content

reth_tasks/
cancel.rs

1//! Cooperative cancellation of spawned work.
2
3use reth_concurrency::sync::{
4    atomic::{AtomicBool, AtomicU8, Ordering},
5    thread_local,
6};
7use std::{cell::RefCell, sync::Arc};
8
9/// The work is still in progress.
10const RUNNING: u8 = 0;
11/// The work should wrap up and keep what it has produced so far.
12const FINALIZATION_REQUESTED: u8 = 1;
13/// The work should stop and discard what it has produced so far.
14const CANCELLED: u8 = 2;
15
16/// Cancels execution on drop and supports cooperative finalization.
17///
18/// If dropped, it will set the `cancelled` flag to true.
19///
20/// This is most useful when a spawned job should stop once its owner goes away, e.g. a payload
21/// job or a blocking RPC call whose caller disconnected.
22#[derive(Default, Clone, Debug)]
23pub struct CancelOnDrop(Arc<AtomicU8>);
24
25// === impl CancelOnDrop ===
26
27impl CancelOnDrop {
28    /// Returns true if the current work should be interrupted.
29    pub fn is_interrupted(&self) -> bool {
30        self.0.load(Ordering::Relaxed) != RUNNING
31    }
32
33    /// Returns true if the job was cancelled.
34    pub fn is_cancelled(&self) -> bool {
35        self.0.load(Ordering::Relaxed) == CANCELLED
36    }
37
38    /// Requests that the current work be finalized without cancelling it.
39    pub fn request_finalization(&self) {
40        let _ = self.0.compare_exchange(
41            RUNNING,
42            FINALIZATION_REQUESTED,
43            Ordering::Relaxed,
44            Ordering::Relaxed,
45        );
46    }
47
48    /// Returns true if finalization was requested.
49    pub fn is_finalization_requested(&self) -> bool {
50        self.0.load(Ordering::Relaxed) == FINALIZATION_REQUESTED
51    }
52
53    /// Runs `f` with this as the cancellation state of the current thread, see [`is_cancelled`].
54    ///
55    /// This lets code deep inside `f`, such as a loop over transactions, observe cancellation
56    /// without threading the [`CancelOnDrop`] through every call. The previous state of the
57    /// thread is restored once `f` returns or unwinds. Leaving the scope does not cancel.
58    pub fn scope<R>(&self, f: impl FnOnce() -> R) -> R {
59        struct Restore(Option<Arc<AtomicU8>>);
60
61        impl Drop for Restore {
62            fn drop(&mut self) {
63                CURRENT.with(|state| *state.borrow_mut() = self.0.take());
64            }
65        }
66
67        let _restore = Restore(CURRENT.with(|state| state.replace(Some(self.0.clone()))));
68        f()
69    }
70}
71
72impl Drop for CancelOnDrop {
73    fn drop(&mut self) {
74        self.0.store(CANCELLED, Ordering::Relaxed);
75    }
76}
77
78/// A marker that can be used to cancel execution.
79///
80/// If dropped, it will NOT set the `cancelled` flag to true.
81/// If `cancel` is called, the `cancelled` flag will be set to true.
82///
83/// This is useful when an external signal should cancel many tasks at once.
84#[derive(Default, Clone, Debug)]
85pub struct ManualCancel(Arc<AtomicBool>);
86
87// === impl ManualCancel ===
88
89impl ManualCancel {
90    /// Returns true if the job was cancelled.
91    pub fn is_cancelled(&self) -> bool {
92        self.0.load(Ordering::Relaxed)
93    }
94
95    /// Drops the [`ManualCancel`], setting the cancelled flag to true.
96    pub fn cancel(self) {
97        self.0.store(true, Ordering::Relaxed);
98    }
99}
100
101/// Returns `true` if the work running on the current thread was cancelled.
102///
103/// This reads the state of the innermost [`CancelOnDrop::scope`] on this thread, for example a
104/// blocking RPC call whose request was dropped because the client disconnected. Long running work
105/// should check this between units of work, such as transactions, and stop early since nobody
106/// waits for the result.
107///
108/// Always returns `false` outside of a [`CancelOnDrop::scope`].
109pub fn is_cancelled() -> bool {
110    #[cfg(not(all(feature = "fuzz", dst)))]
111    {
112        CURRENT.with_borrow(|state| {
113            state.as_ref().is_some_and(|state| state.load(Ordering::Relaxed) == CANCELLED)
114        })
115    }
116    #[cfg(all(feature = "fuzz", dst))]
117    {
118        // Release the TLS borrow before a selected atomic operation can switch tasks.
119        let state = CURRENT.with(|state| state.borrow().clone());
120        state.is_some_and(|state| state.load(Ordering::Relaxed) == CANCELLED)
121    }
122}
123
124thread_local! {
125    /// Cancellation state of the innermost [`CancelOnDrop::scope`] on this thread.
126    static CURRENT: RefCell<Option<Arc<AtomicU8>>> = const { RefCell::new(None) };
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[reth_concurrency::test]
134    fn test_default_cancelled() {
135        let c = CancelOnDrop::default();
136        assert!(!c.is_interrupted());
137        assert!(!c.is_cancelled());
138    }
139
140    #[reth_concurrency::test]
141    fn test_set_cancel_task() {
142        let c = ManualCancel::default();
143        assert!(!c.is_cancelled());
144
145        // Dropping a clone must not cancel the original, unlike `CancelOnDrop`.
146        drop(c.clone());
147        assert!(!c.is_cancelled());
148
149        let c2 = c.clone();
150        let c3 = c.clone();
151        c.cancel();
152        assert!(c3.is_cancelled());
153        assert!(c2.is_cancelled());
154    }
155
156    #[reth_concurrency::test]
157    fn test_cancelondrop_clone_behavior() {
158        let cancel = CancelOnDrop::default();
159        assert!(!cancel.is_cancelled());
160
161        // Clone the CancelOnDrop
162        let cloned_cancel = cancel.clone();
163        assert!(!cloned_cancel.is_cancelled());
164
165        // Drop the original - this should set the cancelled flag
166        drop(cancel);
167
168        // The cloned instance should now see the cancelled flag as true
169        assert!(cloned_cancel.is_interrupted());
170        assert!(cloned_cancel.is_cancelled());
171    }
172
173    #[reth_concurrency::test]
174    fn test_cancelondrop_multiple_clones() {
175        let cancel = CancelOnDrop::default();
176        let clone1 = cancel.clone();
177        let clone2 = cancel.clone();
178        let clone3 = cancel.clone();
179
180        assert!(!cancel.is_cancelled());
181        assert!(!clone1.is_cancelled());
182        assert!(!clone2.is_cancelled());
183        assert!(!clone3.is_cancelled());
184
185        // Drop one clone - this should cancel all instances
186        drop(clone1);
187
188        assert!(cancel.is_interrupted());
189        assert!(cancel.is_cancelled());
190        assert!(clone2.is_cancelled());
191        assert!(clone3.is_cancelled());
192    }
193
194    #[reth_concurrency::test]
195    fn test_cancel_on_drop_finalization_request() {
196        let cancel = CancelOnDrop::default();
197        let clone = cancel.clone();
198
199        cancel.request_finalization();
200
201        assert!(clone.is_interrupted());
202        assert!(clone.is_finalization_requested());
203        assert!(!clone.is_cancelled());
204
205        drop(cancel);
206
207        assert!(clone.is_cancelled());
208        assert!(!clone.is_finalization_requested());
209
210        clone.request_finalization();
211
212        assert!(clone.is_cancelled());
213        assert!(!clone.is_finalization_requested());
214    }
215
216    #[reth_concurrency::test]
217    fn test_scope_is_cancelled() {
218        assert!(!is_cancelled());
219
220        let outer = CancelOnDrop::default();
221        let inner = CancelOnDrop::default();
222        outer.scope(|| {
223            assert!(!is_cancelled());
224            inner.scope(|| {
225                drop(inner.clone());
226                assert!(is_cancelled());
227            });
228            // the outer state is restored
229            assert!(!is_cancelled());
230            outer.request_finalization();
231            assert!(!is_cancelled());
232        });
233
234        // leaving the scope does not cancel
235        assert!(!is_cancelled());
236        assert!(!outer.is_cancelled());
237    }
238
239    #[reth_concurrency::test]
240    fn test_scope_restores_on_panic() {
241        let cancel = CancelOnDrop::default();
242        drop(cancel.clone());
243
244        let res = std::panic::catch_unwind(|| cancel.scope(|| panic!("scope panicked")));
245        assert!(res.is_err());
246        assert!(!is_cancelled());
247    }
248}