Skip to main content

reth_tasks/
lib.rs

1//! Reth task management.
2//!
3//! Blocking concurrency primitives are provided by [`reth_concurrency::sync`].
4//!
5//! # Feature Flags
6//!
7//! - `rayon`: Enable native task-management helpers for rayon thread pools.
8//! - `fuzz`: Enable simulation support; primitives remain native unless `--cfg dst` is also set.
9//!   With both enabled, threads, selected channels, pools, and time use the deterministic backend.
10//!   Existing Tokio channels remain native and are not controlled by Shuttle.
11
12#![doc(
13    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
14    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
15    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
16)]
17#![cfg_attr(not(test), warn(unused_crate_dependencies))]
18#![cfg_attr(docsrs, feature(doc_cfg))]
19
20// Backend-dependent task integration must agree with the selected primitive types.
21const _: () = assert!(
22    cfg!(all(feature = "fuzz", dst)) == reth_concurrency::sync::IS_SIMULATED,
23    "enable reth-tasks/fuzz when enabling reth-concurrency/fuzz with --cfg dst"
24);
25
26#[cfg(all(feature = "fuzz", not(dst)))]
27use shuttle as _;
28
29pub mod cancel;
30pub mod lazy;
31pub mod metrics;
32pub mod runtime;
33pub mod shutdown;
34pub mod utils;
35pub(crate) mod worker_map;
36
37#[cfg(feature = "rayon")]
38pub mod pool;
39#[cfg(feature = "rayon")]
40pub use pool::{build_pool_with_panic_handler, Worker, WorkerPool, WorkerStatefulPool};
41
42/// Lock-free ordered parallel iterator extension trait.
43#[cfg(feature = "rayon")]
44pub mod for_each_ordered;
45#[cfg(feature = "rayon")]
46pub use for_each_ordered::ForEachOrdered;
47
48pub use cancel::{CancelOnDrop, ManualCancel};
49pub use lazy::LazyHandle;
50#[cfg(feature = "rayon")]
51pub use runtime::RayonConfig;
52pub use runtime::{Runtime, RuntimeBuildError, RuntimeBuilder, RuntimeConfig, TokioConfig};
53
54mod task_manager;
55pub use task_manager::{
56    spawn_blocking, spawn_scoped_thread, spawn_thread, PanickedTaskError, TaskExecutor, TaskManager,
57};
58// Preserve the original native thread helper names.
59#[cfg(not(all(feature = "fuzz", dst)))]
60pub use task_manager::{
61    spawn_scoped_thread as spawn_scoped_os_thread, spawn_thread as spawn_os_thread,
62};
63pub(crate) use task_manager::{wait_for_shutdown_progress, TaskEvent};
64
65#[cfg(test)]
66mod test_utils {
67    use reth_concurrency::sync::Runtime;
68    use tokio::runtime::Builder;
69
70    // This lock is acquired before entering the selected runtime and serializes simulations.
71    #[cfg(all(feature = "fuzz", dst))]
72    #[allow(
73        clippy::disallowed_types,
74        reason = "Host lock serializes separate simulations before either enters Shuttle."
75    )]
76    use std::sync::Mutex;
77
78    #[cfg(feature = "rayon")]
79    use futures_util::FutureExt;
80    #[cfg(feature = "rayon")]
81    use reth_concurrency::sync::thread;
82    #[cfg(feature = "rayon")]
83    #[allow(
84        clippy::disallowed_types,
85        reason = "Host watchdog bounds stalled simulations independently of virtual time."
86    )]
87    use std::{
88        future::Future,
89        pin::pin,
90        time::{Duration, Instant},
91    };
92
93    #[cfg_attr(
94        all(feature = "fuzz", dst),
95        allow(
96            clippy::disallowed_types,
97            clippy::disallowed_methods,
98            reason = "Host lock serializes separate simulations before either enters Shuttle."
99        )
100    )]
101    pub(crate) fn run(work: impl FnOnce() + Send + 'static) {
102        // Separate simulations cannot concurrently lease the process-global compute pool.
103        #[cfg(all(feature = "fuzz", dst))]
104        static SIMULATION: Mutex<()> = Mutex::new(());
105        #[cfg(all(feature = "fuzz", dst))]
106        let _simulation = SIMULATION.lock().unwrap_or_else(|error| error.into_inner());
107
108        let tokio = Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
109        // Logical threads share the runner's OS thread and its Tokio context.
110        let _entered = tokio.enter();
111        Runtime::new().run(work);
112    }
113
114    #[cfg(feature = "rayon")]
115    #[allow(
116        clippy::disallowed_types,
117        clippy::disallowed_methods,
118        reason = "Host watchdog bounds stalled simulations independently of virtual time."
119    )]
120    pub(crate) fn block_on<F: Future>(future: F) -> F::Output {
121        let mut future = pin!(future);
122        // A native watchdog bounds Tokio work even while this runnable poller stalls virtual time.
123        let deadline = Instant::now() + Duration::from_secs(5);
124        loop {
125            if let Some(result) = future.as_mut().now_or_never() {
126                return result;
127            }
128            assert!(Instant::now() < deadline, "task future did not complete");
129            // Tokio's block_on would park the OS thread instead of scheduling logical workers.
130            thread::yield_now();
131        }
132    }
133}