1use crate::{
10 metrics::{IncCounterOnDrop, TaskExecutorMetrics},
11 shutdown::{GracefulShutdown, GracefulShutdownGuard, Shutdown},
12 wait_for_shutdown_progress,
13 worker_map::WorkerMap,
14 PanickedTaskError, TaskEvent, TaskManager,
15};
16use futures_util::{
17 future::{select, BoxFuture},
18 Future, FutureExt, TryFutureExt,
19};
20use reth_concurrency::sync::{
21 atomic::{AtomicUsize, Ordering},
22 parking_lot, thread,
23 time::{Duration, Instant},
24 Mutex,
25};
26use std::{num::NonZeroUsize, pin::pin, sync::Arc};
27use tokio::{runtime::Handle, sync::mpsc::UnboundedSender, task::JoinHandle};
28use tracing::{debug, error, Span};
29use tracing_futures::Instrument;
30
31#[cfg(feature = "rayon")]
32use crate::pool::{build_pool_with_panic_handler, BlockingTaskGuard, BlockingTaskPool, WorkerPool};
33#[cfg(feature = "rayon")]
34use reth_concurrency::sync::{
35 rayon::{ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder},
36 thread::available_parallelism,
37};
38
39#[cfg(all(feature = "fuzz", dst))]
40use reth_concurrency::sync::runtime;
41
42use tokio::runtime::Runtime as TokioRuntime;
43
44pub const DEFAULT_THREAD_KEEP_ALIVE: Duration = Duration::from_secs(15);
46
47pub const DEFAULT_RESERVED_CPU_CORES: usize = 2;
49
50pub const DEFAULT_STORAGE_POOL_THREADS: usize = 16;
52
53#[cfg(feature = "rayon")]
55pub const DEFAULT_STATE_TRIE_OVERLAY_WORKER_THREADS: usize = 4;
56
57pub const DEFAULT_MAX_BLOCKING_TASKS: usize = 512;
59
60#[derive(Debug, Clone)]
62pub enum TokioConfig {
63 Owned {
65 worker_threads: Option<usize>,
67 thread_keep_alive: Duration,
69 thread_name: &'static str,
71 },
72 ExistingHandle(Handle),
74}
75
76impl Default for TokioConfig {
77 fn default() -> Self {
78 Self::Owned {
79 worker_threads: None,
80 thread_keep_alive: DEFAULT_THREAD_KEEP_ALIVE,
81 thread_name: "tokio-rt",
82 }
83 }
84}
85
86impl TokioConfig {
87 pub const fn existing_handle(handle: Handle) -> Self {
89 Self::ExistingHandle(handle)
90 }
91
92 pub const fn with_worker_threads(worker_threads: usize) -> Self {
94 Self::Owned {
95 worker_threads: Some(worker_threads),
96 thread_keep_alive: DEFAULT_THREAD_KEEP_ALIVE,
97 thread_name: "tokio-rt",
98 }
99 }
100}
101
102#[derive(Debug, Clone)]
104#[cfg(feature = "rayon")]
105pub struct RayonConfig {
106 pub cpu_threads: Option<usize>,
109 pub reserved_cpu_cores: usize,
111 pub rpc_threads: Option<usize>,
114 pub storage_threads: Option<usize>,
117 pub max_blocking_tasks: usize,
119 pub proof_storage_worker_threads: Option<usize>,
122 pub proof_account_worker_threads: Option<usize>,
125 pub prewarming_threads: Option<usize>,
128 pub bal_streaming_threads: Option<usize>,
131 pub state_trie_overlay_worker_threads: Option<usize>,
134}
135
136#[cfg(feature = "rayon")]
137impl Default for RayonConfig {
138 fn default() -> Self {
139 Self {
140 cpu_threads: None,
141 reserved_cpu_cores: DEFAULT_RESERVED_CPU_CORES,
142 rpc_threads: None,
143 storage_threads: None,
144 max_blocking_tasks: DEFAULT_MAX_BLOCKING_TASKS,
145 proof_storage_worker_threads: None,
146 proof_account_worker_threads: None,
147 prewarming_threads: None,
148 bal_streaming_threads: None,
149 state_trie_overlay_worker_threads: None,
150 }
151 }
152}
153
154#[cfg(feature = "rayon")]
155impl RayonConfig {
156 pub const fn with_reserved_cpu_cores(mut self, reserved_cpu_cores: usize) -> Self {
158 self.reserved_cpu_cores = reserved_cpu_cores;
159 self
160 }
161
162 pub const fn with_max_blocking_tasks(mut self, max_blocking_tasks: usize) -> Self {
164 self.max_blocking_tasks = max_blocking_tasks;
165 self
166 }
167
168 pub const fn with_rpc_threads(mut self, rpc_threads: usize) -> Self {
170 self.rpc_threads = Some(rpc_threads);
171 self
172 }
173
174 pub const fn with_storage_threads(mut self, storage_threads: usize) -> Self {
176 self.storage_threads = Some(storage_threads);
177 self
178 }
179
180 pub const fn with_proof_storage_worker_threads(
182 mut self,
183 proof_storage_worker_threads: usize,
184 ) -> Self {
185 self.proof_storage_worker_threads = Some(proof_storage_worker_threads);
186 self
187 }
188
189 pub const fn with_proof_account_worker_threads(
191 mut self,
192 proof_account_worker_threads: usize,
193 ) -> Self {
194 self.proof_account_worker_threads = Some(proof_account_worker_threads);
195 self
196 }
197
198 pub const fn with_prewarming_threads(mut self, prewarming_threads: usize) -> Self {
200 self.prewarming_threads = Some(prewarming_threads);
201 self
202 }
203
204 pub const fn with_bal_streaming_threads(mut self, bal_streaming_threads: usize) -> Self {
206 self.bal_streaming_threads = Some(bal_streaming_threads);
207 self
208 }
209
210 pub const fn with_state_trie_overlay_worker_threads(
212 mut self,
213 state_trie_overlay_worker_threads: usize,
214 ) -> Self {
215 self.state_trie_overlay_worker_threads = Some(state_trie_overlay_worker_threads);
216 self
217 }
218
219 fn default_thread_count(&self) -> usize {
221 let _ = self.reserved_cpu_cores;
224 self.cpu_threads.unwrap_or_else(|| available_parallelism().map_or(1, NonZeroUsize::get))
225 }
226
227 fn proof_storage_worker_threads_override(&self) -> Option<usize> {
230 self.proof_storage_worker_threads.filter(|&threads| threads > 0)
231 }
232
233 fn proof_account_worker_threads_override(&self) -> Option<usize> {
236 self.proof_account_worker_threads.filter(|&threads| threads > 0)
237 }
238}
239
240#[derive(Debug, Clone, Default)]
242pub struct RuntimeConfig {
243 pub tokio: TokioConfig,
245 #[cfg(feature = "rayon")]
247 pub rayon: RayonConfig,
248}
249
250impl RuntimeConfig {
251 pub fn with_tokio(mut self, tokio: TokioConfig) -> Self {
253 self.tokio = tokio;
254 self
255 }
256
257 #[cfg(feature = "rayon")]
259 pub const fn with_rayon(mut self, rayon: RayonConfig) -> Self {
260 self.rayon = rayon;
261 self
262 }
263
264 pub fn with_cpu_cores(mut self, cpu_cores: NonZeroUsize) -> Self {
269 let cpu_cores = cpu_cores.get();
270 if let TokioConfig::Owned { worker_threads, .. } = &mut self.tokio {
271 worker_threads.get_or_insert(cpu_cores);
272 }
273 #[cfg(feature = "rayon")]
274 self.rayon.cpu_threads.get_or_insert(cpu_cores);
275 self
276 }
277}
278
279#[derive(Debug, thiserror::Error)]
281pub enum RuntimeBuildError {
282 #[error("Failed to build tokio runtime: {0}")]
284 TokioBuild(#[from] std::io::Error),
285 #[cfg(feature = "rayon")]
287 #[error("Failed to build rayon thread pool: {0}")]
288 RayonBuild(#[from] ThreadPoolBuildError),
289}
290
291struct RuntimeInner {
294 tokio_runtime: Mutex<Option<TokioRuntime>>,
296 handle: Handle,
298 on_shutdown: Shutdown,
300 task_events_tx: UnboundedSender<TaskEvent>,
302 metrics: TaskExecutorMetrics,
304 graceful_tasks: Arc<AtomicUsize>,
306 #[cfg(feature = "rayon")]
308 cpu_pool: ThreadPool,
309 #[cfg(feature = "rayon")]
311 rpc_pool: BlockingTaskPool,
312 #[cfg(feature = "rayon")]
314 storage_pool: ThreadPool,
315 #[cfg(feature = "rayon")]
317 blocking_guard: BlockingTaskGuard,
318 #[cfg(feature = "rayon")]
320 proof_storage_worker_pool: WorkerPool,
321 #[cfg(feature = "rayon")]
323 proof_account_worker_pool: WorkerPool,
324 #[cfg(feature = "rayon")]
326 proof_storage_worker_threads_override: Option<usize>,
327 #[cfg(feature = "rayon")]
329 proof_account_worker_threads_override: Option<usize>,
330 #[cfg(feature = "rayon")]
332 prewarming_pool: Arc<WorkerPool>,
333 #[cfg(feature = "rayon")]
335 bal_streaming_pool: Arc<WorkerPool>,
336 #[cfg(feature = "rayon")]
338 state_trie_overlay_worker_pool: Arc<WorkerPool>,
339 worker_map: WorkerMap,
342 task_manager_handle: Mutex<Option<JoinHandle<Result<(), PanickedTaskError>>>>,
346}
347
348impl Drop for RuntimeInner {
349 fn drop(&mut self) {
350 if Handle::try_current().is_ok() &&
353 let Some(runtime) = self.tokio_runtime.get_mut().unwrap().take()
354 {
355 runtime.shutdown_background();
356 }
357 }
358}
359
360#[derive(Clone)]
369pub struct Runtime(Arc<RuntimeInner>);
370
371impl std::fmt::Debug for Runtime {
372 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373 f.debug_struct("Runtime").field("handle", &self.0.handle).finish()
374 }
375}
376
377impl Runtime {
380 pub fn take_task_manager_handle(&self) -> Option<JoinHandle<Result<(), PanickedTaskError>>> {
386 self.0.task_manager_handle.lock().unwrap().take()
387 }
388
389 pub fn handle(&self) -> &Handle {
391 &self.0.handle
392 }
393
394 #[cfg(feature = "rayon")]
396 pub fn cpu_pool(&self) -> &ThreadPool {
397 &self.0.cpu_pool
398 }
399
400 #[cfg(feature = "rayon")]
402 pub fn rpc_pool(&self) -> &BlockingTaskPool {
403 &self.0.rpc_pool
404 }
405
406 #[cfg(feature = "rayon")]
408 pub fn storage_pool(&self) -> &ThreadPool {
409 &self.0.storage_pool
410 }
411
412 #[cfg(feature = "rayon")]
414 pub fn blocking_guard(&self) -> BlockingTaskGuard {
415 self.0.blocking_guard.clone()
416 }
417
418 #[cfg(feature = "rayon")]
420 pub fn proof_storage_worker_pool(&self) -> &WorkerPool {
421 &self.0.proof_storage_worker_pool
422 }
423
424 #[cfg(feature = "rayon")]
426 pub fn proof_account_worker_pool(&self) -> &WorkerPool {
427 &self.0.proof_account_worker_pool
428 }
429
430 #[cfg(feature = "rayon")]
435 pub fn proof_storage_worker_threads_override(&self) -> Option<usize> {
436 self.0.proof_storage_worker_threads_override
437 }
438
439 #[cfg(feature = "rayon")]
444 pub fn proof_account_worker_threads_override(&self) -> Option<usize> {
445 self.0.proof_account_worker_threads_override
446 }
447
448 #[cfg(feature = "rayon")]
450 pub fn prewarming_pool(&self) -> &Arc<WorkerPool> {
451 &self.0.prewarming_pool
452 }
453
454 #[cfg(feature = "rayon")]
456 pub fn bal_streaming_pool(&self) -> &Arc<WorkerPool> {
457 &self.0.bal_streaming_pool
458 }
459
460 #[cfg(feature = "rayon")]
462 pub fn state_trie_overlay_worker_pool(&self) -> Arc<WorkerPool> {
463 Arc::clone(&self.0.state_trie_overlay_worker_pool)
464 }
465}
466
467impl Runtime {
470 pub fn test() -> Self {
475 let config = match Handle::try_current() {
476 Ok(handle) => Self::test_config().with_tokio(TokioConfig::existing_handle(handle)),
477 Err(_) => Self::test_config(),
478 };
479 RuntimeBuilder::new(config).build().expect("failed to build test Runtime")
480 }
481
482 const fn test_config() -> RuntimeConfig {
483 RuntimeConfig {
484 tokio: TokioConfig::Owned {
485 worker_threads: Some(2),
486 thread_keep_alive: DEFAULT_THREAD_KEEP_ALIVE,
487 thread_name: "tokio-test",
488 },
489 #[cfg(feature = "rayon")]
490 rayon: RayonConfig {
491 cpu_threads: Some(2),
492 reserved_cpu_cores: 0,
493 rpc_threads: Some(2),
494 storage_threads: Some(2),
495 max_blocking_tasks: 16,
496 proof_storage_worker_threads: Some(2),
497 proof_account_worker_threads: Some(2),
498 prewarming_threads: Some(2),
499 bal_streaming_threads: Some(2),
500 state_trie_overlay_worker_threads: Some(2),
501 },
502 }
503 }
504}
505
506enum TaskKind {
510 Default,
512 Blocking,
514}
515
516impl Runtime {
517 pub fn on_shutdown_signal(&self) -> &Shutdown {
519 &self.0.on_shutdown
520 }
521
522 fn spawn_on_rt<F>(&self, fut: F, task_kind: TaskKind) -> JoinHandle<()>
524 where
525 F: Future<Output = ()> + Send + 'static,
526 {
527 match task_kind {
528 TaskKind::Default => spawn_async(&self.0.handle, fut),
529 TaskKind::Blocking => {
530 let handle = self.0.handle.clone();
531 self.0.handle.spawn_blocking(move || handle.block_on(fut))
532 }
533 }
534 }
535
536 fn spawn_task_as(&self, fut: BoxFuture<'static, ()>, task_kind: TaskKind) -> JoinHandle<()> {
538 self.spawn_on_rt(self.regular_task(fut, &task_kind), task_kind)
539 }
540
541 fn regular_task(
542 &self,
543 fut: BoxFuture<'static, ()>,
544 task_kind: &TaskKind,
545 ) -> impl Future<Output = ()> + use<> {
546 match task_kind {
547 TaskKind::Default => self.0.metrics.inc_regular_tasks(),
548 TaskKind::Blocking => self.0.metrics.inc_regular_blocking_tasks(),
549 }
550 let on_shutdown = self.0.on_shutdown.clone();
551
552 let finished_counter = match task_kind {
553 TaskKind::Default => self.0.metrics.finished_regular_tasks_total.clone(),
554 TaskKind::Blocking => self.0.metrics.finished_regular_blocking_tasks_total.clone(),
555 };
556
557 async move {
558 let _inc_counter_on_drop = IncCounterOnDrop::new(finished_counter);
559 let _ = select(on_shutdown, fut).await;
560 }
561 .in_current_span()
562 }
563
564 pub fn spawn_task<F>(&self, fut: F) -> JoinHandle<()>
569 where
570 F: Future<Output = ()> + Send + 'static,
571 {
572 self.spawn_task_as(fut.boxed(), TaskKind::Default)
573 }
574
575 pub fn spawn_blocking_task<F>(&self, fut: F) -> JoinHandle<()>
580 where
581 F: Future<Output = ()> + Send + 'static,
582 {
583 self.spawn_task_as(fut.boxed(), TaskKind::Blocking)
584 }
585
586 pub fn spawn_blocking_task_detached(&self, fut: impl Future<Output = ()> + Send + 'static) {
589 #[cfg(all(feature = "fuzz", dst))]
590 if runtime::Runtime::local_services(self.handle()).is_some() {
591 let task = self.regular_task(fut.boxed(), &TaskKind::Blocking);
594 drop(shuttle::future::spawn(std::panic::AssertUnwindSafe(task).catch_unwind()));
595 return;
596 }
597 self.spawn_blocking_task(fut);
598 }
599
600 pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
603 where
604 F: FnOnce() -> R + Send + 'static,
605 R: Send + 'static,
606 {
607 self.0.handle.spawn_blocking(Box::new(func) as Box<dyn FnOnce() -> R + Send>)
610 }
611
612 pub fn spawn_blocking_task_fn<F>(&self, func: F) -> JoinHandle<()>
621 where
622 F: FnOnce() + Send + 'static,
623 {
624 self.spawn_blocking(self.instrument_blocking_task(func))
625 }
626
627 pub fn spawn_blocking_task_fn_detached(&self, func: impl FnOnce() + Send + 'static) {
631 #[cfg(not(all(feature = "fuzz", dst)))]
632 self.spawn_blocking_task_fn(func);
633 #[cfg(all(feature = "fuzz", dst))]
634 thread::spawn(self.instrument_blocking_task(func));
635 }
636
637 fn instrument_blocking_task<F: FnOnce()>(&self, func: F) -> impl FnOnce() + use<F> {
638 self.0.metrics.inc_regular_blocking_tasks();
639 let finished_counter = self.0.metrics.finished_regular_blocking_tasks_total.clone();
640 let span = Span::current();
641 move || {
642 let _inc_counter_on_drop = IncCounterOnDrop::new(finished_counter);
643 let _enter = span.enter();
644 func()
645 }
646 }
647
648 pub fn spawn_drop<T: Send + 'static>(&self, value: T) {
654 self.spawn_blocking_named("drop", move || drop(value));
655 }
656
657 pub fn spawn_blocking_named<F, R>(&self, name: &'static str, func: F) -> crate::LazyHandle<R>
670 where
671 F: FnOnce() -> R + Send + 'static,
672 R: Send + 'static,
673 {
674 crate::LazyHandle::new(self.0.worker_map.spawn_on(name, func))
675 }
676
677 pub fn try_spawn_blocking_named<F, R>(
682 &self,
683 name: &'static str,
684 func: F,
685 ) -> Option<crate::LazyHandle<R>>
686 where
687 F: FnOnce() -> R + Send + 'static,
688 R: Send + 'static,
689 {
690 self.0.worker_map.try_spawn_on(name, func).map(crate::LazyHandle::new)
691 }
692
693 pub fn spawn_blocking_named_or_tokio<F>(&self, name: &'static str, func: F) -> bool
698 where
699 F: FnOnce() + Send + 'static,
700 {
701 let func = Arc::new(parking_lot::Mutex::new(Some(func)));
702 let named_func = func.clone();
703
704 if self
705 .try_spawn_blocking_named(name, move || {
706 #[cfg(not(all(feature = "fuzz", dst)))]
707 if let Some(func) = named_func.lock().take() {
708 func();
709 }
710 #[cfg(all(feature = "fuzz", dst))]
711 {
712 if shuttle::current::try_get_current_task().is_some() {
713 reth_concurrency::sync::thread::yield_now();
714 }
715 let func = named_func.lock().take();
716 if let Some(func) = func {
717 func();
718 }
719 }
720 })
721 .is_some()
722 {
723 return true
724 }
725
726 #[cfg(not(all(feature = "fuzz", dst)))]
727 if let Some(func) = func.lock().take() {
728 self.spawn_blocking(func);
729 }
730 #[cfg(all(feature = "fuzz", dst))]
731 {
732 if shuttle::current::try_get_current_task().is_some() {
733 reth_concurrency::sync::thread::yield_now();
734 }
735 let func = func.lock().take();
736 if let Some(func) = func {
737 self.spawn_blocking(func);
738 }
739 }
740 false
741 }
742
743 pub fn spawn_with_signal<F>(&self, f: impl FnOnce(Shutdown) -> F) -> JoinHandle<()>
748 where
749 F: Future<Output = ()> + Send + 'static,
750 {
751 let on_shutdown = self.0.on_shutdown.clone();
752 let fut = f(on_shutdown);
753 spawn_async(&self.0.handle, fut.boxed().in_current_span())
754 }
755
756 fn spawn_critical_as(
758 &self,
759 name: &'static str,
760 fut: BoxFuture<'static, ()>,
761 task_kind: TaskKind,
762 ) -> JoinHandle<()> {
763 self.0.metrics.inc_critical_tasks();
764 let panicked_tasks_tx = self.0.task_events_tx.clone();
765 let on_shutdown = self.0.on_shutdown.clone();
766
767 let task = std::panic::AssertUnwindSafe(fut)
769 .catch_unwind()
770 .map_err(move |error| {
771 let task_error = PanickedTaskError::new(name, error);
772 error!("{task_error}");
773 let _ = panicked_tasks_tx.send(TaskEvent::Panic(task_error));
774 })
775 .in_current_span();
776
777 let finished_critical_tasks_total_metrics =
778 self.0.metrics.finished_critical_tasks_total.clone();
779 let task = async move {
780 let _inc_counter_on_drop = IncCounterOnDrop::new(finished_critical_tasks_total_metrics);
781 let task = pin!(task);
782 let _ = select(on_shutdown, task).await;
783 };
784
785 self.spawn_on_rt(task, task_kind)
786 }
787
788 pub fn spawn_critical_task<F>(&self, name: &'static str, fut: F) -> JoinHandle<()>
793 where
794 F: Future<Output = ()> + Send + 'static,
795 {
796 self.spawn_critical_as(name, fut.boxed(), TaskKind::Default)
797 }
798
799 pub fn spawn_critical_blocking_task<F>(&self, name: &'static str, fut: F) -> JoinHandle<()>
804 where
805 F: Future<Output = ()> + Send + 'static,
806 {
807 self.spawn_critical_as(name, fut.boxed(), TaskKind::Blocking)
808 }
809
810 pub fn spawn_critical_os_thread<F>(
816 &self,
817 thread_name: &'static str,
818 task_name: &'static str,
819 fut: F,
820 ) -> thread::JoinHandle<()>
821 where
822 F: Future<Output = ()> + Send + 'static,
823 {
824 self.spawn_critical_os_thread_boxed(thread_name, task_name, fut.boxed())
825 }
826
827 fn spawn_critical_os_thread_boxed(
828 &self,
829 thread_name: &'static str,
830 task_name: &'static str,
831 fut: BoxFuture<'static, ()>,
832 ) -> thread::JoinHandle<()> {
833 self.0.metrics.inc_critical_tasks();
834 let handle = self.0.handle.clone();
835 let panicked_tasks_tx = self.0.task_events_tx.clone();
836 let on_shutdown = self.0.on_shutdown.clone();
837
838 let task = std::panic::AssertUnwindSafe(fut)
839 .catch_unwind()
840 .map_err(move |error| {
841 let task_error = PanickedTaskError::new(task_name, error);
842 error!("{task_error}");
843 let _ = panicked_tasks_tx.send(TaskEvent::Panic(task_error));
844 })
845 .in_current_span();
846
847 let finished_critical_tasks_total_metrics =
848 self.0.metrics.finished_critical_tasks_total.clone();
849 let task = async move {
850 let _inc_counter_on_drop = IncCounterOnDrop::new(finished_critical_tasks_total_metrics);
851 let task = pin!(task);
852 let _ = select(on_shutdown, task).await;
853 };
854
855 thread::Builder::new()
856 .name(thread_name.to_string())
857 .spawn(move || {
858 let _guard = handle.enter();
859 handle.block_on(task);
860 })
861 .unwrap_or_else(|e| panic!("failed to spawn critical OS thread {thread_name:?}: {e}"))
862 }
863
864 pub fn spawn_critical_with_graceful_shutdown_signal<F>(
885 &self,
886 name: &'static str,
887 f: impl FnOnce(GracefulShutdown) -> F,
888 ) -> JoinHandle<()>
889 where
890 F: Future<Output = ()> + Send + 'static,
891 {
892 let on_shutdown = GracefulShutdown::new(
893 self.0.on_shutdown.clone(),
894 GracefulShutdownGuard::new(Arc::clone(&self.0.graceful_tasks)),
895 );
896 self.spawn_critical_graceful_boxed(name, f(on_shutdown).boxed())
897 }
898
899 fn spawn_critical_graceful_boxed(
900 &self,
901 name: &'static str,
902 fut: BoxFuture<'static, ()>,
903 ) -> JoinHandle<()> {
904 let panicked_tasks_tx = self.0.task_events_tx.clone();
905
906 let task = std::panic::AssertUnwindSafe(fut)
908 .catch_unwind()
909 .map_err(move |error| {
910 let task_error = PanickedTaskError::new(name, error);
911 error!("{task_error}");
912 let _ = panicked_tasks_tx.send(TaskEvent::Panic(task_error));
913 })
914 .map(drop)
915 .in_current_span();
916
917 spawn_async(&self.0.handle, task)
918 }
919
920 pub fn spawn_with_graceful_shutdown_signal<F>(
940 &self,
941 f: impl FnOnce(GracefulShutdown) -> F,
942 ) -> JoinHandle<()>
943 where
944 F: Future<Output = ()> + Send + 'static,
945 {
946 let on_shutdown = GracefulShutdown::new(
947 self.0.on_shutdown.clone(),
948 GracefulShutdownGuard::new(Arc::clone(&self.0.graceful_tasks)),
949 );
950 spawn_async(&self.0.handle, f(on_shutdown).boxed())
951 }
952
953 pub fn initiate_graceful_shutdown(
957 &self,
958 ) -> Result<GracefulShutdown, tokio::sync::mpsc::error::SendError<()>> {
959 self.0
960 .task_events_tx
961 .send(TaskEvent::GracefulShutdown)
962 .map_err(|_send_error_with_task_event| tokio::sync::mpsc::error::SendError(()))?;
963
964 Ok(GracefulShutdown::new(
965 self.0.on_shutdown.clone(),
966 GracefulShutdownGuard::new(Arc::clone(&self.0.graceful_tasks)),
967 ))
968 }
969
970 pub fn graceful_shutdown(&self) {
972 let _ = self.do_graceful_shutdown(None);
973 }
974
975 pub fn graceful_shutdown_with_timeout(&self, timeout: Duration) -> bool {
980 self.do_graceful_shutdown(Some(timeout))
981 }
982
983 pub fn shutdown_timeout(self, timeout: Duration) {
988 let runtime = self.0.tokio_runtime.lock().unwrap().take();
989 if let Some(runtime) = runtime {
990 runtime.shutdown_timeout(timeout);
991 }
992 }
993
994 fn do_graceful_shutdown(&self, timeout: Option<Duration>) -> bool {
995 let _ = self.0.task_events_tx.send(TaskEvent::GracefulShutdown);
996 let deadline = timeout.map(|t| Instant::now() + t);
997 while self.0.graceful_tasks.load(Ordering::SeqCst) > 0 {
998 if deadline.is_some_and(|d| Instant::now() > d) {
999 debug!("graceful shutdown timed out");
1000 return false;
1001 }
1002 wait_for_shutdown_progress();
1003 }
1004 debug!("gracefully shut down");
1005 true
1006 }
1007}
1008
1009#[derive(Debug, Clone)]
1013pub struct RuntimeBuilder {
1014 config: RuntimeConfig,
1015}
1016
1017impl RuntimeBuilder {
1018 pub const fn new(config: RuntimeConfig) -> Self {
1020 Self { config }
1021 }
1022
1023 #[tracing::instrument(name = "RuntimeBuilder::build", level = "debug", skip_all)]
1029 pub fn build(self) -> Result<Runtime, RuntimeBuildError> {
1030 debug!(?self.config, "Building runtime");
1031 let config = self.config;
1032
1033 let (owned_runtime, handle) = match &config.tokio {
1034 TokioConfig::Owned { worker_threads, thread_keep_alive, thread_name } => {
1035 let mut builder = tokio::runtime::Builder::new_multi_thread();
1036 builder
1037 .enable_all()
1038 .thread_keep_alive(*thread_keep_alive)
1039 .thread_name(*thread_name);
1040
1041 if let Some(threads) = worker_threads {
1042 builder.worker_threads(*threads);
1043 }
1044
1045 let runtime = builder.build()?;
1046 let h = runtime.handle().clone();
1047 (Some(runtime), h)
1048 }
1049 TokioConfig::ExistingHandle(h) => (None, h.clone()),
1050 };
1051
1052 let (task_manager, on_shutdown, task_events_tx, graceful_tasks) =
1053 TaskManager::new_parts(handle.clone());
1054
1055 #[cfg(feature = "rayon")]
1056 let (
1057 cpu_pool,
1058 rpc_pool,
1059 storage_pool,
1060 blocking_guard,
1061 proof_storage_worker_pool,
1062 proof_account_worker_pool,
1063 prewarming_pool,
1064 bal_streaming_pool,
1065 state_trie_overlay_worker_pool,
1066 ) = {
1067 let default_threads = config.rayon.default_thread_count();
1068 let rpc_threads = config.rayon.rpc_threads.unwrap_or(default_threads);
1069
1070 let cpu_pool = build_pool_with_panic_handler(
1071 ThreadPoolBuilder::new()
1072 .num_threads(default_threads)
1073 .thread_name(|i| format!("cpu-{i:02}")),
1074 )?;
1075
1076 let rpc_raw = build_pool_with_panic_handler(
1077 ThreadPoolBuilder::new()
1078 .num_threads(rpc_threads)
1079 .thread_name(|i| format!("rpc-{i:02}")),
1080 )?;
1081 let rpc_pool = BlockingTaskPool::new(rpc_raw);
1082
1083 let storage_threads =
1084 config.rayon.storage_threads.unwrap_or(DEFAULT_STORAGE_POOL_THREADS);
1085 let storage_pool = build_pool_with_panic_handler(
1086 ThreadPoolBuilder::new()
1087 .num_threads(storage_threads)
1088 .thread_name(|i| format!("storage-{i:02}")),
1089 )?;
1090
1091 let blocking_guard = BlockingTaskGuard::new(config.rayon.max_blocking_tasks);
1092
1093 let default_proof_worker_threads = cpu_pool.current_num_threads() * 4;
1097
1098 let proof_storage_worker_threads = config
1099 .rayon
1100 .proof_storage_worker_threads_override()
1101 .unwrap_or(default_proof_worker_threads);
1102 let proof_storage_worker_pool =
1103 WorkerPool::new(proof_storage_worker_threads, "proof-strg");
1104
1105 let proof_account_worker_threads = config
1106 .rayon
1107 .proof_account_worker_threads_override()
1108 .unwrap_or(default_proof_worker_threads);
1109 let proof_account_worker_pool =
1110 WorkerPool::new(proof_account_worker_threads, "proof-acct");
1111
1112 let prewarming_threads = config.rayon.prewarming_threads.unwrap_or(default_threads);
1113 let prewarming_pool = Arc::new(WorkerPool::new(prewarming_threads, "prewarm"));
1114
1115 let bal_streaming_threads =
1116 config.rayon.bal_streaming_threads.unwrap_or(default_threads);
1117 let bal_streaming_pool = Arc::new(WorkerPool::new(bal_streaming_threads, "bal-stream"));
1118
1119 let state_trie_overlay_worker_threads = config
1120 .rayon
1121 .state_trie_overlay_worker_threads
1122 .unwrap_or(DEFAULT_STATE_TRIE_OVERLAY_WORKER_THREADS);
1123 let state_trie_overlay_worker_pool =
1124 Arc::new(WorkerPool::new(state_trie_overlay_worker_threads, "state-ovly"));
1125
1126 debug!(
1127 default_threads,
1128 rpc_threads,
1129 storage_threads,
1130 proof_storage_worker_threads,
1131 proof_account_worker_threads,
1132 prewarming_threads,
1133 bal_streaming_threads,
1134 state_trie_overlay_worker_threads,
1135 max_blocking_tasks = config.rayon.max_blocking_tasks,
1136 "Configured lazy rayon worker pools"
1137 );
1138
1139 (
1140 cpu_pool,
1141 rpc_pool,
1142 storage_pool,
1143 blocking_guard,
1144 proof_storage_worker_pool,
1145 proof_account_worker_pool,
1146 prewarming_pool,
1147 bal_streaming_pool,
1148 state_trie_overlay_worker_pool,
1149 )
1150 };
1151
1152 let task_manager_handle = spawn_async(&handle, async move {
1153 let result = task_manager.await;
1154 if let Err(ref err) = result {
1155 debug!("{err}");
1156 }
1157 result
1158 });
1159
1160 let tokio_runtime = Mutex::new(owned_runtime);
1161 let task_manager_handle = Mutex::new(Some(task_manager_handle));
1162 let inner = RuntimeInner {
1163 tokio_runtime,
1164 handle,
1165 on_shutdown,
1166 task_events_tx,
1167 metrics: Default::default(),
1168 graceful_tasks,
1169 #[cfg(feature = "rayon")]
1170 cpu_pool,
1171 #[cfg(feature = "rayon")]
1172 rpc_pool,
1173 #[cfg(feature = "rayon")]
1174 storage_pool,
1175 #[cfg(feature = "rayon")]
1176 blocking_guard,
1177 #[cfg(feature = "rayon")]
1178 proof_storage_worker_pool,
1179 #[cfg(feature = "rayon")]
1180 proof_account_worker_pool,
1181 #[cfg(feature = "rayon")]
1182 proof_storage_worker_threads_override: config
1183 .rayon
1184 .proof_storage_worker_threads_override(),
1185 #[cfg(feature = "rayon")]
1186 proof_account_worker_threads_override: config
1187 .rayon
1188 .proof_account_worker_threads_override(),
1189 #[cfg(feature = "rayon")]
1190 prewarming_pool,
1191 #[cfg(feature = "rayon")]
1192 bal_streaming_pool,
1193 #[cfg(feature = "rayon")]
1194 state_trie_overlay_worker_pool,
1195 worker_map: WorkerMap::new(),
1196 task_manager_handle,
1197 };
1198
1199 Ok(Runtime(Arc::new(inner)))
1200 }
1201}
1202
1203fn spawn_async<F>(handle: &Handle, future: F) -> JoinHandle<F::Output>
1204where
1205 F: Future + Send + 'static,
1206 F::Output: Send + 'static,
1207{
1208 #[cfg(all(feature = "fuzz", dst))]
1209 if let Some(services) = runtime::Runtime::local_services(handle) {
1210 return services.spawn_local(future);
1211 }
1212 handle.spawn(future)
1213}
1214
1215#[cfg(test)]
1216mod tests {
1217 use super::*;
1218 use reth_concurrency::sync::mpsc;
1219 use tokio::sync::oneshot;
1220
1221 #[cfg(not(all(feature = "fuzz", dst)))]
1222 use crate::test_utils;
1223 #[cfg(not(all(feature = "fuzz", dst)))]
1224 use std::future;
1225
1226 #[test]
1227 fn test_runtime_config_default() {
1228 let config = RuntimeConfig::default();
1229 assert!(matches!(config.tokio, TokioConfig::Owned { .. }));
1230 }
1231
1232 #[test]
1233 fn cpu_cores_override_sizes_tokio_workers() {
1234 let config = RuntimeConfig::default().with_cpu_cores(NonZeroUsize::new(8).unwrap());
1235 assert!(matches!(config.tokio, TokioConfig::Owned { worker_threads: Some(8), .. }));
1236 }
1237
1238 #[test]
1239 fn cpu_cores_override_preserves_explicit_tokio_workers() {
1240 let config = RuntimeConfig::default()
1241 .with_tokio(TokioConfig::with_worker_threads(2))
1242 .with_cpu_cores(NonZeroUsize::new(8).unwrap());
1243 assert!(matches!(config.tokio, TokioConfig::Owned { worker_threads: Some(2), .. }));
1244 }
1245
1246 #[test]
1247 fn cpu_cores_override_preserves_existing_tokio_runtime() {
1248 let runtime = TokioRuntime::new().unwrap();
1249 let config = RuntimeConfig::default()
1250 .with_tokio(TokioConfig::existing_handle(runtime.handle().clone()))
1251 .with_cpu_cores(NonZeroUsize::new(8).unwrap());
1252 assert!(matches!(config.tokio, TokioConfig::ExistingHandle(_)));
1253 }
1254
1255 #[cfg(feature = "rayon")]
1256 #[reth_concurrency::test]
1257 fn cpu_cores_override_sizes_cpu_pools() {
1258 let runtime = RuntimeBuilder::new(
1259 RuntimeConfig::default().with_cpu_cores(NonZeroUsize::new(5).unwrap()),
1260 )
1261 .build()
1262 .unwrap();
1263 assert_eq!(runtime.handle().metrics().num_workers(), 5);
1264 assert_eq!(runtime.cpu_pool().current_num_threads(), 5);
1265 assert_eq!(
1266 crate::test_utils::block_on(
1267 runtime.rpc_pool().spawn(reth_concurrency::sync::rayon::current_num_threads)
1268 )
1269 .unwrap(),
1270 5
1271 );
1272 assert_eq!(runtime.prewarming_pool().current_num_threads(), 5);
1273 assert_eq!(runtime.bal_streaming_pool().current_num_threads(), 5);
1274 assert_eq!(runtime.proof_storage_worker_pool().num_threads(), 20);
1275 assert_eq!(runtime.proof_account_worker_pool().num_threads(), 20);
1276 assert_eq!(runtime.storage_pool().current_num_threads(), DEFAULT_STORAGE_POOL_THREADS);
1277 assert_eq!(
1278 runtime.state_trie_overlay_worker_pool().num_threads(),
1279 DEFAULT_STATE_TRIE_OVERLAY_WORKER_THREADS
1280 );
1281 }
1282
1283 #[cfg(feature = "rayon")]
1284 #[test]
1285 fn cpu_cores_override_preserves_explicit_cpu_threads() {
1286 let config = RuntimeConfig::default()
1287 .with_rayon(RayonConfig { cpu_threads: Some(2), ..Default::default() })
1288 .with_cpu_cores(NonZeroUsize::new(8).unwrap());
1289 assert_eq!(config.rayon.default_thread_count(), 2);
1290 }
1291
1292 #[test]
1293 fn test_runtime_config_existing_handle() {
1294 let rt = TokioRuntime::new().unwrap();
1295 let config =
1296 Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1297 assert!(matches!(config.tokio, TokioConfig::ExistingHandle(_)));
1298 }
1299
1300 #[cfg(feature = "rayon")]
1301 #[test]
1302 fn test_rayon_config_thread_count() {
1303 let config = RayonConfig::default();
1304 let count = config.default_thread_count();
1305 assert!(count >= 1);
1306 }
1307
1308 #[cfg(feature = "rayon")]
1309 #[reth_concurrency::test]
1310 fn zero_cpu_threads_still_size_the_proof_pools() {
1311 let rt = TokioRuntime::new().unwrap();
1312 let mut config =
1313 Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1314 config.rayon.cpu_threads = Some(0);
1315 config.rayon.proof_storage_worker_threads = None;
1316 config.rayon.proof_account_worker_threads = None;
1317 let runtime = RuntimeBuilder::new(config).build().unwrap();
1318
1319 let resolved = runtime.cpu_pool().current_num_threads();
1320 assert!(resolved >= 1);
1321 assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), resolved * 4);
1322 assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), resolved * 4);
1323 }
1324
1325 #[cfg(feature = "rayon")]
1326 #[reth_concurrency::test]
1327 fn proof_worker_threads_keep_pinned_counts() {
1328 let rt = TokioRuntime::new().unwrap();
1329 for configured in [1, 8, 16, 17, 64] {
1330 let mut config = Runtime::test_config()
1331 .with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1332 config.rayon.proof_storage_worker_threads = Some(configured);
1333 config.rayon.proof_account_worker_threads = Some(configured);
1334 let runtime = RuntimeBuilder::new(config).build().unwrap();
1335 assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), configured);
1336 assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), configured);
1337 assert_eq!(runtime.proof_storage_worker_threads_override(), Some(configured));
1338 assert_eq!(runtime.proof_account_worker_threads_override(), Some(configured));
1339 }
1340 }
1341
1342 #[cfg(feature = "rayon")]
1343 #[reth_concurrency::test]
1344 fn zero_proof_worker_threads_use_the_default() {
1345 let rt = TokioRuntime::new().unwrap();
1346 let mut config =
1347 Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1348 config.rayon.proof_storage_worker_threads = Some(0);
1349 config.rayon.proof_account_worker_threads = Some(0);
1350 let runtime = RuntimeBuilder::new(config).build().unwrap();
1351
1352 let default = runtime.cpu_pool().current_num_threads() * 4;
1353 assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), default);
1354 assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), default);
1355 assert_eq!(runtime.proof_storage_worker_threads_override(), None);
1356 assert_eq!(runtime.proof_account_worker_threads_override(), None);
1357 }
1358
1359 #[reth_concurrency::test]
1360 fn test_runtime_builder() {
1361 let rt = TokioRuntime::new().unwrap();
1362 let config =
1363 Runtime::test_config().with_tokio(TokioConfig::existing_handle(rt.handle().clone()));
1364 let runtime = RuntimeBuilder::new(config).build().unwrap();
1365 let _ = runtime.handle();
1366 }
1367
1368 #[cfg(not(all(feature = "fuzz", dst)))]
1370 #[test]
1371 fn last_runtime_clone_can_drop_on_its_worker() {
1372 test_utils::run(|| {
1373 let runtime = RuntimeBuilder::new(Runtime::test_config()).build().unwrap();
1374 let task_runtime = runtime.clone();
1375 let (release, wait) = oneshot::channel();
1376 let task = runtime.handle().spawn(async move {
1377 wait.await.unwrap();
1378 drop(task_runtime);
1379 });
1380
1381 thread::spawn(move || drop(runtime)).join().unwrap();
1382 release.send(()).unwrap();
1383 Handle::current().block_on(task).unwrap();
1384 });
1385 }
1386
1387 #[cfg(not(all(feature = "fuzz", dst)))]
1389 #[test]
1390 fn shutdown_with_live_runtime_clones() {
1391 test_utils::run(|| {
1392 let runtime = RuntimeBuilder::new(Runtime::test_config()).build().unwrap();
1393 let retained = runtime.clone();
1394 let task_runtime = runtime.clone();
1395 let (started, ready) = oneshot::channel();
1396 let task = runtime.handle().spawn(async move {
1397 let _runtime = task_runtime;
1398 started.send(()).unwrap();
1399 future::pending::<()>().await;
1400 });
1401 Handle::current().block_on(ready).unwrap();
1402
1403 thread::spawn(move || runtime.shutdown_timeout(Duration::from_secs(5))).join().unwrap();
1404
1405 assert!(Handle::current().block_on(task).unwrap_err().is_cancelled());
1406 assert!(Handle::current()
1407 .block_on(retained.handle().spawn(async {}))
1408 .unwrap_err()
1409 .is_cancelled());
1410 retained.shutdown_timeout(Duration::from_secs(5));
1411 });
1412 }
1413
1414 #[cfg(not(all(feature = "fuzz", dst)))]
1416 #[test]
1417 fn shutdown_preserves_external_runtime() {
1418 test_utils::run(|| {
1419 let runtime = RuntimeBuilder::new(
1420 Runtime::test_config().with_tokio(TokioConfig::existing_handle(Handle::current())),
1421 )
1422 .build()
1423 .unwrap();
1424 let retained = runtime.clone();
1425
1426 runtime.shutdown_timeout(Duration::from_secs(5));
1427
1428 assert_eq!(
1429 Handle::current().block_on(retained.handle().spawn(async { 42 })).unwrap(),
1430 42
1431 );
1432 });
1433 }
1434
1435 #[cfg(not(all(feature = "fuzz", dst)))]
1437 #[reth_concurrency::test]
1438 fn critical_os_thread_uses_requested_name() {
1439 let runtime = Runtime::test();
1440 let (tx, rx) = mpsc::channel();
1441
1442 let handle = runtime.spawn_critical_os_thread(
1443 "critical-os-test",
1444 "critical os thread test",
1445 async move {
1446 let name = thread::current().name().unwrap().to_string();
1447 tx.send(name).unwrap();
1448 },
1449 );
1450
1451 let name = rx.recv_timeout(Duration::from_secs(5)).unwrap();
1452 assert_eq!(name, "critical-os-test");
1453 handle.join().unwrap();
1454 }
1455
1456 #[cfg(not(all(feature = "fuzz", dst)))]
1458 #[reth_concurrency::test]
1459 fn critical_os_thread_panic_is_reported() {
1460 let runtime = Runtime::test();
1461 let manager_handle = runtime.take_task_manager_handle().unwrap();
1462
1463 let handle = runtime.spawn_critical_os_thread(
1464 "critical-os-panic",
1465 "critical os thread panic test",
1466 async { panic!("critical os thread panic") },
1467 );
1468
1469 let err =
1470 runtime.handle().block_on(async move { manager_handle.await.unwrap().unwrap_err() });
1471 assert_eq!(err.task_name, "critical os thread panic test");
1472 assert_eq!(err.error, Some("critical os thread panic".to_string()));
1473 handle.join().unwrap();
1474 }
1475
1476 #[cfg(feature = "rayon")]
1477 #[reth_concurrency::test]
1478 fn test_worker_pools_are_lazy() {
1479 let runtime = Runtime::test();
1480
1481 assert!(!runtime.0.bal_streaming_pool.is_initialized());
1483 assert!(!runtime.0.proof_storage_worker_pool.is_initialized());
1484 assert!(!runtime.0.state_trie_overlay_worker_pool.is_initialized());
1485
1486 assert_eq!(runtime.bal_streaming_pool().current_num_threads(), 2);
1488 assert!(runtime.0.bal_streaming_pool.is_initialized());
1489
1490 assert_eq!(runtime.proof_storage_worker_pool().current_num_threads(), 2);
1491 assert_eq!(runtime.proof_account_worker_pool().current_num_threads(), 2);
1492 assert_eq!(runtime.prewarming_pool().current_num_threads(), 2);
1493 assert_eq!(runtime.state_trie_overlay_worker_pool().current_num_threads(), 2);
1494 }
1495
1496 #[reth_concurrency::test]
1497 async fn service_can_release_a_blocking_worker() {
1498 let runtime = Runtime::test();
1499 let (started_tx, started_rx) = oneshot::channel();
1500 let (release_tx, release_rx) = mpsc::channel();
1501 let (done_tx, done_rx) = oneshot::channel();
1502
1503 let service = runtime.spawn_critical_task("release worker", async move {
1504 started_rx.await.unwrap();
1505 release_tx.send(()).unwrap();
1506 });
1507 runtime.spawn_blocking_task_detached(async move {
1508 started_tx.send(()).unwrap();
1509 release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1510 done_tx.send(()).unwrap();
1511 });
1512
1513 done_rx.await.unwrap();
1514 service.await.unwrap();
1515 }
1516
1517 #[reth_concurrency::test]
1518 async fn signal_tasks_run_in_async_tests() {
1519 let runtime = Runtime::test();
1520 let (signal_tx, signal_rx) = oneshot::channel();
1521 let (graceful_tx, graceful_rx) = oneshot::channel();
1522 let (critical_tx, critical_rx) = oneshot::channel();
1523
1524 runtime.spawn_with_signal(|_| async move { signal_tx.send(()).unwrap() });
1525 runtime
1526 .spawn_with_graceful_shutdown_signal(|_| async move { graceful_tx.send(()).unwrap() });
1527 runtime.spawn_critical_with_graceful_shutdown_signal("critical", |_| async move {
1528 critical_tx.send(()).unwrap()
1529 });
1530
1531 signal_rx.await.unwrap();
1532 graceful_rx.await.unwrap();
1533 critical_rx.await.unwrap();
1534 }
1535}