Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::borrow::Borrow;
use std::future::Future;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;

use tokio::sync::Notify;

pub async fn cancelable_future<T>(
    future: impl Future<Output = T>,
    cancel: impl Borrow<TaskHandle>,
) -> Option<T> {
    tokio::select! {
        biased;
        _ = cancel.borrow().canceled() => {
            None
        }
        res = future => {
            Some(res)
        }
    }
}

#[derive(Default, Debug)]
struct Shared {
    state: AtomicU64,
    // `Notify` has some features that we don't really need here because it
    // supports waking single tasks (`notify_one`) and does its own (more
    // complicated) state tracking, we could reimplement the waiter linked list
    // with modest effort and reduce memory consumption by one word/8 bytes and
    // reduce code complexity/number of atomic operations.
    //
    // I don't think that's worth the complexity (unsafe code).
    //
    // if we only cared about async code then we could also only use a notify
    // (without the generation count), this would be equivalent (or maybe more
    // correct if we want to allow cloning the TX) but it would be extremly slow
    // to frequently check for cancelation from sync code
    notify: Notify,
}

impl Shared {
    fn generation(&self) -> u32 {
        self.state.load(Relaxed) as u32
    }

    fn num_running(&self) -> u32 {
        (self.state.load(Relaxed) >> 32) as u32
    }

    /// Increments the generation count and sets `num_running`
    /// to the provided value, this operation is not with
    /// regard to the generation counter (doesn't use `fetch_add`)
    /// so the calling code must ensure it cannot execute concurrently
    /// to maintain correctness (but not safety)
    fn inc_generation(&self, num_running: u32) -> (u32, u32) {
        let state = self.state.load(Relaxed);
        let generation = state as u32;
        let prev_running = (state >> 32) as u32;
        // no need to create a new generation if the refcount is zero (fastpath)
        if prev_running == 0 && num_running == 0 {
            return (generation, 0);
        }
        let new_generation = generation.saturating_add(1);
        self.state.store(
            new_generation as u64 | ((num_running as u64) << 32),
            Relaxed,
        );
        self.notify.notify_waiters();
        (new_generation, prev_running)
    }

    fn inc_running(&self, generation: u32) {
        let mut state = self.state.load(Relaxed);
        loop {
            let current_generation = state as u32;
            if current_generation != generation {
                break;
            }
            let off = 1 << 32;
            let res = self.state.compare_exchange_weak(
                state,
                state.saturating_add(off),
                Relaxed,
                Relaxed,
            );
            match res {
                Ok(_) => break,
                Err(new_state) => state = new_state,
            }
        }
    }

    fn dec_running(&self, generation: u32) {
        let mut state = self.state.load(Relaxed);
        loop {
            let current_generation = state as u32;
            if current_generation != generation {
                break;
            }
            let num_running = (state >> 32) as u32;
            // running can't be zero here, that would mean we miscounted somewhere
            assert_ne!(num_running, 0);
            let off = 1 << 32;
            let res = self
                .state
                .compare_exchange_weak(state, state - off, Relaxed, Relaxed);
            match res {
                Ok(_) => break,
                Err(new_state) => state = new_state,
            }
        }
    }
}

// This intentionally doesn't implement `Clone` and requires a mutable reference
// for cancelation to avoid races (in inc_generation).

/// A task controller allows managing a single subtask enabling the controller
/// to cancel the subtask and to check whether it is still running.
///
/// For efficiency reasons the controller can be reused/restarted,
/// in that case the previous task is automatically canceled.
///
/// If the controller is dropped, the subtasks are automatically canceled.
#[derive(Default, Debug)]
pub struct TaskController {
    shared: Arc<Shared>,
}

impl TaskController {
    pub fn new() -> Self {
        TaskController::default()
    }
    /// Cancels the active task (handle).
    ///
    /// Returns whether any tasks were still running before the cancelation.
    pub fn cancel(&mut self) -> bool {
        self.shared.inc_generation(0).1 != 0
    }

    /// Checks whether there are any task handles
    /// that haven't been dropped (or canceled) yet.
    pub fn is_running(&self) -> bool {
        self.shared.num_running() != 0
    }

    /// Starts a new task and cancels the previous task (handles).
    pub fn restart(&mut self) -> TaskHandle {
        TaskHandle {
            generation: self.shared.inc_generation(1).0,
            shared: self.shared.clone(),
        }
    }
}

impl Drop for TaskController {
    fn drop(&mut self) {
        self.cancel();
    }
}

/// A handle that is used to link a task with a task controller.
///
/// It can be used to cancel async futures very efficiently but can also be checked for
/// cancelation very quickly (single atomic read) in blocking code.
/// The handle can be cheaply cloned (reference counted).
///
/// The TaskController can check whether a task is "running" by inspecting the
/// refcount of the (current) tasks handles. Therefore, if that information
/// is important, ensure that the handle is not dropped until the task fully
/// completes.
pub struct TaskHandle {
    shared: Arc<Shared>,
    generation: u32,
}

impl Clone for TaskHandle {
    fn clone(&self) -> Self {
        self.shared.inc_running(self.generation);
        TaskHandle {
            shared: self.shared.clone(),
            generation: self.generation,
        }
    }
}

impl Drop for TaskHandle {
    fn drop(&mut self) {
        self.shared.dec_running(self.generation);
    }
}

impl TaskHandle {
    /// Waits until [`TaskController::cancel`] is called for the corresponding
    /// [`TaskController`]. Immediately returns if `cancel` was already called since
    pub async fn canceled(&self) {
        let notified = self.shared.notify.notified();
        if !self.is_canceled() {
            notified.await
        }
    }

    pub fn is_canceled(&self) -> bool {
        self.generation != self.shared.generation()
    }
}

#[cfg(test)]
mod tests {
    use std::future::poll_fn;

    use futures_executor::block_on;
    use tokio::task::yield_now;

    use crate::{cancelable_future, TaskController};

    #[test]
    fn immediate_cancel() {
        let mut controller = TaskController::new();
        let handle = controller.restart();
        controller.cancel();
        assert!(handle.is_canceled());
        controller.restart();
        assert!(handle.is_canceled());

        let res = block_on(cancelable_future(
            poll_fn(|_cx| std::task::Poll::Ready(())),
            handle,
        ));
        assert!(res.is_none());
    }

    #[test]
    fn running_count() {
        let mut controller = TaskController::new();
        let handle = controller.restart();
        assert!(controller.is_running());
        assert!(!handle.is_canceled());
        drop(handle);
        assert!(!controller.is_running());
        assert!(!controller.cancel());
        let handle = controller.restart();
        assert!(!handle.is_canceled());
        assert!(controller.is_running());
        let handle2 = handle.clone();
        assert!(!handle.is_canceled());
        assert!(controller.is_running());
        drop(handle2);
        assert!(!handle.is_canceled());
        assert!(controller.is_running());
        assert!(controller.cancel());
        assert!(handle.is_canceled());
        assert!(!controller.is_running());
    }

    #[test]
    fn no_cancel() {
        let mut controller = TaskController::new();
        let handle = controller.restart();
        assert!(!handle.is_canceled());

        let res = block_on(cancelable_future(
            poll_fn(|_cx| std::task::Poll::Ready(())),
            handle,
        ));
        assert!(res.is_some());
    }

    #[test]
    fn delayed_cancel() {
        let mut controller = TaskController::new();
        let handle = controller.restart();

        let mut hit = false;
        let res = block_on(cancelable_future(
            async {
                controller.cancel();
                hit = true;
                yield_now().await;
            },
            handle,
        ));
        assert!(res.is_none());
        assert!(hit);
    }
}