ntex_rt/
arbiter.rs

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
28/// Arbiters provide an asynchronous execution environment for actors, functions
29/// and futures.
30///
31/// When an Arbiter is created, it spawns a new OS thread, and
32/// hosts an event loop. Some Arbiter functions execute on the current thread.
33pub 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    /// Returns the current thread's arbiter's address. If no Arbiter is present, then this
75    /// function will panic!
76    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    /// Stop arbiter from continuing it's event loop.
84    pub fn stop(&self) {
85        let _ = self.sender.try_send(ArbiterCommand::Stop);
86    }
87
88    /// Spawn new thread and run event loop in spawned thread.
89    /// Returns address of newly created arbiter.
90    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                    // start arbiter controller
117                    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                    // register arbiter
124                    let _ = System::current()
125                        .sys()
126                        .try_send(SystemCommand::RegisterArbiter(id, arb));
127
128                    // run loop
129                    let _ = stop_rx.await;
130                });
131
132                // unregister arbiter
133                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    /// Send a future to the Arbiter's thread, and spawn it.
148    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    /// Send a function to the Arbiter's thread. This function will be executed asynchronously.
158    /// A future is created, and when resolved will contain the result of the function sent
159    /// to the Arbiters thread.
160    pub fn exec<F, R>(&self, f: F) -> impl Future<Output = Result<R, oneshot::RecvError>> + Send + 'static
161    where
162        F: FnOnce() -> R + Send + 'static,
163        R: Send + 'static,
164    {
165        let (tx, rx) = oneshot::channel();
166        let _ = self
167            .sender
168            .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
169                let _ = tx.send(f());
170            })));
171        rx
172    }
173
174    /// Send a function to the Arbiter's thread, and execute it. Any result from the function
175    /// is discarded.
176    pub fn exec_fn<F>(&self, f: F)
177    where
178        F: FnOnce() + Send + 'static,
179    {
180        let _ = self
181            .sender
182            .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
183                f();
184            })));
185    }
186
187    /// Set item to current arbiter's storage
188    pub fn set_item<T: 'static>(item: T) {
189        STORAGE
190            .with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
191    }
192
193    /// Check if arbiter storage contains item
194    pub fn contains_item<T: 'static>() -> bool {
195        STORAGE.with(move |cell| cell.borrow().get(&TypeId::of::<T>()).is_some())
196    }
197
198    /// Get a reference to a type previously inserted on this arbiter's storage.
199    ///
200    /// Panics is item is not inserted
201    pub fn get_item<T: 'static, F, R>(mut f: F) -> R
202    where
203        F: FnMut(&T) -> R,
204    {
205        STORAGE.with(move |cell| {
206            let st = cell.borrow();
207            let item = st
208                .get(&TypeId::of::<T>())
209                .and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
210                .unwrap();
211            f(item)
212        })
213    }
214
215    /// Get a mutable reference to a type previously inserted on this arbiter's storage.
216    ///
217    /// Panics is item is not inserted
218    pub fn get_mut_item<T: 'static, F, R>(mut f: F) -> R
219    where
220        F: FnMut(&mut T) -> R,
221    {
222        STORAGE.with(move |cell| {
223            let mut st = cell.borrow_mut();
224            let item = st
225                .get_mut(&TypeId::of::<T>())
226                .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
227                .unwrap();
228            f(item)
229        })
230    }
231
232    fn with_sender(sender: Sender<ArbiterCommand>) -> Self {
233        Self {
234            sender,
235            thread_handle: None,
236        }
237    }
238
239    /// Wait for the event loop to stop by joining the underlying thread (if have Some).
240    pub fn join(&mut self) -> thread::Result<()> {
241        if let Some(thread_handle) = self.thread_handle.take() {
242            thread_handle.join()
243        } else {
244            Ok(())
245        }
246    }
247}
248
249pub(crate) struct ArbiterController {
250    stop: Option<oneshot::Sender<i32>>,
251    rx: ArbiterCommandRx,
252}
253
254impl Drop for ArbiterController {
255    fn drop(&mut self) {
256        if thread::panicking() {
257            if System::current().stop_on_panic() {
258                eprintln!("Panic in Arbiter thread, shutting down system.");
259                System::current().stop_with_code(1)
260            } else {
261                eprintln!("Panic in Arbiter thread.");
262            }
263        }
264    }
265}
266
267impl Future for ArbiterController {
268    type Output = ();
269
270    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
271        loop {
272            match Pin::new(&mut self.rx).poll_next(cx) {
273                Poll::Ready(None) => return Poll::Ready(()),
274                Poll::Ready(Some(item)) => match item {
275                    ArbiterCommand::Stop => {
276                        if let Some(stop) = self.stop.take() {
277                            let _ = stop.send(0);
278                        };
279                        return Poll::Ready(());
280                    }
281                    ArbiterCommand::Execute(fut) => {
282                        let _ = crate::spawn(fut);
283                    }
284                    ArbiterCommand::ExecuteFn(f) => {
285                        f.call_box();
286                    }
287                },
288                Poll::Pending => return Poll::Pending,
289            }
290        }
291    }
292}
293
294#[derive(Debug)]
295pub(super) enum SystemCommand {
296    Exit(i32),
297    RegisterArbiter(usize, Arbiter),
298    UnregisterArbiter(usize),
299}
300
301pub(super) struct SystemArbiter {
302    stop: Option<oneshot::Sender<i32>>,
303    commands: ServerCommandRx,
304    arbiters: HashMap<usize, Arbiter>,
305}
306
307impl SystemArbiter {
308    pub(super) fn new(
309        stop: oneshot::Sender<i32>,
310        commands: Receiver<SystemCommand>,
311    ) -> Self {
312        SystemArbiter {
313            commands: Box::pin(commands),
314            stop: Some(stop),
315            arbiters: HashMap::new(),
316        }
317    }
318}
319
320impl fmt::Debug for SystemArbiter {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        f.debug_struct("SystemArbiter")
323            .field("arbiters", &self.arbiters)
324            .finish()
325    }
326}
327
328impl Future for SystemArbiter {
329    type Output = ();
330
331    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
332        loop {
333            let cmd = ready!(Pin::new(&mut self.commands).poll_next(cx));
334            log::debug!("Received system command: {:?}", cmd);
335            match cmd {
336                None => {
337                    log::debug!("System stopped");
338                    return Poll::Ready(());
339                }
340                Some(cmd) => match cmd {
341                    SystemCommand::Exit(code) => {
342                        log::debug!("Stopping system with {} code", code);
343
344                        // stop arbiters
345                        for arb in self.arbiters.values() {
346                            arb.stop();
347                        }
348                        // stop event loop
349                        if let Some(stop) = self.stop.take() {
350                            let _ = stop.send(code);
351                        }
352                    }
353                    SystemCommand::RegisterArbiter(name, hnd) => {
354                        self.arbiters.insert(name, hnd);
355                    }
356                    SystemCommand::UnregisterArbiter(name) => {
357                        self.arbiters.remove(&name);
358                    }
359                },
360            }
361        }
362    }
363}
364
365pub(super) trait FnExec: Send + 'static {
366    fn call_box(self: Box<Self>);
367}
368
369impl<F> FnExec for F
370where
371    F: FnOnce() + Send + 'static,
372{
373    #[allow(clippy::boxed_local)]
374    fn call_box(self: Box<Self>) {
375        (*self)()
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    #[test]
384    fn test_arbiter_local_storage() {
385        let _s = System::new("test");
386        Arbiter::set_item("test");
387        assert!(Arbiter::get_item::<&'static str, _, _>(|s| *s == "test"));
388        assert!(Arbiter::get_mut_item::<&'static str, _, _>(|s| *s == "test"));
389        assert!(Arbiter::contains_item::<&'static str>());
390        assert!(format!("{:?}", Arbiter::current()).contains("Arbiter"));
391    }
392}