Skip to main content

rocketmq_runtime/task_group/
counted.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::future::Future;
16use std::panic::AssertUnwindSafe;
17use std::sync::atomic::AtomicBool;
18use std::sync::atomic::AtomicU64;
19use std::sync::atomic::AtomicUsize;
20use std::sync::atomic::Ordering;
21use std::sync::Arc;
22use std::sync::Weak;
23use std::time::Instant;
24
25use futures::future::FutureExt;
26use tokio::sync::Notify;
27use tokio_util::sync::CancellationToken;
28
29use super::TaskGroup;
30use super::TaskGroupLifecycleState;
31use crate::error::RuntimeError;
32use crate::error::RuntimeResult;
33use crate::shutdown_deadline::ShutdownDeadline;
34use crate::shutdown_deadline::ABORT_CONFIRMATION_TIMEOUT;
35use crate::CancellationObserver;
36use crate::RuntimeOperation;
37
38/// Short-lived tasks of one owner, counted instead of registered one by one.
39///
40/// The other spawn methods of [`TaskGroup`] give every task an id, metadata and an abort handle
41/// in the group's registry, so the group can report, wait for and abort each one. That costs
42/// several locks and allocations per task, which dominates tasks that live for one request.
43/// A set keeps only a count of its running tasks.
44///
45/// Its tasks run on the group's runtime and are tracked by the group, so the group's shutdown
46/// waits for them like for its draining operation tasks. Every task races the cancellation
47/// token the set was created with: cancelling it drops each running task's future at its next
48/// poll, which is when an aborted task stops too. The owner closes the set and waits for it with
49/// [`drain_until`](Self::drain_until). Tasks of a set its owner dropped keep running, owned by
50/// the group: a group shutdown that reaches its deadline cancels the token of every set it
51/// created, where it aborts its registered tasks.
52pub struct CountedTaskSet {
53    inner: Arc<CountedTaskSetInner>,
54}
55
56pub(super) struct CountedTaskSetInner {
57    group: TaskGroup,
58    // Checked and awaited by every task, so through an observer rather than the token's lock.
59    stop: CancellationObserver,
60    active: AtomicUsize,
61    closed: AtomicBool,
62    // Set by a waiter; only then does a task that leaves the set idle notify `idle`.
63    draining: AtomicBool,
64    idle: Notify,
65    panicked: AtomicU64,
66}
67
68impl TaskGroup {
69    /// Creates a [`CountedTaskSet`] whose tasks run on this group's runtime, are tracked by this
70    /// group and stop when `stop` is cancelled.
71    pub fn counted_task_set(&self, stop: CancellationToken) -> CountedTaskSet {
72        let inner = Arc::new(CountedTaskSetInner {
73            group: self.clone(),
74            stop: CancellationObserver::new(stop),
75            active: AtomicUsize::new(0),
76            closed: AtomicBool::new(false),
77            draining: AtomicBool::new(false),
78            idle: Notify::new(),
79            panicked: AtomicU64::new(0),
80        });
81        let mut sets = self.inner.counted_sets.lock();
82        sets.retain(|set| set.strong_count() > 0);
83        sets.push(Arc::downgrade(&inner));
84        drop(sets);
85        CountedTaskSet { inner }
86    }
87}
88
89/// Cancels the token of every live set in `sets` and returns how many of their tasks were running.
90pub(super) fn stop_counted_sets(sets: &parking_lot::Mutex<Vec<Weak<CountedTaskSetInner>>>) -> usize {
91    let live: Vec<_> = sets.lock().iter().filter_map(Weak::upgrade).collect();
92    live.iter()
93        .map(|set| {
94            set.stop.token().cancel();
95            set.active.load(Ordering::SeqCst)
96        })
97        .sum()
98}
99
100impl CountedTaskSet {
101    /// Spawns `future` as a counted task.
102    ///
103    /// A panic in the future ends only its task and is counted in [`Self::panicked`].
104    ///
105    /// # Errors
106    ///
107    /// Returns a closed error once the set is closed or its token cancelled, and the group's
108    /// admission error once the group no longer accepts tasks.
109    pub fn spawn<F>(&self, future: F) -> RuntimeResult<()>
110    where
111        F: Future<Output = ()> + Send + 'static,
112    {
113        let state = self.inner.group.lifecycle_state();
114        if state != TaskGroupLifecycleState::Open {
115            return Err(state.admission_error(RuntimeOperation::SpawnTaskGroupTask));
116        }
117        // Counted before the closed check, and `close` publishes before a waiter reads the
118        // count (both sequentially consistent): a spawn that a waiter does not see sees the set
119        // closed and backs out.
120        self.inner.active.fetch_add(1, Ordering::SeqCst);
121        let task = CountedTask {
122            inner: Arc::clone(&self.inner),
123        };
124        if self.inner.closed.load(Ordering::SeqCst) || self.inner.stop.is_cancelled() {
125            drop(task);
126            return Err(RuntimeError::closed(RuntimeOperation::SpawnTaskGroupTask));
127        }
128        let tracked = self.inner.group.inner.tracker.track_future(task.run(future));
129        drop(self.inner.group.inner.runtime.tokio_handle().spawn(tracked));
130        Ok(())
131    }
132
133    /// Stops accepting tasks. Running tasks continue.
134    pub fn close(&self) {
135        self.inner.closed.store(true, Ordering::SeqCst);
136    }
137
138    /// Returns the number of tasks that have not finished.
139    pub fn active(&self) -> usize {
140        self.inner.active.load(Ordering::SeqCst)
141    }
142
143    /// Returns the number of tasks whose future panicked.
144    pub fn panicked(&self) -> u64 {
145        self.inner.panicked.load(Ordering::Relaxed)
146    }
147
148    /// Closes the set and waits until every task has finished or `deadline` passes.
149    ///
150    /// Tasks still running at the deadline are stopped through the set's token, and the call
151    /// waits up to one second for their futures to be dropped, as
152    /// [`OperationContext::wait`](crate::OperationContext::wait) does for aborted tasks. Returns
153    /// whether every task finished before the deadline.
154    pub async fn drain_until(&self, deadline: ShutdownDeadline) -> bool {
155        self.close();
156        if self.wait_idle(deadline.instant()).await {
157            return true;
158        }
159        self.inner.stop.token().cancel();
160        let _ = self.wait_idle(Instant::now() + ABORT_CONFIRMATION_TIMEOUT).await;
161        false
162    }
163
164    async fn wait_idle(&self, until: Instant) -> bool {
165        self.inner.draining.store(true, Ordering::SeqCst);
166        loop {
167            // Enabled before the count is read, so a task that finishes in between is not missed.
168            let notified = self.inner.idle.notified();
169            tokio::pin!(notified);
170            notified.as_mut().enable();
171            if self.inner.active.load(Ordering::SeqCst) == 0 {
172                return true;
173            }
174            if tokio::time::timeout_at(until.into(), notified).await.is_err() {
175                return self.inner.active.load(Ordering::SeqCst) == 0;
176            }
177        }
178    }
179}
180
181/// One task's place in the set: counted from spawn until it is dropped, even if the runtime drops
182/// the task without polling it.
183struct CountedTask {
184    inner: Arc<CountedTaskSetInner>,
185}
186
187impl CountedTask {
188    async fn run<F>(self, future: F)
189    where
190        F: Future<Output = ()>,
191    {
192        let inner = &self.inner;
193        // The future is polled first, so the token is not polled on the poll that finishes it.
194        tokio::select! {
195            biased;
196            result = AssertUnwindSafe(future).catch_unwind() => {
197                if result.is_err() {
198                    inner.panicked.fetch_add(1, Ordering::Relaxed);
199                    tracing::error!("counted task panicked");
200                }
201            }
202            () = inner.stop.cancelled() => {}
203        }
204    }
205}
206
207impl Drop for CountedTask {
208    fn drop(&mut self) {
209        if self.inner.active.fetch_sub(1, Ordering::SeqCst) == 1 && self.inner.draining.load(Ordering::SeqCst) {
210            self.inner.idle.notify_waiters();
211        }
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use std::time::Duration;
218
219    use tokio::sync::oneshot;
220
221    use super::*;
222    use crate::RuntimeContext;
223
224    fn set_with_token() -> (TaskGroup, CountedTaskSet, CancellationToken) {
225        let context = RuntimeContext::from_current("counted-task-set");
226        let group = context.service_context("owner").task_group().clone();
227        let stop = CancellationToken::new();
228        let set = group.counted_task_set(stop.clone());
229        (group, set, stop)
230    }
231
232    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
233    async fn drain_waits_for_running_tasks_to_finish() {
234        let (_group, set, stop) = set_with_token();
235        let (release, released) = oneshot::channel::<()>();
236        let (finished_tx, finished) = oneshot::channel::<()>();
237        set.spawn(async move {
238            let _ = released.await;
239            let _ = finished_tx.send(());
240        })
241        .unwrap();
242        assert_eq!(set.active(), 1);
243
244        let drained = tokio::spawn(async move {
245            let drained = set.drain_until(ShutdownDeadline::after(Duration::from_secs(5))).await;
246            (drained, set.active())
247        });
248        tokio::task::yield_now().await;
249        assert!(!drained.is_finished(), "the drain waits for the running task");
250        release.send(()).unwrap();
251
252        assert_eq!(drained.await.unwrap(), (true, 0));
253        finished.await.expect("the task ran to completion");
254        drop(stop);
255    }
256
257    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
258    async fn drain_stops_tasks_still_running_at_the_deadline() {
259        let (_group, set, stop) = set_with_token();
260        let (dropped_tx, dropped) = oneshot::channel::<()>();
261        struct NotifyOnDrop(Option<oneshot::Sender<()>>);
262        impl Drop for NotifyOnDrop {
263            fn drop(&mut self) {
264                if let Some(sender) = self.0.take() {
265                    let _ = sender.send(());
266                }
267            }
268        }
269        set.spawn(async move {
270            let _notify = NotifyOnDrop(Some(dropped_tx));
271            std::future::pending::<()>().await;
272        })
273        .unwrap();
274
275        let drained = set
276            .drain_until(ShutdownDeadline::after(Duration::from_millis(50)))
277            .await;
278
279        assert!(!drained, "the task did not finish before the deadline");
280        assert!(stop.is_cancelled(), "the late task is stopped through the token");
281        assert_eq!(set.active(), 0);
282        dropped.await.expect("the late task's future was dropped");
283    }
284
285    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
286    async fn cancelling_the_token_stops_running_tasks() {
287        let (_group, set, stop) = set_with_token();
288        set.spawn(std::future::pending::<()>()).unwrap();
289        stop.cancel();
290
291        assert!(set.drain_until(ShutdownDeadline::after(Duration::from_secs(5))).await);
292        assert!(set.spawn(async {}).is_err(), "a cancelled set takes no new task");
293    }
294
295    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
296    async fn a_closed_set_takes_no_new_task() {
297        let (_group, set, _stop) = set_with_token();
298        set.close();
299
300        let error = set.spawn(async {}).expect_err("closed set");
301        assert_eq!(error.kind(), crate::RuntimeErrorKind::Closed);
302        assert_eq!(set.active(), 0);
303    }
304
305    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
306    async fn a_panicking_task_is_counted_and_leaves_the_others_running() {
307        let (_group, set, _stop) = set_with_token();
308        let (finished_tx, finished) = oneshot::channel::<()>();
309        set.spawn(async { panic!("counted task test panic") }).unwrap();
310        set.spawn(async move {
311            tokio::task::yield_now().await;
312            let _ = finished_tx.send(());
313        })
314        .unwrap();
315
316        finished.await.expect("the other task finished");
317        assert!(set.drain_until(ShutdownDeadline::after(Duration::from_secs(5))).await);
318        assert_eq!(set.panicked(), 1);
319    }
320
321    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
322    async fn a_dropped_sets_tasks_run_until_the_group_shutdown_deadline_stops_them() {
323        let (group, set, stop) = set_with_token();
324        let (dropped_tx, dropped) = oneshot::channel::<()>();
325        struct NotifyOnDrop(Option<oneshot::Sender<()>>);
326        impl Drop for NotifyOnDrop {
327            fn drop(&mut self) {
328                if let Some(sender) = self.0.take() {
329                    let _ = sender.send(());
330                }
331            }
332        }
333        set.spawn(async move {
334            let _notify = NotifyOnDrop(Some(dropped_tx));
335            std::future::pending::<()>().await;
336        })
337        .unwrap();
338
339        drop(set);
340        assert!(
341            !stop.is_cancelled(),
342            "the group, not the set's owner, owns the task now"
343        );
344
345        let report = group.shutdown(Duration::from_millis(50)).await;
346
347        assert!(stop.is_cancelled(), "the shutdown deadline stops the task");
348        assert_eq!(report.aborted, 1, "{report:?}");
349        tokio::time::timeout(Duration::from_secs(5), dropped)
350            .await
351            .expect("the task's future was dropped")
352            .expect("drop notification");
353    }
354
355    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
356    async fn group_shutdown_waits_for_counted_tasks() {
357        let (group, set, _stop) = set_with_token();
358        let (release, released) = oneshot::channel::<()>();
359        set.spawn(async move {
360            let _ = released.await;
361        })
362        .unwrap();
363
364        let shutdown = tokio::spawn({
365            let group = group.clone();
366            async move { group.shutdown(Duration::from_secs(5)).await }
367        });
368        tokio::time::sleep(Duration::from_millis(50)).await;
369        assert!(!shutdown.is_finished(), "the group waits for its counted task");
370        release.send(()).unwrap();
371
372        let report = shutdown.await.unwrap();
373        assert!(report.assert_no_task_leak().is_ok(), "{report:?}");
374        drop(set);
375    }
376}