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, mem, panic, pin::Pin, rc::Rc, 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, Rc<dyn Any>>> = RefCell::new(HashMap::default());
13    static ON_SHUTDOWN: RefCell<Vec<Box<dyn FnOnce()>>> = const { RefCell::new(Vec::new()) };
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/// An asynchronous execution environment running on one OS thread.
25///
26/// Creating an arbiter starts a thread with its own local event loop. Futures
27/// spawned on that event loop are not required to implement `Send`.
28pub struct Arbiter(pub(crate) Arc<ArbiterInner>);
29
30type OnCloseStorage = Arc<Mutex<Vec<Box<dyn Fn() + Send + Sync>>>>;
31
32pub(crate) struct ArbiterInner {
33    id: usize,
34    name: Arc<String>,
35    sys_id: usize,
36    hnd: Option<Handle>,
37    pub(crate) sender: Sender<ArbiterCommand>,
38    thread_handle: Mutex<Option<thread::JoinHandle<()>>>,
39    on_stop: OnCloseStorage,
40    running: AtomicBool,
41    #[cfg(target_os = "linux")]
42    tid: i32,
43}
44
45impl fmt::Debug for Arbiter {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "Arbiter({:?})", self.0.name.as_ref())
48    }
49}
50
51impl Clone for Arbiter {
52    fn clone(&self) -> Self {
53        Self(self.0.clone())
54    }
55}
56
57impl Default for Arbiter {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl Arbiter {
64    #[allow(clippy::borrowed_box)]
65    pub(super) fn new_system(id: usize, name: String) -> (Self, ArbiterController) {
66        let (tx, rx) = unbounded();
67
68        let aid = COUNT.fetch_add(1, Ordering::Relaxed);
69        let arb = Arbiter::with_sender(id, aid, Arc::new(name), tx, Arc::default());
70        ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
71        clear_storage();
72
73        (
74            arb,
75            ArbiterController {
76                rx,
77                sys: None,
78                stop: None,
79            },
80        )
81    }
82
83    /// Returns the arbiter running on the current thread.
84    ///
85    /// # Panics
86    ///
87    /// Panics if no arbiter is running on the current thread.
88    pub fn current() -> Arbiter {
89        ADDR.with(|cell| match *cell.borrow() {
90            Some(ref addr) => addr.clone(),
91            None => panic!("Arbiter is not running"),
92        })
93    }
94
95    /// Requests that the arbiter stop its event loop.
96    pub fn stop(&self) {
97        let _ = self.0.sender.try_send(ArbiterCommand::Stop);
98    }
99
100    /// Starts an arbiter on a new thread with an automatically generated name.
101    pub fn new() -> Arbiter {
102        let id = COUNT.fetch_add(1, Ordering::Relaxed);
103        Arbiter::start(id, format!("{}:arb:{}", System::current().name(), id))
104    }
105
106    /// Starts an arbiter on a new thread with the specified name.
107    pub fn with_name(name: String) -> Arbiter {
108        Arbiter::start(COUNT.fetch_add(1, Ordering::Relaxed), name)
109    }
110
111    fn start(id: usize, name: String) -> Arbiter {
112        let sys = System::current();
113        let name2 = Arc::new(name.clone());
114        let config = sys.config();
115        let (arb_tx, arb_rx) = unbounded();
116
117        let builder = if sys.config().stack_size > 0 {
118            thread::Builder::new()
119                .name(name)
120                .stack_size(sys.config().stack_size)
121        } else {
122            thread::Builder::new().name(name)
123        };
124
125        let name = name2.clone();
126        let sys_id = sys.id();
127        let (arb_hnd_tx, arb_hnd_rx) = oneshot::channel();
128
129        let handle = builder
130            .spawn(move || {
131                let name3 = name2.clone();
132                log::info!("Starting {name3:?} arbiter");
133
134                let sys2 = sys.clone();
135                let (stop, stop_rx) = oneshot::channel();
136                clear_storage();
137
138                let on_stop = Arc::new(Mutex::new(Vec::new()));
139                let on_stop2 = on_stop.clone();
140
141                let result = crate::driver::block_on(config.runner.as_ref(), async move {
142                    let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx, on_stop);
143                    sys.register_arbiter(arb.clone());
144                    arb_hnd_tx
145                        .send(arb.clone())
146                        .expect("Controller thread has gone");
147
148                    // start arbiter controller
149                    crate::spawn(
150                        ArbiterController {
151                            sys: None,
152                            stop: Some(stop),
153                            rx: arb_rx,
154                        }
155                        .run(sys),
156                    );
157                    ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
158
159                    // run loop
160                    let _ = stop_rx.await;
161
162                    // mark as not running
163                    arb.0.running.store(false, Ordering::Relaxed);
164                });
165
166                let on_stop = mem::take(&mut *on_stop2.lock());
167                for f in on_stop {
168                    f();
169                }
170
171                // unregister arbiter
172                sys2.unregister_arbiter(Id(id));
173                // skipped by `block_on` if the event loop panicked
174                run_shutdown_callbacks();
175                unsafe {
176                    remove_all_items();
177                }
178
179                if let Err(e) = result {
180                    log::error!("Arbiter {name3:?} has panicked.");
181                    panic::resume_unwind(e);
182                }
183                log::info!("Arbiter {name3:?} has stopped");
184            })
185            .unwrap_or_else(|err| panic!("Cannot spawn an arbiter's thread {name:?}: {err:?}"));
186
187        let arb = arb_hnd_rx.recv().expect("Could not start new arbiter");
188        *arb.0.thread_handle.lock() = Some(handle);
189        arb
190    }
191
192    fn with_sender(
193        sys_id: usize,
194        id: usize,
195        name: Arc<String>,
196        sender: Sender<ArbiterCommand>,
197        on_stop: OnCloseStorage,
198    ) -> Self {
199        #[cfg(feature = "tokio")]
200        let hnd = { Handle::new(sender.clone()) };
201
202        #[cfg(feature = "compio")]
203        let hnd = { Handle::new(sender.clone()) };
204
205        #[cfg(all(not(feature = "compio"), not(feature = "tokio")))]
206        let hnd = { Handle::current() };
207
208        Self(Arc::new(ArbiterInner {
209            id,
210            sys_id,
211            name,
212            sender,
213            on_stop,
214            hnd: Some(hnd),
215            thread_handle: Mutex::new(None),
216            running: AtomicBool::new(true),
217            #[cfg(target_os = "linux")]
218            #[allow(clippy::cast_possible_truncation)]
219            tid: unsafe { libc::syscall(libc::SYS_gettid) } as i32,
220        }))
221    }
222
223    /// Returns the arbiter identifier.
224    pub fn id(&self) -> Id {
225        Id(self.0.id)
226    }
227
228    #[cfg(target_os = "linux")]
229    /// TID of the arbiter
230    pub(crate) fn tid(&self) -> i32 {
231        self.0.tid
232    }
233
234    /// Returns the arbiter name.
235    pub fn name(&self) -> &str {
236        self.0.name.as_ref()
237    }
238
239    #[inline]
240    /// Returns a handle to the arbiter's runtime.
241    pub fn handle(&self) -> &Handle {
242        self.0.hnd.as_ref().unwrap()
243    }
244
245    #[inline]
246    /// Returns whether the arbiter is running.
247    pub fn is_running(&self) -> bool {
248        self.0.running.load(Ordering::Relaxed)
249    }
250
251    /// Returns a value from thread-local arbiter storage, inserting it if absent.
252    ///
253    /// If the storage has already been destroyed because the thread is
254    /// exiting, the value returned by `f` is not stored.
255    pub fn get_value<T, F>(f: F) -> T
256    where
257        T: Clone + 'static,
258        F: FnOnce() -> T,
259    {
260        let mut f = Some(f);
261        STORAGE
262            .try_with(|cell| {
263                let mut st = cell.borrow_mut();
264                if let Some(boxed) = st.get(&TypeId::of::<T>())
265                    && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
266                {
267                    return val.clone();
268                }
269                let val = (f.take().unwrap())();
270                st.insert(TypeId::of::<T>(), Rc::new(val.clone()));
271                val
272            })
273            .unwrap_or_else(|_| (f.take().unwrap())())
274    }
275
276    /// Registers a callback to run when the current thread's arbiter shuts down.
277    ///
278    /// Callbacks run once, in registration order, on the arbiter's thread when
279    /// its stop is requested, by [`Arbiter::stop()`] or [`System::stop()`],
280    /// while the event loop is still running. An arbiter that ends without a
281    /// stop request, such as one driven by
282    /// [`SystemRunner::block_on()`](crate::SystemRunner::block_on), runs them
283    /// once its event loop has exited instead. A callback registered by
284    /// another callback runs in the same shutdown.
285    ///
286    /// If the thread is exiting and its thread-local storage has already been
287    /// destroyed, `f` is dropped without running.
288    pub fn on_shutdown<F>(f: F)
289    where
290        F: FnOnce() + 'static,
291    {
292        let f: Box<dyn FnOnce()> = Box::new(f);
293        let _ = ON_SHUTDOWN.try_with(move |cell| cell.borrow_mut().push(f));
294    }
295
296    #[must_use]
297    /// Adds a callback to run after the arbiter stops.
298    pub fn on_stop<F>(self, f: F) -> Self
299    where
300        F: Fn() + Send + Sync + 'static,
301    {
302        self.0.on_stop.lock().push(Box::new(f));
303        self
304    }
305
306    /// Waits for the arbiter's thread to stop.
307    ///
308    /// This returns immediately for an arbiter that does not own a thread
309    /// handle, including the system's primary arbiter.
310    pub fn join(&mut self) -> thread::Result<()> {
311        if let Some(thread_handle) = self.0.thread_handle.lock().take() {
312            thread_handle.join()
313        } else {
314            Ok(())
315        }
316    }
317}
318
319impl Eq for Arbiter {}
320
321impl PartialEq for Arbiter {
322    fn eq(&self, other: &Self) -> bool {
323        self.0.id == other.0.id && self.0.sys_id == other.0.sys_id
324    }
325}
326
327pub(crate) struct ArbiterController {
328    sys: Option<System>,
329    rx: Receiver<ArbiterCommand>,
330    stop: Option<oneshot::Sender<i32>>,
331}
332
333impl ArbiterController {
334    pub(super) async fn run(mut self, sys: System) {
335        self.sys = Some(sys);
336        loop {
337            match self.rx.recv().await {
338                Ok(ArbiterCommand::Stop) => {
339                    // the system arbiter has no `stop`, `System::stop()`
340                    // runs its callbacks
341                    if let Some(stop) = self.stop.take() {
342                        run_shutdown_callbacks();
343                        let _ = stop.send(0);
344                    }
345                }
346                Ok(ArbiterCommand::Execute(fut)) => {
347                    crate::spawn(fut);
348                }
349                Err(_) => break,
350            }
351        }
352    }
353}
354
355/// Runs the callbacks registered with [`Arbiter::on_shutdown()`], including
356/// ones registered while they run.
357pub(crate) fn run_shutdown_callbacks() {
358    loop {
359        let callbacks = ON_SHUTDOWN
360            .try_with(|cell| mem::take(&mut *cell.borrow_mut()))
361            .unwrap_or_default();
362        if callbacks.is_empty() {
363            break;
364        }
365        for f in callbacks {
366            f();
367        }
368    }
369}
370
371/// Inserts a value into the current arbiter's thread-local storage.
372///
373/// If the storage has already been destroyed because the thread is
374/// exiting, the value is dropped.
375pub fn set_item<T: 'static>(item: T) {
376    let item: Rc<dyn Any> = Rc::new(item);
377    let old = STORAGE
378        .try_with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), item))
379        .ok()
380        .flatten();
381    drop(old);
382}
383
384/// Returns a cloned value from the current arbiter's thread-local storage.
385///
386/// Returns `None` if the storage has already been destroyed because the
387/// thread is exiting.
388pub fn get_item<T: Clone + 'static>() -> Option<T> {
389    STORAGE
390        .try_with(move |cell| {
391            cell.borrow()
392                .get(&TypeId::of::<T>())
393                .and_then(|boxed| boxed.downcast_ref())
394                .cloned()
395        })
396        .ok()
397        .flatten()
398}
399
400/// Provides access to a value in the current arbiter's thread-local storage.
401///
402/// A default value is inserted if the requested type is not already present.
403/// If the storage has already been destroyed because the thread is exiting,
404/// `f` receives a temporary default value that is not stored.
405pub fn with_item<T: Default + 'static, F, R>(f: F) -> R
406where
407    F: FnOnce(&T) -> R,
408{
409    // `f` holds its own reference, so the value stays alive even if `f`
410    // replaces or removes it
411    let val = STORAGE
412        .try_with(|cell| {
413            let existing = cell.borrow().get(&TypeId::of::<T>()).cloned();
414            existing.unwrap_or_else(|| {
415                let val: Rc<dyn Any> = Rc::new(T::default());
416                cell.borrow_mut().insert(TypeId::of::<T>(), val.clone());
417                val
418            })
419        })
420        .ok();
421    match val {
422        Some(val) => f(val.downcast_ref::<T>().unwrap()),
423        None => f(&T::default()),
424    }
425}
426
427#[doc(hidden)]
428/// Remove all items from storage.
429///
430/// # Safety
431///
432/// All outstanding calls to [`with_item`] must have completed.
433pub unsafe fn remove_all_items() {
434    clear_storage();
435    System::remove_current();
436}
437
438/// Removes all items from the storage.
439///
440/// Each item is dropped outside of the storage borrow, so that its destructor
441/// may access the storage. Items it inserts are removed too.
442fn clear_storage() {
443    let _ = STORAGE.try_with(|cell| {
444        loop {
445            let mut items = cell.borrow_mut();
446            let Some(key) = items.keys().next().copied() else {
447                break;
448            };
449            let item = items.remove(&key);
450            drop(items);
451            drop(item);
452        }
453    });
454}
455
456#[cfg(test)]
457mod tests {
458    use std::cell::Cell;
459
460    use super::*;
461    use crate::testing::TestRunner;
462
463    #[derive(Clone, Default)]
464    struct Value(usize);
465
466    #[test]
467    #[should_panic(expected = "Arbiter is not running")]
468    fn current_without_arbiter() {
469        let _ = Arbiter::current();
470    }
471
472    #[test]
473    fn arbiter_api() {
474        System::new("arb-test", TestRunner).block_on(async {
475            let sys = System::current();
476            let cur = Arbiter::current();
477            assert_eq!(cur.name(), "arb-test");
478            assert_eq!(cur, sys.arbiter());
479            assert!(cur.is_running());
480            assert_eq!(format!("{cur:?}"), "Arbiter(\"arb-test\")");
481            // the primary arbiter does not own a thread
482            assert!(cur.clone().join().is_ok());
483
484            let stopped = Arc::new(AtomicUsize::new(0));
485            let stopped2 = stopped.clone();
486            let mut arb = Arbiter::with_name("named".to_string()).on_stop(move || {
487                stopped2.fetch_add(1, Ordering::Relaxed);
488            });
489            assert_eq!(arb.name(), "named");
490            assert!(arb.is_running());
491            assert_ne!(arb, cur);
492            sys.list_arbiters(|arbs| assert!(arbs.contains(&arb)));
493
494            // shutdown callbacks run on the arbiter's thread
495            let (reg_tx, reg_rx) = oneshot::async_channel();
496            let (tx, rx) = oneshot::channel();
497            arb.handle()
498                .spawn(async move {
499                    let name = Arbiter::current().name().to_string();
500                    Arbiter::on_shutdown(move || {
501                        let _ = tx.send(name);
502                    });
503                    let _ = reg_tx.send(());
504                })
505                .detach();
506            reg_rx.await.unwrap();
507
508            arb.stop();
509            arb.join().unwrap();
510            assert!(!arb.is_running());
511            assert_eq!(stopped.load(Ordering::Relaxed), 1);
512            assert_eq!(rx.recv().unwrap(), "named");
513            sys.list_arbiters(|arbs| assert!(!arbs.contains(&arb)));
514
515            let mut arb = Arbiter::default();
516            assert!(arb.name().starts_with("arb-test:arb:"));
517            arb.stop();
518            arb.join().unwrap();
519        });
520    }
521
522    #[test]
523    fn arbiter_values() {
524        System::new("test", TestRunner).block_on(async {
525            assert_eq!(Arbiter::get_value(|| Value(1)).0, 1);
526            assert_eq!(Arbiter::get_value(|| Value(2)).0, 1);
527        });
528    }
529
530    #[test]
531    fn on_shutdown_runs_after_block_on() {
532        let called = Rc::new(Cell::new(0));
533        let called2 = called.clone();
534        System::new("test", TestRunner).block_on(async move {
535            Arbiter::on_shutdown(move || {
536                called2.set(called2.get() + 1);
537                // registered by a callback, runs in the same shutdown
538                Arbiter::on_shutdown(move || called2.set(called2.get() + 1));
539            });
540        });
541        assert_eq!(called.get(), 2);
542    }
543
544    fn use_storage() {
545        set_item(Value(1));
546        let _ = get_item::<Value>();
547        with_item::<Value, _, _>(|v| v.0);
548        Arbiter::get_value(|| Value(2));
549    }
550
551    struct UseOnDrop;
552
553    impl Drop for UseOnDrop {
554        fn drop(&mut self) {
555            use_storage();
556        }
557    }
558
559    thread_local!(static HOLD: RefCell<Option<UseOnDrop>> = const { RefCell::new(None) });
560
561    #[test]
562    fn storage_access_during_thread_exit() {
563        // item stored in STORAGE accesses STORAGE while it is destroyed
564        thread::spawn(|| set_item(UseOnDrop)).join().unwrap();
565
566        // other thread local accesses STORAGE, in both destruction orders
567        thread::spawn(|| {
568            HOLD.with(|h| *h.borrow_mut() = Some(UseOnDrop));
569            use_storage();
570        })
571        .join()
572        .unwrap();
573        thread::spawn(|| {
574            use_storage();
575            HOLD.with(|h| *h.borrow_mut() = Some(UseOnDrop));
576        })
577        .join()
578        .unwrap();
579    }
580
581    #[test]
582    fn with_item_value_outlives_replacement() {
583        #[derive(Clone, Default)]
584        struct Item(std::rc::Rc<Vec<u8>>);
585
586        thread::spawn(|| {
587            set_item(Item(std::rc::Rc::new(vec![1; 64])));
588            let len = with_item::<Item, _, _>(|item| {
589                // replaces and frees the stored value while `f` holds its clone
590                set_item(Item::default());
591                unsafe { remove_all_items() };
592                item.0.len()
593            });
594            assert_eq!(len, 64);
595            assert!(get_item::<Item>().is_none());
596            assert_eq!(with_item::<Item, _, _>(|item| item.0.len()), 0);
597        })
598        .join()
599        .unwrap();
600    }
601
602    #[test]
603    fn remove_all_items_drops_outside_borrow() {
604        struct Item;
605
606        impl Drop for Item {
607            fn drop(&mut self) {
608                let _ = get_item::<u32>();
609                set_item(2u64);
610            }
611        }
612
613        thread::spawn(|| {
614            set_item(Item);
615            set_item(1u32);
616            unsafe { remove_all_items() };
617            assert!(get_item::<u32>().is_none());
618            assert!(get_item::<u64>().is_none(), "item inserted by a destructor");
619        })
620        .join()
621        .unwrap();
622    }
623
624    #[test]
625    fn storage_fallback_values() {
626        struct Check;
627
628        impl Drop for Check {
629            fn drop(&mut self) {
630                set_item(Value(5));
631                assert!(get_item::<Value>().is_none());
632                assert_eq!(with_item::<Value, _, _>(|v| v.0), 0);
633                assert_eq!(Arbiter::get_value(|| Value(3)).0, 3);
634                assert_eq!(Arbiter::get_value(|| Value(4)).0, 4);
635            }
636        }
637        thread::spawn(|| set_item(Check)).join().unwrap();
638    }
639}