Skip to main content

ntex_rt/
arbiter.rs

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
24/// Arbiters provide an asynchronous execution environment for actors, functions
25/// and futures.
26///
27/// When an Arbiter is created, it spawns a new OS thread, and
28/// hosts an event loop. Some Arbiter functions execute on the current thread.
29pub 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    /// Returns the current thread's arbiter's address
82    ///
83    /// # Panics
84    ///
85    /// Panics if Arbiter is not running
86    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    /// Stop arbiter from continuing it's event loop.
94    pub fn stop(&self) {
95        let _ = self.0.sender.try_send(ArbiterCommand::Stop);
96    }
97
98    /// Spawn new thread and run runtime in spawned thread.
99    /// Returns address of newly created arbiter.
100    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    /// Spawn new thread and run runtime in spawned thread
106    ///
107    /// Returns address of newly created arbiter.
108    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                log::info!("Starting {name2:?} arbiter");
130
131                let sys2 = sys.clone();
132                let (stop, stop_rx) = oneshot::channel();
133                STORAGE.with(|cell| cell.borrow_mut().clear());
134
135                crate::driver::block_on(config.runner.as_ref(), async move {
136                    let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx);
137                    sys.register_arbiter(arb.clone());
138                    arb_hnd_tx
139                        .send(arb.clone())
140                        .expect("Controller thread has gone");
141
142                    // start arbiter controller
143                    crate::spawn(
144                        ArbiterController {
145                            sys: None,
146                            stop: Some(stop),
147                            rx: arb_rx,
148                        }
149                        .run(sys),
150                    );
151                    ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
152
153                    // run loop
154                    let _ = stop_rx.await;
155
156                    // mark as not running
157                    arb.0.running.store(false, Ordering::Relaxed);
158                });
159
160                // unregister arbiter
161                sys2.unregister_arbiter(Id(id));
162
163                remove_all_items();
164            })
165            .unwrap_or_else(|err| {
166                panic!("Cannot spawn an arbiter's thread {:?}: {:?}", &name, err)
167            });
168
169        let arb = arb_hnd_rx.recv().expect("Could not start new arbiter");
170        *arb.0.thread_handle.lock() = Some(handle);
171        arb
172    }
173
174    fn with_sender(
175        sys_id: usize,
176        id: usize,
177        name: Arc<String>,
178        sender: Sender<ArbiterCommand>,
179    ) -> Self {
180        #[cfg(feature = "tokio")]
181        let hnd = { Handle::new(sender.clone()) };
182
183        #[cfg(feature = "compio")]
184        let hnd = { Handle::new(sender.clone()) };
185
186        #[cfg(all(not(feature = "compio"), not(feature = "tokio")))]
187        let hnd = { Handle::current() };
188
189        Self(Arc::new(ArbiterInner {
190            id,
191            sys_id,
192            name,
193            sender,
194            hnd: Some(hnd),
195            thread_handle: Mutex::new(None),
196            running: AtomicBool::new(true),
197            #[cfg(target_os = "linux")]
198            #[allow(clippy::cast_possible_truncation)]
199            tid: unsafe { libc::syscall(libc::SYS_gettid) } as i32,
200        }))
201    }
202
203    /// Id of the arbiter
204    pub fn id(&self) -> Id {
205        Id(self.0.id)
206    }
207
208    #[cfg(target_os = "linux")]
209    /// TID of the arbiter
210    pub(crate) fn tid(&self) -> i32 {
211        self.0.tid
212    }
213
214    /// Name of the arbiter
215    pub fn name(&self) -> &str {
216        self.0.name.as_ref()
217    }
218
219    #[inline]
220    /// Handle to a runtime
221    pub fn handle(&self) -> &Handle {
222        self.0.hnd.as_ref().unwrap()
223    }
224
225    #[inline]
226    /// Check if arbiter is running
227    pub fn is_running(&self) -> bool {
228        self.0.running.load(Ordering::Relaxed)
229    }
230
231    /// Get a type previously inserted to this runtime or create new one.
232    pub fn get_value<T, F>(f: F) -> T
233    where
234        T: Clone + 'static,
235        F: FnOnce() -> T,
236    {
237        STORAGE.with(move |cell| {
238            let mut st = cell.borrow_mut();
239            if let Some(boxed) = st.get(&TypeId::of::<T>())
240                && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
241            {
242                return val.clone();
243            }
244            let val = f();
245            st.insert(TypeId::of::<T>(), Box::new(val.clone()));
246            val
247        })
248    }
249
250    /// Wait for the event loop to stop by joining the underlying thread (if have Some).
251    pub fn join(&mut self) -> thread::Result<()> {
252        if let Some(thread_handle) = self.0.thread_handle.lock().take() {
253            thread_handle.join()
254        } else {
255            Ok(())
256        }
257    }
258}
259
260impl Eq for Arbiter {}
261
262impl PartialEq for Arbiter {
263    fn eq(&self, other: &Self) -> bool {
264        self.0.id == other.0.id && self.0.sys_id == other.0.sys_id
265    }
266}
267
268pub(crate) struct ArbiterController {
269    sys: Option<System>,
270    rx: Receiver<ArbiterCommand>,
271    stop: Option<oneshot::Sender<i32>>,
272}
273
274impl Drop for ArbiterController {
275    fn drop(&mut self) {
276        if thread::panicking() {
277            if let Some(sys) = self.sys.take()
278                && sys.stop_on_panic()
279            {
280                eprintln!("Panic in Arbiter thread, shutting down system.");
281                sys.stop_with_code(1);
282            } else {
283                eprintln!("Panic in Arbiter thread.");
284            }
285        }
286    }
287}
288
289impl ArbiterController {
290    pub(super) async fn run(mut self, sys: System) {
291        self.sys = Some(sys);
292        loop {
293            match self.rx.recv().await {
294                Ok(ArbiterCommand::Stop) => {
295                    if let Some(stop) = self.stop.take() {
296                        let _ = stop.send(0);
297                    }
298                }
299                Ok(ArbiterCommand::Execute(fut)) => {
300                    crate::spawn(fut);
301                }
302                Err(_) => break,
303            }
304        }
305    }
306}
307
308/// Set item to current runtime's storage
309pub fn set_item<T: 'static>(item: T) {
310    STORAGE.with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
311}
312
313/// Get a reference to a type previously inserted on this runtime's storage
314pub fn get_item<T: Clone + 'static>() -> Option<T> {
315    STORAGE.with(move |cell| {
316        cell.borrow()
317            .get(&TypeId::of::<T>())
318            .and_then(|boxed| boxed.downcast_ref())
319            .cloned()
320    })
321}
322
323/// Get a reference to a type or create new if it doesnt exists
324pub fn with_item<T: Default + 'static, F, R>(f: F) -> R
325where
326    F: FnOnce(&T) -> R,
327{
328    STORAGE.with(move |cell| {
329        let mut st = cell.borrow_mut();
330        if let Some(boxed) = st.get(&TypeId::of::<T>()) {
331            f(boxed.downcast_ref().unwrap())
332        } else {
333            let item = T::default();
334            let result = f(&item);
335            st.insert(TypeId::of::<T>(), Box::new(item));
336            result
337        }
338    })
339}
340
341/// Remove all items from storage.
342pub fn remove_all_items() {
343    STORAGE.with(move |cell| cell.borrow_mut().clear());
344    System::remove_current();
345}