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                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                    // start arbiter controller
144                    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                    // run loop
155                    let _ = stop_rx.await;
156
157                    // mark as not running
158                    arb.0.running.store(false, Ordering::Relaxed);
159                });
160
161                // unregister arbiter
162                sys2.unregister_arbiter(Id(id));
163
164                unsafe {
165                    remove_all_items();
166                }
167
168                log::info!("Arbiter {name3:?} has been stopped");
169            })
170            .unwrap_or_else(|err| {
171                panic!("Cannot spawn an arbiter's thread {name:?}: {err:?}")
172            });
173
174        let arb = arb_hnd_rx.recv().expect("Could not start new arbiter");
175        *arb.0.thread_handle.lock() = Some(handle);
176        arb
177    }
178
179    fn with_sender(
180        sys_id: usize,
181        id: usize,
182        name: Arc<String>,
183        sender: Sender<ArbiterCommand>,
184    ) -> Self {
185        #[cfg(feature = "tokio")]
186        let hnd = { Handle::new(sender.clone()) };
187
188        #[cfg(feature = "compio")]
189        let hnd = { Handle::new(sender.clone()) };
190
191        #[cfg(all(not(feature = "compio"), not(feature = "tokio")))]
192        let hnd = { Handle::current() };
193
194        Self(Arc::new(ArbiterInner {
195            id,
196            sys_id,
197            name,
198            sender,
199            hnd: Some(hnd),
200            thread_handle: Mutex::new(None),
201            running: AtomicBool::new(true),
202            #[cfg(target_os = "linux")]
203            #[allow(clippy::cast_possible_truncation)]
204            tid: unsafe { libc::syscall(libc::SYS_gettid) } as i32,
205        }))
206    }
207
208    /// Id of the arbiter
209    pub fn id(&self) -> Id {
210        Id(self.0.id)
211    }
212
213    #[cfg(target_os = "linux")]
214    /// TID of the arbiter
215    pub(crate) fn tid(&self) -> i32 {
216        self.0.tid
217    }
218
219    /// Name of the arbiter
220    pub fn name(&self) -> &str {
221        self.0.name.as_ref()
222    }
223
224    #[inline]
225    /// Handle to a runtime
226    pub fn handle(&self) -> &Handle {
227        self.0.hnd.as_ref().unwrap()
228    }
229
230    #[inline]
231    /// Check if arbiter is running
232    pub fn is_running(&self) -> bool {
233        self.0.running.load(Ordering::Relaxed)
234    }
235
236    /// Get a type previously inserted to this runtime or create new one.
237    pub fn get_value<T, F>(f: F) -> T
238    where
239        T: Clone + 'static,
240        F: FnOnce() -> T,
241    {
242        STORAGE.with(move |cell| {
243            let mut st = cell.borrow_mut();
244            if let Some(boxed) = st.get(&TypeId::of::<T>())
245                && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
246            {
247                return val.clone();
248            }
249            let val = f();
250            st.insert(TypeId::of::<T>(), Box::new(val.clone()));
251            val
252        })
253    }
254
255    /// Wait for the event loop to stop by joining the underlying thread (if have Some).
256    pub fn join(&mut self) -> thread::Result<()> {
257        if let Some(thread_handle) = self.0.thread_handle.lock().take() {
258            thread_handle.join()
259        } else {
260            Ok(())
261        }
262    }
263}
264
265impl Eq for Arbiter {}
266
267impl PartialEq for Arbiter {
268    fn eq(&self, other: &Self) -> bool {
269        self.0.id == other.0.id && self.0.sys_id == other.0.sys_id
270    }
271}
272
273pub(crate) struct ArbiterController {
274    sys: Option<System>,
275    rx: Receiver<ArbiterCommand>,
276    stop: Option<oneshot::Sender<i32>>,
277}
278
279impl Drop for ArbiterController {
280    fn drop(&mut self) {
281        if thread::panicking() {
282            if let Some(sys) = self.sys.take()
283                && sys.stop_on_panic()
284            {
285                eprintln!("Panic in Arbiter thread, shutting down system.");
286                sys.stop_with_code(1);
287            } else {
288                eprintln!("Panic in Arbiter thread.");
289            }
290        }
291    }
292}
293
294impl ArbiterController {
295    pub(super) async fn run(mut self, sys: System) {
296        self.sys = Some(sys);
297        loop {
298            match self.rx.recv().await {
299                Ok(ArbiterCommand::Stop) => {
300                    if let Some(stop) = self.stop.take() {
301                        let _ = stop.send(0);
302                    }
303                }
304                Ok(ArbiterCommand::Execute(fut)) => {
305                    crate::spawn(fut);
306                }
307                Err(_) => break,
308            }
309        }
310    }
311}
312
313/// Set item to current runtime's storage
314pub fn set_item<T: 'static>(item: T) {
315    STORAGE.with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
316}
317
318/// Get a reference to a type previously inserted on this runtime's storage
319pub fn get_item<T: Clone + 'static>() -> Option<T> {
320    STORAGE.with(move |cell| {
321        cell.borrow()
322            .get(&TypeId::of::<T>())
323            .and_then(|boxed| boxed.downcast_ref())
324            .cloned()
325    })
326}
327
328/// Get a reference to a type or create new if it doesnt exists
329pub fn with_item<T: Default + 'static, F, R>(f: F) -> R
330where
331    F: FnOnce(&T) -> R,
332{
333    STORAGE.with(move |cell| {
334        // SAFETY: value of T is stored in heap, manipulation
335        // with STORAGE are not affected location of T
336        let val: &T = unsafe {
337            let mut st = cell.borrow_mut();
338            if let Some(boxed) = st.get(&TypeId::of::<T>()) {
339                std::mem::transmute::<&T, &T>(boxed.downcast_ref::<T>().unwrap())
340            } else {
341                st.insert(TypeId::of::<T>(), Box::new(T::default()));
342                let boxed = st.get(&TypeId::of::<T>()).unwrap();
343                std::mem::transmute::<&T, &T>(boxed.downcast_ref::<T>().unwrap())
344            }
345        };
346        f(val)
347    })
348}
349
350#[doc(hidden)]
351/// Remove all items from storage.
352///
353/// # Safety
354///
355/// Must ensure that all outstading calls to `with_item` are completed.
356pub unsafe fn remove_all_items() {
357    STORAGE.with(move |cell| {
358        loop {
359            let mut items = cell.borrow_mut();
360            let Some(item) = items.drain().next() else {
361                break;
362            };
363            drop(items);
364            drop(item);
365        }
366    });
367    System::remove_current();
368}