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, pin::Pin, thread};
4
5use async_channel::{Receiver, Sender, unbounded};
6use parking_lot::Mutex;
7
8use crate::{Handle, HashMap, Id, System};
9
10thread_local!(
11 static ADDR: RefCell<Option<Arbiter>> = const { RefCell::new(None) };
12 static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> =
13 RefCell::new(HashMap::default());
14);
15
16pub(super) static COUNT: AtomicUsize = AtomicUsize::new(99);
17
18pub(super) enum ArbiterCommand {
19 Stop,
20 #[allow(dead_code)]
21 Execute(Pin<Box<dyn Future<Output = ()> + Send>>),
22}
23
24pub struct Arbiter(pub(crate) Arc<ArbiterInner>);
30
31pub(crate) struct ArbiterInner {
32 id: usize,
33 name: Arc<String>,
34 sys_id: usize,
35 hnd: Option<Handle>,
36 pub(crate) sender: Sender<ArbiterCommand>,
37 thread_handle: Mutex<Option<thread::JoinHandle<()>>>,
38 running: AtomicBool,
39 #[cfg(target_os = "linux")]
40 tid: i32,
41}
42
43impl fmt::Debug for Arbiter {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 write!(f, "Arbiter({:?})", self.0.name.as_ref())
46 }
47}
48
49impl Clone for Arbiter {
50 fn clone(&self) -> Self {
51 Self(self.0.clone())
52 }
53}
54
55impl Default for Arbiter {
56 fn default() -> Self {
57 Self::new()
58 }
59}
60
61impl Arbiter {
62 #[allow(clippy::borrowed_box)]
63 pub(super) fn new_system(id: usize, name: String) -> (Self, ArbiterController) {
64 let (tx, rx) = unbounded();
65
66 let aid = COUNT.fetch_add(1, Ordering::Relaxed);
67 let arb = Arbiter::with_sender(id, aid, Arc::new(name), tx);
68 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
69 STORAGE.with(|cell| cell.borrow_mut().clear());
70
71 (
72 arb,
73 ArbiterController {
74 rx,
75 sys: None,
76 stop: None,
77 },
78 )
79 }
80
81 pub fn current() -> Arbiter {
87 ADDR.with(|cell| match *cell.borrow() {
88 Some(ref addr) => addr.clone(),
89 None => panic!("Arbiter is not running"),
90 })
91 }
92
93 pub fn stop(&self) {
95 let _ = self.0.sender.try_send(ArbiterCommand::Stop);
96 }
97
98 pub fn new() -> Arbiter {
101 let id = COUNT.load(Ordering::Relaxed) + 1;
102 Arbiter::with_name(format!("{}:arb:{}", System::current().name(), id))
103 }
104
105 pub fn with_name(name: String) -> Arbiter {
109 let id = COUNT.fetch_add(1, Ordering::Relaxed);
110 let sys = System::current();
111 let name2 = Arc::new(name.clone());
112 let config = sys.config();
113 let (arb_tx, arb_rx) = unbounded();
114
115 let builder = if sys.config().stack_size > 0 {
116 thread::Builder::new()
117 .name(name)
118 .stack_size(sys.config().stack_size)
119 } else {
120 thread::Builder::new().name(name)
121 };
122
123 let name = name2.clone();
124 let sys_id = sys.id();
125 let (arb_hnd_tx, arb_hnd_rx) = oneshot::channel();
126
127 let handle = builder
128 .spawn(move || {
129 let name3 = name2.clone();
130 log::info!("Starting {name3:?} arbiter");
131
132 let sys2 = sys.clone();
133 let (stop, stop_rx) = oneshot::channel();
134 STORAGE.with(|cell| cell.borrow_mut().clear());
135
136 crate::driver::block_on(config.runner.as_ref(), async move {
137 let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx);
138 sys.register_arbiter(arb.clone());
139 arb_hnd_tx
140 .send(arb.clone())
141 .expect("Controller thread has gone");
142
143 crate::spawn(
145 ArbiterController {
146 sys: None,
147 stop: Some(stop),
148 rx: arb_rx,
149 }
150 .run(sys),
151 );
152 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
153
154 let _ = stop_rx.await;
156
157 arb.0.running.store(false, Ordering::Relaxed);
159 });
160
161 sys2.unregister_arbiter(Id(id));
163
164 remove_all_items();
165
166 log::info!("Arbiter {name3:?} has been stopped");
167 })
168 .unwrap_or_else(|err| {
169 panic!("Cannot spawn an arbiter's thread {:?}: {:?}", &name, err)
170 });
171
172 let arb = arb_hnd_rx.recv().expect("Could not start new arbiter");
173 *arb.0.thread_handle.lock() = Some(handle);
174 arb
175 }
176
177 fn with_sender(
178 sys_id: usize,
179 id: usize,
180 name: Arc<String>,
181 sender: Sender<ArbiterCommand>,
182 ) -> Self {
183 #[cfg(feature = "tokio")]
184 let hnd = { Handle::new(sender.clone()) };
185
186 #[cfg(feature = "compio")]
187 let hnd = { Handle::new(sender.clone()) };
188
189 #[cfg(all(not(feature = "compio"), not(feature = "tokio")))]
190 let hnd = { Handle::current() };
191
192 Self(Arc::new(ArbiterInner {
193 id,
194 sys_id,
195 name,
196 sender,
197 hnd: Some(hnd),
198 thread_handle: Mutex::new(None),
199 running: AtomicBool::new(true),
200 #[cfg(target_os = "linux")]
201 #[allow(clippy::cast_possible_truncation)]
202 tid: unsafe { libc::syscall(libc::SYS_gettid) } as i32,
203 }))
204 }
205
206 pub fn id(&self) -> Id {
208 Id(self.0.id)
209 }
210
211 #[cfg(target_os = "linux")]
212 pub(crate) fn tid(&self) -> i32 {
214 self.0.tid
215 }
216
217 pub fn name(&self) -> &str {
219 self.0.name.as_ref()
220 }
221
222 #[inline]
223 pub fn handle(&self) -> &Handle {
225 self.0.hnd.as_ref().unwrap()
226 }
227
228 #[inline]
229 pub fn is_running(&self) -> bool {
231 self.0.running.load(Ordering::Relaxed)
232 }
233
234 pub fn get_value<T, F>(f: F) -> T
236 where
237 T: Clone + 'static,
238 F: FnOnce() -> T,
239 {
240 STORAGE.with(move |cell| {
241 let mut st = cell.borrow_mut();
242 if let Some(boxed) = st.get(&TypeId::of::<T>())
243 && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
244 {
245 return val.clone();
246 }
247 let val = f();
248 st.insert(TypeId::of::<T>(), Box::new(val.clone()));
249 val
250 })
251 }
252
253 pub fn join(&mut self) -> thread::Result<()> {
255 if let Some(thread_handle) = self.0.thread_handle.lock().take() {
256 thread_handle.join()
257 } else {
258 Ok(())
259 }
260 }
261}
262
263impl Eq for Arbiter {}
264
265impl PartialEq for Arbiter {
266 fn eq(&self, other: &Self) -> bool {
267 self.0.id == other.0.id && self.0.sys_id == other.0.sys_id
268 }
269}
270
271pub(crate) struct ArbiterController {
272 sys: Option<System>,
273 rx: Receiver<ArbiterCommand>,
274 stop: Option<oneshot::Sender<i32>>,
275}
276
277impl Drop for ArbiterController {
278 fn drop(&mut self) {
279 if thread::panicking() {
280 if let Some(sys) = self.sys.take()
281 && sys.stop_on_panic()
282 {
283 eprintln!("Panic in Arbiter thread, shutting down system.");
284 sys.stop_with_code(1);
285 } else {
286 eprintln!("Panic in Arbiter thread.");
287 }
288 }
289 }
290}
291
292impl ArbiterController {
293 pub(super) async fn run(mut self, sys: System) {
294 self.sys = Some(sys);
295 loop {
296 match self.rx.recv().await {
297 Ok(ArbiterCommand::Stop) => {
298 if let Some(stop) = self.stop.take() {
299 let _ = stop.send(0);
300 }
301 }
302 Ok(ArbiterCommand::Execute(fut)) => {
303 crate::spawn(fut);
304 }
305 Err(_) => break,
306 }
307 }
308 }
309}
310
311pub fn set_item<T: 'static>(item: T) {
313 STORAGE.with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
314}
315
316pub fn get_item<T: Clone + 'static>() -> Option<T> {
318 STORAGE.with(move |cell| {
319 cell.borrow()
320 .get(&TypeId::of::<T>())
321 .and_then(|boxed| boxed.downcast_ref())
322 .cloned()
323 })
324}
325
326pub fn with_item<T: Default + 'static, F, R>(f: F) -> R
328where
329 F: FnOnce(&T) -> R,
330{
331 STORAGE.with(move |cell| {
332 let mut st = cell.borrow_mut();
333 if let Some(boxed) = st.get(&TypeId::of::<T>()) {
334 f(boxed.downcast_ref().unwrap())
335 } else {
336 let item = T::default();
337 let result = f(&item);
338 st.insert(TypeId::of::<T>(), Box::new(item));
339 result
340 }
341 })
342}
343
344pub fn remove_all_items() {
346 STORAGE.with(move |cell| cell.borrow_mut().clear());
347 System::remove_current();
348}