Skip to main content

ntex_rt/
system.rs

1use std::any::{Any, TypeId};
2use std::collections::VecDeque;
3use std::sync::{Arc, atomic::AtomicBool, atomic::AtomicUsize, atomic::Ordering};
4use std::time::{Duration, Instant};
5use std::{cell::RefCell, fmt, future::Future, pin::Pin};
6
7use async_channel::{Receiver, Sender, unbounded};
8use parking_lot::{Mutex, RwLock};
9
10use crate::arbiter::Arbiter;
11use crate::pool::PoolMetrics;
12use crate::{BlockingResult, Builder, Handle, HashMap, Runner, SystemRunner, TaskCallbacks};
13
14static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0);
15
16thread_local!(
17    static PINGS: RefCell<HashMap<Id, VecDeque<PingRecord>>> = RefCell::new(HashMap::default());
18);
19
20#[derive(Default)]
21struct Arbiters {
22    all: HashMap<Id, Arbiter>,
23    list: Vec<Arbiter>,
24}
25
26/// Identifier assigned to a [`System`] or [`Arbiter`].
27///
28/// System and arbiter identifiers use separate sequences.
29#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
30pub struct Id(pub(crate) usize);
31
32/// Runtime manager for a group of arbiter threads.
33///
34/// A system stores runtime configuration, manages arbiters, and dispatches
35/// process signals. Each of its arbiters owns a blocking thread pool.
36///
37/// Clones share the same system and may be sent to other threads. Merely holding
38/// a handle does not install that system as the current system on another thread.
39pub struct System(pub(crate) Arc<SystemInner>);
40
41pub(crate) struct SystemInner {
42    id: usize,
43    arbiter: Arbiter,
44    pub(crate) config: SystemConfig,
45    sender: Sender<SystemCommand>,
46    receiver: Receiver<SystemCommand>,
47    storage: RwLock<HashMap<TypeId, Box<dyn Any + Sync + Send>>>,
48    arbiters: Mutex<Arbiters>,
49    signals: AtomicBool,
50    // pool totals of unregistered arbiters
51    retired_pools: Mutex<PoolMetrics>,
52}
53
54/// Configuration shared by a running [`System`].
55///
56/// Obtain a clone with [`System::config`] and reuse it with
57/// [`System::with_config`] or [`Builder::build_with`]. Signal and panic-handling
58/// settings are not part of this configuration.
59#[derive(Clone)]
60pub struct SystemConfig {
61    pub(super) name: String,
62    pub(super) stack_size: usize,
63    pub(super) ping_interval: usize,
64    pub(super) ping_threshold: usize,
65    pub(super) latency_interval: usize,
66    pub(super) pool_limit: usize,
67    pub(super) pool_recv_timeout: Duration,
68    pub(super) timer_resolution: u8,
69    pub(super) testing: bool,
70    pub(super) task_callbacks: Option<fn() -> TaskCallbacks>,
71    pub(super) runner: Arc<dyn Runner>,
72}
73
74thread_local!(
75    static CURRENT: RefCell<Option<System>> = const { RefCell::new(None) };
76);
77
78impl Clone for System {
79    fn clone(&self) -> Self {
80        Self(self.0.clone())
81    }
82}
83
84impl SystemInner {
85    /// Returns the registered arbiters.
86    pub(crate) fn arbiters(&self) -> Vec<Arbiter> {
87        self.arbiters.lock().list.clone()
88    }
89}
90
91impl System {
92    /// Constructs new system and sets it as current
93    pub(super) fn start(config: SystemConfig) -> (Self, oneshot::Receiver<i32>) {
94        let id = SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst);
95        let (sender, receiver) = unbounded();
96
97        let (arbiter, controller) = Arbiter::new_system(id, &config);
98
99        let mut arbiters = Arbiters::default();
100        arbiters.all.insert(arbiter.id(), arbiter.clone());
101        arbiters.list.push(arbiter.clone());
102
103        let sys = System(Arc::new(SystemInner {
104            id,
105            config,
106            arbiter,
107            sender,
108            receiver,
109            arbiters: Mutex::new(arbiters),
110            retired_pools: Mutex::new(PoolMetrics::default()),
111            storage: RwLock::new(HashMap::default()),
112            signals: AtomicBool::new(false),
113        }));
114        System::set_current(sys.clone());
115
116        let (stop_tx, stop) = oneshot::channel();
117
118        // system support tasks
119        crate::spawn_detached(SystemSupport::new(&sys, stop_tx).run());
120        crate::spawn_detached(controller.run(sys.clone()));
121
122        (sys, stop)
123    }
124
125    /// Creates a builder for a system with a customized runtime.
126    ///
127    /// See [`Builder`] for the available configuration options.
128    pub fn build() -> Builder {
129        Builder::new()
130    }
131
132    #[allow(clippy::new_ret_no_self)]
133    /// Creates a system runner with the specified name and runtime runner.
134    ///
135    /// The system is not started until the returned runner is driven.
136    pub fn new<R: Runner>(name: &str, runner: R) -> SystemRunner {
137        Self::build().name(name).build(runner)
138    }
139
140    #[allow(clippy::new_ret_no_self)]
141    /// Creates a system runner from an existing configuration.
142    ///
143    /// Replaces the configuration's name with `name`. Signal and panic handling
144    /// are disabled for the new runner. The system starts only when it is driven.
145    pub fn with_config(name: &str, mut config: SystemConfig) -> SystemRunner {
146        name.clone_into(&mut config.name);
147        Self::build().name(name).build_with(config)
148    }
149
150    /// Returns the system running on the current thread.
151    ///
152    /// # Panics
153    ///
154    /// Panics if no system is running on the current thread.
155    pub fn current() -> System {
156        CURRENT.with(|cell| match *cell.borrow() {
157            Some(ref sys) => sys.clone(),
158            None => panic!("System is not running"),
159        })
160    }
161
162    /// Returns the system running on the current thread, if one exists.
163    pub fn try_current() -> Option<System> {
164        CURRENT.with(|cell| cell.borrow().as_ref().map(Clone::clone))
165    }
166
167    /// Set current running system
168    #[doc(hidden)]
169    pub fn set_current(sys: System) {
170        crate::task::set_callbacks(sys.0.config.task_callbacks.map(|f| f()));
171        CURRENT.with(|s| {
172            *s.borrow_mut() = Some(sys);
173        });
174    }
175
176    pub(crate) fn register_arbiter(&self, arb: Arbiter) {
177        crate::task::set_callbacks(self.0.config.task_callbacks.map(|f| f()));
178        CURRENT.with(|s| {
179            *s.borrow_mut() = Some(self.clone());
180        });
181        let mut arbiters = self.0.arbiters.lock();
182        arbiters.all.insert(arb.id(), arb.clone());
183        arbiters.list.push(arb);
184    }
185
186    pub(crate) fn unregister_arbiter(&self, id: Id) {
187        crate::task::set_callbacks(None);
188        CURRENT.with(|s| {
189            *s.borrow_mut() = None;
190        });
191        let mut arbiters = self.0.arbiters.lock();
192        if let Some(hnd) = arbiters.all.remove(&id) {
193            for (idx, arb) in arbiters.list.iter().enumerate() {
194                if &hnd == arb {
195                    arbiters.list.remove(idx);
196                    break;
197                }
198            }
199            self.retire_pool(&hnd);
200        }
201    }
202
203    /// Keeps the pool totals of an unregistered arbiter, the primary
204    /// arbiter's pool is always included in [`System::pool_metrics`].
205    fn retire_pool(&self, arb: &Arbiter) {
206        if arb != &self.0.arbiter {
207            self.0.retired_pools.lock().add_totals(&arb.pool_metrics());
208        }
209    }
210
211    pub(super) fn remove_current() {
212        crate::task::set_callbacks(None);
213        CURRENT.with(|cell| {
214            cell.borrow_mut().take();
215        });
216    }
217
218    /// Unregisters all arbiters of the system.
219    pub(super) fn take_arbiters(&self) -> Vec<Arbiter> {
220        let mut arbiters = self.0.arbiters.lock();
221        arbiters.all.clear();
222        let list = std::mem::take(&mut arbiters.list);
223        for arb in &list {
224            self.retire_pool(arb);
225        }
226        list
227    }
228
229    /// Stops and unregisters all arbiters of the system.
230    pub(super) fn stop_arbiters(&self) {
231        for arb in self.take_arbiters() {
232            arb.stop();
233        }
234    }
235
236    /// Returns the system identifier.
237    pub fn id(&self) -> Id {
238        Id(self.0.id)
239    }
240
241    /// Returns the system name.
242    pub fn name(&self) -> &str {
243        &self.0.config.name
244    }
245
246    /// Requests that the system stop with exit code `0`.
247    ///
248    /// This does not wait for shutdown. See [`stop_with_code`](Self::stop_with_code).
249    pub fn stop(&self) {
250        self.stop_with_code(0);
251    }
252
253    /// Requests that the system stop with the specified exit code.
254    ///
255    /// The request is processed asynchronously on the primary arbiter, which
256    /// asks all registered arbiters to stop. [`SystemRunner::run`] reports
257    /// nonzero codes as errors. A runner awaiting a user future with
258    /// [`SystemRunner::block_on`] still waits for that future to complete.
259    pub fn stop_with_code(&self, code: i32) {
260        let _ = self.0.sender.try_send(SystemCommand::Exit(code));
261    }
262
263    /// Returns whether this system owns process signal handling.
264    pub fn signals(&self) -> bool {
265        self.0.signals.load(Ordering::Relaxed)
266    }
267
268    /// Enables process signal handling.
269    ///
270    /// Signals are handled by one system at a time, this has no effect while
271    /// another system handles signals. Call this on the system's primary
272    /// arbiter thread, where its signal-delivery task and shutdown state live.
273    pub fn enable_signals(&self) {
274        if !self.signals() && crate::signals::start(self) {
275            self.0.signals.store(true, Ordering::Relaxed);
276        }
277    }
278
279    /// Disables process signal handling.
280    pub fn disable_signals(&self) {
281        if self.signals() {
282            crate::signals::stop(self);
283            self.0.signals.store(false, Ordering::Relaxed);
284        }
285    }
286
287    /// Returns the system's primary arbiter.
288    pub fn arbiter(&self) -> Arbiter {
289        self.0.arbiter.clone()
290    }
291
292    /// Provides access to all arbiters registered with this system.
293    ///
294    /// The callback receives a snapshot, including the primary arbiter while it
295    /// remains registered. It runs without the registry lock held, so it may
296    /// create, stop, join, or enumerate arbiters. This method may be called from
297    /// any thread.
298    pub fn list_arbiters<F, R>(&self, f: F) -> R
299    where
300        F: FnOnce(&[Arbiter]) -> R,
301    {
302        f(&self.0.arbiters())
303    }
304
305    /// Visits the latest ping records for each registered arbiter.
306    ///
307    /// This method should be called from the thread where the system has been initialized,
308    /// typically the "main" thread, because records are thread-local. Records
309    /// are stored newest first, with at most ten per arbiter before callbacks
310    /// modify them. Arbiters without records are not visited.
311    ///
312    /// The callback may modify the stored records and runs without the arbiter
313    /// registry lock, but must not call this method recursively.
314    ///
315    /// # Panics
316    ///
317    /// Panics if no current system is installed or if called recursively.
318    pub fn list_arbiter_pings<F>(mut f: F)
319    where
320        F: FnMut(&Arbiter, &mut VecDeque<PingRecord>),
321    {
322        PINGS.with(|pings| {
323            let mut p = pings.borrow_mut();
324            let sys = System::current();
325            let arbiters: Vec<_> = {
326                let arbiters = sys.0.arbiters.lock();
327                p.keys()
328                    .filter_map(|id| arbiters.all.get(id).map(|arb| (*id, arb.clone())))
329                    .collect()
330            };
331
332            // callbacks run without the registry lock
333            for (id, arb) in &arbiters {
334                if let Some(recs) = p.get_mut(id) {
335                    f(arb, recs);
336                }
337            }
338        });
339    }
340
341    #[doc(hidden)]
342    /// Set arbiter latency callback.
343    ///
344    /// This callback is called with the backtrace of a stalled arbiter, see
345    /// [`Builder::ping_threshold`]. Backtraces are captured on Linux and
346    /// Windows. The provided backtrace is not resolved. The location is the
347    /// spawn location of the task that blocks the arbiter, see
348    /// [`Handle::current_task`].
349    pub fn set_latency_callback<F>(f: F)
350    where
351        F: Fn(ntex_error::Backtrace, Option<&'static std::panic::Location<'static>>)
352            + Send
353            + Sync
354            + 'static,
355    {
356        crate::watchdog::set_latency_callback(Arc::new(f));
357    }
358
359    /// Returns a clone of the system configuration.
360    pub fn config(&self) -> SystemConfig {
361        self.0.config.clone()
362    }
363
364    #[inline]
365    /// Returns a runtime handle for the primary arbiter.
366    pub fn handle(&self) -> Handle {
367        self.arbiter().handle().clone()
368    }
369
370    /// Returns whether the system is configured for testing.
371    pub fn testing(&self) -> bool {
372        self.0.config.testing()
373    }
374
375    #[inline]
376    /// Returns the timer wheel resolution in milliseconds.
377    ///
378    /// See [`Builder::timer_resolution`].
379    pub fn timer_resolution(&self) -> u8 {
380        self.0.config.timer_resolution()
381    }
382
383    /// Submits blocking work to a thread pool and returns its result future.
384    ///
385    /// Work submitted from an arbiter thread of this system runs on that
386    /// arbiter's pool, otherwise on the pool of the system's primary arbiter.
387    /// See [`Builder::thread_pool_limit`] for the size of each pool.
388    ///
389    /// This method does not wait for completion. It may be called from any
390    /// thread, regardless of which system is current there.
391    ///
392    /// Dropping the returned future prevents queued work from starting, but
393    /// cannot interrupt work that is already running. Call
394    /// [`BlockingResult::detach`] to let queued work continue even if its
395    /// result is no longer needed.
396    pub fn spawn_blocking<F, R>(&self, f: F) -> BlockingResult<R>
397    where
398        F: FnOnce() -> R + Send + 'static,
399        R: Send + 'static,
400    {
401        Arbiter::with_current_pool(self.0.id, |pool| {
402            pool.unwrap_or(&self.0.arbiter.0.pool).execute(f)
403        })
404    }
405
406    /// Returns a snapshot of the blocking thread pool metrics of all arbiters.
407    ///
408    /// Limits, gauges, and totals of the running arbiters' pools are summed,
409    /// totals include the pools of stopped arbiters. Use
410    /// [`Arbiter::pool_metrics`] for a single arbiter's pool.
411    pub fn pool_metrics(&self) -> PoolMetrics {
412        let mut metrics = self.0.arbiter.pool_metrics();
413        let arbiters = self.0.arbiters.lock();
414        for arb in &arbiters.list {
415            if arb != &self.0.arbiter {
416                metrics.add(&arb.pool_metrics());
417            }
418        }
419        metrics.add_totals(&self.0.retired_pools.lock());
420        metrics
421    }
422
423    /// Runs `f` with the system of the current thread, if any.
424    pub(crate) fn with_current<F, R>(f: F) -> R
425    where
426        F: FnOnce(Option<&System>) -> R,
427    {
428        CURRENT.with(|cell| f(cell.borrow().as_ref()))
429    }
430
431    /// Returns a clone of the system-wide value of type `T`, inserting one if absent.
432    ///
433    /// This method acquires a lock on the internal data structure.
434    /// To avoid repeated locking, prefer storing a cloned value in the arbiter's storage.
435    /// Initialization is not atomic: concurrent callers may each run `f` and
436    /// return different values, with the last inserted clone remaining in storage.
437    pub fn get_value<T>(&self, f: impl FnOnce() -> T) -> T
438    where
439        T: Clone + Send + Sync + 'static,
440    {
441        if let Some(boxed) = self.0.storage.read().get(&TypeId::of::<T>())
442            && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
443        {
444            val.clone()
445        } else {
446            let val = f();
447            self.0
448                .storage
449                .write()
450                .insert(TypeId::of::<T>(), Box::new(val.clone()));
451            val
452        }
453    }
454}
455
456impl SystemConfig {
457    #[inline]
458    /// Returns whether the system is configured for testing.
459    pub fn testing(&self) -> bool {
460        self.testing
461    }
462
463    #[inline]
464    /// Returns the timer wheel resolution in milliseconds.
465    ///
466    /// See [`Builder::timer_resolution`].
467    pub fn timer_resolution(&self) -> u8 {
468        self.timer_resolution
469    }
470
471    #[inline]
472    /// Returns the task callbacks factory, if set.
473    ///
474    /// See [`Builder::task_callbacks`].
475    pub fn task_callbacks(&self) -> Option<fn() -> TaskCallbacks> {
476        self.task_callbacks
477    }
478}
479
480impl fmt::Debug for System {
481    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482        f.debug_struct("System")
483            .field("id", &self.0.id)
484            .field("config", &self.0.config)
485            .field("signals", &self.signals())
486            .field("pool", &self.0.arbiter.0.pool)
487            .finish()
488    }
489}
490
491impl fmt::Debug for SystemConfig {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        f.debug_struct("SystemConfig")
494            .field("name", &self.name)
495            .field("testing", &self.testing)
496            .field("stack_size", &self.stack_size)
497            .field("timer_resolution", &self.timer_resolution)
498            .field("task_callbacks", &self.task_callbacks)
499            .finish()
500    }
501}
502
503#[derive(Debug)]
504pub(super) enum SystemCommand {
505    Exit(i32),
506}
507
508#[derive(Debug)]
509struct SystemSupport {
510    sys: System,
511    stop: Option<oneshot::Sender<i32>>,
512    commands: Receiver<SystemCommand>,
513    watchdog: Option<Arc<AtomicBool>>,
514}
515
516impl Drop for SystemSupport {
517    fn drop(&mut self) {
518        self.stop_watchdog();
519    }
520}
521
522impl SystemSupport {
523    fn new(sys: &System, stop: oneshot::Sender<i32>) -> Self {
524        Self {
525            sys: sys.clone(),
526            stop: Some(stop),
527            commands: sys.0.receiver.clone(),
528            watchdog: None,
529        }
530    }
531
532    fn stop_watchdog(&mut self) {
533        if let Some(stop) = self.watchdog.take() {
534            stop.store(true, Ordering::Relaxed);
535        }
536    }
537
538    async fn run(mut self) {
539        crate::metrics::start_latency_sampler(
540            &self.sys.0.arbiter.0.latency,
541            self.sys.0.config.latency_interval,
542        );
543        self.watchdog = crate::watchdog::start(&self.sys);
544        if self.sys.0.config.ping_interval != 0 {
545            crate::spawn_detached(ping_arbiters(self.sys.clone()));
546        }
547
548        loop {
549            match self.commands.recv().await {
550                Ok(SystemCommand::Exit(code)) => {
551                    log::debug!("Stopping system with {code} code");
552                    self.stop_watchdog();
553                    self.sys.stop_arbiters();
554
555                    crate::arbiter::run_shutdown_callbacks();
556
557                    // stop event loop
558                    if let Some(stop) = self.stop.take() {
559                        let _ = stop.send(code);
560                    }
561                }
562                Err(_) => {
563                    log::debug!("System stopped");
564                    return;
565                }
566            }
567        }
568    }
569}
570
571/// A ping sent to an arbiter, as exposed by [`System::list_arbiter_pings`].
572#[derive(Copy, Clone, Debug)]
573pub struct PingRecord {
574    /// Time the ping round started.
575    pub start: Instant,
576    /// Elapsed time when the primary arbiter observed the ping task complete.
577    ///
578    /// `None` means no successful response has been recorded, including when
579    /// the ping is still pending or its task was canceled.
580    pub rtt: Option<Duration>,
581}
582
583async fn ping_arbiters(sys: System) {
584    let interval = sys.0.config.ping_interval as u64;
585    let timer = crate::time::TimerHandle::new(0);
586
587    loop {
588        // interval between pings
589        timer.reset(interval);
590        std::future::poll_fn(|cx| timer.poll_elapsed(cx)).await;
591
592        let start = Instant::now();
593        let arbiters = sys.0.arbiters.lock();
594
595        // drop records of stopped arbiters
596        PINGS.with(|pings| {
597            pings
598                .borrow_mut()
599                .retain(|id, _| arbiters.all.contains_key(id));
600        });
601
602        for arb in &arbiters.list {
603            let id = arb.id();
604            let fut = arb.handle().spawn(async move {
605                yield_to().await;
606            });
607
608            PINGS.with(|pings| {
609                let mut p = pings.borrow_mut();
610                let recs = p.entry(id).or_default();
611                recs.push_front(PingRecord { start, rtt: None });
612                recs.truncate(10);
613            });
614
615            crate::spawn_detached(async move {
616                if fut.await.is_ok() {
617                    PINGS.with(|pings| {
618                        // a late pong belongs to its own round
619                        if let Some(recs) = pings.borrow_mut().get_mut(&id)
620                            && let Some(rec) = recs.iter_mut().find(|r| r.start == start)
621                        {
622                            rec.rtt = Some(start.elapsed());
623                        }
624                    });
625                }
626            });
627        }
628    }
629}
630
631async fn yield_to() {
632    use std::task::{Context, Poll};
633
634    struct Yield {
635        completed: bool,
636    }
637
638    impl Future for Yield {
639        type Output = ();
640
641        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
642            if self.completed {
643                return Poll::Ready(());
644            }
645            self.completed = true;
646            cx.waker().wake_by_ref();
647            Poll::Pending
648        }
649    }
650
651    Yield { completed: false }.await;
652}
653
654#[cfg(test)]
655#[path = "../tests/unit/system.rs"]
656mod tests;