Skip to main content

reth_tasks/
worker_map.rs

1//! A map of named single-thread worker pools.
2//!
3//! Each worker is a dedicated OS thread that processes closures sent to it via a channel.
4//! This is a substitute for `spawn_blocking` that reuses the same OS thread for the same
5//! named task, like a 1-thread thread pool keyed by name. Under `fuzz` plus `--cfg dst`, workers
6//! use the deterministic executor and work queues use the selected channel backend.
7//! Task results still use Tokio oneshot channels.
8
9use crate::metrics::WorkerThreadMetrics;
10use dashmap::DashMap;
11use reth_concurrency::sync::{
12    atomic::{AtomicUsize, Ordering},
13    thread,
14    time::Instant,
15};
16use std::{panic::AssertUnwindSafe, sync::Arc};
17use tokio::sync::oneshot;
18
19#[cfg(not(all(feature = "fuzz", dst)))]
20use tokio::sync::mpsc;
21
22#[cfg(all(feature = "fuzz", dst))]
23use reth_concurrency::sync::channel;
24
25type BoxedTask = Box<dyn FnOnce() + Send + 'static>;
26
27/// A single-thread worker that processes closures sequentially on a dedicated OS thread.
28struct WorkerThread {
29    /// Sender to submit work to this worker's thread.
30    #[cfg(not(all(feature = "fuzz", dst)))]
31    tx: mpsc::UnboundedSender<BoxedTask>,
32    #[cfg(all(feature = "fuzz", dst))]
33    tx: Option<channel::Sender<BoxedTask>>,
34    /// Metrics labeled with this worker's name.
35    metrics: WorkerThreadMetrics,
36    /// Number of tasks currently running or queued on this worker.
37    pending: Arc<AtomicUsize>,
38    /// The OS thread handle. Taken during shutdown to join.
39    handle: Option<thread::JoinHandle<()>>,
40}
41
42impl WorkerThread {
43    /// Spawns a new worker thread with the given name.
44    fn new(name: &'static str) -> Self {
45        #[cfg(not(all(feature = "fuzz", dst)))]
46        let (tx, mut rx) = mpsc::unbounded_channel::<BoxedTask>();
47        // The selected queue yields to the simulator; Tokio's blocking receive would
48        // park the simulator's only OS thread.
49        #[cfg(all(feature = "fuzz", dst))]
50        let (tx, rx) = channel::unbounded::<BoxedTask>();
51        let handle = thread::Builder::new()
52            .name(name.to_string())
53            .spawn(move || {
54                while let Some(task) = {
55                    #[cfg(not(all(feature = "fuzz", dst)))]
56                    {
57                        rx.blocking_recv()
58                    }
59                    #[cfg(all(feature = "fuzz", dst))]
60                    {
61                        rx.recv().ok()
62                    }
63                } {
64                    let _ = std::panic::catch_unwind(AssertUnwindSafe(task));
65                }
66            })
67            .unwrap_or_else(|e| panic!("failed to spawn worker thread {name:?}: {e}"));
68
69        Self {
70            #[cfg(not(all(feature = "fuzz", dst)))]
71            tx,
72            #[cfg(all(feature = "fuzz", dst))]
73            tx: Some(tx),
74            metrics: WorkerThreadMetrics::new(name),
75            pending: Arc::new(AtomicUsize::new(0)),
76            handle: Some(handle),
77        }
78    }
79
80    /// Spawns a closure on this worker.
81    fn spawn<F, R>(&self, f: F) -> oneshot::Receiver<R>
82    where
83        F: FnOnce() -> R + Send + 'static,
84        R: Send + 'static,
85    {
86        self.pending.fetch_add(1, Ordering::AcqRel);
87
88        let (result_tx, result_rx) = oneshot::channel();
89        let pending = self.pending.clone();
90        let metrics = self.metrics.clone();
91        let queued_at = Instant::now();
92
93        let task: BoxedTask = Box::new(move || {
94            let started_at = Instant::now();
95            metrics.record_queue_wait(started_at.saturating_duration_since(queued_at));
96            let result = {
97                let _decrement_pending = DecrementPendingOnDrop(pending);
98                let _record_task_duration = RecordTaskDurationOnDrop::new(metrics, started_at);
99                f()
100            };
101            let _ = result_tx.send(result);
102        });
103
104        #[cfg(not(all(feature = "fuzz", dst)))]
105        let tx = &self.tx;
106        #[cfg(all(feature = "fuzz", dst))]
107        let tx = self.tx.as_ref().expect("live worker retains its sender");
108        if tx.send(task).is_err() {
109            self.pending.fetch_sub(1, Ordering::AcqRel);
110        }
111
112        result_rx
113    }
114
115    /// Attempts to spawn a closure if this worker has no task running or queued.
116    fn try_spawn<F, R>(&self, f: F) -> Option<oneshot::Receiver<R>>
117    where
118        F: FnOnce() -> R + Send + 'static,
119        R: Send + 'static,
120    {
121        self.pending.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).ok()?;
122
123        let (result_tx, result_rx) = oneshot::channel();
124        let pending = self.pending.clone();
125        let metrics = self.metrics.clone();
126        let queued_at = Instant::now();
127
128        let task: BoxedTask = Box::new(move || {
129            let started_at = Instant::now();
130            metrics.record_queue_wait(started_at.saturating_duration_since(queued_at));
131            let result = {
132                let _decrement_pending = DecrementPendingOnDrop(pending);
133                let _record_task_duration = RecordTaskDurationOnDrop::new(metrics, started_at);
134                f()
135            };
136            let _ = result_tx.send(result);
137        });
138
139        #[cfg(not(all(feature = "fuzz", dst)))]
140        let tx = &self.tx;
141        #[cfg(all(feature = "fuzz", dst))]
142        let tx = self.tx.as_ref().expect("live worker retains its sender");
143        if tx.send(task).is_err() {
144            self.pending.fetch_sub(1, Ordering::AcqRel);
145            return None
146        }
147
148        Some(result_rx)
149    }
150}
151
152/// Decrements a worker's pending task count when a task finishes, including after panic.
153struct DecrementPendingOnDrop(Arc<AtomicUsize>);
154
155impl Drop for DecrementPendingOnDrop {
156    fn drop(&mut self) {
157        self.0.fetch_sub(1, Ordering::AcqRel);
158    }
159}
160
161/// Records a worker task's run time when the task finishes or unwinds.
162struct RecordTaskDurationOnDrop {
163    metrics: WorkerThreadMetrics,
164    started_at: Instant,
165}
166
167impl RecordTaskDurationOnDrop {
168    const fn new(metrics: WorkerThreadMetrics, started_at: Instant) -> Self {
169        Self { metrics, started_at }
170    }
171}
172
173impl Drop for RecordTaskDurationOnDrop {
174    fn drop(&mut self) {
175        self.metrics.record_task_duration(self.started_at.elapsed());
176    }
177}
178
179/// A map of named single-thread workers.
180///
181/// Each unique name gets a dedicated OS thread that is reused for all tasks submitted under
182/// that name. Workers are created lazily on first use.
183pub(crate) struct WorkerMap {
184    #[cfg(not(all(feature = "fuzz", dst)))]
185    workers: DashMap<&'static str, WorkerThread>,
186    #[cfg(all(feature = "fuzz", dst))]
187    workers: DashMap<&'static str, Arc<WorkerThread>>,
188}
189
190impl Default for WorkerMap {
191    fn default() -> Self {
192        Self::new()
193    }
194}
195
196impl WorkerMap {
197    /// Creates a new empty `WorkerMap`.
198    pub(crate) fn new() -> Self {
199        Self { workers: DashMap::new() }
200    }
201
202    /// Returns the canonical worker without retaining map locks across scheduled operations.
203    #[cfg(all(feature = "fuzz", dst))]
204    fn worker(&self, name: &'static str) -> Arc<WorkerThread> {
205        if let Some(worker) = self.workers.get(name) {
206            return Arc::clone(worker.value());
207        }
208        // Creating or dropping a worker can yield. Neither may hold a DashMap guard.
209        let candidate = Arc::new(WorkerThread::new(name));
210        let worker =
211            Arc::clone(self.workers.entry(name).or_insert_with(|| Arc::clone(&candidate)).value());
212        drop(candidate);
213        worker
214    }
215
216    /// Spawns a closure on the dedicated worker thread for the given name.
217    ///
218    /// If no worker thread exists for this name yet, one is created with the given name as
219    /// the OS thread name. The closure executes on the worker's OS thread and the returned
220    /// receiver resolves with the result.
221    pub(crate) fn spawn_on<F, R>(&self, name: &'static str, f: F) -> oneshot::Receiver<R>
222    where
223        F: FnOnce() -> R + Send + 'static,
224        R: Send + 'static,
225    {
226        #[cfg(not(all(feature = "fuzz", dst)))]
227        let worker = self.workers.entry(name).or_insert_with(|| WorkerThread::new(name));
228        #[cfg(all(feature = "fuzz", dst))]
229        let worker = self.worker(name);
230        worker.spawn(f)
231    }
232
233    /// Attempts to spawn a closure on the dedicated worker thread for the given name.
234    ///
235    /// Returns `None` if the named worker already has a task running or queued.
236    pub(crate) fn try_spawn_on<F, R>(
237        &self,
238        name: &'static str,
239        f: F,
240    ) -> Option<oneshot::Receiver<R>>
241    where
242        F: FnOnce() -> R + Send + 'static,
243        R: Send + 'static,
244    {
245        #[cfg(not(all(feature = "fuzz", dst)))]
246        let worker = self.workers.entry(name).or_insert_with(|| WorkerThread::new(name));
247        #[cfg(all(feature = "fuzz", dst))]
248        let worker = self.worker(name);
249        worker.try_spawn(f)
250    }
251}
252
253#[cfg(not(all(feature = "fuzz", dst)))]
254impl Drop for WorkerMap {
255    fn drop(&mut self) {
256        for (_, mut w) in std::mem::take(&mut self.workers) {
257            // Drop sender so the thread's recv loop exits, then join.
258            drop(w.tx);
259            // A task can own the last reference to this map and drop it on its own worker, which
260            // cannot join itself. That thread exits on its own once the task returns.
261            if let Some(handle) = w.handle.take() &&
262                handle.thread().id() != thread::current().id()
263            {
264                let _ = handle.join();
265            }
266        }
267    }
268}
269
270#[cfg(all(feature = "fuzz", dst))]
271impl Drop for WorkerThread {
272    fn drop(&mut self) {
273        // Close the queue before joining so an idle worker can exit.
274        drop(self.tx.take());
275        // The last map owner may be dropped by this worker's own task.
276        if let Some(handle) = self.handle.take() &&
277            handle.thread().id() != thread::current().id()
278        {
279            let _ = handle.join();
280        }
281    }
282}
283
284impl std::fmt::Debug for WorkerMap {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        f.debug_struct("WorkerMap").field("num_workers", &self.workers.len()).finish()
287    }
288}
289
290// Native Tokio waits do not yield to Shuttle while a simulated worker is parked.
291#[cfg(all(test, not(all(feature = "fuzz", dst))))]
292mod tests {
293    use super::*;
294
295    #[tokio::test]
296    async fn worker_map_basic() {
297        let map = WorkerMap::new();
298
299        let result = map.spawn_on("test", || 42).await.unwrap();
300        assert_eq!(result, 42);
301    }
302
303    #[tokio::test]
304    async fn worker_map_same_thread() {
305        let map = WorkerMap::new();
306
307        let id1 = map.spawn_on("test", || thread::current().id()).await.unwrap();
308        let id2 = map.spawn_on("test", || thread::current().id()).await.unwrap();
309        assert_eq!(id1, id2, "same name should run on the same thread");
310    }
311
312    #[tokio::test]
313    async fn worker_map_different_names_different_threads() {
314        let map = WorkerMap::new();
315
316        let id1 = map.spawn_on("worker-a", || thread::current().id()).await.unwrap();
317        let id2 = map.spawn_on("worker-b", || thread::current().id()).await.unwrap();
318        assert_ne!(id1, id2, "different names should run on different threads");
319    }
320
321    #[tokio::test]
322    async fn worker_map_sequential_execution() {
323        let map = WorkerMap::new();
324        let counter = Arc::new(AtomicUsize::new(0));
325
326        let mut receivers = Vec::new();
327        for i in 0..10 {
328            let c = counter.clone();
329            let rx = map.spawn_on("sequential", move || {
330                let val = c.fetch_add(1, Ordering::SeqCst);
331                assert_eq!(val, i, "tasks should execute in order");
332                val
333            });
334            receivers.push(rx);
335        }
336
337        for (i, rx) in receivers.into_iter().enumerate() {
338            let val = rx.await.unwrap();
339            assert_eq!(val, i);
340        }
341    }
342
343    #[tokio::test]
344    async fn worker_map_thread_name() {
345        let map = WorkerMap::new();
346
347        let name = map
348            .spawn_on("custom-worker", || thread::current().name().unwrap().to_string())
349            .await
350            .unwrap();
351        assert_eq!(name, "custom-worker");
352    }
353
354    #[tokio::test]
355    async fn worker_map_try_spawn_busy() {
356        let map = WorkerMap::new();
357        let (release_tx, release_rx) = std::sync::mpsc::channel();
358
359        let first = map.try_spawn_on("busy-worker", move || {
360            release_rx.recv().unwrap();
361            1
362        });
363        assert!(first.is_some());
364
365        let second = map.try_spawn_on("busy-worker", || 2);
366        assert!(second.is_none(), "busy worker should reject queued work");
367
368        release_tx.send(()).unwrap();
369        assert_eq!(first.unwrap().await.unwrap(), 1);
370
371        let third = map.try_spawn_on("busy-worker", || 3).expect("worker should be idle");
372        assert_eq!(third.await.unwrap(), 3);
373    }
374
375    #[test]
376    fn worker_map_last_owner_dropped_on_worker() {
377        let map = Arc::new(WorkerMap::new());
378        let owner = Arc::clone(&map);
379        let (release_tx, release_rx) = std::sync::mpsc::channel();
380
381        let done = map.spawn_on("last-owner", move || {
382            release_rx.recv().unwrap();
383            // Drops the last reference to the map on the worker it would join.
384            drop(owner);
385        });
386
387        drop(map);
388        release_tx.send(()).unwrap();
389        done.blocking_recv().expect("dropping the map on its own worker should not panic");
390    }
391}