1use std::{io, thread};
5use std::time::Duration;
6use std::sync::Arc;
7
8use tokio::runtime::{Builder as RuntimeBuilder, Handle};
9use tokio::net::{TcpListener, TcpStream};
10use tokio::sync::oneshot;
11
12use crate::worker::Worker;
13use crate::dropper::Dropper;
14
15pub struct Builder {
16 id: String,
18
19 builder: RuntimeBuilder,
21}
22
23impl Default for Builder {
24 fn default() -> Self {
25 Self {
26 id: "default-worker".to_string(),
27 builder: RuntimeBuilder::new_multi_thread(),
28 }
29 }
30}
31
32impl Builder {
33 pub fn worker_threads(&mut self, val: usize) -> &mut Self {
37 self.builder.worker_threads(val);
38 self
39 }
40
41 pub fn max_blocking_threads(&mut self, val: usize) -> &mut Self {
47 self.builder.max_blocking_threads(val);
48 self
49 }
50
51 pub fn thread_keep_alive(&mut self, duration: Duration) -> &mut Self {
55 self.builder.thread_keep_alive(duration);
56 self
57 }
58
59 pub fn thread_name(&mut self, val: impl Into<String>) -> &mut Self {
61 self.id = val.into();
62 self
63 }
64
65 pub fn build(&mut self) -> Result<Worker, io::Error> {
66 let worker = self
67 .builder
68 .enable_all()
69 .thread_name(self.id.clone())
70 .build()?;
71
72 let handle = worker.handle().clone();
73 let (send_stop, recv_stop) = oneshot::channel();
74 let _ = thread::Builder::new()
76 .name(format!("{}-blocker", self.id))
77 .spawn(move || worker.block_on(recv_stop));
78
79 Ok(Worker {
80 handle,
81 _dropper: Arc::new(Dropper {
82 close: Some(send_stop),
83 }),
84 })
85 }
86}