1use crate::metrics::WorkerPoolMetrics;
4use reth_concurrency::sync::{
5 atomic::{AtomicUsize, Ordering},
6 rayon, thread,
7 time::Instant,
8 OnceLock,
9};
10use std::{
11 any::Any,
12 cell::RefCell,
13 future::Future,
14 ops::Deref,
15 panic::{catch_unwind, AssertUnwindSafe},
16 pin::Pin,
17 sync::{Arc, Weak},
18 task::{ready, Context, Poll},
19};
20use tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};
21
22#[cfg(all(feature = "fuzz", dst))]
23use reth_concurrency::sync::channel;
24#[cfg(all(feature = "fuzz", dst))]
25use std::mem;
26
27#[cfg(not(all(feature = "fuzz", dst)))]
28use std::sync;
29
30#[derive(Clone, Debug)]
39pub struct BlockingTaskGuard(Arc<Semaphore>);
40
41impl BlockingTaskGuard {
42 pub fn new(max_blocking_tasks: usize) -> Self {
45 Self(Arc::new(Semaphore::new(max_blocking_tasks)))
46 }
47
48 pub async fn acquire_owned(self) -> Result<OwnedSemaphorePermit, AcquireError> {
50 self.0.acquire_owned().await
51 }
52
53 pub async fn acquire_many_owned(self, n: u32) -> Result<OwnedSemaphorePermit, AcquireError> {
55 self.0.acquire_many_owned(n).await
56 }
57}
58
59#[derive(Clone, Debug)]
72pub struct BlockingTaskPool {
73 pool: Arc<rayon::ThreadPool>,
74}
75
76impl BlockingTaskPool {
77 pub fn new(pool: rayon::ThreadPool) -> Self {
79 Self { pool: Arc::new(pool) }
80 }
81
82 pub fn builder() -> rayon::ThreadPoolBuilder {
84 rayon::ThreadPoolBuilder::new()
85 }
86
87 pub fn build() -> Result<Self, rayon::ThreadPoolBuildError> {
93 Self::builder().build().map(Self::new)
94 }
95
96 pub fn spawn<F, R>(&self, func: F) -> BlockingTaskHandle<R>
104 where
105 F: FnOnce() -> R + Send + 'static,
106 R: Send + 'static,
107 {
108 let (tx, rx) = oneshot::channel();
109
110 self.pool.spawn(move || {
111 let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));
112 });
113
114 BlockingTaskHandle { rx }
115 }
116
117 pub fn spawn_fifo<F, R>(&self, func: F) -> BlockingTaskHandle<R>
125 where
126 F: FnOnce() -> R + Send + 'static,
127 R: Send + 'static,
128 {
129 let (tx, rx) = oneshot::channel();
130
131 self.pool.spawn_fifo(move || {
132 let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));
133 });
134
135 BlockingTaskHandle { rx }
136 }
137}
138
139#[derive(Debug)]
145#[must_use = "futures do nothing unless you `.await` or poll them"]
146#[pin_project::pin_project]
147pub struct BlockingTaskHandle<T> {
148 #[pin]
149 pub(crate) rx: oneshot::Receiver<thread::Result<T>>,
150}
151
152impl<T> Future for BlockingTaskHandle<T> {
153 type Output = thread::Result<T>;
154
155 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
156 match ready!(self.project().rx.poll(cx)) {
157 Ok(res) => Poll::Ready(res),
158 Err(_) => Poll::Ready(Err(Box::<TokioBlockingTaskError>::default())),
159 }
160 }
161}
162
163#[derive(Debug, Default, thiserror::Error)]
167#[error("tokio channel dropped while awaiting result")]
168#[non_exhaustive]
169pub struct TokioBlockingTaskError;
170
171reth_concurrency::sync::thread_local! {
172 static WORKER: RefCell<Worker> = const { RefCell::new(Worker::new()) };
173}
174
175#[cfg(all(feature = "fuzz", dst))]
176std::thread_local! {
177 #[allow(
179 clippy::disallowed_types,
180 reason = "Host-local storage retains non-Send worker values; access is serialized by the selected Mutex."
181 )]
182 static WORKERS: RefCell<std::collections::BTreeMap<(usize, usize), std::rc::Rc<WorkerSlot>>> =
183 const { RefCell::new(std::collections::BTreeMap::new()) };
184}
185
186#[cfg(all(feature = "fuzz", dst))]
187#[derive(Default)]
188struct WorkerSlot {
189 state: RefCell<Worker>,
190 access: reth_concurrency::sync::Mutex<()>,
191 owner: std::cell::Cell<Option<thread::ThreadId>>,
192}
193
194fn with_current_worker<R>(f: impl FnOnce(&RefCell<Worker>) -> R) -> R {
195 #[cfg(all(feature = "fuzz", dst))]
196 if let Some(pool) = rayon::current_pool_id() {
197 let index = rayon::current_thread_index().expect("pool context has a worker index");
198 #[allow(
199 clippy::disallowed_methods,
200 reason = "Only finds worker storage in host TLS; the borrow ends before scheduler-managed locking."
201 )]
202 let worker =
203 WORKERS.with(|workers| workers.borrow_mut().entry((pool, index)).or_default().clone());
204 let current = thread::current().id();
207 if worker.owner.get() == Some(current) {
208 return f(&worker.state);
209 }
210 let access = worker.access.lock().expect("worker access is not poisoned");
212 worker.owner.set(Some(current));
213 let result = catch_unwind(AssertUnwindSafe(|| f(&worker.state)));
214 worker.owner.set(None);
215 drop(access);
216 return match result {
217 Ok(value) => value,
218 Err(panic) => std::panic::resume_unwind(panic),
219 };
220 }
221 WORKER.with(f)
222}
223
224#[derive(Debug)]
243pub struct WorkerPool {
244 pool: OnceLock<rayon::ThreadPool>,
245 metrics: OnceLock<WorkerPoolMetrics>,
246 num_threads: usize,
247 thread_name_prefix: &'static str,
248}
249
250impl WorkerPool {
251 pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {
256 Self { pool: OnceLock::new(), metrics: OnceLock::new(), num_threads, thread_name_prefix }
257 }
258
259 fn pool(&self) -> &rayon::ThreadPool {
261 self.pool.get_or_init(|| {
262 let prefix = self.thread_name_prefix;
263 build_pool_with_panic_handler(
264 rayon::ThreadPoolBuilder::new()
265 .num_threads(self.num_threads)
266 .thread_name(move |i| format!("{prefix}-{i:02}")),
267 )
268 .unwrap_or_else(|err| panic!("failed to build {prefix} worker pool: {err}"))
269 })
270 }
271
272 fn metrics(&self) -> &WorkerPoolMetrics {
274 self.metrics.get_or_init(|| WorkerPoolMetrics::new(self.thread_name_prefix))
275 }
276
277 pub fn is_initialized(&self) -> bool {
279 self.pool.get().is_some()
280 }
281
282 pub const fn num_threads(&self) -> usize {
284 self.num_threads
285 }
286
287 pub fn current_num_threads(&self) -> usize {
289 self.pool().current_num_threads()
290 }
291
292 pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {
298 if num_threads >= self.pool().current_num_threads() {
299 self.pool().broadcast(|_| {
301 with_current_worker(|worker| f(&mut worker.borrow_mut()));
302 });
303 } else {
304 let remaining = AtomicUsize::new(num_threads);
305 self.pool().broadcast(|_| {
306 let mut current = remaining.load(Ordering::Relaxed);
308 loop {
309 if current == 0 {
310 return;
311 }
312 match remaining.compare_exchange_weak(
313 current,
314 current - 1,
315 Ordering::Relaxed,
316 Ordering::Relaxed,
317 ) {
318 Ok(_) => break,
319 Err(actual) => current = actual,
320 }
321 }
322 with_current_worker(|worker| f(&mut worker.borrow_mut()));
323 });
324 }
325 }
326
327 pub fn install<R: Send>(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {
333 let pool = self.pool();
334 let metrics = self.metrics().clone();
335 let queued_at = Instant::now();
336
337 pool.install(move || {
338 let started_at = Instant::now();
339 metrics.record_job_queue_wait(started_at.saturating_duration_since(queued_at));
340 let _record_job_duration = RecordWorkerPoolJobDurationOnDrop::new(metrics, started_at);
341 Self::with_worker(f)
342 })
343 }
344
345 pub fn install_fn<R: Send>(&self, f: impl FnOnce() -> R + Send) -> R {
350 let pool = self.pool();
351 let metrics = self.metrics().clone();
352 let queued_at = Instant::now();
353
354 pool.install(move || {
355 let started_at = Instant::now();
356 metrics.record_job_queue_wait(started_at.saturating_duration_since(queued_at));
357 let _record_job_duration = RecordWorkerPoolJobDurationOnDrop::new(metrics, started_at);
358 f()
359 })
360 }
361
362 pub fn spawn_and_wait<R: Send + 'static>(&self, f: impl FnOnce() -> R + Send + 'static) -> R {
368 let pool = self.pool();
369 if pool.current_thread_index().is_some() {
370 return f()
371 }
372
373 #[cfg(not(all(feature = "fuzz", dst)))]
374 let (tx, rx) = sync::mpsc::sync_channel(1);
375 #[cfg(all(feature = "fuzz", dst))]
376 let (tx, rx) = channel::bounded(1);
377 self.spawn(move || {
378 let _ = tx.send(catch_unwind(AssertUnwindSafe(f)));
379 });
380
381 match rx.recv().expect("worker pool exited before completing task") {
382 Ok(result) => result,
383 Err(panic) => std::panic::resume_unwind(panic),
384 }
385 }
386
387 pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {
389 let pool = self.pool();
390 let metrics = self.metrics().clone();
391 let queued_at = Instant::now();
392
393 pool.spawn(move || {
394 let started_at = Instant::now();
395 metrics.record_job_queue_wait(started_at.saturating_duration_since(queued_at));
396 let _record_job_duration = RecordWorkerPoolJobDurationOnDrop::new(metrics, started_at);
397 f();
398 });
399 }
400
401 pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {
405 self.pool().in_place_scope(f)
406 }
407
408 pub fn with_worker<R>(f: impl FnOnce(&Worker) -> R) -> R {
427 with_current_worker(|worker| f(&worker.borrow()))
428 }
429
430 pub fn with_worker_mut<R>(f: impl FnOnce(&mut Worker) -> R) -> R {
449 with_current_worker(|worker| f(&mut worker.borrow_mut()))
450 }
451}
452
453#[cfg(all(feature = "fuzz", dst))]
454impl Drop for WorkerPool {
455 fn drop(&mut self) {
456 if let Some(pool) = self.pool.get() {
457 let id = pool.id();
458 #[allow(
459 clippy::disallowed_methods,
460 reason = "Removes this pool's non-Send worker storage on its host runner during teardown."
461 )]
462 WORKERS.with(|workers| workers.borrow_mut().retain(|(pool, _), _| *pool != id));
463 }
464 }
465}
466
467struct RecordWorkerPoolJobDurationOnDrop {
469 metrics: WorkerPoolMetrics,
470 started_at: Instant,
471}
472
473impl RecordWorkerPoolJobDurationOnDrop {
474 const fn new(metrics: WorkerPoolMetrics, started_at: Instant) -> Self {
475 Self { metrics, started_at }
476 }
477}
478
479impl Drop for RecordWorkerPoolJobDurationOnDrop {
480 fn drop(&mut self) {
481 self.metrics.record_job_duration(self.started_at.elapsed());
482 }
483}
484
485pub fn build_pool_with_panic_handler(
490 builder: rayon::ThreadPoolBuilder,
491) -> Result<rayon::ThreadPool, rayon::ThreadPoolBuildError> {
492 builder.panic_handler(|_| {}).build()
493}
494
495#[derive(Debug, Default)]
500pub struct Worker {
501 state: Option<(Weak<WorkerStatefulPool>, Box<dyn Any>)>,
502}
503
504impl Worker {
505 const fn new() -> Self {
507 Self { state: None }
508 }
509
510 fn init<T: 'static>(
516 &mut self,
517 stateful_pool: &Weak<WorkerStatefulPool>,
518 f: impl FnOnce(Option<&mut T>) -> T,
519 ) {
520 let existing = self.state.take().and_then(|(owner, boxed)| {
521 (Weak::ptr_eq(&owner, stateful_pool) && boxed.is::<T>()).then_some(boxed)
522 });
523
524 let new_state = match existing {
525 Some(mut boxed) => {
526 let r = boxed.downcast_mut::<T>().expect("type checked above");
527 *r = f(Some(r));
528 boxed
529 }
530 None => Box::new(f(None)),
531 };
532
533 self.state = Some((stateful_pool.clone(), new_state));
534 }
535
536 fn get<T: 'static>(&self, stateful_pool: &Weak<WorkerStatefulPool>) -> &T {
542 let (owner, state) = self.state.as_ref().expect("worker not initialized");
543 assert!(Weak::ptr_eq(owner, stateful_pool), "worker state run mismatch");
544 state.downcast_ref::<T>().expect("worker state type mismatch")
545 }
546
547 fn get_mut<T: 'static>(&mut self, stateful_pool: &Weak<WorkerStatefulPool>) -> &mut T {
553 let (owner, state) = self.state.as_mut().expect("worker not initialized");
554 assert!(Weak::ptr_eq(owner, stateful_pool), "worker state run mismatch");
555 state.downcast_mut::<T>().expect("worker state type mismatch")
556 }
557
558 fn get_or_init<T: 'static>(
564 &mut self,
565 stateful_pool: &Weak<WorkerStatefulPool>,
566 f: impl FnOnce() -> T,
567 ) -> &mut T {
568 if !self
569 .state
570 .as_ref()
571 .is_some_and(|(owner, state)| Weak::ptr_eq(owner, stateful_pool) && state.is::<T>())
572 {
573 self.state = None;
574 self.state = Some((stateful_pool.clone(), Box::new(f())));
575 }
576 self.get_mut(stateful_pool)
577 }
578
579 fn clear(&mut self, stateful_pool: &Weak<WorkerStatefulPool>) {
581 if self.state.as_ref().is_some_and(|(owner, _)| Weak::ptr_eq(owner, stateful_pool)) {
582 self.state = None;
583 }
584 }
585}
586
587#[derive(Debug)]
598pub struct WorkerStatefulPool {
599 pool: Arc<WorkerPool>,
600 owner: Weak<Self>,
601}
602
603impl WorkerStatefulPool {
604 pub fn new(pool: Arc<WorkerPool>) -> Arc<Self> {
606 Arc::new_cyclic(|owner| Self { pool, owner: owner.clone() })
607 }
608
609 pub fn init<T: 'static>(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {
614 self.pool.broadcast(self.pool.current_num_threads(), |worker| {
615 worker.init(&self.owner, &f);
616 });
617 }
618
619 pub fn get<T: 'static, R>(&self, f: impl FnOnce(&T) -> R) -> R {
625 WorkerPool::with_worker(|worker| f(worker.get(&self.owner)))
626 }
627
628 pub fn get_or_init<T: 'static, R>(
637 &self,
638 init: impl FnOnce() -> T,
639 f: impl FnOnce(&mut T) -> R,
640 ) -> R {
641 WorkerPool::with_worker_mut(|worker| f(worker.get_or_init(&self.owner, init)))
642 }
643}
644
645impl Deref for WorkerStatefulPool {
646 type Target = WorkerPool;
647
648 fn deref(&self) -> &Self::Target {
649 &self.pool
650 }
651}
652
653impl Drop for WorkerStatefulPool {
654 fn drop(&mut self) {
655 if let Some(pool) = self.pool.pool.get() {
656 #[cfg(all(feature = "fuzz", dst))]
657 let unwinding = thread::panicking();
658 pool.broadcast(|_| {
659 let clear = || {
660 with_current_worker(|worker| worker.borrow_mut().clear(&self.owner));
661 };
662 #[cfg(not(all(feature = "fuzz", dst)))]
663 clear();
664 #[cfg(all(feature = "fuzz", dst))]
665 if unwinding {
666 if let Err(panic) = catch_unwind(AssertUnwindSafe(clear)) {
667 mem::forget(panic);
669 tracing::error!("worker state destructor panicked during unwinding");
670 }
671 } else {
672 clear();
673 }
674 });
675 }
676 }
677}
678
679#[cfg(test)]
680mod tests {
681 use super::*;
682 use crate::test_utils;
683 use reth_concurrency::sync::{channel, rayon::prelude::*};
684 use std::{mem, time::Duration};
685
686 #[test]
687 fn blocking_pool() {
688 test_utils::run(|| {
689 let pool = BlockingTaskPool::build().unwrap();
690 let res = pool.spawn(move || 5);
691 let res = test_utils::block_on(res).unwrap();
692 assert_eq!(res, 5);
693 });
694 }
695
696 #[test]
697 fn blocking_pool_panic() {
698 test_utils::run(|| {
699 let pool = BlockingTaskPool::build().unwrap();
700 let res = pool.spawn(move || -> i32 {
701 panic!("blocking pool panic");
702 });
703 let panic = test_utils::block_on(res).unwrap_err();
704 assert_eq!(panic.downcast_ref::<&str>(), Some(&"blocking pool panic"));
705 });
706 }
707
708 #[reth_concurrency::test]
709 fn worker_pool_init_and_access() {
710 let pool = Arc::new(WorkerPool::new(2, "test"));
711 let state = WorkerStatefulPool::new(Arc::clone(&pool));
712 state.init(|_| vec![1u8, 2, 3]);
713 let sum = pool.install_fn(|| state.get(|v: &Vec<u8>| v.iter().sum::<u8>()));
714 assert_eq!(sum, 6);
715 drop(state);
716 pool.broadcast(2, |worker| assert!(worker.state.is_none()));
717 }
718
719 #[reth_concurrency::test]
720 fn worker_pool_reinit_reuses_resources() {
721 let pool = Arc::new(WorkerPool::new(1, "test"));
722 let state = WorkerStatefulPool::new(Arc::clone(&pool));
723 state.init(|existing: Option<&mut Vec<u8>>| {
724 assert!(existing.is_none());
725 vec![1, 2, 3]
726 });
727 state.init(|existing: Option<&mut Vec<u8>>| {
728 let v = existing.expect("should have existing state");
729 assert_eq!(v, &mut vec![1, 2, 3]);
730 v.push(4);
731 mem::take(v)
732 });
733 let len = pool.install_fn(|| state.get(Vec::<u8>::len));
734 assert_eq!(len, 4);
735 }
736
737 #[reth_concurrency::test]
738 fn worker_pool_clear_and_reinit() {
739 let pool = Arc::new(WorkerPool::new(1, "test"));
740 let state = WorkerStatefulPool::new(Arc::clone(&pool));
741 state.init(|_| 42u64);
742 assert_eq!(pool.install_fn(|| state.get(|v: &u64| *v)), 42);
743 drop(state);
744 let state = WorkerStatefulPool::new(Arc::clone(&pool));
745 state.init(|_| String::from("hello"));
746 assert_eq!(pool.install_fn(|| state.get(String::clone)), "hello");
747 }
748
749 #[reth_concurrency::test]
750 fn worker_pool_par_iter_with_worker() {
751 let pool = Arc::new(WorkerPool::new(2, "test"));
752 let state = WorkerStatefulPool::new(Arc::clone(&pool));
753 state.init(|_| 10u64);
754 let results = pool.install_fn(|| {
755 (0u64..4).into_par_iter().map(|i| state.get(|v: &u64| i + *v)).collect::<Vec<_>>()
756 });
757 assert_eq!(results, vec![10, 11, 12, 13]);
758 }
759
760 #[reth_concurrency::test]
761 fn worker_pool_spawn_and_wait_runs_on_target_pool() {
762 let caller_pool = WorkerPool::new(1, "caller");
763 let target_pool = Arc::new(WorkerPool::new(1, "target"));
764
765 let thread_name = caller_pool.install_fn({
766 let target_pool = Arc::clone(&target_pool);
767 move || {
768 WorkerPool::with_worker_mut(|_| {
769 target_pool.spawn_and_wait(|| thread::current().name().unwrap().to_owned())
770 })
771 }
772 });
773
774 assert_eq!(thread_name, "target-00");
775 }
776
777 #[reth_concurrency::test]
778 fn worker_get_or_init_reuses_only_matching_run_and_type() {
779 let mut worker = Worker::new();
780 let first = stateful_pool();
781 let second = stateful_pool();
782
783 worker.get_or_init(&first.owner, || vec![1u8]).push(2);
784 assert_eq!(
785 worker.get_or_init::<Vec<u8>>(&first.owner.clone(), || panic!("must reuse")),
786 &[1, 2]
787 );
788 assert_eq!(worker.get_or_init(&second.owner, || vec![3u8]), &[3]);
789 assert_eq!(worker.get_or_init(&second.owner, || String::from("new type")), "new type");
790 assert_eq!(*worker.get_or_init(&first.owner, || 42u64), 42);
791 }
792
793 #[reth_concurrency::test]
794 fn worker_init_reuses_only_matching_run_and_type() {
795 let mut worker = Worker::new();
796 let first = stateful_pool();
797 let second = stateful_pool();
798 worker.init(&first.owner, |_| 1u64);
799 worker.init(&second.owner, |existing: Option<&mut u64>| {
800 assert!(existing.is_none());
801 2
802 });
803 worker.init(&second.owner, |existing: Option<&mut String>| {
804 assert!(existing.is_none());
805 String::from("new type")
806 });
807 assert_eq!(worker.get::<String>(&second.owner), "new type");
808 }
809
810 #[reth_concurrency::test]
811 fn worker_pool_late_cleanup_preserves_other_runs() {
812 let pool = Arc::new(WorkerPool::new(2, "run-cleanup"));
813 let first = WorkerStatefulPool::new(Arc::clone(&pool));
814 let second = WorkerStatefulPool::new(Arc::clone(&pool));
815 first.init(|_| 1u64);
816 pool.broadcast(1, |worker| {
817 assert_eq!(*worker.get_or_init(&second.owner, || 2u64), 2);
818 });
819 drop(first);
820 let retained = AtomicUsize::new(0);
821 pool.broadcast(2, |worker| {
822 if let Some((owner, state)) = &worker.state {
823 assert!(Weak::ptr_eq(owner, &second.owner));
824 assert_eq!(state.downcast_ref::<u64>(), Some(&2));
825 retained.fetch_add(1, Ordering::Relaxed);
826 }
827 });
828 assert_eq!(retained.load(Ordering::Relaxed), 1);
829 drop(second);
830 pool.broadcast(2, |worker| assert!(worker.state.is_none()));
831 }
832
833 #[reth_concurrency::test]
834 #[should_panic(expected = "worker state run mismatch")]
835 fn worker_get_rejects_another_run() {
836 let mut worker = Worker::new();
837 worker.init(&stateful_pool().owner, |_| 1u64);
838 worker.get::<u64>(&stateful_pool().owner);
839 }
840
841 #[reth_concurrency::test]
842 #[should_panic(expected = "worker state run mismatch")]
843 fn worker_get_mut_rejects_another_run() {
844 let mut worker = Worker::new();
845 worker.init(&stateful_pool().owner, |_| 1u64);
846 worker.get_mut::<u64>(&stateful_pool().owner);
847 }
848
849 #[reth_concurrency::test]
850 fn worker_replacement_drops_previous_state_before_initialization() {
851 let mut worker = Worker::new();
852 let previous_run = stateful_pool();
853 let next_run = stateful_pool();
854 let resource = Arc::new(());
855
856 for owner in [&previous_run.owner, &next_run.owner] {
857 worker.init(&previous_run.owner, |_| Arc::clone(&resource));
858 assert_eq!(Arc::strong_count(&resource), 2);
859 assert_eq!(
860 *worker.get_or_init(owner, || {
861 assert_eq!(Arc::strong_count(&resource), 1);
862 42u64
863 }),
864 42,
865 );
866 }
867 }
868
869 #[reth_concurrency::test]
870 fn worker_failed_replacement_leaves_state_uninitialized() {
871 let mut worker = Worker::new();
872 let previous_run = stateful_pool();
873 let next_run = stateful_pool();
874 worker.init(&previous_run.owner, |_| 1u64);
875
876 let panic = catch_unwind(AssertUnwindSafe(|| {
877 worker.get_or_init::<u64>(&next_run.owner, || panic!("initialization failed"));
878 }))
879 .unwrap_err();
880 assert_eq!(panic.downcast_ref::<&str>(), Some(&"initialization failed"));
881 assert!(worker.state.is_none());
882 assert_eq!(*worker.get_or_init(&next_run.owner, || 2u64), 2);
883 }
884
885 #[reth_concurrency::test]
886 fn stateful_pool_drop_does_not_initialize_unused_pool() {
887 let pool = Arc::new(WorkerPool::new(1, "unused-state"));
888 drop(WorkerStatefulPool::new(Arc::clone(&pool)));
889 assert!(!pool.is_initialized());
890 }
891
892 #[reth_concurrency::test]
893 fn stateful_pool_last_job_handle_clears_state() {
894 let pool = Arc::new(WorkerPool::new(2, "owned-state"));
895 let state = WorkerStatefulPool::new(Arc::clone(&pool));
896 let owner = Arc::downgrade(&state);
897 let resource = Arc::new(());
898 state.init(|_| Arc::clone(&resource));
899 let (ready_tx, ready_rx) = channel::unbounded();
900 let (release_tx, release_rx) = channel::unbounded();
901 let (done_tx, done_rx) = channel::unbounded();
902 let job_state = Arc::clone(&state);
903 state.spawn(move || {
904 ready_tx.send(()).unwrap();
905 release_rx.recv_timeout(Duration::from_secs(5)).unwrap();
906 job_state.get(|value: &Arc<()>| assert_eq!(Arc::strong_count(value), 3));
907 drop(job_state);
908 done_tx.send(()).unwrap();
909 });
910 ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();
911 drop(state);
912 assert!(owner.upgrade().is_some());
913 assert_eq!(Arc::strong_count(&resource), 3);
914 release_tx.send(()).unwrap();
915 done_rx.recv_timeout(Duration::from_secs(5)).unwrap();
916 assert!(owner.upgrade().is_none());
917 assert_eq!(Arc::strong_count(&resource), 1);
918 pool.broadcast(2, |worker| assert!(worker.state.is_none()));
919 }
920
921 #[reth_concurrency::test]
922 fn stateful_pool_clears_after_job_panics() {
923 let pool = Arc::new(WorkerPool::new(1, "unwind-state"));
924 let state = WorkerStatefulPool::new(Arc::clone(&pool));
925 let resource = Arc::new(());
926 state.init(|_| Arc::clone(&resource));
927 let panic = catch_unwind(AssertUnwindSafe(|| {
928 pool.install_fn(move || {
929 state.get_or_init(|| Arc::new(()), |_| panic!("job failed"));
930 });
931 }))
932 .unwrap_err();
933 assert_eq!(panic.downcast_ref::<&str>(), Some(&"job failed"));
934 assert_eq!(Arc::strong_count(&resource), 1);
935 pool.broadcast(1, |worker| assert!(worker.state.is_none()));
936 }
937
938 #[reth_concurrency::test]
939 fn stateful_pool_clears_after_unwrapping_owner() {
940 let pool = Arc::new(WorkerPool::new(1, "unwrapped-state"));
941 let state = WorkerStatefulPool::new(Arc::clone(&pool));
942 let resource = Arc::new(());
943 state.init(|_| Arc::clone(&resource));
944 let state = Arc::try_unwrap(state).unwrap();
945 assert_eq!(Arc::strong_count(&resource), 2);
946 drop(state);
947 assert_eq!(Arc::strong_count(&resource), 1);
948 pool.broadcast(1, |worker| assert!(worker.state.is_none()));
949 }
950
951 fn stateful_pool() -> Arc<WorkerStatefulPool> {
952 WorkerStatefulPool::new(Arc::new(WorkerPool::new(1, "state-test")))
953 }
954}