1#![allow(clippy::missing_panics_doc)]
2use std::sync::{Arc, atomic::AtomicBool, atomic::AtomicUsize, atomic::Ordering};
3use std::{any::Any, any::TypeId, cell::RefCell, fmt, mem, panic, rc::Rc, thread};
4
5use async_channel::{Receiver, Sender, unbounded};
6use parking_lot::Mutex;
7
8use crate::metrics::{LatencyMetrics, LatencyStats, start_latency_sampler};
9use crate::{Handle, HashMap, Id, System};
10
11thread_local!(
12 static ADDR: RefCell<Option<Arbiter>> = const { RefCell::new(None) };
13 static STORAGE: RefCell<HashMap<TypeId, Rc<dyn Any>>> = RefCell::new(HashMap::default());
14 static ON_SHUTDOWN: RefCell<Vec<Box<dyn FnOnce()>>> = const { RefCell::new(Vec::new()) };
15);
16
17pub(super) static COUNT: AtomicUsize = AtomicUsize::new(99);
18
19pub(super) enum ArbiterCommand {
20 Stop,
21}
22
23pub struct Arbiter(pub(crate) Arc<ArbiterInner>);
33
34type OnCloseStorage = Arc<Mutex<Vec<Box<dyn Fn() + Send + Sync>>>>;
35
36pub(crate) struct ArbiterInner {
37 id: usize,
38 name: Arc<String>,
39 sys_id: usize,
40 hnd: Option<Handle>,
41 pub(crate) sender: Sender<ArbiterCommand>,
42 thread_handle: Mutex<Option<thread::JoinHandle<()>>>,
43 on_stop: OnCloseStorage,
44 running: AtomicBool,
45 pub(crate) latency: Arc<LatencyStats>,
46 #[cfg(target_os = "linux")]
47 tid: i32,
48 #[cfg(windows)]
49 thread: Option<crate::watchdog::ThreadHandle>,
50}
51
52impl fmt::Debug for Arbiter {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 write!(f, "Arbiter({:?})", self.0.name.as_ref())
55 }
56}
57
58impl Clone for Arbiter {
59 fn clone(&self) -> Self {
60 Self(self.0.clone())
61 }
62}
63
64impl Default for Arbiter {
65 fn default() -> Self {
66 Self::new()
67 }
68}
69
70impl Arbiter {
71 #[allow(clippy::borrowed_box)]
72 pub(super) fn new_system(id: usize, name: String) -> (Self, ArbiterController) {
73 let (tx, rx) = unbounded();
74
75 let aid = COUNT.fetch_add(1, Ordering::Relaxed);
76 let arb = Arbiter::with_sender(id, aid, Arc::new(name), tx, Arc::default());
77 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
78 clear_storage();
79
80 (
81 arb,
82 ArbiterController {
83 rx,
84 sys: None,
85 stop: None,
86 },
87 )
88 }
89
90 pub fn current() -> Arbiter {
96 ADDR.with(|cell| match *cell.borrow() {
97 Some(ref addr) => addr.clone(),
98 None => panic!("Arbiter is not running"),
99 })
100 }
101
102 pub fn stop(&self) {
108 let _ = self.0.sender.try_send(ArbiterCommand::Stop);
109 }
110
111 pub fn new() -> Arbiter {
120 let id = COUNT.fetch_add(1, Ordering::Relaxed);
121 Arbiter::start(id, format!("{}:arb:{}", System::current().name(), id), None)
122 }
123
124 pub fn with_name(name: String) -> Arbiter {
133 Arbiter::start(COUNT.fetch_add(1, Ordering::Relaxed), name, None)
134 }
135
136 pub fn with_init<F>(name: String, init: F) -> Arbiter
149 where
150 F: FnOnce() + Send + 'static,
151 {
152 Arbiter::start(
153 COUNT.fetch_add(1, Ordering::Relaxed),
154 name,
155 Some(Box::new(init)),
156 )
157 }
158
159 fn start(id: usize, name: String, init: Option<Box<dyn FnOnce() + Send>>) -> Arbiter {
160 let sys = System::current();
161 let name2 = Arc::new(name.clone());
162 let config = sys.config();
163 let (arb_tx, arb_rx) = unbounded();
164
165 let builder = if sys.config().stack_size > 0 {
166 thread::Builder::new()
167 .name(name)
168 .stack_size(sys.config().stack_size)
169 } else {
170 thread::Builder::new().name(name)
171 };
172
173 let name = name2.clone();
174 let sys_id = sys.id();
175 let (arb_hnd_tx, arb_hnd_rx) = oneshot::channel();
176
177 let handle = builder
178 .spawn(move || {
179 if let Some(init) = init {
180 init();
181 }
182 let name3 = name2.clone();
183 log::info!("Starting {name3:?} arbiter");
184
185 let sys2 = sys.clone();
186 let (stop, stop_rx) = oneshot::channel();
187 clear_storage();
188
189 let result = crate::driver::block_on(config.runner.as_ref(), async move {
191 let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx, Arc::default());
192 sys.register_arbiter(arb.clone());
193 start_latency_sampler(&arb.0.latency, config.latency_interval);
195 arb_hnd_tx
196 .send(arb.clone())
197 .expect("Controller thread has gone");
198
199 crate::spawn_detached(
201 ArbiterController {
202 sys: None,
203 stop: Some(stop),
204 rx: arb_rx,
205 }
206 .run(sys),
207 );
208 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
209
210 let _ = stop_rx.await;
212 });
213
214 let cleanup = || {
215 sys2.unregister_arbiter(Id(id));
217 run_shutdown_callbacks();
219 unsafe {
220 remove_all_items();
221 }
222 };
223 if result.is_err() {
224 crate::abort_on_panic(cleanup);
225 } else {
226 cleanup();
227 }
228
229 if let Err(e) = result {
230 log::error!("Arbiter {name3:?} has panicked.");
231 panic::resume_unwind(e);
232 }
233 log::info!("Arbiter {name3:?} has stopped");
234 })
235 .unwrap_or_else(|err| panic!("Cannot spawn an arbiter's thread {name:?}: {err:?}"));
236
237 let arb = arb_hnd_rx.recv().expect("Could not start new arbiter");
238 *arb.0.thread_handle.lock() = Some(handle);
239 arb
240 }
241
242 fn with_sender(
243 sys_id: usize,
244 id: usize,
245 name: Arc<String>,
246 sender: Sender<ArbiterCommand>,
247 on_stop: OnCloseStorage,
248 ) -> Self {
249 #[cfg(feature = "tokio")]
250 let hnd = { Handle::new() };
251
252 #[cfg(feature = "compio")]
253 let hnd = { Handle::new() };
254
255 #[cfg(all(not(feature = "compio"), not(feature = "tokio")))]
256 let hnd = { Handle::current() };
257
258 Self(Arc::new(ArbiterInner {
259 id,
260 sys_id,
261 name,
262 sender,
263 on_stop,
264 hnd: Some(hnd),
265 thread_handle: Mutex::new(None),
266 running: AtomicBool::new(true),
267 latency: Arc::default(),
268 #[cfg(target_os = "linux")]
269 #[allow(clippy::cast_possible_truncation)]
270 tid: unsafe { libc::syscall(libc::SYS_gettid) } as i32,
271 #[cfg(windows)]
272 thread: crate::watchdog::ThreadHandle::current(),
273 }))
274 }
275
276 pub fn id(&self) -> Id {
278 Id(self.0.id)
279 }
280
281 #[cfg(target_os = "linux")]
282 pub(crate) fn tid(&self) -> i32 {
284 self.0.tid
285 }
286
287 #[cfg(windows)]
288 pub(crate) fn thread(&self) -> Option<&crate::watchdog::ThreadHandle> {
290 self.0.thread.as_ref()
291 }
292
293 pub fn name(&self) -> &str {
295 self.0.name.as_ref()
296 }
297
298 #[inline]
299 pub fn handle(&self) -> &Handle {
301 self.0.hnd.as_ref().unwrap()
302 }
303
304 pub fn latency(&self) -> Option<LatencyMetrics> {
309 self.0.latency.metrics()
310 }
311
312 #[inline]
313 pub fn is_running(&self) -> bool {
318 self.0.running.load(Ordering::Relaxed)
319 }
320
321 pub fn get_value<T, F>(f: F) -> T
331 where
332 T: Clone + 'static,
333 F: FnOnce() -> T,
334 {
335 let mut f = Some(f);
336 STORAGE
337 .try_with(|cell| {
338 let mut st = cell.borrow_mut();
339 if let Some(boxed) = st.get(&TypeId::of::<T>())
340 && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
341 {
342 return val.clone();
343 }
344 let val = (f.take().unwrap())();
345 st.insert(TypeId::of::<T>(), Rc::new(val.clone()));
346 val
347 })
348 .unwrap_or_else(|_| (f.take().unwrap())())
349 }
350
351 pub fn on_shutdown<F>(f: F)
365 where
366 F: FnOnce() + 'static,
367 {
368 let f: Box<dyn FnOnce()> = Box::new(f);
369 let _ = ON_SHUTDOWN.try_with(move |cell| cell.borrow_mut().push(f));
370 }
371
372 #[must_use]
373 pub fn on_stop<F>(self, f: F) -> Self
381 where
382 F: Fn() + Send + Sync + 'static,
383 {
384 self.0.on_stop.lock().push(Box::new(f));
385 self
386 }
387
388 pub(crate) fn try_current() -> Option<Arbiter> {
390 ADDR.try_with(|cell| cell.borrow().clone()).ok().flatten()
391 }
392
393 pub(crate) fn finalize(&self) {
396 self.0.running.store(false, Ordering::Relaxed);
397 let on_stop = mem::take(&mut *self.0.on_stop.lock());
398 for f in on_stop {
400 f();
401 }
402 }
403
404 pub fn join(&mut self) -> thread::Result<()> {
418 if let Some(thread_handle) = self.0.thread_handle.lock().take() {
419 thread_handle.join()
420 } else {
421 Ok(())
422 }
423 }
424}
425
426impl Eq for Arbiter {}
427
428impl PartialEq for Arbiter {
429 fn eq(&self, other: &Self) -> bool {
430 self.0.id == other.0.id && self.0.sys_id == other.0.sys_id
431 }
432}
433
434pub(crate) struct ArbiterController {
435 sys: Option<System>,
436 rx: Receiver<ArbiterCommand>,
437 stop: Option<oneshot::Sender<i32>>,
438}
439
440impl ArbiterController {
441 pub(super) async fn run(mut self, sys: System) {
442 self.sys = Some(sys);
443 while let Ok(ArbiterCommand::Stop) = self.rx.recv().await {
444 if let Some(stop) = self.stop.take() {
447 run_shutdown_callbacks();
448 let _ = stop.send(0);
449 }
450 }
451 }
452}
453
454pub(crate) fn run_shutdown_callbacks() {
457 loop {
458 let callbacks = ON_SHUTDOWN
459 .try_with(|cell| mem::take(&mut *cell.borrow_mut()))
460 .unwrap_or_default();
461 if callbacks.is_empty() {
462 break;
463 }
464 for f in callbacks {
465 f();
466 }
467 }
468}
469
470pub fn set_item<T: 'static>(item: T) {
478 let item: Rc<dyn Any> = Rc::new(item);
479 let old = STORAGE
480 .try_with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), item))
481 .ok()
482 .flatten();
483 drop(old);
484}
485
486pub fn get_item<T: Clone + 'static>() -> Option<T> {
491 STORAGE
492 .try_with(move |cell| {
493 cell.borrow()
494 .get(&TypeId::of::<T>())
495 .and_then(|boxed| boxed.downcast_ref())
496 .cloned()
497 })
498 .ok()
499 .flatten()
500}
501
502pub fn with_item<T: Default + 'static, F, R>(f: F) -> R
510where
511 F: FnOnce(&T) -> R,
512{
513 let val = STORAGE
516 .try_with(|cell| {
517 let existing = cell.borrow().get(&TypeId::of::<T>()).cloned();
518 existing.unwrap_or_else(|| {
519 let val: Rc<dyn Any> = Rc::new(T::default());
520 cell.borrow_mut().insert(TypeId::of::<T>(), val.clone());
521 val
522 })
523 })
524 .ok();
525 match val {
526 Some(val) => f(val.downcast_ref::<T>().unwrap()),
527 None => f(&T::default()),
528 }
529}
530
531#[doc(hidden)]
532pub unsafe fn remove_all_items() {
538 clear_storage();
539 System::remove_current();
540}
541
542fn clear_storage() {
547 let _ = STORAGE.try_with(|cell| {
548 loop {
549 let mut items = cell.borrow_mut();
550 let Some(key) = items.keys().next().copied() else {
551 break;
552 };
553 let item = items.remove(&key);
554 drop(items);
555 drop(item);
556 }
557 });
558}
559
560#[cfg(test)]
561#[path = "../tests/unit/arbiter.rs"]
562mod tests;