Skip to main content

common/
task_scope.rs

1//! Task-scoped cancellation accounting for spawned asynchronous descendants.
2
3use std::sync::Arc;
4
5#[derive(Clone)]
6struct TaskTracker {
7    state: Arc<TaskTrackerState>,
8}
9
10struct TaskTrackerState {
11    active: std::sync::atomic::AtomicUsize,
12    idle: tokio::sync::Notify,
13}
14
15struct TrackedTask(TaskTracker);
16
17pin_project_lite::pin_project! {
18    /// One child future paired with the task-scope guard that accounts for it.
19    ///
20    /// Field order is load-bearing: cancelling even an unpolled Tokio task must destroy the child
21    /// future and all of its captures before [`TrackedTask`] decrements the scope's active count.
22    struct TrackedFuture<F> {
23        #[pin]
24        future: F,
25        _tracked: TrackedTask,
26    }
27}
28
29impl<F> std::future::Future for TrackedFuture<F>
30where
31    F: std::future::Future,
32{
33    type Output = F::Output;
34
35    fn poll(
36        self: std::pin::Pin<&mut Self>,
37        cx: &mut std::task::Context<'_>,
38    ) -> std::task::Poll<Self::Output> {
39        self.project().future.poll(cx)
40    }
41}
42
43impl TaskTracker {
44    fn new() -> Self {
45        Self {
46            state: Arc::new(TaskTrackerState {
47                active: std::sync::atomic::AtomicUsize::new(0),
48                idle: tokio::sync::Notify::new(),
49            }),
50        }
51    }
52
53    fn enter(&self) -> TrackedTask {
54        self.state
55            .active
56            .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
57        TrackedTask(self.clone())
58    }
59
60    async fn wait_idle(&self) {
61        loop {
62            let idle = self.state.idle.notified();
63            if self.state.active.load(std::sync::atomic::Ordering::Acquire) == 0 {
64                return;
65            }
66            idle.await;
67        }
68    }
69}
70
71impl Drop for TrackedTask {
72    fn drop(&mut self) {
73        if self
74            .0
75            .state
76            .active
77            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel)
78            == 1
79        {
80            self.0.state.idle.notify_one();
81        }
82    }
83}
84
85tokio::task_local! {
86    static TASK_TRACKER: TaskTracker;
87}
88
89/// Runs an operation in a task scope and waits for cancelled descendants to finish dropping.
90pub async fn scope_tasks<F>(future: F) -> F::Output
91where
92    F: std::future::Future,
93{
94    if TASK_TRACKER.try_with(Clone::clone).is_ok() {
95        return future.await;
96    }
97    let tracker = TaskTracker::new();
98    let output = TASK_TRACKER.scope(tracker.clone(), future).await;
99    tracker.wait_idle().await;
100    output
101}
102
103/// Spawns work tracked by the current task scope.
104pub fn spawn_tracked<T, F>(join_set: &mut tokio::task::JoinSet<T>, future: F)
105where
106    T: Send + 'static,
107    F: std::future::Future<Output = T> + Send + 'static,
108{
109    let tracker = TASK_TRACKER
110        .try_with(Clone::clone)
111        .expect("tracked work must run inside a task scope");
112    let tracked = tracker.enter();
113    join_set.spawn(TASK_TRACKER.scope(
114        tracker,
115        TrackedFuture {
116            future,
117            _tracked: tracked,
118        },
119    ));
120}