1use crate::{
4 shutdown::{signal, Shutdown, Signal},
5 Runtime,
6};
7use reth_concurrency::sync::{
8 atomic::{AtomicUsize, Ordering},
9 thread, time,
10};
11use std::{
12 any::Any,
13 fmt::{Display, Formatter},
14 pin::Pin,
15 sync::Arc,
16 task::{ready, Context, Poll},
17};
18use tokio::{
19 runtime::Handle,
20 sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
21 task::{self, JoinHandle},
22};
23use tracing::debug;
24
25pub type TaskExecutor = Runtime;
27
28#[track_caller]
37pub fn spawn_thread<F, T>(name: &str, f: F) -> thread::JoinHandle<T>
38where
39 F: FnOnce() -> T + Send + 'static,
40 T: Send + 'static,
41{
42 #[cfg(not(all(feature = "fuzz", dst)))]
43 let handle = Handle::try_current().ok();
44 thread::Builder::new()
45 .name(name.to_string())
46 .spawn(move || {
47 #[cfg(not(all(feature = "fuzz", dst)))]
48 let _guard = handle.as_ref().map(Handle::enter);
49 f()
50 })
51 .unwrap_or_else(|e| panic!("failed to spawn thread {name:?}: {e}"))
52}
53
54#[track_caller]
60pub fn spawn_scoped_thread<'scope, 'env, F, T>(
61 scope: &'scope thread::Scope<'scope, 'env>,
62 name: &str,
63 f: F,
64) -> thread::ScopedJoinHandle<'scope, T>
65where
66 F: FnOnce() -> T + Send + 'scope,
67 T: Send + 'scope,
68{
69 #[cfg(not(all(feature = "fuzz", dst)))]
70 let handle = Handle::try_current().ok();
71 thread::Builder::new()
72 .name(name.to_string())
73 .spawn_scoped(scope, move || {
74 #[cfg(not(all(feature = "fuzz", dst)))]
75 let _guard = handle.as_ref().map(Handle::enter);
76 f()
77 })
78 .unwrap_or_else(|e| panic!("failed to spawn scoped thread {name:?}: {e}"))
79}
80
81pub fn spawn_blocking<F, R>(func: F) -> JoinHandle<R>
90where
91 F: FnOnce() -> R + Send + 'static,
92 R: Send + 'static,
93{
94 task::spawn_blocking(Box::new(func) as Box<dyn FnOnce() -> R + Send>)
95}
96
97#[derive(Debug)]
107#[must_use = "TaskManager must be polled to monitor critical tasks"]
108pub struct TaskManager {
109 task_events_rx: UnboundedReceiver<TaskEvent>,
111 signal: Option<Signal>,
115 graceful_tasks: Arc<AtomicUsize>,
118}
119
120impl TaskManager {
123 pub(crate) fn new_parts(
126 _handle: Handle,
127 ) -> (Self, Shutdown, UnboundedSender<TaskEvent>, Arc<AtomicUsize>) {
128 let (task_events_tx, task_events_rx) = unbounded_channel();
129 let (signal, on_shutdown) = signal();
130 let graceful_tasks = Arc::new(AtomicUsize::new(0));
131 let manager = Self {
132 task_events_rx,
133 signal: Some(signal),
134 graceful_tasks: Arc::clone(&graceful_tasks),
135 };
136 (manager, on_shutdown, task_events_tx, graceful_tasks)
137 }
138
139 pub fn graceful_shutdown(self) {
141 let _ = self.do_graceful_shutdown(None);
142 }
143
144 pub fn graceful_shutdown_with_timeout(self, timeout: time::Duration) -> bool {
148 self.do_graceful_shutdown(Some(timeout))
149 }
150
151 fn do_graceful_shutdown(self, timeout: Option<time::Duration>) -> bool {
152 drop(self.signal);
153 let deadline = timeout.map(|t| time::Instant::now() + t);
154 while self.graceful_tasks.load(Ordering::SeqCst) > 0 {
155 if deadline.is_some_and(|d| time::Instant::now() > d) {
156 debug!("graceful shutdown timed out");
157 return false;
158 }
159 wait_for_shutdown_progress();
160 }
161 debug!("gracefully shut down");
162 true
163 }
164}
165
166pub(crate) fn wait_for_shutdown_progress() {
167 #[cfg(not(all(feature = "fuzz", dst)))]
168 thread::yield_now();
169 #[cfg(all(feature = "fuzz", dst))]
171 time::sleep(time::Duration::from_millis(1));
172}
173
174impl std::future::Future for TaskManager {
178 type Output = Result<(), PanickedTaskError>;
179
180 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
181 match ready!(self.as_mut().get_mut().task_events_rx.poll_recv(cx)) {
182 Some(TaskEvent::Panic(err)) => Poll::Ready(Err(err)),
183 Some(TaskEvent::GracefulShutdown) | None => {
184 if let Some(signal) = self.get_mut().signal.take() {
185 signal.fire();
186 }
187 Poll::Ready(Ok(()))
188 }
189 }
190 }
191}
192
193#[derive(Debug, thiserror::Error, PartialEq, Eq)]
195pub struct PanickedTaskError {
196 pub(super) task_name: &'static str,
197 pub(super) error: Option<String>,
198}
199
200impl Display for PanickedTaskError {
201 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
202 let task_name = self.task_name;
203 if let Some(error) = &self.error {
204 write!(f, "Critical task `{task_name}` panicked: `{error}`")
205 } else {
206 write!(f, "Critical task `{task_name}` panicked")
207 }
208 }
209}
210
211impl PanickedTaskError {
212 pub(crate) fn new(task_name: &'static str, error: Box<dyn Any>) -> Self {
213 let error = match error.downcast::<String>() {
214 Ok(value) => Some(*value),
215 Err(error) => match error.downcast::<&str>() {
216 Ok(value) => Some(value.to_string()),
217 Err(_) => None,
218 },
219 };
220
221 Self { task_name, error }
222 }
223}
224
225#[derive(Debug)]
227pub(crate) enum TaskEvent {
228 Panic(PanickedTaskError),
230 GracefulShutdown,
232}
233
234#[cfg(all(test, not(all(feature = "fuzz", dst))))]
236mod tests {
237 use super::*;
238 use crate::test_utils;
239 use std::{
240 sync::atomic::{AtomicBool, AtomicUsize, Ordering},
241 time::Duration,
242 };
243 use tokio::time::sleep;
244
245 #[test]
246 fn test_critical() {
247 test_utils::run(|| {
248 let rt = Runtime::test();
249 let handle = rt.take_task_manager_handle().unwrap();
250
251 rt.spawn_critical_task("this is a critical task", async {
252 panic!("intentionally panic")
253 });
254
255 rt.handle().block_on(async move {
256 let panicked_err = handle.await.unwrap().unwrap_err();
257
258 assert_eq!(panicked_err.task_name, "this is a critical task");
259 assert_eq!(panicked_err.error, Some("intentionally panic".to_string()));
260 })
261 });
262 }
263
264 #[test]
265 fn test_manager_shutdown_critical() {
266 test_utils::run(|| {
267 let rt = Runtime::test();
268
269 let (signal, shutdown) = signal();
270
271 rt.spawn_critical_task("this is a critical task", async move {
272 sleep(Duration::from_millis(200)).await;
273 drop(signal);
274 });
275
276 rt.graceful_shutdown();
277
278 rt.handle().block_on(shutdown);
279 });
280 }
281
282 #[test]
283 fn test_manager_shutdown() {
284 test_utils::run(|| {
285 let rt = Runtime::test();
286
287 let (signal, shutdown) = signal();
288
289 rt.spawn_task(async move {
290 sleep(Duration::from_millis(200)).await;
291 drop(signal);
292 });
293
294 rt.graceful_shutdown();
295
296 rt.handle().block_on(shutdown);
297 });
298 }
299
300 #[test]
301 fn test_manager_graceful_shutdown() {
302 test_utils::run(|| {
303 let rt = Runtime::test();
304
305 let val = Arc::new(AtomicBool::new(false));
306 let c = val.clone();
307 rt.spawn_critical_with_graceful_shutdown_signal("grace", async move |shutdown| {
308 let _guard = shutdown.await;
309 sleep(Duration::from_millis(200)).await;
310 c.store(true, Ordering::Relaxed);
311 });
312
313 rt.graceful_shutdown();
314 assert!(val.load(Ordering::Relaxed));
315 });
316 }
317
318 #[test]
319 fn test_manager_graceful_shutdown_many() {
320 test_utils::run(|| {
321 let rt = Runtime::test();
322
323 let counter = Arc::new(AtomicUsize::new(0));
324 let num = 10;
325 for _ in 0..num {
326 let c = counter.clone();
327 rt.spawn_critical_with_graceful_shutdown_signal("grace", async move |shutdown| {
328 let _guard = shutdown.await;
329 sleep(Duration::from_millis(200)).await;
330 c.fetch_add(1, Ordering::SeqCst);
331 });
332 }
333
334 rt.graceful_shutdown();
335 assert_eq!(counter.load(Ordering::Relaxed), num);
336 });
337 }
338
339 #[test]
340 fn test_manager_graceful_shutdown_timeout() {
341 test_utils::run(|| {
342 let rt = Runtime::test();
343
344 let timeout = Duration::from_millis(500);
345 let val = Arc::new(AtomicBool::new(false));
346 let val2 = val.clone();
347 rt.spawn_critical_with_graceful_shutdown_signal("grace", async move |shutdown| {
348 let _guard = shutdown.await;
349 sleep(timeout * 3).await;
350 val2.store(true, Ordering::Relaxed);
351 unreachable!("should not be reached");
352 });
353
354 rt.graceful_shutdown_with_timeout(timeout);
355 assert!(!val.load(Ordering::Relaxed));
356 });
357 }
358
359 #[test]
360 fn can_build_runtime() {
361 test_utils::run(|| {
362 let rt = Runtime::test();
363 let _handle = rt.handle();
364 });
365 }
366
367 #[test]
368 fn test_graceful_shutdown_triggered_by_executor() {
369 test_utils::run(|| {
370 let rt = Runtime::test();
371 let task_manager_handle = rt.take_task_manager_handle().unwrap();
372
373 let task_did_shutdown_flag = Arc::new(AtomicBool::new(false));
374 let flag_clone = task_did_shutdown_flag.clone();
375
376 let spawned_task_handle = rt.spawn_with_signal(async move |shutdown_signal| {
377 shutdown_signal.await;
378 flag_clone.store(true, Ordering::SeqCst);
379 });
380
381 let send_result = rt.initiate_graceful_shutdown();
382 assert!(send_result.is_ok());
383
384 let manager_final_result = rt.handle().block_on(task_manager_handle);
385 assert!(manager_final_result.is_ok(), "TaskManager task should not panic");
386 assert_eq!(manager_final_result.unwrap(), Ok(()));
387
388 let task_join_result = rt.handle().block_on(spawned_task_handle);
389 assert!(task_join_result.is_ok());
390
391 assert!(task_did_shutdown_flag.load(Ordering::Relaxed));
392 });
393 }
394}