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
use std::future::Future;
use tokio::{runtime::Handle, task::JoinHandle};
use tokio_util::{
sync::{CancellationToken, WaitForCancellationFuture, WaitForCancellationFutureOwned},
task::{task_tracker::TaskTrackerWaitFuture, TaskTracker},
};
/// This is a wrapper around a [`TaskTracker`] and a [`CancellationToken`]. It
/// is used to manage a set of tasks, and to token them to shut down when the
/// set is dropped.
///
/// When a [`Handle`] is provided, tasks are spawned on that handle. Otherwise,
/// they are spawned on the current runtime.
#[derive(Debug, Clone, Default)]
pub(crate) struct TaskSet {
tasks: TaskTracker,
token: CancellationToken,
handle: Option<Handle>,
}
impl From<Handle> for TaskSet {
fn from(handle: Handle) -> Self {
Self::from_handle(handle)
}
}
#[allow(dead_code)] // used in pubsub and axum features
impl TaskSet {
/// Create a new [`TaskSet`] with a handle.
pub(crate) fn from_handle(handle: Handle) -> Self {
Self {
tasks: TaskTracker::new(),
token: CancellationToken::new(),
handle: Some(handle),
}
}
/// Change the handle for the task set. This is used to spawn tasks on a
/// specific runtime.This should generally not be called after tasks have
/// been spawned.
pub(crate) fn with_handle(mut self, handle: Handle) -> Self {
self.handle = Some(handle);
self
}
/// Get a handle to the runtime that the task set is running on.
///
/// ## Panics
///
/// This will panic if called outside the context of a Tokio runtime.
pub(crate) fn handle(&self) -> Handle {
self.handle
.clone()
.unwrap_or_else(tokio::runtime::Handle::current)
}
/// Cancel the token, causing all tasks to be cancelled.
pub(crate) fn cancel(&self) {
self.token.cancel();
self.close();
}
/// True if the token is cancelled.
pub(crate) fn is_cancelled(&self) -> bool {
self.token.is_cancelled()
}
/// Get a future that resolves when the token is fired.
pub(crate) fn cancelled(&self) -> WaitForCancellationFuture<'_> {
self.token.cancelled()
}
/// Close the task tracker, allowing [`Self::wait`] futures to resolve.
pub(crate) fn close(&self) {
self.tasks.close();
}
/// True if the task set is closed.
pub(crate) fn is_closed(&self) -> bool {
self.tasks.is_closed()
}
/// Get a future that resolves when all tasks in the set are complete.
pub(crate) fn wait(&self) -> TaskTrackerWaitFuture<'_> {
self.tasks.wait()
}
/// Shutdown the task set. This will cancel all tasks and wait for them to
/// complete.
pub(crate) async fn shutdown(&self) {
self.cancel();
self.close();
self.tasks.wait().await
}
/// Get a child [`TaskSet`]. This set will be fired when the parent
/// set is fired, or may be fired independently.
pub(crate) fn child(&self) -> Self {
Self {
tasks: TaskTracker::new(),
token: self.token.child_token(),
handle: self.handle.clone(),
}
}
/// Prepare a future to be added to the task set, by wrapping it with a
/// cancellation token.
fn prep_abortable_fut<F>(
&self,
task: F,
) -> impl Future<Output = Option<F::Output>> + Send + 'static
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let token = self.token.clone();
async move {
tokio::select! {
_ = token.cancelled() => None,
result = task => Some(result),
}
}
}
/// Spawn a future on the provided handle, and add it to the task set. A
/// future spawned this way will be aborted when the [`TaskSet`] is
/// cancelled.
///
/// If the future completes before the task set is cancelled, the result
/// will be returned. Otherwise, `None` will be returned.
///
/// ## Panics
///
/// This will panic if called outside the context of a Tokio runtime when
/// `self.handle` is `None`.
pub(crate) fn spawn_cancellable<F>(&self, task: F) -> JoinHandle<Option<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.tasks
.spawn_on(self.prep_abortable_fut(task), &self.handle())
}
/// Spawn a blocking future on the provided handle, and add it to the task
/// set. A future spawned this way will be cancelled when the [`TaskSet`]
/// is cancelled.
///
/// ## Panics
///
/// This will panic if called outside the context of a Tokio runtime when
/// `self.handle` is `None`.
pub(crate) fn spawn_blocking_cancellable<F>(&self, task: F) -> JoinHandle<Option<F::Output>>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let h = self.handle();
let task = self.prep_abortable_fut(task);
self.tasks
.spawn_blocking_on(move || h.block_on(task), &self.handle())
}
/// Spawn a future on the provided handle, and add it to the task set. A
/// future spawned this way will not be aborted when the [`TaskSet`] is
/// cancelled, instead it will receive a notification via a
/// [`CancellationToken`]. This allows the future to complete gracefully.
/// This is useful for tasks that need to clean up resources before
/// completing.
///
/// ## Panics
///
/// This will panic if called outside the context of a Tokio runtime when
/// `self.handle` is `None`.
pub(crate) fn spawn_graceful<F, Fut>(&self, task: F) -> JoinHandle<Fut::Output>
where
F: FnOnce(WaitForCancellationFutureOwned) -> Fut + Send + 'static,
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
let token = self.token.clone().cancelled_owned();
self.tasks.spawn_on(task(token), &self.handle())
}
/// Spawn a blocking future on the provided handle, and add it to the task
/// set. A future spawned this way will not be cancelled when the
/// [`TaskSet`] is cancelled, instead it will receive a notification via a
/// [`CancellationToken`]. This allows the future to complete gracefully.
/// This is useful for tasks that need to clean up resources before
/// completing.
///
/// ## Panics
///
/// This will panic if called outside the context of a Tokio runtime when
/// `self.handle` is `None`.
pub(crate) fn spawn_blocking_graceful<F, Fut>(&self, task: F) -> JoinHandle<Fut::Output>
where
F: FnOnce(WaitForCancellationFutureOwned) -> Fut + Send + 'static,
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
let h = self.handle();
let token = self.token.clone().cancelled_owned();
let task = task(token);
self.tasks
.spawn_blocking_on(move || h.block_on(task), &self.handle())
}
}