1#![allow(clippy::let_underscore_future)]
2use std::any::{Any, TypeId};
3use std::sync::{Arc, atomic::AtomicUsize, atomic::Ordering};
4use std::{cell::RefCell, collections::HashMap, fmt, future::Future, pin::Pin, thread};
5
6use async_channel::{Receiver, Sender, unbounded};
7
8use crate::system::{FnExec, Id, System, SystemCommand};
9
10thread_local!(
11 static ADDR: RefCell<Option<Arbiter>> = const { RefCell::new(None) };
12 static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> = RefCell::new(HashMap::new());
13);
14
15pub(super) static COUNT: AtomicUsize = AtomicUsize::new(0);
16
17pub(super) enum ArbiterCommand {
18 Stop,
19 Execute(Pin<Box<dyn Future<Output = ()> + Send>>),
20 ExecuteFn(Box<dyn FnExec>),
21}
22
23pub struct Arbiter {
29 id: usize,
30 pub(crate) sys_id: usize,
31 name: Arc<String>,
32 sender: Sender<ArbiterCommand>,
33 thread_handle: Option<thread::JoinHandle<()>>,
34}
35
36impl fmt::Debug for Arbiter {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 write!(f, "Arbiter({:?})", self.name.as_ref())
39 }
40}
41
42impl Default for Arbiter {
43 fn default() -> Arbiter {
44 Arbiter::new()
45 }
46}
47
48impl Clone for Arbiter {
49 fn clone(&self) -> Self {
50 Self::with_sender(self.sys_id, self.id, self.name.clone(), self.sender.clone())
51 }
52}
53
54impl Arbiter {
55 #[allow(clippy::borrowed_box)]
56 pub(super) fn new_system(name: String) -> (Self, ArbiterController) {
57 let (tx, rx) = unbounded();
58
59 let arb = Arbiter::with_sender(0, 0, Arc::new(name), tx);
60 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
61 STORAGE.with(|cell| cell.borrow_mut().clear());
62
63 (arb, ArbiterController { rx, stop: None })
64 }
65
66 pub fn current() -> Arbiter {
69 ADDR.with(|cell| match *cell.borrow() {
70 Some(ref addr) => addr.clone(),
71 None => panic!("Arbiter is not running"),
72 })
73 }
74
75 pub fn stop(&self) {
77 let _ = self.sender.try_send(ArbiterCommand::Stop);
78 }
79
80 pub fn new() -> Arbiter {
83 let id = COUNT.load(Ordering::Relaxed) + 1;
84 Arbiter::with_name(format!("{}:arb:{}", System::current().name(), id))
85 }
86
87 pub fn with_name(name: String) -> Arbiter {
90 let id = COUNT.fetch_add(1, Ordering::Relaxed);
91 let sys = System::current();
92 let name2 = Arc::new(name.clone());
93 let config = sys.config();
94 let (arb_tx, arb_rx) = unbounded();
95 let arb_tx2 = arb_tx.clone();
96
97 let builder = if sys.config().stack_size > 0 {
98 thread::Builder::new()
99 .name(name)
100 .stack_size(sys.config().stack_size)
101 } else {
102 thread::Builder::new().name(name)
103 };
104
105 let name = name2.clone();
106 let sys_id = sys.id();
107
108 let handle = builder
109 .spawn(move || {
110 log::info!("Starting {:?} arbiter", name2);
111
112 let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx);
113
114 let (stop, stop_rx) = oneshot::channel();
115 STORAGE.with(|cell| cell.borrow_mut().clear());
116
117 System::set_current(sys);
118
119 config.block_on(async move {
120 let _ = crate::spawn(
122 ArbiterController {
123 stop: Some(stop),
124 rx: arb_rx,
125 }
126 .run(),
127 );
128 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
129
130 let _ = System::current()
132 .sys()
133 .try_send(SystemCommand::RegisterArbiter(Id(id), arb));
134
135 let _ = stop_rx.await;
137 });
138
139 let _ = System::current()
141 .sys()
142 .try_send(SystemCommand::UnregisterArbiter(Id(id)));
143 })
144 .unwrap_or_else(|err| {
145 panic!("Cannot spawn an arbiter's thread {:?}: {:?}", &name, err)
146 });
147
148 Arbiter {
149 id,
150 name,
151 sys_id: sys_id.0,
152 sender: arb_tx2,
153 thread_handle: Some(handle),
154 }
155 }
156
157 fn with_sender(
158 sys_id: usize,
159 id: usize,
160 name: Arc<String>,
161 sender: Sender<ArbiterCommand>,
162 ) -> Self {
163 Self {
164 id,
165 sys_id,
166 name,
167 sender,
168 thread_handle: None,
169 }
170 }
171
172 pub fn id(&self) -> Id {
174 Id(self.id)
175 }
176
177 pub fn name(&self) -> &str {
179 self.name.as_ref()
180 }
181
182 pub fn spawn<F>(&self, future: F)
184 where
185 F: Future<Output = ()> + Send + 'static,
186 {
187 let _ = self
188 .sender
189 .try_send(ArbiterCommand::Execute(Box::pin(future)));
190 }
191
192 #[rustfmt::skip]
193 pub fn spawn_with<F, R, O>(
196 &self,
197 f: F
198 ) -> impl Future<Output = Result<O, oneshot::RecvError>> + Send + 'static
199 where
200 F: FnOnce() -> R + Send + 'static,
201 R: Future<Output = O> + 'static,
202 O: Send + 'static,
203 {
204 let (tx, rx) = oneshot::channel();
205 let _ = self
206 .sender
207 .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
208 crate::spawn(async move {
209 let _ = tx.send(f().await);
210 });
211 })));
212 rx
213 }
214
215 #[rustfmt::skip]
216 pub fn exec<F, R>(&self, f: F) -> impl Future<Output = Result<R, oneshot::RecvError>> + Send + 'static
220 where
221 F: FnOnce() -> R + Send + 'static,
222 R: Send + 'static,
223 {
224 let (tx, rx) = oneshot::channel();
225 let _ = self
226 .sender
227 .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
228 let _ = tx.send(f());
229 })));
230 rx
231 }
232
233 pub fn exec_fn<F>(&self, f: F)
236 where
237 F: FnOnce() + Send + 'static,
238 {
239 let _ = self
240 .sender
241 .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
242 f();
243 })));
244 }
245
246 pub fn set_item<T: 'static>(item: T) {
248 STORAGE
249 .with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
250 }
251
252 pub fn contains_item<T: 'static>() -> bool {
254 STORAGE.with(move |cell| cell.borrow().get(&TypeId::of::<T>()).is_some())
255 }
256
257 pub fn get_item<T: 'static, F, R>(f: F) -> R
261 where
262 F: FnOnce(&T) -> R,
263 {
264 STORAGE.with(move |cell| {
265 let mut st = cell.borrow_mut();
266 let item = st
267 .get_mut(&TypeId::of::<T>())
268 .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
269 .unwrap();
270 f(item)
271 })
272 }
273
274 pub fn get_value<T, F>(f: F) -> T
276 where
277 T: Clone + 'static,
278 F: FnOnce() -> T,
279 {
280 STORAGE.with(move |cell| {
281 let mut st = cell.borrow_mut();
282 if let Some(boxed) = st.get(&TypeId::of::<T>())
283 && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
284 {
285 return val.clone();
286 }
287 let val = f();
288 st.insert(TypeId::of::<T>(), Box::new(val.clone()));
289 val
290 })
291 }
292
293 pub fn join(&mut self) -> thread::Result<()> {
295 if let Some(thread_handle) = self.thread_handle.take() {
296 thread_handle.join()
297 } else {
298 Ok(())
299 }
300 }
301}
302
303impl Eq for Arbiter {}
304
305impl PartialEq for Arbiter {
306 fn eq(&self, other: &Self) -> bool {
307 self.id == other.id && self.sys_id == other.sys_id
308 }
309}
310
311pub(crate) struct ArbiterController {
312 stop: Option<oneshot::Sender<i32>>,
313 rx: Receiver<ArbiterCommand>,
314}
315
316impl Drop for ArbiterController {
317 fn drop(&mut self) {
318 if thread::panicking() {
319 if System::current().stop_on_panic() {
320 eprintln!("Panic in Arbiter thread, shutting down system.");
321 System::current().stop_with_code(1)
322 } else {
323 eprintln!("Panic in Arbiter thread.");
324 }
325 }
326 }
327}
328
329impl ArbiterController {
330 pub(super) async fn run(mut self) {
331 loop {
332 match self.rx.recv().await {
333 Ok(ArbiterCommand::Stop) => {
334 if let Some(stop) = self.stop.take() {
335 let _ = stop.send(0);
336 };
337 break;
338 }
339 Ok(ArbiterCommand::Execute(fut)) => {
340 let _ = crate::spawn(fut);
341 }
342 Ok(ArbiterCommand::ExecuteFn(f)) => {
343 f.call_box();
344 }
345 Err(_) => break,
346 }
347 }
348 }
349}