1#![allow(clippy::let_underscore_future)]
2use std::any::{Any, TypeId};
3use std::sync::atomic::{AtomicUsize, Ordering};
4use std::task::{ready, Context, Poll};
5use std::{cell::RefCell, collections::HashMap, fmt, future::Future, pin::Pin, thread};
6
7use async_channel::{unbounded, Receiver, Sender};
8use futures_core::stream::Stream;
9
10use crate::system::System;
11
12thread_local!(
13 static ADDR: RefCell<Option<Arbiter>> = const { RefCell::new(None) };
14 static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> = RefCell::new(HashMap::new());
15);
16
17type ServerCommandRx = Pin<Box<dyn Stream<Item = SystemCommand>>>;
18type ArbiterCommandRx = Pin<Box<dyn Stream<Item = ArbiterCommand>>>;
19
20pub(super) static COUNT: AtomicUsize = AtomicUsize::new(0);
21
22pub(super) enum ArbiterCommand {
23 Stop,
24 Execute(Pin<Box<dyn Future<Output = ()> + Send>>),
25 ExecuteFn(Box<dyn FnExec>),
26}
27
28pub struct Arbiter {
34 sender: Sender<ArbiterCommand>,
35 thread_handle: Option<thread::JoinHandle<()>>,
36}
37
38impl fmt::Debug for Arbiter {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 write!(f, "Arbiter")
41 }
42}
43
44impl Default for Arbiter {
45 fn default() -> Arbiter {
46 Arbiter::new()
47 }
48}
49
50impl Clone for Arbiter {
51 fn clone(&self) -> Self {
52 Self::with_sender(self.sender.clone())
53 }
54}
55
56impl Arbiter {
57 #[allow(clippy::borrowed_box)]
58 pub(super) fn new_system() -> (Self, ArbiterController) {
59 let (tx, rx) = unbounded();
60
61 let arb = Arbiter::with_sender(tx);
62 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
63 STORAGE.with(|cell| cell.borrow_mut().clear());
64
65 (
66 arb,
67 ArbiterController {
68 stop: None,
69 rx: Box::pin(rx),
70 },
71 )
72 }
73
74 pub fn current() -> Arbiter {
77 ADDR.with(|cell| match *cell.borrow() {
78 Some(ref addr) => addr.clone(),
79 None => panic!("Arbiter is not running"),
80 })
81 }
82
83 pub fn stop(&self) {
85 let _ = self.sender.try_send(ArbiterCommand::Stop);
86 }
87
88 pub fn new() -> Arbiter {
91 let id = COUNT.fetch_add(1, Ordering::Relaxed);
92 let name = format!("ntex-rt:worker:{}", id);
93 let sys = System::current();
94 let config = sys.config();
95 let (arb_tx, arb_rx) = unbounded();
96 let arb_tx2 = arb_tx.clone();
97
98 let builder = if sys.config().stack_size > 0 {
99 thread::Builder::new()
100 .name(name.clone())
101 .stack_size(sys.config().stack_size)
102 } else {
103 thread::Builder::new().name(name.clone())
104 };
105
106 let handle = builder
107 .spawn(move || {
108 let arb = Arbiter::with_sender(arb_tx);
109
110 let (stop, stop_rx) = oneshot::channel();
111 STORAGE.with(|cell| cell.borrow_mut().clear());
112
113 System::set_current(sys);
114
115 config.block_on(async move {
116 let _ = crate::spawn(ArbiterController {
118 stop: Some(stop),
119 rx: Box::pin(arb_rx),
120 });
121 ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
122
123 let _ = System::current()
125 .sys()
126 .try_send(SystemCommand::RegisterArbiter(id, arb));
127
128 let _ = stop_rx.await;
130 });
131
132 let _ = System::current()
134 .sys()
135 .try_send(SystemCommand::UnregisterArbiter(id));
136 })
137 .unwrap_or_else(|err| {
138 panic!("Cannot spawn an arbiter's thread {:?}: {:?}", &name, err)
139 });
140
141 Arbiter {
142 sender: arb_tx2,
143 thread_handle: Some(handle),
144 }
145 }
146
147 pub fn spawn<F>(&self, future: F)
149 where
150 F: Future<Output = ()> + Send + 'static,
151 {
152 let _ = self
153 .sender
154 .try_send(ArbiterCommand::Execute(Box::pin(future)));
155 }
156
157 pub fn spawn_with<F, R, O>(
160 &self,
161 f: F,
162 ) -> impl Future<Output = Result<O, oneshot::RecvError>> + Send + 'static
163 where
164 F: FnOnce() -> R + Send + 'static,
165 R: Future<Output = O> + 'static,
166 O: Send + 'static,
167 {
168 let (tx, rx) = oneshot::channel();
169 let _ = self
170 .sender
171 .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
172 let fut = f();
173 let fut = Box::pin(async {
174 let _ = tx.send(fut.await);
175 });
176 crate::spawn(fut);
177 })));
178 rx
179 }
180
181 #[rustfmt::skip]
182 pub fn exec<F, R>(&self, f: F) -> impl Future<Output = Result<R, oneshot::RecvError>> + Send + 'static
186 where
187 F: FnOnce() -> R + Send + 'static,
188 R: Send + 'static,
189 {
190 let (tx, rx) = oneshot::channel();
191 let _ = self
192 .sender
193 .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
194 let _ = tx.send(f());
195 })));
196 rx
197 }
198
199 pub fn exec_fn<F>(&self, f: F)
202 where
203 F: FnOnce() + Send + 'static,
204 {
205 let _ = self
206 .sender
207 .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
208 f();
209 })));
210 }
211
212 pub fn set_item<T: 'static>(item: T) {
214 STORAGE
215 .with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
216 }
217
218 pub fn contains_item<T: 'static>() -> bool {
220 STORAGE.with(move |cell| cell.borrow().get(&TypeId::of::<T>()).is_some())
221 }
222
223 pub fn get_item<T: 'static, F, R>(mut f: F) -> R
227 where
228 F: FnMut(&T) -> R,
229 {
230 STORAGE.with(move |cell| {
231 let st = cell.borrow();
232 let item = st
233 .get(&TypeId::of::<T>())
234 .and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
235 .unwrap();
236 f(item)
237 })
238 }
239
240 pub fn get_mut_item<T: 'static, F, R>(mut f: F) -> R
244 where
245 F: FnMut(&mut T) -> R,
246 {
247 STORAGE.with(move |cell| {
248 let mut st = cell.borrow_mut();
249 let item = st
250 .get_mut(&TypeId::of::<T>())
251 .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
252 .unwrap();
253 f(item)
254 })
255 }
256
257 fn with_sender(sender: Sender<ArbiterCommand>) -> Self {
258 Self {
259 sender,
260 thread_handle: None,
261 }
262 }
263
264 pub fn join(&mut self) -> thread::Result<()> {
266 if let Some(thread_handle) = self.thread_handle.take() {
267 thread_handle.join()
268 } else {
269 Ok(())
270 }
271 }
272}
273
274pub(crate) struct ArbiterController {
275 stop: Option<oneshot::Sender<i32>>,
276 rx: ArbiterCommandRx,
277}
278
279impl Drop for ArbiterController {
280 fn drop(&mut self) {
281 if thread::panicking() {
282 if System::current().stop_on_panic() {
283 eprintln!("Panic in Arbiter thread, shutting down system.");
284 System::current().stop_with_code(1)
285 } else {
286 eprintln!("Panic in Arbiter thread.");
287 }
288 }
289 }
290}
291
292impl Future for ArbiterController {
293 type Output = ();
294
295 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
296 loop {
297 match Pin::new(&mut self.rx).poll_next(cx) {
298 Poll::Ready(None) => return Poll::Ready(()),
299 Poll::Ready(Some(item)) => match item {
300 ArbiterCommand::Stop => {
301 if let Some(stop) = self.stop.take() {
302 let _ = stop.send(0);
303 };
304 return Poll::Ready(());
305 }
306 ArbiterCommand::Execute(fut) => {
307 let _ = crate::spawn(fut);
308 }
309 ArbiterCommand::ExecuteFn(f) => {
310 f.call_box();
311 }
312 },
313 Poll::Pending => return Poll::Pending,
314 }
315 }
316 }
317}
318
319#[derive(Debug)]
320pub(super) enum SystemCommand {
321 Exit(i32),
322 RegisterArbiter(usize, Arbiter),
323 UnregisterArbiter(usize),
324}
325
326pub(super) struct SystemArbiter {
327 stop: Option<oneshot::Sender<i32>>,
328 commands: ServerCommandRx,
329 arbiters: HashMap<usize, Arbiter>,
330}
331
332impl SystemArbiter {
333 pub(super) fn new(
334 stop: oneshot::Sender<i32>,
335 commands: Receiver<SystemCommand>,
336 ) -> Self {
337 SystemArbiter {
338 commands: Box::pin(commands),
339 stop: Some(stop),
340 arbiters: HashMap::new(),
341 }
342 }
343}
344
345impl fmt::Debug for SystemArbiter {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 f.debug_struct("SystemArbiter")
348 .field("arbiters", &self.arbiters)
349 .finish()
350 }
351}
352
353impl Future for SystemArbiter {
354 type Output = ();
355
356 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
357 loop {
358 let cmd = ready!(Pin::new(&mut self.commands).poll_next(cx));
359 log::debug!("Received system command: {:?}", cmd);
360 match cmd {
361 None => {
362 log::debug!("System stopped");
363 return Poll::Ready(());
364 }
365 Some(cmd) => match cmd {
366 SystemCommand::Exit(code) => {
367 log::debug!("Stopping system with {} code", code);
368
369 for arb in self.arbiters.values() {
371 arb.stop();
372 }
373 if let Some(stop) = self.stop.take() {
375 let _ = stop.send(code);
376 }
377 }
378 SystemCommand::RegisterArbiter(name, hnd) => {
379 self.arbiters.insert(name, hnd);
380 }
381 SystemCommand::UnregisterArbiter(name) => {
382 self.arbiters.remove(&name);
383 }
384 },
385 }
386 }
387 }
388}
389
390pub(super) trait FnExec: Send + 'static {
391 fn call_box(self: Box<Self>);
392}
393
394impl<F> FnExec for F
395where
396 F: FnOnce() + Send + 'static,
397{
398 #[allow(clippy::boxed_local)]
399 fn call_box(self: Box<Self>) {
400 (*self)()
401 }
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 #[test]
409 fn test_arbiter_local_storage() {
410 let _s = System::new("test");
411 Arbiter::set_item("test");
412 assert!(Arbiter::get_item::<&'static str, _, _>(|s| *s == "test"));
413 assert!(Arbiter::get_mut_item::<&'static str, _, _>(|s| *s == "test"));
414 assert!(Arbiter::contains_item::<&'static str>());
415 assert!(format!("{:?}", Arbiter::current()).contains("Arbiter"));
416 }
417}