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, auth root), counting presence regardless of
14//! whether any data flows.
15//!
16//! # Where counting happens
17//!
18//! Counting lives in the model layer, not the wire loops. A session tags its
19//! origin pair with a [`Session`] context ([`crate::Client::with_stats`] /
20//! [`crate::Server::with_stats`], which call `origin::{Consumer, Producer}`
21//! `with_stats`); every derived handle (broadcast, announce, track, group, frame)
22//! then attributes its reads (egress = publisher) and writes (ingress =
23//! subscriber) through that context. So any protocol that drives the model gets
24//! the full counter set for free, and an untagged handle pays nothing.
25//!
26//! Per-counter semantics:
27//!
28//! * `announces_started` / `announces_ended`: cumulative broadcast
29//!   announce/unannounce events on this `(tier, role)`. Driven by the tagged
30//!   announce stream on the egress side, and by `create_broadcast` route
31//!   transitions on the ingress side.
32//! * `announced_bytes`: cumulative broadcast-name length summed over each
33//!   model-visible announce and unannounce of this broadcast (the name, not the
34//!   encoded message size, so hop/framing overhead isn't charged, and the count
35//!   is the same across protocol versions). Kept separate from the `bytes`
36//!   payload counter.
37//! * `broadcasts_started` / `broadcasts_ended`: per-(broadcast, context) egress
38//!   subscription sentinel. The first active subscription a context opens for a
39//!   broadcast bumps `broadcasts_started`; the last it closes bumps
40//!   `broadcasts_ended`. Summed across contexts, `broadcasts_started -
41//!   broadcasts_ended` is the number of distinct sessions currently subscribed
42//!   (viewers on the egress side).
43//! * `subscriptions_started` / `subscriptions_ended`: cumulative track-level
44//!   subscriptions opened/dropped (egress `track::Subscriber`, ingress
45//!   `track::Producer`).
46//! * `fetches`: cumulative one-shot group fetches *requested* by a calling
47//!   context, counted once per coalesced fetch at request time. A fetch that
48//!   resolves to `NotFound` still counts. Separate from `subscriptions_started`
49//!   and the viewer refcount; fetched payload still flows into `bytes` /
50//!   `frames` / `groups`.
51//! * `bytes` / `frames` / `groups`: cumulative payload counters bumped as
52//!   groups/frames are read (egress) or written (ingress) in the model.
53//! * `datagrams`: cumulative single-frame groups carried over unreliable QUIC
54//!   datagrams. A datagram is metered as the group it stands in for, so it also
55//!   bumps `groups`, `frames`, and `bytes`; this counter breaks out how many of
56//!   those took the datagram path.
57//! * `sessions_started` / `sessions_ended` ([`Presence`]): cumulative count of
58//!   sessions connected/disconnected under an auth root on this tier.
59//!   Driven by [`Handle::session`] (the [`Session`] context); a
60//!   [`Session::set_tier`] ends the session on the old tier and starts it on
61//!   the new one.
62//!
63//! Counters are strictly monotonic (only `fetch_add`); a counter going
64//! backwards across reads means the underlying entry was garbage collected
65//! (see [`Registry::report`]) and re-created. Downstream consumers should
66//! treat decreases as a fresh segment, summing across resets when computing
67//! lifetime totals.
68//!
69//! # Disabled stats
70//!
71//! [`Registry::disabled`] builds a no-op registry: all counter bumps are
72//! silently dropped and nothing is ever tracked. [`Registry::default`] /
73//! [`Handle::default`] return one, so call sites can hold a [`Handle`]
74//! unconditionally instead of threading an `Option`.
75//!
76//! # Garbage collection
77//!
78//! [`Registry::report`] refills a caller-owned [`Report`] with the current
79//! per-broadcast detail and prunes
80//! entries no longer referenced by any guard, so a publisher draining the
81//! registry on an interval keeps it bounded. A registry that is never
82//! drained accumulates one entry per broadcast path ever seen; call
83//! [`Registry::report`] periodically if you enable a registry without
84//! attaching a publisher. [`Registry::snapshot`] never prunes.
85//!
86//! # Snapshot atomicity
87//!
88//! Each counter readout loads `*_ended` atomics (with `Acquire`)
89//! before their `*_started` counterparts (with `Relaxed`). The matching
90//! end bumps in the RAII guards' `Drop` impls use `Release`. With this
91//! pairing the readout always satisfies `started >= ended` even on
92//! weakly-ordered architectures (ARM, POWER): the `Acquire` load of
93//! ended synchronizes-with the `Release` bump that produced the
94//! observed value, making every write that happened-before that end
95//! (including the matching start bump on whichever thread opened the
96//! guard) visible to the reading thread. Started / payload counters can
97//! then stay `Relaxed` because the visibility comes for free through
98//! the ended pairing. The cost is a slight upward bias on the started
99//! counts when a bump lands between the two loads, which never produces
100//! a logically impossible (`ended > started`) readout for downstream.
101//!
102//! # Cycles
103//!
104//! A [`Registry`] built with excluded patterns ([`Config::exclude`]) returns
105//! empty handles (whose bumps no-op) for any path they match. The `moq-stats`
106//! publisher excludes its own top-level subtree this way, breaking the feedback
107//! loop where serving a stats broadcast would itself generate more stats
108//! traffic.
109
110use std::{
111	collections::HashMap,
112	fmt,
113	sync::{
114		Arc, Mutex,
115		atomic::{AtomicU64, Ordering},
116	},
117};
118
119use kio::Lock;
120use serde::{Deserialize, Deserializer, Serialize, Serializer};
121
122use crate::{AsPath, PathOwned, Pattern, Patterns};
123
124/// Cumulative atomic counters for a single `(tier, role)` on a broadcast.
125///
126/// Started counters bump when a model handle records activity; their `_ended`
127/// counterparts bump from the [`Scope`] / [`Subscription`] / [`Announce`] RAII
128/// guards on drop. `broadcasts_started` / `broadcasts_ended` are the
129/// per-(broadcast, context) egress subscription sentinel (the first active
130/// subscription a context opens for the broadcast bumps `broadcasts_started`,
131/// the last to close bumps `broadcasts_ended`), so summed across contexts
132/// `broadcasts_started - broadcasts_ended` is the count of distinct sessions
133/// currently subscribed.
134// Kept crate-private: the load/store orderings are load-bearing (see the
135// module-level "Snapshot atomicity" note), so external code only ever sees
136// the derived [`Traffic`] readout.
137#[derive(Default, Debug)]
138pub(crate) struct Counters {
139	announces_started: AtomicU64,
140	announces_ended: AtomicU64,
141	// Cumulative broadcast-name length summed over each announce and unannounce
142	// of this broadcast. Counts the name, not the encoded message size, so it
143	// doesn't penalize the broadcast for hop/framing overhead. Kept separate
144	// from `bytes`, which is media payload.
145	announced_bytes: AtomicU64,
146	subscriptions_started: AtomicU64,
147	subscriptions_ended: AtomicU64,
148	// Cumulative one-shot group fetches requested by a calling context. Counted
149	// once per coalesced fetch, at request time rather than on resolution; does
150	// not touch `subscriptions_started` or the viewer refcount.
151	fetches: AtomicU64,
152	broadcasts_started: AtomicU64,
153	broadcasts_ended: AtomicU64,
154	bytes: AtomicU64,
155	frames: AtomicU64,
156	groups: AtomicU64,
157	// Subset of `groups` carried over an unreliable QUIC datagram.
158	datagrams: AtomicU64,
159	// Content the drift budget gave up on before delivery. Disjoint from the
160	// top-level payload counters, which count only what was handed over.
161	stale: ContentCounters,
162}
163
164/// Atomic backing for one [`Content`] readout.
165#[derive(Default, Debug)]
166struct ContentCounters {
167	bytes: AtomicU64,
168	frames: AtomicU64,
169	groups: AtomicU64,
170	datagrams: AtomicU64,
171}
172
173impl ContentCounters {
174	fn snapshot(&self) -> Content {
175		Content {
176			bytes: self.bytes.load(Ordering::Relaxed),
177			frames: self.frames.load(Ordering::Relaxed),
178			groups: self.groups.load(Ordering::Relaxed),
179			datagrams: self.datagrams.load(Ordering::Relaxed),
180		}
181	}
182
183	fn add(&self, content: Content) {
184		self.bytes.fetch_add(content.bytes, Ordering::Relaxed);
185		self.frames.fetch_add(content.frames, Ordering::Relaxed);
186		self.groups.fetch_add(content.groups, Ordering::Relaxed);
187		self.datagrams.fetch_add(content.datagrams, Ordering::Relaxed);
188	}
189}
190
191impl Counters {
192	/// Read all atomics into a [`Traffic`]. Ended counters are read with
193	/// `Acquire` ordering before their started counterparts so the readout
194	/// always satisfies `started >= ended`; see the module-level "Snapshot
195	/// atomicity" note. Started / payload counters stay `Relaxed`: the
196	/// Acquire on ended synchronizes-with the matching Release on the
197	/// end bump, which transitively makes all earlier writes (including
198	/// the prior start bump) visible to this thread.
199	fn snapshot(&self) -> Traffic {
200		let announces_ended = self.announces_ended.load(Ordering::Acquire);
201		let subscriptions_ended = self.subscriptions_ended.load(Ordering::Acquire);
202		let broadcasts_ended = self.broadcasts_ended.load(Ordering::Acquire);
203		let announces_started = self.announces_started.load(Ordering::Relaxed);
204		let announced_bytes = self.announced_bytes.load(Ordering::Relaxed);
205		let subscriptions_started = self.subscriptions_started.load(Ordering::Relaxed);
206		let fetches = self.fetches.load(Ordering::Relaxed);
207		let broadcasts_started = self.broadcasts_started.load(Ordering::Relaxed);
208		let bytes = self.bytes.load(Ordering::Relaxed);
209		let frames = self.frames.load(Ordering::Relaxed);
210		let groups = self.groups.load(Ordering::Relaxed);
211		let datagrams = self.datagrams.load(Ordering::Relaxed);
212		let stale = self.stale.snapshot();
213		Traffic {
214			announces_started,
215			announces_ended,
216			announced_bytes,
217			broadcasts_started,
218			broadcasts_ended,
219			subscriptions_started,
220			subscriptions_ended,
221			fetches,
222			bytes,
223			frames,
224			groups,
225			datagrams,
226			stale,
227		}
228	}
229}
230
231/// Payload-volume counters for content with the same delivery outcome.
232///
233/// This is the nested shape used by [`Traffic::stale`]. The successfully
234/// delivered equivalents remain as top-level [`Traffic`] fields for wire
235/// compatibility with existing stats consumers.
236#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(default)]
238#[non_exhaustive]
239pub struct Content {
240	/// Cumulative payload bytes.
241	pub bytes: u64,
242	/// Cumulative frames.
243	pub frames: u64,
244	/// Cumulative groups.
245	pub groups: u64,
246	/// Cumulative single-frame groups carried as unreliable datagrams.
247	pub datagrams: u64,
248}
249
250impl Content {
251	/// Fold another readout into this one, counter by counter.
252	pub(crate) fn add(&mut self, other: Self) {
253		self.bytes += other.bytes;
254		self.frames += other.frames;
255		self.groups += other.groups;
256		self.datagrams += other.datagrams;
257	}
258}
259
260/// Per-(tier, root) session gauge. One of these is shared (via `Arc`) by every
261/// [`Session`] guard for the same auth root on the same tier: `sessions_started`
262/// bumps on connect, `sessions_ended` on disconnect.
263#[derive(Default, Debug)]
264struct SessionCounters {
265	sessions_started: AtomicU64,
266	sessions_ended: AtomicU64,
267}
268
269impl SessionCounters {
270	/// Read the gauge into a [`Presence`]. Ended is loaded with `Acquire`
271	/// before started with `Relaxed`, the same pairing as [`Counters::snapshot`],
272	/// so the readout never shows `ended > started`.
273	fn snapshot(&self) -> Presence {
274		let sessions_ended = self.sessions_ended.load(Ordering::Acquire);
275		let sessions_started = self.sessions_started.load(Ordering::Relaxed);
276		Presence {
277			sessions_started,
278			sessions_ended,
279		}
280	}
281}
282
283/// A cumulative traffic counter readout for one slice (a broadcast on a
284/// `(tier, role)`, or any sum of such slices).
285///
286/// Every counter is cumulative, so a rate is `delta / delta_t` and a live
287/// count is `started - ended`. This is also the wire shape of one entry on a
288/// published stats track (the `moq-stats` crate serializes maps of these).
289/// Serialize writes both the canonical `*_started`/`*_ended` names and the
290/// legacy `announced`/`*_closed` spellings so an older consumer still reads a
291/// new relay; deserialize accepts either spelling, with the canonical name
292/// winning when both are present. Unknown fields from a newer publisher are
293/// ignored and missing fields from an older one default to zero.
294#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
295#[non_exhaustive]
296pub struct Traffic {
297	/// Cumulative broadcast announce events on this slice.
298	pub announces_started: u64,
299	/// Cumulative broadcast unannounce events on this slice.
300	pub announces_ended: u64,
301	/// Cumulative announce-control bytes: the broadcast name length summed
302	/// over each announce and unannounce. Distinct from `bytes` (payload).
303	pub announced_bytes: u64,
304	/// Per-(broadcast, session) subscription sentinel opens: the first active
305	/// subscription a session holds on a broadcast.
306	pub broadcasts_started: u64,
307	/// Sentinel closes: the session's last subscription to the broadcast ended.
308	pub broadcasts_ended: u64,
309	/// Cumulative track-level subscriptions opened.
310	pub subscriptions_started: u64,
311	/// Cumulative track-level subscriptions closed.
312	pub subscriptions_ended: u64,
313	/// Cumulative one-shot group fetches requested. Counted once per coalesced fetch
314	/// when the fetch is issued, so one that resolves to `NotFound` still counts.
315	/// Separate from `subscriptions_started` and the viewer refcount. Fetched payload still
316	/// flows into `bytes`/`frames`/`groups`.
317	pub fetches: u64,
318	/// Cumulative payload bytes.
319	pub bytes: u64,
320	/// Cumulative frames delivered.
321	pub frames: u64,
322	/// Cumulative groups delivered.
323	pub groups: u64,
324	/// Cumulative single-frame groups delivered over an unreliable QUIC datagram.
325	/// A subset of `groups`: each one also counts there and its payload in
326	/// `frames` / `bytes`.
327	pub datagrams: u64,
328	/// Content skipped because it aged past a subscriber's
329	/// [`max_age`](crate::track::Subscription::max_age) budget. Disjoint from the top-level payload
330	/// counters: skipped content is never handed over. A steady rate here means
331	/// subscribers are consistently behind the live edge.
332	pub stale: Content,
333}
334
335/// One spelling of a counter edge on the wire: absent, or a present integer.
336///
337/// Decoding goes through `u64`, so an explicit `null` is refused rather than
338/// read as absent; only a missing field takes the default.
339#[derive(Default, Clone, Copy)]
340struct Edge(Option<u64>);
341
342impl<'de> Deserialize<'de> for Edge {
343	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
344		u64::deserialize(deserializer).map(|v| Self(Some(v)))
345	}
346}
347
348/// Prefer the canonical `*_started`/`*_ended` spelling; fall back to the
349/// legacy name so a consumer built after the rename still reads an older relay.
350fn counter_edge(canonical: Edge, legacy: Edge) -> u64 {
351	canonical.0.or(legacy.0).unwrap_or(0)
352}
353
354#[derive(Serialize)]
355struct TrafficSer {
356	announces_started: u64,
357	announced: u64,
358	announces_ended: u64,
359	announced_closed: u64,
360	announced_bytes: u64,
361	broadcasts_started: u64,
362	broadcasts: u64,
363	broadcasts_ended: u64,
364	broadcasts_closed: u64,
365	subscriptions_started: u64,
366	subscriptions: u64,
367	subscriptions_ended: u64,
368	subscriptions_closed: u64,
369	fetches: u64,
370	bytes: u64,
371	frames: u64,
372	groups: u64,
373	datagrams: u64,
374	stale: Content,
375}
376
377impl From<Traffic> for TrafficSer {
378	fn from(t: Traffic) -> Self {
379		Self {
380			announces_started: t.announces_started,
381			announced: t.announces_started,
382			announces_ended: t.announces_ended,
383			announced_closed: t.announces_ended,
384			announced_bytes: t.announced_bytes,
385			broadcasts_started: t.broadcasts_started,
386			broadcasts: t.broadcasts_started,
387			broadcasts_ended: t.broadcasts_ended,
388			broadcasts_closed: t.broadcasts_ended,
389			subscriptions_started: t.subscriptions_started,
390			subscriptions: t.subscriptions_started,
391			subscriptions_ended: t.subscriptions_ended,
392			subscriptions_closed: t.subscriptions_ended,
393			fetches: t.fetches,
394			bytes: t.bytes,
395			frames: t.frames,
396			groups: t.groups,
397			datagrams: t.datagrams,
398			stale: t.stale,
399		}
400	}
401}
402
403#[derive(Default, Deserialize)]
404#[serde(default)]
405struct TrafficDe {
406	announces_started: Edge,
407	announced: Edge,
408	announces_ended: Edge,
409	announced_closed: Edge,
410	announced_bytes: u64,
411	broadcasts_started: Edge,
412	broadcasts: Edge,
413	broadcasts_ended: Edge,
414	broadcasts_closed: Edge,
415	subscriptions_started: Edge,
416	subscriptions: Edge,
417	subscriptions_ended: Edge,
418	subscriptions_closed: Edge,
419	fetches: u64,
420	bytes: u64,
421	frames: u64,
422	groups: u64,
423	datagrams: u64,
424	stale: Content,
425}
426
427impl From<TrafficDe> for Traffic {
428	fn from(d: TrafficDe) -> Self {
429		Self {
430			announces_started: counter_edge(d.announces_started, d.announced),
431			announces_ended: counter_edge(d.announces_ended, d.announced_closed),
432			announced_bytes: d.announced_bytes,
433			broadcasts_started: counter_edge(d.broadcasts_started, d.broadcasts),
434			broadcasts_ended: counter_edge(d.broadcasts_ended, d.broadcasts_closed),
435			subscriptions_started: counter_edge(d.subscriptions_started, d.subscriptions),
436			subscriptions_ended: counter_edge(d.subscriptions_ended, d.subscriptions_closed),
437			fetches: d.fetches,
438			bytes: d.bytes,
439			frames: d.frames,
440			groups: d.groups,
441			datagrams: d.datagrams,
442			stale: d.stale,
443		}
444	}
445}
446
447impl Serialize for Traffic {
448	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
449		TrafficSer::from(*self).serialize(serializer)
450	}
451}
452
453impl<'de> Deserialize<'de> for Traffic {
454	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
455		TrafficDe::deserialize(deserializer).map(Into::into)
456	}
457}
458
459impl Traffic {
460	/// Fold another readout into this one, counter by counter.
461	pub fn add(&mut self, other: Traffic) {
462		self.announces_started += other.announces_started;
463		self.announces_ended += other.announces_ended;
464		self.announced_bytes += other.announced_bytes;
465		self.broadcasts_started += other.broadcasts_started;
466		self.broadcasts_ended += other.broadcasts_ended;
467		self.subscriptions_started += other.subscriptions_started;
468		self.subscriptions_ended += other.subscriptions_ended;
469		self.fetches += other.fetches;
470		self.bytes += other.bytes;
471		self.frames += other.frames;
472		self.groups += other.groups;
473		self.datagrams += other.datagrams;
474		self.stale.add(other.stale);
475	}
476
477	/// True while the broadcast is announced (an announce guard is open).
478	pub fn is_announced(&self) -> bool {
479		self.announces_started > self.announces_ended
480	}
481
482	/// Distinct sessions currently subscribed (viewers on the egress side).
483	pub fn active_broadcasts(&self) -> u64 {
484		self.broadcasts_started.saturating_sub(self.broadcasts_ended)
485	}
486
487	/// Track subscriptions currently open.
488	pub fn active_subscriptions(&self) -> u64 {
489		self.subscriptions_started.saturating_sub(self.subscriptions_ended)
490	}
491
492	/// All bytes attributable to this slice: payload plus announce overhead.
493	/// Both inputs are monotonic, so the sum regresses only when the entry was
494	/// garbage collected and re-created.
495	pub fn total_bytes(&self) -> u64 {
496		self.bytes.saturating_add(self.announced_bytes)
497	}
498
499	/// True once every started counter equals its ended counterpart: no guard is
500	/// held, so no more traffic can flow until a new start.
501	pub fn is_idle(&self) -> bool {
502		self.announces_started == self.announces_ended
503			&& self.subscriptions_started == self.subscriptions_ended
504			&& self.broadcasts_started == self.broadcasts_ended
505	}
506}
507
508/// Connected-session presence for one slice (an auth root on a tier, or any
509/// sum of such slices): cumulative connects and disconnects. `sessions_started
510/// - sessions_ended` is the current live session count.
511///
512/// Like [`Traffic`], this is also the wire shape of one entry on a published
513/// sessions track. Serialize writes both the canonical names and the legacy
514/// `sessions`/`sessions_closed` spellings; deserialize accepts either, with
515/// the canonical name winning when both are present.
516#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
517#[non_exhaustive]
518pub struct Presence {
519	/// Cumulative sessions connected.
520	pub sessions_started: u64,
521	/// Cumulative sessions disconnected.
522	pub sessions_ended: u64,
523}
524
525#[derive(Serialize)]
526struct PresenceSer {
527	sessions_started: u64,
528	sessions: u64,
529	sessions_ended: u64,
530	sessions_closed: u64,
531}
532
533impl From<Presence> for PresenceSer {
534	fn from(p: Presence) -> Self {
535		Self {
536			sessions_started: p.sessions_started,
537			sessions: p.sessions_started,
538			sessions_ended: p.sessions_ended,
539			sessions_closed: p.sessions_ended,
540		}
541	}
542}
543
544#[derive(Default, Deserialize)]
545#[serde(default)]
546struct PresenceDe {
547	sessions_started: Edge,
548	sessions: Edge,
549	sessions_ended: Edge,
550	sessions_closed: Edge,
551}
552
553impl From<PresenceDe> for Presence {
554	fn from(d: PresenceDe) -> Self {
555		Self {
556			sessions_started: counter_edge(d.sessions_started, d.sessions),
557			sessions_ended: counter_edge(d.sessions_ended, d.sessions_closed),
558		}
559	}
560}
561
562impl Serialize for Presence {
563	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
564		PresenceSer::from(*self).serialize(serializer)
565	}
566}
567
568impl<'de> Deserialize<'de> for Presence {
569	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
570		PresenceDe::deserialize(deserializer).map(Into::into)
571	}
572}
573
574impl Presence {
575	/// Fold another readout into this one.
576	pub fn add(&mut self, other: Presence) {
577		self.sessions_started += other.sessions_started;
578		self.sessions_ended += other.sessions_ended;
579	}
580
581	/// Sessions currently connected.
582	pub fn active(&self) -> u64 {
583		self.sessions_started.saturating_sub(self.sessions_ended)
584	}
585}
586
587/// Traffic-class label that selects which counter set a session's bumps record
588/// in, so a single [`Registry`] can split customer-facing, cluster-peer, regional,
589/// etc. traffic. Each tracked broadcast keeps a per-tier counter set on both its
590/// publisher and subscriber sides.
591///
592/// The default tier ([`Tier::default`]) is unprefixed: its published tracks are
593/// `publisher.json`, `subscriber.json`, and `sessions.json`. A named tier
594/// prefixes every track with its label, so `Tier::new("region/sjc")` records on
595/// `region/sjc/publisher.json`. The label is an arbitrary path chosen by business
596/// logic; an empty label is the default tier.
597#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
598pub struct Tier(PathOwned);
599
600impl Tier {
601	/// A tier with the given label. An empty label is the default tier.
602	pub fn new(label: impl Into<PathOwned>) -> Self {
603		Self(label.into())
604	}
605
606	/// The tier label, empty for the default tier.
607	pub fn label(&self) -> &PathOwned {
608		&self.0
609	}
610
611	/// True for the default (unprefixed) tier.
612	pub fn is_default(&self) -> bool {
613		self.0.is_empty()
614	}
615
616	/// Track name for this tier: `name` on the default tier, else `<tier>/<name>`.
617	/// This is the naming rule the published stats tracks follow.
618	pub fn track_name(&self, name: &str) -> String {
619		if self.0.is_empty() {
620			name.to_string()
621		} else {
622			format!("{}/{}", self.0.as_str(), name)
623		}
624	}
625
626	/// The tier label as used in metrics: empty (`""`) for the default tier,
627	/// otherwise the label (e.g. `"region/sjc"`). Mirrors the
628	/// wire convention, where the default tier is unprefixed and named
629	/// tiers are `<label>/`-prefixed.
630	pub fn as_str(&self) -> &str {
631		self.0.as_str()
632	}
633}
634
635impl fmt::Display for Tier {
636	/// The label, empty for the default unprefixed tier.
637	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638		fmt::Display::fmt(&self.0, f)
639	}
640}
641
642/// Publisher (egress) vs subscriber (ingress) side of a broadcast, used as a
643/// label on a [`Snapshot`] traffic row. The internal bump paths track the
644/// side statically, so this only surfaces on the aggregate read side.
645///
646/// This is the direction traffic flowed, not the session role a client advertises
647/// in its SETUP ([`crate::Role`]): one session records on both sides.
648#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
649pub enum Role {
650	/// Egress: bytes this node published to a peer.
651	Publisher,
652	/// Ingress: bytes this node consumed from a peer.
653	Subscriber,
654}
655
656impl Role {
657	fn idx(self) -> usize {
658		match self {
659			Role::Publisher => 0,
660			Role::Subscriber => 1,
661		}
662	}
663
664	/// Lowercase label for this role (`"publisher"` / `"subscriber"`).
665	pub fn as_str(self) -> &'static str {
666		match self {
667			Role::Publisher => "publisher",
668			Role::Subscriber => "subscriber",
669		}
670	}
671}
672
673/// A point-in-time, host-level rollup of a registry's counters, returned
674/// by [`Registry::snapshot`].
675///
676/// Every counter is summed across all broadcasts the registry is tracking and
677/// split by tier and role, plus per-tier connected-session presence. One entry
678/// per tier that recorded any traffic or session, keyed by the tier's label (so
679/// an idle tier is simply absent). Intended for a scrape / `/metrics`-style
680/// endpoint where per-broadcast cardinality is unwanted; use
681/// [`Registry::report`] for the per-broadcast breakdown. A disabled registry
682/// yields no rows.
683#[derive(Debug, Default, Clone, PartialEq, Eq)]
684#[non_exhaustive]
685pub struct Snapshot {
686	/// Traffic totals per tier, indexed by [`Role`] within each tier; read via
687	/// [`Self::traffic`].
688	traffic: HashMap<Tier, [Traffic; 2]>,
689	/// Session presence per tier; read via [`Self::sessions`].
690	sessions: HashMap<Tier, Presence>,
691}
692
693impl Snapshot {
694	/// The `(tier, role, totals)` traffic rows, one publisher and one subscriber
695	/// row per tier present. Sorted by tier label then role for stable output.
696	pub fn traffic(&self) -> Vec<(Tier, Role, Traffic)> {
697		let mut rows = Vec::with_capacity(self.traffic.len() * 2);
698		for (tier, roles) in &self.traffic {
699			rows.push((tier.clone(), Role::Publisher, roles[Role::Publisher.idx()]));
700			rows.push((tier.clone(), Role::Subscriber, roles[Role::Subscriber.idx()]));
701		}
702		rows.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()).then(a.1.idx().cmp(&b.1.idx())));
703		rows
704	}
705
706	/// The `(tier, sessions)` presence rows, one per tier present, sorted by tier
707	/// label.
708	pub fn sessions(&self) -> Vec<(Tier, Presence)> {
709		let mut rows: Vec<_> = self.sessions.iter().map(|(tier, s)| (tier.clone(), *s)).collect();
710		rows.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
711		rows
712	}
713}
714
715/// The per-broadcast detail [`Registry::report`] fills: one traffic entry per
716/// `(broadcast, tier)` and one session entry per `(tier, root)`. Entries are
717/// unordered. Reuse one across drains to keep its capacity.
718#[derive(Debug, Default, Clone)]
719#[non_exhaustive]
720pub struct Report {
721	/// Per-`(broadcast, tier)` traffic, both roles per entry.
722	pub traffic: Vec<TrafficEntry>,
723	/// Per-`(tier, root)` connected-session presence.
724	pub sessions: Vec<SessionEntry>,
725}
726
727/// One `(broadcast, tier)` row of a [`Report`].
728#[derive(Debug, Clone)]
729#[non_exhaustive]
730pub struct TrafficEntry {
731	/// The broadcast path the counters are keyed by.
732	pub path: PathOwned,
733	/// The tier the counters recorded under.
734	pub tier: Tier,
735	/// Egress counters (this node publishing to peers).
736	pub publisher: Traffic,
737	/// Ingress counters (this node consuming from peers).
738	pub subscriber: Traffic,
739}
740
741/// One `(tier, root)` row of a [`Report`].
742#[derive(Debug, Clone)]
743#[non_exhaustive]
744pub struct SessionEntry {
745	/// The tier the sessions recorded under.
746	pub tier: Tier,
747	/// The auth root the sessions connected under.
748	pub root: PathOwned,
749	/// The cumulative connect/disconnect gauge.
750	pub presence: Presence,
751}
752
753/// Settings for a [`Registry`]. Construct with [`Config::new`] and chain the
754/// `with_*` setters, then hand it to [`Registry::new`].
755///
756/// Every field here is about *collection*; the publishing knobs (origin,
757/// interval, node, ...) live on the `moq-stats` producer config.
758#[derive(Clone, Debug, Default)]
759#[non_exhaustive]
760pub struct Config {
761	/// Patterns whose broadcasts are not tracked: a matching path gets an empty
762	/// handle whose bumps no-op. A publisher excludes its own stats subtree
763	/// (`.stats/**`) this way, breaking the stats-of-stats feedback loop. Empty
764	/// (the default) tracks everything.
765	pub exclude: Patterns,
766}
767
768impl Config {
769	/// A config with default settings: nothing excluded.
770	pub fn new() -> Self {
771		Self::default()
772	}
773
774	/// Add a pattern to exclude from tracking. May be chained to exclude
775	/// several.
776	pub fn with_exclude(mut self, pattern: Pattern) -> Self {
777		self.exclude.insert(pattern);
778		self
779	}
780}
781
782/// Counter collection registry. Cheap to clone (`Arc` inside for the shared
783/// state). One instance per relay; sessions get tier-scoped handles via
784/// [`Registry::tier`]. The `moq-stats` crate drains it with
785/// [`Registry::report`] to publish the counters as MoQ broadcasts.
786#[derive(Clone)]
787pub struct Registry {
788	/// Paths these patterns match get empty handles (bumps no-op); see
789	/// [`Config::exclude`].
790	exclude: Patterns,
791	/// `None` for a disabled registry: bumps are dropped and nothing is tracked.
792	shared: Option<Arc<Shared>>,
793}
794
795/// State shared by every clone of a [`Registry`].
796struct Shared {
797	entries: Lock<HashMap<PathOwned, Arc<BroadcastEntry>>>,
798	/// Connected-session gauges keyed by `(tier, auth root)`. Independent of any
799	/// broadcast; surfaced on the per-tier session tracks. A tier's inner map is
800	/// created the first time a session records under it.
801	sessions: Lock<HashMap<Tier, HashMap<PathOwned, Arc<SessionCounters>>>>,
802}
803
804/// Per-broadcast counters, lazily split by tier. A tier's [`TierCounters`] is
805/// created the first time a guard records under that label, so the set of tiers
806/// is fully dynamic. A [`Scope`] resolves the `Arc<TierCounters>` once per session
807/// tier and hands it to the guards and meters it creates, so the per-byte path
808/// never touches this map.
809struct BroadcastEntry {
810	tiers: Mutex<HashMap<Tier, Arc<TierCounters>>>,
811}
812
813impl BroadcastEntry {
814	fn new() -> Self {
815		Self {
816			tiers: Mutex::new(HashMap::new()),
817		}
818	}
819
820	/// Get-or-create the counters for `tier` on this broadcast.
821	fn tier(&self, tier: &Tier) -> Arc<TierCounters> {
822		self.tiers
823			.lock()
824			.expect("stats tiers poisoned")
825			.entry(tier.clone())
826			.or_default()
827			.clone()
828	}
829}
830
831/// Publisher and subscriber [`Counters`] for one `(broadcast, tier)`. The two
832/// sides are named explicitly (rather than indexed by a `Role` enum) because
833/// the bump-path call sites always know which side they're on at compile time.
834#[derive(Default)]
835struct TierCounters {
836	publisher: Counters,
837	subscriber: Counters,
838}
839
840impl Registry {
841	/// Build an enabled registry from `config`.
842	pub fn new(config: Config) -> Self {
843		let Config { exclude } = config;
844		Self {
845			exclude,
846			shared: Some(Arc::new(Shared {
847				entries: Lock::default(),
848				sessions: Default::default(),
849			})),
850		}
851	}
852
853	/// Build a no-op registry: every handle is empty and all bumps are dropped.
854	pub fn disabled() -> Self {
855		Self {
856			exclude: Patterns::new(),
857			shared: None,
858		}
859	}
860
861	/// The excluded patterns. See [`Config::exclude`].
862	pub fn exclude(&self) -> &Patterns {
863		&self.exclude
864	}
865
866	/// The shared state, panicking for a disabled registry. Tests build enabled
867	/// registries so this is always present.
868	#[cfg(test)]
869	fn shared(&self) -> &Arc<Shared> {
870		self.shared.as_ref().expect("enabled stats registry")
871	}
872
873	/// Returns a tier-scoped handle. Bumps through this handle land in the
874	/// tier's counters.
875	pub fn tier(&self, tier: Tier) -> Handle {
876		Handle {
877			stats: self.clone(),
878			tier,
879		}
880	}
881
882	fn entry(&self, path: impl AsPath) -> Option<Arc<BroadcastEntry>> {
883		// A disabled registry never allocates state.
884		let shared = self.shared.as_ref()?;
885		let path = path.as_path();
886		// Skip excluded paths (our own stats broadcasts and any sibling category
887		// under the same prefix) so serving a stats broadcast doesn't generate
888		// more stats.
889		if self.exclude.matches(path.as_str()) {
890			return None;
891		}
892		let owned = path.to_owned();
893		let mut entries = shared.entries.lock();
894		Some(
895			entries
896				.entry(owned)
897				.or_insert_with(|| Arc::new(BroadcastEntry::new()))
898				.clone(),
899		)
900	}
901
902	/// Get-or-create the session gauge for `root` on `tier`. `None` for a
903	/// disabled registry. Unlike [`Self::entry`], roots are auth scopes (never
904	/// under a stats prefix), so no cycle-breaking filter is needed.
905	fn session_counters(&self, tier: &Tier, root: impl AsPath) -> Option<Arc<SessionCounters>> {
906		let shared = self.shared.as_ref()?;
907		let owned = root.as_path().to_owned();
908		let mut sessions = shared.sessions.lock();
909		Some(
910			sessions
911				.entry(tier.clone())
912				.or_default()
913				.entry(owned)
914				.or_default()
915				.clone(),
916		)
917	}
918
919	/// Take a host-level [`Snapshot`]: every counter summed across all
920	/// tracked broadcasts, split by tier and role, plus per-tier session
921	/// presence. Briefly takes the entry then the session locks. Returns an
922	/// all-zero snapshot for a disabled registry.
923	///
924	/// Unlike [`Registry::report`], this collapses per-broadcast detail into
925	/// node totals (what a `/metrics`-style scrape wants) and never prunes.
926	pub fn snapshot(&self) -> Snapshot {
927		let mut snap = Snapshot::default();
928		let Some(shared) = self.shared.as_ref() else {
929			return snap;
930		};
931		{
932			let entries = shared.entries.lock();
933			for entry in entries.values() {
934				let tiers = entry.tiers.lock().expect("stats tiers poisoned");
935				for (tier, counters) in tiers.iter() {
936					let totals = snap.traffic.entry(tier.clone()).or_default();
937					totals[Role::Publisher.idx()].add(counters.publisher.snapshot());
938					totals[Role::Subscriber.idx()].add(counters.subscriber.snapshot());
939				}
940			}
941		}
942		{
943			let sessions = shared.sessions.lock();
944			for (tier, roots) in sessions.iter() {
945				let totals = snap.sessions.entry(tier.clone()).or_default();
946				for counters in roots.values() {
947					totals.add(counters.snapshot());
948				}
949			}
950		}
951		snap
952	}
953
954	/// Refill `report` with the per-broadcast detail and prune dead entries.
955	///
956	/// Clears `report`, keeping its capacity so a caller draining on an
957	/// interval reuses one report instead of allocating per drain, then fills
958	/// every `(broadcast, tier)` traffic readout and every `(tier, root)`
959	/// session gauge. Entries no guard references anymore are then dropped
960	/// (their final values are still in the report, so a publisher draining on
961	/// an interval emits the closing readout exactly once). A pruned path that
962	/// sees traffic again restarts from zero; see the module docs on counter
963	/// resets. Leaves the report empty for a disabled registry.
964	pub fn report(&self, report: &mut Report) {
965		report.traffic.clear();
966		report.sessions.clear();
967		let Some(shared) = self.shared.as_ref() else {
968			return;
969		};
970		{
971			let mut entries = shared.entries.lock();
972			for (path, entry) in entries.iter() {
973				let tiers = entry.tiers.lock().expect("stats tiers poisoned");
974				for (tier, counters) in tiers.iter() {
975					report.traffic.push(TrafficEntry {
976						path: path.clone(),
977						tier: tier.clone(),
978						publisher: counters.publisher.snapshot(),
979						subscriber: counters.subscriber.snapshot(),
980					});
981				}
982			}
983			// Prune entries no guard holds anymore: with only the map's Arc
984			// left, no future bump can land, so the entry is done. (A guard
985			// created after the readout above still holds the Arc and keeps
986			// its entry alive.)
987			entries.retain(|_, entry| {
988				if Arc::strong_count(entry) > 1 {
989					return true;
990				}
991				let mut tiers = entry.tiers.lock().expect("stats tiers poisoned");
992				tiers.retain(|_, counters| Arc::strong_count(counters) > 1);
993				!tiers.is_empty()
994			});
995		}
996		{
997			let mut sessions = shared.sessions.lock();
998			for (tier, roots) in sessions.iter() {
999				for (root, counters) in roots.iter() {
1000					report.sessions.push(SessionEntry {
1001						tier: tier.clone(),
1002						root: root.clone(),
1003						presence: counters.snapshot(),
1004					});
1005				}
1006			}
1007			for roots in sessions.values_mut() {
1008				roots.retain(|_, counters| Arc::strong_count(counters) > 1);
1009			}
1010			sessions.retain(|_, roots| !roots.is_empty());
1011		}
1012	}
1013}
1014
1015impl Default for Registry {
1016	/// A disabled (no-op) registry; see [`Registry::disabled`].
1017	fn default() -> Self {
1018		Self::disabled()
1019	}
1020}
1021
1022/// Tier-scoped wrapper around [`Registry`]. What [`crate::Client::with_stats`] and
1023/// [`crate::Server::with_stats`] accept. Cheap to clone.
1024#[derive(Clone)]
1025pub struct Handle {
1026	stats: Registry,
1027	tier: Tier,
1028}
1029
1030impl Handle {
1031	/// The registry this handle is tied to.
1032	pub fn parent(&self) -> &Registry {
1033		&self.stats
1034	}
1035
1036	/// The tier this handle bumps into.
1037	pub fn tier(&self) -> &Tier {
1038		&self.tier
1039	}
1040
1041	/// Record a connected session authenticated under `root` on this tier. Hold
1042	/// the returned guard for the session's lifetime; dropping it bumps
1043	/// `sessions_ended`. Counts presence regardless of any data flow, so a
1044	/// session that merely connects is still billable. Surfaced on the session
1045	/// track for this tier, keyed by `root`.
1046	pub fn session(&self, root: impl AsPath) -> Session {
1047		Session::new(self.stats.clone(), self.tier.clone(), root)
1048	}
1049}
1050
1051impl Default for Handle {
1052	/// A no-op handle backed by a disabled [`Registry`].
1053	fn default() -> Self {
1054		Registry::disabled().tier(Tier::default())
1055	}
1056}
1057
1058/// Which side of a [`TierCounters`] a bump lands on: publisher (egress) or
1059/// subscriber (ingress). `Default` is `Publisher`, chosen only so an empty
1060/// [`Meter`] / [`Scope`] has one; it never records because its counters are `None`.
1061#[derive(Copy, Clone, Default)]
1062enum Side {
1063	#[default]
1064	Publisher,
1065	Subscriber,
1066}
1067
1068impl Side {
1069	fn counters(self, tier: &TierCounters) -> &Counters {
1070		match self {
1071			Side::Publisher => &tier.publisher,
1072			Side::Subscriber => &tier.subscriber,
1073		}
1074	}
1075}
1076
1077/// Per-connection stats context, created via [`Handle::session`].
1078///
1079/// Cheap to clone (an `Arc` inside): one context is shared by both origin handles
1080/// of a session (its publish and subscribe halves) so presence and viewer counts
1081/// are never double-attributed. It carries three things:
1082///
1083/// * the tier + auth root, so any broadcast reached through a tagged origin handle
1084///   resolves the right per-`(path, tier)` counters,
1085/// * the presence gauge: `sessions_started` bumps when the context is created and
1086///   `sessions_ended` when the last clone drops (a more honest close than a
1087///   separately-held guard),
1088/// * the egress viewer refcount map (first/last active subscription per broadcast),
1089///   driving `broadcasts_started` / `broadcasts_ended`.
1090///
1091/// [`Session::set_tier`] moves a live context to another tier: presence and traffic
1092/// recorded afterwards land there, while what was already counted stays put and an
1093/// open subscription or announce closes on the tier it opened on.
1094///
1095/// [`Session::default`] is the no-op context (disabled registry / untagged caller):
1096/// every bump reached through it is silently dropped, so a handle can hold one
1097/// unconditionally instead of threading an `Option`.
1098#[derive(Clone, Default)]
1099pub struct Session {
1100	/// `None` for the no-op context (disabled registry or a `default()` handle).
1101	inner: Option<Arc<SessionInner>>,
1102}
1103
1104/// The shared state behind a [`Session`]. Its `Drop` (on the last clone) records
1105/// the session as closed.
1106struct SessionInner {
1107	registry: Registry,
1108	/// The auth root the presence gauge is keyed by.
1109	root: PathOwned,
1110	/// The current tier and its presence gauge, swapped together by [`Session::set_tier`].
1111	current: Mutex<Current>,
1112	/// Bumped on every tier change, so a [`Scope`] notices without taking a lock.
1113	generation: AtomicU64,
1114	/// Egress viewer refcount, keyed by absolute broadcast path: the first active
1115	/// subscription this context opens for a broadcast bumps `broadcasts_started`, the last
1116	/// to close bumps `broadcasts_ended` on the same counters, even across a tier change.
1117	viewers: Mutex<HashMap<PathOwned, Viewer>>,
1118}
1119
1120/// The tier a [`Session`] records under right now.
1121struct Current {
1122	tier: Tier,
1123	/// The presence gauge for `(tier, root)`, or `None` for a disabled registry.
1124	presence: Option<Arc<SessionCounters>>,
1125}
1126
1127/// One broadcast's viewer refcount within a [`Session`].
1128struct Viewer {
1129	subscriptions: u32,
1130	/// The counters `broadcasts_started` bumped on, where `broadcasts_ended` lands too.
1131	counters: Arc<TierCounters>,
1132}
1133
1134impl Session {
1135	fn new(registry: Registry, tier: Tier, root: impl AsPath) -> Self {
1136		let root = root.as_path().to_owned();
1137		let presence = registry.session_counters(&tier, &root);
1138		if let Some(presence) = &presence {
1139			presence.sessions_started.fetch_add(1, Ordering::Relaxed);
1140		}
1141		Self {
1142			inner: Some(Arc::new(SessionInner {
1143				registry,
1144				root,
1145				current: Mutex::new(Current { tier, presence }),
1146				generation: AtomicU64::new(0),
1147				viewers: Mutex::new(HashMap::new()),
1148			})),
1149		}
1150	}
1151
1152	/// Record this session's presence and later traffic under `tier` from now on.
1153	pub fn set_tier(&self, tier: Tier) {
1154		let Some(inner) = &self.inner else { return };
1155		let mut current = inner.current.lock().expect("stats session poisoned");
1156		if current.tier == tier {
1157			return;
1158		}
1159		let presence = inner.registry.session_counters(&tier, &inner.root);
1160		if let Some(presence) = &presence {
1161			presence.sessions_started.fetch_add(1, Ordering::Relaxed);
1162		}
1163		if let Some(old) = std::mem::replace(&mut current.presence, presence) {
1164			// Release pairs with the readout's Acquire load of `sessions_ended`.
1165			old.sessions_ended.fetch_add(1, Ordering::Release);
1166		}
1167		current.tier = tier;
1168		inner.generation.fetch_add(1, Ordering::Release);
1169	}
1170
1171	/// Egress (publisher / reads) scope for a broadcast path. The path is the
1172	/// absolute broadcast name.
1173	pub(crate) fn egress(&self, path: impl AsPath) -> Scope {
1174		self.scope(path, Side::Publisher)
1175	}
1176
1177	/// Ingress (subscriber / writes) scope for a broadcast path.
1178	pub(crate) fn ingress(&self, path: impl AsPath) -> Scope {
1179		self.scope(path, Side::Subscriber)
1180	}
1181
1182	fn scope(&self, path: impl AsPath, side: Side) -> Scope {
1183		let Some(inner) = &self.inner else {
1184			return Scope::default();
1185		};
1186		let path = path.as_path().to_owned();
1187		let resolved = inner.resolve(&path);
1188		Scope {
1189			session: self.clone(),
1190			resolved: Some(Box::new(Mutex::new(resolved))),
1191			side,
1192			path,
1193		}
1194	}
1195
1196	/// Register one active egress subscription to `path` recording on `counters`.
1197	/// The first bumps `broadcasts_started` there.
1198	fn viewer_open(&self, path: &PathOwned, counters: &Arc<TierCounters>) {
1199		let Some(inner) = &self.inner else { return };
1200		let mut viewers = inner.viewers.lock().expect("stats viewers poisoned");
1201		let viewer = viewers.entry(path.clone()).or_insert_with(|| {
1202			counters.publisher.broadcasts_started.fetch_add(1, Ordering::Relaxed);
1203			Viewer {
1204				subscriptions: 0,
1205				counters: counters.clone(),
1206			}
1207		});
1208		viewer.subscriptions += 1;
1209	}
1210
1211	/// Release one active egress subscription to `path`. The last bumps
1212	/// `broadcasts_ended` on the counters the first opened on.
1213	fn viewer_close(&self, path: &PathOwned) {
1214		let Some(inner) = &self.inner else { return };
1215		let mut viewers = inner.viewers.lock().expect("stats viewers poisoned");
1216		let Some(viewer) = viewers.get_mut(path) else { return };
1217		viewer.subscriptions -= 1;
1218		if viewer.subscriptions == 0
1219			&& let Some(viewer) = viewers.remove(path)
1220		{
1221			// Release pairs with the readout's Acquire load of `broadcasts_ended`.
1222			viewer
1223				.counters
1224				.publisher
1225				.broadcasts_ended
1226				.fetch_add(1, Ordering::Release);
1227		}
1228	}
1229}
1230
1231impl SessionInner {
1232	/// The counters `path` records on under the current tier, tagged with the
1233	/// generation they were resolved at.
1234	fn resolve(&self, path: &PathOwned) -> Resolved {
1235		let (generation, tier) = {
1236			let current = self.current.lock().expect("stats session poisoned");
1237			(self.generation.load(Ordering::Relaxed), current.tier.clone())
1238		};
1239		Resolved {
1240			generation,
1241			counters: self.registry.entry(path).map(|entry| entry.tier(&tier)),
1242		}
1243	}
1244}
1245
1246impl Drop for SessionInner {
1247	fn drop(&mut self) {
1248		let current = self.current.get_mut().expect("stats session poisoned");
1249		if let Some(presence) = &current.presence {
1250			// Release pairs with the readout's Acquire load of `sessions_ended`
1251			// (see the module-level "Snapshot atomicity" note).
1252			presence.sessions_ended.fetch_add(1, Ordering::Release);
1253		}
1254	}
1255}
1256
1257// ---------------------------------------------------------------------------
1258// Model-layer carriers
1259//
1260// These are what a tagged `origin::{Consumer, Producer}` threads down through the
1261// derived handles (broadcast -> track -> group -> frame). A tagged origin creates a
1262// [`Scope`] per broadcast, which resolves the per-`(path, tier)` counters again
1263// only after [`Session::set_tier`]; child handles carry a cheap [`Meter`] for the
1264// payload bumps, fixed to the tier the group started under. All of them are no-ops when empty (a
1265// disabled registry, an excluded path, or an untagged caller), so an untagged
1266// handle pays nothing.
1267// ---------------------------------------------------------------------------
1268
1269/// Payload bump handle carried by the group and frame model handles. Cheap to
1270/// clone (an `Option<Arc>` plus a `Side`); empty when the broadcast is untracked.
1271#[derive(Clone, Default)]
1272pub(crate) struct Meter {
1273	counters: Option<Arc<TierCounters>>,
1274	side: Side,
1275}
1276
1277impl Meter {
1278	fn counters(&self) -> Option<&Counters> {
1279		self.counters.as_ref().map(|c| self.side.counters(c))
1280	}
1281
1282	/// Bump `groups` once (a group delivered/consumed on this side).
1283	pub(crate) fn group(&self) {
1284		if let Some(counters) = self.counters() {
1285			counters.groups.fetch_add(1, Ordering::Relaxed);
1286		}
1287	}
1288
1289	/// Bump `frames` by `n`.
1290	pub(crate) fn frames(&self, n: u64) {
1291		if n == 0 {
1292			return;
1293		}
1294		if let Some(counters) = self.counters() {
1295			counters.frames.fetch_add(n, Ordering::Relaxed);
1296		}
1297	}
1298
1299	/// Record one datagram of `n` payload bytes. A datagram stands in for the
1300	/// single-frame group it replaces, so this bumps `groups`, `frames`, and
1301	/// `bytes` alongside `datagrams`.
1302	pub(crate) fn datagram(&self, n: u64) {
1303		if let Some(counters) = self.counters() {
1304			counters.datagrams.fetch_add(1, Ordering::Relaxed);
1305			counters.groups.fetch_add(1, Ordering::Relaxed);
1306			counters.frames.fetch_add(1, Ordering::Relaxed);
1307			counters.bytes.fetch_add(n, Ordering::Relaxed);
1308		}
1309	}
1310
1311	/// Whether this meter attributes anything, i.e. the broadcast is tracked and the
1312	/// handle was tagged. A caller holding a count that has to land exactly once can
1313	/// keep it rather than drop it into an untagged meter.
1314	pub(crate) fn is_tracked(&self) -> bool {
1315		self.counters.is_some()
1316	}
1317
1318	/// Record content skipped before delivery by the drift budget.
1319	pub(crate) fn stale(&self, content: Content) {
1320		if let Some(counters) = self.counters() {
1321			counters.stale.add(content);
1322		}
1323	}
1324
1325	/// Bump `bytes` by `n`.
1326	pub(crate) fn bytes(&self, n: u64) {
1327		if n == 0 {
1328			return;
1329		}
1330		if let Some(counters) = self.counters() {
1331			counters.bytes.fetch_add(n, Ordering::Relaxed);
1332		}
1333	}
1334}
1335
1336/// A per-`(broadcast, side)` scope, carried by the broadcast and track model
1337/// handles. Created by a tagged origin at the broadcast handoff; hands out
1338/// [`Meter`]s for the payload path and RAII guards for the subscription / announce
1339/// lifecycle, each recording under the session's tier at the time. Cheap to clone;
1340/// empty (no-op) when the broadcast is untracked.
1341#[derive(Default)]
1342pub(crate) struct Scope {
1343	/// The owning context: its tier, and the egress viewer refcount map.
1344	session: Session,
1345	/// The counters for `(path, tier)`, re-resolved when the session changes tier.
1346	/// Per clone, so tracks sharing a broadcast never contend on the per-group path;
1347	/// boxed to keep every track handle small. `None` for the no-op context.
1348	resolved: Option<Box<Mutex<Resolved>>>,
1349	side: Side,
1350	/// Absolute broadcast path, used to key the viewer refcount and as the
1351	/// `announced_bytes` length.
1352	path: PathOwned,
1353}
1354
1355/// A [`Scope`]'s counters and the session tier generation they belong to.
1356#[derive(Clone)]
1357struct Resolved {
1358	generation: u64,
1359	/// `None` when untracked.
1360	counters: Option<Arc<TierCounters>>,
1361}
1362
1363impl Clone for Scope {
1364	fn clone(&self) -> Self {
1365		Self {
1366			session: self.session.clone(),
1367			resolved: self
1368				.resolved
1369				.as_ref()
1370				.map(|r| Box::new(Mutex::new(r.lock().expect("stats scope poisoned").clone()))),
1371			side: self.side,
1372			path: self.path.clone(),
1373		}
1374	}
1375}
1376
1377impl Scope {
1378	/// The counters for the session's current tier. Skips the registry unless the
1379	/// tier changed since the last call, so the per-group path stays cheap.
1380	fn counters(&self) -> Option<Arc<TierCounters>> {
1381		let inner = self.session.inner.as_ref()?;
1382		let generation = inner.generation.load(Ordering::Acquire);
1383		let mut resolved = self.resolved.as_ref()?.lock().expect("stats scope poisoned");
1384		if resolved.generation != generation {
1385			*resolved = inner.resolve(&self.path);
1386		}
1387		resolved.counters.clone()
1388	}
1389
1390	/// A payload [`Meter`] for a group/frame derived from this scope.
1391	pub(crate) fn meter(&self) -> Meter {
1392		Meter {
1393			counters: self.counters(),
1394			side: self.side,
1395		}
1396	}
1397
1398	/// Open a track-subscription guard: bumps `subscriptions_started` now and
1399	/// `subscriptions_ended` on drop. On the egress (publisher) side it also drives
1400	/// the context's viewer refcount (`broadcasts_started` / `broadcasts_ended`).
1401	pub(crate) fn subscribe(&self) -> Subscription {
1402		let counters = self.counters();
1403		let mut viewer = None;
1404		if let Some(counters) = &counters {
1405			self.side
1406				.counters(counters)
1407				.subscriptions_started
1408				.fetch_add(1, Ordering::Relaxed);
1409			// Viewer refcount is egress-only: `broadcasts_started` counts distinct sessions
1410			// watching a broadcast.
1411			if matches!(self.side, Side::Publisher) {
1412				self.session.viewer_open(&self.path, counters);
1413				viewer = Some((self.session.clone(), self.path.clone()));
1414			}
1415		}
1416		Subscription {
1417			counters,
1418			side: self.side,
1419			viewer,
1420		}
1421	}
1422
1423	/// Bump the `fetches` counter once (a coalesced group fetch served).
1424	pub(crate) fn fetch(&self) {
1425		if let Some(counters) = self.counters() {
1426			self.side.counters(&counters).fetches.fetch_add(1, Ordering::Relaxed);
1427		}
1428	}
1429
1430	/// Open an announce guard: bumps `announces_started` and adds the path length to
1431	/// `announced_bytes` now; on drop bumps `announces_ended` and adds the path
1432	/// length again. Used for egress announce-stream events and ingress
1433	/// route-transition (un)announces.
1434	pub(crate) fn announce(&self) -> Announce {
1435		let len = self.path.as_str().len() as u64;
1436		let counters = self.counters();
1437		if let Some(counters) = &counters {
1438			let counters = self.side.counters(counters);
1439			counters.announces_started.fetch_add(1, Ordering::Relaxed);
1440			counters.announced_bytes.fetch_add(len, Ordering::Relaxed);
1441		}
1442		Announce {
1443			counters,
1444			side: self.side,
1445			len,
1446		}
1447	}
1448}
1449
1450/// RAII guard for a track subscription (either side). See [`Scope::subscribe`].
1451/// [`Subscription::default`] is an empty no-op guard.
1452#[derive(Default)]
1453#[must_use = "drop the guard to record the subscription as closed"]
1454pub(crate) struct Subscription {
1455	counters: Option<Arc<TierCounters>>,
1456	side: Side,
1457	/// `Some((session, path))` on the egress side, to release the viewer refcount.
1458	viewer: Option<(Session, PathOwned)>,
1459}
1460
1461impl Drop for Subscription {
1462	fn drop(&mut self) {
1463		if let Some((session, path)) = &self.viewer {
1464			session.viewer_close(path);
1465		}
1466		if let Some(counters) = &self.counters {
1467			// Release pairs with the readout's Acquire load of `subscriptions_ended`.
1468			self.side
1469				.counters(counters)
1470				.subscriptions_ended
1471				.fetch_add(1, Ordering::Release);
1472		}
1473	}
1474}
1475
1476/// RAII guard for one announce lifetime. See [`Scope::announce`].
1477#[must_use = "drop the guard to record the unannounce"]
1478pub(crate) struct Announce {
1479	counters: Option<Arc<TierCounters>>,
1480	side: Side,
1481	len: u64,
1482}
1483
1484impl Drop for Announce {
1485	fn drop(&mut self) {
1486		if let Some(counters) = &self.counters {
1487			let counters = self.side.counters(counters);
1488			counters.announced_bytes.fetch_add(self.len, Ordering::Relaxed);
1489			// Release pairs with the readout's Acquire load of `announces_ended`.
1490			counters.announces_ended.fetch_add(1, Ordering::Release);
1491		}
1492	}
1493}
1494
1495#[cfg(test)]
1496mod tests {
1497	use std::sync::{Arc, atomic::Ordering::Relaxed};
1498
1499	use super::*;
1500
1501	#[test]
1502	fn default_tier_has_empty_label() {
1503		let tier = Tier::default();
1504		assert_eq!(tier.as_str(), "");
1505		assert_eq!(tier.to_string(), "");
1506		assert_eq!(tier.track_name("publisher.json"), "publisher.json");
1507	}
1508
1509	/// Counters for `(path, tier)`, creating the tier slot if absent.
1510	fn tier_counters(stats: &Registry, path: &str, tier: &Tier) -> Arc<TierCounters> {
1511		stats
1512			.shared()
1513			.entries
1514			.lock()
1515			.get(&PathOwned::from(path.to_string()))
1516			.expect("entry")
1517			.tier(tier)
1518	}
1519
1520	/// The [`Presence`] for `(tier, root)`, or `None` if absent.
1521	fn session_snapshot(stats: &Registry, tier: &Tier, root: &str) -> Option<Presence> {
1522		stats
1523			.shared()
1524			.sessions
1525			.lock()
1526			.get(tier)
1527			.and_then(|roots| roots.get(&PathOwned::from(root.to_string())).map(|c| c.snapshot()))
1528	}
1529
1530	fn test_stats() -> Registry {
1531		Registry::new(Config::new().with_exclude(Pattern::subtree(".stats").unwrap()))
1532	}
1533
1534	#[test]
1535	fn default_and_named_tiers_are_independent() {
1536		let stats = test_stats();
1537		let default = stats.tier(Tier::default()).session("root");
1538		let regional = stats.tier(Tier::new("region/sjc")).session("root");
1539
1540		default.egress("demo/bbb").meter().bytes(100);
1541		regional.ingress("demo/bbb").meter().bytes(7);
1542
1543		let default_counters = tier_counters(&stats, "demo/bbb", &Tier::default());
1544		let regional_counters = tier_counters(&stats, "demo/bbb", &Tier::new("region/sjc"));
1545		assert_eq!(default_counters.publisher.bytes.load(Relaxed), 100);
1546		assert_eq!(default_counters.subscriber.bytes.load(Relaxed), 0);
1547		assert_eq!(regional_counters.publisher.bytes.load(Relaxed), 0);
1548		assert_eq!(regional_counters.subscriber.bytes.load(Relaxed), 7);
1549	}
1550
1551	#[test]
1552	fn snapshot_rolls_up_by_tier_role_and_sessions() {
1553		let stats = test_stats();
1554		let default = stats.tier(Tier::default());
1555		let regional = stats.tier(Tier::new("region/sjc"));
1556
1557		// Two default-tier sessions under one root, one regional; presence sums them.
1558		let s1 = default.session("acme");
1559		let _s2 = default.session("acme");
1560		let s3 = regional.session("peer");
1561
1562		// Default-tier egress across two broadcasts; the snapshot sums them.
1563		{
1564			let m = s1.egress("demo/aaa").meter();
1565			m.bytes(100);
1566			m.frames(1);
1567			m.group();
1568		}
1569		s1.egress("demo/bbb").meter().bytes(50);
1570		// Regional ingress on a different tier/role stays isolated.
1571		s3.ingress("demo/aaa").meter().bytes(7);
1572
1573		let snap = stats.snapshot();
1574
1575		let slot = |tier, role| {
1576			snap.traffic()
1577				.into_iter()
1578				.find(|(t, r, _)| *t == tier && *r == role)
1579				.map(|(_, _, c)| c)
1580				.expect("row present")
1581		};
1582
1583		let default_publisher = slot(Tier::default(), Role::Publisher);
1584		assert_eq!(
1585			default_publisher.bytes, 150,
1586			"default egress bytes sum across broadcasts"
1587		);
1588		assert_eq!(default_publisher.frames, 1);
1589		assert_eq!(default_publisher.groups, 1);
1590
1591		let regional_subscriber = slot(Tier::new("region/sjc"), Role::Subscriber);
1592		assert_eq!(regional_subscriber.bytes, 7, "regional ingress isolated by tier/role");
1593		assert_eq!(slot(Tier::default(), Role::Subscriber).bytes, 0);
1594		assert_eq!(slot(Tier::new("region/sjc"), Role::Publisher).bytes, 0);
1595
1596		let sessions = |tier| {
1597			snap.sessions()
1598				.into_iter()
1599				.find(|(t, _)| *t == tier)
1600				.map(|(_, s)| s)
1601				.expect("tier present")
1602		};
1603		let default_sessions = sessions(Tier::default());
1604		assert_eq!(
1605			default_sessions.sessions_started, 2,
1606			"two default-tier sessions under one root"
1607		);
1608		assert_eq!(default_sessions.sessions_ended, 0, "guards still held");
1609		assert_eq!(sessions(Tier::new("region/sjc")).sessions_started, 1);
1610	}
1611
1612	fn drain(stats: &Registry) -> Report {
1613		let mut report = Report::default();
1614		stats.report(&mut report);
1615		report
1616	}
1617
1618	#[test]
1619	fn report_reuses_capacity() {
1620		// A reused report is cleared, not appended to, and keeps its buffers.
1621		let stats = test_stats();
1622		let ctx = stats.tier(Tier::default()).session("root");
1623		let _scopes: Vec<_> = (0..8).map(|i| ctx.egress(format!("b/{i}").as_str())).collect();
1624
1625		let mut report = Report::default();
1626		stats.report(&mut report);
1627		assert_eq!(report.traffic.len(), 8);
1628		assert_eq!(report.sessions.len(), 1);
1629		let (traffic, sessions) = (report.traffic.as_ptr(), report.sessions.as_ptr());
1630
1631		stats.report(&mut report);
1632		assert_eq!(report.traffic.len(), 8, "refilled, not appended");
1633		assert_eq!(report.sessions.len(), 1);
1634		assert_eq!(report.traffic.as_ptr(), traffic, "traffic buffer reused");
1635		assert_eq!(report.sessions.as_ptr(), sessions, "sessions buffer reused");
1636	}
1637
1638	#[test]
1639	fn report_returns_detail_and_prunes() {
1640		// report() surfaces per-broadcast rows while a guard is held, keeps the
1641		// entry across drains while live, and prunes it on the first drain
1642		// after the last guard drops (returning the final values that once).
1643		let stats = test_stats();
1644		let key = PathOwned::from("foo/bar");
1645		let ctx = stats.tier(Tier::default()).session("root");
1646		let scope = ctx.egress("foo/bar");
1647		let sub = scope.subscribe();
1648		scope.meter().bytes(42);
1649
1650		let report = drain(&stats);
1651		let row = report
1652			.traffic
1653			.iter()
1654			.find(|row| row.path == key)
1655			.expect("live entry present");
1656		assert_eq!(row.publisher.bytes, 42);
1657		assert_eq!(row.publisher.subscriptions_started, 1);
1658		assert!(!row.publisher.is_idle(), "subscription guard still open");
1659		assert!(
1660			stats.shared().entries.lock().contains_key(&key),
1661			"live entry kept across drains"
1662		);
1663
1664		drop(sub);
1665		drop(scope);
1666
1667		// The drain after the last guard drops still returns the final values,
1668		// then prunes the entry.
1669		let report = drain(&stats);
1670		let row = report
1671			.traffic
1672			.iter()
1673			.find(|row| row.path == key)
1674			.expect("closing values still reported once");
1675		assert_eq!(row.publisher.subscriptions_ended, 1);
1676		assert!(row.publisher.is_idle());
1677		assert!(
1678			!stats.shared().entries.lock().contains_key(&key),
1679			"fully-closed entry pruned"
1680		);
1681		assert!(drain(&stats).traffic.is_empty(), "nothing left after the prune");
1682	}
1683
1684	#[test]
1685	fn report_keeps_idle_but_announced_entry() {
1686		// A broadcast with a live announce guard but no traffic must stay in
1687		// the registry indefinitely: announces_started != announces_ended means a
1688		// subscription could still begin at any moment.
1689		let stats = test_stats();
1690		let key = PathOwned::from("foo/bar");
1691		let ctx = stats.tier(Tier::default()).session("root");
1692		let scope = ctx.egress("foo/bar");
1693		let guard = scope.announce();
1694
1695		for _ in 0..3 {
1696			let report = drain(&stats);
1697			assert!(
1698				report.traffic.iter().any(|row| row.path == key),
1699				"announced-but-idle broadcast stays while the guard is held"
1700			);
1701		}
1702
1703		drop(guard);
1704		drop(scope);
1705		let report = drain(&stats);
1706		let row = report.traffic.iter().find(|row| row.path == key).expect("final report");
1707		assert!(row.publisher.is_idle());
1708		assert!(!stats.shared().entries.lock().contains_key(&key));
1709	}
1710
1711	#[test]
1712	fn report_prunes_empty_session_roots() {
1713		// Once the last session under a root disconnects, the root leaves the
1714		// registry on the drain that reports its final gauge.
1715		let stats = test_stats();
1716		let session = stats.tier(Tier::default()).session("acme");
1717
1718		let report = drain(&stats);
1719		let row = report
1720			.sessions
1721			.iter()
1722			.find(|row| row.root.as_str() == "acme")
1723			.expect("root present");
1724		assert_eq!(row.presence.active(), 1);
1725
1726		drop(session);
1727		let report = drain(&stats);
1728		let row = report
1729			.sessions
1730			.iter()
1731			.find(|row| row.root.as_str() == "acme")
1732			.expect("final gauge reported once");
1733		assert_eq!(row.presence.active(), 0);
1734		assert!(drain(&stats).sessions.is_empty(), "root pruned after the last drain");
1735		assert!(session_snapshot(&stats, &Tier::default(), "acme").is_none());
1736	}
1737
1738	#[test]
1739	fn paths_under_exclude_are_no_op() {
1740		// Our own stats broadcasts (and any sibling category under the same
1741		// prefix) must not feed back into the registry.
1742		let stats = test_stats();
1743		let ctx = stats.tier(Tier::default()).session("root");
1744		let scope = ctx.egress(".stats/node/sjc");
1745		scope.meter().bytes(100);
1746		let _guard = scope.announce();
1747		let _sub = scope.subscribe();
1748		assert!(stats.shared().entries.lock().is_empty());
1749	}
1750
1751	#[test]
1752	fn disabled_stats_are_noop() {
1753		// A disabled registry allocates no shared state; every handle is empty
1754		// and bumps are dropped.
1755		let stats = Registry::default();
1756		assert!(stats.shared.is_none());
1757		let ctx = stats.tier(Tier::default()).session("root");
1758		let scope = ctx.egress("demo/bbb");
1759		scope.meter().bytes(100);
1760		let _guard = scope.announce();
1761		let _sub = scope.subscribe();
1762		assert!(drain(&stats).traffic.is_empty());
1763		assert!(stats.snapshot().traffic().is_empty());
1764	}
1765
1766	#[test]
1767	fn session_counts_by_root() {
1768		// session() counts connected sessions per auth root, independent of any
1769		// broadcast: open bumps `sessions_started`, drop bumps `sessions_ended`.
1770		let stats = test_stats();
1771		let ext = stats.tier(Tier::default());
1772
1773		let snap = |root: &str| {
1774			session_snapshot(&stats, &Tier::default(), root).map(|p| (p.sessions_started, p.sessions_ended))
1775		};
1776
1777		let a1 = ext.session("acme");
1778		let a2 = ext.session("acme");
1779		let b1 = ext.session("globex");
1780		assert_eq!(snap("acme"), Some((2, 0)), "two sessions under one root");
1781		assert_eq!(snap("globex"), Some((1, 0)), "a distinct root is counted separately");
1782
1783		drop(a1);
1784		assert_eq!(snap("acme"), Some((2, 1)));
1785		drop(a2);
1786		drop(b1);
1787		assert_eq!(snap("acme"), Some((2, 2)));
1788		assert_eq!(snap("globex"), Some((1, 1)));
1789	}
1790
1791	#[test]
1792	fn traffic_parses_with_missing_and_unknown_fields() {
1793		// Wire forward/backward compat: a frame entry from an older publisher
1794		// (missing fields) or a newer one (extra fields) must still parse.
1795		let old: Traffic = serde_json::from_str(r#"{"announced":1,"bytes":5}"#).expect("older shape parses");
1796		assert_eq!(old.announces_started, 1);
1797		assert_eq!(old.bytes, 5);
1798		assert_eq!(old.announced_bytes, 0, "missing fields default to zero");
1799
1800		let new: Traffic = serde_json::from_str(r#"{"announces_started":1,"announces_ended":1,"future_counter":9}"#)
1801			.expect("newer shape parses");
1802		assert!(new.is_idle());
1803	}
1804
1805	#[test]
1806	fn snapshot_reads_ended_before_started() {
1807		// Reading ended counters before their started counterparts is the
1808		// guarantee that a readout never shows ended > started under concurrent
1809		// bumps. This unit-test pins the ordering at the source level so a
1810		// future refactor that re-orders the loads trips the test.
1811		let src = include_str!("stats.rs");
1812		// Find the body of `impl Counters { fn snapshot(...) ... }` and
1813		// check the line order.
1814		let body_start = src.find("fn snapshot(&self) -> Traffic").expect("snapshot fn present");
1815		let body = &src[body_start..];
1816		let ended_pos = body.find("self.announces_ended.load").expect("announces_ended load");
1817		let started_pos = body
1818			.find("self.announces_started.load")
1819			.expect("announces_started load");
1820		assert!(
1821			ended_pos < started_pos,
1822			"announces_ended must be loaded before announces_started; reversing breaks the started>=ended invariant",
1823		);
1824		let subs_ended_pos = body
1825			.find("self.subscriptions_ended.load")
1826			.expect("subscriptions_ended load");
1827		let subs_pos = body
1828			.find("self.subscriptions_started.load")
1829			.expect("subscriptions_started load");
1830		assert!(
1831			subs_ended_pos < subs_pos,
1832			"subscriptions_ended must be loaded before subscriptions_started",
1833		);
1834		let bcast_ended_pos = body.find("self.broadcasts_ended.load").expect("broadcasts_ended load");
1835		let bcast_pos = body
1836			.find("self.broadcasts_started.load")
1837			.expect("broadcasts_started load");
1838		assert!(
1839			bcast_ended_pos < bcast_pos,
1840			"broadcasts_ended must be loaded before broadcasts_started",
1841		);
1842	}
1843
1844	#[test]
1845	fn context_presence_closes_on_last_clone() {
1846		// The reshaped Session context bumps `sessions_started` once at creation and
1847		// `sessions_ended` only when the last clone drops.
1848		let stats = test_stats();
1849		let snap = |root: &str| {
1850			session_snapshot(&stats, &Tier::default(), root).map(|p| (p.sessions_started, p.sessions_ended))
1851		};
1852
1853		let ctx = stats.tier(Tier::default()).session("acme");
1854		assert_eq!(snap("acme"), Some((1, 0)));
1855
1856		let clone = ctx.clone();
1857		// A clone shares the Arc: no extra `sessions_started`, and dropping one does nothing.
1858		assert_eq!(snap("acme"), Some((1, 0)));
1859		drop(ctx);
1860		assert_eq!(snap("acme"), Some((1, 0)));
1861		drop(clone);
1862		assert_eq!(snap("acme"), Some((1, 1)));
1863	}
1864
1865	#[test]
1866	fn set_tier_moves_presence() {
1867		let stats = test_stats();
1868		let gold = Tier::new("gold");
1869		let snap = |tier: &Tier| session_snapshot(&stats, tier, "acme").map(|p| (p.sessions_started, p.sessions_ended));
1870
1871		let ctx = stats.tier(Tier::default()).session("acme");
1872		ctx.set_tier(Tier::default());
1873		assert_eq!(snap(&Tier::default()), Some((1, 0)), "the same tier is a no-op");
1874
1875		ctx.set_tier(gold.clone());
1876		assert_eq!(snap(&Tier::default()), Some((1, 1)));
1877		assert_eq!(snap(&gold), Some((1, 0)));
1878
1879		drop(ctx);
1880		assert_eq!(snap(&gold), Some((1, 1)), "the session closes on its current tier");
1881	}
1882
1883	#[test]
1884	fn set_tier_moves_subsequent_traffic() {
1885		let stats = test_stats();
1886		let gold = Tier::new("gold");
1887		let ctx = stats.tier(Tier::default()).session("acme");
1888		let scope = ctx.egress("demo/bbb");
1889		let clone = scope.clone();
1890
1891		let before = scope.meter();
1892		let sub = scope.subscribe();
1893		let announce = scope.announce();
1894		before.bytes(10);
1895
1896		ctx.set_tier(gold.clone());
1897		// A meter handed out earlier keeps its tier; everything after moves.
1898		before.bytes(1);
1899		scope.meter().bytes(5);
1900		clone.meter().bytes(7);
1901		let sub2 = scope.subscribe();
1902		scope.fetch();
1903
1904		drop(sub);
1905		drop(sub2);
1906		drop(announce);
1907
1908		let old = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
1909		let new = tier_counters(&stats, "demo/bbb", &gold).publisher.snapshot();
1910		assert_eq!(old.bytes, 11);
1911		assert_eq!(new.bytes, 12);
1912		assert_eq!((old.fetches, new.fetches), (0, 1));
1913
1914		// Each guard closes on the tier it opened on, so neither tier leaks a gauge.
1915		assert_eq!((old.subscriptions_started, old.subscriptions_ended), (1, 1));
1916		assert_eq!((new.subscriptions_started, new.subscriptions_ended), (1, 1));
1917		assert_eq!((old.announces_started, old.announces_ended), (1, 1));
1918		// The viewer opened on the old tier and closes there, even though the
1919		// session's last subscription was opened under the new one.
1920		assert_eq!((old.broadcasts_started, old.broadcasts_ended), (1, 1));
1921		assert_eq!((new.broadcasts_started, new.broadcasts_ended), (0, 0));
1922		assert!(old.is_idle() && new.is_idle());
1923	}
1924
1925	#[test]
1926	fn meter_bumps_the_right_side() {
1927		// A payload meter records on its own side only.
1928		let stats = test_stats();
1929		let ctx = stats.tier(Tier::default()).session("root");
1930
1931		let egress = ctx.egress("demo/bbb").meter();
1932		egress.group();
1933		egress.frames(3);
1934		egress.bytes(100);
1935
1936		let ingress = ctx.ingress("demo/bbb").meter();
1937		ingress.group();
1938		ingress.frames(1);
1939		ingress.bytes(7);
1940
1941		let counters = tier_counters(&stats, "demo/bbb", &Tier::default());
1942		let pub_ = counters.publisher.snapshot();
1943		let sub = counters.subscriber.snapshot();
1944		assert_eq!((pub_.groups, pub_.frames, pub_.bytes), (1, 3, 100));
1945		assert_eq!((sub.groups, sub.frames, sub.bytes), (1, 1, 7));
1946	}
1947
1948	#[test]
1949	fn egress_subscribe_drives_subscriptions_and_viewers() {
1950		// An egress subscription bumps `subscriptions_started` and, being the context's first
1951		// for the broadcast, `broadcasts_started`. Dropping closes both.
1952		let stats = test_stats();
1953		let ctx = stats.tier(Tier::default()).session("root");
1954		let raw = || tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
1955
1956		let scope = ctx.egress("demo/bbb");
1957		let s1 = scope.subscribe();
1958		let s2 = scope.subscribe();
1959		let r = raw();
1960		assert_eq!(r.subscriptions_started, 2, "two track subs");
1961		assert_eq!(r.broadcasts_started, 1, "one context => one viewer");
1962		assert_eq!(r.broadcasts_ended, 0);
1963
1964		drop(s1);
1965		assert_eq!(raw().broadcasts_ended, 0, "context still has a sub open");
1966		drop(s2);
1967		let r = raw();
1968		assert_eq!(r.subscriptions_ended, 2);
1969		assert_eq!(r.broadcasts_ended, 1, "last sub closed => one broadcasts_ended");
1970	}
1971
1972	#[test]
1973	fn distinct_contexts_are_distinct_viewers() {
1974		// Two contexts (sessions) subscribing to the same broadcast are two viewers.
1975		let stats = test_stats();
1976		let raw = || tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
1977
1978		let v1 = stats.tier(Tier::default()).session("a").egress("demo/bbb").subscribe();
1979		assert_eq!(raw().broadcasts_started, 1);
1980		let v2 = stats.tier(Tier::default()).session("b").egress("demo/bbb").subscribe();
1981		assert_eq!(raw().broadcasts_started, 2, "two distinct contexts => two viewers");
1982
1983		drop(v1);
1984		assert_eq!(raw().active_broadcasts(), 1);
1985		drop(v2);
1986		assert_eq!(raw().broadcasts_ended, 2);
1987	}
1988
1989	#[test]
1990	fn ingress_subscription_has_no_viewer() {
1991		// An ingress (producer-lifetime) subscription bumps subscriptions but never
1992		// the viewer refcount, which is egress-only.
1993		let stats = test_stats();
1994		let ctx = stats.tier(Tier::default()).session("root");
1995		let guard = ctx.ingress("demo/bbb").subscribe();
1996		let sub = tier_counters(&stats, "demo/bbb", &Tier::default())
1997			.subscriber
1998			.snapshot();
1999		assert_eq!(sub.subscriptions_started, 1);
2000		assert_eq!(sub.broadcasts_started, 0, "ingress has no viewer refcount");
2001		drop(guard);
2002		assert_eq!(
2003			tier_counters(&stats, "demo/bbb", &Tier::default())
2004				.subscriber
2005				.snapshot()
2006				.subscriptions_ended,
2007			1
2008		);
2009	}
2010
2011	#[test]
2012	fn fetch_counts_separately_from_subscriptions() {
2013		// A fetch bumps `fetches`, not `subscriptions_started` or the viewer refcount.
2014		let stats = test_stats();
2015		let ctx = stats.tier(Tier::default()).session("root");
2016		let scope = ctx.egress("demo/bbb");
2017		scope.fetch();
2018		scope.fetch();
2019		let r = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
2020		assert_eq!(r.fetches, 2);
2021		assert_eq!(r.subscriptions_started, 0);
2022		assert_eq!(r.broadcasts_started, 0);
2023	}
2024
2025	#[test]
2026	fn announce_guard_records_bytes_on_open_and_close() {
2027		// The announce guard bumps `announces_started` + the path length on open, and
2028		// `announces_ended` + the path length again on drop.
2029		let stats = test_stats();
2030		let ctx = stats.tier(Tier::default()).session("root");
2031		let path_len = "demo/bbb".len() as u64;
2032
2033		let guard = ctx.egress("demo/bbb").announce();
2034		let r = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
2035		assert_eq!(r.announces_started, 1);
2036		assert_eq!(r.announces_ended, 0);
2037		assert_eq!(r.announced_bytes, path_len);
2038
2039		drop(guard);
2040		let r = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
2041		assert_eq!(r.announces_ended, 1);
2042		assert_eq!(
2043			r.announced_bytes,
2044			path_len * 2,
2045			"path length recorded on open and close"
2046		);
2047	}
2048
2049	#[test]
2050	fn disabled_context_is_noop() {
2051		// A default (disabled) context resolves empty scopes: every bump is dropped.
2052		let ctx = Session::default();
2053		let scope = ctx.egress("demo/bbb");
2054		scope.meter().bytes(100);
2055		let _guard = scope.announce();
2056		let _sub = scope.subscribe();
2057		scope.fetch();
2058		// No registry to inspect; the point is that none of this panics or allocates.
2059		assert!(ctx.inner.is_none());
2060	}
2061
2062	#[test]
2063	fn fetches_serde_roundtrips() {
2064		// The new `fetches` field is additive: an older frame omits it (defaults to
2065		// zero), and it survives a roundtrip.
2066		let old: Traffic = serde_json::from_str(r#"{"bytes":5}"#).expect("older shape parses");
2067		assert_eq!(old.fetches, 0);
2068
2069		let t = Traffic {
2070			fetches: 9,
2071			..Default::default()
2072		};
2073		let json = serde_json::to_string(&t).unwrap();
2074		let back: Traffic = serde_json::from_str(&json).unwrap();
2075		assert_eq!(back.fetches, 9);
2076	}
2077
2078	#[test]
2079	fn session_snapshot_reads_ended_before_started() {
2080		// Same `ended`-before-`started` invariant as `Counters::snapshot`, pinned
2081		// at the source level so a reordering refactor can't let
2082		// `sessions_ended > sessions_started` leak into a readout.
2083		let src = include_str!("stats.rs");
2084		let body_start = src
2085			.find("fn snapshot(&self) -> Presence")
2086			.expect("SessionCounters::snapshot fn present");
2087		let body = &src[body_start..];
2088		let ended_pos = body.find("self.sessions_ended.load").expect("sessions_ended load");
2089		let started_pos = body.find("self.sessions_started.load").expect("sessions_started load");
2090		assert!(
2091			ended_pos < started_pos,
2092			"sessions_ended must be loaded before sessions_started",
2093		);
2094	}
2095
2096	fn expected_traffic() -> Traffic {
2097		Traffic {
2098			announces_started: 2,
2099			announces_ended: 1,
2100			broadcasts_started: 4,
2101			broadcasts_ended: 3,
2102			subscriptions_started: 6,
2103			subscriptions_ended: 5,
2104			bytes: 9,
2105			..Default::default()
2106		}
2107	}
2108
2109	fn expected_presence() -> Presence {
2110		Presence {
2111			sessions_started: 3,
2112			sessions_ended: 1,
2113		}
2114	}
2115
2116	#[test]
2117	fn traffic_decodes_old_new_and_both_spellings() {
2118		// A new consumer reads an old relay, a new relay, and the dual-name
2119		// frame this serializer actually emits, all as the same Traffic.
2120		let expected = expected_traffic();
2121		let old = r#"{"announced":2,"announced_closed":1,"broadcasts":4,"broadcasts_closed":3,"subscriptions":6,"subscriptions_closed":5,"bytes":9}"#;
2122		let new = r#"{"announces_started":2,"announces_ended":1,"broadcasts_started":4,"broadcasts_ended":3,"subscriptions_started":6,"subscriptions_ended":5,"bytes":9}"#;
2123		assert_eq!(serde_json::from_str::<Traffic>(old).unwrap(), expected);
2124		assert_eq!(serde_json::from_str::<Traffic>(new).unwrap(), expected);
2125		let both = serde_json::to_string(&expected).unwrap();
2126		assert!(both.contains("\"announces_started\":2"), "{both}");
2127		assert!(both.contains("\"announced\":2"), "{both}");
2128		assert!(both.contains("\"announces_ended\":1"), "{both}");
2129		assert!(both.contains("\"announced_closed\":1"), "{both}");
2130		assert!(both.contains("\"broadcasts_started\":4"), "{both}");
2131		assert!(both.contains("\"broadcasts\":4"), "{both}");
2132		assert!(both.contains("\"subscriptions_started\":6"), "{both}");
2133		assert!(both.contains("\"subscriptions\":6"), "{both}");
2134		assert_eq!(serde_json::from_str::<Traffic>(&both).unwrap(), expected);
2135	}
2136
2137	#[test]
2138	fn presence_decodes_old_new_and_both_spellings() {
2139		let expected = expected_presence();
2140		assert_eq!(
2141			serde_json::from_str::<Presence>(r#"{"sessions":3,"sessions_closed":1}"#).unwrap(),
2142			expected
2143		);
2144		assert_eq!(
2145			serde_json::from_str::<Presence>(r#"{"sessions_started":3,"sessions_ended":1}"#).unwrap(),
2146			expected
2147		);
2148		let both = serde_json::to_string(&expected).unwrap();
2149		assert!(both.contains("\"sessions_started\":3"), "{both}");
2150		assert!(both.contains("\"sessions\":3"), "{both}");
2151		assert!(both.contains("\"sessions_ended\":1"), "{both}");
2152		assert!(both.contains("\"sessions_closed\":1"), "{both}");
2153		assert_eq!(serde_json::from_str::<Presence>(&both).unwrap(), expected);
2154	}
2155
2156	#[test]
2157	fn counter_edge_canonical_wins_when_spellings_disagree() {
2158		let traffic: Traffic =
2159			serde_json::from_str(r#"{"announces_started":9,"announced":1,"announces_ended":8,"announced_closed":0}"#)
2160				.unwrap();
2161		assert_eq!(traffic.announces_started, 9);
2162		assert_eq!(traffic.announces_ended, 8);
2163
2164		let presence: Presence =
2165			serde_json::from_str(r#"{"sessions_started":4,"sessions":0,"sessions_ended":2,"sessions_closed":9}"#)
2166				.unwrap();
2167		assert_eq!(presence.sessions_started, 4);
2168		assert_eq!(presence.sessions_ended, 2);
2169	}
2170
2171	#[test]
2172	fn counter_edge_refuses_null() {
2173		// A present null is malformed, not absent: it must not fall through to the legacy spelling or to zero.
2174		assert!(serde_json::from_str::<Traffic>(r#"{"announces_started":null,"announced":7}"#).is_err());
2175		assert!(serde_json::from_str::<Traffic>(r#"{"subscriptions_closed":null}"#).is_err());
2176		assert!(serde_json::from_str::<Presence>(r#"{"sessions_started":null}"#).is_err());
2177		assert!(serde_json::from_str::<Presence>(r#"{"sessions":null,"sessions_closed":1}"#).is_err());
2178	}
2179}