rocketmq_runtime/task_group/
counted.rs1use 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
38pub struct CountedTaskSet {
53 inner: Arc<CountedTaskSetInner>,
54}
55
56pub(super) struct CountedTaskSetInner {
57 group: TaskGroup,
58 stop: CancellationObserver,
60 active: AtomicUsize,
61 closed: AtomicBool,
62 draining: AtomicBool,
64 idle: Notify,
65 panicked: AtomicU64,
66}
67
68impl TaskGroup {
69 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
89pub(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 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 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 pub fn close(&self) {
135 self.inner.closed.store(true, Ordering::SeqCst);
136 }
137
138 pub fn active(&self) -> usize {
140 self.inner.active.load(Ordering::SeqCst)
141 }
142
143 pub fn panicked(&self) -> u64 {
145 self.inner.panicked.load(Ordering::Relaxed)
146 }
147
148 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 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
181struct 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 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}