Debian Codegraph @

helix-event/src/cancel.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use std::borrow::Borrow;
2 use std::future::Future;
3 use std::sync::Arc;
4
•5 use portable_atomic::{AtomicU64, Ordering::Relaxed};
6 use tokio::sync::Notify;
7
8 pub async fn cancelable_future<T>(
9 future: impl Future<Output = T>,
10 cancel: impl Borrow<TaskHandle>,
11 ) -> Option<T> {
12 tokio::select! {
13 biased;
14 _ = cancel.borrow().canceled() => {
15 None
16 }
17 res = future => {
18 Some(res)
19 }
20 }
21 }
22
23 #[derive(Default, Debug)]
24 struct Shared {
25 state: AtomicU64,
26 // `Notify` has some features that we don't really need here because it
27 // supports waking single tasks (`notify_one`) and does its own (more
28 // complicated) state tracking, we could reimplement the waiter linked list
29 // with modest effort and reduce memory consumption by one word/8 bytes and
30 // reduce code complexity/number of atomic operations.
31 //
32 // I don't think that's worth the complexity (unsafe code).
33 //
34 // if we only cared about async code then we could also only use a notify
35 // (without the generation count), this would be equivalent (or maybe more
36 // correct if we want to allow cloning the TX) but it would be extremely slow
37 // to frequently check for cancellation from sync code
38 notify: Notify,
39 }
40
41 impl Shared {
42 fn generation(&self) -> u32 {
43 self.state.load(Relaxed) as u32
44 }
45
46 fn num_running(&self) -> u32 {
47 (self.state.load(Relaxed) >> 32) as u32
48 }
49
50 /// Increments the generation count and sets `num_running`
51 /// to the provided value, this operation is not with
52 /// regard to the generation counter (doesn't use `fetch_add`)
53 /// so the calling code must ensure it cannot execute concurrently
54 /// to maintain correctness (but not safety)
55 fn inc_generation(&self, num_running: u32) -> (u32, u32) {
56 let state = self.state.load(Relaxed);
57 let generation = state as u32;
58 let prev_running = (state >> 32) as u32;
59 // no need to create a new generation if the refcount is zero (fastpath)
60 if prev_running == 0 && num_running == 0 {
61 return (generation, 0);
62 }
63 let new_generation = generation.saturating_add(1);
64 self.state.store(
65 new_generation as u64 | ((num_running as u64) << 32),
66 Relaxed,
67 );
68 self.notify.notify_waiters();
69 (new_generation, prev_running)
70 }
71
72 fn inc_running(&self, generation: u32) {
73 let mut state = self.state.load(Relaxed);
74 loop {
75 let current_generation = state as u32;
76 if current_generation != generation {
77 break;
78 }
79 let off = 1 << 32;
80 let res = self.state.compare_exchange_weak(
81 state,
82 state.saturating_add(off),
83 Relaxed,
84 Relaxed,
85 );
86 match res {
87 Ok(_) => break,
88 Err(new_state) => state = new_state,
89 }
90 }
91 }
92
93 fn dec_running(&self, generation: u32) {
94 let mut state = self.state.load(Relaxed);
95 loop {
96 let current_generation = state as u32;
97 if current_generation != generation {
98 break;
99 }
100 let num_running = (state >> 32) as u32;
101 // running can't be zero here, that would mean we miscounted somewhere
102 assert_ne!(num_running, 0);
103 let off = 1 << 32;
104 let res = self
105 .state
106 .compare_exchange_weak(state, state - off, Relaxed, Relaxed);
107 match res {
108 Ok(_) => break,
109 Err(new_state) => state = new_state,
110 }
111 }
112 }
113 }
114
115 // This intentionally doesn't implement `Clone` and requires a mutable reference
116 // for cancellation to avoid races (in inc_generation).
117
118 /// A task controller allows managing a single subtask enabling the controller
119 /// to cancel the subtask and to check whether it is still running.
120 ///
121 /// For efficiency reasons the controller can be reused/restarted,
122 /// in that case the previous task is automatically canceled.
123 ///
124 /// If the controller is dropped, the subtasks are automatically canceled.
125 #[derive(Default, Debug)]
126 pub struct TaskController {
127 shared: Arc<Shared>,
128 }
129
130 impl TaskController {
131 pub fn new() -> Self {
132 TaskController::default()
133 }
134 /// Cancels the active task (handle).
135 ///
136 /// Returns whether any tasks were still running before the cancellation.
137 pub fn cancel(&mut self) -> bool {
138 self.shared.inc_generation(0).1 != 0
139 }
140
141 /// Checks whether there are any task handles
142 /// that haven't been dropped (or canceled) yet.
143 pub fn is_running(&self) -> bool {
144 self.shared.num_running() != 0
145 }
146
147 /// Starts a new task and cancels the previous task (handles).
148 pub fn restart(&mut self) -> TaskHandle {
149 TaskHandle {
150 generation: self.shared.inc_generation(1).0,
151 shared: self.shared.clone(),
152 }
153 }
154 }
155
156 impl Drop for TaskController {
157 fn drop(&mut self) {
158 self.cancel();
159 }
160 }
161
162 /// A handle that is used to link a task with a task controller.
163 ///
164 /// It can be used to cancel async futures very efficiently but can also be checked for
165 /// cancellation very quickly (single atomic read) in blocking code.
166 /// The handle can be cheaply cloned (reference counted).
167 ///
168 /// The TaskController can check whether a task is "running" by inspecting the
169 /// refcount of the (current) tasks handles. Therefore, if that information
170 /// is important, ensure that the handle is not dropped until the task fully
171 /// completes.
172 pub struct TaskHandle {
173 shared: Arc<Shared>,
174 generation: u32,
175 }
176
177 impl Clone for TaskHandle {
178 fn clone(&self) -> Self {
179 self.shared.inc_running(self.generation);
180 TaskHandle {
181 shared: self.shared.clone(),
182 generation: self.generation,
183 }
184 }
185 }
186
187 impl Drop for TaskHandle {
188 fn drop(&mut self) {
189 self.shared.dec_running(self.generation);
190 }
191 }
192
193 impl TaskHandle {
194 /// Waits until [`TaskController::cancel`] is called for the corresponding
195 /// [`TaskController`]. Immediately returns if `cancel` was already called since
196 pub async fn canceled(&self) {
197 let notified = self.shared.notify.notified();
198 if !self.is_canceled() {
199 notified.await
200 }
201 }
202
203 pub fn is_canceled(&self) -> bool {
204 self.generation != self.shared.generation()
205 }
206 }
207
208 #[cfg(test)]
209 mod tests {
210 use std::future::poll_fn;
211
212 use futures_executor::block_on;
213 use tokio::task::yield_now;
214
215 use crate::{cancelable_future, TaskController};
216
217 #[test]
218 fn immediate_cancel() {
219 let mut controller = TaskController::new();
220 let handle = controller.restart();
221 controller.cancel();
222 assert!(handle.is_canceled());
223 controller.restart();
224 assert!(handle.is_canceled());
225
226 let res = block_on(cancelable_future(
227 poll_fn(|_cx| std::task::Poll::Ready(())),
228 handle,
229 ));
230 assert!(res.is_none());
231 }
232
233 #[test]
234 fn running_count() {
235 let mut controller = TaskController::new();
236 let handle = controller.restart();
237 assert!(controller.is_running());
238 assert!(!handle.is_canceled());
239 drop(handle);
240 assert!(!controller.is_running());
241 assert!(!controller.cancel());
242 let handle = controller.restart();
243 assert!(!handle.is_canceled());
244 assert!(controller.is_running());
245 let handle2 = handle.clone();
246 assert!(!handle.is_canceled());
247 assert!(controller.is_running());
248 drop(handle2);
249 assert!(!handle.is_canceled());
250 assert!(controller.is_running());
251 assert!(controller.cancel());
252 assert!(handle.is_canceled());
253 assert!(!controller.is_running());
254 }
255
256 #[test]
257 fn no_cancel() {
258 let mut controller = TaskController::new();
259 let handle = controller.restart();
260 assert!(!handle.is_canceled());
261
262 let res = block_on(cancelable_future(
263 poll_fn(|_cx| std::task::Poll::Ready(())),
264 handle,
265 ));
266 assert!(res.is_some());
267 }
268
269 #[test]
270 fn delayed_cancel() {
271 let mut controller = TaskController::new();
272 let handle = controller.restart();
273
274 let mut hit = false;
275 let res = block_on(cancelable_future(
276 async {
277 controller.cancel();
278 hit = true;
279 yield_now().await;
280 },
281 handle,
282 ));
283 assert!(res.is_none());
284 assert!(hit);
285 }
286 }