Skip to main content

ntex_server/
metrics.rs

1use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering, fence};
2use std::sync::{Arc, OnceLock};
3use std::{cell::RefCell, panic::Location, time::Duration, time::Instant};
4
5use ntex_bytes::{PageCacheMetrics, PageCacheSnapshot};
6use ntex_io::{IoConfigMetrics, IoMetricsGroup, IoMetricsSnapshot};
7use ntex_rt::Arbiter;
8use ntex_rt::metrics::{Histogram, LatencyMetrics};
9use parking_lot::Mutex;
10
11use crate::WorkerId;
12
13/// Snapshot of server metrics.
14///
15/// Counters and durations are totals since the server started. Rates over an
16/// interval are computed from the deltas of two snapshots.
17#[derive(Clone, Debug, Default, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct ServerMetrics {
20    /// Per-worker metrics, indexed by worker id.
21    pub workers: Vec<WorkerMetrics>,
22    /// Per-listener metrics, empty for servers without listeners.
23    pub listeners: Vec<ListenerMetrics>,
24    /// Number of times the accept loop stopped accepting connections, because
25    /// no worker was available or the server was paused.
26    pub accept_pauses: u64,
27    /// Total time the accept loop did not accept connections, including the
28    /// current pause.
29    pub accept_paused_duration: Duration,
30    /// Number of accepted connections waiting in the accept loop for an
31    /// available worker.
32    pub accept_backlog: usize,
33    /// Number of items sent to the worker on their incoming CPU, see
34    /// [`LoadBalancing::IncomingCpu`](crate::LoadBalancing::IncomingCpu).
35    pub incoming_cpu_hits: u64,
36    /// Number of items with a known incoming CPU that were sent to another
37    /// worker, because no worker is placed on that CPU or its worker was
38    /// busier than other workers.
39    pub incoming_cpu_misses: u64,
40    /// Number of items taken from the queue of a failed, unavailable or
41    /// blocked worker and sent to another worker.
42    pub rescheduled: u64,
43}
44
45/// Metrics of a single worker.
46///
47/// A restarted worker keeps the metrics of the worker it replaces.
48#[derive(Clone, Debug, Default, PartialEq, Eq)]
49#[non_exhaustive]
50pub struct WorkerMetrics {
51    /// Worker id.
52    pub id: WorkerId,
53    /// Number of items, connections for network servers, the worker received.
54    pub items: u64,
55    /// Number of open connections, network servers only.
56    pub active_connections: usize,
57    /// Number of times the worker service stopped being ready, e.g. it reached
58    /// the maximum number of connections.
59    pub not_ready: u64,
60    /// Total time the worker service was not ready, including the current
61    /// period.
62    pub not_ready_duration: Duration,
63    /// Number of times the worker was restarted after a failure.
64    pub restarts: u64,
65    /// I/O statistics of connections created on the worker, one entry per
66    /// listener configuration and per configuration with
67    /// `IoConfig::set_metrics()` enabled.
68    pub io: Vec<IoConfigMetrics>,
69    /// I/O statistics of the worker's other connections, e.g. client
70    /// connections of configurations without their own metrics.
71    pub io_other: IoMetricsSnapshot,
72    /// Statistics of the worker thread's buffer page cache.
73    ///
74    /// The metrics are single-writer. While a failed worker's thread is still
75    /// releasing pages and its replacement already runs, updates can be lost,
76    /// so after a worker restart the statistics may be slightly off.
77    pub page_cache: PageCacheSnapshot,
78    /// Statistics of the worker's runtime.
79    pub runtime: RuntimeMetrics,
80}
81
82/// Runtime statistics of a worker.
83///
84/// Counters, durations and histograms are totals over all runtimes the
85/// worker slot ran on, a restarted worker continues the totals of the worker
86/// it replaces. Values a runtime backend does not provide are `None`.
87#[derive(Clone, Debug, Default, PartialEq, Eq)]
88#[non_exhaustive]
89pub struct RuntimeMetrics {
90    /// Total time the runtime was busy running tasks.
91    ///
92    /// The `busy_duration` delta divided by the elapsed time is the worker's
93    /// utilization. On tokio it is available only for current-thread
94    /// runtimes.
95    pub busy_duration: Option<Duration>,
96    /// Number of runtime turns that ran scheduled tasks. Not available on
97    /// tokio.
98    pub polls: Option<u64>,
99    /// Number of runtime turns that left scheduled tasks for the next turn.
100    /// Not available on tokio.
101    pub polls_again: Option<u64>,
102    /// Number of times a task woke itself while it was polled. Neon only.
103    pub self_wakes: Option<u64>,
104    /// Durations of runtime turns. Not available on tokio.
105    pub poll_histogram: Option<Histogram>,
106    /// How long the current runtime turn has been running, `None` while the
107    /// runtime is idle or the backend does not track turns.
108    pub current_turn: Option<Duration>,
109    /// Spawn location of the task the runtime is polling now. Neon only.
110    pub current_task: Option<&'static Location<'static>>,
111    /// Scheduling latency and stalls, `None` if latency sampling is disabled,
112    /// see `ntex_rt::Builder::latency_interval()`.
113    ///
114    /// `histogram`, `stalls` and `stall_duration` are totals over all
115    /// runtimes of the worker slot, the other fields describe the current
116    /// runtime.
117    pub latency: Option<LatencyMetrics>,
118}
119
120/// Metrics of a single listener.
121#[derive(Clone, Debug, Default, PartialEq, Eq)]
122#[non_exhaustive]
123pub struct ListenerMetrics {
124    /// Service name the listener was registered with.
125    pub name: String,
126    /// Local address of the listener.
127    pub addr: String,
128    /// Number of accepted connections.
129    pub accepted: u64,
130    /// Number of per-connection accept errors, e.g. the connection was reset
131    /// before it was accepted.
132    pub connection_errors: u64,
133    /// Number of other accept errors, e.g. the process ran out of file
134    /// descriptors. The listener stops accepting for a short time after each.
135    pub resource_errors: u64,
136}
137
138fn as_nanos(d: Duration) -> u64 {
139    u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)
140}
141
142/// Accumulated period, e.g. time the worker was not ready.
143///
144/// The total and the open period are packed into one word, so a reader sees a
145/// coherent value with a single load: `state >> 2` is the total in
146/// nanoseconds, minus the start of the open period if `OPEN` is set. Values
147/// are nanoseconds since the epoch, modulo 2^62 (about 146 years).
148#[derive(Debug, Default)]
149struct Period {
150    count: AtomicU64,
151    state: AtomicU64,
152}
153
154impl Period {
155    const OPEN: u64 = 1;
156    // the open period is ending, its end time is not stored yet
157    const ENDING: u64 = 2;
158    const MASK: u64 = u64::MAX >> 2;
159
160    // single writer
161    fn set(&self, epoch: Instant, on: bool) {
162        let state = self.state.load(Ordering::Relaxed);
163        // called on every readiness check, read the clock only on changes
164        if on == (state & Self::OPEN != 0) {
165            return;
166        }
167        if on {
168            self.count.fetch_add(1, Ordering::Relaxed);
169            let acc = (state >> 2).wrapping_sub(as_nanos(epoch.elapsed()));
170            self.state.store((acc << 2) | Self::OPEN, Ordering::Release);
171        } else {
172            // readers wait for the end time instead of reading a later clock
173            self.state.store(state | Self::ENDING, Ordering::Relaxed);
174            fence(Ordering::SeqCst);
175            let total = (state >> 2).wrapping_add(as_nanos(epoch.elapsed()));
176            self.state.store(total << 2, Ordering::Release);
177        }
178    }
179
180    fn get(&self, epoch: Instant) -> (u64, Duration) {
181        let total = loop {
182            // acquire, the clock is read after the writer's
183            let state = self.state.load(Ordering::Acquire);
184            if state & Self::OPEN == 0 {
185                break state >> 2;
186            }
187            if state & Self::ENDING == 0 {
188                let now = as_nanos(epoch.elapsed());
189                fence(Ordering::SeqCst);
190                // the period did not start ending before the clock was read
191                if self.state.load(Ordering::Relaxed) == state {
192                    break (state >> 2).wrapping_add(now) & Self::MASK;
193                }
194            }
195            std::thread::yield_now();
196        };
197        (
198            self.count.load(Ordering::Relaxed),
199            Duration::from_nanos(total),
200        )
201    }
202}
203
204#[derive(Debug)]
205pub(crate) struct Metrics {
206    epoch: Instant,
207    workers: Box<[Arc<WorkerSlot>]>,
208    accept: OnceLock<Arc<AcceptSlot>>,
209    incoming_cpu_hits: AtomicU64,
210    incoming_cpu_misses: AtomicU64,
211    rescheduled: AtomicU64,
212}
213
214impl Metrics {
215    pub(crate) fn new(workers: usize) -> Self {
216        let epoch = Instant::now();
217        Self {
218            epoch,
219            workers: (0..workers)
220                .map(|_| Arc::new(WorkerSlot::new(epoch)))
221                .collect(),
222            accept: OnceLock::new(),
223            incoming_cpu_hits: AtomicU64::new(0),
224            incoming_cpu_misses: AtomicU64::new(0),
225            rescheduled: AtomicU64::new(0),
226        }
227    }
228
229    /// An item with a known incoming CPU was sent to the worker on that CPU,
230    /// or to another worker.
231    pub(crate) fn incoming_cpu(&self, hit: bool) {
232        let counter = if hit {
233            &self.incoming_cpu_hits
234        } else {
235            &self.incoming_cpu_misses
236        };
237        counter.fetch_add(1, Ordering::Relaxed);
238    }
239
240    /// Items were taken from a worker's queue to be sent to other workers.
241    pub(crate) fn rescheduled(&self, n: u64) {
242        self.rescheduled.fetch_add(n, Ordering::Relaxed);
243    }
244
245    pub(crate) fn worker(&self, id: WorkerId) -> Option<Arc<WorkerSlot>> {
246        self.workers.get(id.0).cloned()
247    }
248
249    /// Registers the listeners, in accept loop order.
250    ///
251    /// Only the first call has an effect.
252    pub(crate) fn listeners<I>(&self, listeners: I) -> &AcceptSlot
253    where
254        I: IntoIterator<Item = (String, String)>,
255    {
256        self.accept.get_or_init(|| {
257            Arc::new(AcceptSlot {
258                epoch: self.epoch,
259                listeners: listeners
260                    .into_iter()
261                    .map(|(name, addr)| ListenerSlot {
262                        name,
263                        addr,
264                        ..Default::default()
265                    })
266                    .collect(),
267                paused: Period::default(),
268                paused_loops: Mutex::new(0),
269                backlog: AtomicUsize::new(0),
270            })
271        })
272    }
273
274    /// Returns the listener metrics, if registered.
275    pub(crate) fn accept_slot(&self) -> Option<Arc<AcceptSlot>> {
276        self.accept.get().cloned()
277    }
278
279    pub(crate) fn snapshot(&self) -> ServerMetrics {
280        let workers = self
281            .workers
282            .iter()
283            .enumerate()
284            .map(|(id, w)| {
285                let (not_ready, not_ready_duration) = w.not_ready.get(self.epoch);
286                WorkerMetrics {
287                    id: WorkerId(id),
288                    items: w.items.load(Ordering::Relaxed),
289                    active_connections: w.active.load(Ordering::Relaxed),
290                    not_ready,
291                    not_ready_duration,
292                    restarts: w.restarts.load(Ordering::Relaxed),
293                    io: w.io.snapshot(),
294                    io_other: w.io.other().snapshot(),
295                    page_cache: w.page_cache.snapshot(),
296                    runtime: w.runtime_metrics(),
297                }
298            })
299            .collect();
300
301        let mut metrics = ServerMetrics {
302            workers,
303            incoming_cpu_hits: self.incoming_cpu_hits.load(Ordering::Relaxed),
304            incoming_cpu_misses: self.incoming_cpu_misses.load(Ordering::Relaxed),
305            rescheduled: self.rescheduled.load(Ordering::Relaxed),
306            ..Default::default()
307        };
308        if let Some(accept) = self.accept.get() {
309            (metrics.accept_pauses, metrics.accept_paused_duration) = accept.paused.get(self.epoch);
310            metrics.accept_backlog = accept.backlog.load(Ordering::Relaxed);
311            metrics.listeners = accept
312                .listeners
313                .iter()
314                .map(|l| ListenerMetrics {
315                    name: l.name.clone(),
316                    addr: l.addr.clone(),
317                    accepted: l.accepted.load(Ordering::Relaxed),
318                    connection_errors: l.connection_errors.load(Ordering::Relaxed),
319                    resource_errors: l.resource_errors.load(Ordering::Relaxed),
320                })
321                .collect();
322        }
323        metrics
324    }
325}
326
327// separate cache lines, every worker updates its own slot
328#[derive(Debug)]
329#[repr(align(64))]
330pub(crate) struct WorkerSlot {
331    epoch: Instant,
332    items: AtomicU64,
333    active: AtomicUsize,
334    not_ready: Period,
335    restarts: AtomicU64,
336    io: Arc<IoMetricsGroup>,
337    page_cache: Arc<PageCacheMetrics>,
338    runtime: Mutex<RuntimeSlot>,
339}
340
341/// Runtime of the worker and the totals of the runtimes it replaced.
342#[derive(Debug, Default)]
343struct RuntimeSlot {
344    arbiter: Option<Arbiter>,
345    base: RuntimeTotals,
346}
347
348#[derive(Debug, Default)]
349struct RuntimeTotals {
350    busy: Duration,
351    polls: u64,
352    polls_again: u64,
353    self_wakes: u64,
354    poll_histogram: Histogram,
355    latency_histogram: Histogram,
356    stalls: u64,
357    stall_duration: Duration,
358}
359
360impl RuntimeTotals {
361    fn add(&mut self, m: &RuntimeMetrics) {
362        self.busy += m.busy_duration.unwrap_or_default();
363        self.polls += m.polls.unwrap_or_default();
364        self.polls_again += m.polls_again.unwrap_or_default();
365        self.self_wakes += m.self_wakes.unwrap_or_default();
366        if let Some(ref h) = m.poll_histogram {
367            self.poll_histogram = self.poll_histogram.merge(h);
368        }
369        if let Some(ref l) = m.latency {
370            self.latency_histogram = self.latency_histogram.merge(&l.histogram);
371            self.stalls += l.stalls;
372            self.stall_duration += l.stall_duration;
373        }
374    }
375}
376
377fn runtime_metrics(arb: &Arbiter) -> RuntimeMetrics {
378    let hnd = arb.handle();
379    RuntimeMetrics {
380        busy_duration: hnd.busy_duration(),
381        polls: hnd.poll_count(),
382        polls_again: hnd.poll_again_count(),
383        self_wakes: hnd.self_wake_count(),
384        poll_histogram: hnd.poll_histogram(),
385        current_turn: hnd.current_turn(),
386        current_task: hnd.current_task(),
387        latency: arb.latency(),
388    }
389}
390
391thread_local! {
392    static CURRENT_WORKER: RefCell<Option<Arc<WorkerSlot>>> = const { RefCell::new(None) };
393}
394
395impl WorkerSlot {
396    fn new(epoch: Instant) -> Self {
397        Self {
398            epoch,
399            items: AtomicU64::new(0),
400            active: AtomicUsize::new(0),
401            not_ready: Period::default(),
402            restarts: AtomicU64::new(0),
403            io: IoMetricsGroup::new(),
404            page_cache: PageCacheMetrics::new(),
405            runtime: Mutex::default(),
406        }
407    }
408
409    /// Sets the arbiter the worker runs on, the totals of the previous
410    /// arbiter are kept.
411    pub(crate) fn set_arbiter(&self, arbiter: Arbiter) {
412        let mut rt = self.runtime.lock();
413        if let Some(prev) = rt.arbiter.replace(arbiter) {
414            let m = runtime_metrics(&prev);
415            rt.base.add(&m);
416        }
417    }
418
419    fn runtime_metrics(&self) -> RuntimeMetrics {
420        let rt = self.runtime.lock();
421        let Some(ref arb) = rt.arbiter else {
422            return RuntimeMetrics::default();
423        };
424        let base = &rt.base;
425        let mut m = runtime_metrics(arb);
426        m.busy_duration = m.busy_duration.map(|d| d + base.busy);
427        m.polls = m.polls.map(|n| n + base.polls);
428        m.polls_again = m.polls_again.map(|n| n + base.polls_again);
429        m.self_wakes = m.self_wakes.map(|n| n + base.self_wakes);
430        m.poll_histogram = m.poll_histogram.map(|h| h.merge(&base.poll_histogram));
431        if let Some(ref mut l) = m.latency {
432            l.histogram = l.histogram.merge(&base.latency_histogram);
433            l.stalls += base.stalls;
434            l.stall_duration += base.stall_duration;
435        }
436        m
437    }
438
439    /// Metrics slot of the worker running on the current thread.
440    pub(crate) fn current() -> Option<Arc<WorkerSlot>> {
441        CURRENT_WORKER.with(|w| w.borrow().clone())
442    }
443
444    /// Installs the slot for the current thread, connections created on the
445    /// thread afterwards report I/O statistics to the slot, the thread's page
446    /// cache reports to the slot.
447    pub(crate) fn set_current(slot: Option<Arc<WorkerSlot>>) {
448        if let Some(ref slot) = slot {
449            IoMetricsGroup::set_current(slot.io.clone());
450            PageCacheMetrics::set_current(slot.page_cache.clone());
451        }
452        CURRENT_WORKER.with(|w| *w.borrow_mut() = slot);
453    }
454
455    pub(crate) fn item(&self) {
456        self.items.fetch_add(1, Ordering::Relaxed);
457    }
458
459    pub(crate) fn ready(&self, ready: bool) {
460        self.not_ready.set(self.epoch, !ready);
461    }
462
463    pub(crate) fn restart(&self) {
464        self.restarts.fetch_add(1, Ordering::Relaxed);
465    }
466
467    pub(crate) fn active(&self) -> usize {
468        self.active.load(Ordering::Relaxed)
469    }
470
471    pub(crate) fn conn_opened(&self) {
472        self.active.fetch_add(1, Ordering::Relaxed);
473    }
474
475    pub(crate) fn conn_closed(&self) {
476        self.active.fetch_sub(1, Ordering::Relaxed);
477    }
478}
479
480#[derive(Debug)]
481pub(crate) struct AcceptSlot {
482    epoch: Instant,
483    listeners: Box<[ListenerSlot]>,
484    paused: Period,
485    /// Number of paused accept threads, also serializes `paused` updates.
486    paused_loops: Mutex<usize>,
487    backlog: AtomicUsize,
488}
489
490#[derive(Debug, Default)]
491struct ListenerSlot {
492    name: String,
493    addr: String,
494    accepted: AtomicU64,
495    connection_errors: AtomicU64,
496    resource_errors: AtomicU64,
497}
498
499impl AcceptSlot {
500    /// Reports that one accept thread paused or resumed.
501    ///
502    /// The accept loop is paused while any of its threads is paused. Every
503    /// thread reports a resume only after a pause.
504    pub(crate) fn paused(&self, paused: bool) {
505        let mut loops = self.paused_loops.lock();
506        if paused {
507            *loops += 1;
508        } else {
509            debug_assert!(*loops > 0);
510            *loops = loops.saturating_sub(1);
511        }
512        self.paused.set(self.epoch, *loops > 0);
513    }
514
515    /// Updates the backlog of one accept thread from `prev` to `len`.
516    ///
517    /// The metric is the sum of the backlogs of all accept threads.
518    pub(crate) fn backlog(&self, prev: usize, len: usize) {
519        if len > prev {
520            self.backlog.fetch_add(len - prev, Ordering::Relaxed);
521        } else {
522            self.backlog.fetch_sub(prev - len, Ordering::Relaxed);
523        }
524    }
525
526    pub(crate) fn accepted(&self, idx: usize) {
527        if let Some(l) = self.listeners.get(idx) {
528            l.accepted.fetch_add(1, Ordering::Relaxed);
529        }
530    }
531
532    pub(crate) fn connection_error(&self, idx: usize) {
533        if let Some(l) = self.listeners.get(idx) {
534            l.connection_errors.fetch_add(1, Ordering::Relaxed);
535        }
536    }
537
538    pub(crate) fn resource_error(&self, idx: usize) {
539        if let Some(l) = self.listeners.get(idx) {
540            l.resource_errors.fetch_add(1, Ordering::Relaxed);
541        }
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use std::sync::atomic::AtomicBool;
548
549    use super::*;
550
551    /// STATEMENT: `Period` counts distinct periods and their total time, ignoring repeated
552    /// state changes.
553    ///
554    /// HOW:
555    /// - Expect no periods at first.
556    /// - Start twice and wait 10 ms; expect one period of at least 10 ms so far.
557    /// - End twice; expect one period whose total no longer grows.
558    /// - Start again; expect 2 periods.
559    #[test]
560    fn period() {
561        let epoch = Instant::now();
562        let p = Period::default();
563        assert_eq!(p.get(epoch), (0, Duration::ZERO));
564
565        p.set(epoch, true);
566        p.set(epoch, true);
567        std::thread::sleep(Duration::from_millis(10));
568        let (cnt, cur) = p.get(epoch);
569        assert_eq!(cnt, 1);
570        assert!(cur >= Duration::from_millis(10));
571
572        p.set(epoch, false);
573        p.set(epoch, false);
574        let (cnt, total) = p.get(epoch);
575        assert_eq!(cnt, 1);
576        assert!(total >= cur);
577        std::thread::sleep(Duration::from_millis(5));
578        assert_eq!(p.get(epoch), (1, total));
579
580        p.set(epoch, true);
581        assert_eq!(p.get(epoch).0, 2);
582    }
583
584    /// STATEMENT: Readers of a `Period` see a total that never decreases and never exceeds the
585    /// elapsed time while a writer toggles it.
586    ///
587    /// HOW:
588    /// - Start and end periods of about 20 µs in a loop on a writer thread.
589    /// - Read it for 500 ms; expect a total that never drops and stays within the uptime.
590    #[test]
591    fn period_is_coherent() {
592        let epoch = Instant::now();
593        let p = Arc::new(Period::default());
594        let stop = Arc::new(AtomicBool::new(false));
595        let writer = {
596            let (p, stop) = (p.clone(), stop.clone());
597            std::thread::spawn(move || {
598                while !stop.load(Ordering::Relaxed) {
599                    p.set(epoch, true);
600                    let start = Instant::now();
601                    while start.elapsed() < Duration::from_micros(20) {}
602                    p.set(epoch, false);
603                }
604            })
605        };
606        let deadline = Instant::now() + Duration::from_millis(500);
607        let mut prev = Duration::ZERO;
608        while Instant::now() < deadline {
609            let (_, total) = p.get(epoch);
610            // a completed period is not counted twice
611            assert!(total >= prev, "{total:?} < {prev:?}");
612            prev = total;
613            // periods do not overlap, the writer is almost always in one
614            let uptime = epoch.elapsed();
615            assert!(total <= uptime, "{total:?} > {uptime:?}");
616        }
617        stop.store(true, Ordering::Relaxed);
618        writer.join().unwrap();
619    }
620
621    /// STATEMENT: A metrics snapshot reports worker and listener counters, and keeps the first
622    /// listener registration.
623    ///
624    /// HOW:
625    /// - Record items, connections and a restart on worker 1; expect no worker 2.
626    /// - Record accept events on listener 0, an error on a missing listener, and a backlog;
627    ///   register listeners twice.
628    /// - Expect default worker 0, the worker 1 counts, one listener with its name, address and
629    ///   counts, the backlog and no pauses.
630    #[test]
631    fn snapshot() {
632        let m = Metrics::new(2);
633        let w = m.worker(WorkerId(1)).unwrap();
634        assert!(m.worker(WorkerId(2)).is_none());
635        w.item();
636        w.item();
637        w.conn_opened();
638        w.conn_opened();
639        w.conn_closed();
640        w.restart();
641
642        let acc = m.listeners([("srv".to_string(), "127.0.0.1:1".to_string())]);
643        acc.accepted(0);
644        acc.connection_error(0);
645        acc.resource_error(0);
646        acc.resource_error(1);
647        acc.backlog(0, 3);
648        // the first registration wins
649        m.listeners([]);
650
651        let s = m.snapshot();
652        assert_eq!(s.workers.len(), 2);
653        assert_eq!(s.workers[0], WorkerMetrics::default());
654        assert_eq!(s.workers[1].id, WorkerId(1));
655        assert_eq!(s.workers[1].items, 2);
656        assert_eq!(s.workers[1].active_connections, 1);
657        assert_eq!(s.workers[1].restarts, 1);
658        assert_eq!(s.listeners.len(), 1);
659        assert_eq!(s.listeners[0].name, "srv");
660        assert_eq!(s.listeners[0].addr, "127.0.0.1:1");
661        assert_eq!(s.listeners[0].accepted, 1);
662        assert_eq!(s.listeners[0].connection_errors, 1);
663        assert_eq!(s.listeners[0].resource_errors, 1);
664        assert_eq!(s.accept_backlog, 3);
665        assert_eq!(s.accept_pauses, 0);
666    }
667
668    /// STATEMENT: Worker runtime metrics keep their totals when the worker's arbiter is
669    /// replaced.
670    ///
671    /// HOW:
672    /// - Expect default metrics before an arbiter is set.
673    /// - Keep a first arbiter busy for 20 ms; expect busy time and latency samples.
674    /// - Replace it and keep the new one busy; expect busy time, latency samples and polls
675    ///   (when available) to grow from the first totals.
676    #[ntex::test]
677    async fn runtime_restart() {
678        let busy = |a: &Arbiter| {
679            a.handle().spawn(async {
680                std::thread::sleep(Duration::from_millis(20));
681            });
682        };
683
684        let m = Metrics::new(1);
685        let w = m.worker(WorkerId(0)).unwrap();
686        assert_eq!(w.runtime_metrics(), RuntimeMetrics::default());
687
688        let a1 = Arbiter::with_name("rt-metrics-1".to_string());
689        w.set_arbiter(a1.clone());
690        busy(&a1);
691        ntex::time::sleep(ntex::time::Millis(250)).await;
692        let m1 = w.runtime_metrics();
693        let b1 = m1.busy_duration.unwrap();
694        let l1 = m1.latency.clone().unwrap().histogram.count();
695        assert!(b1 >= Duration::from_millis(20));
696        assert!(l1 > 0);
697        a1.stop();
698
699        let a2 = Arbiter::with_name("rt-metrics-2".to_string());
700        w.set_arbiter(a2.clone());
701        busy(&a2);
702        ntex::time::sleep(ntex::time::Millis(250)).await;
703        let m2 = w.runtime_metrics();
704        assert!(m2.busy_duration.unwrap() >= b1 + Duration::from_millis(20));
705        assert!(m2.latency.unwrap().histogram.count() > l1);
706        if let (Some(p1), Some(p2)) = (m1.polls, m2.polls) {
707            assert!(p2 > p1);
708        }
709        a2.stop();
710    }
711}