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, rc::Rc, thread};
4
5use async_channel::{Receiver, Sender, unbounded};
6use parking_lot::Mutex;
7
8use crate::metrics::{LatencyMetrics, LatencyStats, start_latency_sampler};
9use crate::pool::{PoolMetrics, ThreadPool};
10use crate::system::SystemConfig;
11use crate::{Handle, HashMap, Id, System};
12
13thread_local!(
14    static ADDR: RefCell<Option<Arbiter>> = const { RefCell::new(None) };
15    static STORAGE: RefCell<HashMap<TypeId, Rc<dyn Any>>> = RefCell::new(HashMap::default());
16    static ON_SHUTDOWN: RefCell<Vec<Box<dyn FnOnce()>>> = const { RefCell::new(Vec::new()) };
17);
18
19pub(super) static COUNT: AtomicUsize = AtomicUsize::new(99);
20
21pub(super) enum ArbiterCommand {
22    Stop,
23}
24
25/// An asynchronous execution environment running on one OS thread.
26///
27/// Creating an arbiter starts a thread with its own local event loop. Futures
28/// spawned on that event loop are not required to implement `Send`.
29/// The system's primary arbiter instead runs on the thread driving its
30/// [`SystemRunner`](crate::SystemRunner).
31///
32/// Clones refer to the same arbiter and may be sent to other threads. Use
33/// [`handle`](Self::handle) to submit `Send` futures from another thread.
34pub struct Arbiter(pub(crate) Arc<ArbiterInner>);
35
36type OnCloseStorage = Arc<Mutex<Vec<Box<dyn Fn() + Send + Sync>>>>;
37
38pub(crate) struct ArbiterInner {
39    id: usize,
40    name: Arc<String>,
41    sys_id: usize,
42    hnd: Option<Handle>,
43    pub(crate) sender: Sender<ArbiterCommand>,
44    thread_handle: Mutex<Option<thread::JoinHandle<()>>>,
45    on_stop: OnCloseStorage,
46    running: AtomicBool,
47    pub(crate) latency: Arc<LatencyStats>,
48    pub(crate) pool: ThreadPool,
49    #[cfg(target_os = "linux")]
50    tid: i32,
51    #[cfg(windows)]
52    thread: Option<crate::watchdog::ThreadHandle>,
53}
54
55impl fmt::Debug for Arbiter {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "Arbiter({:?})", self.0.name.as_ref())
58    }
59}
60
61impl Clone for Arbiter {
62    fn clone(&self) -> Self {
63        Self(self.0.clone())
64    }
65}
66
67impl Default for Arbiter {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl Arbiter {
74    #[allow(clippy::borrowed_box)]
75    pub(super) fn new_system(id: usize, config: &SystemConfig) -> (Self, ArbiterController) {
76        let (tx, rx) = unbounded();
77
78        let aid = COUNT.fetch_add(1, Ordering::Relaxed);
79        let pool = ThreadPool::new(&config.name, config.pool_limit, config.pool_recv_timeout);
80        let arb = Arbiter::with_sender(id, aid, Arc::new(config.name.clone()), tx, pool);
81        ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
82        clear_storage();
83
84        (
85            arb,
86            ArbiterController {
87                rx,
88                sys: None,
89                stop: None,
90            },
91        )
92    }
93
94    /// Returns the arbiter running on the current thread.
95    ///
96    /// # Panics
97    ///
98    /// Panics if no arbiter is running on the current thread.
99    pub fn current() -> Arbiter {
100        ADDR.with(|cell| match *cell.borrow() {
101            Some(ref addr) => addr.clone(),
102            None => panic!("Arbiter is not running"),
103        })
104    }
105
106    /// Requests that the arbiter stop its event loop.
107    ///
108    /// This returns without waiting for shutdown; use [`join`](Self::join) to
109    /// wait for a spawned arbiter's thread. To stop the primary arbiter's event
110    /// loop, stop its [`System`] or complete the future driving the system.
111    pub fn stop(&self) {
112        let _ = self.0.sender.try_send(ArbiterCommand::Stop);
113    }
114
115    /// Starts an arbiter on a new thread with an automatically generated name.
116    ///
117    /// Uses the current system's runner and thread configuration.
118    ///
119    /// # Panics
120    ///
121    /// Panics if no current system is installed or the arbiter thread cannot
122    /// be started.
123    pub fn new() -> Arbiter {
124        let id = COUNT.fetch_add(1, Ordering::Relaxed);
125        Arbiter::start(id, format!("{}:arb:{}", System::current().name(), id), None)
126    }
127
128    /// Starts an arbiter on a new thread with the specified name.
129    ///
130    /// Uses the current system's runner and thread configuration.
131    ///
132    /// # Panics
133    ///
134    /// Panics if no current system is installed or the arbiter thread cannot
135    /// be started.
136    pub fn with_name(name: String) -> Arbiter {
137        Arbiter::start(COUNT.fetch_add(1, Ordering::Relaxed), name, None)
138    }
139
140    /// Starts an arbiter on a new thread with the specified name.
141    ///
142    /// `init` runs on the new thread before the arbiter's runtime is created,
143    /// for example to set the thread's CPU affinity, so that the runtime's
144    /// memory is allocated on the NUMA node of that CPU.
145    /// The new thread has no current system or arbiter during `init`, and its
146    /// arbiter storage is cleared after `init` returns. Affinity set by `init`
147    /// does not apply to the arbiter's blocking pool threads, see
148    /// [`ThreadPool`](crate::ThreadPool).
149    ///
150    /// # Panics
151    ///
152    /// Panics if no current system is installed, the thread cannot be started,
153    /// or initialization fails, including a panic in `init`.
154    pub fn with_init<F>(name: String, init: F) -> Arbiter
155    where
156        F: FnOnce() + Send + 'static,
157    {
158        Arbiter::start(
159            COUNT.fetch_add(1, Ordering::Relaxed),
160            name,
161            Some(Box::new(init)),
162        )
163    }
164
165    fn start(id: usize, name: String, init: Option<Box<dyn FnOnce() + Send>>) -> Arbiter {
166        let sys = System::current();
167        let name2 = Arc::new(name.clone());
168        let config = sys.config();
169        let (arb_tx, arb_rx) = unbounded();
170
171        let builder = if sys.config().stack_size > 0 {
172            thread::Builder::new()
173                .name(name)
174                .stack_size(sys.config().stack_size)
175        } else {
176            thread::Builder::new().name(name)
177        };
178
179        let name = name2.clone();
180        let sys_id = sys.id();
181        let (arb_hnd_tx, arb_hnd_rx) = oneshot::channel();
182        // created before `init`, pool threads do not inherit the affinity
183        // that `init` sets for the arbiter thread
184        let pool = ThreadPool::new(&name2, config.pool_limit, config.pool_recv_timeout);
185
186        let handle = builder
187            .spawn(move || {
188                if let Some(init) = init {
189                    init();
190                }
191                let name3 = name2.clone();
192                log::info!("Starting {name3:?} arbiter");
193
194                let sys2 = sys.clone();
195                let (stop, stop_rx) = oneshot::channel();
196                clear_storage();
197
198                // `block_on` finalizes the arbiter once its event loop exits
199                let result = crate::driver::block_on(config.runner.as_ref(), async move {
200                    let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx, pool);
201                    sys.register_arbiter(arb.clone());
202                    // `Arbiter::latency()` is available once the arbiter is returned
203                    start_latency_sampler(&arb.0.latency, config.latency_interval);
204                    arb_hnd_tx
205                        .send(arb.clone())
206                        .expect("Controller thread has gone");
207
208                    // start arbiter controller
209                    crate::spawn_detached(
210                        ArbiterController {
211                            sys: None,
212                            stop: Some(stop),
213                            rx: arb_rx,
214                        }
215                        .run(sys),
216                    );
217                    ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
218
219                    // run loop
220                    let _ = stop_rx.await;
221                });
222
223                let cleanup = || {
224                    // unregister arbiter
225                    sys2.unregister_arbiter(Id(id));
226                    // skipped by `block_on` if the event loop panicked
227                    run_shutdown_callbacks();
228                    // SAFETY: The event loop and shutdown callbacks have ended, so storage borrows are released.
229                    unsafe {
230                        remove_all_items();
231                    }
232                };
233                if result.is_err() {
234                    crate::abort_on_panic(cleanup);
235                } else {
236                    cleanup();
237                }
238
239                if let Err(e) = result {
240                    log::error!("Arbiter {name3:?} has panicked.");
241                    panic::resume_unwind(e);
242                }
243                log::info!("Arbiter {name3:?} has stopped");
244            })
245            .unwrap_or_else(|err| panic!("Cannot spawn an arbiter's thread {name:?}: {err:?}"));
246
247        let arb = arb_hnd_rx.recv().expect("Could not start new arbiter");
248        *arb.0.thread_handle.lock() = Some(handle);
249        arb
250    }
251
252    fn with_sender(
253        sys_id: usize,
254        id: usize,
255        name: Arc<String>,
256        sender: Sender<ArbiterCommand>,
257        pool: ThreadPool,
258    ) -> Self {
259        #[cfg(feature = "tokio")]
260        let hnd = { Handle::new() };
261
262        #[cfg(feature = "compio")]
263        let hnd = { Handle::new() };
264
265        #[cfg(all(not(feature = "compio"), not(feature = "tokio")))]
266        let hnd = { Handle::current() };
267
268        Self(Arc::new(ArbiterInner {
269            id,
270            sys_id,
271            name,
272            sender,
273            pool,
274            on_stop: Arc::default(),
275            hnd: Some(hnd),
276            thread_handle: Mutex::new(None),
277            running: AtomicBool::new(true),
278            latency: Arc::default(),
279            #[cfg(target_os = "linux")]
280            #[allow(clippy::cast_possible_truncation)]
281            // SAFETY: `SYS_gettid` takes no pointer arguments and returns this thread's ID.
282            tid: unsafe { libc::syscall(libc::SYS_gettid) } as i32,
283            #[cfg(windows)]
284            thread: crate::watchdog::ThreadHandle::current(),
285        }))
286    }
287
288    /// Returns the arbiter identifier.
289    pub fn id(&self) -> Id {
290        Id(self.0.id)
291    }
292
293    #[cfg(target_os = "linux")]
294    /// TID of the arbiter
295    pub(crate) fn tid(&self) -> i32 {
296        self.0.tid
297    }
298
299    #[cfg(windows)]
300    /// Handle of the arbiter thread
301    pub(crate) fn thread(&self) -> Option<&crate::watchdog::ThreadHandle> {
302        self.0.thread.as_ref()
303    }
304
305    /// Returns the arbiter name.
306    pub fn name(&self) -> &str {
307        self.0.name.as_ref()
308    }
309
310    #[inline]
311    /// Returns a handle to the arbiter's runtime.
312    pub fn handle(&self) -> &Handle {
313        self.0.hnd.as_ref().unwrap()
314    }
315
316    /// Returns the arbiter's scheduling latency.
317    ///
318    /// Returns `None` if latency sampling is disabled, see
319    /// [`Builder::latency_interval`](crate::Builder::latency_interval).
320    pub fn latency(&self) -> Option<LatencyMetrics> {
321        self.0.latency.metrics()
322    }
323
324    /// Returns a snapshot of the arbiter's blocking thread pool metrics.
325    ///
326    /// Each arbiter has its own pool, used by [`spawn_blocking`](crate::spawn_blocking)
327    /// on the arbiter's thread, see [`System::spawn_blocking`].
328    pub fn pool_metrics(&self) -> PoolMetrics {
329        self.0.pool.metrics()
330    }
331
332    #[inline]
333    /// Returns whether the arbiter is running.
334    ///
335    /// A stop request does not change this immediately. The flag is cleared
336    /// after the event loop exits, before [`on_stop`](Self::on_stop) callbacks.
337    pub fn is_running(&self) -> bool {
338        self.0.running.load(Ordering::Relaxed)
339    }
340
341    /// Returns a value from thread-local arbiter storage, inserting it if absent.
342    ///
343    /// Values are keyed by type and shared with [`get_item`], [`set_item`], and
344    /// [`with_item`] on the calling thread. Existing values are cloned.
345    /// The initializer runs while storage is mutably borrowed and must not
346    /// reenter these storage APIs.
347    ///
348    /// If the storage has already been destroyed because the thread is
349    /// exiting, the value returned by `f` is not stored.
350    pub fn get_value<T, F>(f: F) -> T
351    where
352        T: Clone + 'static,
353        F: FnOnce() -> T,
354    {
355        let mut f = Some(f);
356        STORAGE
357            .try_with(|cell| {
358                let mut st = cell.borrow_mut();
359                if let Some(boxed) = st.get(&TypeId::of::<T>())
360                    && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
361                {
362                    return val.clone();
363                }
364                let val = (f.take().unwrap())();
365                st.insert(TypeId::of::<T>(), Rc::new(val.clone()));
366                val
367            })
368            .unwrap_or_else(|_| (f.take().unwrap())())
369    }
370
371    /// Registers a callback to run when the current thread's arbiter shuts down.
372    ///
373    /// Callbacks run once, in registration order, on the arbiter's thread when
374    /// its stop is requested, by [`Arbiter::stop()`] or [`System::stop()`],
375    /// while the event loop is still running. An arbiter that ends without a
376    /// stop request, such as one driven by
377    /// [`SystemRunner::block_on()`](crate::SystemRunner::block_on), runs them
378    /// once its event loop has exited instead. A callback registered by
379    /// another callback runs in the same shutdown.
380    ///
381    /// If the thread is exiting and its thread-local storage has already been
382    /// destroyed, `f` is dropped without running. If `f` panics after the
383    /// event loop panicked, the process is aborted.
384    pub fn on_shutdown<F>(f: F)
385    where
386        F: FnOnce() + 'static,
387    {
388        let f: Box<dyn FnOnce()> = Box::new(f);
389        let _ = ON_SHUTDOWN.try_with(move |cell| cell.borrow_mut().push(f));
390    }
391
392    #[must_use]
393    /// Adds a callback to run after the arbiter stops.
394    ///
395    /// The callback runs on the arbiter thread after its event loop exits and
396    /// its running flag is cleared. Register before shutdown; registration after
397    /// finalization does not invoke the callback.
398    ///
399    /// If `f` panics after the event loop panicked, the process is aborted.
400    pub fn on_stop<F>(self, f: F) -> Self
401    where
402        F: Fn() + Send + Sync + 'static,
403    {
404        self.0.on_stop.lock().push(Box::new(f));
405        self
406    }
407
408    /// Returns the arbiter of the current thread, if any.
409    pub(crate) fn try_current() -> Option<Arbiter> {
410        ADDR.try_with(|cell| cell.borrow().clone()).ok().flatten()
411    }
412
413    /// Runs `f` with the blocking pool of the current thread's arbiter, if
414    /// that arbiter belongs to the system `sys_id`.
415    pub(crate) fn with_current_pool<F, R>(sys_id: usize, f: F) -> R
416    where
417        F: FnOnce(Option<&ThreadPool>) -> R,
418    {
419        let mut f = Some(f);
420        ADDR.try_with(|cell| {
421            let arb = cell.borrow();
422            let pool = arb
423                .as_ref()
424                .filter(|arb| arb.0.sys_id == sys_id)
425                .map(|arb| &arb.0.pool);
426            (f.take().unwrap())(pool)
427        })
428        .unwrap_or_else(|_| (f.take().unwrap())(None))
429    }
430
431    /// Marks the arbiter as stopped and runs its `on_stop` callbacks,
432    /// called once its event loop has exited.
433    pub(crate) fn finalize(&self) {
434        self.0.running.store(false, Ordering::Relaxed);
435        let on_stop = mem::take(&mut *self.0.on_stop.lock());
436        // a panic while unwinding aborts the process
437        for f in on_stop {
438            f();
439        }
440    }
441
442    /// Waits for the arbiter's thread to stop.
443    ///
444    /// This returns immediately for an arbiter that does not own a thread
445    /// handle, including the system's primary arbiter. The join handle is shared
446    /// by all clones and consumed by the first call. This does not request a stop.
447    ///
448    /// # Errors
449    ///
450    /// Returns the panic payload if the arbiter thread panicked.
451    ///
452    /// # Panics
453    ///
454    /// May panic when attempting to join the current thread.
455    pub fn join(&mut self) -> thread::Result<()> {
456        if let Some(thread_handle) = self.0.thread_handle.lock().take() {
457            thread_handle.join()
458        } else {
459            Ok(())
460        }
461    }
462}
463
464impl Eq for Arbiter {}
465
466impl PartialEq for Arbiter {
467    fn eq(&self, other: &Self) -> bool {
468        self.0.id == other.0.id && self.0.sys_id == other.0.sys_id
469    }
470}
471
472pub(crate) struct ArbiterController {
473    sys: Option<System>,
474    rx: Receiver<ArbiterCommand>,
475    stop: Option<oneshot::Sender<i32>>,
476}
477
478impl ArbiterController {
479    pub(super) async fn run(mut self, sys: System) {
480        self.sys = Some(sys);
481        while let Ok(ArbiterCommand::Stop) = self.rx.recv().await {
482            // the system arbiter has no `stop`, `System::stop()`
483            // runs its callbacks
484            if let Some(stop) = self.stop.take() {
485                run_shutdown_callbacks();
486                let _ = stop.send(0);
487            }
488        }
489    }
490}
491
492/// Runs the callbacks registered with [`Arbiter::on_shutdown()`], including
493/// ones registered while they run.
494pub(crate) fn run_shutdown_callbacks() {
495    loop {
496        let callbacks = ON_SHUTDOWN
497            .try_with(|cell| mem::take(&mut *cell.borrow_mut()))
498            .unwrap_or_default();
499        if callbacks.is_empty() {
500            break;
501        }
502        for f in callbacks {
503            f();
504        }
505    }
506}
507
508/// Inserts a value into the current arbiter's thread-local storage.
509///
510/// Values are keyed by type. Replaces and drops any previous value of type `T`;
511/// the previous value is dropped after releasing the storage borrow.
512///
513/// If the storage has already been destroyed because the thread is
514/// exiting, the value is dropped.
515pub fn set_item<T: 'static>(item: T) {
516    let item: Rc<dyn Any> = Rc::new(item);
517    let old = STORAGE
518        .try_with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), item))
519        .ok()
520        .flatten();
521    drop(old);
522}
523
524/// Returns a cloned value from the current arbiter's thread-local storage.
525///
526/// Returns `None` if no value of type `T` is stored, or if the storage has
527/// already been destroyed because the thread is exiting.
528pub fn get_item<T: Clone + 'static>() -> Option<T> {
529    STORAGE
530        .try_with(move |cell| {
531            cell.borrow()
532                .get(&TypeId::of::<T>())
533                .and_then(|boxed| boxed.downcast_ref())
534                .cloned()
535        })
536        .ok()
537        .flatten()
538}
539
540/// Provides access to a value in the current arbiter's thread-local storage.
541///
542/// A default value is inserted if the requested type is not already present.
543/// The callback holds a reference to that value independently of the storage,
544/// so it may replace or remove stored values without invalidating its argument.
545/// If the storage has already been destroyed because the thread is exiting,
546/// `f` receives a temporary default value that is not stored.
547pub fn with_item<T: Default + 'static, F, R>(f: F) -> R
548where
549    F: FnOnce(&T) -> R,
550{
551    // `f` holds its own reference, so the value stays alive even if `f`
552    // replaces or removes it
553    let val = STORAGE
554        .try_with(|cell| {
555            let existing = cell.borrow().get(&TypeId::of::<T>()).cloned();
556            existing.unwrap_or_else(|| {
557                let val: Rc<dyn Any> = Rc::new(T::default());
558                cell.borrow_mut().insert(TypeId::of::<T>(), val.clone());
559                val
560            })
561        })
562        .ok();
563    match val {
564        Some(val) => f(val.downcast_ref::<T>().unwrap()),
565        None => f(&T::default()),
566    }
567}
568
569#[doc(hidden)]
570/// Remove all items from storage.
571///
572/// # Safety
573///
574/// All outstanding calls to [`with_item`] must have completed.
575pub unsafe fn remove_all_items() {
576    clear_storage();
577    System::remove_current();
578}
579
580/// Removes all items from the storage.
581///
582/// Each item is dropped outside of the storage borrow, so that its destructor
583/// may access the storage. Items it inserts are removed too.
584fn clear_storage() {
585    let _ = STORAGE.try_with(|cell| {
586        loop {
587            let mut items = cell.borrow_mut();
588            let Some(key) = items.keys().next().copied() else {
589                break;
590            };
591            let item = items.remove(&key);
592            drop(items);
593            drop(item);
594        }
595    });
596}
597
598#[cfg(test)]
599#[path = "../tests/unit/arbiter.rs"]
600mod tests;