Skip to main content

moq_net/
stats.rs

1//! Traffic counter collection for moq-net sessions.
2//!
3//! This module only *collects*: build a [`Registry`], hand each session a
4//! tier-scoped [`Handle`] via [`Registry::tier`], and read the counters back
5//! with [`Registry::snapshot`] (host-level rollup, e.g. a `/metrics` scrape) or
6//! [`Registry::report`] (per-broadcast detail). Publishing the counters as MoQ
7//! broadcasts lives in the `moq-stats` crate, which drains a [`Registry`] on an
8//! interval and writes the JSON stats tracks.
9//!
10//! Traffic is bucketed by an arbitrary [`Tier`] label chosen by business logic
11//! (billing class, region, ...) and, within a tier, by broadcast path and
12//! [`Role`] (publisher = egress, subscriber = ingress). Connected sessions are
13//! tracked separately per (tier, root, label), counting presence regardless of
14//! whether any data flows. The label is a stats key the auth decider picks,
15//! independent of what the session may access; the empty label holds sessions
16//! without one. The root is the origin path the session is scoped to, so a
17//! publisher can show each root only its own sessions; rows that differ only by
18//! root share their label.
19//!
20//! # Where counting happens
21//!
22//! Counting lives in the model layer, not the wire loops. A session tags its
23//! origin pair with a [`Session`] context (`crate::Client::with_stats` /
24//! `crate::Server::with_stats`, which call `origin::{Consumer, Producer}`
25//! `with_stats`); every derived handle (broadcast, announce, track, group, frame)
26//! then attributes its reads (egress = publisher) and writes (ingress =
27//! subscriber) through that context. So any protocol that drives the model gets
28//! the full counter set for free, and an untagged handle pays nothing.
29//!
30//! Per-counter semantics:
31//!
32//! * `announces_started` / `announces_ended`: cumulative broadcast
33//!   announce/unannounce events on this `(tier, role)`. Driven by the tagged
34//!   announce stream on the egress side, and by `origin::Producer::route`
35//!   transitions on the ingress side.
36//! * `announced_bytes`: cumulative broadcast-name length summed over each
37//!   model-visible announce and unannounce of this broadcast (the name, not the
38//!   encoded message size, so hop/framing overhead isn't charged, and the count
39//!   is the same across protocol versions). Kept separate from the `bytes`
40//!   payload counter.
41//! * `broadcasts_started` / `broadcasts_ended`: per-(broadcast, context) egress
42//!   subscription sentinel. The first active subscription a context opens for a
43//!   broadcast bumps `broadcasts_started`; the last it closes bumps
44//!   `broadcasts_ended`. Summed across contexts, `broadcasts_started -
45//!   broadcasts_ended` is the number of distinct sessions currently subscribed
46//!   (viewers on the egress side).
47//! * `subscriptions_started` / `subscriptions_ended`: cumulative track-level
48//!   subscriptions opened/dropped (egress `track::Subscriber`, ingress
49//!   `track::Producer`).
50//! * `fetches`: cumulative group fetches *requested* by a calling context,
51//!   counted once per coalesced fetch at request time, a lite-07 subscription
52//!   naming every group it reads included. A fetch that resolves to `NotFound`
53//!   still counts. Separate from `subscriptions_started` and the viewer
54//!   refcount; fetched payload still flows into `bytes` / `frames` / `groups`.
55//! * `bytes` / `frames` / `groups`: cumulative payload counters bumped as
56//!   groups/frames are read (egress) or written (ingress) in the model. A
57//!   session's egress `bytes` / `frames` count only payload the peer
58//!   acknowledged, or that a reliable link such as qmux's took (see
59//!   [`SendStream::poll_acked`](crate::transport::poll::SendStream::poll_acked)),
60//!   never what a reset or a lost session discarded: a frame's bytes once an
61//!   offset past them is acknowledged, and the frame with its last byte. A
62//!   transport that cannot see acknowledgments counts the bytes the stream
63//!   took instead. An in-process reader counts on read,
64//!   unless it takes a [`Bill`] to count only what it delivers onward.
65//! * `datagrams`: cumulative datagrams of datagram tracks. A datagram belongs to
66//!   no group, so it bumps `bytes` but not `groups` or `frames`. A session counts
67//!   an egress datagram once the transport accepts it.
68//! * `inflated`: cumulative bytes inflated from compressed groups for plain
69//!   readers (in-process consumers, and egress that cannot carry compression).
70//!   Every plain reader of a group shares one inflated copy, so each byte counts
71//!   once, on the side of the reader whose read inflated it. Kept separate from
72//!   `bytes`, which counts payload as stored or sent.
73//! * `requests` ([`Presence`]): cumulative request/response admissions under the
74//!   label and tier at admission. [`Handle::request`] meters their traffic
75//!   without starting or ending a connected session.
76//! * `sent_bytes` / `received_bytes` ([`Presence`]): cumulative payload bytes
77//!   this node sent to, or received from, the sessions and requests under a
78//!   label. Each session counts its own bytes, so a write touches no shared
79//!   row; a readout sums them.
80//! * `sessions_started` / `sessions_ended` ([`Presence`]): cumulative count of
81//!   sessions connected/disconnected under a label on this tier.
82//!   Driven by [`Handle::session`] (the [`Session`] context); a
83//!   [`Session::retag`] ends the session on the old label and starts it on
84//!   the new one.
85//! * `wire_tx` / `wire_rx` ([`Presence`]): cumulative transport bytes, including
86//!   overhead and retransmissions. The transport updates its
87//!   [`crate::transport::Wire`] counters as it sends and receives, and
88//!   [`Registry::report`] and [`Registry::snapshot`] read each registered [`Wire`]
89//!   without polling the session. A retag flushes its old tier and label; dropping the guard flushes
90//!   its final nonnegative delta. Unsupported transports contribute zero.
91//! * `credit_stalls` / `credit_stalled_us` ([`Presence`]): cumulative episodes, and
92//!   microseconds, that the label's connections spent with a write blocked on the
93//!   peer's connection-level credit (`MAX_DATA`), read from the same
94//!   [`crate::transport::Wire`] counters as `wire_tx`.
95//! * `credit_held_readers_us` / `credit_held_evicted_us` ([`Presence`]): cumulative
96//!   microseconds the label's connections had their whole receive window spent by the
97//!   peer while eviction waited, on a reader behind or on an evicted reader yet to stop
98//!   its stream, read from the same counters.
99//! * `wire_lost` / `cwnd_blocked_us` / `pacing_blocked_us` ([`Presence`]): cumulative
100//!   sent transport bytes declared lost, and microseconds the label's connections had
101//!   data ready to send held back by a full congestion window or by the pacer, read
102//!   from the same counters. Loss lands on the label and tier current when QUIC declares it,
103//!   so after a retag it need not be part of that row's `wire_tx`; summed over a node and a
104//!   window longer than a retag, lost bytes over `wire_tx` is the loss rate.
105//! * `routes_refused` ([`Presence`]): cumulative routes and claims that lite-07
106//!   sessions under the label forwarded and this node refused, each withdrawn while
107//!   the session stays open; [`Routes::refused`] splits it by reason.
108//! * `routes` ([`Presence`], [`Routes`]): what the label's lite-07 sessions did on
109//!   the route layer: route changes their peers caused and the broadcasts each
110//!   rewrote into the origin, DEAD and DRAIN withdrawals sent and received, refusals
111//!   by reason, and sessions closed for their route layer by kind.
112//! * `announces_peak` / `subscriptions_peak` ([`Presence`]): the most
113//!   announcements, or subscriptions, any one session under the label held
114//!   at once, to compare against what bounds them. A peak never
115//!   goes down; a rollup takes the largest rather than the sum.
116//!
117//! Beside the counters, [`Registry::report`] gives each side the moment it began
118//! holding the broadcast announced ([`Announced`]): its held announce guards last
119//! rose from none, so overlapping announcements keep one start.
120//!
121//! Counters are strictly monotonic (only `fetch_add`); a counter going
122//! backwards across reads means the underlying entry was garbage collected
123//! (see [`Registry::report`]) and re-created. Downstream consumers should
124//! treat decreases as a fresh segment, summing across resets when computing
125//! lifetime totals.
126//!
127//! # Disabled stats
128//!
129//! [`Registry::disabled`] builds a no-op registry: all counter bumps are
130//! silently dropped and nothing is ever tracked. [`Registry::default`] /
131//! [`Handle::default`] return one, so call sites can hold a [`Handle`]
132//! unconditionally instead of threading an `Option`.
133//!
134//! # Garbage collection
135//!
136//! [`Registry::report`] refills a caller-owned [`Report`] with the current
137//! per-broadcast detail and prunes
138//! entries no longer referenced by any guard, so a publisher draining the
139//! registry on an interval keeps it bounded. A registry that is never
140//! drained accumulates one entry per broadcast path ever seen; call
141//! [`Registry::report`] periodically if you enable a registry without
142//! attaching a publisher. [`Registry::snapshot`] never prunes.
143//!
144//! # Snapshot atomicity
145//!
146//! Each counter readout loads `*_ended` atomics (with `Acquire`)
147//! before their `*_started` counterparts (with `Relaxed`). The matching
148//! end bumps in the RAII guards' `Drop` impls use `Release`. With this
149//! pairing the readout always satisfies `started >= ended` even on
150//! weakly-ordered architectures (ARM, POWER): the `Acquire` load of
151//! ended synchronizes-with the `Release` bump that produced the
152//! observed value, making every write that happened-before that end
153//! (including the matching start bump on whichever thread opened the
154//! guard) visible to the reading thread. Started / payload counters can
155//! then stay `Relaxed` because the visibility comes for free through
156//! the ended pairing. The cost is a slight upward bias on the started
157//! counts when a bump lands between the two loads, which never produces
158//! a logically impossible (`ended > started`) readout for downstream.
159//!
160//! # Cycles
161//!
162//! A [`Registry`] built with excluded prefixes ([`Config::exclude`]) returns
163//! empty handles (whose bumps no-op) for any path they match. The `moq-stats`
164//! publisher excludes its own top-level subtree this way, breaking the feedback
165//! loop where serving a stats broadcast would itself generate more stats
166//! traffic. [`Config::exclude_rooted`] does the same for a subtree under each
167//! session's own root, where a relay presents that root's stats.
168
169use std::{
170	collections::HashMap,
171	fmt,
172	sync::{
173		Arc, Mutex, MutexGuard, PoisonError, Weak,
174		atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering, fence},
175	},
176};
177
178use kio::Lock;
179use serde::{Deserialize, Serialize};
180
181use crate::{Path, Prefix, Prefixes, time::Instant, util::SendCell};
182
183mod outcomes;
184mod routes;
185pub use outcomes::{Failure, Failures, RefusalKind, Refusals};
186use outcomes::{FailureCounters, RefusalCounters};
187use routes::RouteCounters;
188pub use routes::{RouteClose, RouteCloses, RouteRefusal, RouteRefusals, Routes, Withdrawal, Withdrawals};
189
190/// Cumulative atomic counters for a single `(tier, role)` on a broadcast.
191///
192/// Started counters bump when a model handle records activity; their `_ended`
193/// counterparts bump from the [`Scope`] / [`Subscription`] / [`Announce`] RAII
194/// guards on drop. `broadcasts_started` / `broadcasts_ended` are the
195/// per-(broadcast, context) egress subscription sentinel (the first active
196/// subscription a context opens for the broadcast bumps `broadcasts_started`,
197/// the last to close bumps `broadcasts_ended`), so summed across contexts
198/// `broadcasts_started - broadcasts_ended` is the count of distinct sessions
199/// currently subscribed.
200// Kept crate-private: the load/store orderings are load-bearing (see the
201// module-level "Snapshot atomicity" note), so external code only ever sees
202// the derived [`Traffic`] readout.
203#[derive(Default, Debug)]
204pub(crate) struct Counters {
205	announces_started: AtomicU64,
206	announces_ended: AtomicU64,
207	// Cumulative broadcast-name length summed over each announce and unannounce
208	// of this broadcast. Counts the name, not the encoded message size, so it
209	// doesn't penalize the broadcast for hop/framing overhead. Kept separate
210	// from `bytes`, which is media payload.
211	announced_bytes: AtomicU64,
212	subscriptions_started: AtomicU64,
213	subscriptions_ended: AtomicU64,
214	// Cumulative group fetches requested by a calling context. Counted
215	// once per coalesced fetch, at request time rather than on resolution; does
216	// not touch `subscriptions_started` or the viewer refcount.
217	fetches: AtomicU64,
218	broadcasts_started: AtomicU64,
219	broadcasts_ended: AtomicU64,
220	bytes: AtomicU64,
221	frames: AtomicU64,
222	groups: AtomicU64,
223	// Datagrams of datagram tracks, disjoint from `groups`.
224	datagrams: AtomicU64,
225	// Bytes inflated from compressed groups for plain readers, once per group.
226	inflated: AtomicU64,
227	// Content the drift budget gave up on before delivery. Disjoint from the
228	// top-level payload counters, which count only what was handed over.
229	stale: ContentCounters,
230	// The announce guards held now and when the count last rose from zero, under one
231	// lock so a guard opening as the last one closes never splits them. Guards bump
232	// `announces_started`/`announces_ended` while holding it, so a readout under it
233	// sees counts and start agree. Only announce events and readouts take it, never
234	// the payload path.
235	held: Mutex<Held>,
236}
237
238/// The announce guards one side holds, and since when it has held any.
239#[derive(Default, Debug)]
240struct Held {
241	count: u64,
242	since: Option<kio::clock::Wall>,
243}
244
245/// Atomic backing for one [`Content`] readout.
246#[derive(Default, Debug)]
247struct ContentCounters {
248	bytes: AtomicU64,
249	frames: AtomicU64,
250	groups: AtomicU64,
251}
252
253impl ContentCounters {
254	fn snapshot(&self) -> Content {
255		Content {
256			bytes: self.bytes.load(Ordering::Relaxed),
257			frames: self.frames.load(Ordering::Relaxed),
258			groups: self.groups.load(Ordering::Relaxed),
259		}
260	}
261
262	fn add(&self, content: Content) {
263		self.bytes.fetch_add(content.bytes, Ordering::Relaxed);
264		self.frames.fetch_add(content.frames, Ordering::Relaxed);
265		self.groups.fetch_add(content.groups, Ordering::Relaxed);
266	}
267}
268
269impl Counters {
270	/// Read all atomics into a [`Traffic`]. Ended counters are read with
271	/// `Acquire` ordering before their started counterparts so the readout
272	/// always satisfies `started >= ended`; see the module-level "Snapshot
273	/// atomicity" note. Started / payload counters stay `Relaxed`: the
274	/// Acquire on ended synchronizes-with the matching Release on the
275	/// end bump, which transitively makes all earlier writes (including
276	/// the prior start bump) visible to this thread.
277	fn snapshot(&self) -> Traffic {
278		let announces_ended = self.announces_ended.load(Ordering::Acquire);
279		let subscriptions_ended = self.subscriptions_ended.load(Ordering::Acquire);
280		let broadcasts_ended = self.broadcasts_ended.load(Ordering::Acquire);
281		let announces_started = self.announces_started.load(Ordering::Relaxed);
282		let announced_bytes = self.announced_bytes.load(Ordering::Relaxed);
283		let subscriptions_started = self.subscriptions_started.load(Ordering::Relaxed);
284		let fetches = self.fetches.load(Ordering::Relaxed);
285		let broadcasts_started = self.broadcasts_started.load(Ordering::Relaxed);
286		let bytes = self.bytes.load(Ordering::Relaxed);
287		let frames = self.frames.load(Ordering::Relaxed);
288		let groups = self.groups.load(Ordering::Relaxed);
289		let datagrams = self.datagrams.load(Ordering::Relaxed);
290		let inflated = self.inflated.load(Ordering::Relaxed);
291		let stale = self.stale.snapshot();
292		Traffic {
293			announces_started,
294			announces_ended,
295			announced_bytes,
296			broadcasts_started,
297			broadcasts_ended,
298			subscriptions_started,
299			subscriptions_ended,
300			fetches,
301			bytes,
302			frames,
303			groups,
304			datagrams,
305			inflated,
306			stale,
307		}
308	}
309
310	/// The counters and, while this side holds an announcement, when it began to, read
311	/// under the lock announce guards bump their counts in, so a start is reported
312	/// exactly when `announces_started > announces_ended`.
313	fn readout(&self) -> (Traffic, Option<kio::clock::Wall>) {
314		let held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
315		(self.snapshot(), held.since)
316	}
317}
318
319/// Payload-volume counters for content with the same delivery outcome.
320///
321/// This is the nested shape used by [`Traffic::stale`]. The successfully
322/// delivered equivalents remain as top-level [`Traffic`] fields for wire
323/// compatibility with existing stats consumers.
324#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(default)]
326#[non_exhaustive]
327pub struct Content {
328	/// Cumulative payload bytes.
329	pub bytes: u64,
330	/// Cumulative frames.
331	pub frames: u64,
332	/// Cumulative groups.
333	pub groups: u64,
334}
335
336impl Content {
337	/// Fold another readout into this one, counter by counter.
338	pub(crate) fn add(&mut self, other: Self) {
339		self.bytes = self.bytes.saturating_add(other.bytes);
340		self.frames = self.frames.saturating_add(other.frames);
341		self.groups = self.groups.saturating_add(other.groups);
342	}
343}
344
345/// Per-(tier, label) session gauge. One of these is shared (via `Arc`) by every
346/// [`Session`] guard for the same label on the same tier: `sessions_started`
347/// bumps on connect, `sessions_ended` on disconnect.
348#[derive(Default, Debug)]
349struct SessionCounters {
350	sessions_refused: RefusalCounters,
351	sessions_failed: FailureCounters,
352	requests: AtomicU64,
353	sessions_started: AtomicU64,
354	sessions_ended: AtomicU64,
355	announces_peak: AtomicU64,
356	subscriptions_peak: AtomicU64,
357	routes: RouteCounters,
358	/// Payload bytes of the sessions recording here. One lock covers the folded totals
359	/// and the live sessions, so a readout never goes down when a session leaves.
360	bytes: Mutex<SessionBytes>,
361	/// Totals of the [`Presence::wire_mut`] fields, in its order.
362	wire: [AtomicU64; Presence::WIRE_FIELDS],
363	/// Per class: bytes sent and received, then messages sent and received.
364	control: [[AtomicU64; 4]; Message::ALL.len()],
365}
366
367impl SessionCounters {
368	fn peak(&self, cap: Cap) -> &AtomicU64 {
369		match cap {
370			Cap::Announces => &self.announces_peak,
371			Cap::Subscriptions => &self.subscriptions_peak,
372		}
373	}
374
375	/// Read the gauge, its connected sessions' [`Activity`] at `now`, and whether all its payload
376	/// meters have ended. Ended is loaded with `Acquire` before started with `Relaxed`, the same
377	/// pairing as [`Counters::snapshot`], so the readout never shows `ended > started`.
378	fn snapshot(&self, now: Instant) -> (Presence, Activity, bool) {
379		let sessions_failed = self.sessions_failed.snapshot();
380		let sessions_ended = self.sessions_ended.load(Ordering::Acquire);
381		let sessions_started = self.sessions_started.load(Ordering::Relaxed);
382		let (sent_bytes, received_bytes, activity, empty) = {
383			let mut bytes = self.bytes();
384			let (sent, received, activity) = bytes.read(now);
385			(sent, received, activity, bytes.live.is_empty())
386		};
387		let routes = self.routes.snapshot();
388		let mut presence = Presence {
389			sessions_refused: self.sessions_refused.snapshot(),
390			sessions_failed,
391			requests: self.requests.load(Ordering::Relaxed),
392			sessions_started,
393			sessions_ended,
394			sent_bytes,
395			received_bytes,
396			announces_peak: self.announces_peak.load(Ordering::Relaxed),
397			subscriptions_peak: self.subscriptions_peak.load(Ordering::Relaxed),
398			routes_refused: routes.refused.total(),
399			routes,
400			..Presence::default()
401		};
402		for (field, total) in presence.wire_mut().into_iter().zip(&self.wire) {
403			*field = total.load(Ordering::Relaxed);
404		}
405		(presence, activity, empty)
406	}
407
408	fn control(&self, totals: &mut [Totals; Message::ALL.len()]) {
409		for (total, [tx, rx, tx_messages, rx_messages]) in totals.iter_mut().zip(&self.control) {
410			total.tx += tx.load(Ordering::Relaxed);
411			total.rx += rx.load(Ordering::Relaxed);
412			total.tx_messages += tx_messages.load(Ordering::Relaxed);
413			total.rx_messages += rx_messages.load(Ordering::Relaxed);
414		}
415	}
416
417	fn bytes(&self) -> MutexGuard<'_, SessionBytes> {
418		self.bytes.lock().unwrap_or_else(PoisonError::into_inner)
419	}
420}
421
422/// The payload bytes of one `(tier, label)` row.
423#[derive(Default, Debug)]
424struct SessionBytes {
425	/// Bytes recorded here by sessions that have since ended or retagged away.
426	sent: u64,
427	received: u64,
428	/// The sessions recording here, keyed by identity so a retag leaves in constant time,
429	/// each with its counters as of when it arrived.
430	live: HashMap<usize, Arrival>,
431}
432
433/// A session recording on a row, and its byte counters when it arrived there.
434#[derive(Debug)]
435struct Arrival {
436	traffic: Arc<SessionTraffic>,
437	sent: u64,
438	received: u64,
439	sample: Sample,
440}
441
442/// What readouts have seen of one session's payload, carried across a retag so a change of
443/// row neither forgets recent activity nor misses a move made before it.
444#[derive(Clone, Copy, Debug)]
445struct Sample {
446	/// The counters as of the last readout, to notice payload moving between readouts.
447	seen: (u64, u64),
448	/// The first readout that saw the counters move since the one before it.
449	moved: Option<Instant>,
450}
451
452impl SessionBytes {
453	/// The key a session's arrival lives under. The arrival holds the `Arc`, so no other
454	/// session can reuse the address while it is here.
455	fn key(traffic: &Arc<SessionTraffic>) -> usize {
456		Arc::as_ptr(traffic) as usize
457	}
458
459	/// Count `traffic` here from `(sent, received)` on, continuing `sample`.
460	fn join(&mut self, traffic: Arc<SessionTraffic>, (sent, received): (u64, u64), sample: Sample) {
461		self.live.insert(
462			Self::key(&traffic),
463			Arrival {
464				traffic,
465				sent,
466				received,
467				sample,
468			},
469		);
470	}
471
472	/// Stop counting `traffic` here, keeping what it recorded so far, and return the
473	/// counters at that cut, where a concurrent write lands on one side of the single
474	/// load, with the session's sample for its next row.
475	fn leave(&mut self, traffic: &Arc<SessionTraffic>) -> ((u64, u64), Sample) {
476		let (sent, received) = traffic.load();
477		let arrival = self
478			.live
479			.remove(&Self::key(traffic))
480			.expect("a session is live on its current row");
481		self.sent += sent - arrival.sent;
482		self.received += received - arrival.received;
483		((sent, received), arrival.sample)
484	}
485
486	/// The row's `(sent, received)` totals and its connected sessions' [`Activity`] at `now`.
487	/// Folds in each session that no handle can write through anymore, since its count is final.
488	///
489	/// Every readout samples each session, so how precisely a move is dated depends on
490	/// how often the registry is read, by anyone.
491	fn read(&mut self, now: Instant) -> (u64, u64, Activity) {
492		let Self { sent, received, live } = self;
493		let (mut live_sent, mut live_received) = (0, 0);
494		let mut activity = Activity::default();
495		live.retain(|_, arrival| {
496			// No Weak<SessionTraffic> exists, so a unique arrival cannot gain another writer.
497			let ended = Arc::strong_count(&arrival.traffic) == 1;
498			if ended {
499				// Pair with the last writer's Arc drop before loading its final relaxed counters.
500				fence(Ordering::Acquire);
501			}
502			let (now_sent, now_received) = arrival.traffic.load();
503			let sample = &mut arrival.sample;
504			if (now_sent, now_received) != sample.seen {
505				sample.seen = (now_sent, now_received);
506				sample.moved = Some(now);
507			}
508			if arrival.traffic.connected.load(Ordering::Relaxed) {
509				match sample.moved {
510					Some(moved) if now.saturating_duration_since(moved) < Activity::WINDOW => activity.active += 1,
511					_ => activity.idle += 1,
512				}
513			}
514			let (delta_sent, delta_received) = (now_sent - arrival.sent, now_received - arrival.received);
515			if ended {
516				*sent += delta_sent;
517				*received += delta_received;
518			} else {
519				live_sent += delta_sent;
520				live_received += delta_received;
521			}
522			!ended
523		});
524		(*sent + live_sent, *received + live_received, activity)
525	}
526}
527
528/// A cumulative traffic counter readout for one slice (a broadcast on a
529/// `(tier, role)`, or any sum of such slices).
530///
531/// Every counter is cumulative, so a rate is `delta / delta_t` and a live
532/// count is `started - ended`. This is also the wire shape of one entry on a
533/// published stats track (the `moq-stats` crate serializes maps of these).
534/// Unknown fields from a newer publisher are ignored and missing fields from
535/// an older one default to zero.
536#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
537#[serde(default)]
538#[non_exhaustive]
539pub struct Traffic {
540	/// Cumulative broadcast announce events on this slice.
541	pub announces_started: u64,
542	/// Cumulative broadcast unannounce events on this slice.
543	pub announces_ended: u64,
544	/// Cumulative announce-control bytes: the broadcast name length summed
545	/// over each announce and unannounce. Distinct from `bytes` (payload).
546	pub announced_bytes: u64,
547	/// Per-(broadcast, session) subscription sentinel opens: the first active
548	/// subscription a session holds on a broadcast.
549	pub broadcasts_started: u64,
550	/// Sentinel closes: the session's last subscription to the broadcast ended.
551	pub broadcasts_ended: u64,
552	/// Cumulative track-level subscriptions opened.
553	pub subscriptions_started: u64,
554	/// Cumulative track-level subscriptions closed.
555	pub subscriptions_ended: u64,
556	/// Cumulative group fetches requested. Counted once per coalesced fetch
557	/// when the fetch is issued, so one that resolves to `NotFound` still counts.
558	/// Separate from `subscriptions_started` and the viewer refcount. Fetched payload still
559	/// flows into `bytes`/`frames`/`groups`.
560	pub fetches: u64,
561	/// Cumulative payload bytes.
562	pub bytes: u64,
563	/// Cumulative frames delivered.
564	pub frames: u64,
565	/// Cumulative groups delivered.
566	pub groups: u64,
567	/// Cumulative datagrams of datagram tracks delivered. Disjoint from `groups` and
568	/// `frames`; their payload counts in `bytes`.
569	pub datagrams: u64,
570	/// Cumulative bytes inflated from compressed groups for plain readers. Every plain
571	/// reader shares one inflated copy per group, so each byte counts once. `bytes` still counts
572	/// payload as stored or sent.
573	pub inflated: u64,
574	/// Content skipped because it fell behind a live join's
575	/// [`Start::Live`](crate::track::Start::Live) `max`. Disjoint from the top-level payload
576	/// counters: skipped content is never handed over. A steady rate here means
577	/// subscribers are consistently behind the live edge.
578	pub stale: Content,
579}
580
581impl Traffic {
582	/// Fold another readout into this one, counter by counter.
583	pub fn add(&mut self, other: Traffic) {
584		self.announces_started = self.announces_started.saturating_add(other.announces_started);
585		self.announces_ended = self.announces_ended.saturating_add(other.announces_ended);
586		self.announced_bytes = self.announced_bytes.saturating_add(other.announced_bytes);
587		self.broadcasts_started = self.broadcasts_started.saturating_add(other.broadcasts_started);
588		self.broadcasts_ended = self.broadcasts_ended.saturating_add(other.broadcasts_ended);
589		self.subscriptions_started = self.subscriptions_started.saturating_add(other.subscriptions_started);
590		self.subscriptions_ended = self.subscriptions_ended.saturating_add(other.subscriptions_ended);
591		self.fetches = self.fetches.saturating_add(other.fetches);
592		self.bytes = self.bytes.saturating_add(other.bytes);
593		self.frames = self.frames.saturating_add(other.frames);
594		self.groups = self.groups.saturating_add(other.groups);
595		self.datagrams = self.datagrams.saturating_add(other.datagrams);
596		self.inflated = self.inflated.saturating_add(other.inflated);
597		self.stale.add(other.stale);
598	}
599
600	/// Distinct sessions currently subscribed (viewers on the egress side).
601	pub fn active_broadcasts(&self) -> u64 {
602		self.broadcasts_started.saturating_sub(self.broadcasts_ended)
603	}
604
605	/// Track subscriptions currently open.
606	pub fn active_subscriptions(&self) -> u64 {
607		self.subscriptions_started.saturating_sub(self.subscriptions_ended)
608	}
609
610	/// True once every started counter equals its ended counterpart: no guard is
611	/// held, so no more traffic can flow until a new start.
612	pub fn is_idle(&self) -> bool {
613		self.announces_started == self.announces_ended
614			&& self.subscriptions_started == self.subscriptions_ended
615			&& self.broadcasts_started == self.broadcasts_ended
616	}
617}
618
619/// Whether a counter is zero, which serializing skips.
620fn is_zero(value: &u64) -> bool {
621	*value == 0
622}
623
624/// Request admissions and connected-session presence for a label on a tier, or their sum.
625/// The session counters are cumulative connects and disconnects, so
626/// `sessions_started - sessions_ended` is the current live session count. The peaks
627/// show how close one session came to the bounds on what it holds.
628///
629/// Like [`Traffic`], this is also the wire shape of one entry on a published
630/// sessions, presence, or totals track.
631#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
632#[serde(default)]
633#[non_exhaustive]
634pub struct Presence {
635	/// Cumulative sessions refused before admission, by reason.
636	pub sessions_refused: Refusals,
637	/// Cumulative admitted sessions ending abnormally, by kind.
638	pub sessions_failed: Failures,
639	/// Cumulative request/response exchanges admitted.
640	pub requests: u64,
641	/// Cumulative sessions connected.
642	pub sessions_started: u64,
643	/// Cumulative sessions disconnected.
644	pub sessions_ended: u64,
645	/// Cumulative payload bytes sent by sessions under this label.
646	pub sent_bytes: u64,
647	/// Cumulative payload bytes received by sessions under this label.
648	pub received_bytes: u64,
649	/// The most broadcasts (moq-transport: namespaces) any one session has held announced
650	/// to us at once.
651	pub announces_peak: u64,
652	/// The most subscriptions any one session has held on our broadcasts at once.
653	pub subscriptions_peak: u64,
654	/// Cumulative transport bytes sent, including transport framing and retransmits.
655	pub wire_tx: u64,
656	/// Cumulative transport bytes received, including transport framing.
657	pub wire_rx: u64,
658	/// Cumulative sent transport bytes declared lost, counted where the loss is declared, so a
659	/// retagged session's loss may land on a row whose `wire_tx` never held those bytes.
660	// Zero on every transport but QUIC, so a zero stays off the wire like the credit counters.
661	#[serde(skip_serializing_if = "is_zero")]
662	pub wire_lost: u64,
663	/// Cumulative times a connection's write blocked with all the peer's connection-level
664	/// credit (`MAX_DATA`) spent.
665	// The credit counters stay zero on most labels, so a zero stays off the wire; readers default it.
666	#[serde(skip_serializing_if = "is_zero")]
667	pub credit_stalls: u64,
668	/// Cumulative microseconds connections spent blocked on the peer's connection-level credit.
669	#[serde(skip_serializing_if = "is_zero")]
670	pub credit_stalled_us: u64,
671	/// Cumulative microseconds the peer had a connection's whole receive window spent while a
672	/// reader had data it had not looked at yet: readers behind holding the window.
673	#[serde(skip_serializing_if = "is_zero")]
674	pub credit_held_readers_us: u64,
675	/// Cumulative microseconds the peer had a connection's whole receive window spent while an
676	/// evicted reader had not stopped its stream.
677	#[serde(skip_serializing_if = "is_zero")]
678	pub credit_held_evicted_us: u64,
679	/// Cumulative microseconds connections had data ready to send held back by a full
680	/// congestion window.
681	#[serde(skip_serializing_if = "is_zero")]
682	pub cwnd_blocked_us: u64,
683	/// Cumulative microseconds connections had data ready to send held back by the pacer.
684	#[serde(skip_serializing_if = "is_zero")]
685	pub pacing_blocked_us: u64,
686	/// Cumulative routes and claims a lite-07 session forwarded that this
687	/// node refused, withdrawing each and keeping the session: the total of
688	/// [`Routes::refused`].
689	pub routes_refused: u64,
690	/// What the label's lite-07 sessions did on the route layer.
691	// Most labels never route, so an all-zero readout stays off the wire; readers default it.
692	#[serde(skip_serializing_if = "Routes::is_zero")]
693	pub routes: Routes,
694}
695
696impl Presence {
697	/// How many fields [`Self::wire_mut`] returns.
698	pub const WIRE_FIELDS: usize = 9;
699
700	/// The fields summed from transports' [`crate::transport::Wire`] counters, in a fixed order.
701	pub fn wire_mut(&mut self) -> [&mut u64; Self::WIRE_FIELDS] {
702		[
703			&mut self.wire_tx,
704			&mut self.wire_rx,
705			&mut self.wire_lost,
706			&mut self.credit_stalls,
707			&mut self.credit_stalled_us,
708			&mut self.credit_held_readers_us,
709			&mut self.credit_held_evicted_us,
710			&mut self.cwnd_blocked_us,
711			&mut self.pacing_blocked_us,
712		]
713	}
714
715	/// Fold another readout into this one. The peaks are per session, so they take the larger.
716	pub fn add(&mut self, other: Presence) {
717		self.sessions_refused.add(other.sessions_refused);
718		self.sessions_failed.add(other.sessions_failed);
719		self.requests = self.requests.saturating_add(other.requests);
720		self.wire_tx = self.wire_tx.saturating_add(other.wire_tx);
721		self.wire_rx = self.wire_rx.saturating_add(other.wire_rx);
722		self.wire_lost = self.wire_lost.saturating_add(other.wire_lost);
723		self.cwnd_blocked_us = self.cwnd_blocked_us.saturating_add(other.cwnd_blocked_us);
724		self.pacing_blocked_us = self.pacing_blocked_us.saturating_add(other.pacing_blocked_us);
725		self.credit_stalls = self.credit_stalls.saturating_add(other.credit_stalls);
726		self.credit_stalled_us = self.credit_stalled_us.saturating_add(other.credit_stalled_us);
727		self.credit_held_readers_us = self.credit_held_readers_us.saturating_add(other.credit_held_readers_us);
728		self.credit_held_evicted_us = self.credit_held_evicted_us.saturating_add(other.credit_held_evicted_us);
729		self.sessions_started = self.sessions_started.saturating_add(other.sessions_started);
730		self.sessions_ended = self.sessions_ended.saturating_add(other.sessions_ended);
731		self.sent_bytes = self.sent_bytes.saturating_add(other.sent_bytes);
732		self.received_bytes = self.received_bytes.saturating_add(other.received_bytes);
733		self.announces_peak = self.announces_peak.max(other.announces_peak);
734		self.subscriptions_peak = self.subscriptions_peak.max(other.subscriptions_peak);
735		self.routes_refused = self.routes_refused.saturating_add(other.routes_refused);
736		self.routes.add(other.routes);
737	}
738
739	/// Sessions currently connected.
740	pub fn active(&self) -> u64 {
741		self.sessions_started.saturating_sub(self.sessions_ended)
742	}
743}
744
745/// Connected sessions right now, split by whether media payload moved through them
746/// within the last 10 seconds, in either direction.
747///
748/// A gauge, not a counter. A session that only holds announces, or subscriptions
749/// with nothing flowing, is idle: it costs keepalives and control traffic, not
750/// media forwarding. Moves are dated at registry readouts, so a move is seen no
751/// earlier than the readout after it.
752#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
753#[non_exhaustive]
754pub struct Activity {
755	/// Connected sessions with no payload moved within the window.
756	pub idle: u64,
757	/// Connected sessions with payload moved within the window.
758	pub active: u64,
759}
760
761impl Activity {
762	/// How recently payload must have moved for a session to count as active.
763	const WINDOW: std::time::Duration = std::time::Duration::from_secs(10);
764
765	fn add(&mut self, other: Self) {
766		self.idle += other.idle;
767		self.active += other.active;
768	}
769}
770
771/// Traffic-class label that selects which counter set a session's bumps record
772/// in, so a single [`Registry`] can split customer-facing, cluster-peer, regional,
773/// etc. traffic. Each tracked broadcast keeps a per-tier counter set on both its
774/// publisher and subscriber sides.
775///
776/// Published stats frames key each tier's counters by its label, so
777/// `Tier::new("region/sjc")` records under `"region/sjc"`. The label is an
778/// arbitrary path chosen by business logic; an empty label is the default tier.
779#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
780pub struct Tier(Path);
781
782impl Tier {
783	/// A tier with the given label. An empty label is the default tier.
784	pub fn new(label: impl Into<Path>) -> Self {
785		Self(label.into())
786	}
787
788	/// The tier label, empty for the default tier.
789	pub fn label(&self) -> &Path {
790		&self.0
791	}
792
793	/// The tier label as used in metrics: empty (`""`) for the default tier,
794	/// otherwise the label (e.g. `"region/sjc"`), as stats frames key it.
795	pub fn as_str(&self) -> &str {
796		self.0.as_str()
797	}
798}
799
800impl fmt::Display for Tier {
801	/// The label, empty for the default unprefixed tier.
802	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803		fmt::Display::fmt(&self.0, f)
804	}
805}
806
807/// Publisher (egress) vs subscriber (ingress) side of a broadcast, used as a
808/// label on a [`Snapshot`] traffic row. The internal bump paths track the
809/// side statically, so this only surfaces on the aggregate read side.
810///
811/// This is the direction traffic flowed, not the session role a client advertises
812/// in its SETUP: one session records on both sides.
813#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
814pub enum Role {
815	/// Egress: bytes this node published to a peer.
816	Publisher,
817	/// Ingress: bytes this node consumed from a peer.
818	Subscriber,
819}
820
821impl Role {
822	fn idx(self) -> usize {
823		match self {
824			Role::Publisher => 0,
825			Role::Subscriber => 1,
826		}
827	}
828
829	/// Lowercase label for this role (`"publisher"` / `"subscriber"`).
830	pub fn as_str(self) -> &'static str {
831		match self {
832			Role::Publisher => "publisher",
833			Role::Subscriber => "subscriber",
834		}
835	}
836}
837
838/// Cumulative bytes and messages sent and received, returned per [`Message`] class by
839/// [`Snapshot::control`].
840#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
841#[non_exhaustive]
842pub struct Totals {
843	/// Bytes successfully encoded for sending, counted even if the stream later fails.
844	pub tx: u64,
845	/// Bytes of complete messages decoded and consumed.
846	pub rx: u64,
847	/// Messages successfully encoded for sending, counted like [`Self::tx`].
848	pub tx_messages: u64,
849	/// Complete messages decoded and consumed, counted like [`Self::rx`].
850	pub rx_messages: u64,
851}
852
853/// The bounded class of a successfully encoded or decoded control message.
854///
855/// Counters include prefixes inside a complete codec value, but exclude separately
856/// coded selectors and raw payload writes. A framed IETF body counts after its
857/// framing decodes, before request validation. Shared reply IDs use [`Self::Other`].
858#[derive(Clone, Copy, Debug, PartialEq, Eq)]
859#[non_exhaustive]
860pub enum Message {
861	/// Session setup and information.
862	Session,
863	/// Namespace advertisements and listings.
864	Announce,
865	/// Track metadata and listings.
866	TrackInfo,
867	/// Live subscriptions and their updates.
868	Subscribe,
869	/// Finite fetch requests.
870	Fetch,
871	/// Bandwidth probes.
872	Probe,
873	/// Authorization messages.
874	Auth,
875	/// Session or request migration.
876	Goaway,
877	/// Other protocol control messages, including shared request responses.
878	Other,
879}
880
881impl Message {
882	const ALL: [Self; 9] = [
883		Self::Session,
884		Self::Announce,
885		Self::TrackInfo,
886		Self::Subscribe,
887		Self::Fetch,
888		Self::Probe,
889		Self::Auth,
890		Self::Goaway,
891		Self::Other,
892	];
893
894	/// The stable label used by control metrics.
895	pub fn as_str(self) -> &'static str {
896		match self {
897			Self::Session => "session",
898			Self::Announce => "announce",
899			Self::TrackInfo => "track_info",
900			Self::Subscribe => "subscribe",
901			Self::Fetch => "fetch",
902			Self::Probe => "probe",
903			Self::Auth => "auth",
904			Self::Goaway => "goaway",
905			Self::Other => "other",
906		}
907	}
908}
909
910/// A point-in-time, host-level rollup of a registry's counters, returned
911/// by [`Registry::snapshot`].
912///
913/// Every counter is summed across all broadcasts the registry is tracking and
914/// split by tier and role, plus per-tier connected-session presence. One entry
915/// per tier that recorded any traffic or session, keyed by the tier's label (so
916/// an idle tier is simply absent). Intended for a scrape / `/metrics`-style
917/// endpoint where per-broadcast cardinality is unwanted; use
918/// [`Registry::report`] for the per-broadcast breakdown. A disabled registry
919/// yields no rows.
920#[derive(Debug, Default, Clone, PartialEq, Eq)]
921#[non_exhaustive]
922pub struct Snapshot {
923	/// Traffic totals per tier, indexed by [`Role`] within each tier; read via
924	/// [`Self::traffic`].
925	traffic: HashMap<Tier, [Traffic; 2]>,
926	/// Session presence per tier; read via [`Self::sessions`].
927	sessions: HashMap<Tier, Presence>,
928	/// Connected-session activity per tier; read via [`Self::activity`].
929	activity: HashMap<Tier, Activity>,
930	control: HashMap<Tier, [Totals; Message::ALL.len()]>,
931}
932
933impl Snapshot {
934	/// The `(tier, class, totals)` control-message rows with any traffic, sorted by tier and class.
935	/// Includes prefixes inside complete codec values, but excludes separately coded type selectors,
936	/// media payload, and transport framing, acknowledgements, and retransmissions.
937	pub fn control(&self) -> Vec<(Tier, Message, Totals)> {
938		let mut rows = Vec::new();
939		for (tier, totals) in &self.control {
940			for class in Message::ALL {
941				let totals = totals[class as usize];
942				if totals != Totals::default() {
943					rows.push((tier.clone(), class, totals));
944				}
945			}
946		}
947		rows.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()).then(a.1.as_str().cmp(b.1.as_str())));
948		rows
949	}
950
951	/// The `(tier, role, totals)` traffic rows, one publisher and one subscriber
952	/// row per tier present. Sorted by tier label then role for stable output.
953	pub fn traffic(&self) -> Vec<(Tier, Role, Traffic)> {
954		let mut rows = Vec::with_capacity(self.traffic.len() * 2);
955		for (tier, roles) in &self.traffic {
956			rows.push((tier.clone(), Role::Publisher, roles[Role::Publisher.idx()]));
957			rows.push((tier.clone(), Role::Subscriber, roles[Role::Subscriber.idx()]));
958		}
959		rows.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()).then(a.1.idx().cmp(&b.1.idx())));
960		rows
961	}
962
963	/// The `(tier, sessions)` presence rows, one per tier present, sorted by tier
964	/// label.
965	pub fn sessions(&self) -> Vec<(Tier, Presence)> {
966		let mut rows: Vec<_> = self.sessions.iter().map(|(tier, s)| (tier.clone(), *s)).collect();
967		rows.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
968		rows
969	}
970
971	/// The `(tier, activity)` rows of connected sessions, one per tier with a session row,
972	/// sorted by tier label.
973	pub fn activity(&self) -> Vec<(Tier, Activity)> {
974		let mut rows: Vec<_> = self.activity.iter().map(|(tier, a)| (tier.clone(), *a)).collect();
975		rows.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
976		rows
977	}
978}
979
980/// The per-broadcast detail [`Registry::report`] fills: one traffic entry per
981/// `(broadcast, tier)` and one session entry per `(tier, root, label)`. Entries are
982/// unordered. Reuse one across drains to keep its capacity.
983#[derive(Debug, Default, Clone)]
984#[non_exhaustive]
985pub struct Report {
986	/// Per-`(broadcast, tier)` traffic, both roles per entry.
987	pub traffic: Vec<TrafficEntry>,
988	/// Per-`(tier, root, label)` connected-session presence.
989	pub sessions: Vec<SessionEntry>,
990}
991
992/// One `(broadcast, tier)` row of a [`Report`].
993#[derive(Debug, Clone)]
994#[non_exhaustive]
995pub struct TrafficEntry {
996	/// The broadcast path the counters are keyed by.
997	pub path: Path,
998	/// The tier the counters recorded under.
999	pub tier: Tier,
1000	/// Egress counters (this node publishing to peers).
1001	pub publisher: Traffic,
1002	/// Ingress counters (this node consuming from peers).
1003	pub subscriber: Traffic,
1004	/// When each side began holding the broadcast announced, while it does.
1005	pub announced: Announced,
1006	/// This is the entry's final readout: no guard holds it, so the registry
1007	/// pruned it, and a later entry at the same key starts from zero.
1008	pub closed: bool,
1009}
1010
1011/// When each side of a [`TrafficEntry`] began holding its broadcast announced: the
1012/// moment the side's held announcements last rose from none. `None` while the side
1013/// holds none, so a broadcast unannounced and announced again starts over, while
1014/// one whose announcements overlap (a publisher reconnecting before its old session
1015/// closes) keeps its start.
1016#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1017#[non_exhaustive]
1018pub struct Announced {
1019	/// Egress: since when this node has announced the broadcast to a peer.
1020	pub publisher: Option<kio::clock::Wall>,
1021	/// Ingress: since when a peer has announced the broadcast to this node.
1022	pub subscriber: Option<kio::clock::Wall>,
1023}
1024
1025/// One `(tier, root, label)` row of a [`Report`].
1026#[derive(Debug, Clone)]
1027#[non_exhaustive]
1028pub struct SessionEntry {
1029	/// The tier the sessions recorded under.
1030	pub tier: Tier,
1031	/// The root the sessions are scoped to, empty for sessions without one.
1032	pub root: Path,
1033	/// The label the sessions record under, empty for sessions without one.
1034	pub label: Path,
1035	/// Cumulative request admissions and connect/disconnect gauge.
1036	pub presence: Presence,
1037	/// This is the label's final readout: its last session or request ended, so the
1038	/// registry pruned it, and a later context under the label starts from zero.
1039	pub closed: bool,
1040}
1041
1042/// Settings for a [`Registry`]. Construct with [`Config::new`] and chain the
1043/// `with_*` setters, then hand it to [`Registry::new`].
1044///
1045/// Every field here is about *collection*; the publishing knobs (origin,
1046/// interval, node, ...) live on the `moq-stats` producer config.
1047#[derive(Clone, Debug, Default)]
1048#[non_exhaustive]
1049pub struct Config {
1050	/// Prefixes whose broadcasts are not tracked: a path at or beneath one gets an
1051	/// empty handle whose bumps no-op. A publisher excludes its own stats subtree
1052	/// (`.stats`) this way, breaking the stats-of-stats feedback loop. Empty
1053	/// (the default) tracks everything.
1054	pub exclude: Prefixes,
1055	/// Prefixes matched against a path relative to the counting session's root:
1056	/// a path at or beneath one under that root is not tracked for that session. A
1057	/// relay that presents each root's stats under the root excludes that subtree
1058	/// this way. Empty (the default) excludes nothing.
1059	pub exclude_rooted: Prefixes,
1060}
1061
1062impl Config {
1063	/// A config with default settings: nothing excluded.
1064	pub fn new() -> Self {
1065		Self::default()
1066	}
1067
1068	/// Add a prefix to exclude from tracking, with its subtree. May be chained to
1069	/// exclude several.
1070	pub fn with_exclude(mut self, prefix: Prefix) -> Self {
1071		self.exclude.insert(prefix);
1072		self
1073	}
1074
1075	/// Add a prefix to exclude under each session's root. May be chained to
1076	/// exclude several. See [`Self::exclude_rooted`].
1077	pub fn with_exclude_rooted(mut self, prefix: Prefix) -> Self {
1078		self.exclude_rooted.insert(prefix);
1079		self
1080	}
1081}
1082
1083/// Counter collection registry. Cheap to clone (`Arc` inside for the shared
1084/// state). One instance per relay; sessions get tier-scoped handles via
1085/// [`Registry::tier`]. The `moq-stats` crate drains it with
1086/// [`Registry::report`] to publish the counters as MoQ broadcasts.
1087#[derive(Clone)]
1088pub struct Registry {
1089	/// Paths at or beneath these get empty handles (bumps no-op); see
1090	/// [`Config::exclude`].
1091	exclude: Prefixes,
1092	/// The same, relative to the counting session's root; see [`Config::exclude_rooted`].
1093	exclude_rooted: Prefixes,
1094	/// `None` for a disabled registry: bumps are dropped and nothing is tracked.
1095	shared: Option<Arc<Shared>>,
1096}
1097
1098/// State shared by every clone of a [`Registry`].
1099struct Shared {
1100	/// Completed entries folded by tier before pruning. Lock before either map
1101	/// so a snapshot sees each entry either here or live, never both or neither.
1102	retired: Lock<Snapshot>,
1103	entries: Lock<HashMap<Path, Arc<BroadcastEntry>>>,
1104	/// Connected-session gauges keyed by `(tier, (root, label))`. Independent of any
1105	/// broadcast; surfaced on the per-tier session tracks and in the totals and
1106	/// presence tracks. A tier's inner map is
1107	/// created the first time a session records under it.
1108	sessions: Lock<HashMap<Tier, HashMap<SessionKey, Arc<SessionCounters>>>>,
1109	wire: Lock<Vec<Weak<WireInner>>>,
1110}
1111
1112/// The `(root, label)` a tier's session gauges are keyed by.
1113type SessionKey = (Path, Path);
1114
1115/// Per-broadcast counters, lazily split by tier. A tier's [`TierCounters`] is
1116/// created the first time a guard records under that label, so the set of tiers
1117/// is fully dynamic. A [`Scope`] resolves the `Arc<TierCounters>` once per session
1118/// tier and hands it to the guards and meters it creates, so the per-byte path
1119/// never touches this map.
1120struct BroadcastEntry {
1121	tiers: Mutex<HashMap<Tier, Arc<TierCounters>>>,
1122}
1123
1124impl BroadcastEntry {
1125	fn new() -> Self {
1126		Self {
1127			tiers: Mutex::new(HashMap::new()),
1128		}
1129	}
1130
1131	/// Get-or-create the counters for `tier` on this broadcast.
1132	fn tier(&self, tier: &Tier) -> Arc<TierCounters> {
1133		self.tiers
1134			.lock()
1135			.unwrap_or_else(PoisonError::into_inner)
1136			.entry(tier.clone())
1137			.or_default()
1138			.clone()
1139	}
1140}
1141
1142/// Publisher and subscriber [`Counters`] for one `(broadcast, tier)`. The two
1143/// sides are named explicitly (rather than indexed by a `Role` enum) because
1144/// the bump-path call sites always know which side they're on at compile time.
1145#[derive(Default)]
1146struct TierCounters {
1147	publisher: Counters,
1148	subscriber: Counters,
1149}
1150
1151impl Registry {
1152	/// Build an enabled registry from `config`.
1153	pub fn new(config: Config) -> Self {
1154		let Config {
1155			exclude,
1156			exclude_rooted,
1157		} = config;
1158		Self {
1159			exclude,
1160			exclude_rooted,
1161			shared: Some(Arc::new(Shared {
1162				retired: Lock::default(),
1163				entries: Lock::default(),
1164				sessions: Default::default(),
1165				wire: Lock::default(),
1166			})),
1167		}
1168	}
1169
1170	/// Build a no-op registry: every handle is empty and all bumps are dropped.
1171	pub fn disabled() -> Self {
1172		Self {
1173			exclude: Prefixes::new(),
1174			exclude_rooted: Prefixes::new(),
1175			shared: None,
1176		}
1177	}
1178
1179	/// Whether this registry collects counters.
1180	pub fn is_enabled(&self) -> bool {
1181		self.shared.is_some()
1182	}
1183
1184	/// The shared state, panicking for a disabled registry. Tests build enabled
1185	/// registries so this is always present.
1186	#[cfg(test)]
1187	fn shared(&self) -> &Arc<Shared> {
1188		self.shared.as_ref().expect("enabled stats registry")
1189	}
1190
1191	/// Returns a tier-scoped handle. Bumps through this handle land in the
1192	/// tier's counters.
1193	pub fn tier(&self, tier: Tier) -> Handle {
1194		Handle {
1195			stats: self.clone(),
1196			tier,
1197		}
1198	}
1199
1200	/// Add `n` publisher-side payload bytes on `(path, tier)`. The `fuzz`
1201	/// module exposes this to the stats producer bench. A report drops the entry
1202	/// unless a guard still holds it.
1203	#[cfg(any(test, feature = "fuzz"))]
1204	#[cfg(feature = "async")]
1205	pub(crate) fn bump_publisher_bytes(&self, path: impl Into<Path>, tier: &Tier, n: u64) {
1206		let Some(entry) = self.entry(path, &Path::empty()) else {
1207			return;
1208		};
1209		entry.tier(tier).publisher.bytes.fetch_add(n, Ordering::Relaxed);
1210	}
1211
1212	/// Resolve the pre-label payload meter used as the stats write benchmark's baseline.
1213	#[cfg(any(test, feature = "fuzz"))]
1214	#[cfg(feature = "async")]
1215	pub(crate) fn publisher_meter(&self, path: impl Into<Path>, tier: &Tier) -> Meter {
1216		Meter {
1217			counters: self.entry(path, &Path::empty()).map(|entry| entry.tier(tier)),
1218			traffic: None,
1219			side: Side::Publisher,
1220			delegated: false,
1221		}
1222	}
1223
1224	/// The counters for `path`, as a session scoped to `root` counts it.
1225	fn entry(&self, path: impl Into<Path>, root: &Path) -> Option<Arc<BroadcastEntry>> {
1226		// A disabled registry never allocates state.
1227		let shared = self.shared.as_ref()?;
1228		let path: Path = path.into();
1229		// Skip excluded paths (our own stats broadcasts and any sibling category
1230		// under the same prefix) so serving a stats broadcast doesn't generate
1231		// more stats.
1232		if self.exclude.matches(path.as_str()) {
1233			return None;
1234		}
1235		if !self.exclude_rooted.is_empty()
1236			&& let Some(relative) = path.strip_prefix(root)
1237			&& self.exclude_rooted.matches(relative.as_str())
1238		{
1239			return None;
1240		}
1241		let mut entries = shared.entries.lock();
1242		Some(
1243			entries
1244				.entry(path)
1245				.or_insert_with(|| Arc::new(BroadcastEntry::new()))
1246				.clone(),
1247		)
1248	}
1249
1250	/// Get-or-create the session gauge for `label` under `root` on `tier`. `None`
1251	/// for a disabled registry. Unlike [`Self::entry`], labels key sessions rather
1252	/// than broadcasts, so no cycle-breaking filter is needed.
1253	fn session_counters(&self, tier: &Tier, root: &Path, label: &Path) -> Option<Arc<SessionCounters>> {
1254		let shared = self.shared.as_ref()?;
1255		let mut sessions = shared.sessions.lock();
1256		Some(
1257			sessions
1258				.entry(tier.clone())
1259				.or_default()
1260				.entry((root.clone(), label.clone()))
1261				.or_default()
1262				.clone(),
1263		)
1264	}
1265
1266	/// Take a host-level [`Snapshot`]: every counter summed across all
1267	/// tracked broadcasts, split by tier and role, plus per-tier session
1268	/// presence. Briefly takes the entry then the session locks. Returns an
1269	/// all-zero snapshot for a disabled registry.
1270	///
1271	/// Unlike [`Registry::report`], this collapses per-broadcast detail into
1272	/// node lifetime totals (what a `/metrics`-style scrape wants) and never prunes.
1273	/// Retired entries remain in these totals after [`Self::report`] prunes them.
1274	pub fn snapshot(&self) -> Snapshot {
1275		self.snapshot_at(Instant::now())
1276	}
1277
1278	fn snapshot_at(&self, now: Instant) -> Snapshot {
1279		self.collect_wire();
1280		let Some(shared) = self.shared.as_ref() else {
1281			return Snapshot::default();
1282		};
1283		let retired = shared.retired.lock();
1284		let mut snap = retired.clone();
1285		{
1286			let entries = shared.entries.lock();
1287			for entry in entries.values() {
1288				let tiers = entry.tiers.lock().unwrap_or_else(PoisonError::into_inner);
1289				for (tier, counters) in tiers.iter() {
1290					let totals = snap.traffic.entry(tier.clone()).or_default();
1291					totals[Role::Publisher.idx()].add(counters.publisher.snapshot());
1292					totals[Role::Subscriber.idx()].add(counters.subscriber.snapshot());
1293				}
1294			}
1295		}
1296		{
1297			let sessions = shared.sessions.lock();
1298			for (tier, labels) in sessions.iter() {
1299				let totals = snap.sessions.entry(tier.clone()).or_default();
1300				let activity = snap.activity.entry(tier.clone()).or_default();
1301				for counters in labels.values() {
1302					let (presence, active, _) = counters.snapshot(now);
1303					totals.add(presence);
1304					activity.add(active);
1305					counters.control(snap.control.entry(tier.clone()).or_default());
1306				}
1307			}
1308		}
1309		// A tier whose sessions were all pruned still reports, as zero connected.
1310		for tier in snap.sessions.keys() {
1311			snap.activity.entry(tier.clone()).or_default();
1312		}
1313		snap
1314	}
1315
1316	/// Refill `report` with the per-broadcast detail and prune dead entries.
1317	///
1318	/// Clears `report`, keeping its capacity so a caller draining on an
1319	/// interval reuses one report instead of allocating per drain, then fills
1320	/// every `(broadcast, tier)` traffic readout and every `(tier, root, label)`
1321	/// session gauge. Entries no guard references anymore are dropped after
1322	/// their final readout, which is marked `closed`, so a publisher draining on
1323	/// an interval sees the closing readout exactly once. A pruned path that
1324	/// sees traffic again restarts from zero; see the module docs on counter
1325	/// resets. Leaves the report empty for a disabled registry.
1326	///
1327	/// `now` is the drain's time, usually [`Instant::now`], which dates each
1328	/// session's activity window.
1329	pub fn report(&self, report: &mut Report, now: Instant) {
1330		self.collect_wire();
1331		report.traffic.clear();
1332		report.sessions.clear();
1333		let Some(shared) = self.shared.as_ref() else {
1334			return;
1335		};
1336		let mut retired = shared.retired.lock();
1337		// Each readout decides its prune first. Counters only the map holds can't
1338		// be reached by any guard (a new one needs the map lock held here), so
1339		// their readout is final: it is marked closed, folded into the retired
1340		// totals, and dropped, with no bump able to land after it.
1341		shared.entries.lock().retain(|path, entry| {
1342			let free = Arc::strong_count(entry) == 1;
1343			let mut tiers = entry.tiers.lock().unwrap_or_else(PoisonError::into_inner);
1344			tiers.retain(|tier, counters| {
1345				let closed = free && Arc::strong_count(counters) == 1;
1346				let (publisher, publisher_since) = counters.publisher.readout();
1347				let (subscriber, subscriber_since) = counters.subscriber.readout();
1348				report.traffic.push(TrafficEntry {
1349					path: path.clone(),
1350					tier: tier.clone(),
1351					publisher,
1352					subscriber,
1353					announced: Announced {
1354						publisher: publisher_since,
1355						subscriber: subscriber_since,
1356					},
1357					closed,
1358				});
1359				if closed {
1360					let totals = retired.traffic.entry(tier.clone()).or_default();
1361					totals[Role::Publisher.idx()].add(publisher);
1362					totals[Role::Subscriber.idx()].add(subscriber);
1363				}
1364				!closed
1365			});
1366			!free || !tiers.is_empty()
1367		});
1368
1369		shared.sessions.lock().retain(|tier, labels| {
1370			labels.retain(|(root, label), counters| {
1371				// Nothing can join a row only the map holds (that needs the lock held here),
1372				// but a meter outliving its session still writes until its last clone drops.
1373				let unheld = Arc::strong_count(counters) == 1;
1374				let (presence, _, empty) = counters.snapshot(now);
1375				let closed = unheld && empty;
1376				report.sessions.push(SessionEntry {
1377					tier: tier.clone(),
1378					root: root.clone(),
1379					label: label.clone(),
1380					presence,
1381					closed,
1382				});
1383				if closed {
1384					retired.sessions.entry(tier.clone()).or_default().add(presence);
1385					counters.control(retired.control.entry(tier.clone()).or_default());
1386				}
1387				!closed
1388			});
1389			!labels.is_empty()
1390		});
1391	}
1392
1393	/// Sample each source once before taking the counter maps, independently of held tracks.
1394	fn collect_wire(&self) {
1395		let Some(shared) = &self.shared else { return };
1396		// A sourced sample makes a syscall, so sample outside the lock each new connection takes.
1397		// A closed source samples nothing; its entry goes once its guard drops.
1398		let live: Vec<_> = {
1399			let mut wire = shared.wire.lock();
1400			wire.retain(|source| source.strong_count() > 0);
1401			wire.iter().filter_map(Weak::upgrade).collect()
1402		};
1403		for source in live {
1404			source.sample(false);
1405		}
1406	}
1407}
1408
1409impl Default for Registry {
1410	/// A disabled (no-op) registry; see [`Registry::disabled`].
1411	fn default() -> Self {
1412		Self::disabled()
1413	}
1414}
1415
1416/// Tier-scoped wrapper around [`Registry`]. What `crate::Client::with_stats` and
1417/// `crate::Server::with_stats` accept. Cheap to clone.
1418#[derive(Clone)]
1419pub struct Handle {
1420	stats: Registry,
1421	tier: Tier,
1422}
1423
1424/// A refused session, as [`Handle::refuse`] counts it.
1425#[derive(Clone, Debug)]
1426#[non_exhaustive]
1427pub struct Refusal {
1428	/// The session's resolved stats label.
1429	pub label: Path,
1430	/// Why it was refused.
1431	pub reason: RefusalKind,
1432}
1433
1434impl Refusal {
1435	/// A session under `label`, refused for `reason`.
1436	pub fn new(label: impl Into<Path>, reason: RefusalKind) -> Self {
1437		Self {
1438			label: label.into(),
1439			reason,
1440		}
1441	}
1442}
1443
1444/// A connected session or admitted request, as [`Handle::session`] and
1445/// [`Handle::request`] record it.
1446#[derive(Clone, Debug)]
1447#[non_exhaustive]
1448pub struct SessionInfo {
1449	/// The session's resolved stats label.
1450	pub label: Path,
1451	/// The origin root the session is scoped to, empty (the default) for none.
1452	/// Fixed for the session's life: a [`Session::retag`] keeps it.
1453	pub root: Path,
1454}
1455
1456impl SessionInfo {
1457	/// A session under `label`, without a root.
1458	pub fn new(label: impl Into<Path>) -> Self {
1459		Self {
1460			label: label.into(),
1461			root: Path::empty(),
1462		}
1463	}
1464
1465	/// Set the root the session is scoped to.
1466	pub fn with_root(mut self, root: impl Into<Path>) -> Self {
1467		self.root = root.into();
1468		self
1469	}
1470}
1471
1472impl Handle {
1473	/// Count a session refused outside relay admission under its resolved label and tier.
1474	pub fn refuse(&self, refusal: Refusal) {
1475		if let Some(presence) = self.stats.session_counters(&self.tier, &Path::empty(), &refusal.label) {
1476			presence
1477				.sessions_refused
1478				.counter(refusal.reason)
1479				.fetch_add(1, Ordering::Relaxed);
1480		}
1481	}
1482
1483	/// Record a connected session on this tier. Hold the returned guard for
1484	/// the session's lifetime; dropping it bumps `sessions_ended`. Counts
1485	/// presence regardless of any data flow, so a session that merely connects
1486	/// is still billable. Surfaced on the session track for this tier, keyed by
1487	/// its label, in its totals, and in that label's presence track.
1488	pub fn session(&self, session: SessionInfo) -> Session {
1489		self.context(session, Context::Session)
1490	}
1491
1492	/// Count one admitted request under its label and root, and meter its traffic
1493	/// without session presence.
1494	///
1495	/// A request has no session end to classify, so it never records a failure.
1496	pub fn request(&self, request: SessionInfo) -> Session {
1497		self.context(request, Context::Request)
1498	}
1499
1500	fn context(&self, info: SessionInfo, context: Context) -> Session {
1501		let SessionInfo { label, root } = info;
1502		let presence = self.stats.session_counters(&self.tier, &root, &label);
1503		if let Some(presence) = &presence {
1504			match context {
1505				Context::Session => {
1506					presence.sessions_started.fetch_add(1, Ordering::Relaxed);
1507				}
1508				Context::Request => {
1509					presence.requests.fetch_add(1, Ordering::Relaxed);
1510				}
1511			}
1512		}
1513		let traffic = Arc::new(SessionTraffic {
1514			connected: AtomicBool::new(matches!(context, Context::Session)),
1515			..Default::default()
1516		});
1517		if let Some(presence) = &presence {
1518			let sample = Sample {
1519				seen: (0, 0),
1520				moved: None,
1521			};
1522			presence.bytes().join(traffic.clone(), (0, 0), sample);
1523		}
1524		Session {
1525			inner: Some(SendCell::new(Arc::new(SessionInner {
1526				registry: self.stats.clone(),
1527				root,
1528				connected: matches!(context, Context::Session),
1529				current: Mutex::new(Current {
1530					failure: None,
1531					tier: self.tier.clone(),
1532					label,
1533					presence,
1534				}),
1535				traffic,
1536				generation: AtomicU64::new(0),
1537				viewers: Mutex::new(HashMap::new()),
1538				held: Mutex::new(Vec::new()),
1539				wire: Mutex::new(Vec::new()),
1540			}))),
1541		}
1542	}
1543}
1544
1545impl Default for Handle {
1546	/// A no-op handle backed by a disabled [`Registry`].
1547	fn default() -> Self {
1548		Registry::disabled().tier(Tier::default())
1549	}
1550}
1551
1552enum Context {
1553	Session,
1554	Request,
1555}
1556
1557/// Registered wire counters; dropping this adds their final reading and unregisters them.
1558#[derive(Default)]
1559pub struct Wire {
1560	inner: Option<Arc<WireInner>>,
1561}
1562
1563struct WireInner {
1564	session: SendCell<Arc<SessionInner>>,
1565	counters: crate::transport::Wire,
1566	last: Mutex<WireState>,
1567}
1568
1569#[derive(Default)]
1570struct WireState {
1571	/// The [`WIRE`] counters as last read.
1572	read: [u64; Presence::WIRE_FIELDS],
1573	closed: bool,
1574}
1575
1576/// How to read each counter a transport's [`crate::transport::Wire`] carries, in the order of the
1577/// [`Presence::wire_mut`] fields that sum them.
1578const WIRE: [fn(&crate::transport::Wire) -> u64; Presence::WIRE_FIELDS] = [
1579	|wire| wire.sent_bytes(),
1580	|wire| wire.received_bytes(),
1581	|wire| wire.lost_bytes(),
1582	|wire| wire.credit_stalls(),
1583	|wire| crate::transport::micros(wire.credit_stalled()),
1584	|wire| crate::transport::micros(wire.credit_held_readers()),
1585	|wire| crate::transport::micros(wire.credit_held_evicted()),
1586	|wire| crate::transport::micros(wire.cwnd_blocked()),
1587	|wire| crate::transport::micros(wire.pacing_blocked()),
1588];
1589
1590impl WireInner {
1591	fn sample(&self, close: bool) -> bool {
1592		let current = self.session.current.lock().unwrap_or_else(PoisonError::into_inner);
1593		self.sample_on(&current, close)
1594	}
1595
1596	/// Current always precedes last: tier changes and a tick cannot attribute one reading twice.
1597	fn sample_on(&self, current: &Current, close: bool) -> bool {
1598		let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
1599		if last.closed {
1600			return false;
1601		};
1602		// Refresh under `last`: a source's setters are plain stores, so two samplers refreshing
1603		// unlocked could leave an older reading over a newer one and count the gap twice.
1604		self.counters.refresh();
1605		let read = WIRE.map(|read| read(&self.counters));
1606		if let Some(presence) = &current.presence {
1607			for ((counter, now), then) in presence.wire.iter().zip(read).zip(last.read) {
1608				// Most counters hold still between ticks, and an atomic add costs even when zero.
1609				let delta = now.saturating_sub(then);
1610				if delta > 0 {
1611					counter.fetch_add(delta, Ordering::Relaxed);
1612				}
1613			}
1614		}
1615		*last = WireState { read, closed: close };
1616		!close
1617	}
1618}
1619
1620impl Drop for Wire {
1621	fn drop(&mut self) {
1622		if let Some(inner) = &self.inner {
1623			inner.sample(true);
1624		}
1625	}
1626}
1627
1628/// Which side of a [`TierCounters`] a bump lands on: publisher (egress) or
1629/// subscriber (ingress). `Default` is `Publisher`, chosen only so an empty
1630/// [`Meter`] / [`Scope`] has one; it never records because its counters are `None`.
1631#[derive(Copy, Clone, Default)]
1632enum Side {
1633	#[default]
1634	Publisher,
1635	Subscriber,
1636}
1637
1638impl Side {
1639	fn counters(self, tier: &TierCounters) -> &Counters {
1640		match self {
1641			Side::Publisher => &tier.publisher,
1642			Side::Subscriber => &tier.subscriber,
1643		}
1644	}
1645}
1646
1647/// Traffic context for a connection or request, created by [`Handle::session`] or [`Handle::request`].
1648///
1649/// Cheap to clone (an `Arc` inside): one context is shared by both origin handles
1650/// of a session (its publish and subscribe halves) so presence and viewer counts
1651/// are never double-attributed. It carries three things:
1652///
1653/// * the tier and label, so any broadcast reached through a tagged origin handle
1654///   resolves the right per-`(path, tier)` counters and its bytes count toward the label,
1655/// * the presence gauge: `sessions_started` bumps when the context is created and
1656///   `sessions_ended` when the last clone drops; a request instead bumps `requests`
1657///   once at admission and never touches session presence,
1658/// * the egress viewer refcount map (first/last active subscription per broadcast),
1659///   driving `broadcasts_started` / `broadcasts_ended`.
1660///
1661/// [`Session::retag`] moves a live context to another tier and label: presence and traffic
1662/// recorded afterwards land there, while what was already counted stays put and an
1663/// open subscription or announce closes on the tier it opened on.
1664///
1665/// [`Session::default`] is the no-op context (disabled registry / untagged caller):
1666/// every bump reached through it is silently dropped, so a handle can hold one
1667/// unconditionally instead of threading an `Option`.
1668#[derive(Clone, Default)]
1669pub struct Session {
1670	/// `None` for the no-op context (disabled registry or a `default()` handle).
1671	///
1672	/// The context and its wire counters reference each other, so every future
1673	/// holding a context would repeat that recursive Send proof; [`SendCell`]
1674	/// checks it once here.
1675	inner: Option<SendCell<Arc<SessionInner>>>,
1676}
1677
1678/// Which peak a [`Session::hold`] raises.
1679#[derive(Clone, Copy, Debug)]
1680pub(crate) enum Cap {
1681	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1682	Announces,
1683	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1684	Subscriptions,
1685}
1686
1687/// The shared traffic context; its last clone closes presence only for a session.
1688struct SessionInner {
1689	/// Requests meter traffic but never open or close connected-session presence.
1690	connected: bool,
1691	registry: Registry,
1692	/// The origin root the session is scoped to; a retag keeps it.
1693	root: Path,
1694	/// The current tier, label, and presence gauge, swapped together by [`Session::retag`].
1695	current: Mutex<Current>,
1696	/// This session's payload bytes, shared with the meters it hands out.
1697	traffic: Arc<SessionTraffic>,
1698	/// Bumped on every tier or label change, so a [`Scope`] notices without taking a lock.
1699	generation: AtomicU64,
1700	/// Egress viewer refcount, keyed by absolute broadcast path: the first active
1701	/// subscription this context opens for a broadcast bumps `broadcasts_started`, the last
1702	/// to close bumps `broadcasts_ended` on the same counters, even across a tier change.
1703	viewers: Mutex<HashMap<Path, Viewer>>,
1704	/// What this session holds against each cap right now, so a tier change can seed the
1705	/// new tier's peaks with slots it still holds.
1706	held: Mutex<Vec<(Cap, Weak<AtomicUsize>)>>,
1707	/// Weak, because a wire guard retains this context until its final reading.
1708	wire: Mutex<Vec<Weak<WireInner>>>,
1709}
1710
1711/// The tier and label a [`Session`] records under right now.
1712struct Current {
1713	failure: Option<Failure>,
1714	tier: Tier,
1715	label: Path,
1716	/// The presence gauge for `(tier, label)`, or `None` for a disabled registry.
1717	presence: Option<Arc<SessionCounters>>,
1718}
1719
1720/// One session's payload bytes. Its meters write here, never to a shared row, so a
1721/// meter handed out before a retag still counts toward the session's current label.
1722#[derive(Default, Debug)]
1723struct SessionTraffic {
1724	sent: AtomicU64,
1725	received: AtomicU64,
1726	/// A connected session that has not ended: its [`Activity`] counts. Requests never set it.
1727	connected: AtomicBool,
1728}
1729
1730impl SessionTraffic {
1731	fn load(&self) -> (u64, u64) {
1732		(self.sent.load(Ordering::Relaxed), self.received.load(Ordering::Relaxed))
1733	}
1734}
1735
1736/// One broadcast's viewer refcount within a [`Session`].
1737struct Viewer {
1738	subscriptions: u32,
1739	/// The counters `broadcasts_started` bumped on, where `broadcasts_ended` lands too.
1740	counters: Arc<TierCounters>,
1741}
1742
1743impl Session {
1744	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1745	pub(crate) fn control(&self, class: Message, bytes: usize, received: bool) {
1746		let Some(inner) = &self.inner else { return };
1747		let current = inner.current.lock().unwrap_or_else(PoisonError::into_inner);
1748		if let Some(counters) = &current.presence {
1749			let counters = &counters.control[class as usize];
1750			counters[usize::from(received)].fetch_add(bytes as u64, Ordering::Relaxed);
1751			counters[2 + usize::from(received)].fetch_add(1, Ordering::Relaxed);
1752		}
1753	}
1754
1755	/// Count a connection's wire counters under this context's label, following its retags.
1756	pub fn wire(&self, counters: crate::transport::Wire) -> Wire {
1757		let Some(inner) = &self.inner else {
1758			return Wire::default();
1759		};
1760		let Some(shared) = &inner.registry.shared else {
1761			return Wire::default();
1762		};
1763		let source = Arc::new(WireInner {
1764			session: inner.clone(),
1765			counters,
1766			last: Mutex::new(WireState::default()),
1767		});
1768		{
1769			let mut wire = inner.wire.lock().unwrap_or_else(PoisonError::into_inner);
1770			wire.retain(|source| source.strong_count() > 0);
1771			wire.push(Arc::downgrade(&source));
1772		}
1773		shared.wire.lock().push(Arc::downgrade(&source));
1774		Wire { inner: Some(source) }
1775	}
1776
1777	/// Record how a transport session under this connected context ended, shared across
1778	/// clones. A reconnect's later end replaces an earlier one, so the context fails only
1779	/// if its last session did.
1780	///
1781	/// Only a context from [`Handle::session`] has an end to classify: on one from
1782	/// [`Handle::request`] this records nothing.
1783	#[cfg(any(feature = "async", test))]
1784	pub(crate) fn end(&self, err: &crate::Error) {
1785		let Some(inner) = &self.inner else { return };
1786		if !inner.connected {
1787			return;
1788		}
1789		inner.current.lock().unwrap_or_else(PoisonError::into_inner).failure = Failure::of(err);
1790	}
1791
1792	/// Record later traffic and session presence under `(tier, label)`; a request stays counted where admitted.
1793	pub fn retag(&self, tier: Tier, label: impl Into<Path>) {
1794		let Some(inner) = &self.inner else { return };
1795		let label = label.into();
1796		let mut current = inner.current.lock().unwrap_or_else(PoisonError::into_inner);
1797		if current.tier == tier && current.label == label {
1798			return;
1799		}
1800		inner
1801			.wire
1802			.lock()
1803			.unwrap_or_else(PoisonError::into_inner)
1804			.retain(|source| {
1805				let Some(source) = source.upgrade() else { return false };
1806				source.sample_on(&current, false)
1807			});
1808		let presence = inner.registry.session_counters(&tier, &inner.root, &label);
1809		// Bytes before the cut stay on the old row; later ones, through any meter, go to the new.
1810		let (cut, sample) = match &current.presence {
1811			Some(old) => old.bytes().leave(&inner.traffic),
1812			None => {
1813				let cut = inner.traffic.load();
1814				(cut, Sample { seen: cut, moved: None })
1815			}
1816		};
1817		if let Some(presence) = &presence {
1818			presence.bytes().join(inner.traffic.clone(), cut, sample);
1819		}
1820		if inner.connected
1821			&& let Some(presence) = &presence
1822		{
1823			presence.sessions_started.fetch_add(1, Ordering::Relaxed);
1824		}
1825		if let Some(presence) = &presence {
1826			// Slots still held count on the new tier, but not the old tier's history.
1827			let mut held = inner.held.lock().unwrap_or_else(PoisonError::into_inner);
1828			held.retain(|(cap, live)| {
1829				let Some(live) = live.upgrade() else { return false };
1830				presence
1831					.peak(*cap)
1832					.fetch_max(live.load(Ordering::Acquire) as u64, Ordering::Relaxed);
1833				true
1834			});
1835		}
1836		if let Some(old) = std::mem::replace(&mut current.presence, presence.clone())
1837			&& inner.connected
1838		{
1839			// Release pairs with the readout's Acquire load of `sessions_ended`.
1840			old.sessions_ended.fetch_add(1, Ordering::Release);
1841		}
1842		current.tier = tier;
1843		current.label = label;
1844		inner.generation.fetch_add(1, Ordering::Release);
1845	}
1846
1847	/// Count `live` as what this session holds against `cap`, so a tier change carries it.
1848	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1849	pub(crate) fn track_held(&self, cap: Cap, live: &Arc<AtomicUsize>) {
1850		let Some(inner) = &self.inner else { return };
1851		let mut held = inner.held.lock().unwrap_or_else(PoisonError::into_inner);
1852		// A context reused across reconnects registers again each time: drop the gone ones.
1853		held.retain(|(_, live)| live.strong_count() > 0);
1854		held.push((cap, Arc::downgrade(live)));
1855	}
1856
1857	/// Record that this session holds `held` of what `cap` limits, raising that peak on its
1858	/// tier and label.
1859	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1860	pub(crate) fn hold(&self, cap: Cap, held: u64) {
1861		let Some(inner) = &self.inner else { return };
1862		let current = inner.current.lock().unwrap_or_else(PoisonError::into_inner);
1863		let Some(presence) = &current.presence else { return };
1864		presence.peak(cap).fetch_max(held, Ordering::Relaxed);
1865	}
1866
1867	/// Count a route or claim the peer forwarded that this node refused.
1868	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1869	pub(crate) fn refuse_route(&self, kind: RouteRefusal) {
1870		self.refuse_routes(kind, 1);
1871	}
1872
1873	/// Count `count` routes or claims the peer forwarded that this node refused.
1874	pub(crate) fn refuse_routes(&self, kind: RouteRefusal, count: u64) {
1875		if count > 0 {
1876			self.routes(|routes| routes.refused.add(kind, count));
1877		}
1878	}
1879
1880	/// Count a change to a relay's route that the peer caused, and the broadcasts it rewrote.
1881	pub(crate) fn route_changed(&self, rewritten: u64) {
1882		self.routes(|routes| routes.changed(rewritten));
1883	}
1884
1885	/// Count a withdrawal sent to the peer, or `received` from it.
1886	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1887	pub(crate) fn withdrawal(&self, kind: Withdrawal, received: bool) {
1888		self.routes(|routes| match received {
1889			true => routes.received.add(kind, 1),
1890			false => routes.sent.add(kind, 1),
1891		});
1892	}
1893
1894	/// Count the session closing for its route layer.
1895	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1896	pub(crate) fn route_closed(&self, kind: RouteClose) {
1897		self.routes(|routes| routes.closed.add(kind, 1));
1898	}
1899
1900	fn routes(&self, bump: impl FnOnce(&RouteCounters)) {
1901		let Some(inner) = &self.inner else { return };
1902		let current = inner.current.lock().unwrap_or_else(PoisonError::into_inner);
1903		let Some(presence) = &current.presence else { return };
1904		bump(&presence.routes);
1905	}
1906
1907	/// Egress (publisher / reads) scope for a broadcast path. The path is the
1908	/// absolute broadcast name.
1909	pub(crate) fn egress(&self, path: impl Into<Path>) -> Scope {
1910		self.scope(path, Side::Publisher)
1911	}
1912
1913	/// Ingress (subscriber / writes) scope for a broadcast path.
1914	pub(crate) fn ingress(&self, path: impl Into<Path>) -> Scope {
1915		self.scope(path, Side::Subscriber)
1916	}
1917
1918	fn scope(&self, path: impl Into<Path>, side: Side) -> Scope {
1919		let Some(inner) = &self.inner else {
1920			return Scope::default();
1921		};
1922		let path = path.into();
1923		let resolved = inner.resolve(&path);
1924		Scope {
1925			session: self.clone(),
1926			resolved: Some(Box::new(Mutex::new(resolved))),
1927			side,
1928			path,
1929			billed: false,
1930		}
1931	}
1932
1933	/// Register one active egress subscription to `path` recording on `counters`.
1934	/// The first bumps `broadcasts_started` there.
1935	fn viewer_open(&self, path: &Path, counters: &Arc<TierCounters>) {
1936		let Some(inner) = &self.inner else { return };
1937		let mut viewers = inner.viewers.lock().unwrap_or_else(PoisonError::into_inner);
1938		let viewer = viewers.entry(path.clone()).or_insert_with(|| {
1939			counters.publisher.broadcasts_started.fetch_add(1, Ordering::Relaxed);
1940			Viewer {
1941				subscriptions: 0,
1942				counters: counters.clone(),
1943			}
1944		});
1945		viewer.subscriptions += 1;
1946	}
1947
1948	/// Release one active egress subscription to `path`. The last bumps
1949	/// `broadcasts_ended` on the counters the first opened on.
1950	fn viewer_close(&self, path: &Path) {
1951		let Some(inner) = &self.inner else { return };
1952		let mut viewers = inner.viewers.lock().unwrap_or_else(PoisonError::into_inner);
1953		let Some(viewer) = viewers.get_mut(path) else { return };
1954		viewer.subscriptions -= 1;
1955		if viewer.subscriptions == 0
1956			&& let Some(viewer) = viewers.remove(path)
1957		{
1958			// Release pairs with the readout's Acquire load of `broadcasts_ended`.
1959			viewer
1960				.counters
1961				.publisher
1962				.broadcasts_ended
1963				.fetch_add(1, Ordering::Release);
1964		}
1965	}
1966}
1967
1968impl SessionInner {
1969	/// The counters `path` records on under the current tier, tagged with the
1970	/// generation they were resolved at.
1971	fn resolve(&self, path: &Path) -> Resolved {
1972		let (generation, tier) = {
1973			let current = self.current.lock().unwrap_or_else(PoisonError::into_inner);
1974			(self.generation.load(Ordering::Relaxed), current.tier.clone())
1975		};
1976		Resolved {
1977			generation,
1978			counters: self.registry.entry(path, &self.root).map(|entry| entry.tier(&tier)),
1979		}
1980	}
1981}
1982
1983impl Drop for SessionInner {
1984	fn drop(&mut self) {
1985		// Meters may outlive the session; the ended session is neither idle nor active.
1986		self.traffic.connected.store(false, Ordering::Relaxed);
1987		let current = self.current.get_mut().expect("stats session poisoned");
1988		if self.connected
1989			&& let Some(presence) = &current.presence
1990		{
1991			// Release pairs with the readout's Acquire load of `sessions_ended`
1992			// (see the module-level "Snapshot atomicity" note).
1993			presence.sessions_ended.fetch_add(1, Ordering::Release);
1994			if let Some(kind) = current.failure {
1995				// Read failures before ended; this release also publishes its matching end.
1996				presence.sessions_failed.counter(kind).fetch_add(1, Ordering::Release);
1997			}
1998		}
1999	}
2000}
2001
2002// ---------------------------------------------------------------------------
2003// Model-layer carriers
2004//
2005// These are what a tagged `origin::{Consumer, Producer}` threads down through the
2006// derived handles (broadcast -> track -> group -> frame). A tagged origin creates a
2007// [`Scope`] per broadcast, which resolves the per-`(path, tier)` counters again
2008// only after [`Session::retag`]; child handles carry a cheap [`Meter`] for the
2009// payload bumps, fixed to the tier the group started under. All of them are no-ops when empty (a
2010// disabled registry, an excluded path, or an untagged caller), so an untagged
2011// handle pays nothing.
2012// ---------------------------------------------------------------------------
2013
2014/// Payload bump handle carried by the group and frame model handles. Cheap to
2015/// clone (an `Option<Arc>` plus a `Side`); empty when the broadcast is untracked.
2016#[derive(Clone, Default)]
2017pub(crate) struct Meter {
2018	counters: Option<Arc<TierCounters>>,
2019	traffic: Option<Arc<SessionTraffic>>,
2020	side: Side,
2021	/// Set once a wire writer took over the payload counts, see [`Self::delegate`].
2022	delegated: bool,
2023}
2024
2025impl Meter {
2026	fn counters(&self) -> Option<&Counters> {
2027		self.counters.as_ref().map(|c| self.side.counters(c))
2028	}
2029
2030	/// The counters `frames` and `bytes` bump, none once the payload is [delegated](Self::delegate).
2031	fn payload(&self) -> Option<&Counters> {
2032		match self.delegated {
2033			true => None,
2034			false => self.counters(),
2035		}
2036	}
2037
2038	/// Hand the payload counts to the caller: this meter stops counting `frames` and `bytes`,
2039	/// and the returned one counts them for a wire writer as the transport delivers them.
2040	/// The rest (`groups`, `inflated`, `stale`) stays here.
2041	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2042	pub(crate) fn delegate(&mut self) -> Meter {
2043		self.delegated = true;
2044		Meter {
2045			delegated: false,
2046			..self.clone()
2047		}
2048	}
2049
2050	/// Bump `groups` once (a group delivered/consumed on this side).
2051	pub(crate) fn group(&self) {
2052		if let Some(counters) = self.counters() {
2053			counters.groups.fetch_add(1, Ordering::Relaxed);
2054		}
2055	}
2056
2057	/// Bump `frames` by `n`.
2058	pub(crate) fn frames(&self, n: u64) {
2059		if n == 0 {
2060			return;
2061		}
2062		if let Some(counters) = self.payload() {
2063			counters.frames.fetch_add(n, Ordering::Relaxed);
2064		}
2065	}
2066
2067	/// Record one datagram of `n` payload bytes, which belongs to no group.
2068	pub(crate) fn datagram(&self, n: u64) {
2069		if self.delegated {
2070			return;
2071		}
2072		if let Some(counters) = self.counters() {
2073			counters.datagrams.fetch_add(1, Ordering::Relaxed);
2074			counters.bytes.fetch_add(n, Ordering::Relaxed);
2075		}
2076		self.session_bytes(n);
2077	}
2078
2079	/// Whether this meter attributes anything, i.e. the broadcast is tracked and the
2080	/// handle was tagged. A caller holding a count that has to land exactly once can
2081	/// keep it rather than drop it into an untagged meter.
2082	pub(crate) fn is_tracked(&self) -> bool {
2083		self.counters.is_some()
2084	}
2085
2086	/// Bump `inflated` by `n`, bytes a plain read inflated from a compressed group.
2087	pub(crate) fn inflated(&self, n: u64) {
2088		if let Some(counters) = self.counters() {
2089			counters.inflated.fetch_add(n, Ordering::Relaxed);
2090		}
2091	}
2092
2093	/// Record content skipped before delivery by the drift budget.
2094	pub(crate) fn stale(&self, content: Content) {
2095		if let Some(counters) = self.counters() {
2096			counters.stale.add(content);
2097		}
2098	}
2099
2100	/// Bump `bytes` by `n`.
2101	pub(crate) fn bytes(&self, n: u64) {
2102		if n == 0 || self.delegated {
2103			return;
2104		}
2105		if let Some(counters) = self.counters() {
2106			counters.bytes.fetch_add(n, Ordering::Relaxed);
2107		}
2108		self.session_bytes(n);
2109	}
2110
2111	fn session_bytes(&self, n: u64) {
2112		if let Some(traffic) = &self.traffic {
2113			match self.side {
2114				Side::Publisher => &traffic.sent,
2115				Side::Subscriber => &traffic.received,
2116			}
2117			.fetch_add(n, Ordering::Relaxed);
2118		}
2119	}
2120}
2121
2122/// The payload a wire stream carries, billed to a delegated [`Meter`] as the transport delivers
2123/// it, so egress never counts bytes a reset or a lost session discarded.
2124///
2125/// Offsets are the stream's. A frame's bytes count as they are delivered, and the frame once
2126/// its last byte is.
2127#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2128pub(crate) struct Delivery {
2129	meter: Meter,
2130	/// Each frame not yet wholly delivered, oldest first: where its payload starts and ends.
2131	frames: std::collections::VecDeque<(u64, u64)>,
2132	/// The stream offset billed through.
2133	through: u64,
2134}
2135
2136#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
2137impl Delivery {
2138	pub(crate) fn new(meter: Meter) -> Self {
2139		Self {
2140			meter,
2141			frames: Default::default(),
2142			through: 0,
2143		}
2144	}
2145
2146	/// A frame whose payload is the stream's `start..start + size`, after every earlier one.
2147	pub(crate) fn frame(&mut self, start: u64, size: u64) {
2148		self.frames.push_back((start, start + size));
2149	}
2150
2151	/// Whether a frame's payload the stream took before offset `written` waits on delivery.
2152	pub(crate) fn waiting(&self, written: u64) -> bool {
2153		!self.frames.is_empty() && self.through < written
2154	}
2155
2156	/// The stream offset billed through.
2157	pub(crate) fn through(&self) -> u64 {
2158		self.through
2159	}
2160
2161	/// Whether a frame waiting on delivery ends after stream offset `after`, at or before `through`.
2162	pub(crate) fn ends_between(&self, after: u64, through: u64) -> bool {
2163		self.frames
2164			.iter()
2165			.rev()
2166			.find(|&&(_, end)| end <= through)
2167			.is_some_and(|&(_, end)| end > after)
2168	}
2169
2170	/// Bill the payload before stream offset `through`, which never goes back.
2171	pub(crate) fn deliver(&mut self, through: u64) {
2172		if through <= self.through {
2173			return;
2174		}
2175		let (mut bytes, mut frames) = (0, 0);
2176		while let Some(&(start, end)) = self.frames.front() {
2177			bytes += end.min(through).saturating_sub(start.max(self.through));
2178			if end > through {
2179				break;
2180			}
2181			frames += 1;
2182			self.frames.pop_front();
2183		}
2184		self.through = through;
2185		self.meter.frames(frames);
2186		self.meter.bytes(bytes);
2187	}
2188}
2189
2190/// The payload of a track a reader counts as it delivers it onward, rather than as it reads it.
2191///
2192/// For an in-process reader that drops some of what it reads, such as a gateway's jitter
2193/// buffer: what it reads and drops counts nothing. Taken from
2194/// [`track::Subscriber::bill`](crate::track::Subscriber::bill). Cheap to clone; the default
2195/// counts nothing.
2196#[derive(Clone, Default)]
2197pub struct Bill(Option<Arc<Scope>>);
2198
2199impl std::fmt::Debug for Bill {
2200	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2201		f.debug_struct("Bill")
2202			.field("path", &self.0.as_ref().map(|scope| &scope.path))
2203			.finish()
2204	}
2205}
2206
2207impl Bill {
2208	/// Count one frame of `bytes` payload as delivered.
2209	pub fn deliver(&self, bytes: u64) {
2210		if let Some(scope) = &self.0 {
2211			let meter = scope.meter();
2212			meter.frames(1);
2213			meter.bytes(bytes);
2214		}
2215	}
2216}
2217
2218/// A per-`(broadcast, side)` scope, carried by the broadcast and track model
2219/// handles. Created by a tagged origin at the broadcast handoff; hands out
2220/// [`Meter`]s for the payload path and RAII guards for the subscription / announce
2221/// lifecycle, each recording under the session's tier at the time. Cheap to clone;
2222/// empty (no-op) when the broadcast is untracked.
2223#[derive(Default)]
2224pub(crate) struct Scope {
2225	/// The owning context: its tier, and the egress viewer refcount map.
2226	session: Session,
2227	/// The counters for `(path, tier)`, re-resolved when the session changes tier.
2228	/// Per clone, so tracks sharing a broadcast never contend on the per-group path;
2229	/// boxed to keep every track handle small. `None` for the no-op context.
2230	resolved: Option<Box<Mutex<Resolved>>>,
2231	side: Side,
2232	/// Absolute broadcast path, used to key the viewer refcount and as the
2233	/// `announced_bytes` length.
2234	path: Path,
2235	/// Whether a [`Bill`] counts the payload instead, so the meters handed out count none.
2236	billed: bool,
2237}
2238
2239/// A [`Scope`]'s counters and the session tier generation they belong to.
2240#[derive(Clone)]
2241struct Resolved {
2242	generation: u64,
2243	/// `None` when untracked.
2244	counters: Option<Arc<TierCounters>>,
2245}
2246
2247impl Clone for Scope {
2248	fn clone(&self) -> Self {
2249		Self {
2250			session: self.session.clone(),
2251			resolved: self
2252				.resolved
2253				.as_ref()
2254				.map(|r| Box::new(Mutex::new(r.lock().unwrap_or_else(PoisonError::into_inner).clone()))),
2255			side: self.side,
2256			path: self.path.clone(),
2257			billed: self.billed,
2258		}
2259	}
2260}
2261
2262impl Scope {
2263	/// Whether this scope was tagged, a cheap pre-check that never resolves: an untagged
2264	/// scope's [`Meter`] counts nothing, but a tagged one's may count nothing either, when
2265	/// the registry is disabled or excludes its path, so [`Meter::is_tracked`] decides.
2266	pub(crate) fn is_tagged(&self) -> bool {
2267		self.session.inner.is_some() && self.resolved.is_some()
2268	}
2269
2270	/// The counters for the session's current tier. Skips the registry unless the
2271	/// tier changed since the last call, so the per-group path stays cheap.
2272	fn counters(&self) -> Option<Arc<TierCounters>> {
2273		let inner = self.session.inner.as_ref()?;
2274		let generation = inner.generation.load(Ordering::Acquire);
2275		let mut resolved = self.resolved.as_ref()?.lock().unwrap_or_else(PoisonError::into_inner);
2276		if resolved.generation != generation {
2277			*resolved = inner.resolve(&self.path);
2278		}
2279		resolved.counters.clone()
2280	}
2281
2282	/// A payload [`Meter`] for a group/frame derived from this scope.
2283	pub(crate) fn meter(&self) -> Meter {
2284		let counters = self.counters();
2285		// An excluded path counts nowhere, including its session's label.
2286		let traffic = counters
2287			.as_ref()
2288			.and(self.session.inner.as_ref())
2289			.map(|inner| inner.traffic.clone());
2290		Meter {
2291			counters,
2292			traffic,
2293			side: self.side,
2294			delegated: self.billed,
2295		}
2296	}
2297
2298	/// Hand the payload counts of the meters this scope hands out from now on to the returned
2299	/// [`Bill`].
2300	pub(crate) fn bill(&mut self) -> Bill {
2301		let bill = Bill(self.is_tagged().then(|| {
2302			Arc::new(Self {
2303				billed: false,
2304				..self.clone()
2305			})
2306		}));
2307		self.billed = true;
2308		bill
2309	}
2310
2311	/// Open a track-subscription guard: bumps `subscriptions_started` now and
2312	/// `subscriptions_ended` on drop. On the egress (publisher) side it also drives
2313	/// the context's viewer refcount (`broadcasts_started` / `broadcasts_ended`).
2314	pub(crate) fn subscribe(&self) -> Subscription {
2315		let counters = self.counters();
2316		let mut viewer = None;
2317		if let Some(counters) = &counters {
2318			self.side
2319				.counters(counters)
2320				.subscriptions_started
2321				.fetch_add(1, Ordering::Relaxed);
2322			// Viewer refcount is egress-only: `broadcasts_started` counts distinct sessions
2323			// watching a broadcast.
2324			if matches!(self.side, Side::Publisher) {
2325				self.session.viewer_open(&self.path, counters);
2326				viewer = Some((self.session.clone(), self.path.clone()));
2327			}
2328		}
2329		Subscription {
2330			counters,
2331			side: self.side,
2332			viewer,
2333		}
2334	}
2335
2336	/// Bump the `fetches` counter once (a coalesced group fetch served).
2337	pub(crate) fn fetch(&self) {
2338		if let Some(counters) = self.counters() {
2339			self.side.counters(&counters).fetches.fetch_add(1, Ordering::Relaxed);
2340		}
2341	}
2342
2343	/// Open an announce guard: bumps `announces_started` and adds the path length to
2344	/// `announced_bytes` now; on drop bumps `announces_ended` and adds the path
2345	/// length again. Used for egress announce-stream events and ingress
2346	/// route-transition (un)announces.
2347	pub(crate) fn announce(&self) -> Announce {
2348		let len = self.path.as_str().len() as u64;
2349		let counters = self.counters();
2350		if let Some(counters) = &counters {
2351			let counters = self.side.counters(counters);
2352			let mut held = counters.held.lock().unwrap_or_else(PoisonError::into_inner);
2353			counters.announces_started.fetch_add(1, Ordering::Relaxed);
2354			counters.announced_bytes.fetch_add(len, Ordering::Relaxed);
2355			if held.count == 0 {
2356				// Wall time, not an instant mapped onto it: readers compare starts across
2357				// nodes, and a mapping drifts by any suspend or clock step since it was fixed.
2358				held.since = Some(kio::clock::wall());
2359			}
2360			held.count += 1;
2361		}
2362		Announce {
2363			counters,
2364			side: self.side,
2365			len,
2366		}
2367	}
2368}
2369
2370/// RAII guard for a track subscription (either side). See [`Scope::subscribe`].
2371/// [`Subscription::default`] is an empty no-op guard.
2372#[derive(Default)]
2373#[must_use = "drop the guard to record the subscription as closed"]
2374pub(crate) struct Subscription {
2375	counters: Option<Arc<TierCounters>>,
2376	side: Side,
2377	/// `Some((session, path))` on the egress side, to release the viewer refcount.
2378	viewer: Option<(Session, Path)>,
2379}
2380
2381impl Drop for Subscription {
2382	fn drop(&mut self) {
2383		if let Some((session, path)) = &self.viewer {
2384			session.viewer_close(path);
2385		}
2386		if let Some(counters) = &self.counters {
2387			// Release pairs with the readout's Acquire load of `subscriptions_ended`.
2388			self.side
2389				.counters(counters)
2390				.subscriptions_ended
2391				.fetch_add(1, Ordering::Release);
2392		}
2393	}
2394}
2395
2396/// RAII guard for one announce lifetime. See [`Scope::announce`].
2397#[must_use = "drop the guard to record the unannounce"]
2398pub(crate) struct Announce {
2399	counters: Option<Arc<TierCounters>>,
2400	side: Side,
2401	len: u64,
2402}
2403
2404impl Drop for Announce {
2405	fn drop(&mut self) {
2406		if let Some(counters) = &self.counters {
2407			let counters = self.side.counters(counters);
2408			counters.announced_bytes.fetch_add(self.len, Ordering::Relaxed);
2409			let mut held = counters.held.lock().unwrap_or_else(PoisonError::into_inner);
2410			held.count -= 1;
2411			if held.count == 0 {
2412				held.since = None;
2413			}
2414			// Release pairs with the readout's Acquire load of `announces_ended`.
2415			counters.announces_ended.fetch_add(1, Ordering::Release);
2416		}
2417	}
2418}
2419
2420#[cfg(test)]
2421mod tests {
2422	use std::sync::{Arc, atomic::Ordering::Relaxed};
2423
2424	use super::*;
2425
2426	fn counters(sent: u64, received: u64) -> crate::transport::Wire {
2427		let wire = crate::transport::Wire::new();
2428		wire.set_sent_bytes(sent);
2429		wire.set_received_bytes(received);
2430		wire
2431	}
2432
2433	#[test]
2434	fn wire_deltas_follow_label_and_tier_changes() {
2435		let registry = test_stats();
2436		let old = Tier::new(crate::Path::from_static("old"));
2437		let new = Tier::new(crate::Path::from_static("new"));
2438		let session = registry
2439			.tier(old.clone())
2440			.session(SessionInfo::new(crate::Path::from_static("room")));
2441		let bytes = counters(10, 20);
2442		let _wire = session.wire(bytes.clone());
2443		let report = drain(&registry);
2444		assert_eq!(report.sessions.len(), 1);
2445		assert_eq!(report.sessions[0].label.as_str(), "room");
2446		assert_eq!(report.sessions[0].tier, old);
2447		assert_eq!(
2448			(report.sessions[0].presence.wire_tx, report.sessions[0].presence.wire_rx),
2449			(10, 20)
2450		);
2451		bytes.set_sent_bytes(15);
2452		bytes.set_received_bytes(27);
2453		let ms = std::time::Duration::from_millis;
2454		bytes.set_credit_stalls(2, ms(3));
2455		bytes.set_credit_held(ms(4), ms(1));
2456		bytes.set_lost_bytes(3);
2457		bytes.set_congestion_blocked(ms(6), ms(2));
2458		session.retag(new.clone(), crate::Path::from_static("hall"));
2459		bytes.set_sent_bytes(25);
2460		bytes.set_received_bytes(50);
2461		bytes.set_credit_stalls(5, ms(10));
2462		bytes.set_credit_held(ms(9), ms(3));
2463		bytes.set_lost_bytes(4);
2464		bytes.set_congestion_blocked(ms(11), ms(7));
2465		let report = drain(&registry);
2466		for (tier, label, expected, stalls, held, congestion) in [
2467			(old, "room", (15, 27), (2, 3_000), (4_000, 1_000), (3, 6_000, 2_000)),
2468			(new, "hall", (10, 23), (3, 7_000), (5_000, 2_000), (1, 5_000, 5_000)),
2469		] {
2470			let row = report
2471				.sessions
2472				.iter()
2473				.find(|row| row.tier == tier && row.label.as_str() == label)
2474				.unwrap();
2475			assert_eq!((row.presence.wire_tx, row.presence.wire_rx), expected);
2476			assert_eq!((row.presence.credit_stalls, row.presence.credit_stalled_us), stalls);
2477			let presence = &row.presence;
2478			assert_eq!((presence.credit_held_readers_us, presence.credit_held_evicted_us), held);
2479			let blocked = (presence.wire_lost, presence.cwnd_blocked_us, presence.pacing_blocked_us);
2480			assert_eq!(blocked, congestion);
2481		}
2482	}
2483
2484	#[test]
2485	fn a_wire_counter_reset_never_lowers_presence() {
2486		let registry = test_stats();
2487		let session = registry
2488			.tier(Tier::default())
2489			.session(SessionInfo::new(crate::Path::from_static("room")));
2490		let bytes = crate::transport::Wire::new();
2491		let _wire = session.wire(bytes.clone());
2492		for (reading, expected) in [((20, 30), (20, 30)), ((3, 4), (20, 30)), ((8, 10), (25, 36))] {
2493			bytes.set_sent_bytes(reading.0);
2494			bytes.set_received_bytes(reading.1);
2495			let report = drain(&registry);
2496			assert_eq!(
2497				(report.sessions[0].presence.wire_tx, report.sessions[0].presence.wire_rx),
2498				expected
2499			);
2500		}
2501	}
2502
2503	#[test]
2504	fn disabled_wire_collection_reports_nothing() {
2505		let registry = Registry::disabled();
2506		let session = registry
2507			.tier(Tier::default())
2508			.session(SessionInfo::new(crate::Path::from_static("root")));
2509		let wire = session.wire(counters(5, 7));
2510		assert!(drain(&registry).sessions.is_empty());
2511		drop(wire);
2512		assert!(drain(&registry).sessions.is_empty());
2513	}
2514
2515	#[test]
2516	fn wire_guards_hold_the_session_until_the_final_reading() {
2517		let registry = test_stats();
2518		let session = registry
2519			.tier(Tier::default())
2520			.session(SessionInfo::new(crate::Path::from_static("room")));
2521		let wire = session.wire(counters(19, 23));
2522		drop(session);
2523		assert_eq!(drain(&registry).sessions[0].presence.active(), 1);
2524		drop(wire);
2525		let report = drain(&registry);
2526		assert!(report.sessions[0].closed);
2527		assert_eq!(report.sessions[0].presence.active(), 0);
2528		assert_eq!(
2529			(report.sessions[0].presence.wire_tx, report.sessions[0].presence.wire_rx),
2530			(19, 23)
2531		);
2532	}
2533
2534	/// A source's counts, which nothing pushes, are pulled by each report, by a retag so the
2535	/// old row keeps what came before it, and by the guard's drop for the final reading.
2536	#[test]
2537	fn a_wire_source_is_read_on_each_report_retag_and_close() {
2538		struct Kernel(Arc<std::sync::atomic::AtomicU64>);
2539		impl crate::transport::WireSource for Kernel {
2540			fn refresh(&self, wire: &crate::transport::Wire) {
2541				let sent = self.0.load(Relaxed);
2542				wire.set_sent_bytes(sent);
2543				wire.set_received_bytes(2 * sent);
2544			}
2545		}
2546
2547		let registry = test_stats();
2548		let session = registry
2549			.tier(Tier::default())
2550			.session(SessionInfo::new(crate::Path::from_static("old")));
2551		let kernel = Arc::new(std::sync::atomic::AtomicU64::new(5));
2552		let wire = session.wire(crate::transport::Wire::from_source(Kernel(kernel.clone())));
2553		let row = |report: &Report, label: &str| {
2554			let row = report.sessions.iter().find(|row| row.label.as_str() == label).unwrap();
2555			(row.presence.wire_tx, row.presence.wire_rx)
2556		};
2557		assert_eq!(row(&drain(&registry), "old"), (5, 10));
2558		kernel.store(9, Relaxed);
2559		assert_eq!(row(&drain(&registry), "old"), (9, 18));
2560
2561		kernel.store(12, Relaxed);
2562		session.retag(Tier::default(), crate::Path::from_static("new"));
2563		kernel.store(20, Relaxed);
2564		let report = drain(&registry);
2565		assert_eq!(row(&report, "old"), (12, 24));
2566		assert_eq!(row(&report, "new"), (8, 16));
2567
2568		kernel.store(21, Relaxed);
2569		drop(wire);
2570		assert_eq!(row(&drain(&registry), "new"), (9, 18));
2571	}
2572
2573	#[test]
2574	fn presence_wire_fields_survive_serialization() {
2575		let value: Presence = serde_json::from_str(r#"{"wire_tx":71,"wire_rx":29}"#).unwrap();
2576		let output = serde_json::to_value(value).unwrap();
2577		assert_eq!(output["wire_tx"], 71);
2578		assert_eq!(output["wire_rx"], 29);
2579	}
2580
2581	/// A label that never routed writes no `routes` and reads back as zeros, and one count
2582	/// writes the whole readout.
2583	#[test]
2584	fn presence_routes_stay_off_the_wire_until_counted() {
2585		let mut presence = Presence::default();
2586		let output = serde_json::to_value(presence).unwrap();
2587		assert!(output.get("routes").is_none(), "{output}");
2588		assert_eq!(serde_json::from_value::<Presence>(output).unwrap(), presence);
2589
2590		presence.routes.closed.other = 1;
2591		let output = serde_json::to_value(presence).unwrap();
2592		assert_eq!(output["routes"]["closed"]["other"], 1);
2593		assert_eq!(output["routes"]["changed"], 0);
2594		assert_eq!(serde_json::from_value::<Presence>(output).unwrap(), presence);
2595	}
2596
2597	/// A zero credit counter stays off the wire and reads back as zero; a nonzero one is written.
2598	#[test]
2599	fn presence_credit_counters_stay_off_the_wire_while_zero() {
2600		let mut presence = Presence::default();
2601		let output = serde_json::to_value(presence).unwrap();
2602		for key in [
2603			"credit_stalls",
2604			"credit_stalled_us",
2605			"credit_held_readers_us",
2606			"credit_held_evicted_us",
2607			"wire_lost",
2608			"cwnd_blocked_us",
2609			"pacing_blocked_us",
2610		] {
2611			assert!(output.get(key).is_none(), "{output}");
2612		}
2613		assert_eq!(serde_json::from_value::<Presence>(output).unwrap(), presence);
2614
2615		presence.credit_held_evicted_us = 5;
2616		let output = serde_json::to_value(presence).unwrap();
2617		assert_eq!(output["credit_held_evicted_us"], 5);
2618		assert!(output.get("credit_stalls").is_none(), "{output}");
2619		assert_eq!(serde_json::from_value::<Presence>(output).unwrap(), presence);
2620	}
2621
2622	#[test]
2623	fn outcomes_survive_clones_tier_changes_and_pruning() {
2624		let stats = test_stats();
2625		let handle = stats.tier(Tier::new(crate::Path::from_static("gateway")));
2626		handle.refuse(Refusal::new(crate::Path::from_static("root"), RefusalKind::Forbidden));
2627		let session = handle.session(SessionInfo::new(crate::Path::from_static("root")));
2628		let clone = session.clone();
2629		session.retag(
2630			Tier::new(crate::Path::from_static("next")),
2631			crate::Path::from_static("root"),
2632		);
2633		// A reconnect's later end replaces an earlier one.
2634		clone.end(&crate::Error::Transport("lost".into()));
2635		session.end(&crate::Error::IdleTimeout);
2636		drop(clone);
2637		drop(session);
2638		let before = stats.snapshot();
2639		let gateway = before
2640			.sessions()
2641			.into_iter()
2642			.find(|(tier, _)| tier.as_str() == "gateway")
2643			.unwrap()
2644			.1;
2645		assert_eq!(gateway.sessions_refused.forbidden, 1);
2646		assert_eq!(gateway.sessions_failed, Failures::default());
2647		let next = before
2648			.sessions()
2649			.into_iter()
2650			.find(|(tier, _)| tier.as_str() == "next")
2651			.unwrap()
2652			.1;
2653		assert_eq!(next.sessions_failed.idle_timeout, 1);
2654		assert_eq!(next.sessions_failed.transport, 0);
2655		assert_eq!(next.active(), 0);
2656		drain(&stats);
2657		let after = stats.snapshot();
2658		assert_eq!(before.sessions(), after.sessions(), "retirement keeps outcomes once");
2659		let disabled = Registry::disabled();
2660		disabled
2661			.tier(Tier::default())
2662			.refuse(Refusal::new(crate::Path::from_static("root"), RefusalKind::Refused));
2663		disabled
2664			.tier(Tier::default())
2665			.session(SessionInfo::new(crate::Path::from_static("root")))
2666			.end(&crate::Error::Expired);
2667		assert!(disabled.snapshot().sessions().is_empty());
2668	}
2669
2670	#[test]
2671	fn outcome_wire_fields_default_and_roundtrip_without_changing_live_count() {
2672		let old: Presence = serde_json::from_str(r#"{"sessions_started":4,"sessions_ended":2}"#).unwrap();
2673		assert_eq!(old.sessions_refused, Refusals::default());
2674		assert_eq!(old.sessions_failed, Failures::default());
2675		let mut current = old;
2676		current.sessions_refused.request = 3;
2677		current.sessions_failed.expired = 1;
2678		assert_eq!(current.active(), 2);
2679		assert_eq!(
2680			serde_json::from_str::<Presence>(&serde_json::to_string(&current).unwrap()).unwrap(),
2681			current
2682		);
2683		let mut sum = current;
2684		sum.add(current);
2685		assert_eq!(sum.sessions_refused.request, 6);
2686		assert_eq!(sum.sessions_failed.expired, 2);
2687	}
2688
2689	#[test]
2690	fn default_tier_has_empty_label() {
2691		let tier = Tier::default();
2692		assert_eq!(tier.as_str(), "");
2693		assert_eq!(tier.to_string(), "");
2694	}
2695
2696	/// Counters for `(path, tier)`, creating the tier slot if absent.
2697	fn tier_counters(stats: &Registry, path: &str, tier: &Tier) -> Arc<TierCounters> {
2698		stats
2699			.shared()
2700			.entries
2701			.lock()
2702			.get(&crate::Path::try_from(path.to_string()).unwrap())
2703			.expect("entry")
2704			.tier(tier)
2705	}
2706
2707	/// The [`Presence`] for `(tier, label)`, or `None` if absent.
2708	fn session_snapshot(stats: &Registry, tier: &Tier, label: &str) -> Option<Presence> {
2709		stats.shared().sessions.lock().get(tier).and_then(|labels| {
2710			labels
2711				.get(&(crate::Path::empty(), crate::Path::try_from(label.to_string()).unwrap()))
2712				.map(|c| c.snapshot(Instant::ZERO).0)
2713		})
2714	}
2715
2716	fn test_stats() -> Registry {
2717		Registry::new(Config::new().with_exclude(".stats".parse().unwrap()))
2718	}
2719
2720	#[test]
2721	fn default_and_named_tiers_are_independent() {
2722		let stats = test_stats();
2723		let default = stats
2724			.tier(Tier::default())
2725			.session(SessionInfo::new(crate::Path::from_static("root")));
2726		let regional = stats
2727			.tier(Tier::new(crate::Path::from_static("region/sjc")))
2728			.session(SessionInfo::new(crate::Path::from_static("root")));
2729
2730		default.egress(crate::Path::from_static("demo/bbb")).meter().bytes(100);
2731		regional.ingress(crate::Path::from_static("demo/bbb")).meter().bytes(7);
2732
2733		let default_counters = tier_counters(&stats, "demo/bbb", &Tier::default());
2734		let regional_counters = tier_counters(&stats, "demo/bbb", &Tier::new(crate::Path::from_static("region/sjc")));
2735		assert_eq!(default_counters.publisher.bytes.load(Relaxed), 100);
2736		assert_eq!(default_counters.subscriber.bytes.load(Relaxed), 0);
2737		assert_eq!(regional_counters.publisher.bytes.load(Relaxed), 0);
2738		assert_eq!(regional_counters.subscriber.bytes.load(Relaxed), 7);
2739	}
2740
2741	/// Each label's sessions row carries the most any one of its sessions held against each
2742	/// cap, which a slot released does not lower and a rollup does not sum.
2743	#[test]
2744	#[cfg(feature = "async")]
2745	fn sessions_report_their_peaks_against_the_caps() {
2746		use crate::session::Slots;
2747
2748		let stats = test_stats();
2749		let tier = stats.tier(Tier::default());
2750		let (s1, s2) = (
2751			tier.session(SessionInfo::new(crate::Path::from_static("acme"))),
2752			tier.session(SessionInfo::new(crate::Path::from_static("acme"))),
2753		);
2754		let announces = Slots::new(10).with_stats(&s1, Cap::Announces);
2755		let subscriptions = Slots::new(10).with_stats(&s2, Cap::Subscriptions);
2756		let other = Slots::new(10).with_stats(&s2, Cap::Announces);
2757
2758		let held: Vec<_> = (0..3).map(|_| announces.acquire().unwrap()).collect();
2759		drop(held);
2760		let _one = announces.acquire().unwrap();
2761		let _subs: Vec<_> = (0..5).map(|_| subscriptions.acquire().unwrap()).collect();
2762		let _two: Vec<_> = (0..2).map(|_| other.acquire().unwrap()).collect();
2763
2764		let (_, presence) = stats
2765			.snapshot()
2766			.sessions()
2767			.into_iter()
2768			.find(|(t, _)| *t == Tier::default())
2769			.expect("sessions row");
2770		assert_eq!(presence.announces_peak, 3, "the peak of one session, not the sum");
2771		assert_eq!(presence.subscriptions_peak, 5);
2772
2773		let json = serde_json::to_string(&presence).unwrap();
2774		assert_eq!(serde_json::from_str::<Presence>(&json).unwrap(), presence);
2775	}
2776
2777	/// A session moving tiers brings the slots it still holds to the new tier's peak, but
2778	/// not the old tier's history.
2779	#[test]
2780	#[cfg(feature = "async")]
2781	fn a_tier_change_carries_the_slots_still_held() {
2782		use crate::session::Slots;
2783
2784		let stats = test_stats();
2785		let session = stats
2786			.tier(Tier::default())
2787			.session(SessionInfo::new(crate::Path::from_static("acme")));
2788		let subscriptions = Slots::new(10).with_stats(&session, Cap::Subscriptions);
2789		let mut held: Vec<_> = (0..5).map(|_| subscriptions.acquire().unwrap()).collect();
2790		held.truncate(3);
2791
2792		let gold = Tier::new(crate::Path::from_static("gold"));
2793		session.retag(gold.clone(), crate::Path::from_static("acme"));
2794
2795		let peak = |tier: &Tier| {
2796			let (_, presence) = stats
2797				.snapshot()
2798				.sessions()
2799				.into_iter()
2800				.find(|(t, _)| t == tier)
2801				.expect("sessions row");
2802			presence.subscriptions_peak
2803		};
2804		assert_eq!(peak(&Tier::default()), 5);
2805		assert_eq!(peak(&gold), 3, "the new tier sees what is still held");
2806	}
2807
2808	#[test]
2809	fn snapshot_rolls_up_by_tier_role_and_sessions() {
2810		let stats = test_stats();
2811		let default = stats.tier(Tier::default());
2812		let regional = stats.tier(Tier::new(crate::Path::from_static("region/sjc")));
2813
2814		// Two default-tier sessions under one label, one regional; presence sums them.
2815		let s1 = default.session(SessionInfo::new(crate::Path::from_static("acme")));
2816		let _s2 = default.session(SessionInfo::new(crate::Path::from_static("acme")));
2817		let s3 = regional.session(SessionInfo::new(crate::Path::from_static("peer")));
2818
2819		// Default-tier egress across two broadcasts; the snapshot sums them.
2820		{
2821			let m = s1.egress(crate::Path::from_static("demo/aaa")).meter();
2822			m.bytes(100);
2823			m.frames(1);
2824			m.group();
2825		}
2826		s1.egress(crate::Path::from_static("demo/bbb")).meter().bytes(50);
2827		// Regional ingress on a different tier/role stays isolated.
2828		s3.ingress(crate::Path::from_static("demo/aaa")).meter().bytes(7);
2829
2830		let snap = stats.snapshot();
2831
2832		let slot = |tier, role| {
2833			snap.traffic()
2834				.into_iter()
2835				.find(|(t, r, _)| *t == tier && *r == role)
2836				.map(|(_, _, c)| c)
2837				.expect("row present")
2838		};
2839
2840		let default_publisher = slot(Tier::default(), Role::Publisher);
2841		assert_eq!(
2842			default_publisher.bytes, 150,
2843			"default egress bytes sum across broadcasts"
2844		);
2845		assert_eq!(default_publisher.frames, 1);
2846		assert_eq!(default_publisher.groups, 1);
2847
2848		let regional_subscriber = slot(Tier::new(crate::Path::from_static("region/sjc")), Role::Subscriber);
2849		assert_eq!(regional_subscriber.bytes, 7, "regional ingress isolated by tier/role");
2850		assert_eq!(slot(Tier::default(), Role::Subscriber).bytes, 0);
2851		assert_eq!(
2852			slot(Tier::new(crate::Path::from_static("region/sjc")), Role::Publisher).bytes,
2853			0
2854		);
2855
2856		let sessions = |tier| {
2857			snap.sessions()
2858				.into_iter()
2859				.find(|(t, _)| *t == tier)
2860				.map(|(_, s)| s)
2861				.expect("tier present")
2862		};
2863		let default_sessions = sessions(Tier::default());
2864		assert_eq!(
2865			default_sessions.sessions_started, 2,
2866			"two default-tier sessions under one label"
2867		);
2868		assert_eq!(default_sessions.sessions_ended, 0, "guards still held");
2869		assert_eq!(
2870			sessions(Tier::new(crate::Path::from_static("region/sjc"))).sessions_started,
2871			1
2872		);
2873	}
2874
2875	fn drain(stats: &Registry) -> Report {
2876		let mut report = Report::default();
2877		stats.report(&mut report, crate::time::Instant::now());
2878		report
2879	}
2880
2881	#[test]
2882	fn report_reuses_capacity() {
2883		// A reused report is cleared, not appended to, and keeps its buffers.
2884		let stats = test_stats();
2885		let ctx = stats
2886			.tier(Tier::default())
2887			.session(SessionInfo::new(crate::Path::from_static("root")));
2888		let _scopes: Vec<_> = (0..8)
2889			.map(|i| ctx.egress(crate::Path::new(format!("b/{i}").as_str()).unwrap()))
2890			.collect();
2891
2892		let mut report = Report::default();
2893		stats.report(&mut report, crate::time::Instant::now());
2894		assert_eq!(report.traffic.len(), 8);
2895		assert_eq!(report.sessions.len(), 1);
2896		let (traffic, sessions) = (report.traffic.as_ptr(), report.sessions.as_ptr());
2897
2898		stats.report(&mut report, crate::time::Instant::now());
2899		assert_eq!(report.traffic.len(), 8, "refilled, not appended");
2900		assert_eq!(report.sessions.len(), 1);
2901		assert_eq!(report.traffic.as_ptr(), traffic, "traffic buffer reused");
2902		assert_eq!(report.sessions.as_ptr(), sessions, "sessions buffer reused");
2903	}
2904
2905	#[test]
2906	fn report_returns_detail_and_prunes() {
2907		// report() surfaces per-broadcast rows while a guard is held, keeps the
2908		// entry across drains while live, and prunes it on the first drain
2909		// after the last guard drops (returning the final values that once).
2910		let stats = test_stats();
2911		let key = crate::Path::from_static("foo/bar");
2912		let ctx = stats
2913			.tier(Tier::default())
2914			.session(SessionInfo::new(crate::Path::from_static("root")));
2915		let scope = ctx.egress(crate::Path::from_static("foo/bar"));
2916		let sub = scope.subscribe();
2917		scope.meter().bytes(42);
2918
2919		let report = drain(&stats);
2920		let row = report
2921			.traffic
2922			.iter()
2923			.find(|row| row.path == key)
2924			.expect("live entry present");
2925		assert_eq!(row.publisher.bytes, 42);
2926		assert_eq!(row.publisher.subscriptions_started, 1);
2927		assert!(!row.publisher.is_idle(), "subscription guard still open");
2928		assert!(!row.closed, "a held entry is not final");
2929		assert!(
2930			stats.shared().entries.lock().contains_key(&key),
2931			"live entry kept across drains"
2932		);
2933
2934		drop(sub);
2935		drop(scope);
2936
2937		// The drain after the last guard drops still returns the final values,
2938		// then prunes the entry.
2939		let report = drain(&stats);
2940		let row = report
2941			.traffic
2942			.iter()
2943			.find(|row| row.path == key)
2944			.expect("closing values still reported once");
2945		assert_eq!(row.publisher.subscriptions_ended, 1);
2946		assert!(row.publisher.is_idle());
2947		assert!(row.closed, "the closing readout is marked final");
2948		assert!(
2949			!stats.shared().entries.lock().contains_key(&key),
2950			"fully-closed entry pruned"
2951		);
2952		assert!(drain(&stats).traffic.is_empty(), "nothing left after the prune");
2953	}
2954
2955	#[test]
2956	fn report_keeps_idle_but_announced_entry() {
2957		// A broadcast with a live announce guard but no traffic must stay in
2958		// the registry indefinitely: announces_started != announces_ended means a
2959		// subscription could still begin at any moment.
2960		let stats = test_stats();
2961		let key = crate::Path::from_static("foo/bar");
2962		let ctx = stats
2963			.tier(Tier::default())
2964			.session(SessionInfo::new(crate::Path::from_static("root")));
2965		let scope = ctx.egress(crate::Path::from_static("foo/bar"));
2966		let guard = scope.announce();
2967
2968		for _ in 0..3 {
2969			let report = drain(&stats);
2970			assert!(
2971				report.traffic.iter().any(|row| row.path == key),
2972				"announced-but-idle broadcast stays while the guard is held"
2973			);
2974		}
2975
2976		drop(guard);
2977		drop(scope);
2978		let report = drain(&stats);
2979		let row = report.traffic.iter().find(|row| row.path == key).expect("final report");
2980		assert!(row.publisher.is_idle());
2981		assert!(!stats.shared().entries.lock().contains_key(&key));
2982	}
2983
2984	#[test]
2985	fn report_prunes_empty_session_labels() {
2986		// Once the last session under a label disconnects, the label leaves the
2987		// registry on the drain that reports its final gauge.
2988		let stats = test_stats();
2989		let session = stats
2990			.tier(Tier::default())
2991			.session(SessionInfo::new(crate::Path::from_static("acme")));
2992
2993		let report = drain(&stats);
2994		let row = report
2995			.sessions
2996			.iter()
2997			.find(|row| row.label.as_str() == "acme")
2998			.expect("root present");
2999		assert_eq!(row.presence.active(), 1);
3000		assert!(!row.closed);
3001
3002		drop(session);
3003		let report = drain(&stats);
3004		let row = report
3005			.sessions
3006			.iter()
3007			.find(|row| row.label.as_str() == "acme")
3008			.expect("final gauge reported once");
3009		assert_eq!(row.presence.active(), 0);
3010		assert!(row.closed, "the final gauge is marked closed");
3011		assert!(drain(&stats).sessions.is_empty(), "root pruned after the last drain");
3012		assert!(session_snapshot(&stats, &Tier::default(), "acme").is_none());
3013	}
3014
3015	#[test]
3016	fn control_body_totals_follow_retags_and_survive_retirement() {
3017		let registry = Registry::new(Default::default());
3018		let first = Tier::new(crate::Path::from_static("internal"));
3019		let second = Tier::new(crate::Path::from_static("edge"));
3020		let context = registry
3021			.tier(first.clone())
3022			.session(SessionInfo::new(crate::Path::from_static("")));
3023		context.control(Message::Announce, 17, false);
3024		context.retag(second.clone(), crate::Path::from_static(""));
3025		context.control(Message::TrackInfo, 23, true);
3026		let expected = vec![
3027			(
3028				second,
3029				Message::TrackInfo,
3030				Totals {
3031					rx: 23,
3032					rx_messages: 1,
3033					..Default::default()
3034				},
3035			),
3036			(
3037				first,
3038				Message::Announce,
3039				Totals {
3040					tx: 17,
3041					tx_messages: 1,
3042					..Default::default()
3043				},
3044			),
3045		];
3046		assert_eq!(registry.snapshot().control(), expected);
3047		drop(context);
3048		registry.report(&mut Report::default(), crate::time::Instant::now());
3049		assert_eq!(registry.snapshot().control(), expected);
3050		assert_eq!(registry.snapshot().control(), expected, "scrapes do not drain totals");
3051	}
3052
3053	#[test]
3054	fn snapshot_preserves_retired_counters() {
3055		let stats = test_stats();
3056		let tier = Tier::default();
3057		let live = stats
3058			.tier(tier.clone())
3059			.session(SessionInfo::new(crate::Path::from_static("live")));
3060		let scope = live.egress(crate::Path::from_static("live/video"));
3061		let _live_sub = scope.subscribe();
3062		for _ in 0..2 {
3063			let session = stats
3064				.tier(tier.clone())
3065				.session(SessionInfo::new(crate::Path::from_static("retired")));
3066			let scope = session.egress(crate::Path::from_static("retired/video"));
3067			let sub = scope.subscribe();
3068			scope.meter().bytes(100);
3069			drop(sub);
3070			drop(scope);
3071			drop(session);
3072			let before = stats.snapshot();
3073			drain(&stats);
3074			assert_eq!(stats.snapshot(), before, "pruning must not reset host counters");
3075		}
3076		let snap = stats.snapshot();
3077		let traffic = snap
3078			.traffic()
3079			.into_iter()
3080			.find(|(_, role, _)| *role == Role::Publisher)
3081			.unwrap()
3082			.2;
3083		assert_eq!(traffic.bytes, 200);
3084		assert_eq!(traffic.subscriptions_started, 3);
3085		assert_eq!(traffic.subscriptions_ended, 2);
3086		let sessions = snap.sessions().into_iter().find(|(label, _)| label == &tier).unwrap().1;
3087		assert_eq!(sessions.sessions_started, 3);
3088		assert_eq!(sessions.sessions_ended, 2);
3089		assert_eq!(stats.shared().entries.lock().len(), 1, "retired paths are still pruned");
3090		assert_eq!(
3091			stats.shared().sessions.lock()[&tier].len(),
3092			1,
3093			"retired labels are still pruned"
3094		);
3095		let retired = stats.shared().retired.lock();
3096		assert_eq!(retired.traffic.len(), 1, "retain only a total per tier");
3097		assert_eq!(retired.sessions.len(), 1);
3098	}
3099
3100	#[test]
3101	fn snapshot_and_report_transfer_counters_once() {
3102		let stats = test_stats();
3103		let worker_stats = stats.clone();
3104		let worker = std::thread::spawn(move || {
3105			for i in 0..256 {
3106				let path = format!("root/{i}");
3107				let session = worker_stats
3108					.tier(Tier::default())
3109					.session(SessionInfo::new(crate::Path::new(path.as_str()).unwrap()));
3110				session
3111					.ingress(crate::Path::new(path.as_str()).unwrap())
3112					.meter()
3113					.bytes(1);
3114				drop(session);
3115				drain(&worker_stats);
3116			}
3117		});
3118		let mut previous = 0;
3119		let mut previous_received = 0;
3120		while !worker.is_finished() {
3121			let snap = stats.snapshot();
3122			let received = snap.sessions().iter().map(|(_, row)| row.received_bytes).sum::<u64>();
3123			assert!(
3124				received >= previous_received,
3125				"retiring a session must retain its final payload bytes"
3126			);
3127			assert!(received <= 256);
3128			previous_received = received;
3129			let bytes: u64 = snap.traffic().iter().map(|(_, _, traffic)| traffic.bytes).sum();
3130			assert!(
3131				bytes >= previous,
3132				"retiring an entry must not double-count or lose its bytes"
3133			);
3134			assert!(bytes <= 256);
3135			previous = bytes;
3136		}
3137		worker.join().unwrap();
3138		let snap = stats.snapshot();
3139		assert_eq!(
3140			snap.traffic().iter().map(|(_, _, traffic)| traffic.bytes).sum::<u64>(),
3141			256
3142		);
3143		assert_eq!(snap.sessions()[0].1.sessions_started, 256);
3144		assert_eq!(snap.sessions()[0].1.sessions_ended, 256);
3145		assert_eq!(snap.sessions()[0].1.received_bytes, 256);
3146		assert!(stats.shared().entries.lock().is_empty());
3147		assert!(stats.shared().sessions.lock().is_empty());
3148		let retired = stats.shared().retired.lock();
3149		assert_eq!(retired.traffic.len(), 1);
3150		assert_eq!(retired.sessions.len(), 1);
3151	}
3152
3153	#[test]
3154	fn paths_under_exclude_are_no_op() {
3155		// Our own stats broadcasts (and any sibling category under the same
3156		// prefix) must not feed back into the registry.
3157		let stats = test_stats();
3158		let ctx = stats
3159			.tier(Tier::default())
3160			.session(SessionInfo::new(crate::Path::from_static("root")));
3161		let scope = ctx.egress(crate::Path::from_static(".stats/node/sjc"));
3162		scope.meter().bytes(100);
3163		let _guard = scope.announce();
3164		let _sub = scope.subscribe();
3165		assert!(stats.shared().entries.lock().is_empty());
3166	}
3167
3168	#[test]
3169	fn disabled_stats_are_noop() {
3170		// A disabled registry allocates no shared state; every handle is empty
3171		// and bumps are dropped.
3172		let stats = Registry::default();
3173		assert!(stats.shared.is_none());
3174		let ctx = stats
3175			.tier(Tier::default())
3176			.session(SessionInfo::new(crate::Path::from_static("root")));
3177		let scope = ctx.egress(crate::Path::from_static("demo/bbb"));
3178		scope.meter().bytes(100);
3179		let _guard = scope.announce();
3180		let _sub = scope.subscribe();
3181		assert!(drain(&stats).traffic.is_empty());
3182		assert!(stats.snapshot().traffic().is_empty());
3183	}
3184
3185	#[test]
3186	fn session_counts_by_label() {
3187		// session() counts connected sessions per label, independent of any
3188		// broadcast: open bumps `sessions_started`, drop bumps `sessions_ended`.
3189		let stats = test_stats();
3190		let ext = stats.tier(Tier::default());
3191
3192		let snap = |label: &str| {
3193			session_snapshot(&stats, &Tier::default(), label).map(|p| (p.sessions_started, p.sessions_ended))
3194		};
3195
3196		let a1 = ext.session(SessionInfo::new(crate::Path::from_static("acme")));
3197		let a2 = ext.session(SessionInfo::new(crate::Path::from_static("acme")));
3198		let b1 = ext.session(SessionInfo::new(crate::Path::from_static("globex")));
3199		assert_eq!(snap("acme"), Some((2, 0)), "two sessions under one label");
3200		assert_eq!(snap("globex"), Some((1, 0)), "a distinct label is counted separately");
3201
3202		drop(a1);
3203		assert_eq!(snap("acme"), Some((2, 1)));
3204		drop(a2);
3205		drop(b1);
3206		assert_eq!(snap("acme"), Some((2, 2)));
3207		assert_eq!(snap("globex"), Some((1, 1)));
3208	}
3209
3210	#[test]
3211	fn traffic_parses_with_missing_and_unknown_fields() {
3212		// Wire forward/backward compat: a frame entry from an older publisher
3213		// (missing fields) or a newer one (extra fields) must still parse.
3214		let old: Traffic = serde_json::from_str(r#"{"announces_started":1,"bytes":5}"#).expect("older shape parses");
3215		assert_eq!(old.announces_started, 1);
3216		assert_eq!(old.bytes, 5);
3217		assert_eq!(old.announced_bytes, 0, "missing fields default to zero");
3218
3219		let new: Traffic = serde_json::from_str(r#"{"announces_started":1,"announces_ended":1,"future_counter":9}"#)
3220			.expect("newer shape parses");
3221		assert!(new.is_idle());
3222	}
3223
3224	#[test]
3225	fn snapshot_reads_ended_before_started() {
3226		// Reading ended counters before their started counterparts is the
3227		// guarantee that a readout never shows ended > started under concurrent
3228		// bumps. This unit-test pins the ordering at the source level so a
3229		// future refactor that re-orders the loads trips the test.
3230		let src = include_str!("stats.rs");
3231		// Find the body of `impl Counters { fn snapshot(...) ... }` and
3232		// check the line order.
3233		let body_start = src.find("fn snapshot(&self) -> Traffic").expect("snapshot fn present");
3234		let body = &src[body_start..];
3235		let body = &body[..body.find("\n\t}\n").expect("snapshot fn end")];
3236		let ended_pos = body.find("self.announces_ended.load").expect("announces_ended load");
3237		let started_pos = body
3238			.find("self.announces_started.load")
3239			.expect("announces_started load");
3240		assert!(
3241			ended_pos < started_pos,
3242			"announces_ended must be loaded before announces_started; reversing breaks the started>=ended invariant",
3243		);
3244		let subs_ended_pos = body
3245			.find("self.subscriptions_ended.load")
3246			.expect("subscriptions_ended load");
3247		let subs_pos = body
3248			.find("self.subscriptions_started.load")
3249			.expect("subscriptions_started load");
3250		assert!(
3251			subs_ended_pos < subs_pos,
3252			"subscriptions_ended must be loaded before subscriptions_started",
3253		);
3254		let bcast_ended_pos = body.find("self.broadcasts_ended.load").expect("broadcasts_ended load");
3255		let bcast_pos = body
3256			.find("self.broadcasts_started.load")
3257			.expect("broadcasts_started load");
3258		assert!(
3259			bcast_ended_pos < bcast_pos,
3260			"broadcasts_ended must be loaded before broadcasts_started",
3261		);
3262	}
3263
3264	#[test]
3265	fn context_presence_closes_on_last_clone() {
3266		// The reshaped Session context bumps `sessions_started` once at creation and
3267		// `sessions_ended` only when the last clone drops.
3268		let stats = test_stats();
3269		let snap = |label: &str| {
3270			session_snapshot(&stats, &Tier::default(), label).map(|p| (p.sessions_started, p.sessions_ended))
3271		};
3272
3273		let ctx = stats
3274			.tier(Tier::default())
3275			.session(SessionInfo::new(crate::Path::from_static("acme")));
3276		assert_eq!(snap("acme"), Some((1, 0)));
3277
3278		let clone = ctx.clone();
3279		// A clone shares the Arc: no extra `sessions_started`, and dropping one does nothing.
3280		assert_eq!(snap("acme"), Some((1, 0)));
3281		drop(ctx);
3282		assert_eq!(snap("acme"), Some((1, 0)));
3283		drop(clone);
3284		assert_eq!(snap("acme"), Some((1, 1)));
3285	}
3286
3287	#[test]
3288	fn retag_moves_presence() {
3289		let stats = test_stats();
3290		let gold = Tier::new(crate::Path::from_static("gold"));
3291		let snap = |tier: &Tier| session_snapshot(&stats, tier, "acme").map(|p| (p.sessions_started, p.sessions_ended));
3292
3293		let ctx = stats
3294			.tier(Tier::default())
3295			.session(SessionInfo::new(crate::Path::from_static("acme")));
3296		ctx.retag(Tier::default(), crate::Path::from_static("acme"));
3297		assert_eq!(snap(&Tier::default()), Some((1, 0)), "the same tier is a no-op");
3298
3299		ctx.retag(gold.clone(), crate::Path::from_static("acme"));
3300		assert_eq!(snap(&Tier::default()), Some((1, 1)));
3301		assert_eq!(snap(&gold), Some((1, 0)));
3302
3303		drop(ctx);
3304		assert_eq!(snap(&gold), Some((1, 1)), "the session closes on its current tier");
3305	}
3306
3307	#[test]
3308	fn retag_moves_subsequent_traffic() {
3309		let stats = test_stats();
3310		let gold = Tier::new(crate::Path::from_static("gold"));
3311		let ctx = stats
3312			.tier(Tier::default())
3313			.session(SessionInfo::new(crate::Path::from_static("acme")));
3314		let scope = ctx.egress(crate::Path::from_static("demo/bbb"));
3315		let clone = scope.clone();
3316
3317		let before = scope.meter();
3318		let sub = scope.subscribe();
3319		let announce = scope.announce();
3320		before.bytes(10);
3321
3322		ctx.retag(gold.clone(), crate::Path::from_static("acme"));
3323		// A meter handed out earlier keeps its tier; everything after moves.
3324		before.bytes(1);
3325		scope.meter().bytes(5);
3326		clone.meter().bytes(7);
3327		let sub2 = scope.subscribe();
3328		scope.fetch();
3329
3330		drop(sub);
3331		drop(sub2);
3332		drop(announce);
3333
3334		let old = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
3335		let new = tier_counters(&stats, "demo/bbb", &gold).publisher.snapshot();
3336		let old_presence = session_snapshot(&stats, &Tier::default(), "acme").unwrap();
3337		let new_presence = session_snapshot(&stats, &gold, "acme").unwrap();
3338		assert_eq!(old_presence.sent_bytes, 10);
3339		assert_eq!(new_presence.sent_bytes, 13, "a retained meter follows the retag");
3340		assert_eq!(old.bytes, 11);
3341		assert_eq!(new.bytes, 12);
3342		assert_eq!((old.fetches, new.fetches), (0, 1));
3343
3344		// Each guard closes on the tier it opened on, so neither tier leaks a gauge.
3345		assert_eq!((old.subscriptions_started, old.subscriptions_ended), (1, 1));
3346		assert_eq!((new.subscriptions_started, new.subscriptions_ended), (1, 1));
3347		assert_eq!((old.announces_started, old.announces_ended), (1, 1));
3348		// The viewer opened on the old tier and closes there, even though the
3349		// session's last subscription was opened under the new one.
3350		assert_eq!((old.broadcasts_started, old.broadcasts_ended), (1, 1));
3351		assert_eq!((new.broadcasts_started, new.broadcasts_ended), (0, 0));
3352		assert!(old.is_idle() && new.is_idle());
3353	}
3354
3355	#[test]
3356	fn retag_moves_presence_between_labels_on_one_tier() {
3357		let stats = test_stats();
3358		let tier = Tier::default();
3359		let session = stats
3360			.tier(tier.clone())
3361			.session(SessionInfo::new(crate::Path::from_static("project/root")));
3362		session
3363			.egress(crate::Path::from_static("project/live"))
3364			.meter()
3365			.bytes(5);
3366
3367		session.retag(tier.clone(), crate::Path::from_static("project/key/123"));
3368		session
3369			.egress(crate::Path::from_static("project/live"))
3370			.meter()
3371			.bytes(7);
3372
3373		let root = session_snapshot(&stats, &tier, "project/root").unwrap();
3374		let key = session_snapshot(&stats, &tier, "project/key/123").unwrap();
3375		assert_eq!((root.sessions_started, root.sessions_ended, root.sent_bytes), (1, 1, 5));
3376		assert_eq!((key.sessions_started, key.sessions_ended, key.sent_bytes), (1, 0, 7));
3377	}
3378
3379	/// A rooted exclusion skips the subtree under the counting session's own root
3380	/// and no other, and a session's rows stay under its root across a retag.
3381	#[test]
3382	fn rooted_exclusion_follows_the_session_root() {
3383		let stats = Registry::new(Config::new().with_exclude_rooted(".stats".parse().unwrap()));
3384		let tier = Tier::default();
3385		let path = crate::Path::from_static;
3386		let rooted = stats
3387			.tier(tier.clone())
3388			.session(SessionInfo::new(path("x")).with_root(path("a")));
3389		let unrooted = stats.tier(tier.clone()).session(SessionInfo::new(path("x")));
3390		rooted.egress(path("a/.stats/node")).meter().bytes(1);
3391		rooted.egress(path("a/b/.stats/node")).meter().bytes(2);
3392		unrooted.egress(path(".stats/node")).meter().bytes(4);
3393		unrooted.egress(path("a/.stats/node")).meter().bytes(8);
3394		rooted.retag(tier.clone(), path("y"));
3395		rooted.egress(path("a/live")).meter().bytes(16);
3396
3397		let mut report = Report::default();
3398		stats.report(&mut report, Instant::now());
3399		let mut traffic: Vec<_> = report
3400			.traffic
3401			.iter()
3402			.map(|row| (row.path.as_str(), row.publisher.bytes))
3403			.collect();
3404		traffic.sort();
3405		assert_eq!(traffic, [("a/.stats/node", 8), ("a/b/.stats/node", 2), ("a/live", 16)]);
3406		let mut sessions: Vec<_> = report
3407			.sessions
3408			.iter()
3409			.map(|row| (row.root.as_str(), row.label.as_str(), row.presence.sent_bytes))
3410			.collect();
3411		sessions.sort();
3412		assert_eq!(sessions, [("", "x", 8), ("a", "x", 2), ("a", "y", 16)]);
3413	}
3414
3415	#[test]
3416	fn retag_back_counts_bytes_once() {
3417		let stats = test_stats();
3418		let tier = Tier::default();
3419		let session = stats
3420			.tier(tier.clone())
3421			.session(SessionInfo::new(crate::Path::from_static("a")));
3422		let meter = session.ingress(crate::Path::from_static("a/live")).meter();
3423		meter.bytes(1);
3424		session.retag(tier.clone(), crate::Path::from_static("b"));
3425		meter.bytes(2);
3426		session.retag(tier.clone(), crate::Path::from_static("a"));
3427		meter.bytes(4);
3428
3429		let received = |label| session_snapshot(&stats, &tier, label).unwrap().received_bytes;
3430		assert_eq!((received("a"), received("b")), (5, 2));
3431	}
3432
3433	#[test]
3434	fn session_bytes_outlive_the_session() {
3435		let stats = test_stats();
3436		let tier = Tier::default();
3437		let session = stats
3438			.tier(tier.clone())
3439			.session(SessionInfo::new(crate::Path::from_static("acme")));
3440		let meter = session.egress(crate::Path::from_static("acme/live")).meter();
3441		meter.bytes(3);
3442		drop(session);
3443
3444		let mut report = Report::default();
3445		stats.report(&mut report, crate::time::Instant::now());
3446		assert!(!report.sessions[0].closed, "a live meter keeps its label's row open");
3447		meter.datagram(4);
3448		drop(meter);
3449
3450		stats.report(&mut report, crate::time::Instant::now());
3451		assert_eq!(report.sessions[0].presence.sent_bytes, 7);
3452		assert!(report.sessions[0].closed);
3453		assert_eq!(
3454			stats.snapshot().sessions[&tier].sent_bytes,
3455			7,
3456			"retired totals keep the bytes"
3457		);
3458	}
3459
3460	#[test]
3461	fn activity_follows_recent_payload() {
3462		let stats = test_stats();
3463		let tier = Tier::default();
3464		let at = |secs| Instant::ZERO.saturating_add(std::time::Duration::from_secs(secs));
3465		let activity = |secs| stats.snapshot_at(at(secs)).activity[&tier];
3466		let both = |idle, active| Activity { idle, active };
3467
3468		let quiet = stats
3469			.tier(tier.clone())
3470			.session(SessionInfo::new(crate::Path::from_static("acme")));
3471		let busy = stats
3472			.tier(tier.clone())
3473			.session(SessionInfo::new(crate::Path::from_static("acme")));
3474		let _request = stats
3475			.tier(tier.clone())
3476			.request(SessionInfo::new(crate::Path::from_static("acme")));
3477		let meter = busy.egress(crate::Path::from_static("acme/live")).meter();
3478		let _held = quiet.ingress(crate::Path::from_static("acme/other")).meter();
3479		assert_eq!(
3480			activity(0),
3481			both(2, 0),
3482			"connecting moves no payload; requests never count"
3483		);
3484
3485		meter.bytes(1);
3486		assert_eq!(activity(1), both(1, 1));
3487		assert_eq!(
3488			activity(10),
3489			both(1, 1),
3490			"still within the window of the readout that saw it"
3491		);
3492		assert_eq!(activity(11), both(2, 0), "the window ends");
3493
3494		meter.bytes(1);
3495		busy.retag(tier.clone(), crate::Path::from_static("other"));
3496		assert_eq!(activity(12), both(1, 1), "a move before a retag is still seen after it");
3497		busy.retag(tier.clone(), crate::Path::from_static("acme"));
3498		assert_eq!(activity(13), both(1, 1), "a retag keeps recent activity");
3499
3500		meter.datagram(1);
3501		drop(busy);
3502		assert_eq!(
3503			activity(14),
3504			both(1, 0),
3505			"an ended session is neither, even with a live meter"
3506		);
3507
3508		drop((quiet, _held, _request, meter));
3509		stats.report(&mut Report::default(), at(15));
3510		assert_eq!(activity(15), both(0, 0), "a pruned tier still reports zero");
3511	}
3512
3513	#[test]
3514	fn excluded_paths_skip_session_bytes() {
3515		let stats = test_stats();
3516		let tier = Tier::default();
3517		let session = stats
3518			.tier(tier.clone())
3519			.session(SessionInfo::new(crate::Path::from_static("acme")));
3520		session.egress(crate::Path::from_static(".stats/node")).meter().bytes(9);
3521		assert_eq!(session_snapshot(&stats, &tier, "acme").unwrap().sent_bytes, 0);
3522	}
3523
3524	#[test]
3525	fn meter_bumps_the_right_side() {
3526		// A payload meter records on its own side only.
3527		let stats = test_stats();
3528		let ctx = stats
3529			.tier(Tier::default())
3530			.session(SessionInfo::new(crate::Path::from_static("root")));
3531
3532		let egress = ctx.egress(crate::Path::from_static("demo/bbb")).meter();
3533		egress.group();
3534		egress.frames(3);
3535		egress.bytes(100);
3536
3537		let ingress = ctx.ingress(crate::Path::from_static("demo/bbb")).meter();
3538		ingress.group();
3539		ingress.frames(1);
3540		ingress.bytes(7);
3541
3542		let counters = tier_counters(&stats, "demo/bbb", &Tier::default());
3543		let pub_ = counters.publisher.snapshot();
3544		let sub = counters.subscriber.snapshot();
3545		assert_eq!((pub_.groups, pub_.frames, pub_.bytes), (1, 3, 100));
3546		assert_eq!((sub.groups, sub.frames, sub.bytes), (1, 1, 7));
3547	}
3548
3549	#[test]
3550	fn egress_subscribe_drives_subscriptions_and_viewers() {
3551		// An egress subscription bumps `subscriptions_started` and, being the context's first
3552		// for the broadcast, `broadcasts_started`. Dropping closes both.
3553		let stats = test_stats();
3554		let ctx = stats
3555			.tier(Tier::default())
3556			.session(SessionInfo::new(crate::Path::from_static("root")));
3557		let raw = || tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
3558
3559		let scope = ctx.egress(crate::Path::from_static("demo/bbb"));
3560		let s1 = scope.subscribe();
3561		let s2 = scope.subscribe();
3562		let r = raw();
3563		assert_eq!(r.subscriptions_started, 2, "two track subs");
3564		assert_eq!(r.broadcasts_started, 1, "one context => one viewer");
3565		assert_eq!(r.broadcasts_ended, 0);
3566
3567		drop(s1);
3568		assert_eq!(raw().broadcasts_ended, 0, "context still has a sub open");
3569		drop(s2);
3570		let r = raw();
3571		assert_eq!(r.subscriptions_ended, 2);
3572		assert_eq!(r.broadcasts_ended, 1, "last sub closed => one broadcasts_ended");
3573	}
3574
3575	#[test]
3576	fn distinct_contexts_are_distinct_viewers() {
3577		// Two contexts (sessions) subscribing to the same broadcast are two viewers.
3578		let stats = test_stats();
3579		let raw = || tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
3580
3581		let v1 = stats
3582			.tier(Tier::default())
3583			.session(SessionInfo::new(crate::Path::from_static("a")))
3584			.egress(crate::Path::from_static("demo/bbb"))
3585			.subscribe();
3586		assert_eq!(raw().broadcasts_started, 1);
3587		let v2 = stats
3588			.tier(Tier::default())
3589			.session(SessionInfo::new(crate::Path::from_static("b")))
3590			.egress(crate::Path::from_static("demo/bbb"))
3591			.subscribe();
3592		assert_eq!(raw().broadcasts_started, 2, "two distinct contexts => two viewers");
3593
3594		drop(v1);
3595		assert_eq!(raw().active_broadcasts(), 1);
3596		drop(v2);
3597		assert_eq!(raw().broadcasts_ended, 2);
3598	}
3599
3600	#[test]
3601	fn ingress_subscription_has_no_viewer() {
3602		// An ingress (producer-lifetime) subscription bumps subscriptions but never
3603		// the viewer refcount, which is egress-only.
3604		let stats = test_stats();
3605		let ctx = stats
3606			.tier(Tier::default())
3607			.session(SessionInfo::new(crate::Path::from_static("root")));
3608		let guard = ctx.ingress(crate::Path::from_static("demo/bbb")).subscribe();
3609		let sub = tier_counters(&stats, "demo/bbb", &Tier::default())
3610			.subscriber
3611			.snapshot();
3612		assert_eq!(sub.subscriptions_started, 1);
3613		assert_eq!(sub.broadcasts_started, 0, "ingress has no viewer refcount");
3614		drop(guard);
3615		assert_eq!(
3616			tier_counters(&stats, "demo/bbb", &Tier::default())
3617				.subscriber
3618				.snapshot()
3619				.subscriptions_ended,
3620			1
3621		);
3622	}
3623
3624	#[test]
3625	fn request_admission_survives_clones_retiering_and_retirement_without_presence() {
3626		let stats = test_stats();
3627		let request = stats
3628			.tier(Tier::new(crate::Path::from_static("old")))
3629			.request(SessionInfo::new(crate::Path::from_static("root")));
3630		let clone = request.clone();
3631		request.egress(crate::Path::from_static("root/video")).meter().bytes(7);
3632		request.retag(
3633			Tier::new(crate::Path::from_static("new")),
3634			crate::Path::from_static("root"),
3635		);
3636		clone.egress(crate::Path::from_static("root/video")).meter().bytes(11);
3637		drop(request);
3638		drop(clone);
3639		let mut report = Report::default();
3640		stats.report(&mut report, crate::time::Instant::now());
3641		for (label, requests, bytes) in [("old", 1, 7), ("new", 0, 11)] {
3642			let tier = Tier::new(crate::Path::new(label).unwrap());
3643			let presence = report.sessions.iter().find(|entry| entry.tier == tier).unwrap();
3644			assert_eq!(presence.presence.requests, requests);
3645			assert_eq!(presence.presence.active(), 0);
3646			assert_eq!(
3647				(presence.presence.sessions_started, presence.presence.sessions_ended),
3648				(0, 0)
3649			);
3650			assert!(presence.closed);
3651			assert_eq!(
3652				report
3653					.traffic
3654					.iter()
3655					.find(|entry| entry.tier == tier)
3656					.unwrap()
3657					.publisher
3658					.bytes,
3659				bytes
3660			);
3661		}
3662		stats.report(&mut report, crate::time::Instant::now());
3663		assert!(report.sessions.is_empty());
3664		let totals = stats.snapshot().sessions();
3665		assert_eq!(totals.iter().map(|(_, p)| p.requests).sum::<u64>(), 1);
3666	}
3667
3668	#[test]
3669	fn request_counter_is_additive_and_compatible_with_old_frames() {
3670		let old: Presence = serde_json::from_str(r#"{"sessions_started":2,"sessions_ended":1}"#).unwrap();
3671		assert_eq!(old.requests, 0);
3672		let mut requests = Presence {
3673			requests: 3,
3674			..Default::default()
3675		};
3676		requests.add(old);
3677		assert_eq!(
3678			serde_json::from_str::<Presence>(&serde_json::to_string(&requests).unwrap()).unwrap(),
3679			requests
3680		);
3681		assert_eq!(
3682			(requests.requests, requests.sessions_started, requests.sessions_ended),
3683			(3, 2, 1)
3684		);
3685		assert!(serde_json::from_str::<Presence>(r#"{"requests":null}"#).is_err());
3686	}
3687
3688	#[test]
3689	fn fetch_counts_separately_from_subscriptions() {
3690		// A fetch bumps `fetches`, not `subscriptions_started` or the viewer refcount.
3691		let stats = test_stats();
3692		let ctx = stats
3693			.tier(Tier::default())
3694			.session(SessionInfo::new(crate::Path::from_static("root")));
3695		let scope = ctx.egress(crate::Path::from_static("demo/bbb"));
3696		scope.fetch();
3697		scope.fetch();
3698		let r = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
3699		assert_eq!(r.fetches, 2);
3700		assert_eq!(r.subscriptions_started, 0);
3701		assert_eq!(r.broadcasts_started, 0);
3702	}
3703
3704	#[test]
3705	fn announce_guard_records_bytes_on_open_and_close() {
3706		// The announce guard bumps `announces_started` + the path length on open, and
3707		// `announces_ended` + the path length again on drop.
3708		let stats = test_stats();
3709		let ctx = stats
3710			.tier(Tier::default())
3711			.session(SessionInfo::new(crate::Path::from_static("root")));
3712		let path_len = "demo/bbb".len() as u64;
3713
3714		let guard = ctx.egress(crate::Path::from_static("demo/bbb")).announce();
3715		let r = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
3716		assert_eq!(r.announces_started, 1);
3717		assert_eq!(r.announces_ended, 0);
3718		assert_eq!(r.announced_bytes, path_len);
3719
3720		drop(guard);
3721		let r = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
3722		assert_eq!(r.announces_ended, 1);
3723		assert_eq!(
3724			r.announced_bytes,
3725			path_len * 2,
3726			"path length recorded on open and close"
3727		);
3728	}
3729
3730	#[kio::test]
3731	async fn announced_holds_the_start_while_any_guard_does() {
3732		let stats = test_stats();
3733		let ctx = stats
3734			.tier(Tier::default())
3735			.session(SessionInfo::new(crate::Path::from_static("root")));
3736		let scope = ctx.ingress(crate::Path::from_static("demo/bbb"));
3737		let announced = |stats: &Registry| {
3738			let report = drain(stats);
3739			let row = report
3740				.traffic
3741				.iter()
3742				.find(|row| row.path.as_str() == "demo/bbb")
3743				.expect("the held entry is reported");
3744			assert_eq!(row.announced.publisher, None, "egress never announced");
3745			let held = row.subscriber.announces_started > row.subscriber.announces_ended;
3746			assert_eq!(row.announced.subscriber.is_some(), held, "a start exactly while held");
3747			row.announced.subscriber
3748		};
3749
3750		let first = scope.announce();
3751		let start = kio::clock::wall();
3752		kio::clock::sleep(std::time::Duration::from_secs(5)).await;
3753		// A second route overlapping the first keeps the start, after the first ends too.
3754		let second = scope.announce();
3755		assert_eq!(announced(&stats), Some(start));
3756		drop(first);
3757		kio::clock::sleep(std::time::Duration::from_secs(5)).await;
3758		assert_eq!(announced(&stats), Some(start), "the overlap keeps the start");
3759
3760		drop(second);
3761		assert_eq!(announced(&stats), None, "nothing held, nothing announced");
3762
3763		kio::clock::sleep(std::time::Duration::from_secs(5)).await;
3764		let _third = scope.announce();
3765		assert_eq!(
3766			announced(&stats),
3767			Some(kio::clock::wall()),
3768			"announced again after a gap starts over"
3769		);
3770	}
3771
3772	#[test]
3773	fn disabled_context_is_noop() {
3774		// A default (disabled) context resolves empty scopes: every bump is dropped.
3775		let ctx = Session::default();
3776		let scope = ctx.egress(crate::Path::from_static("demo/bbb"));
3777		scope.meter().bytes(100);
3778		let _guard = scope.announce();
3779		let _sub = scope.subscribe();
3780		scope.fetch();
3781		// No registry to inspect; the point is that none of this panics or allocates.
3782		assert!(ctx.inner.is_none());
3783	}
3784
3785	#[test]
3786	fn fetches_serde_roundtrips() {
3787		// The new `fetches` field is additive: an older frame omits it (defaults to
3788		// zero), and it survives a roundtrip.
3789		let old: Traffic = serde_json::from_str(r#"{"bytes":5}"#).expect("older shape parses");
3790		assert_eq!(old.fetches, 0);
3791
3792		let t = Traffic {
3793			fetches: 9,
3794			..Default::default()
3795		};
3796		let json = serde_json::to_string(&t).unwrap();
3797		let back: Traffic = serde_json::from_str(&json).unwrap();
3798		assert_eq!(back.fetches, 9);
3799	}
3800
3801	#[test]
3802	fn session_snapshot_reads_ended_before_started() {
3803		// Same `ended`-before-`started` invariant as `Counters::snapshot`, pinned
3804		// at the source level so a reordering refactor can't let
3805		// `sessions_ended > sessions_started` leak into a readout.
3806		// Anchor on the impl's column-0 header, which this test's escaped literal can't match,
3807		// so a signature change fails the search instead of finding the test's own strings.
3808		let src = include_str!("stats.rs");
3809		let impl_start = src
3810			.find("\nimpl SessionCounters {")
3811			.expect("impl SessionCounters present");
3812		let body = &src[impl_start..];
3813		let body = &body[..body.find("\n}\n").expect("impl SessionCounters end")];
3814		let body = &body[body
3815			.find("\tfn snapshot(")
3816			.expect("SessionCounters::snapshot fn present")..];
3817		let body = &body[..body.find("\n\t}\n").expect("SessionCounters::snapshot fn end")];
3818		let ended_pos = body.find("self.sessions_ended.load").expect("sessions_ended load");
3819		let started_pos = body.find("self.sessions_started.load").expect("sessions_started load");
3820		assert!(
3821			ended_pos < started_pos,
3822			"sessions_ended must be loaded before sessions_started",
3823		);
3824	}
3825
3826	fn expected_traffic() -> Traffic {
3827		Traffic {
3828			announces_started: 2,
3829			announces_ended: 1,
3830			broadcasts_started: 4,
3831			broadcasts_ended: 3,
3832			subscriptions_started: 6,
3833			subscriptions_ended: 5,
3834			bytes: 9,
3835			..Default::default()
3836		}
3837	}
3838
3839	fn expected_presence() -> Presence {
3840		Presence {
3841			sessions_started: 3,
3842			sessions_ended: 1,
3843			..Default::default()
3844		}
3845	}
3846
3847	#[test]
3848	fn traffic_round_trips_each_counter_once() {
3849		let expected = expected_traffic();
3850		let json = serde_json::to_string(&expected).unwrap();
3851		for name in [
3852			"announces_started",
3853			"announces_ended",
3854			"broadcasts_started",
3855			"broadcasts_ended",
3856			"subscriptions_started",
3857			"subscriptions_ended",
3858		] {
3859			assert_eq!(json.matches(&format!("\"{name}\":")).count(), 1, "{json}");
3860		}
3861		for old in [
3862			"announced",
3863			"announced_closed",
3864			"broadcasts",
3865			"broadcasts_closed",
3866			"subscriptions",
3867			"subscriptions_closed",
3868		] {
3869			assert!(!json.contains(&format!("\"{old}\":")), "{json}");
3870		}
3871		assert_eq!(serde_json::from_str::<Traffic>(&json).unwrap(), expected);
3872		// A counter the frame omits reads as zero.
3873		let missing: Traffic = serde_json::from_str(r#"{"announces_started":2}"#).unwrap();
3874		assert_eq!(missing.announces_started, 2);
3875		assert_eq!(missing.announces_ended, 0);
3876	}
3877
3878	#[test]
3879	fn presence_round_trips_each_counter_once() {
3880		let expected = expected_presence();
3881		let json = serde_json::to_string(&expected).unwrap();
3882		assert_eq!(json.matches("\"sessions_started\":3").count(), 1, "{json}");
3883		assert_eq!(json.matches("\"sessions_ended\":1").count(), 1, "{json}");
3884		assert!(!json.contains("\"sessions\":"), "{json}");
3885		assert!(!json.contains("\"sessions_closed\":"), "{json}");
3886		assert_eq!(serde_json::from_str::<Presence>(&json).unwrap(), expected);
3887		let missing: Presence = serde_json::from_str(r#"{"sessions_started":3}"#).unwrap();
3888		assert_eq!(missing.sessions_started, 3);
3889		assert_eq!(missing.sessions_ended, 0);
3890	}
3891}