Skip to main content

mtorrent_utils/
task_scope.rs

1use std::mem;
2use std::ops::{Deref, DerefMut};
3use std::pin::Pin;
4use std::task::{Context, Poll};
5use tokio::{runtime, task};
6
7/// A collection of tokio task abort handles that aborts all still-running tasks on drop.
8///
9/// Finished handles are pruned each time a new task is spawned, so the scope does not
10/// accumulate memory for completed tasks.
11#[derive(Debug)]
12pub struct TaskScope(Vec<task::AbortHandle>);
13
14impl TaskScope {
15    /// Create an empty scope with no tracked tasks.
16    pub fn new() -> Self {
17        Self(Vec::new())
18    }
19
20    /// Spawn a `!Send` future on the current [`LocalRuntime`](tokio::runtime::LocalRuntime) and
21    /// track its abort handle in this scope.
22    pub fn spawn_local<F>(&mut self, future: F) -> task::JoinHandle<F::Output>
23    where
24        F: Future + 'static,
25        F::Output: 'static,
26    {
27        self.0.retain(|handle| !handle.is_finished());
28        let join_handle = task::spawn_local(future);
29        self.0.push(join_handle.abort_handle());
30        join_handle
31    }
32
33    /// Spawn a future on the current tokio runtime and track its abort handle in this scope.
34    pub fn spawn<F>(&mut self, future: F) -> task::JoinHandle<F::Output>
35    where
36        F: Future + Send + 'static,
37        F::Output: Send + 'static,
38    {
39        self.0.retain(|handle| !handle.is_finished());
40        let join_handle = task::spawn(future);
41        self.0.push(join_handle.abort_handle());
42        join_handle
43    }
44
45    /// Spawn a future on the runtime referenced by `handle` and track its abort handle
46    /// in this scope.
47    pub fn spawn_on<F>(
48        &mut self,
49        future: F,
50        handle: &runtime::Handle,
51    ) -> task::JoinHandle<F::Output>
52    where
53        F: Future + Send + 'static,
54        F::Output: Send + 'static,
55    {
56        self.0.retain(|handle| !handle.is_finished());
57        let join_handle = handle.spawn(future);
58        self.0.push(join_handle.abort_handle());
59        join_handle
60    }
61
62    /// Abort every tracked task and drop all handles emptying the scope.
63    pub fn abort_all(&mut self) {
64        for handle in mem::take(&mut self.0) {
65            handle.abort();
66        }
67    }
68}
69
70impl Drop for TaskScope {
71    fn drop(&mut self) {
72        self.abort_all();
73    }
74}
75
76impl Default for TaskScope {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82// ------------------------------------------------------------------------------------------------
83
84/// Spawn a future on the current tokio runtime and return a handle that aborts the task on drop.
85///
86/// Unlike [`std::thread::scope`], the future must still be `'static`.
87pub fn spawn_scoped<F>(future: F) -> ScopedTaskHandle<F::Output>
88where
89    F: Future + Send + 'static,
90    F::Output: Send + 'static,
91{
92    ScopedTaskHandle(task::spawn(future))
93}
94
95/// Spawn a `!Send` future on the current [`LocalRuntime`](tokio::runtime::LocalRuntime) and
96/// return a handle that aborts the task on drop.
97pub fn spawn_scoped_local<F>(future: F) -> ScopedTaskHandle<F::Output>
98where
99    F: Future + 'static,
100    F::Output: 'static,
101{
102    ScopedTaskHandle(task::spawn_local(future))
103}
104
105/// Spawn a future on the runtime referenced by `handle` and return a handle that aborts the task
106/// on drop.
107pub fn spawn_scoped_on<F>(future: F, handle: &runtime::Handle) -> ScopedTaskHandle<F::Output>
108where
109    F: Future + Send + 'static,
110    F::Output: Send + 'static,
111{
112    ScopedTaskHandle(handle.spawn(future))
113}
114
115/// A [`JoinHandle`](task::JoinHandle) that aborts its task when dropped.
116///
117/// Awaiting it yields the task's output, just like awaiting a plain `JoinHandle`.
118#[derive(Debug)]
119pub struct ScopedTaskHandle<T>(task::JoinHandle<T>);
120
121impl<T> Deref for ScopedTaskHandle<T> {
122    type Target = task::JoinHandle<T>;
123
124    fn deref(&self) -> &Self::Target {
125        &self.0
126    }
127}
128
129impl<T> DerefMut for ScopedTaskHandle<T> {
130    fn deref_mut(&mut self) -> &mut Self::Target {
131        &mut self.0
132    }
133}
134
135impl<T> Future for ScopedTaskHandle<T> {
136    type Output = Result<T, task::JoinError>;
137
138    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
139        Pin::new(&mut self.0).poll(cx)
140    }
141}
142
143impl<T> Drop for ScopedTaskHandle<T> {
144    fn drop(&mut self) {
145        self.0.abort();
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    use std::sync::Arc;
153    use tokio::sync::{Notify, mpsc};
154
155    #[tokio::test]
156    async fn test_dont_leak_finished_handles() {
157        let mut scope = TaskScope::new();
158        let start_signal = Arc::new(Notify::new());
159
160        let (tx, mut rx) = mpsc::unbounded_channel();
161        scope.spawn({
162            let signal = start_signal.clone();
163            async move {
164                signal.notified().await;
165                tx.send(42).unwrap();
166            }
167        });
168        assert_eq!(scope.0.len(), 1);
169
170        task::yield_now().await;
171        let result = rx.try_recv();
172        assert_eq!(result, Err(mpsc::error::TryRecvError::Empty));
173
174        start_signal.notify_one();
175        task::yield_now().await;
176        let result = rx.try_recv();
177        assert_eq!(result, Ok(42));
178
179        let (tx, mut rx) = mpsc::unbounded_channel();
180        scope.spawn({
181            let signal = start_signal.clone();
182            async move {
183                signal.notified().await;
184                tx.send(43).unwrap();
185            }
186        });
187        assert_eq!(scope.0.len(), 1);
188
189        task::yield_now().await;
190        let result = rx.try_recv();
191        assert_eq!(result, Err(mpsc::error::TryRecvError::Empty));
192    }
193
194    #[tokio::test]
195    async fn test_abort_all_on_drop() {
196        let mut scope = TaskScope::new();
197        let start_signal = Arc::new(Notify::new());
198        let (tx, mut rx) = mpsc::unbounded_channel();
199
200        let h1 = scope.spawn({
201            let signal = start_signal.clone();
202            let tx = tx.clone();
203            async move {
204                signal.notified().await;
205                tx.send(42).unwrap();
206            }
207        });
208        assert_eq!(scope.0.len(), 1);
209
210        let h2 = scope.spawn({
211            let signal = start_signal.clone();
212            let tx = tx.clone();
213            async move {
214                signal.notified().await;
215                tx.send(43).unwrap();
216            }
217        });
218        assert_eq!(scope.0.len(), 2);
219
220        task::yield_now().await;
221        let result = rx.try_recv();
222        assert_eq!(result, Err(mpsc::error::TryRecvError::Empty));
223
224        drop(tx);
225        drop(scope);
226        start_signal.notify_one();
227        task::yield_now().await;
228        let result = rx.try_recv();
229        assert_eq!(result, Err(mpsc::error::TryRecvError::Disconnected));
230        assert!(h1.is_finished());
231        assert!(h2.is_finished());
232    }
233
234    #[tokio::test]
235    async fn test_scoped_handle_returns_output() {
236        let mut handle = tokio_test::task::spawn(spawn_scoped(async { 42 }));
237        task::yield_now().await;
238        let result = tokio_test::assert_ready!(handle.poll());
239        assert_eq!(result.unwrap(), 42);
240    }
241
242    #[tokio::test]
243    async fn test_scoped_handle_aborts_on_drop() {
244        let start_signal = Arc::new(Notify::new());
245        let (tx, mut rx) = mpsc::unbounded_channel();
246
247        let handle = spawn_scoped({
248            let signal = start_signal.clone();
249            async move {
250                signal.notified().await;
251                tx.send(42).unwrap();
252            }
253        });
254        let abort_handle = handle.abort_handle();
255
256        task::yield_now().await;
257        let result = rx.try_recv();
258        assert_eq!(result, Err(mpsc::error::TryRecvError::Empty));
259
260        drop(handle);
261        start_signal.notify_one();
262        task::yield_now().await;
263        let result = rx.try_recv();
264        assert_eq!(result, Err(mpsc::error::TryRecvError::Disconnected));
265        assert!(abort_handle.is_finished());
266    }
267}