ntex_rt/
arbiter.rs

1#![allow(clippy::let_underscore_future)]
2use std::any::{Any, TypeId};
3use std::sync::{atomic::AtomicUsize, atomic::Ordering, Arc};
4use std::{cell::RefCell, collections::HashMap, fmt, future::Future, pin::Pin, thread};
5
6use async_channel::{unbounded, Receiver, Sender};
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
23/// Arbiters provide an asynchronous execution environment for actors, functions
24/// and futures.
25///
26/// When an Arbiter is created, it spawns a new OS thread, and
27/// hosts an event loop. Some Arbiter functions execute on the current thread.
28pub 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    /// Returns the current thread's arbiter's address. If no Arbiter is present, then this
67    /// function will panic!
68    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    /// Stop arbiter from continuing it's event loop.
76    pub fn stop(&self) {
77        let _ = self.sender.try_send(ArbiterCommand::Stop);
78    }
79
80    /// Spawn new thread and run runtime in spawned thread.
81    /// Returns address of newly created arbiter.
82    pub fn new() -> Arbiter {
83        let name = format!("worker:{}", COUNT.load(Ordering::Relaxed) + 1);
84        Arbiter::with_name(name)
85    }
86
87    /// Spawn new thread and run runtime in spawned thread.
88    /// Returns address of newly created arbiter.
89    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                let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx);
111
112                let (stop, stop_rx) = oneshot::channel();
113                STORAGE.with(|cell| cell.borrow_mut().clear());
114
115                System::set_current(sys);
116
117                config.block_on(async move {
118                    // start arbiter controller
119                    let _ = crate::spawn(
120                        ArbiterController {
121                            stop: Some(stop),
122                            rx: arb_rx,
123                        }
124                        .run(),
125                    );
126                    ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
127
128                    // register arbiter
129                    let _ = System::current()
130                        .sys()
131                        .try_send(SystemCommand::RegisterArbiter(Id(id), arb));
132
133                    // run loop
134                    let _ = stop_rx.await;
135                });
136
137                // unregister arbiter
138                let _ = System::current()
139                    .sys()
140                    .try_send(SystemCommand::UnregisterArbiter(Id(id)));
141            })
142            .unwrap_or_else(|err| {
143                panic!("Cannot spawn an arbiter's thread {:?}: {:?}", &name, err)
144            });
145
146        Arbiter {
147            id,
148            name,
149            sys_id: sys_id.0,
150            sender: arb_tx2,
151            thread_handle: Some(handle),
152        }
153    }
154
155    fn with_sender(
156        sys_id: usize,
157        id: usize,
158        name: Arc<String>,
159        sender: Sender<ArbiterCommand>,
160    ) -> Self {
161        Self {
162            id,
163            sys_id,
164            name,
165            sender,
166            thread_handle: None,
167        }
168    }
169
170    /// Id of the arbiter
171    pub fn id(&self) -> Id {
172        Id(self.id)
173    }
174
175    /// Name of the arbiter
176    pub fn name(&self) -> &str {
177        self.name.as_ref()
178    }
179
180    /// Send a future to the Arbiter's thread, and spawn it.
181    pub fn spawn<F>(&self, future: F)
182    where
183        F: Future<Output = ()> + Send + 'static,
184    {
185        let _ = self
186            .sender
187            .try_send(ArbiterCommand::Execute(Box::pin(future)));
188    }
189
190    #[rustfmt::skip]
191    /// Send a function to the Arbiter's thread and spawns it's resulting future.
192    /// This can be used to spawn non-send futures on the arbiter thread.
193    pub fn spawn_with<F, R, O>(
194        &self,
195        f: F
196    ) -> impl Future<Output = Result<O, oneshot::RecvError>> + Send + 'static
197    where
198        F: FnOnce() -> R + Send + 'static,
199        R: Future<Output = O> + 'static,
200        O: Send + 'static,
201    {
202        let (tx, rx) = oneshot::channel();
203        let _ = self
204            .sender
205            .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
206                crate::spawn(async move {
207                    let _ = tx.send(f().await);
208                });
209            })));
210        rx
211    }
212
213    #[rustfmt::skip]
214    /// Send a function to the Arbiter's thread. This function will be executed asynchronously.
215    /// A future is created, and when resolved will contain the result of the function sent
216    /// to the Arbiters thread.
217    pub fn exec<F, R>(&self, f: F) -> impl Future<Output = Result<R, oneshot::RecvError>> + Send + 'static
218    where
219        F: FnOnce() -> R + Send + 'static,
220        R: Send + 'static,
221    {
222        let (tx, rx) = oneshot::channel();
223        let _ = self
224            .sender
225            .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
226                let _ = tx.send(f());
227            })));
228        rx
229    }
230
231    /// Send a function to the Arbiter's thread, and execute it. Any result from the function
232    /// is discarded.
233    pub fn exec_fn<F>(&self, f: F)
234    where
235        F: FnOnce() + Send + 'static,
236    {
237        let _ = self
238            .sender
239            .try_send(ArbiterCommand::ExecuteFn(Box::new(move || {
240                f();
241            })));
242    }
243
244    /// Set item to current arbiter's storage
245    pub fn set_item<T: 'static>(item: T) {
246        STORAGE
247            .with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
248    }
249
250    /// Check if arbiter storage contains item
251    pub fn contains_item<T: 'static>() -> bool {
252        STORAGE.with(move |cell| cell.borrow().get(&TypeId::of::<T>()).is_some())
253    }
254
255    /// Get a reference to a type previously inserted on this arbiter's storage.
256    ///
257    /// Panics is item is not inserted
258    pub fn get_item<T: 'static, F, R>(mut f: F) -> R
259    where
260        F: FnMut(&T) -> R,
261    {
262        STORAGE.with(move |cell| {
263            let st = cell.borrow();
264            let item = st
265                .get(&TypeId::of::<T>())
266                .and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
267                .unwrap();
268            f(item)
269        })
270    }
271
272    /// Get a mutable reference to a type previously inserted on this arbiter's storage.
273    ///
274    /// Panics is item is not inserted
275    pub fn get_mut_item<T: 'static, F, R>(mut f: F) -> R
276    where
277        F: FnMut(&mut T) -> R,
278    {
279        STORAGE.with(move |cell| {
280            let mut st = cell.borrow_mut();
281            let item = st
282                .get_mut(&TypeId::of::<T>())
283                .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
284                .unwrap();
285            f(item)
286        })
287    }
288
289    /// Get a type previously inserted to this runtime or create new one.
290    pub fn get_value<T, F>(f: F) -> T
291    where
292        T: Clone + 'static,
293        F: FnOnce() -> T,
294    {
295        STORAGE.with(move |cell| {
296            let mut st = cell.borrow_mut();
297            if let Some(boxed) = st.get(&TypeId::of::<T>()) {
298                if let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>() {
299                    return val.clone();
300                }
301            }
302            let val = f();
303            st.insert(TypeId::of::<T>(), Box::new(val.clone()));
304            val
305        })
306    }
307
308    /// Wait for the event loop to stop by joining the underlying thread (if have Some).
309    pub fn join(&mut self) -> thread::Result<()> {
310        if let Some(thread_handle) = self.thread_handle.take() {
311            thread_handle.join()
312        } else {
313            Ok(())
314        }
315    }
316}
317
318impl Eq for Arbiter {}
319
320impl PartialEq for Arbiter {
321    fn eq(&self, other: &Self) -> bool {
322        self.id == other.id && self.sys_id == other.sys_id
323    }
324}
325
326pub(crate) struct ArbiterController {
327    stop: Option<oneshot::Sender<i32>>,
328    rx: Receiver<ArbiterCommand>,
329}
330
331impl Drop for ArbiterController {
332    fn drop(&mut self) {
333        if thread::panicking() {
334            if System::current().stop_on_panic() {
335                eprintln!("Panic in Arbiter thread, shutting down system.");
336                System::current().stop_with_code(1)
337            } else {
338                eprintln!("Panic in Arbiter thread.");
339            }
340        }
341    }
342}
343
344impl ArbiterController {
345    pub(super) async fn run(mut self) {
346        loop {
347            match self.rx.recv().await {
348                Ok(ArbiterCommand::Stop) => {
349                    if let Some(stop) = self.stop.take() {
350                        let _ = stop.send(0);
351                    };
352                    break;
353                }
354                Ok(ArbiterCommand::Execute(fut)) => {
355                    let _ = crate::spawn(fut);
356                }
357                Ok(ArbiterCommand::ExecuteFn(f)) => {
358                    f.call_box();
359                }
360                Err(_) => break,
361            }
362        }
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[test]
371    fn test_arbiter_local_storage() {
372        let _s = System::new("test");
373        Arbiter::set_item("test");
374        assert!(Arbiter::get_item::<&'static str, _, _>(|s| *s == "test"));
375        assert!(Arbiter::get_mut_item::<&'static str, _, _>(|s| *s == "test"));
376        assert!(Arbiter::contains_item::<&'static str>());
377        assert!(Arbiter::get_value(|| 64u64) == 64);
378        assert!(format!("{:?}", Arbiter::current()).contains("Arbiter"));
379    }
380}