diff --git a/demo/web/src/stats.html b/demo/web/src/stats.html
index 132e6102a96..22f06bab7ae 100644
--- a/demo/web/src/stats.html
+++ b/demo/web/src/stats.html
@@ -116,8 +116,8 @@
Viewers no viewers
-
Sessions · by auth root
-
no sessions
+
Sessions · by stats label
+
no sessions
diff --git a/demo/web/src/stats.ts b/demo/web/src/stats.ts
index 422d3b4c1ab..c912cc70c54 100644
--- a/demo/web/src/stats.ts
+++ b/demo/web/src/stats.ts
@@ -11,7 +11,7 @@
* Per-node tracks we read:
* publisher.json egress (relay -> downstream viewers)
* subscriber.json ingress (upstream publishers -> relay)
- * sessions.json sessions by auth root
+ * sessions.json sessions by stats label
*
* Each frame is `{ "": Snapshot }`. Counters are cumulative;
* "active" = started - ended. The relay includes every entry it still holds
@@ -525,15 +525,15 @@ ui.run((effect) => {
};
});
- // Sessions connected under each auth root, counted regardless of data flow.
+ // Sessions connected under each stats label, counted regardless of data flow.
const sessionRows = Object.keys(stats.sessions)
.sort()
- .map((root) => {
- const s = stats.sessions[root] ?? {};
+ .map((label) => {
+ const s = stats.sessions[label] ?? {};
return {
- key: root,
+ key: label,
cells: [
- root || "(none)",
+ label || "(none)",
String(active(sessionsStarted(s), sessionsEnded(s))),
String(sessionsStarted(s)),
],
@@ -550,7 +550,7 @@ ui.run((effect) => {
["broadcast", "viewers", "tracks", "egress", "frames", "groups", "datagrams", "fetches", "announce"],
egressRows(stats.egress),
);
- renderTable($("node-session-roots"), ["auth root", "connected", "total"], sessionRows);
+ renderTable($("node-session-labels"), ["label", "connected", "total"], sessionRows);
const sessions = countSessions(stats.sessions);
$("node-sessions").textContent = `${sessions} session${sessions === 1 ? "" : "s"}`;
diff --git a/doc/bin/inspect.md b/doc/bin/inspect.md
index f46c49ecc85..7acd57a099c 100644
--- a/doc/bin/inspect.md
+++ b/doc/bin/inspect.md
@@ -76,8 +76,8 @@ curl http://localhost:4443/fetch/.stats/node/local/host/publisher.json | jq
The node name (`local/host` here) is `stats.node`. Each fetch returns the
newest snapshot of cumulative counters. `totals.json` sums each tier's traffic
and sessions, `publisher.json` is egress per broadcast path,
-`subscriber.json` is ingress, and `sessions.json` counts sessions per auth
-root. A subscriber may also ask for `/traffic.json`, one broadcast
+`subscriber.json` is ingress, and `sessions.json` counts sessions per stats
+label. A subscriber may also ask for `/traffic.json`, one broadcast
prefix rolled up with each child, produced only while held. Fetch twice and divide by the interval for a
rate. The `.json.z` twins carry compressed patches, which these tools print as
raw bytes. [Stats](/concept/stats) describes every field.
diff --git a/doc/bin/relay/auth.md b/doc/bin/relay/auth.md
index 9ec90779a2e..1b1c48e0928 100644
--- a/doc/bin/relay/auth.md
+++ b/doc/bin/relay/auth.md
@@ -28,7 +28,7 @@ token, the declared role, and the verified client certificate. Nothing is
parsed on the server's behalf: the `jwt` query parameter is a convention of
`moq auth serve`, not of the relay. The grant answers with `publish` and
`subscribe` pattern unions and optionally a `root` alias, read-only `mounts`,
-`expires`, a `revalidate` cadence, a stats `tier`, and `peer` / `upstream` to
+`expires`, a `revalidate` cadence, a stats `tier` and `label`, and `peer` / `upstream` to
mark another relay and an [upstream link](/bin/relay/cluster#upstream-links).
The fields are documented on `moq_auth::Request` and `moq_auth::Grant`
([Rust](/lib/rs/moq-auth), [TypeScript](/lib/js/auth)).
@@ -52,8 +52,8 @@ flowing. A wider grant brings those paths back within the admitted root and
SETUP role. A one-shot HTTP `/fetch` ends on a narrower grant instead. A
changed `root`, `mounts`, `peer`, or `upstream`, or a 401 or 403, ends that
credential's grant, which closes the session unless an
-[in-band](#in-band-renewal) credential still holds it. A changed `tier` keeps
-the session and moves its stats from then on. Any other failure retries with backoff and the session lives
+[in-band](#in-band-renewal) credential still holds it. A changed `tier` or
+`label` keeps the session and moves its later stats. Any other failure retries with backoff and the session lives
until `expires`, so an outage always has the bound the server chose. A grant
with `revalidate` must set `expires` for that reason. A session that
reaches `expires` closes as `Expired` rather than `Unauthorized`, which also
diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md
index 31579b68835..70d96a50846 100644
--- a/doc/bin/relay/config.md
+++ b/doc/bin/relay/config.md
@@ -316,7 +316,7 @@ relay dials and LAN peers it admits), which is what makes billing per customer o
Each run, and each group returning after its linger, announces under a fresh
[epoch](/concept/moq-lite#publisher-epochs), so a restart is a new broadcast at
the same path. Each group's totals count everything since its epoch began, so
-billing reads those; per-path traffic and per-root sessions and HTTP requests are for
+billing reads those; per-path traffic and per-label sessions and HTTP requests are for
dashboards. Session counters report how close sessions come to the
per-session limits, past which one is closed with `TOO_MANY_REQUESTS`.
[Stats](/concept/stats) describes the paths, tracks, and encodings; read them
diff --git a/doc/concept/stats.md b/doc/concept/stats.md
index 33e4a1a1301..52a82d2e233 100644
--- a/doc/concept/stats.md
+++ b/doc/concept/stats.md
@@ -51,7 +51,7 @@ generate more stats.
- `` tells relays sharing a cluster apart. It may span several segments
(`sjc/1`), and is omitted along with its slash when unset: `/node`.
- `` is the first `depth` segments of each broadcast path (for traffic)
- or auth root (for sessions), so a consumer can scope an announce to one
+ or stats label (for sessions), so a consumer can scope an announce to one
tenant. A path shorter than `depth` groups under all of its segments.
- The literal `node` segment leaves room for sibling categories under the same
prefix, so a consumer skips any path without `node` where it expects one. A
@@ -89,8 +89,8 @@ comes in two encodings:
| `totals.json` | tier | [Totals](#totals) for the whole group |
| `[/]publisher.json` | broadcast path | [Traffic](#traffic) this node sent (egress) |
| `[/]subscriber.json` | broadcast path | [Traffic](#traffic) this node received (ingress) |
-| `[/]sessions.json` | auth root | [Sessions](#sessions) connected now |
-| `[/]presence.json` | tier | [Sessions](#sessions) under one auth root |
+| `[/]sessions.json` | stats label | [Sessions](#sessions) connected now |
+| `[/]presence.json` | tier | [Sessions](#sessions) under one stats label |
| `[/]traffic.json` | tier | [Prefix](#prefix) traffic under one broadcast prefix |
The default tier's per-tier tracks are unprefixed. A named tier prefixes each
@@ -104,13 +104,13 @@ them earlier: any name of the shape
`[/]{publisher,subscriber,sessions}.json[.z]` is accepted and held open
with `{}` until the tier records.
-A presence track exists only while subscribed. Ask for `/presence.json`
-for any auth root in the group (`presence.json` for the empty root). The relay
-answers with the root's current sessions and counts from there, holding a root
+A presence track exists only while subscribed. Ask for `/presence.json`
+for any stats label in the group (`presence.json` for the empty label). The relay
+answers with the label's current sessions and counts from there, holding a label
with no sessions open at `{}`, and stops producing it once the last subscriber
leaves. A prefix track works the same way for any broadcast prefix in the
group: ask for `/traffic.json` (`traffic.json` for the empty prefix). A
-root or prefix outside the group, or any other name, is refused.
+label or prefix outside the group, or any other name, is refused.
## Frames
@@ -136,7 +136,7 @@ under the limit, keeps updating.
Each tier that recorded anything in the group's epoch, with its egress
(`publisher`) and ingress (`subscriber`) [Traffic](#traffic) and its
-[Sessions](#sessions), summed over every broadcast and auth root in the group.
+[Sessions](#sessions), summed over every broadcast and stats label in the group.
Unlike the per-path tracks, an entry that ends stays counted, so the next
frame always carries everything since the epoch began: a reader that misses
frames loses nothing while the group stays announced. Billing reads this
@@ -241,6 +241,7 @@ should prefer the canonical name and fall back to the legacy one.
"acme": {
"requests": 3, "sessions_started": 12, "sessions_ended": 10,
"sessions": 12, "sessions_closed": 10,
+ "sent_bytes": 1048576, "received_bytes": 524288,
"sessions_refused": { "refused": 0, "unavailable": 0, "request": 0, "forbidden": 0, "lan": 0 },
"sessions_failed": { "idle_timeout": 1, "transport": 0, "application": 0, "expired": 0 },
"announces_peak": 40, "subscriptions_peak": 900,
@@ -250,18 +251,26 @@ should prefer the canonical name and fall back to the legacy one.
```
`sessions_started` and `sessions_ended` count connects and disconnects, whether
-or not any data flows: under an auth root on the tier for `sessions.json`,
-under the root on each tier for `presence.json`, and under every root in the
+or not any data flows: under a stats label on the tier for `sessions.json`,
+under the label on each tier for `presence.json`, and under every label in the
group on the tier for `totals.json`. `sessions` and `sessions_closed` are their
legacy spellings. A session moved to a new tier ends on the old one and starts
-on the new.
+on the new. `sent_bytes` and `received_bytes` count the payload this node sent
+to and received from those sessions and HTTP requests, the same bytes the
+per-path tracks count. A changed label moves later presence and bytes; bytes
+before the change remain under the old label. Older readers ignore these fields
+and newer readers default missing fields to zero.
+
+The label is the grant's `label`, a path the auth server picks to attribute
+usage, independent of the root that scopes what the session may access. A grant
+without a `label` counts under the empty label, never under its root.
`wire_tx` and `wire_rx` count transport bytes sent and received, separately
from `Traffic.bytes`, which counts media payload. QUIC and WebTransport count
UDP bytes, including retransmissions and transport overhead. The transport
updates a connection's counters as it sends and receives, and a stats tick reads
-them without polling the session or activating its periodic sampler. Tier
-changes flush the old tier first; closing a session records its final delta.
+them without polling the session or activating its periodic sampler. A retag
+flushes the old tier and label first; closing a session records its final delta.
An embedder creates a `transport::Wire`, registers it with `stats::Handle::wire`
or `stats::Session::wire`, records its connection's cumulative totals on it, and
holds the returned guard. Dropping the guard records the final reading.
@@ -272,9 +281,9 @@ qmux counter source; unavailable counters are never estimated from payload.
Readers default missing wire fields to zero for older relays.
`sessions_refused` counts sessions turned away before admission, by reason.
-They never start a session. The relay's own refusals have no resolved root, so
-they count under the empty root on the default tier; an embedder can count one
-it refuses itself with `stats::Handle::refuse`, under the root and tier it
+They never start a session. The relay's own refusals have no resolved label, so
+they count under the empty label on the default tier; an embedder can count one
+it refuses itself with `stats::Handle::refuse`, under the label and tier it
resolved.
`sessions_failed` counts admitted sessions that ended abnormally, by kind: a
@@ -283,7 +292,7 @@ either side, a drain, or a shutdown is not a failure. A grant that expires
mid-session counts as `expired`; one revoked or narrowed out from under it
counts as `application`. A reader treats a missing object as zeros.
-`requests` counts admitted request/response exchanges under the token's root and
+`requests` counts admitted request/response exchanges under the token's label and
tier, including HTTP `/fetch` and `/announced`. They never start or end a session.
A fetch's delivered group bytes count against the broadcast path on that tier;
`/announced` delivers no media bytes. The auth decider can give HTTP its own tier
@@ -295,9 +304,9 @@ it was admitted; later traffic follows the new tier.
the relay, and subscriptions held on it, by any one session. Compare them with
the relay's [client or peer session limits](/bin/relay/config#session-and-peer):
a session that goes past one is closed with `TOO_MANY_REQUESTS`. On
-`sessions.json` a peak never goes down while the root has a session; on the
+`sessions.json` a peak never goes down while the label has a session; on the
totals and presence tracks it never goes down while the track lives. Summing
-nodes or roots takes the largest.
+nodes or labels takes the largest.
### Counters
diff --git a/doc/lib/js/auth.md b/doc/lib/js/auth.md
index 613970e60b7..d268f9d17cb 100644
--- a/doc/lib/js/auth.md
+++ b/doc/lib/js/auth.md
@@ -12,7 +12,8 @@ The TypeScript twin of [`moq-auth`](/lib/rs/moq-auth). `RequestSchema` and
what an auth server answers, so a Worker or a Node server implements the
contract with one import. It also generates keys, signs and verifies JWTs, and
checks a connection path against a token's claims exactly as `moq auth serve`
-does. Tokens are interchangeable with the Rust side. Grants and claims are
+does. A grant can label its session's stats independently of its authorization
+root. Tokens are interchangeable with the Rust side. Grants and claims are
[`Pattern`](https://www.npmjs.com/package/@moq/pattern) unions: `foo` is one
broadcast, `foo/**` is a subtree, `**` is everything. Parsed roles are `Access`
values with path patterns and an optional bitrate cap; authorization preserves
diff --git a/doc/lib/rs/moq-auth.md b/doc/lib/rs/moq-auth.md
index d245c7a30fb..143182e5f1d 100644
--- a/doc/lib/rs/moq-auth.md
+++ b/doc/lib/rs/moq-auth.md
@@ -13,7 +13,7 @@ Everything a party needs to ask for or answer an authorization on
answers the relay, in a service that mints tokens for clients, or in your own
accept loop that decides in process.
-- **Request and grant.** `Request` is the JSON a relay POSTs on each session event (`connect`, `revalidate`, `end`), carrying everything it knows about the session. `Grant` is the answer: publish and subscribe [`Pattern`](https://docs.rs/moq-pattern) unions, an expiry, a revalidation cadence, and whether the session is a cluster peer or an [upstream link](/bin/relay/cluster#upstream-links). `Grant::validate` checks the grant contract; the accept loop must enforce its caps or refuse it. Expiry is exact, with no allowance for clock skew.
+- **Request and grant.** `Request` is the JSON a relay POSTs on each session event (`connect`, `revalidate`, `end`), carrying everything it knows about the session. `Grant` is the answer: publish and subscribe [`Pattern`](https://docs.rs/moq-pattern) unions, an expiry, a revalidation cadence, optional stats tier and label, and whether the session is a cluster peer or an [upstream link](/bin/relay/cluster#upstream-links). `Grant::validate` checks the grant contract; the accept loop must enforce its caps or refuse it. Expiry is exact, with no allowance for clock skew.
- **Lease.** `lease::Producer` and `lease::Consumer` are the handle a session holds for its grant: read it, wait for a change, revoke it, and learn why it ended. Whoever runs the accept loop builds the producer, so an embedder can decide in process with no HTTP.
- **Client.** `Client` drives a lease against an auth server over `https://`, `unix://`, or loopback `http://`. It revalidates on cadence and retries through an outage until the grant expires, revokes on a 401, 403, or invalid grant, and reports `end` with the session's byte totals.
- **Server** (feature `serve`). `serve::Server` is the reference auth server behind `moq auth serve`: JWTs from the query or the moq-transport SETUP token, certificate grants, anonymous rules, tiers, and session caps. `Server::router` mounts it in your own axum service.
diff --git a/js/auth/src/contract.test.ts b/js/auth/src/contract.test.ts
index 143af98bb73..ac19cbbe018 100644
--- a/js/auth/src/contract.test.ts
+++ b/js/auth/src/contract.test.ts
@@ -109,6 +109,7 @@ test("a grant round trips and is validated", () => {
expires: 4102444800,
revalidate: 60,
tier: "websocket",
+ label: "project/key/123",
});
expect(grant.publish?.toJSON()).toEqual(["alice/**"]);
@@ -119,6 +120,7 @@ test("a grant round trips and is validated", () => {
expect(() => GrantSchema.parse({ publish: ["**"], expires: 4102444800, revalidate: 0.5 })).toThrow();
expect(() => GrantSchema.parse({ publish: ["**"], expires: 4102444800.5 })).toThrow();
expect(() => GrantSchema.parse({ publish: ["a/**/b/**"] })).toThrow();
+ expect(() => GrantSchema.parse({ publish: ["**"], label: "project/*" })).toThrow(/invalid path/);
});
test("an auth endpoint grant accepts a capped role", () => {
diff --git a/js/auth/src/contract.ts b/js/auth/src/contract.ts
index ad7fbbbd024..82d1a4ad96a 100644
--- a/js/auth/src/contract.ts
+++ b/js/auth/src/contract.ts
@@ -7,9 +7,24 @@
* @module
*/
+import { Pattern } from "@moq/pattern";
import * as z from "@zod/mini";
import { AccessSchema } from "./access.ts";
+const PathSchema = z.string().check(
+ z.refine(
+ (path) => {
+ try {
+ Pattern.literal(path);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ { message: "invalid path" },
+ ),
+);
+
/** How a session reached the relay; `http` is a one-shot request on the relay's web listener. */
export const TransportSchema = z.pipe(
z.string(),
@@ -153,6 +168,8 @@ export const GrantSchema = z
revalidate: z.optional(z.int().check(z.positive())),
/** An opaque label handed to stats, so traffic can be bucketed. */
tier: z.optional(z.string()),
+ /** The literal path this session's stats record under, independent of its root. Absent records under the empty label. */
+ label: z.optional(PathSchema),
/** The session is a cluster peer (another relay): what it announces entered the cluster elsewhere. */
peer: z.optional(z.boolean()),
/** The peer is upstream: the relay never offers it a route learned from another upstream. Requires `peer`. */
diff --git a/js/auth/src/interop.test.ts b/js/auth/src/interop.test.ts
index a1a00315595..a7a6e119819 100644
--- a/js/auth/src/interop.test.ts
+++ b/js/auth/src/interop.test.ts
@@ -261,7 +261,7 @@ describe("Rust-serialized contract", () => {
const RUST_INVALID_END =
'{"id":"00ff","event":"end","reason":"invalid","duration":1.5,"bytes":{"sent":10,"received":20},"node":"relay-1","transport":"websocket","remote":"203.0.113.9:4433","path":"/demo/room","query":"jwt=abc"}';
const RUST_GRANT =
- '{"publish":["alice/**"],"subscribe":["**"],"root":"pid/room","expires":4102444800,"revalidate":60,"tier":"websocket","peer":true,"upstream":true}';
+ '{"publish":["alice/**"],"subscribe":["**"],"root":"pid/room","expires":4102444800,"revalidate":60,"tier":"websocket","label":"project/key/123","peer":true,"upstream":true}';
test("parse a request a Rust relay sent", () => {
const request = RequestSchema.parse(JSON.parse(RUST_REQUEST));
@@ -297,6 +297,7 @@ describe("Rust-serialized contract", () => {
expires: 4102444800,
revalidate: 60,
tier: "websocket",
+ label: "project/key/123",
peer: true,
upstream: true,
});
diff --git a/quest/m2/README.md b/quest/m2/README.md
index 7425fc7d62e..0ba7f3d2b4c 100644
--- a/quest/m2/README.md
+++ b/quest/m2/README.md
@@ -84,7 +84,6 @@ ranked just below deterministic TS legs, which it requires.
- [Dart on iOS](/quest/m2/dart-ios.md) - prove the shipped iOS native asset actually loads on a device, which no CI can
- [Mobile completion](/quest/m2/mobile-completion.md) - verify the Swift and Kotlin bindings over Rust-owned capture before closing #700
- [WebGPU HDR](/quest/m2/webgpu-hdr.md) - HDR renditions play as HDR where the browser and display can show it, and tone-map to SDR elsewhere
-- [Grant stats label](/quest/m2/grant-label.md) - an auth grant's optional `label` names what its session's presence and live bytes count under in stats, apart from the path scope it may access
- [One port](/quest/m2/one-port/README.md) - one UDP port carries QUIC, SRT, and WebRTC media through an embedder hook, and one TCP port carries HTTP, RTMP, and RTMPS
- [QUIC caps](/quest/m2/rate-quic.md) - paced MAX_DATA credit in and a capped pacer out hold a QUIC session to its token's bitrate
- [WebSocket caps](/quest/m2/rate-websocket.md) - paced reads and writes over bounded socket buffers hold WebSocket to the same caps
diff --git a/quest/m2/grant-label.md b/quest/m2/grant-label.md
deleted file mode 100644
index f6c33b6ed48..00000000000
--- a/quest/m2/grant-label.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# [M] Grant stats label
-
-## Goal
-
-An auth grant can carry an optional `label` beside `tier`. A session admitted
-under it counts its presence, peaks, HTTP requests, and live sent and
-received bytes in stats under `(tier, label)`, while its path scope (what it
-may publish and subscribe to) stays the grant's `root`. Absent, the label
-defaults to the grant's root, so nothing changes for existing deciders. This
-gives live per-credential usage without changing what a session may access.
-
-## Plan
-
-Decided 2026-10-10 by maintainer priority, extended 2026-10-11:
-
-- **Why.** A multi-tenant operator needs each credential's usage while its
- sessions run. Stats key presence by `token.root` (`Cluster::scope` and
- `websocket.rs` call `stats.tier(..).session(&token.root)`), so two
- credentials scoped to the same path are indistinguishable, and bytes are
- keyed only by broadcast path and tier. Per-credential transport bytes reach
- an auth-server decider through `Lease::close`, but only once a session
- ends. `tier` already separates traffic classes; `label` separates who
- within one.
-- **Shape.** An optional `label` on `moq_auth::Grant`
- (`rs/moq-auth/src/grant.rs`) and its JS schema (`js/auth/src/contract.ts`),
- carried onto the relay's token and used wherever a session's or request's
- stats context is created.
-- **Bound.** It is the auth server's claim, trusted like `tier`. It must be a
- valid path so `--stats-depth` grouping and the per-root track still apply;
- refuse a grant whose label is not one, rather than fall back.
-- **Bytes, off the hot path.** Payload bytes stay on the per-`(path, tier)`
- rows as today. Each session also counts its sent and received bytes in its
- own counters, which no other session touches, and a snapshot or report
- folds them into the `(tier, label)` row, with a closed session's totals
- folded in when it drops. A write therefore adds no shared atomic. Reads
- rebuild a row and never consume deltas: the row's finalized total (closed
- sessions and retag checkpoints) plus each live session's counters minus the
- base its last retag recorded. A retag holds the session's lock while it
- loads the counters once, adds them less the base to the old row's
- finalized total, and records them as the new base, and a read takes the
- same lock per session. A concurrent write lands on one side of that single
- load, so it counts exactly once, under the old label or the new. Add a
- write-path benchmark to `rs/moq-net/benches/stats.rs` showing no
- regression against today's per-path bump, and sweep the fold over sessions
- and labels so its cost shows as a slope.
-- **Wire.** The sessions output gains sent and received byte fields per
- label. The change is additive: an older reader ignores them and a newer one
- defaults them to zero.
-- **HTTP.** A `/fetch` request context counts its bytes under the label too,
- beside its `requests`.
-- **Re-checked grants retag live.** A changed or removed label on a re-checked
- grant moves the session to the new label, the way a changed tier does
- today. Generalize `stats::Session::set_tier` into one `(tier, label)` retag
- rather than adding a second method, and call it from `Lease::ended`
- (`rs/moq-relay/src/auth.rs`). Bytes counted before the change stay under
- the old label; bytes after go to the new one, including writes through a
- meter handed out before the retag. A meter therefore carries the session's
- own counters, never a label: the retag folds the session's totals so far
- into the old `(tier, label)` row, and later writes accrue toward the new
- one. The per-path rows keep today's rule, where a meter stays on the tier
- its group started under.
-- **Defaults on both sides.** An older relay ignores the field (`Grant` does
- not deny unknown fields) and counts under the grant's root; access is
- unchanged, so that degrades to today's accounting, not to a wider scope.
- Say so in the docs.
-- Tests: `label` round-trips in Rust and JS; absent, stats key by the grant's
- root; present, an admitted session's presence and bytes land under the
- label while a publish or subscribe outside the grant's root is still
- refused; a re-checked grant with a new label moves later presence and bytes
- there and leaves earlier bytes under the old one, mirroring
- `set_tier_moves_presence` and `set_tier_moves_subsequent_traffic`
- (`rs/moq-net/src/stats.rs`), and a meter retained across the retag writes
- under the new label; an invalid label is refused.
-- Update `doc/concept/stats.md`, `doc/bin/relay/auth.md`,
- `doc/lib/rs/moq-auth.md`, and `doc/lib/js/auth.md`.
-
-Public API: a new optional `Grant::label` in `moq-auth` and `@moq/auth`, and
-`stats::Session::set_tier` becomes a `(tier, label)` retag. Wire: the auth
-HTTP grant body and the stats track's per-label byte fields, not MoQ.
-
-The per-root session outcome counters follow the same label.
-
-## Related
-
-- [Typed refusal reason](/quest/m1/refusal-reason.md) - a refusal body names
- a root too; decide there whether it may name a label
diff --git a/rs/moq-auth/src/error.rs b/rs/moq-auth/src/error.rs
index 3a6e154f357..d0b00e99184 100644
--- a/rs/moq-auth/src/error.rs
+++ b/rs/moq-auth/src/error.rs
@@ -117,6 +117,9 @@ pub enum Error {
#[error("grant has already expired")]
GrantExpired,
+ #[error("invalid stats label: {0}")]
+ InvalidLabel(moq_pattern::InvalidPattern),
+
#[error("the auth server refused the session")]
Refused,
diff --git a/rs/moq-auth/src/grant.rs b/rs/moq-auth/src/grant.rs
index 10587b98b54..fcdb71fd4f0 100644
--- a/rs/moq-auth/src/grant.rs
+++ b/rs/moq-auth/src/grant.rs
@@ -45,6 +45,9 @@ pub struct Grant {
/// An opaque label handed to stats, so traffic can be bucketed.
pub tier: Option,
+ /// The literal path this session's stats record under, independent of its root. Absent records under the empty label.
+ pub label: Option,
+
/// The session is a cluster peer (another relay): what it announces entered
/// the cluster elsewhere, not here.
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -91,6 +94,9 @@ impl Grant {
if self.revalidate.is_some_and(|cadence| cadence.is_zero()) {
return Err(crate::Error::ZeroRevalidate);
}
+ if let Some(label) = &self.label {
+ moq_pattern::Pattern::literal(label).map_err(crate::Error::InvalidLabel)?;
+ }
if self.expires.is_some_and(|expires| expires <= SystemTime::now()) {
return Err(crate::Error::GrantExpired);
}
@@ -116,6 +122,7 @@ mod tests {
expires: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(4_102_444_800)),
revalidate: Some(Duration::from_secs(60)),
tier: Some("websocket".into()),
+ label: Some("project/key/123".into()),
peer: true,
upstream: true,
};
@@ -140,12 +147,13 @@ mod tests {
expires: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(4_102_444_800)),
revalidate: Some(Duration::from_secs(60)),
tier: Some("websocket".into()),
+ label: Some("project/key/123".into()),
peer: true,
upstream: true,
};
assert_eq!(
serde_json::to_string(&grant).unwrap(),
- r#"{"publish":["alice/**"],"subscribe":["**"],"root":"pid/room","expires":4102444800,"revalidate":60,"tier":"websocket","peer":true,"upstream":true}"#
+ r#"{"publish":["alice/**"],"subscribe":["**"],"root":"pid/room","expires":4102444800,"revalidate":60,"tier":"websocket","label":"project/key/123","peer":true,"upstream":true}"#
);
}
@@ -198,6 +206,13 @@ mod tests {
grant.validate().unwrap();
}
+ #[test]
+ fn validate_refuses_an_invalid_stats_label() {
+ let mut grant = Grant::new(patterns(&["**"]), Access::default());
+ grant.label = Some("project/*".into());
+ assert!(matches!(grant.validate(), Err(crate::Error::InvalidLabel(_))));
+ }
+
#[cfg(feature = "tokio")]
#[tokio::test(start_paused = true)]
async fn deadline_is_the_exact_expiry() {
diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs
index 18cb95a3a5d..fb6658f5107 100644
--- a/rs/moq-cli/src/main.rs
+++ b/rs/moq-cli/src/main.rs
@@ -217,7 +217,7 @@ impl Serving {
anyhow::bail!("grant allows nothing this endpoint serves at {}", token.root);
}
- let stats = self.cluster.stats.tier(token.tier.clone()).session(&token.root);
+ let stats = self.cluster.stats.tier(token.tier.clone()).session(&token.label);
let lease = lease.with_stats(stats.clone());
let mut request = request.with_stats(stats);
if let Some(publish) = publish {
diff --git a/rs/moq-net/Cargo.toml b/rs/moq-net/Cargo.toml
index 817d74e89bd..cb2a5a3cf0e 100644
--- a/rs/moq-net/Cargo.toml
+++ b/rs/moq-net/Cargo.toml
@@ -149,7 +149,7 @@ required-features = ["async"]
[[bench]]
name = "stats"
harness = false
-required-features = ["async"]
+required-features = ["fuzz"]
[[bench]]
name = "session"
diff --git a/rs/moq-net/MIGRATE.md b/rs/moq-net/MIGRATE.md
index 17a15cdb876..0d6fc145fb5 100644
--- a/rs/moq-net/MIGRATE.md
+++ b/rs/moq-net/MIGRATE.md
@@ -4,6 +4,22 @@ How to update your code for each breaking change, newest first.
## Unreleased
+### Session stats are keyed by label, not auth root (#5731)
+
+`stats::Handle::session`, `stats::Handle::request`, and `stats::Handle::refuse` take the stats label where they took the auth root.
+Pass the empty path for a session without one.
+`Session::set_tier` is now `Session::retag`, which also moves the session to a new label.
+`SessionEntry::root` is renamed `SessionEntry::label`.
+
+```rust
+// Before
+let session = handle.session(&root);
+session.set_tier(tier);
+// After
+let session = handle.session(&label);
+session.retag(tier, &label);
+```
+
### Subscriptions carry group ranges (#5732)
`track::Subscription::start` and `end` are replaced by `ranges: Vec`, and `with_start` and `with_end` are gone.
diff --git a/rs/moq-net/benches/stats.rs b/rs/moq-net/benches/stats.rs
index 200b55ac2b4..422bfe5b5d7 100644
--- a/rs/moq-net/benches/stats.rs
+++ b/rs/moq-net/benches/stats.rs
@@ -4,9 +4,9 @@
//!
//! Run with `cargo bench -p moq-net --bench stats`.
-use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
+use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use futures::FutureExt;
-use moq_net::{announce, broadcast, origin, stats};
+use moq_net::{announce, broadcast, fuzz, origin, stats};
/// `(broadcasts, tiers)` shapes; every broadcast records under every tier.
const SHAPES: [(usize, usize); 4] = [(100, 1), (1_000, 1), (100, 10), (1_000, 10)];
@@ -87,5 +87,69 @@ fn request(c: &mut Criterion) {
group.finish();
}
-criterion_group!(benches, report, request);
+fn write(c: &mut Criterion) {
+ let registry = stats::Registry::new(stats::Config::new());
+ let tier = stats::Tier::default();
+ let path = fuzz::path_meter(®istry, &tier, "room/live");
+ let session = fuzz::session_meter(®istry, tier, "root", "room/live");
+ c.bench_function("stats/write/path-bytes", |b| b.iter(|| path.bytes(1)));
+ c.bench_function("stats/write/session-bytes", |b| b.iter(|| session.bytes(1)));
+}
+
+fn session_report(c: &mut Criterion) {
+ let mut group = c.benchmark_group("stats/session-report");
+ for labels in [1, 100, 1_000] {
+ for sessions in [1, 10] {
+ let registry = stats::Registry::new(stats::Config::new());
+ let handle = registry.tier(stats::Tier::default());
+ let contexts: Vec<_> = (0..labels)
+ .flat_map(|label| {
+ let handle = handle.clone();
+ (0..sessions).map(move |_| handle.session(format!("project/key/{label}")))
+ })
+ .collect();
+ let mut report = stats::Report::default();
+ group.bench_function(BenchmarkId::from_parameter(format!("{labels}x{sessions}")), |b| {
+ b.iter(|| registry.report(&mut report));
+ });
+ std::hint::black_box(contexts);
+ }
+ }
+ group.finish();
+}
+
+/// Move every session on one label to another and back, as a revalidation that relabels
+/// a whole project does. Per-session cost should stay flat as sessions and labels grow.
+fn retag(c: &mut Criterion) {
+ let mut group = c.benchmark_group("stats/retag");
+ for labels in [1, 100] {
+ for sessions in [1, 100, 10_000] {
+ let registry = stats::Registry::new(stats::Config::new());
+ let tier = stats::Tier::default();
+ let handle = registry.tier(tier.clone());
+ let mut contexts: Vec<_> = (0..labels)
+ .flat_map(|label| {
+ let handle = handle.clone();
+ (0..sessions).map(move |_| handle.session(format!("project/key/{label}")))
+ })
+ .collect();
+ let moving = contexts.split_off(contexts.len() - sessions);
+ group.throughput(Throughput::Elements(sessions as u64 * 2));
+ group.bench_function(BenchmarkId::from_parameter(format!("{labels}x{sessions}")), |b| {
+ b.iter(|| {
+ for session in moving.iter().rev() {
+ session.retag(tier.clone(), "project/moved");
+ }
+ for session in moving.iter().rev() {
+ session.retag(tier.clone(), format!("project/key/{}", labels - 1));
+ }
+ });
+ });
+ std::hint::black_box((contexts, moving));
+ }
+ }
+ group.finish();
+}
+
+criterion_group!(benches, report, request, write, session_report, retag);
criterion_main!(benches);
diff --git a/rs/moq-net/src/fuzz.rs b/rs/moq-net/src/fuzz.rs
index c7b1b8ed26c..be45262c4c6 100644
--- a/rs/moq-net/src/fuzz.rs
+++ b/rs/moq-net/src/fuzz.rs
@@ -290,6 +290,27 @@ pub fn bump_publisher_bytes(
registry.bump_publisher_bytes(path, tier, n);
}
+/// A payload-byte meter for the stats write-path benchmark.
+pub struct Meter(crate::stats::Meter);
+
+impl Meter {
+ /// Add publisher-side payload bytes.
+ pub fn bytes(&self, n: u64) {
+ self.0.bytes(n);
+ }
+}
+
+/// Build a session-local payload meter without exposing the model's private stats carriers.
+pub fn session_meter(registry: &crate::stats::Registry, tier: crate::stats::Tier, label: &str, path: &str) -> Meter {
+ let session = registry.tier(tier).session(label);
+ Meter(session.egress(path).meter())
+}
+
+/// Build the original per-path-only payload meter as the benchmark baseline.
+pub fn path_meter(registry: &crate::stats::Registry, tier: &crate::stats::Tier, path: &str) -> Meter {
+ Meter(registry.publisher_meter(path, tier))
+}
+
/// Encode `announced` as a fresh [`AnnounceWriter`] stream.
pub fn encode_announces(announced: &[Announced], compress: bool) -> Vec {
let mut writer = AnnounceWriter::new(compress);
diff --git a/rs/moq-net/src/stats.rs b/rs/moq-net/src/stats.rs
index 542f4d58053..d494804c29e 100644
--- a/rs/moq-net/src/stats.rs
+++ b/rs/moq-net/src/stats.rs
@@ -10,8 +10,10 @@
//! Traffic is bucketed by an arbitrary [`Tier`] label chosen by business logic
//! (billing class, region, ...) and, within a tier, by broadcast path and
//! [`Role`] (publisher = egress, subscriber = ingress). Connected sessions are
-//! tracked separately per (tier, auth root), counting presence regardless of
-//! whether any data flows.
+//! tracked separately per (tier, label), counting presence regardless of
+//! whether any data flows. The label is a stats key the auth decider picks,
+//! independent of what the session may access; the empty label holds sessions
+//! without one.
//!
//! # Where counting happens
//!
@@ -55,21 +57,25 @@
//! bumps `groups`, `frames`, and `bytes`; this counter breaks out how many of
//! those took the datagram path.
//! * `requests` ([`Presence`]): cumulative request/response admissions under the
-//! auth root and tier at admission. [`Handle::request`] meters their traffic
+//! label and tier at admission. [`Handle::request`] meters their traffic
//! without starting or ending a connected session.
+//! * `sent_bytes` / `received_bytes` ([`Presence`]): cumulative payload bytes
+//! this node sent to, or received from, the sessions and requests under a
+//! label. Each session counts its own bytes, so a write touches no shared
+//! row; a readout sums them.
//! * `sessions_started` / `sessions_ended` ([`Presence`]): cumulative count of
-//! sessions connected/disconnected under an auth root on this tier.
+//! sessions connected/disconnected under a label on this tier.
//! Driven by [`Handle::session`] (the [`Session`] context); a
-//! [`Session::set_tier`] ends the session on the old tier and starts it on
+//! [`Session::retag`] ends the session on the old label and starts it on
//! the new one.
//! * `wire_tx` / `wire_rx` ([`Presence`]): cumulative transport bytes, including
//! overhead and retransmissions. The transport updates its
//! [`crate::transport::Wire`] counters as it sends and receives, and
//! [`Registry::report`] and [`Registry::snapshot`] read each registered [`Wire`]
-//! without polling the session. A tier move flushes its old tier; dropping the guard flushes
+//! without polling the session. A retag flushes its old tier and label; dropping the guard flushes
//! its final nonnegative delta. Unsupported transports contribute zero.
//! * `announces_peak` / `subscriptions_peak` ([`Presence`]): the most
-//! announcements, or subscriptions, any one session under the auth root held
+//! announcements, or subscriptions, any one session under the label held
//! at once, to compare against its `crate::session::Limits`. A peak never
//! goes down; a rollup takes the largest rather than the sum.
//!
@@ -124,7 +130,7 @@ use std::{
collections::HashMap,
fmt,
sync::{
- Arc, Mutex, PoisonError, Weak,
+ Arc, Mutex, MutexGuard, PoisonError, Weak,
atomic::{AtomicU64, AtomicUsize, Ordering},
},
};
@@ -274,8 +280,8 @@ impl Content {
}
}
-/// Per-(tier, root) session gauge. One of these is shared (via `Arc`) by every
-/// [`Session`] guard for the same auth root on the same tier: `sessions_started`
+/// Per-(tier, label) session gauge. One of these is shared (via `Arc`) by every
+/// [`Session`] guard for the same label on the same tier: `sessions_started`
/// bumps on connect, `sessions_ended` on disconnect.
#[derive(Default, Debug)]
struct SessionCounters {
@@ -286,6 +292,9 @@ struct SessionCounters {
sessions_ended: AtomicU64,
announces_peak: AtomicU64,
subscriptions_peak: AtomicU64,
+ /// Payload bytes of the sessions recording here. One lock covers the folded totals
+ /// and the live sessions, so a readout never goes down when a session leaves.
+ bytes: Mutex,
wire_tx: AtomicU64,
wire_rx: AtomicU64,
}
@@ -305,6 +314,7 @@ impl SessionCounters {
let sessions_failed = self.sessions_failed.snapshot();
let sessions_ended = self.sessions_ended.load(Ordering::Acquire);
let sessions_started = self.sessions_started.load(Ordering::Relaxed);
+ let (sent_bytes, received_bytes) = self.bytes().read();
Presence {
sessions_refused: self.sessions_refused.snapshot(),
sessions_failed,
@@ -313,10 +323,90 @@ impl SessionCounters {
wire_rx: self.wire_rx.load(Ordering::Relaxed),
sessions_started,
sessions_ended,
+ sent_bytes,
+ received_bytes,
announces_peak: self.announces_peak.load(Ordering::Relaxed),
subscriptions_peak: self.subscriptions_peak.load(Ordering::Relaxed),
}
}
+
+ fn bytes(&self) -> MutexGuard<'_, SessionBytes> {
+ self.bytes.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+}
+
+/// The payload bytes of one `(tier, label)` row.
+#[derive(Default, Debug)]
+struct SessionBytes {
+ /// Bytes recorded here by sessions that have since ended or retagged away.
+ sent: u64,
+ received: u64,
+ /// The sessions recording here, keyed by identity so a retag leaves in constant time,
+ /// each with its counters as of when it arrived.
+ live: HashMap,
+}
+
+/// A session recording on a row, and its byte counters when it arrived there.
+#[derive(Debug)]
+struct Arrival {
+ traffic: Arc,
+ sent: u64,
+ received: u64,
+}
+
+impl SessionBytes {
+ /// The key a session's arrival lives under. The arrival holds the `Arc`, so no other
+ /// session can reuse the address while it is here.
+ fn key(traffic: &Arc) -> usize {
+ Arc::as_ptr(traffic) as usize
+ }
+
+ /// Count `traffic` here from `(sent, received)` on.
+ fn join(&mut self, traffic: Arc, (sent, received): (u64, u64)) {
+ self.live.insert(
+ Self::key(&traffic),
+ Arrival {
+ traffic,
+ sent,
+ received,
+ },
+ );
+ }
+
+ /// Stop counting `traffic` here, keeping what it recorded so far, and return the
+ /// counters at that cut: a concurrent write lands on one side of the single load.
+ fn leave(&mut self, traffic: &Arc) -> (u64, u64) {
+ let (sent, received) = traffic.load();
+ let arrival = self
+ .live
+ .remove(&Self::key(traffic))
+ .expect("a session is live on its current row");
+ self.sent += sent - arrival.sent;
+ self.received += received - arrival.received;
+ (sent, received)
+ }
+
+ /// The row's `(sent, received)` totals. Folds in each session that no handle can
+ /// write through anymore, since its count is final.
+ fn read(&mut self) -> (u64, u64) {
+ let Self { sent, received, live } = self;
+ let (mut live_sent, mut live_received) = (0, 0);
+ live.retain(|_, arrival| {
+ // Unique means the session and every meter it handed out have dropped.
+ let ended = Arc::get_mut(&mut arrival.traffic).is_some();
+ let (now_sent, now_received) = arrival.traffic.load();
+ let (delta_sent, delta_received) = (now_sent - arrival.sent, now_received - arrival.received);
+ if ended {
+ *sent += delta_sent;
+ *received += delta_received;
+ } else {
+ live_sent += delta_sent;
+ live_received += delta_received;
+ }
+ !ended
+ });
+ (*sent + live_sent, *received + live_received)
+ }
}
/// A cumulative traffic counter readout for one slice (a broadcast on a
@@ -544,7 +634,7 @@ impl Traffic {
}
}
-/// Request admissions and connected-session presence for an auth root on a tier, or their sum.
+/// Request admissions and connected-session presence for a label on a tier, or their sum.
/// The session counters are cumulative connects and disconnects. `sessions_started
/// - sessions_ended` is the current live session count. The peaks show how close
/// one session came to its `crate::session::Limits`.
@@ -566,6 +656,10 @@ pub struct Presence {
pub sessions_started: u64,
/// Cumulative sessions disconnected.
pub sessions_ended: u64,
+ /// Cumulative payload bytes sent by sessions under this label.
+ pub sent_bytes: u64,
+ /// Cumulative payload bytes received by sessions under this label.
+ pub received_bytes: u64,
/// The most broadcasts (moq-transport: namespaces) any one session has held announced
/// to us at once.
pub announces_peak: u64,
@@ -586,6 +680,8 @@ struct PresenceSer {
sessions: u64,
sessions_ended: u64,
sessions_closed: u64,
+ sent_bytes: u64,
+ received_bytes: u64,
announces_peak: u64,
subscriptions_peak: u64,
wire_tx: u64,
@@ -604,6 +700,8 @@ impl From for PresenceSer {
sessions: p.sessions_started,
sessions_ended: p.sessions_ended,
sessions_closed: p.sessions_ended,
+ sent_bytes: p.sent_bytes,
+ received_bytes: p.received_bytes,
announces_peak: p.announces_peak,
subscriptions_peak: p.subscriptions_peak,
}
@@ -620,6 +718,8 @@ struct PresenceDe {
sessions: Edge,
sessions_ended: Edge,
sessions_closed: Edge,
+ sent_bytes: u64,
+ received_bytes: u64,
announces_peak: u64,
subscriptions_peak: u64,
#[serde(default)]
@@ -638,6 +738,8 @@ impl From for Presence {
wire_rx: d.wire_rx,
sessions_started: counter_edge(d.sessions_started, d.sessions),
sessions_ended: counter_edge(d.sessions_ended, d.sessions_closed),
+ sent_bytes: d.sent_bytes,
+ received_bytes: d.received_bytes,
announces_peak: d.announces_peak,
subscriptions_peak: d.subscriptions_peak,
}
@@ -666,6 +768,8 @@ impl Presence {
self.wire_rx += other.wire_rx;
self.sessions_started += other.sessions_started;
self.sessions_ended += other.sessions_ended;
+ self.sent_bytes += other.sent_bytes;
+ self.received_bytes += other.received_bytes;
self.announces_peak = self.announces_peak.max(other.announces_peak);
self.subscriptions_peak = self.subscriptions_peak.max(other.subscriptions_peak);
}
@@ -805,14 +909,14 @@ impl Snapshot {
}
/// The per-broadcast detail [`Registry::report`] fills: one traffic entry per
-/// `(broadcast, tier)` and one session entry per `(tier, root)`. Entries are
+/// `(broadcast, tier)` and one session entry per `(tier, label)`. Entries are
/// unordered. Reuse one across drains to keep its capacity.
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct Report {
/// Per-`(broadcast, tier)` traffic, both roles per entry.
pub traffic: Vec,
- /// Per-`(tier, root)` connected-session presence.
+ /// Per-`(tier, label)` connected-session presence.
pub sessions: Vec,
}
@@ -833,18 +937,18 @@ pub struct TrafficEntry {
pub closed: bool,
}
-/// One `(tier, root)` row of a [`Report`].
+/// One `(tier, label)` row of a [`Report`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SessionEntry {
/// The tier the sessions recorded under.
pub tier: Tier,
- /// The auth root the sessions connected under.
- pub root: PathOwned,
+ /// The label the sessions record under, empty for sessions without one.
+ pub label: PathOwned,
/// Cumulative request admissions and connect/disconnect gauge.
pub presence: Presence,
- /// This is the root's final readout: its last session or request ended, so the
- /// registry pruned it, and a later context under the root starts from zero.
+ /// This is the label's final readout: its last session or request ended, so the
+ /// registry pruned it, and a later context under the label starts from zero.
pub closed: bool,
}
@@ -896,7 +1000,7 @@ struct Shared {
/// so a snapshot sees each entry either here or live, never both or neither.
retired: Lock,
entries: Lock>>,
- /// Connected-session gauges keyed by `(tier, auth root)`. Independent of any
+ /// Connected-session gauges keyed by `(tier, label)`. Independent of any
/// broadcast; surfaced on the per-tier session tracks and in the totals and
/// presence tracks. A tier's inner map is
/// created the first time a session records under it.
@@ -1001,6 +1105,17 @@ impl Registry {
entry.tier(tier).publisher.bytes.fetch_add(n, Ordering::Relaxed);
}
+ /// Resolve the pre-label payload meter used as the stats write benchmark's baseline.
+ #[cfg(any(test, feature = "fuzz"))]
+ #[cfg(feature = "async")]
+ pub(crate) fn publisher_meter(&self, path: impl AsPath, tier: &Tier) -> Meter {
+ Meter {
+ counters: self.entry(path).map(|entry| entry.tier(tier)),
+ traffic: None,
+ side: Side::Publisher,
+ }
+ }
+
fn entry(&self, path: impl AsPath) -> Option> {
// A disabled registry never allocates state.
let shared = self.shared.as_ref()?;
@@ -1021,12 +1136,12 @@ impl Registry {
)
}
- /// Get-or-create the session gauge for `root` on `tier`. `None` for a
- /// disabled registry. Unlike [`Self::entry`], roots are auth scopes (never
- /// under a stats prefix), so no cycle-breaking filter is needed.
- fn session_counters(&self, tier: &Tier, root: impl AsPath) -> Option> {
+ /// Get-or-create the session gauge for `label` on `tier`. `None` for a
+ /// disabled registry. Unlike [`Self::entry`], labels key sessions rather than
+ /// broadcasts, so no cycle-breaking filter is needed.
+ fn session_counters(&self, tier: &Tier, label: impl AsPath) -> Option> {
let shared = self.shared.as_ref()?;
- let owned = root.as_path().to_owned();
+ let owned = label.as_path().to_owned();
let mut sessions = shared.sessions.lock();
Some(
sessions
@@ -1066,9 +1181,9 @@ impl Registry {
}
{
let sessions = shared.sessions.lock();
- for (tier, roots) in sessions.iter() {
+ for (tier, labels) in sessions.iter() {
let totals = snap.sessions.entry(tier.clone()).or_default();
- for counters in roots.values() {
+ for counters in labels.values() {
totals.add(counters.snapshot());
}
}
@@ -1080,7 +1195,7 @@ impl Registry {
///
/// Clears `report`, keeping its capacity so a caller draining on an
/// interval reuses one report instead of allocating per drain, then fills
- /// every `(broadcast, tier)` traffic readout and every `(tier, root)`
+ /// every `(broadcast, tier)` traffic readout and every `(tier, label)`
/// session gauge. Entries no guard references anymore are dropped after
/// their final readout, which is marked `closed`, so a publisher draining on
/// an interval sees the closing readout exactly once. A pruned path that
@@ -1122,13 +1237,16 @@ impl Registry {
!free || !tiers.is_empty()
});
- shared.sessions.lock().retain(|tier, roots| {
- roots.retain(|root, counters| {
- let closed = Arc::strong_count(counters) == 1;
+ shared.sessions.lock().retain(|tier, labels| {
+ labels.retain(|label, counters| {
+ // Nothing can join a row only the map holds (that needs the lock held here),
+ // but a meter outliving its session still writes until its last clone drops.
+ let unheld = Arc::strong_count(counters) == 1;
let presence = counters.snapshot();
+ let closed = unheld && counters.bytes().live.is_empty();
report.sessions.push(SessionEntry {
tier: tier.clone(),
- root: root.clone(),
+ label: label.clone(),
presence,
closed,
});
@@ -1137,7 +1255,7 @@ impl Registry {
}
!closed
});
- !roots.is_empty()
+ !labels.is_empty()
});
}
@@ -1167,9 +1285,9 @@ pub struct Handle {
}
impl Handle {
- /// Count a session refused outside relay admission under its resolved root and tier.
- pub fn refuse(&self, root: impl AsPath, reason: Refusal) {
- if let Some(presence) = self.stats.session_counters(&self.tier, root) {
+ /// Count a session refused outside relay admission under its resolved label and tier.
+ pub fn refuse(&self, label: impl AsPath, reason: Refusal) {
+ if let Some(presence) = self.stats.session_counters(&self.tier, label) {
presence
.sessions_refused
.counter(reason)
@@ -1187,29 +1305,29 @@ impl Handle {
&self.tier
}
- /// Record a connected session authenticated under `root` on this tier. Hold
+ /// Record a connected session under `label` on this tier. Hold
/// the returned guard for the session's lifetime; dropping it bumps
/// `sessions_ended`. Counts presence regardless of any data flow, so a
/// session that merely connects is still billable. Surfaced on the session
- /// track for this tier, keyed by `root`, in its totals, and in `root`'s
+ /// track for this tier, keyed by `label`, in its totals, and in `label`'s
/// presence track.
- pub fn session(&self, root: impl AsPath) -> Session {
- self.context(root, Context::Session)
+ pub fn session(&self, label: impl AsPath) -> Session {
+ self.context(label, Context::Session)
}
- /// Count one admitted request under `root` and meter its traffic without session presence.
- pub fn request(&self, root: impl AsPath) -> Session {
- self.context(root, Context::Request)
+ /// Count one admitted request under `label` and meter its traffic without session presence.
+ pub fn request(&self, label: impl AsPath) -> Session {
+ self.context(label, Context::Request)
}
- /// Count an external connection's wire counters under `root` without counting an admission.
- pub fn wire(&self, root: impl AsPath, counters: crate::transport::Wire) -> Wire {
- self.context(root, Context::Wire).wire(counters)
+ /// Count an external connection's wire counters under `label` without counting an admission.
+ pub fn wire(&self, label: impl AsPath, counters: crate::transport::Wire) -> Wire {
+ self.context(label, Context::Wire).wire(counters)
}
- fn context(&self, root: impl AsPath, context: Context) -> Session {
- let root = root.as_path().to_owned();
- let presence = self.stats.session_counters(&self.tier, &root);
+ fn context(&self, label: impl AsPath, context: Context) -> Session {
+ let label = label.as_path().to_owned();
+ let presence = self.stats.session_counters(&self.tier, &label);
if let Some(presence) = &presence {
match context {
Context::Session => {
@@ -1221,16 +1339,21 @@ impl Handle {
Context::Wire => {}
}
}
+ let traffic = Arc::new(SessionTraffic::default());
+ if let Some(presence) = &presence {
+ presence.bytes().join(traffic.clone(), (0, 0));
+ }
Session {
inner: Some(Arc::new(SessionInner {
registry: self.stats.clone(),
- root,
connected: matches!(context, Context::Session),
current: Mutex::new(Current {
failure: None,
tier: self.tier.clone(),
+ label,
presence,
}),
+ traffic,
generation: AtomicU64::new(0),
viewers: Mutex::new(HashMap::new()),
held: Mutex::new(Vec::new()),
@@ -1336,15 +1459,15 @@ impl Side {
/// of a session (its publish and subscribe halves) so presence and viewer counts
/// are never double-attributed. It carries three things:
///
-/// * the tier + auth root, so any broadcast reached through a tagged origin handle
-/// resolves the right per-`(path, tier)` counters,
+/// * the tier and label, so any broadcast reached through a tagged origin handle
+/// resolves the right per-`(path, tier)` counters and its bytes count toward the label,
/// * the presence gauge: `sessions_started` bumps when the context is created and
/// `sessions_ended` when the last clone drops; a request instead bumps `requests`
/// once at admission and never touches session presence,
/// * the egress viewer refcount map (first/last active subscription per broadcast),
/// driving `broadcasts_started` / `broadcasts_ended`.
///
-/// [`Session::set_tier`] moves a live context to another tier: presence and traffic
+/// [`Session::retag`] moves a live context to another tier and label: presence and traffic
/// recorded afterwards land there, while what was already counted stays put and an
/// open subscription or announce closes on the tier it opened on.
///
@@ -1371,11 +1494,11 @@ struct SessionInner {
/// Requests meter traffic but never open or close connected-session presence.
connected: bool,
registry: Registry,
- /// The auth root the presence gauge is keyed by.
- root: PathOwned,
- /// The current tier and its presence gauge, swapped together by [`Session::set_tier`].
+ /// The current tier, label, and presence gauge, swapped together by [`Session::retag`].
current: Mutex,
- /// Bumped on every tier change, so a [`Scope`] notices without taking a lock.
+ /// This session's payload bytes, shared with the meters it hands out.
+ traffic: Arc,
+ /// Bumped on every tier or label change, so a [`Scope`] notices without taking a lock.
generation: AtomicU64,
/// Egress viewer refcount, keyed by absolute broadcast path: the first active
/// subscription this context opens for a broadcast bumps `broadcasts_started`, the last
@@ -1388,14 +1511,29 @@ struct SessionInner {
wire: Mutex>>,
}
-/// The tier a [`Session`] records under right now.
+/// The tier and label a [`Session`] records under right now.
struct Current {
failure: Option,
tier: Tier,
- /// The presence gauge for `(tier, root)`, or `None` for a disabled registry.
+ label: PathOwned,
+ /// The presence gauge for `(tier, label)`, or `None` for a disabled registry.
presence: Option>,
}
+/// One session's payload bytes. Its meters write here, never to a shared row, so a
+/// meter handed out before a retag still counts toward the session's current label.
+#[derive(Default, Debug)]
+struct SessionTraffic {
+ sent: AtomicU64,
+ received: AtomicU64,
+}
+
+impl SessionTraffic {
+ fn load(&self) -> (u64, u64) {
+ (self.sent.load(Ordering::Relaxed), self.received.load(Ordering::Relaxed))
+ }
+}
+
/// One broadcast's viewer refcount within a [`Session`].
struct Viewer {
subscriptions: u32,
@@ -1404,7 +1542,7 @@ struct Viewer {
}
impl Session {
- /// Count a connection's wire counters under this context's root, following its tier.
+ /// Count a connection's wire counters under this context's label, following its retags.
pub fn wire(&self, counters: crate::transport::Wire) -> Wire {
let Some(inner) = &self.inner else {
return Wire::default();
@@ -1438,11 +1576,12 @@ impl Session {
}
}
- /// Record later traffic and session presence under `tier`; a request stays counted where admitted.
- pub fn set_tier(&self, tier: Tier) {
+ /// Record later traffic and session presence under `(tier, label)`; a request stays counted where admitted.
+ pub fn retag(&self, tier: Tier, label: impl AsPath) {
let Some(inner) = &self.inner else { return };
+ let label = label.as_path().to_owned();
let mut current = inner.current.lock().unwrap_or_else(PoisonError::into_inner);
- if current.tier == tier {
+ if current.tier == tier && current.label == label {
return;
}
inner
@@ -1453,7 +1592,15 @@ impl Session {
let Some(source) = source.upgrade() else { return false };
source.sample_on(¤t, false)
});
- let presence = inner.registry.session_counters(&tier, &inner.root);
+ let presence = inner.registry.session_counters(&tier, &label);
+ // Bytes before the cut stay on the old row; later ones, through any meter, go to the new.
+ let cut = match ¤t.presence {
+ Some(old) => old.bytes().leave(&inner.traffic),
+ None => inner.traffic.load(),
+ };
+ if let Some(presence) = &presence {
+ presence.bytes().join(inner.traffic.clone(), cut);
+ }
if inner.connected
&& let Some(presence) = &presence
{
@@ -1470,13 +1617,14 @@ impl Session {
true
});
}
- if let Some(old) = std::mem::replace(&mut current.presence, presence)
+ if let Some(old) = std::mem::replace(&mut current.presence, presence.clone())
&& inner.connected
{
// Release pairs with the readout's Acquire load of `sessions_ended`.
old.sessions_ended.fetch_add(1, Ordering::Release);
}
current.tier = tier;
+ current.label = label;
inner.generation.fetch_add(1, Ordering::Release);
}
@@ -1491,7 +1639,7 @@ impl Session {
}
/// Record that this session holds `held` of what `cap` limits, raising that peak on its
- /// tier and root.
+ /// tier and label.
#[cfg_attr(not(feature = "async"), allow(dead_code))]
pub(crate) fn hold(&self, cap: Cap, held: u64) {
let Some(inner) = &self.inner else { return };
@@ -1598,7 +1746,7 @@ impl Drop for SessionInner {
// These are what a tagged `origin::{Consumer, Producer}` threads down through the
// derived handles (broadcast -> track -> group -> frame). A tagged origin creates a
// [`Scope`] per broadcast, which resolves the per-`(path, tier)` counters again
-// only after [`Session::set_tier`]; child handles carry a cheap [`Meter`] for the
+// only after [`Session::retag`]; child handles carry a cheap [`Meter`] for the
// payload bumps, fixed to the tier the group started under. All of them are no-ops when empty (a
// disabled registry, an excluded path, or an untagged caller), so an untagged
// handle pays nothing.
@@ -1609,6 +1757,7 @@ impl Drop for SessionInner {
#[derive(Clone, Default)]
pub(crate) struct Meter {
counters: Option>,
+ traffic: Option>,
side: Side,
}
@@ -1644,6 +1793,7 @@ impl Meter {
counters.frames.fetch_add(1, Ordering::Relaxed);
counters.bytes.fetch_add(n, Ordering::Relaxed);
}
+ self.session_bytes(n);
}
/// Whether this meter attributes anything, i.e. the broadcast is tracked and the
@@ -1668,6 +1818,17 @@ impl Meter {
if let Some(counters) = self.counters() {
counters.bytes.fetch_add(n, Ordering::Relaxed);
}
+ self.session_bytes(n);
+ }
+
+ fn session_bytes(&self, n: u64) {
+ if let Some(traffic) = &self.traffic {
+ match self.side {
+ Side::Publisher => &traffic.sent,
+ Side::Subscriber => &traffic.received,
+ }
+ .fetch_add(n, Ordering::Relaxed);
+ }
}
}
@@ -1727,8 +1888,15 @@ impl Scope {
/// A payload [`Meter`] for a group/frame derived from this scope.
pub(crate) fn meter(&self) -> Meter {
+ let counters = self.counters();
+ // An excluded path counts nowhere, including its session's label.
+ let traffic = counters
+ .as_ref()
+ .and(self.session.inner.as_ref())
+ .map(|inner| inner.traffic.clone());
Meter {
- counters: self.counters(),
+ counters,
+ traffic,
side: self.side,
}
}
@@ -1844,7 +2012,7 @@ mod tests {
}
#[test]
- fn wire_deltas_follow_root_and_tier_changes() {
+ fn wire_deltas_follow_label_and_tier_changes() {
let registry = test_stats();
let old = Tier::new("old");
let new = Tier::new("new");
@@ -1853,7 +2021,7 @@ mod tests {
let _wire = session.wire(bytes.clone());
let report = drain(®istry);
assert_eq!(report.sessions.len(), 1);
- assert_eq!(report.sessions[0].root.as_str(), "room");
+ assert_eq!(report.sessions[0].label.as_str(), "room");
assert_eq!(report.sessions[0].tier, old);
assert_eq!(
(report.sessions[0].presence.wire_tx, report.sessions[0].presence.wire_rx),
@@ -1861,12 +2029,16 @@ mod tests {
);
bytes.set_sent_bytes(15);
bytes.set_received_bytes(27);
- session.set_tier(new.clone());
+ session.retag(new.clone(), "hall");
bytes.set_sent_bytes(25);
bytes.set_received_bytes(50);
let report = drain(®istry);
- for (tier, expected) in [(old, (15, 27)), (new, (10, 23))] {
- let row = report.sessions.iter().find(|row| row.tier == tier).unwrap();
+ for (tier, label, expected) in [(old, "room", (15, 27)), (new, "hall", (10, 23))] {
+ let row = report
+ .sessions
+ .iter()
+ .find(|row| row.tier == tier && row.label.as_str() == label)
+ .unwrap();
assert_eq!((row.presence.wire_tx, row.presence.wire_rx), expected);
}
}
@@ -1957,7 +2129,7 @@ mod tests {
handle.refuse("root", Refusal::Forbidden);
let session = handle.session("root");
let clone = session.clone();
- session.set_tier(Tier::new("next"));
+ session.retag(Tier::new("next"), "root");
clone.fail(Failure::IdleTimeout);
session.fail(Failure::Application);
drop(clone);
@@ -2027,14 +2199,14 @@ mod tests {
.tier(tier)
}
- /// The [`Presence`] for `(tier, root)`, or `None` if absent.
- fn session_snapshot(stats: &Registry, tier: &Tier, root: &str) -> Option {
+ /// The [`Presence`] for `(tier, label)`, or `None` if absent.
+ fn session_snapshot(stats: &Registry, tier: &Tier, label: &str) -> Option {
stats
.shared()
.sessions
.lock()
.get(tier)
- .and_then(|roots| roots.get(&PathOwned::from(root.to_string())).map(|c| c.snapshot()))
+ .and_then(|labels| labels.get(&PathOwned::from(label.to_string())).map(|c| c.snapshot()))
}
fn test_stats() -> Registry {
@@ -2058,7 +2230,7 @@ mod tests {
assert_eq!(regional_counters.subscriber.bytes.load(Relaxed), 7);
}
- /// Each root's sessions row carries the most any one of its sessions held against each
+ /// Each label's sessions row carries the most any one of its sessions held against each
/// cap, which a slot released does not lower and a rollup does not sum.
#[test]
#[cfg(feature = "async")]
@@ -2105,7 +2277,7 @@ mod tests {
held.truncate(3);
let gold = Tier::new("gold");
- session.set_tier(gold.clone());
+ session.retag(gold.clone(), "acme");
let peak = |tier: &Tier| {
let (_, presence) = stats
@@ -2126,7 +2298,7 @@ mod tests {
let default = stats.tier(Tier::default());
let regional = stats.tier(Tier::new("region/sjc"));
- // Two default-tier sessions under one root, one regional; presence sums them.
+ // Two default-tier sessions under one label, one regional; presence sums them.
let s1 = default.session("acme");
let _s2 = default.session("acme");
let s3 = regional.session("peer");
@@ -2175,7 +2347,7 @@ mod tests {
let default_sessions = sessions(Tier::default());
assert_eq!(
default_sessions.sessions_started, 2,
- "two default-tier sessions under one root"
+ "two default-tier sessions under one label"
);
assert_eq!(default_sessions.sessions_ended, 0, "guards still held");
assert_eq!(sessions(Tier::new("region/sjc")).sessions_started, 1);
@@ -2283,8 +2455,8 @@ mod tests {
}
#[test]
- fn report_prunes_empty_session_roots() {
- // Once the last session under a root disconnects, the root leaves the
+ fn report_prunes_empty_session_labels() {
+ // Once the last session under a label disconnects, the label leaves the
// registry on the drain that reports its final gauge.
let stats = test_stats();
let session = stats.tier(Tier::default()).session("acme");
@@ -2293,7 +2465,7 @@ mod tests {
let row = report
.sessions
.iter()
- .find(|row| row.root.as_str() == "acme")
+ .find(|row| row.label.as_str() == "acme")
.expect("root present");
assert_eq!(row.presence.active(), 1);
assert!(!row.closed);
@@ -2303,7 +2475,7 @@ mod tests {
let row = report
.sessions
.iter()
- .find(|row| row.root.as_str() == "acme")
+ .find(|row| row.label.as_str() == "acme")
.expect("final gauge reported once");
assert_eq!(row.presence.active(), 0);
assert!(row.closed, "the final gauge is marked closed");
@@ -2347,7 +2519,7 @@ mod tests {
assert_eq!(
stats.shared().sessions.lock()[&tier].len(),
1,
- "retired roots are still pruned"
+ "retired labels are still pruned"
);
let retired = stats.shared().retired.lock();
assert_eq!(retired.traffic.len(), 1, "retain only a total per tier");
@@ -2427,21 +2599,21 @@ mod tests {
}
#[test]
- fn session_counts_by_root() {
- // session() counts connected sessions per auth root, independent of any
+ fn session_counts_by_label() {
+ // session() counts connected sessions per label, independent of any
// broadcast: open bumps `sessions_started`, drop bumps `sessions_ended`.
let stats = test_stats();
let ext = stats.tier(Tier::default());
- let snap = |root: &str| {
- session_snapshot(&stats, &Tier::default(), root).map(|p| (p.sessions_started, p.sessions_ended))
+ let snap = |label: &str| {
+ session_snapshot(&stats, &Tier::default(), label).map(|p| (p.sessions_started, p.sessions_ended))
};
let a1 = ext.session("acme");
let a2 = ext.session("acme");
let b1 = ext.session("globex");
- assert_eq!(snap("acme"), Some((2, 0)), "two sessions under one root");
- assert_eq!(snap("globex"), Some((1, 0)), "a distinct root is counted separately");
+ assert_eq!(snap("acme"), Some((2, 0)), "two sessions under one label");
+ assert_eq!(snap("globex"), Some((1, 0)), "a distinct label is counted separately");
drop(a1);
assert_eq!(snap("acme"), Some((2, 1)));
@@ -2509,8 +2681,8 @@ mod tests {
// The reshaped Session context bumps `sessions_started` once at creation and
// `sessions_ended` only when the last clone drops.
let stats = test_stats();
- let snap = |root: &str| {
- session_snapshot(&stats, &Tier::default(), root).map(|p| (p.sessions_started, p.sessions_ended))
+ let snap = |label: &str| {
+ session_snapshot(&stats, &Tier::default(), label).map(|p| (p.sessions_started, p.sessions_ended))
};
let ctx = stats.tier(Tier::default()).session("acme");
@@ -2526,16 +2698,16 @@ mod tests {
}
#[test]
- fn set_tier_moves_presence() {
+ fn retag_moves_presence() {
let stats = test_stats();
let gold = Tier::new("gold");
let snap = |tier: &Tier| session_snapshot(&stats, tier, "acme").map(|p| (p.sessions_started, p.sessions_ended));
let ctx = stats.tier(Tier::default()).session("acme");
- ctx.set_tier(Tier::default());
+ ctx.retag(Tier::default(), "acme");
assert_eq!(snap(&Tier::default()), Some((1, 0)), "the same tier is a no-op");
- ctx.set_tier(gold.clone());
+ ctx.retag(gold.clone(), "acme");
assert_eq!(snap(&Tier::default()), Some((1, 1)));
assert_eq!(snap(&gold), Some((1, 0)));
@@ -2544,7 +2716,7 @@ mod tests {
}
#[test]
- fn set_tier_moves_subsequent_traffic() {
+ fn retag_moves_subsequent_traffic() {
let stats = test_stats();
let gold = Tier::new("gold");
let ctx = stats.tier(Tier::default()).session("acme");
@@ -2556,7 +2728,7 @@ mod tests {
let announce = scope.announce();
before.bytes(10);
- ctx.set_tier(gold.clone());
+ ctx.retag(gold.clone(), "acme");
// A meter handed out earlier keeps its tier; everything after moves.
before.bytes(1);
scope.meter().bytes(5);
@@ -2570,6 +2742,10 @@ mod tests {
let old = tier_counters(&stats, "demo/bbb", &Tier::default()).publisher.snapshot();
let new = tier_counters(&stats, "demo/bbb", &gold).publisher.snapshot();
+ let old_presence = session_snapshot(&stats, &Tier::default(), "acme").unwrap();
+ let new_presence = session_snapshot(&stats, &gold, "acme").unwrap();
+ assert_eq!(old_presence.sent_bytes, 10);
+ assert_eq!(new_presence.sent_bytes, 13, "a retained meter follows the retag");
assert_eq!(old.bytes, 11);
assert_eq!(new.bytes, 12);
assert_eq!((old.fetches, new.fetches), (0, 1));
@@ -2585,6 +2761,72 @@ mod tests {
assert!(old.is_idle() && new.is_idle());
}
+ #[test]
+ fn retag_moves_presence_between_labels_on_one_tier() {
+ let stats = test_stats();
+ let tier = Tier::default();
+ let session = stats.tier(tier.clone()).session("project/root");
+ session.egress("project/live").meter().bytes(5);
+
+ session.retag(tier.clone(), "project/key/123");
+ session.egress("project/live").meter().bytes(7);
+
+ let root = session_snapshot(&stats, &tier, "project/root").unwrap();
+ let key = session_snapshot(&stats, &tier, "project/key/123").unwrap();
+ assert_eq!((root.sessions_started, root.sessions_ended, root.sent_bytes), (1, 1, 5));
+ assert_eq!((key.sessions_started, key.sessions_ended, key.sent_bytes), (1, 0, 7));
+ }
+
+ #[test]
+ fn retag_back_counts_bytes_once() {
+ let stats = test_stats();
+ let tier = Tier::default();
+ let session = stats.tier(tier.clone()).session("a");
+ let meter = session.ingress("a/live").meter();
+ meter.bytes(1);
+ session.retag(tier.clone(), "b");
+ meter.bytes(2);
+ session.retag(tier.clone(), "a");
+ meter.bytes(4);
+
+ let received = |label| session_snapshot(&stats, &tier, label).unwrap().received_bytes;
+ assert_eq!((received("a"), received("b")), (5, 2));
+ }
+
+ #[test]
+ fn session_bytes_outlive_the_session() {
+ let stats = test_stats();
+ let tier = Tier::default();
+ let session = stats.tier(tier.clone()).session("acme");
+ let meter = session.egress("acme/live").meter();
+ meter.bytes(3);
+ drop(session);
+
+ let mut report = Report::default();
+ stats.report(&mut report);
+ assert!(!report.sessions[0].closed, "a live meter keeps its label's row open");
+ meter.datagram(4);
+ drop(meter);
+
+ stats.report(&mut report);
+ assert_eq!(report.sessions[0].presence.sent_bytes, 7);
+ assert!(report.sessions[0].closed);
+ assert_eq!(
+ stats.snapshot().sessions[&tier].sent_bytes,
+ 7,
+ "retired totals keep the bytes"
+ );
+ }
+
+ #[test]
+ fn excluded_paths_skip_session_bytes() {
+ let stats = test_stats();
+ let tier = Tier::default();
+ let session = stats.tier(tier.clone()).session("acme");
+ session.egress(".stats/node").meter().bytes(9);
+ assert_eq!(session_snapshot(&stats, &tier, "acme").unwrap().sent_bytes, 0);
+ }
+
#[test]
fn meter_bumps_the_right_side() {
// A payload meter records on its own side only.
@@ -2677,7 +2919,7 @@ mod tests {
let request = stats.tier(Tier::new("old")).request("root");
let clone = request.clone();
request.egress("root/video").meter().bytes(7);
- request.set_tier(Tier::new("new"));
+ request.retag(Tier::new("new"), "root");
clone.egress("root/video").meter().bytes(11);
drop(request);
drop(clone);
diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs
index 71bfb668702..ddd5ee4b94a 100644
--- a/rs/moq-relay/src/auth.rs
+++ b/rs/moq-relay/src/auth.rs
@@ -423,6 +423,8 @@ pub struct Token {
pub publish: moq_auth::Access,
/// The tier this session's stats record under.
pub tier: Tier,
+ /// The path this session's stats record under, empty when the grant names none.
+ pub label: PathOwned,
/// Whether the session is a cluster peer, so its routes entered elsewhere.
pub peer: bool,
/// Whether the peer is upstream, so it is never offered another upstream's routes.
@@ -448,6 +450,7 @@ impl Token {
subscribe: grant.subscribe.clone(),
publish: grant.publish.clone(),
tier: crate::configured_tier(grant.tier.clone()),
+ label: Path::new(grant.label.as_deref().unwrap_or_default()).to_owned(),
peer: grant.peer,
upstream: grant.upstream,
}
@@ -507,10 +510,16 @@ impl Lease {
/// what the origin scopes by.
pub fn new(path: &str, consumer: lease::Consumer) -> Self {
let grant = consumer.grant();
+ Self::granted(path, &grant, consumer)
+ }
+
+ /// Hold `consumer` with its token built from `grant`, a snapshot of it. A later
+ /// update still reaches [`Self::ended`] as a change, which re-checks it.
+ fn granted(path: &str, grant: &Grant, consumer: lease::Consumer) -> Self {
Self {
refresh: None,
source: None,
- token: Token::new(path, &grant),
+ token: Token::new(path, grant),
expires: grant.deadline(),
consumer,
session: None,
@@ -611,6 +620,9 @@ impl Lease {
tokio::select! {
changed = self.consumer.changed() => match changed {
Ok(grant) => {
+ if let Err(reason) = still_valid(&grant) {
+ return reason;
+ }
let fresh = self.token.recheck(&grant);
if let Err(err) = fresh.uncapped() {
return err.to_string().into();
@@ -649,10 +661,11 @@ impl Lease {
None => {}
}
}
- if fresh.tier != self.token.tier {
- tracing::info!(from = %self.token.tier, to = %fresh.tier, "tier changed");
- self.stats.set_tier(fresh.tier.clone());
+ if fresh.tier != self.token.tier || fresh.label != self.token.label {
+ tracing::info!(tier = %fresh.tier, label = %fresh.label, "stats tier or label changed");
+ self.stats.retag(fresh.tier.clone(), &fresh.label);
self.token.tier = fresh.tier;
+ self.token.label = fresh.label;
}
self.expires = grant.deadline();
},
@@ -871,8 +884,10 @@ impl Auth {
/// Admit a session: the lease it holds, carrying the scope the origin applies.
pub async fn admit(&self, request: Request) -> Result {
- let consumer = self.decide(request.clone()).await?;
- let mut lease = Lease::new(&request.path, consumer);
+ // Build the token from the grant the admission checked: re-reading it could
+ // pick up an update that skipped the check.
+ let (consumer, grant) = self.decide(request.clone()).await?;
+ let mut lease = Lease::granted(&request.path, &grant, consumer);
lease.token.uncapped()?;
lease.source = Some(Source {
auth: self.clone(),
@@ -881,7 +896,7 @@ impl Auth {
Ok(lease)
}
- async fn decide(&self, request: Request) -> Result {
+ async fn decide(&self, request: Request) -> Result<(lease::Consumer, Grant), Error> {
let answer = self.submit(request, None)?;
let answered = tokio::time::timeout(ADMIT_TIMEOUT, answer)
.await
@@ -918,15 +933,25 @@ fn timed_out() -> Error {
/// Check a decider's answer against the contract every decider is held to: a
/// grant that admits nothing or asks for a re-check without a bound is a bug, not
-/// a refusal.
+/// a refusal. Returns the grant snapshot it checked.
fn answered_with(
answered: Result, oneshot::error::RecvError>,
-) -> Result {
+) -> Result<(lease::Consumer, Grant), Error> {
let consumer = answered.map_err(|_| Error::Unavailable("the admission went unanswered".into()))??;
let grant = consumer.grant();
grant.validate()?;
check_rates(&grant.publish, &grant.subscribe)?;
- Ok(consumer)
+ Ok((consumer, grant))
+}
+
+/// Hold a changed grant to the contract its first answer met: one that admits nothing
+/// narrowed the session away, and one already past its expiry ended it.
+fn still_valid(grant: &Grant) -> Result<(), lease::Reason> {
+ grant.validate().map_err(|err| match err {
+ moq_auth::Error::UselessGrant => lease::Reason::Narrowed,
+ moq_auth::Error::GrantExpired => lease::Reason::Expired,
+ err => err.to_string().into(),
+ })
}
/// Refuse caps before reducing a grant to the paths its origin can enforce.
@@ -1126,6 +1151,18 @@ mod tests {
assert!(lease.ended().await.to_string().contains("cannot enforce bitrate caps"));
}
+ #[tokio::test(start_paused = true)]
+ async fn an_invalid_label_at_revalidation_ends_the_lease() {
+ let grant = Grant::new(moq_net::Pattern::all(), moq_net::Pattern::all());
+ let (producer, consumer) = lease::Producer::new(grant.clone());
+ let mut lease = Lease::new("/room", consumer);
+ let mut wildcard = grant;
+ wildcard.label = Some("project/*".into());
+ producer.update(wildcard);
+ assert!(lease.ended().await.to_string().contains("invalid stats label"));
+ assert!(lease.token().label.is_empty(), "the label never applied");
+ }
+
#[test]
fn every_transport_has_an_auth_name() {
use moq_tokio::Transport as T;
@@ -1407,15 +1444,21 @@ mod tests {
let mut grant = Grant::new(patterns(&["alice/**"]), patterns(&["**"]));
grant.root = Some("pid/room".into());
grant.tier = Some("gold".into());
+ grant.label = Some("project/key/123".into());
let token = Token::new("/vanity/room", &grant);
assert_eq!(token.root, Path::new("pid/room").to_owned());
assert_eq!(token.publish, patterns(&["alice/**"]));
assert_eq!(token.subscribe, patterns(&["**"]));
assert_eq!(token.tier, Tier::new("gold"));
+ assert_eq!(token.label, Path::new("project/key/123").to_owned());
let patterns = patterns(&["*/chat", "alice", ""]);
let token = Token::new("/", &Grant::new(patterns.clone(), Patterns::new()));
assert_eq!(token.publish, patterns);
+ assert!(
+ token.label.is_empty(),
+ "an absent label is the empty label, not the root"
+ );
}
#[test]
diff --git a/rs/moq-relay/src/auth/refresh.rs b/rs/moq-relay/src/auth/refresh.rs
index 1150889fef9..32aced92b89 100644
--- a/rs/moq-relay/src/auth/refresh.rs
+++ b/rs/moq-relay/src/auth/refresh.rs
@@ -128,8 +128,11 @@ impl Refresh {
role: Option,
) -> Result {
let mut initial = Credential::new(lease.consumer.clone());
- // Admission and protocol setup can observe different live grant versions.
- if super::check_rates(&initial.grant.publish, &initial.grant.subscribe).is_err() {
+ // Admission and protocol setup can observe different live grant versions, so
+ // hold this one to the admission's checks too.
+ if super::still_valid(&initial.grant).is_err()
+ || super::check_rates(&initial.grant.publish, &initial.grant.subscribe).is_err()
+ {
return Err(moq_net::Error::Unauthorized);
}
initial.initial = true;
@@ -156,7 +159,8 @@ impl Refresh {
fn valid(&self, grant: &Grant) -> bool {
let fresh = self.admitted.recheck(grant);
- super::check_rates(&grant.publish, &grant.subscribe).is_ok()
+ super::still_valid(grant).is_ok()
+ && super::check_rates(&grant.publish, &grant.subscribe).is_ok()
&& fresh.root == self.admitted.root
&& fresh.mounts == self.admitted.mounts
&& fresh.peer == self.admitted.peer
@@ -278,7 +282,7 @@ impl Refresh {
// Withdrawing the stream cannot cancel the decider's work. Keep its slot
// until the decider answers so churn cannot bypass the bound.
let (result, settling) = match tokio::time::timeout_at(deadline, &mut answer).await {
- Ok(answered) => (super::answered_with(answered), None),
+ Ok(answered) => (super::answered_with(answered).map(|(consumer, _)| consumer), None),
Err(_) => {
let settling: Settling = Box::pin(async move {
let _ = answer.await;
@@ -378,10 +382,11 @@ impl Refresh {
}
}
Event::Changed(id, Change::Grant(grant)) if self.valid(&grant) => {
+ let fresh = self.admitted.recheck(&grant);
let credential = self.credentials.get_mut(&id).expect("observed credential");
credential.expires = grant.deadline();
if credential.initial {
- self.stats.set_tier(crate::configured_tier(grant.tier.clone()));
+ self.stats.retag(fresh.tier, &fresh.label);
}
credential.grant = grant;
if let Some(issued) = &credential.issued {
@@ -395,9 +400,12 @@ impl Refresh {
let reason = match change {
Change::Ended(reason) => reason,
Change::Withdrawn => lease::Reason::Dropped,
- Change::Grant(grant) => match super::check_rates(&grant.publish, &grant.subscribe) {
- Err(err) => err.to_string().into(),
- Ok(()) => lease::Reason::Narrowed,
+ Change::Grant(grant) => match super::still_valid(&grant) {
+ Err(reason) => reason,
+ Ok(()) => match super::check_rates(&grant.publish, &grant.subscribe) {
+ Err(err) => err.to_string().into(),
+ Ok(()) => lease::Reason::Narrowed,
+ },
},
};
if !withdrawn && let Some(issued) = credential.issued {
@@ -581,6 +589,17 @@ mod tests {
#[tokio::test(start_paused = true)]
async fn a_cap_added_before_protocol_setup_is_refused() {
+ refused_before_setup(|grant| grant.publish.rate = Some(moq_auth::Rate::from_bps(8000).unwrap())).await;
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn an_invalid_label_added_before_protocol_setup_is_refused() {
+ refused_before_setup(|grant| grant.label = Some("project/*".into())).await;
+ }
+
+ /// Admit a session, apply `change` to its grant before protocol setup, and check
+ /// that setup refuses it as a failure.
+ async fn refused_before_setup(change: fn(&mut moq_auth::Grant)) {
let (producer, consumer) = lease::Producer::new(grant("a/**", 3000));
let registry = moq_net::stats::Registry::new(Default::default());
let stats = registry.tier(moq_net::stats::Tier::default()).session("room");
@@ -611,9 +630,9 @@ mod tests {
)
.await
.unwrap();
- let mut capped = grant("a/**", 3000);
- capped.publish.rate = Some(moq_auth::Rate::from_bps(8000).unwrap());
- producer.update(capped);
+ let mut changed = grant("a/**", 3000);
+ change(&mut changed);
+ producer.update(changed);
let handle = request.auth();
assert!(matches!(
lease.preparing(handle.clone(), request.role()),
diff --git a/rs/moq-relay/src/cluster.rs b/rs/moq-relay/src/cluster.rs
index d056c1541ac..cd5949b448f 100644
--- a/rs/moq-relay/src/cluster.rs
+++ b/rs/moq-relay/src/cluster.rs
@@ -1333,7 +1333,7 @@ impl Cluster {
)));
}
- let stats = self.stats.tier(token.tier.clone()).session(&token.root);
+ let stats = self.stats.tier(token.tier.clone()).session(&token.label);
tracing::info!(transport = %request.transport, ?request.role, tier = %token.tier, root = %token.root,
publish = ?publisher.as_ref().map(origin::Producer::allowed),
subscribe = ?subscriber.as_ref().map(origin::Producer::allowed),
diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs
index 1ff205be25b..fdd8b9bd165 100644
--- a/rs/moq-relay/src/web.rs
+++ b/rs/moq-relay/src/web.rs
@@ -994,7 +994,7 @@ async fn admit_http(
state.cluster.refusals.record(crate::refusals::Refusal::Forbidden);
return Err(StatusCode::UNAUTHORIZED.into());
};
- let stats = state.cluster.stats.tier(token.tier.clone()).request(&token.root);
+ let stats = state.cluster.stats.tier(token.tier.clone()).request(&token.label);
let origin = origin.consume().with_stats(stats.clone());
Ok((lease.with_stats(stats), origin))
}
@@ -1354,7 +1354,11 @@ mod tests {
);
assert_eq!(traffic.subscriber.bytes, 0);
let presence = report.sessions.iter().find(|entry| entry.tier == tier).unwrap();
- assert_eq!(presence.root.as_str(), "room");
+ assert_eq!(
+ presence.label.as_str(),
+ "",
+ "an unlabeled request counts under the empty label"
+ );
assert_eq!(presence.presence.requests, 3);
assert_eq!(
(presence.presence.sessions_started, presence.presence.sessions_ended),
diff --git a/rs/moq-relay/tests/integration/auth_embedder.rs b/rs/moq-relay/tests/integration/auth_embedder.rs
index 61be067868c..94421e466cf 100644
--- a/rs/moq-relay/tests/integration/auth_embedder.rs
+++ b/rs/moq-relay/tests/integration/auth_embedder.rs
@@ -170,8 +170,8 @@ async fn gateway_admission_refuses_once_in_the_shared_stats_registry() {
let mut report = moq_net::stats::Report::default();
registry.report(&mut report);
assert_eq!(
- report.sessions[0].root.as_str(),
+ report.sessions[0].label.as_str(),
"",
- "refused admission cannot claim the dialed root"
+ "a refused admission counts under the empty label"
);
}
diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs
index 66c196d56b5..c622cbb0647 100644
--- a/rs/moq-relay/tests/integration/auth_lifetime.rs
+++ b/rs/moq-relay/tests/integration/auth_lifetime.rs
@@ -11,6 +11,7 @@
//! `Admissions`, and prove the lease it drives reaches the session the same way,
//! including an outage that keeps it until `expires`, on Tokio's paused clock.
+use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
@@ -460,12 +461,14 @@ async fn refusals_and_outages_refuse_at_connect() {
relay.abort();
}
-/// A re-check that moves the tier keeps the session and retags its stats live:
-/// both sessions' presence leaves the old tier for the new one, and media sent
-/// afterwards records under the new tier in both directions.
+/// A re-check that moves the tier and stats label keeps the session and retags its
+/// stats live: both sessions' presence leaves the old tier and label for the new
+/// ones, and media sent afterwards records there in both directions.
#[tokio::test]
async fn a_moved_tier_retags_the_live_session() {
- let script = Script::new(grant(Duration::from_secs(3600)));
+ let mut labeled = grant(Duration::from_secs(3600));
+ labeled.label = Some("project/key/1".into());
+ let script = Script::new(labeled);
let mut cluster = cluster::Cluster::new(cluster::Options::default()).expect("cluster init");
cluster.stats = stats::Registry::new(stats::Config::new());
let registry = cluster.stats.clone();
@@ -489,6 +492,22 @@ async fn a_moved_tier_retags_the_live_session() {
.find(|(t, r, _)| t == tier && *r == role)
.map_or(0, |(_, _, traffic)| traffic.bytes)
};
+ // Each label's (active sessions, sent bytes, received bytes), from one report.
+ let labels = || {
+ let mut report = stats::Report::default();
+ registry.report(&mut report);
+ report
+ .sessions
+ .into_iter()
+ .map(|entry| {
+ let presence = entry.presence;
+ (
+ (entry.tier, entry.label.to_string()),
+ (presence.active(), presence.sent_bytes, presence.received_bytes),
+ )
+ })
+ .collect::>()
+ };
// A publisher whose track stays open across the move, and a subscriber to it.
let pub_origin = moq_tokio::origin::spawn();
@@ -555,9 +574,15 @@ async fn a_moved_tier_retags_the_live_session() {
round_trip(b"before").await;
assert_eq!(active(&stats::Tier::default()), 2);
assert_eq!(active(&moved), 0);
+ assert_eq!(
+ labels()[&(stats::Tier::default(), "project/key/1".to_string())],
+ (2, 6, 6),
+ "sessions and bytes count under the grant's label"
+ );
let mut moved_grant = grant(Duration::from_secs(3600));
moved_grant.tier = Some("moved".into());
+ moved_grant.label = Some("project/key/2".into());
script.on_revalidate(Answer::Grant(moved_grant));
let deadline = tokio::time::Instant::now() + TIMEOUT;
@@ -585,6 +610,17 @@ async fn a_moved_tier_retags_the_live_session() {
);
assert_eq!(bytes(&moved, stats::Role::Subscriber), 5, "ingress from the publisher");
assert_eq!(bytes(&moved, stats::Role::Publisher), 5, "egress to the subscriber");
+ let labels = labels();
+ assert_eq!(
+ labels[&(stats::Tier::default(), "project/key/1".to_string())],
+ (0, 6, 6),
+ "earlier bytes stay under the old label"
+ );
+ assert_eq!(
+ labels[&(moved.clone(), "project/key/2".to_string())],
+ (2, 5, 5),
+ "later presence and bytes move to the new label"
+ );
assert!(
tokio::time::timeout(Duration::from_millis(200), pub_session.closed())
diff --git a/rs/moq-relay/tests/integration/session_revalidate.rs b/rs/moq-relay/tests/integration/session_revalidate.rs
index 40585ba7d65..e76cc54948e 100644
--- a/rs/moq-relay/tests/integration/session_revalidate.rs
+++ b/rs/moq-relay/tests/integration/session_revalidate.rs
@@ -21,6 +21,7 @@ use moq_tokio::moq_net;
const TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]
+#[allow(clippy::large_enum_variant)]
enum Answer {
Grant(Grant),
Status(u16),
diff --git a/rs/moq-stats/benches/producer_tick.rs b/rs/moq-stats/benches/producer_tick.rs
index 169e5955c33..137fa9889f0 100644
--- a/rs/moq-stats/benches/producer_tick.rs
+++ b/rs/moq-stats/benches/producer_tick.rs
@@ -10,7 +10,7 @@
//! delta. Time is the Criterion target `stats/tick`. The table is one warm-up
//! plus a few ticks, allocations included.
//!
-//! `stats/presence` sweeps the same tick over connected auth roots and the
+//! `stats/presence` sweeps the same tick over connected labels and the
//! presence tracks held for them.
//!
//! `stats/prefix` sweeps it over held paths, path depth, and held prefix
@@ -260,13 +260,13 @@ fn bench(c: &mut Criterion) {
group.finish();
}
-/// Connected auth roots, one session each.
-const ROOTS: [usize; 2] = [100, 10_000];
+/// Connected labels, one session each.
+const LABELS: [usize; 2] = [100, 10_000];
-/// Roots whose presence track a reader holds.
+/// Labels whose presence track a reader holds.
const HELD: [usize; 3] = [0, 100, 1_000];
-/// A relay with sessions under many roots, some of them held.
+/// A relay with sessions under many labels, some of them held.
struct Presence {
driver: Driver,
_registry: stats::Registry,
@@ -278,13 +278,13 @@ struct Presence {
}
impl Presence {
- fn build(roots: usize, held: usize) -> Self {
+ fn build(labels: usize, held: usize) -> Self {
let registry = stats::Registry::new(stats::Config::new());
let (origin, origin_driver) = origin::Producer::new(origin::Config::default());
- let names: Vec = (0..roots).map(|index| format!("room/{index:05}")).collect();
+ let names: Vec = (0..labels).map(|index| format!("room/{index:05}")).collect();
let sessions: Vec<_> = names
.iter()
- .map(|root| registry.tier(stats::Tier::default()).session(root.as_str()))
+ .map(|label| registry.tier(stats::Tier::default()).session(label.as_str()))
.collect();
// One set of wire counters per connection, independently of held presence tracks.
let wire = sessions
@@ -293,7 +293,11 @@ impl Presence {
.collect();
let mut driver = Driver::new(registry.clone(), origin.clone()).expect("stats broadcast");
driver.tick();
- let held = names.iter().take(held).map(|root| driver.hold_presence(root)).collect();
+ let held = names
+ .iter()
+ .take(held)
+ .map(|label| driver.hold_presence(label))
+ .collect();
Self {
driver,
_registry: registry,
@@ -306,24 +310,24 @@ impl Presence {
}
}
-/// What holding presence tracks costs a tick, swept over connected roots and
-/// held roots: each session row looks its root up once, and each held track
+/// What holding presence tracks costs a tick, swept over connected labels and
+/// held labels: each session row looks its label up once, and each held track
/// is summed and encoded once.
fn presence(c: &mut Criterion) {
- println!("roots held allocs/tick us/tick");
+ println!("labels held allocs/tick us/tick");
let mut group = c.benchmark_group("stats/presence");
group.sample_size(10);
group.warm_up_time(Duration::from_millis(200));
group.measurement_time(Duration::from_secs(1));
- for &roots in &ROOTS {
- for &held in HELD.iter().filter(|&&held| held <= roots) {
- let id = BenchmarkId::from_parameter(format!("{roots}r_{held}h"));
- group.throughput(Throughput::Elements(roots as u64));
+ for &labels in &LABELS {
+ for &held in HELD.iter().filter(|&&held| held <= labels) {
+ let id = BenchmarkId::from_parameter(format!("{labels}l_{held}h"));
+ group.throughput(Throughput::Elements(labels as u64));
let mut relay = None;
group.bench_function(id, |b| {
let relay = relay.get_or_insert_with(|| {
- let mut relay = Presence::build(roots, held);
+ let mut relay = Presence::build(labels, held);
black_box(relay.driver.tick());
ALLOCATIONS.store(0, Ordering::Relaxed);
COUNTING.store(true, Ordering::Relaxed);
@@ -334,7 +338,7 @@ fn presence(c: &mut Criterion) {
let micros = start.elapsed().as_secs_f64() * 1e6 / TABLE_TICKS as f64;
COUNTING.store(false, Ordering::Relaxed);
let allocs = ALLOCATIONS.load(Ordering::Relaxed) / TABLE_TICKS as usize;
- println!("{roots:>5} {held:>4} {allocs:>11} {micros:>8.1}");
+ println!("{labels:>5} {held:>4} {allocs:>11} {micros:>8.1}");
relay
});
b.iter_custom(|iters| {
diff --git a/rs/moq-stats/src/aggregate.rs b/rs/moq-stats/src/aggregate.rs
index 6f0b9d69cc7..a3bb8a6885a 100644
--- a/rs/moq-stats/src/aggregate.rs
+++ b/rs/moq-stats/src/aggregate.rs
@@ -172,10 +172,10 @@ impl Consumer {
}
}
- /// A merged reader over auth `root`'s presence track, holding it on every
+ /// A merged reader over `label`'s presence track, holding it on every
/// node broadcast in the group; see [`Self::totals`].
- pub fn presence(&self, root: impl AsPath) -> PresenceConsumer {
- let name = presence_track(root, self.config.compression);
+ pub fn presence(&self, label: impl AsPath) -> PresenceConsumer {
+ let name = presence_track(label, self.config.compression);
PresenceConsumer {
inner: Merged::new(self.origin.clone(), &self.config, name),
}
@@ -231,11 +231,11 @@ impl SessionsConsumer {
/// The next merged frame, or `None` once the announce stream ends.
pub async fn next(&mut self) -> Result> {
let frame = kio::wait(|waiter| self.inner.poll_next(waiter)).await?;
- Ok(frame.map(|frame| frame.into_iter().map(|(root, gauge)| (root, gauge.0)).collect()))
+ Ok(frame.map(|frame| frame.into_iter().map(|(label, gauge)| (label, gauge.0)).collect()))
}
}
-/// A merged reader over one root's presence track across every node in the
+/// A merged reader over one label's presence track across every node in the
/// group; see [`TotalsConsumer`].
pub struct PresenceConsumer {
inner: Merged,
@@ -393,14 +393,16 @@ impl Mergeable for Presence {
|| self.requests < prev.requests
|| self.sessions_started < prev.sessions_started
|| self.sessions_ended < prev.sessions_ended
+ || self.sent_bytes < prev.sent_bytes
+ || self.received_bytes < prev.received_bytes
|| self.announces_peak < prev.announces_peak
|| self.subscriptions_peak < prev.subscriptions_peak
}
}
-/// One root's sessions on a sessions track, merged as a gauge: a departed
+/// One label's sessions on a sessions track, merged as a gauge: a departed
/// node's contribution leaves at once rather than staying with its pairs
-/// closed, and a root leaving a node's frame is not a reset.
+/// closed, and a label leaving a node's frame is not a reset.
#[derive(Debug, Default, Clone, Copy, PartialEq, serde::Deserialize)]
#[serde(transparent)]
struct Gauge(Presence);
@@ -1026,10 +1028,10 @@ mod tests {
}
/// Record `bytes` of egress traffic on `path` in `producer`'s registry under
- /// `tier`/`root`, by driving a throwaway tagged broadcast. The broadcast lives
+ /// `tier`/`label`, by driving a throwaway tagged broadcast. The broadcast lives
/// on its own origin so it never lands on the stats origin.
- async fn feed(producer: &Producer, tier: Tier, root: &str, path: &str, bytes: usize) -> Feed {
- let ctx = producer.registry().tier(tier).session(root);
+ async fn feed(producer: &Producer, tier: Tier, label: &str, path: &str, bytes: usize) -> Feed {
+ let ctx = producer.registry().tier(tier).session(label);
let feed_origin = produce_origin();
let egress = feed_origin.consume().with_stats(ctx.clone());
@@ -1751,7 +1753,7 @@ mod tests {
#[tokio::test(start_paused = true)]
async fn merges_sessions_across_nodes() {
- // Session presence sums per auth root across nodes.
+ // Session presence sums per stats label across nodes.
let origin = produce_origin();
let node_a = node_producer(&origin, "a");
let node_b = node_producer(&origin, "b");
@@ -1769,7 +1771,7 @@ mod tests {
loop {
let frame = sessions.next().await.expect("read").expect("frame");
- // Each feed opens one session ("acme" root) plus the explicit ones,
+ // Each feed opens one session ("acme" label) plus the explicit ones,
// summed across both nodes.
if frame.get("acme").map(|p| p.active()) >= Some(4) {
break;
@@ -1796,7 +1798,7 @@ mod tests {
loop {
let frame = sessions.next().await.expect("read").expect("frame");
- // Each feed opens one session ("acme" root) plus the explicit ones,
+ // Each feed opens one session ("acme" label) plus the explicit ones,
// summed across both nodes.
if frame.get("acme").map(|p| p.active()) >= Some(4) {
break;
@@ -2069,6 +2071,21 @@ mod tests {
);
}
+ #[test]
+ fn byte_only_regression_begins_another_segment() {
+ let (mut merged, key) = hand_merged::();
+ let bytes = |sent, received| {
+ let mut presence = Presence::default();
+ presence.sent_bytes = sent;
+ presence.received_bytes = received;
+ presence
+ };
+ let node = merged.nodes.get_mut(&key).unwrap();
+ node.observe(BTreeMap::from([(String::new(), bytes(6, 4))]));
+ node.observe(BTreeMap::from([(String::new(), bytes(2, 1))]));
+ assert_eq!(merged.merged()[""], bytes(8, 5));
+ }
+
#[test]
fn a_resume_reopens_closed_pairs_without_going_down() {
let (mut merged, key) = hand_merged::();
@@ -2259,7 +2276,7 @@ mod tests {
#[tokio::test(start_paused = true)]
async fn presence_survives_join_leave_and_restart() {
- // One root held across nodes: a node joining adds its sessions, one
+ // One label held across nodes: a node joining adds its sessions, one
// leaving closes its sessions but keeps its count, and a restarted node
// is a new epoch that adds to it. The merged count never goes down.
let origin = produce_origin();
diff --git a/rs/moq-stats/src/consume.rs b/rs/moq-stats/src/consume.rs
index 275c5be0c1f..41a3289177d 100644
--- a/rs/moq-stats/src/consume.rs
+++ b/rs/moq-stats/src/consume.rs
@@ -38,7 +38,7 @@ impl Config {
/// Subscribe to the tracks you care about with [`Self::totals`],
/// [`Self::traffic`], [`Self::sessions`], [`Self::presence`], and
/// [`Self::prefix`]. A named tier's tracks are held open with an empty frame
-/// until the tier records, and a root's presence track and a prefix's track
+/// until the tier records, and a label's presence track and a prefix's track
/// are produced only while subscribed.
pub struct Consumer {
broadcast: broadcast::Consumer,
@@ -78,11 +78,11 @@ impl Consumer {
})
}
- /// Subscribe to the presence track for auth `root`, awaiting the
+ /// Subscribe to the presence track for `label`, awaiting the
/// subscription handshake. Fails with
- /// [`NotFound`](moq_net::Error::NotFound) for a root outside the group.
- pub async fn presence(&self, root: impl AsPath) -> Result {
- let name = presence_track(root, self.config.compression);
+ /// [`NotFound`](moq_net::Error::NotFound) for a label outside the group.
+ pub async fn presence(&self, label: impl AsPath) -> Result {
+ let name = presence_track(label, self.config.compression);
Ok(Presence {
inner: self.subscribe(&name).await?,
})
@@ -146,7 +146,7 @@ impl Totals {
}
}
-/// A typed reader over one root's presence track; see [`Traffic`].
+/// A typed reader over one label's presence track; see [`Traffic`].
pub struct Presence {
inner: moq_json::snapshot::Consumer,
}
@@ -223,7 +223,7 @@ mod tests {
}
/// A tagged egress feed into a producer's registry, holding the handles needed
- /// to write more traffic incrementally. Presence is recorded under `root`.
+ /// to write more traffic incrementally. Presence is recorded under `label`.
struct Feed {
track: track::Producer,
sub: track::Subscriber,
@@ -244,8 +244,8 @@ mod tests {
}
}
- async fn feed(producer: &Producer, tier: Tier, root: &str, path: &str) -> Feed {
- let ctx = producer.registry().tier(tier).session(root);
+ async fn feed(producer: &Producer, tier: Tier, label: &str, path: &str) -> Feed {
+ let ctx = producer.registry().tier(tier).session(label);
let feed_origin = produce_origin();
let egress = feed_origin.consume().with_stats(ctx.clone());
diff --git a/rs/moq-stats/src/lib.rs b/rs/moq-stats/src/lib.rs
index a73d8607309..448e8aac6a9 100644
--- a/rs/moq-stats/src/lib.rs
+++ b/rs/moq-stats/src/lib.rs
@@ -25,8 +25,8 @@
//! them apart by the announced route's epoch. Every broadcast carries a
//! `totals.json` track of each [`Tier`]'s [`Totals`] for the epoch, each tier
//! carries `publisher.json` and `subscriber.json` tracks of per-path
-//! [`Traffic`] and a `sessions.json` track of per-root [`Presence`], and a
-//! reader may request any auth root's `/presence.json` track and any
+//! [`Traffic`] and a `sessions.json` track of per-label [`Presence`], and a
+//! reader may request any stats label's `/presence.json` track and any
//! broadcast prefix's `/traffic.json` track of [`Prefix`] counters. Every
//! track has a `.z` sibling encoded with [`moq_json::snapshot`]; compute names
//! with [`totals_track`], [`traffic_track`], [`sessions_track`],
@@ -52,14 +52,14 @@ use moq_net::{AsPath, Path, PathOwned};
/// One frame off a traffic track: cumulative counters keyed by broadcast path.
pub type TrafficFrame = BTreeMap;
-/// One frame off a sessions track: connect/disconnect gauges keyed by auth root.
+/// One frame off a sessions track: connect/disconnect gauges keyed by stats label.
pub type SessionsFrame = BTreeMap;
/// One frame off the totals track: each tier's [`Totals`], keyed by tier label
/// (`""` for the default tier).
pub type TotalsFrame = BTreeMap;
-/// One frame off a presence track: one auth root's sessions, keyed by tier label
+/// One frame off a presence track: one stats label's sessions, keyed by tier label
/// (`""` for the default tier).
pub type PresenceFrame = BTreeMap;
@@ -78,7 +78,7 @@ pub struct Totals {
pub publisher: Traffic,
/// Ingress: what this node received.
pub subscriber: Traffic,
- /// Sessions connected under the group's auth roots.
+ /// Sessions connected under the group's stats labels.
pub sessions: Presence,
}
@@ -172,11 +172,11 @@ pub fn totals_track(compressed: bool) -> String {
name
}
-/// The presence track name for an auth root: `/presence.json`, or
-/// `presence.json` for the empty root, plus [`COMPRESSED_SUFFIX`] when
+/// The presence track name for a stats label: `/presence.json`, or
+/// `presence.json` for the empty label, plus [`COMPRESSED_SUFFIX`] when
/// `compressed`. Served only while requested.
-pub fn presence_track(root: impl AsPath, compressed: bool) -> String {
- keyed_track(root.as_path(), PRESENCE, compressed)
+pub fn presence_track(label: impl AsPath, compressed: bool) -> String {
+ keyed_track(label.as_path(), PRESENCE, compressed)
}
/// The prefix track name for a broadcast prefix: `/traffic.json`, or
@@ -198,7 +198,7 @@ fn keyed_track(key: Path, kind: &str, compressed: bool) -> String {
name
}
-/// The auth root a presence track name requests, and whether it is the
+/// The stats label a presence track name requests, and whether it is the
/// compressed flavor; `None` for any other name. The inverse of
/// [`presence_track`].
pub(crate) fn parse_presence_track(name: &str) -> Option<(PathOwned, bool)> {
@@ -368,19 +368,19 @@ mod tests {
#[test]
fn presence_track_names_round_trip() {
- for root in ["", "acme", "acme/live", "a.json", "x/presence.json", "publisher", "z"] {
+ for label in ["", "acme", "acme/live", "a.json", "x/presence.json", "publisher", "z"] {
for compressed in [false, true] {
- let name = presence_track(root, compressed);
+ let name = presence_track(label, compressed);
assert_eq!(
parse_presence_track(&name),
- Some((PathOwned::from(root), compressed)),
+ Some((PathOwned::from(label), compressed)),
"{name}"
);
}
}
- // Names no root produces, including unnormalized ones, which would give
- // one root two names.
+ // Names no label produces, including unnormalized ones, which would give
+ // one label two names.
for name in [
"publisher.json",
"acme/publisher.json",
diff --git a/rs/moq-stats/src/produce.rs b/rs/moq-stats/src/produce.rs
index 41d494e5e61..30bec6bc277 100644
--- a/rs/moq-stats/src/produce.rs
+++ b/rs/moq-stats/src/produce.rs
@@ -325,7 +325,7 @@ impl Drain {
}
}
for (i, entry) in self.report.sessions.iter().enumerate() {
- let key = group_key(entry.root.as_str(), self.task.depth);
+ let key = group_key(entry.label.as_str(), self.task.depth);
if let Some(group) = Self::group(&self.task, &mut self.groups, &mut self.refused, key) {
group.session_rows.push(i);
}
@@ -380,7 +380,7 @@ impl Drain {
group.flush(self.tick);
// Serve consumer requests for tracks no drain has created yet: a
- // tier's tracks appear lazily on its first traffic, and a root's
+ // tier's tracks appear lazily on its first traffic, and a label's
// presence track only while requested. See `serve_requests`.
group.serve_requests(&self.report, depth, self.tick);
}
@@ -852,7 +852,7 @@ impl TrackFamily {
/// One group stats broadcast and its change-detection state.
struct GroupPublisher {
- /// The group's key: the leading segments every member path and root shares.
+ /// The group's key: the leading segments every member path and label shares.
key: PathOwned,
broadcast: broadcast::Producer,
/// Holds the broadcast's request queue open, so a subscriber asking for a
@@ -870,7 +870,7 @@ struct GroupPublisher {
/// Track names per tier, built once so a drain never formats a name.
names: HashMap,
totals: TotalsTrack,
- /// Held presence tracks, keyed by auth root.
+ /// Held presence tracks, keyed by stats label.
presence: HashMap,
/// Held prefix tracks, keyed by broadcast prefix. A `String` key, so a
/// drain looks each row's ancestors up by `&str` without allocating.
@@ -973,7 +973,7 @@ struct TotalsTrack {
sums: Cumulative,
}
-/// One auth root's requested `presence.json` pair and its per-tier sums,
+/// One stats label's requested `presence.json` pair and its per-tier sums,
/// cumulative from when it was first held. Reclaimed once nobody reads it.
struct PresenceTrack {
/// The plain track name, for logs.
@@ -1235,7 +1235,7 @@ impl GroupPublisher {
totals
.sums
.add(&entry.tier, entry.closed, |sum| sum.sessions.add(entry.presence));
- if let Some(track) = presence.get_mut(&entry.root) {
+ if let Some(track) = presence.get_mut(&entry.label) {
track.sums.add(&entry.tier, entry.closed, |sum| sum.add(entry.presence));
}
}
@@ -1259,8 +1259,8 @@ impl GroupPublisher {
});
}
- // The registry reports a root only while a session or request holds its
- // counters, plus its final readout, so every row is in the frame: a root
+ // The registry reports a label only while a session or request holds its
+ // counters, plus its final readout, so every row is in the frame: a label
// held by an idle request must not drop out and return looking reset.
for &i in session_rows.iter() {
let entry = &report.sessions[i];
@@ -1271,7 +1271,7 @@ impl GroupPublisher {
broadcast,
requested,
&names.sessions,
- entry.root.clone(),
+ entry.label.clone(),
entry.presence,
);
}
@@ -1309,8 +1309,8 @@ impl GroupPublisher {
/// ([`TrackFamily::push`] finds the pair already created). Valid tier names
/// over the quota park (bounded) until it frees rather than being rejected.
///
- /// A presence track is held only while requested, for a root in this group,
- /// and answered at once with the root's current counters from `report`.
+ /// A presence track is held only while requested, for a label in this group,
+ /// and answered at once with the label's current counters from `report`.
/// It is reclaimed once its last consumer leaves, so the held set follows
/// live readers. A prefix track follows the same rules for a broadcast
/// prefix in this group. Any other name is rejected.
@@ -1337,12 +1337,12 @@ impl GroupPublisher {
// Pop everything queued, grouping the two flavors of one plain name so
// a pair is built from the actual requests where present. Only tier
// names past the parked bound are rejected.
- let mut roots: HashMap = HashMap::new();
+ let mut labels: HashMap = HashMap::new();
let mut paths: HashMap = HashMap::new();
let noop = kio::Waiter::noop();
while let Poll::Ready(Ok(request)) = self.dynamic.poll_requested_track(&noop) {
let keyed = match parse_presence_track(request.name()) {
- Some((root, compressed)) => Some((&mut roots, root, compressed)),
+ Some((label, compressed)) => Some((&mut labels, label, compressed)),
None => parse_prefix_track(request.name())
// No broadcast path is deeper than `MAX_PARTS`.
.filter(|(path, _)| path.parts().count() <= Path::MAX_PARTS)
@@ -1377,24 +1377,24 @@ impl GroupPublisher {
self.traffic.adopt_parked(&self.broadcast, &mut self.requested);
self.sessions.adopt_parked(&self.broadcast, &mut self.requested);
- for (root, pending) in roots {
- self.adopt_presence(report, root, pending);
+ for (label, pending) in labels {
+ self.adopt_presence(report, label, pending);
}
for (path, pending) in paths {
self.adopt_prefix(report, path, pending, tick);
}
}
- /// Hold a requested root's presence track, publishing its current counters
+ /// Hold a requested label's presence track, publishing its current counters
/// so the subscription resolves at once. Cumulative from here on.
- fn adopt_presence(&mut self, report: &Report, root: PathOwned, pending: PendingPair) {
+ fn adopt_presence(&mut self, report: &Report, label: PathOwned, pending: PendingPair) {
// A request for a live track is served by the broadcast itself, so a
// live pair here means the requested flavor ended and cannot update.
- if self.presence.contains_key(&root) {
+ if self.presence.contains_key(&label) {
pending.reject(moq_net::Error::NotFound);
return;
}
- let name = presence_track(&root, false);
+ let name = presence_track(&label, false);
let pair = match pending.adopt(&self.broadcast, &name, self.traffic.sequence.clone()) {
Ok(pair) => pair,
Err(err) => {
@@ -1410,7 +1410,7 @@ impl GroupPublisher {
};
for &i in &self.session_rows {
let entry = &report.sessions[i];
- if entry.root == root {
+ if entry.label == label {
track.sums.add(&entry.tier, entry.closed, |sum| sum.add(entry.presence));
let start = track.wire_start.entry(entry.tier.label().clone()).or_default();
start.0 += entry.presence.wire_tx;
@@ -1418,7 +1418,7 @@ impl GroupPublisher {
}
}
track.publish();
- self.presence.insert(root, track);
+ self.presence.insert(label, track);
}
/// Hold a requested prefix track, publishing its current counters so the
@@ -2538,7 +2538,7 @@ mod tests {
let (_, broadcast) = announced(&origin).await;
let frame = read_session_frame(&broadcast, "sessions.json").await;
- let snap = frame.get("acme").expect("root entry");
+ let snap = frame.get("acme").expect("label entry");
assert_eq!(snap.sessions_started, 2);
assert_eq!(snap.sessions_ended, 0);
assert!(
@@ -2553,7 +2553,7 @@ mod tests {
assert_eq!(snap.sessions_started, 1);
}
- /// A root held only by requests has no live session, but it stays in every
+ /// A label held only by requests has no live session, but it stays in every
/// frame until its last request ends: dropping out would read as a reset, and
/// the next admission would then count the earlier ones twice.
#[tokio::test(start_paused = true)]
@@ -2598,11 +2598,11 @@ mod tests {
drive_tick().await;
let (_, broadcast) = announced(&origin).await;
let totals = read_totals(&broadcast).await;
- assert_eq!(totals[""].sessions.sessions_started, 2, "both default-tier roots");
+ assert_eq!(totals[""].sessions.sessions_started, 2, "both default-tier labels");
assert_eq!(totals["region/sjc"].sessions.sessions_started, 1);
assert_eq!(totals["region/sjc"].publisher, Traffic::default());
- // A root whose last session leaves is pruned from the registry, but the
+ // A label whose last session leaves is pruned from the registry, but the
// totals keep it.
drop(b);
drive_tick().await;
@@ -2632,11 +2632,11 @@ mod tests {
assert_eq!(default_totals(&beta).await.publisher.bytes, 7);
}
- /// Subscribe to `root`'s presence track on `broadcast`, driving a tick so
+ /// Subscribe to `label`'s presence track on `broadcast`, driving a tick so
/// the producer adopts the request.
- async fn hold_presence(broadcast: &moq_net::broadcast::Consumer, root: &str) -> track::Ordered {
+ async fn hold_presence(broadcast: &moq_net::broadcast::Consumer, label: &str) -> track::Ordered {
let subscribing = broadcast
- .track(&presence_track(root, false))
+ .track(&presence_track(label, false))
.expect("track")
.subscribe(None);
drive_tick().await;
@@ -2644,8 +2644,8 @@ mod tests {
}
/// A held presence track is cumulative from when it was first held: it
- /// starts at the root's current counters, keeps a session that ended and
- /// was pruned, and continues across the root's return.
+ /// starts at the label's current counters, keeps a session that ended and
+ /// was pruned, and continues across the label's return.
#[tokio::test(start_paused = true)]
async fn presence_track_is_cumulative_while_held() {
let (producer, origin) = test_producer(Some("sjc"));
@@ -2659,10 +2659,10 @@ mod tests {
let mut track = hold_presence(&broadcast, "acme/live").await;
let frame = try_presence(&mut track).expect("answered at once");
assert_eq!(frame[""].active(), 1);
- assert_eq!(frame["rtmp"].active(), 1, "every tier the root records on");
- assert_eq!(frame.len(), 2, "only this root");
+ assert_eq!(frame["rtmp"].active(), 1, "every tier the label records on");
+ assert_eq!(frame.len(), 2, "only this label");
- // The root's default-tier session leaves and its counters are pruned.
+ // The label's default-tier session leaves and its counters are pruned.
drop(first);
for _ in 0..3 {
drive_tick().await;
@@ -2675,7 +2675,7 @@ mod tests {
assert_eq!(frame[""].sessions_started, 1, "kept after the prune");
assert_eq!(frame[""].active(), 0);
- // A new session under the root continues the count.
+ // A new session under the label continues the count.
let _again = registry.tier(Tier::default()).session("acme/live");
drive_tick().await;
let mut last = None;
@@ -2687,7 +2687,7 @@ mod tests {
assert_eq!(frame[""].active(), 1);
}
- /// A root with no sessions is held open at zero, and reclaimed once its
+ /// A label with no sessions is held open at zero, and reclaimed once its
/// last consumer leaves.
#[tokio::test(start_paused = true)]
async fn presence_track_for_an_idle_root_is_held_then_reclaimed() {
@@ -2726,7 +2726,7 @@ mod tests {
let mut track = subscribing.await.expect("held").ordered();
assert_eq!(try_presence(&mut track), Some(PresenceFrame::new()), "held at zero");
- // The root records while held: the same subscription carries it.
+ // The label records while held: the same subscription carries it.
let _session = registry.tier(Tier::default()).session("");
tick();
assert_eq!(try_presence(&mut track).expect("recorded")[""].active(), 1);
@@ -2744,7 +2744,7 @@ mod tests {
assert_eq!(tick(), 0, "reclaimed");
}
- /// A root outside the group is not found, and every root inside it is held.
+ /// A label outside the group is not found, and every label inside it is held.
#[tokio::test(start_paused = true)]
async fn presence_requests_are_scoped() {
let (producer, origin, _events) = grouped_producer(DEFAULT_LINGER);
@@ -2759,7 +2759,7 @@ mod tests {
drive_tick().await;
assert!(
matches!(subscribing.await, Err(moq_net::Error::NotFound)),
- "a root in another group"
+ "a label in another group"
);
let pending: Vec<_> = (0..3)
@@ -2775,13 +2775,13 @@ mod tests {
held.push(subscribing.await.expect("held"));
}
- // A held root's compressed flavor shares the live pair.
+ // A held label's compressed flavor shares the live pair.
let subscribing = acme
.track(&presence_track("acme/0", true))
.expect("track")
.subscribe(None);
drive_tick().await;
- subscribing.await.expect("the compressed sibling of a held root");
+ subscribing.await.expect("the compressed sibling of a held label");
}
/// Subscribe to `path`'s prefix track on `broadcast`, driving a tick so the
diff --git a/rs/moq-stats/src/produce_bench.rs b/rs/moq-stats/src/produce_bench.rs
index 839cb6e6a48..46ab721ddf5 100644
--- a/rs/moq-stats/src/produce_bench.rs
+++ b/rs/moq-stats/src/produce_bench.rs
@@ -55,14 +55,14 @@ impl Driver {
self.drain.publisher_frame_bytes()
}
- /// Hold `root`'s presence track as a reader would, so every tick updates
+ /// Hold `label`'s presence track as a reader would, so every tick updates
/// it. Keep the returned subscriber: dropping it lets a tick reclaim the
/// track.
- pub fn hold_presence(&mut self, root: &str) -> track::Subscriber {
+ pub fn hold_presence(&mut self, label: &str) -> track::Subscriber {
let group = self.drain.groups.get_mut("").expect("the depth 0 broadcast");
- let root = PathOwned::from(root.to_string());
- group.adopt_presence(&self.drain.report, root.clone(), PendingPair::default());
- group.presence[&root].pair.plain.track.subscribe(None)
+ let label = PathOwned::from(label.to_string());
+ group.adopt_presence(&self.drain.report, label.clone(), PendingPair::default());
+ group.presence[&label].pair.plain.track.subscribe(None)
}
/// Hold broadcast prefix `path`'s track as a reader would; see