relay_threading/
builder.rs1use std::any::Any;
2use std::future::Future;
3use std::io;
4use std::sync::Arc;
5
6use crate::pool::{AsyncPool, Thread};
7use crate::pool::{CustomSpawn, DefaultSpawn, ThreadSpawn};
8
9pub(crate) type PanicHandler = dyn Fn(Box<dyn Any + Send>) + Send + Sync;
11
12pub struct AsyncPoolBuilder<S = DefaultSpawn> {
18 pub(crate) runtime: tokio::runtime::Handle,
19 pub(crate) pool_name: Option<&'static str>,
20 pub(crate) thread_name: Option<Box<dyn FnMut(usize) -> String>>,
21 pub(crate) thread_panic_handler: Option<Arc<PanicHandler>>,
22 pub(crate) task_panic_handler: Option<Arc<PanicHandler>>,
23 pub(crate) spawn_handler: S,
24 pub(crate) num_threads: usize,
25 pub(crate) max_concurrency: usize,
26}
27
28impl AsyncPoolBuilder<DefaultSpawn> {
29 pub fn new(runtime: tokio::runtime::Handle) -> AsyncPoolBuilder<DefaultSpawn> {
33 AsyncPoolBuilder {
34 runtime,
35 pool_name: None,
36 thread_name: None,
37 thread_panic_handler: None,
38 task_panic_handler: None,
39 spawn_handler: DefaultSpawn,
40 num_threads: 1,
41 max_concurrency: 1,
42 }
43 }
44}
45
46impl<S> AsyncPoolBuilder<S>
47where
48 S: ThreadSpawn,
49{
50 pub fn pool_name(mut self, pool_name: &'static str) -> Self {
52 self.pool_name = Some(pool_name);
53 self
54 }
55
56 pub fn thread_name<F>(mut self, thread_name: F) -> Self
61 where
62 F: FnMut(usize) -> String + 'static,
63 {
64 self.thread_name = Some(Box::new(thread_name));
65 self
66 }
67
68 pub fn thread_panic_handler<F>(mut self, panic_handler: F) -> Self
73 where
74 F: Fn(Box<dyn Any + Send>) + Send + Sync + 'static,
75 {
76 self.thread_panic_handler = Some(Arc::new(panic_handler));
77 self
78 }
79
80 pub fn task_panic_handler<F>(mut self, panic_handler: F) -> Self
85 where
86 F: Fn(Box<dyn Any + Send>) + Send + Sync + 'static,
87 {
88 self.task_panic_handler = Some(Arc::new(panic_handler));
89 self
90 }
91
92 pub fn spawn_handler<F>(self, spawn_handler: F) -> AsyncPoolBuilder<CustomSpawn<F>>
97 where
98 F: FnMut(Thread) -> io::Result<()>,
99 {
100 AsyncPoolBuilder {
101 runtime: self.runtime,
102 pool_name: self.pool_name,
103 thread_name: self.thread_name,
104 thread_panic_handler: self.thread_panic_handler,
105 task_panic_handler: self.task_panic_handler,
106 spawn_handler: CustomSpawn::new(spawn_handler),
107 num_threads: self.num_threads,
108 max_concurrency: self.max_concurrency,
109 }
110 }
111
112 pub fn num_threads(mut self, num_threads: usize) -> Self {
116 self.num_threads = num_threads;
117 self
118 }
119
120 pub fn max_concurrency(mut self, max_concurrency: usize) -> Self {
124 self.max_concurrency = max_concurrency;
125 self
126 }
127
128 pub fn build<F>(self) -> Result<AsyncPool<F>, io::Error>
133 where
134 F: Future<Output = ()> + Send + 'static,
135 {
136 AsyncPool::new(self)
137 }
138}