Skip to main content

ntex_io/
metrics.rs

1//! I/O load statistics.
2use std::sync::atomic::{
3    AtomicU64, AtomicUsize, Ordering::Acquire, Ordering::Relaxed, Ordering::Release, fence,
4};
5use std::sync::{Arc, Mutex, PoisonError};
6use std::{cell::RefCell, collections::HashMap, time::Duration, time::Instant};
7
8use crate::IoConfig;
9
10thread_local! {
11    static CURRENT: RefCell<Option<Current>> = const { RefCell::new(None) };
12    static DETACHED: Arc<IoMetrics> = IoMetrics::new();
13}
14
15/// I/O metrics of one thread, one [`IoMetrics`] per opted-in [`IoConfig`].
16///
17/// A connection reports to the metrics of its configuration in the group that
18/// was current on its thread when it was created, see
19/// [`IoMetricsGroup::current`] and [`IoConfig::metrics`]. Connections created
20/// with the same configuration on the thread share the metrics, for example
21/// all connections accepted by one server listener on one worker.
22///
23/// A configuration has its own metrics if it was registered in the group with
24/// [`IoMetricsGroup::register`] or enabled with
25/// [`IoConfig::set_metrics`](crate::IoConfig::set_metrics). Connections of
26/// other configurations report to the group's shared
27/// [`other`](IoMetricsGroup::other) metrics. Metrics are kept for the lifetime
28/// of the group.
29#[derive(Debug)]
30pub struct IoMetricsGroup {
31    configs: Mutex<HashMap<usize, Entry>>,
32    other: Arc<IoMetrics>,
33    /// Incremented by each registration, invalidates the thread caches.
34    generation: AtomicU64,
35}
36
37#[derive(Debug)]
38struct Entry {
39    tag: &'static str,
40    service: &'static str,
41    metrics: Arc<IoMetrics>,
42}
43
44/// The current thread's group and its configurations with own metrics, the
45/// group's lock is taken when a configuration with metrics enabled is first
46/// used on the thread, and once after each registration in the group.
47/// Configurations without own metrics are not cached, they map to `other`.
48struct Current {
49    group: Arc<IoMetricsGroup>,
50    cache: HashMap<usize, Arc<IoMetrics>>,
51    /// Generation of the group when the cache was filled.
52    generation: u64,
53}
54
55impl Current {
56    fn new(group: Arc<IoMetricsGroup>) -> Self {
57        let mut c = Current {
58            generation: 0,
59            group,
60            cache: HashMap::new(),
61        };
62        c.fill();
63        c
64    }
65
66    /// Refills the cache if configurations were registered since it was
67    /// filled.
68    fn refresh(&mut self) {
69        if self.group.generation.load(Acquire) != self.generation {
70            self.fill();
71        }
72    }
73
74    fn fill(&mut self) {
75        self.generation = self.group.generation.load(Acquire);
76        self.cache = self
77            .group
78            .configs
79            .lock()
80            .unwrap_or_else(PoisonError::into_inner)
81            .iter()
82            .map(|(id, e)| (*id, e.metrics.clone()))
83            .collect();
84    }
85}
86
87/// A snapshot of the metrics of one configuration in an [`IoMetricsGroup`].
88#[derive(Copy, Clone, Debug, PartialEq, Eq)]
89#[non_exhaustive]
90pub struct IoConfigMetrics {
91    /// Id of the shared configuration, see `SharedCfg::id()`.
92    pub id: usize,
93    /// Tag of the shared configuration.
94    pub tag: &'static str,
95    /// Service name of the shared configuration.
96    pub service: &'static str,
97    /// I/O statistics of the configuration's connections.
98    pub io: IoMetricsSnapshot,
99}
100
101impl IoMetricsGroup {
102    /// Creates an empty group.
103    pub fn new() -> Arc<Self> {
104        Arc::new(IoMetricsGroup {
105            configs: Mutex::default(),
106            other: IoMetrics::new(),
107            generation: AtomicU64::new(0),
108        })
109    }
110
111    /// Returns the group of the current thread.
112    ///
113    /// Each thread has its own group, created on first use, unless another
114    /// group was installed with [`IoMetricsGroup::set_current`].
115    pub fn current() -> Arc<Self> {
116        CURRENT
117            .try_with(|c| {
118                c.borrow_mut()
119                    .get_or_insert_with(|| Current::new(IoMetricsGroup::new()))
120                    .group
121                    .clone()
122            })
123            .unwrap_or_else(|_| IoMetricsGroup::new())
124    }
125
126    /// Returns the metrics of `cfg` in the current thread's group.
127    pub(crate) fn current_metrics(cfg: &IoConfig) -> Arc<IoMetrics> {
128        CURRENT
129            .try_with(|c| {
130                let mut c = c.borrow_mut();
131                let c = c.get_or_insert_with(|| Current::new(IoMetricsGroup::new()));
132                // a configuration may have been registered on another thread
133                c.refresh();
134                if let Some(m) = c.cache.get(&cfg.config.id()) {
135                    m.clone()
136                } else if cfg.metrics_enabled() {
137                    let m = c.group.entry(cfg);
138                    c.cache.insert(cfg.config.id(), m.clone());
139                    m
140                } else {
141                    c.group.other.clone()
142                }
143            })
144            .unwrap_or_else(|_| IoMetricsGroup::new().get(cfg))
145    }
146
147    /// Installs `group` as the current thread's group.
148    ///
149    /// Connections created afterwards on this thread report to `group`,
150    /// existing connections keep reporting to the previous one.
151    ///
152    /// The byte and write counters of [`IoMetrics`] are single-writer, install
153    /// a group on one thread at a time.
154    pub fn set_current(group: Arc<Self>) {
155        let _ = CURRENT.try_with(|c| *c.borrow_mut() = Some(Current::new(group)));
156    }
157
158    /// Gives `cfg` its own metrics in this group.
159    ///
160    /// Connections created afterwards with `cfg`, on any thread whose current
161    /// group this is, report to these metrics instead of the shared
162    /// [`other`](Self::other) metrics.
163    pub fn register(&self, cfg: &IoConfig) {
164        let _ = self.entry(cfg);
165        // threads refill their caches on the next lookup
166        self.generation.fetch_add(1, Release);
167    }
168
169    /// Returns the metrics `cfg` reports to.
170    ///
171    /// These are the configuration's own metrics if it is registered or has
172    /// metrics enabled, and the shared [`other`](Self::other) metrics
173    /// otherwise.
174    pub fn get(&self, cfg: &IoConfig) -> Arc<IoMetrics> {
175        if cfg.metrics_enabled() {
176            self.entry(cfg)
177        } else {
178            self.configs
179                .lock()
180                .unwrap_or_else(PoisonError::into_inner)
181                .get(&cfg.config.id())
182                .map_or_else(|| self.other.clone(), |e| e.metrics.clone())
183        }
184    }
185
186    /// Returns the metrics of connections whose configuration has no metrics
187    /// of its own.
188    pub fn other(&self) -> &Arc<IoMetrics> {
189        &self.other
190    }
191
192    fn entry(&self, cfg: &IoConfig) -> Arc<IoMetrics> {
193        let ctx = &cfg.config;
194        self.configs
195            .lock()
196            .unwrap_or_else(PoisonError::into_inner)
197            .entry(ctx.id())
198            .or_insert_with(|| Entry {
199                tag: ctx.tag(),
200                service: ctx.service(),
201                metrics: IoMetrics::new(),
202            })
203            .metrics
204            .clone()
205    }
206
207    /// Returns snapshots of the metrics of configurations with their own
208    /// metrics, ordered by configuration id. See [`other`](Self::other) for
209    /// the remaining connections.
210    pub fn snapshot(&self) -> Vec<IoConfigMetrics> {
211        let mut items: Vec<_> = self
212            .configs
213            .lock()
214            .unwrap_or_else(PoisonError::into_inner)
215            .iter()
216            .map(|(id, e)| IoConfigMetrics {
217                id: *id,
218                tag: e.tag,
219                service: e.service,
220                io: e.metrics.snapshot(),
221            })
222            .collect();
223        items.sort_unstable_by_key(|m| m.id);
224        items
225    }
226}
227
228/// I/O load statistics shared by connections.
229///
230/// Metrics belong to a configuration in an [`IoMetricsGroup`], see
231/// [`IoConfig::metrics`]. Statistics are updated with relaxed atomics, a
232/// snapshot is not a consistent cut across all fields.
233///
234/// The byte and write counters (`bytes_read`, `bytes_written`, `eager_writes`,
235/// `eager_writes_partial`, `scheduled_writes`) are updated with a plain load
236/// and store, not an atomic read-modify-write, so they must be updated by one
237/// thread at a time. If the same group is installed on several threads with
238/// [`IoMetricsGroup::set_current`], concurrent updates can be lost and these
239/// counters undercount. The other statistics stay exact.
240#[derive(Debug)]
241pub struct IoMetrics {
242    base: Instant,
243    rd: Backpressure,
244    wr: Backpressure,
245    read_buffered: AtomicUsize,
246    /// `read_buffers_held` in the bits above `HELD_SHIFT`, and
247    /// `read_buffer_capacity` below it, so both change with one update.
248    read_buffers: AtomicU64,
249    write_buffered: AtomicUsize,
250    bytes_read: AtomicU64,
251    bytes_written: AtomicU64,
252    eager_writes: AtomicU64,
253    eager_writes_partial: AtomicU64,
254    scheduled_writes: AtomicU64,
255    closed: [AtomicU64; CLOSE_REASONS],
256}
257
258const CLOSE_REASONS: usize = 18;
259
260/// Packing of `IoMetrics::read_buffers`, it counts up to 2^24 (16M) held read
261/// buffers with up to 1 TiB of capacity.
262const HELD_SHIFT: u32 = 40;
263const CAPACITY_MASK: u64 = (1 << HELD_SHIFT) - 1;
264
265/// Reason a connection was closed.
266///
267/// Protocol dispatchers report it with
268/// [`IoRef::set_close_reason`](crate::IoRef::set_close_reason), the first
269/// reported reason is kept. It is counted in [`IoMetrics`] when the connection
270/// state is released.
271///
272/// Applications can count their own reasons with `Custom1` to `Custom8`. Set
273/// the reason before closing the connection or failing the service, a reason
274/// reported by the dispatcher is not replaced.
275#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
276#[non_exhaustive]
277pub enum CloseReason {
278    /// The connection was idle for longer than the keep-alive timeout.
279    KeepAlive,
280    /// Input did not arrive within the read timeout.
281    ReadTimeout,
282    /// Write backpressure stayed enabled for longer than the write timeout.
283    WriteTimeout,
284    /// The peer closed the connection.
285    PeerGone,
286    /// The transport failed with an I/O error.
287    Io,
288    /// Incoming data could not be decoded.
289    Decoder,
290    /// Outgoing data could not be encoded.
291    Encoder,
292    /// The service failed or closed the connection.
293    Service,
294    /// The server is shutting down.
295    Shutdown,
296    /// Application-defined reason, counted in `CloseStats::custom[0]`.
297    Custom1,
298    /// Application-defined reason, counted in `CloseStats::custom[1]`.
299    Custom2,
300    /// Application-defined reason, counted in `CloseStats::custom[2]`.
301    Custom3,
302    /// Application-defined reason, counted in `CloseStats::custom[3]`.
303    Custom4,
304    /// Application-defined reason, counted in `CloseStats::custom[4]`.
305    Custom5,
306    /// Application-defined reason, counted in `CloseStats::custom[5]`.
307    Custom6,
308    /// Application-defined reason, counted in `CloseStats::custom[6]`.
309    Custom7,
310    /// Application-defined reason, counted in `CloseStats::custom[7]`.
311    Custom8,
312}
313
314impl CloseReason {
315    fn index(self) -> usize {
316        match self {
317            CloseReason::KeepAlive => 0,
318            CloseReason::ReadTimeout => 1,
319            CloseReason::WriteTimeout => 2,
320            CloseReason::PeerGone => 3,
321            CloseReason::Io => 4,
322            CloseReason::Decoder => 5,
323            CloseReason::Encoder => 6,
324            CloseReason::Service => 7,
325            CloseReason::Shutdown => 8,
326            CloseReason::Custom1 => 9,
327            CloseReason::Custom2 => 10,
328            CloseReason::Custom3 => 11,
329            CloseReason::Custom4 => 12,
330            CloseReason::Custom5 => 13,
331            CloseReason::Custom6 => 14,
332            CloseReason::Custom7 => 15,
333            CloseReason::Custom8 => 16,
334        }
335    }
336}
337
338// connections closed without a reported reason or I/O error
339const CLOSE_OTHER: usize = 17;
340
341/// Closed connections by [`CloseReason`].
342#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
343#[non_exhaustive]
344pub struct CloseStats {
345    /// Closed connections.
346    pub total: u64,
347    /// Closed by the keep-alive timeout.
348    pub keepalive: u64,
349    /// Closed by the read timeout.
350    pub read_timeout: u64,
351    /// Closed by the write timeout.
352    pub write_timeout: u64,
353    /// Closed by the peer.
354    pub peer_gone: u64,
355    /// Closed by an I/O error, reported or not.
356    pub io: u64,
357    /// Closed because incoming data could not be decoded.
358    pub decoder: u64,
359    /// Closed because outgoing data could not be encoded.
360    pub encoder: u64,
361    /// Closed by the service.
362    pub service: u64,
363    /// Closed by server shutdown.
364    pub shutdown: u64,
365    /// Closed by application-defined reasons, `custom[0]` counts
366    /// [`CloseReason::Custom1`] and so on.
367    pub custom: [u64; 8],
368    /// Closed without a reported reason, e.g. by the application.
369    pub other: u64,
370}
371
372/// Backpressure statistics of one direction.
373///
374/// The connection-time under backpressure is the sum of all ended periods
375/// plus the open ones. Each period adds its start to `starts` and its end to
376/// `ends`, so the total at time `now` is `ends - starts + active * now`,
377/// without any per-connection state. Times are nanoseconds since `base`.
378///
379/// The fields are updated under a sequence lock, readers retry until they
380/// read the fields of one version, without blocking writers. Writers to the
381/// same metrics on several threads take turns.
382#[derive(Debug, Default)]
383struct Backpressure {
384    seq: AtomicU64,
385    count: AtomicU64,
386    active: AtomicUsize,
387    starts: AtomicU64,
388    ends: AtomicU64,
389}
390
391/// A snapshot of [`IoMetrics`].
392#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
393#[non_exhaustive]
394pub struct IoMetricsSnapshot {
395    /// Number of times read backpressure was enabled.
396    pub read_backpressure: u64,
397    /// Number of times write backpressure was enabled.
398    pub write_backpressure: u64,
399    /// Connections with read backpressure enabled.
400    pub read_backpressure_active: usize,
401    /// Connections with write backpressure enabled.
402    pub write_backpressure_active: usize,
403    /// Total connection-time spent under read backpressure.
404    pub read_backpressure_time: Duration,
405    /// Total connection-time spent under write backpressure.
406    pub write_backpressure_time: Duration,
407    /// Bytes held in read buffers.
408    pub read_buffered: usize,
409    /// Connections that keep a read buffer allocated.
410    ///
411    /// Read buffers are released once their input is consumed, so a
412    /// connection is counted while it holds unconsumed input, such as the
413    /// start of a frame that has not fully arrived. A snapshot mostly counts
414    /// idle connections waiting for the rest of their input, busy ones are
415    /// only briefly counted. A buffer a transport holds for a pending read,
416    /// as with io-uring, is not counted.
417    pub read_buffers_held: usize,
418    /// Bytes allocated by the read buffers of
419    /// [`read_buffers_held`](Self::read_buffers_held), a whole page for a
420    /// pooled buffer.
421    ///
422    /// Compared with [`read_buffered`](Self::read_buffered) it shows the
423    /// memory kept for small leftover input. Frames split off a read buffer
424    /// share its allocation and can keep it alive after it is released, that
425    /// memory is not counted.
426    pub read_buffer_capacity: usize,
427    /// Bytes held in write buffers or taken by the transport but not written.
428    pub write_buffered: usize,
429    /// Bytes read from transports.
430    pub bytes_read: u64,
431    /// Bytes written to transports.
432    pub bytes_written: u64,
433    /// Writes started in place because buffered output reached the write
434    /// buffer threshold, see `IoConfig::set_write_buf_threshold()`.
435    pub eager_writes: u64,
436    /// Eager writes that could not write all buffered output, the rest is
437    /// left to the write task.
438    pub eager_writes_partial: u64,
439    /// Writes left to the write task, below the write buffer threshold or with
440    /// eager writes disabled. The io-uring transport always uses the write
441    /// task.
442    pub scheduled_writes: u64,
443    /// Closed connections by reason.
444    pub closed: CloseStats,
445}
446
447impl IoMetrics {
448    pub(crate) fn new() -> Arc<Self> {
449        Arc::new(IoMetrics {
450            base: Instant::now(),
451            rd: Backpressure::default(),
452            wr: Backpressure::default(),
453            read_buffered: AtomicUsize::new(0),
454            read_buffers: AtomicU64::new(0),
455            write_buffered: AtomicUsize::new(0),
456            bytes_read: AtomicU64::new(0),
457            bytes_written: AtomicU64::new(0),
458            eager_writes: AtomicU64::new(0),
459            eager_writes_partial: AtomicU64::new(0),
460            scheduled_writes: AtomicU64::new(0),
461            closed: Default::default(),
462        })
463    }
464
465    /// Metrics not in any group, for placeholder connection states.
466    pub(crate) fn detached() -> Arc<Self> {
467        DETACHED
468            .try_with(Clone::clone)
469            .unwrap_or_else(|_| IoMetrics::new())
470    }
471
472    /// Returns a snapshot of the statistics.
473    pub fn snapshot(&self) -> IoMetricsSnapshot {
474        let (read_backpressure, read_backpressure_active, read_backpressure_time) =
475            self.rd.read(self.base);
476        let (write_backpressure, write_backpressure_active, write_backpressure_time) =
477            self.wr.read(self.base);
478        let read_buffers = self.read_buffers.load(Relaxed);
479        IoMetricsSnapshot {
480            read_backpressure,
481            write_backpressure,
482            read_backpressure_active,
483            write_backpressure_active,
484            read_backpressure_time,
485            write_backpressure_time,
486            read_buffered: self.read_buffered.load(Relaxed),
487            read_buffers_held: (read_buffers >> HELD_SHIFT) as usize,
488            read_buffer_capacity: (read_buffers & CAPACITY_MASK) as usize,
489            write_buffered: self.write_buffered.load(Relaxed),
490            bytes_read: self.bytes_read.load(Relaxed),
491            bytes_written: self.bytes_written.load(Relaxed),
492            eager_writes: self.eager_writes.load(Relaxed),
493            eager_writes_partial: self.eager_writes_partial.load(Relaxed),
494            scheduled_writes: self.scheduled_writes.load(Relaxed),
495            closed: self.close_stats(),
496        }
497    }
498
499    fn close_stats(&self) -> CloseStats {
500        let c: [u64; CLOSE_REASONS] = std::array::from_fn(|i| self.closed[i].load(Relaxed));
501        CloseStats {
502            total: c.iter().sum(),
503            keepalive: c[CloseReason::KeepAlive.index()],
504            read_timeout: c[CloseReason::ReadTimeout.index()],
505            write_timeout: c[CloseReason::WriteTimeout.index()],
506            peer_gone: c[CloseReason::PeerGone.index()],
507            io: c[CloseReason::Io.index()],
508            decoder: c[CloseReason::Decoder.index()],
509            encoder: c[CloseReason::Encoder.index()],
510            service: c[CloseReason::Service.index()],
511            shutdown: c[CloseReason::Shutdown.index()],
512            custom: std::array::from_fn(|i| c[CloseReason::Custom1.index() + i]),
513            other: c[CLOSE_OTHER],
514        }
515    }
516
517    /// Counts a closed connection.
518    pub(crate) fn closed(&self, reason: Option<CloseReason>, io_error: bool) {
519        let idx = match reason {
520            Some(r) => r.index(),
521            None if io_error => CloseReason::Io.index(),
522            None => CLOSE_OTHER,
523        };
524        self.closed[idx].fetch_add(1, Relaxed);
525    }
526
527    fn now(&self) -> u64 {
528        nanos(self.base, ntex_rt::now())
529    }
530
531    pub(crate) fn rd_backpressure_on(&self) {
532        self.rd.on(self.now());
533    }
534
535    pub(crate) fn rd_backpressure_off(&self) {
536        self.rd.off(self.now());
537    }
538
539    pub(crate) fn wr_backpressure_on(&self) {
540        self.wr.on(self.now());
541    }
542
543    pub(crate) fn wr_backpressure_off(&self) {
544        self.wr.off(self.now());
545    }
546
547    /// Moves a connection's gauges from `self` to `to`, e.g. after the
548    /// connection's configuration was replaced. Counters stay.
549    pub(crate) fn move_to(
550        &self,
551        to: &IoMetrics,
552        rd_bp: bool,
553        wr_bp: bool,
554        rd: u32,
555        rd_cap: u32,
556        wr: u32,
557    ) {
558        if rd_bp {
559            self.rd.off(self.now());
560            to.rd.resume(to.now());
561        }
562        if wr_bp {
563            self.wr.off(self.now());
564            to.wr.resume(to.now());
565        }
566        self.update_read_buffered(rd, 0, rd_cap, 0);
567        to.update_read_buffered(0, rd, 0, rd_cap);
568        self.update_write_buffered(wr, 0);
569        to.update_write_buffered(0, wr);
570    }
571
572    pub(crate) fn read(&self, n: usize) {
573        inc(&self.bytes_read, n as u64);
574    }
575
576    pub(crate) fn written(&self, n: usize) {
577        inc(&self.bytes_written, n as u64);
578    }
579
580    pub(crate) fn eager_write(&self, partial: bool) {
581        inc(&self.eager_writes, 1);
582        if partial {
583            inc(&self.eager_writes_partial, 1);
584        }
585    }
586
587    pub(crate) fn scheduled_write(&self) {
588        inc(&self.scheduled_writes, 1);
589    }
590
591    /// Updates the read buffer gauges of a connection, `cap` is the retained
592    /// capacity, a connection with capacity holds a read buffer.
593    pub(crate) fn update_read_buffered(&self, prev: u32, cur: u32, prev_cap: u32, cap: u32) {
594        update(&self.read_buffered, prev, cur);
595
596        // A connection's packed contribution never goes below zero, so a
597        // wrapping delta updates both fields of the total without borrowing
598        // from or carrying into the other one.
599        let packed = |cap: u32| (u64::from(cap > 0) << HELD_SHIFT) | u64::from(cap);
600        let (prev, cur) = (packed(prev_cap), packed(cap));
601        if cur != prev {
602            self.read_buffers.fetch_add(cur.wrapping_sub(prev), Relaxed);
603        }
604    }
605
606    pub(crate) fn update_write_buffered(&self, prev: u32, cur: u32) {
607        update(&self.write_buffered, prev, cur);
608    }
609}
610
611fn update(gauge: &AtomicUsize, prev: u32, cur: u32) {
612    if cur > prev {
613        gauge.fetch_add((cur - prev) as usize, Relaxed);
614    } else if cur < prev {
615        gauge.fetch_sub((prev - cur) as usize, Relaxed);
616    }
617}
618
619impl Backpressure {
620    fn on(&self, now: u64) {
621        self.write(|| {
622            inc(&self.count, 1);
623            self.start(now);
624        });
625    }
626
627    // continues a period started on other metrics, not counted again
628    fn resume(&self, now: u64) {
629        self.write(|| self.start(now));
630    }
631
632    fn off(&self, now: u64) {
633        self.write(|| {
634            inc(&self.ends, now);
635            let active = self.active.load(Relaxed);
636            self.active.store(active.wrapping_sub(1), Relaxed);
637        });
638    }
639
640    fn start(&self, now: u64) {
641        inc(&self.starts, now);
642        let active = self.active.load(Relaxed);
643        self.active.store(active.wrapping_add(1), Relaxed);
644    }
645
646    /// Updates the fields under the write lock, `seq` is odd while locked.
647    fn write(&self, f: impl FnOnce()) {
648        let mut seq = self.seq.load(Relaxed);
649        loop {
650            if seq & 1 == 0 {
651                match self
652                    .seq
653                    .compare_exchange_weak(seq, seq + 1, Acquire, Relaxed)
654                {
655                    Ok(_) => break,
656                    Err(s) => seq = s,
657                }
658            } else {
659                std::hint::spin_loop();
660                seq = self.seq.load(Relaxed);
661            }
662        }
663        // field stores are not visible before the odd `seq`
664        fence(Release);
665        f();
666        self.seq.store(seq.wrapping_add(2), Release);
667    }
668
669    /// Returns the count, active periods and total time at the current time,
670    /// read from one version of the fields.
671    fn read(&self, base: Instant) -> (u64, usize, Duration) {
672        loop {
673            let seq = self.seq.load(Acquire);
674            if seq & 1 == 0 {
675                let count = self.count.load(Relaxed);
676                let active = self.active.load(Relaxed);
677                let starts = self.starts.load(Relaxed);
678                let ends = self.ends.load(Relaxed);
679                fence(Acquire);
680                if self.seq.load(Relaxed) == seq {
681                    // after the acquire, not before the writer's times
682                    let now = nanos(base, Instant::now());
683                    let total = ends
684                        .wrapping_add((active as u64).wrapping_mul(now))
685                        .wrapping_sub(starts);
686                    // a writer's cached time may be ahead of `now`
687                    let total = if total > i64::MAX as u64 { 0 } else { total };
688                    return (count, active, Duration::from_nanos(total));
689                }
690            }
691            std::hint::spin_loop();
692        }
693    }
694}
695
696fn nanos(base: Instant, t: Instant) -> u64 {
697    u64::try_from(t.saturating_duration_since(base).as_nanos()).unwrap_or(u64::MAX)
698}
699
700// single writer, cheaper than `fetch_add`
701#[inline]
702fn inc(counter: &AtomicU64, n: u64) {
703    counter.store(counter.load(Relaxed).wrapping_add(n), Relaxed);
704}
705
706#[cfg(test)]
707mod tests {
708    use std::sync::atomic::AtomicBool;
709
710    use ntex_service::cfg::SharedCfg;
711
712    use super::*;
713
714    /// STATEMENT: Concurrent backpressure updates yield coherent duration and active-count snapshots.
715    ///
716    /// HOW:
717    /// - Toggle one connection's read backpressure on a worker while repeatedly taking snapshots.
718    /// - Check time never exceeds uptime, active count never exceeds one, and final activity is zero.
719    #[test]
720    fn backpressure_time_is_coherent() {
721        let m = IoMetrics::new();
722        let stop = Arc::new(AtomicBool::new(false));
723        let writer = {
724            let (m, stop) = (m.clone(), stop.clone());
725            std::thread::spawn(move || {
726                while !stop.load(Relaxed) {
727                    m.rd.on(nanos(m.base, Instant::now()));
728                    m.rd.off(nanos(m.base, Instant::now()));
729                }
730            })
731        };
732        let deadline = Instant::now() + Duration::from_millis(200);
733        while Instant::now() < deadline {
734            let s = m.snapshot();
735            // a single connection, its time is bounded by the metrics' uptime
736            let uptime = m.base.elapsed();
737            assert!(
738                s.read_backpressure_time <= uptime,
739                "{:?} > {uptime:?}",
740                s.read_backpressure_time
741            );
742            assert!(s.read_backpressure_active <= 1);
743        }
744        stop.store(true, Relaxed);
745        writer.join().unwrap();
746        let s = m.snapshot();
747        assert_eq!(s.read_backpressure_active, 0);
748        assert!(s.read_backpressure > 0);
749    }
750
751    /// STATEMENT: The packed read-buffer gauge keeps held count and capacity
752    /// apart when capacities shrink or exceed 32 bits in total.
753    ///
754    /// HOW:
755    /// - Give two connections `u32::MAX` capacity, then shrink one while both
756    ///   stay held.
757    /// - Release both and check `read_buffers_held` and `read_buffer_capacity`
758    ///   in each snapshot.
759    #[test]
760    #[cfg(target_pointer_width = "64")]
761    fn read_buffer_gauges_stay_separate() {
762        let m = IoMetrics::new();
763        let held = || {
764            let s = m.snapshot();
765            (s.read_buffers_held, s.read_buffer_capacity)
766        };
767        let max = u32::MAX as usize;
768
769        m.update_read_buffered(0, 0, 0, u32::MAX);
770        m.update_read_buffered(0, 0, 0, u32::MAX);
771        assert_eq!(held(), (2, 2 * max));
772
773        m.update_read_buffered(0, 0, u32::MAX, 16);
774        assert_eq!(held(), (2, max + 16));
775
776        m.update_read_buffered(0, 0, 16, 0);
777        assert_eq!(held(), (1, max));
778        m.update_read_buffered(0, 0, u32::MAX, 0);
779        assert_eq!(held(), (0, 0));
780    }
781
782    /// STATEMENT: Only registered configurations receive cached dedicated metrics.
783    ///
784    /// HOW:
785    /// - Register one server configuration and create 1,000 unregistered client configurations.
786    /// - Verify clients use the shared fallback, the server has dedicated metrics, and one cache entry remains.
787    #[test]
788    fn unregistered_configs_are_not_cached() {
789        let group = IoMetricsGroup::new();
790        IoMetricsGroup::set_current(group.clone());
791        let srv = SharedCfg::new("SRV").build();
792        group.register(&srv.get::<IoConfig>());
793
794        for _ in 0..1000 {
795            let cfg = SharedCfg::new("CLI").build();
796            assert!(Arc::ptr_eq(&cfg.get::<IoConfig>().metrics(), group.other()));
797        }
798        let srv_metrics = srv.get::<IoConfig>().metrics();
799        assert!(Arc::ptr_eq(
800            &srv_metrics,
801            &group.get(&srv.get::<IoConfig>())
802        ));
803        assert!(!Arc::ptr_eq(&srv_metrics, group.other()));
804        let cached = CURRENT.with(|c| c.borrow().as_ref().unwrap().cache.len());
805        assert_eq!(cached, 1);
806    }
807}