diff --git a/doc/.vitepress/drafts.test.ts b/doc/.vitepress/drafts.test.ts
index df79be4f232..bae6a5d20d7 100644
--- a/doc/.vitepress/drafts.test.ts
+++ b/doc/.vitepress/drafts.test.ts
@@ -128,20 +128,20 @@ describe("tables render as tables", () => {
const rendered = html(page as DraftPage);
- // The Bidirectional Streams table: one header, seven body rows, each
+ // The Bidirectional Streams table: one header, eight body rows, each
// separated by a kramdown rule in the source. Cells carry the source's
// alignment, so match around the style attribute.
const header = /
]*>Stream<\/th>/.exec(rendered);
expect(header).not.toBeNull();
- for (const stream of ["Announce", "Subscribe", "Fetch", "Probe", "Goaway", "Track", "Auth"]) {
+ for (const stream of ["Announce", "Subscribe", "Fetch", "Probe", "Goaway", "Track", "Auth", "Tracks"]) {
expect(rendered).toMatch(new RegExp(`
]*>${stream}
`));
}
- // One header row plus seven body rows, in a single table.
+ // One header row plus eight body rows, in a single table.
const start = rendered.lastIndexOf("
")[0];
- expect(rows.match(/
/g) ?? []).toHaveLength(8);
+ expect(rows.match(/
/g) ?? []).toHaveLength(9);
});
});
diff --git a/doc/concept/moq-lite.md b/doc/concept/moq-lite.md
index edda6e031b0..a2a651e1a53 100644
--- a/doc/concept/moq-lite.md
+++ b/doc/concept/moq-lite.md
@@ -56,6 +56,15 @@ always a prefix. A service that serves only some of the paths beneath it
refuses the rest as they are requested. Announcements are hints; the request is
what decides.
+Inside a broadcast, a reader can list its tracks (moq-lite-07, Rust only so
+far): each track with its fixed properties, a synced mark, then tracks as they
+come and go. Listing is discovery, not delivery: subscribe to each track you
+want, and its groups still cached upstream reach you late. A broadcast lists
+the tracks its publisher creates, never one served only on request, and a path
+served under a prefix claim has nothing to list. Like announcements, a relay
+syncs on what it holds now, so a fresh relay syncs empty and its upstream's
+tracks follow.
+
Each route carries the chain of relay identities it passed through, which is
how forwarding loops are caught, and a cost, which is how a subscriber picks
among several routes to the same broadcast. It may also carry a
diff --git a/drafts/draft-lcurley-moq-ietf.md b/drafts/draft-lcurley-moq-ietf.md
index bfab6d046f1..e814eba4e64 100644
--- a/drafts/draft-lcurley-moq-ietf.md
+++ b/drafts/draft-lcurley-moq-ietf.md
@@ -208,6 +208,8 @@ A receiver refuses such a track as {{moqt}} ingress does, with an unsupported ex
The receiver parses the keys inside the Immutable Properties from its value, which a relay MUST NOT restate as mutable.
It SHOULD read them from the value when needed rather than hold them beside it, as a list of IDs can cost several times the value.
+A TRACKS_ADD ({{moql}} Tracks Stream) embeds TRACK_INFO without TRACK_PROPERTIES, so when the extension is negotiated a subscriber MUST NOT skip the Track Stream for a track it learned from a listing.
+
# Datagrams {#datagrams}
When the extension is negotiated, a DATAGRAM carries a Datagram State after its Group Sequence.
diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md
index 583757c3888..3ecfd1154dd 100644
--- a/drafts/draft-lcurley-moq-lite.md
+++ b/drafts/draft-lcurley-moq-lite.md
@@ -396,6 +396,8 @@ There's a 1-byte STREAM_TYPE at the beginning of each stream.
| ------- | ------------- | ----------- |
| 0x7 | Auth | Either |
| ------- | ------------- | ----------- |
+| 0x8 | Tracks | Subscriber |
+| ------- | ------------- | ----------- |
### Announce
A subscriber can open an Announce Stream to discover routes matching a prefix.
@@ -552,6 +554,39 @@ If FRAME messages cannot be decoded against the cached TRACK_INFO, the subscribe
Because a subscriber cannot parse buffered group frames until TRACK_INFO arrives, the publisher SHOULD prioritize TRACK_INFO ahead of group data on the connection.
+### Tracks {#tracks-stream}
+A subscriber opens a Tracks Stream (0x8) to list the Tracks of one Broadcast.
+A listing is discovery, not delivery: the subscriber SUBSCRIBEs to each Track it wants as usual, and a Track's groups reach a late SUBSCRIBE from the publisher's cache while they are retained.
+
+The subscriber sends a [TRACKS](#tracks) message naming the broadcast path and Epoch.
+The publisher replies with listing events, then FINs the stream once the Broadcast ends, or resets it on error:
+
+- [TRACKS_ADD](#tracks-add): a Track is listed, with its TRACK_INFO.
+- [TRACKS_REMOVE](#tracks-remove): a listed Track no longer is.
+- [SYNCED](#synced): every Track this hop listed when the stream opened, and still lists, has been sent.
+
+A Broadcast lists the Tracks its publisher produces.
+A Track the publisher serves only on request, such as any name a transcoder answers for, is never listed, and listing never creates one.
+A removal promises only that the Track is no longer listed; a SUBSCRIBE for its name MAY still succeed.
+A Track listed again under a removed name is the same Track: within one Broadcast a name always means the same content.
+
+The listing is relative to this hop: a relay answers with the Tracks it currently holds and never waits on its upstream, so a relay without a listing of its own sends SYNCED at once and its upstream's Tracks follow as live TRACKS_ADD.
+A relay SHOULD answer every listing of a Broadcast from one upstream Tracks Stream.
+A subscriber SHOULD hold at most one Tracks Stream per Broadcast, since each costs the publisher the whole listed set.
+A publisher keeps only the newest Tracks Stream per Broadcast on a session and resets any older one with CANCELLED, rather than refusing the newer: a subscriber that stops listing and lists again can open the new stream before the publisher sees the old one close.
+
+The publisher keeps a pending queue per stream, keyed by Track name in the order the changes happened.
+A removal of a Track the subscriber has not been sent cancels its add, and a removal followed by an add of a name it was sent collapses in place into that removal then that add, so a stalled subscriber costs the names it was sent plus the listed set.
+The publisher MUST send SYNCED exactly once: the first time that queue drains, or after it has sent N events, whichever comes first, where N is the queue's length when the stream opened.
+A removal of a Track already sent MAY precede SYNCED.
+
+The subscriber MUST close the session with a PROTOCOL_VIOLATION on a TRACKS_ADD for a name already listed on the stream, a TRACKS_REMOVE for a name not listed, a second SYNCED, or an unknown event type.
+A FIN before SYNCED means the Broadcast ended.
+On a FIN, a relay ends the listings it answers from that stream, even before the Broadcast's retraction arrives.
+A publisher MUST reset a Tracks Stream with NOT_FOUND when the route it would serve the path from covers it by a shorter prefix: a route claims capability, not inventory, so it names no Broadcast to list.
+A subscriber MAY skip the Track Stream for a Track it learned from TRACKS_ADD, since the properties are the same immutable ones.
+Each listed Track a subscriber holds counts against its bound on announcements (see [Resource Exhaustion](#resource-exhaustion)); past it, the subscriber resets the stream rather than hold more.
+
### Probe
A subscriber opens a Probe Stream (0x4) to measure, and optionally increase, the available bitrate of the connection.
The publisher advertises its Probe level in SETUP (see [Probe Parameter](#probe-parameter)): None, Report (measure only), or Increase (measure and actively probe).
@@ -977,7 +1012,8 @@ SYNCED Message {
~~~
SYNCED has no body and assigns no Announce ID.
-A second SYNCED on the same stream, or a stream ending before SYNCED, is a PROTOCOL_VIOLATION.
+A second SYNCED on the same stream is a PROTOCOL_VIOLATION.
+An Announce Stream ending before SYNCED is a PROTOCOL_VIOLATION; a Tracks Stream FIN before SYNCED means the Broadcast ended (see [Tracks](#tracks-stream)).
## ANNOUNCE_START {#announce-start}
@@ -1309,6 +1345,57 @@ Joins coalesce until the requested group arrives.
A relay preserves the ratio and evaluates joins against its own cache, forwarding demand in SUBSCRIBE_UPDATE.
Versions before lite-07 omit Refresh and Wanted Group; a Track received on those versions never refreshes.
+## TRACKS {#tracks}
+TRACKS is sent by a subscriber to list a Broadcast's Tracks.
+It is the first message on a Tracks Stream (0x8).
+
+~~~
+TRACKS Message {
+ Message Length (i)
+ Broadcast Path (s)
+ Epoch (b)
+}
+~~~
+
+**Broadcast Path**:
+The path of the Broadcast to list.
+
+**Epoch**:
+The publisher instance the subscriber expects, as in [TRACK](#track).
+The listing is pinned to the instance that answers it and ends with that instance.
+
+## TRACKS_ADD {#tracks-add}
+A publisher sends TRACKS_ADD on a Tracks Stream when a Track is listed.
+
+~~~
+TRACKS_ADD Message {
+ Type (i) = 0x0
+ Message Length (i)
+ Track Name (s)
+ Track Info (..)
+}
+~~~
+
+**Track Name**:
+The name of the Track, unique among the Tracks listed on the stream.
+
+**Track Info**:
+A [TRACK_INFO](#track-info) message, with its own Message Length, as a Track Stream would answer for the Track.
+
+## TRACKS_REMOVE {#tracks-remove}
+A publisher sends TRACKS_REMOVE on a Tracks Stream when a listed Track is no longer listed.
+
+~~~
+TRACKS_REMOVE Message {
+ Type (i) = 0x1
+ Message Length (i)
+ Track Name (s)
+}
+~~~
+
+**Track Name**:
+The name a TRACKS_ADD on the stream listed.
+
## SUBSCRIBE_OK {#subscribe-ok}
A SUBSCRIBE_OK message confirms a subscription and resolves its absolute start position.
It is the first message the publisher sends on the Subscribe Stream, once the start position is known.
@@ -1639,6 +1726,7 @@ The `Message Length` describes the payload size on the wire.
## moq-lite-07
+- Added the Tracks Stream (0x8) with TRACKS, TRACKS_ADD, TRACKS_REMOVE, and SYNCED: a subscriber lists one Broadcast's Tracks, each with its TRACK_INFO, then SUBSCRIBEs to those it wants. A relay answers at once with what it holds. Older versions reset the stream type.
- Added TRACK_INFO `Refresh` and SUBSCRIBE_UPDATE `Wanted Group`, carrying ratio-based refresh demand through relays.
- Replaced ANNOUNCE_OK Active Count with an ordered, empty SYNCED event (0x4), marking the initial set without retaining routes that end before delivery.
diff --git a/quest/m1/archive/README.md b/quest/m1/archive/README.md
index d2d61379328..1d940249f59 100644
--- a/quest/m1/archive/README.md
+++ b/quest/m1/archive/README.md
@@ -28,7 +28,8 @@ archive (per-track `.timeline.z` records named by the catalog's root
- **Discovery is pull**, decided 2026-10-19 in place of SUBSCRIBE_ALL's push:
ANNOUNCE finds the broadcasts under a prefix, a moq-lite TRACKS request
lists each broadcast's tracks as they appear, and the archive SUBSCRIBEs per
- track, gating the lite-07 cut ([TRACKS](/quest/m1/archive/tracks.md)).
+ track, gating the lite-07 cut (`broadcast::Consumer::tracks` in Rust;
+ [TRACKS in js/net](/quest/m1/archive/tracks-js.md)).
moq-transport answers SUBSCRIBE_TRACKS through the same hook and learns an
IETF peer's tracks with a FORWARD=0 SUBSCRIBE_TRACKS
([SUBSCRIBE_TRACKS](/quest/m1/archive/subscribe-tracks.md)). Rejected:
@@ -83,7 +84,7 @@ from a host. Each child fixes the stale docs it touches.
## Required
-- [TRACKS](/quest/m1/archive/tracks.md) - a moq-lite-07 request lists a broadcast's tracks with their TRACK_INFO, marks when it is synced, and names removed tracks, for the subscriber to SUBSCRIBE per track, and relays fan it out from one upstream request
+- [TRACKS in js/net](/quest/m1/archive/tracks-js.md) - `@moq/net` lists a broadcast's tracks over lite-07's Tracks Stream and answers listings of its own broadcasts, mirroring Rust
- [Archive producer](/quest/m1/archive/producer.md) - `archive::Producer` stores every matching broadcast as duration-cut per-track objects keyed by group and pts, recording gaps instead of stalling, with an optional DVR mode
- [Archive consumer](/quest/m1/archive/consumer.md) - `archive::Consumer` serves a stored prefix as a broadcast from its key listing, and `moq export/import archive` use the new pair
- [Catalog HLS field](/quest/m1/archive/catalog-hls.md) - the root `archive` section is gone; an opt-in per-rendition `hls` field marks each aligned HLS segment's first group and pts and declares its nominal duration
diff --git a/quest/m1/archive/producer.md b/quest/m1/archive/producer.md
index 452e39b5c1b..bac4caf7453 100644
--- a/quest/m1/archive/producer.md
+++ b/quest/m1/archive/producer.md
@@ -18,7 +18,7 @@ Decided by the maintainer on 2026-10-17 (see the
- **Input.** One producer records every broadcast under a prefix as it
appears: ANNOUNCE finds each broadcast announced at its own path,
- [TRACKS](/quest/m1/archive/tracks.md) lists its tracks, and each track
+ TRACKS (`broadcast::Consumer::tracks`) lists its tracks, and each track
records through its own SUBSCRIBE. A covering-prefix route is capability,
not inventory, so broadcasts served under one on request without their own
announcement are not recorded, and a TRACKS refused with NOT_FOUND on an
@@ -152,10 +152,6 @@ mid-recording writing no marker.
Public API: `archive::Producer` and its config replace `Writer`, `Control`,
and the timeline-driven types. Wire: none.
-## Required
-
-- [TRACKS](/quest/m1/archive/tracks.md) - how it learns each broadcast's tracks
-
## Related
- [Archive consumer](/quest/m1/archive/consumer.md) - reads this layout back
diff --git a/quest/m1/archive/subscribe-tracks.md b/quest/m1/archive/subscribe-tracks.md
index 7545c9207e0..5440254c9f8 100644
--- a/quest/m1/archive/subscribe-tracks.md
+++ b/quest/m1/archive/subscribe-tracks.md
@@ -3,7 +3,8 @@
## Goal
moq-net speaks moq-transport SUBSCRIBE_TRACKS (draft-18 on) in both
-directions through the [TRACKS](/quest/m1/archive/tracks.md) model hook,
+directions through the TRACKS model hook (`broadcast::Consumer::tracks`
+and `broadcast::Lister`),
instead of refusing it with NOT_SUPPORTED:
- **Inbound.** A moq-transport subscriber's SUBSCRIBE_TRACKS lists every
@@ -244,7 +245,3 @@ Public API: none beyond the TRACKS hook. Wire: moq-transport support for an
existing message, a FORWARD=0 PUBLISH held as a listing entry and resumed
for data, and an
inbound listing that answers FORWARD=1 with skips rather than data.
-
-## Required
-
-- [TRACKS](/quest/m1/archive/tracks.md) - the model hook this maps onto
diff --git a/quest/m1/archive/tracks-js.md b/quest/m1/archive/tracks-js.md
new file mode 100644
index 00000000000..aaf1a14b5e6
--- /dev/null
+++ b/quest/m1/archive/tracks-js.md
@@ -0,0 +1,38 @@
+# [M] TRACKS in js/net
+
+## Goal
+
+`@moq/net` speaks the moq-lite-07 Tracks Stream (0x8) that Rust already
+speaks, with the same behavior and mirrored names:
+
+- **Listing.** A broadcast consumer lists its tracks (Rust
+ `broadcast::Consumer::tracks`): each listed track with its info, one
+ `synced` event, then adds and removals until the broadcast ends. Over a
+ session it opens one TRACKS per broadcast however many readers list it,
+ syncs its readers at once, and forwards the peer's tracks as live adds.
+- **Answering.** A session answers a peer's TRACKS for a broadcast it
+ publishes with the tracks its producer created (never one served only on
+ request), using the per-reader queue and SYNCED rule the draft specifies.
+- **Refusals.** Older versions reset the stream type, as now. A covering
+ prefix route answers NOT_FOUND. A listing past the session's announce cap
+ is reset.
+
+## Plan
+
+The wire and the Rust model landed first; read the Tracks section of
+`drafts/draft-lcurley-moq-lite.md` and mirror `rs/moq-net/src/model/listing.rs`
+(the queue keyed by name in insertion order, where an unread add and removal
+cancel and a removal then re-add of a seen name collapses in place) and
+`rs/moq-net/src/lite/tracks.rs` (the encoding: TRACKS_ADD 0x0 with an
+embedded TRACK_INFO, TRACKS_REMOVE 0x1, SYNCED 0x4).
+
+`js/net/src/lite/malformed.test.ts` still treats type 8 as unknown on
+lite-07; it becomes a real stream here.
+
+Test the same cases as Rust: snapshot then SYNCED, SYNCED after N events
+under churn, a stalled reader's bounded queue, removal before SYNCED, a
+dynamic-only track never listed, the broadcast ending the listing, and
+`just test interop --all` against the Rust side in both directions.
+
+Public API: a track-listing method on the JS broadcast consumer, named like
+Rust's. Wire: none new.
diff --git a/quest/m1/archive/tracks.md b/quest/m1/archive/tracks.md
deleted file mode 100644
index 1c0fabad466..00000000000
--- a/quest/m1/archive/tracks.md
+++ /dev/null
@@ -1,210 +0,0 @@
-# [L] TRACKS
-
-## Goal
-
-A moq-lite-07 TRACKS request lists the tracks of one broadcast as its
-producer creates them, each with its name and TRACK_INFO, marks with SYNCED
-when the lister has drained what this hop held, and names
-each track that no longer exists. The subscriber then SUBSCRIBEs to each track it wants, so
-delivery stays pull: nothing is ever pushed into a pulled copy. A listing
-never creates a track the publisher serves only on request (an any-name
-`broadcast::Dynamic` handler such as a transcoder). A relay answers many
-downstream TRACKS for a broadcast from one upstream TRACKS. Rust and JS both
-speak it. A listed track's groups reach a late SUBSCRIBE from the cache;
-its datagrams do not, since datagrams are lossy and never cached, so a
-subscriber receives a track's datagrams only from when its SUBSCRIBE takes
-effect.
-
-## Plan
-
-Decided by the maintainer on 2026-10-19, replacing SUBSCRIBE_ALL. Asked about
-listing tracks against SUBSCRIBE_ALL: "ugh I guess the difference is push vs
-pull. Maybe the right answer here is actually a method to list all of the
-tracks within a broadcast/namespace. I'd rather do that for moq-lite than
-deal with merging subscriptions and publishes." Choosing between a `.tracks`
-track, a lite TRACKS message, and keeping SUBSCRIBE_ALL: "I think TRACKS,
-which would actually be kind of nice as an IETF extension too? Oh actually we
-don't need an extension; we could issue forward=0 to learn about all tracks
-from IETF peers?"
-
-Why the 2026-10-17 rejection of "a track-listing stream plus a SUBSCRIBE per
-track" no longer holds:
-
-- **The first-groups race is closed by the cache.** A SUBSCRIBE with no floor
- and a max age at least the publisher's starts at the oldest group the cache
- still holds, so a track's first groups reach a subscriber that learned of
- the track an RTT late, as long as the publisher retains them (Publisher Max
- Age). A group already past retention is a gap, which the archive records
- anyway. Datagrams are outside this: they are never cached
- (`rs/moq-net/src/model/track.rs`), so any late subscriber misses the ones
- sent before it, and SUBSCRIBE_ALL's pushed feed missed those sent before
- it attached too. A datagram track is listed like any other; its datagrams
- arrive from the SUBSCRIBE on, and its groups still come from the cache.
-- **One mechanism cost more than two.**
- [moq-dev/moq#5931](https://github.com/moq-dev/moq/pull/5931) implemented
- SUBSCRIBE_ALL and found that a relay has to merge pushed feeds into pulled
- copies: copies shared by path and epoch, a feed attached to a track already
- requested, bounded SUBSCRIBEs for floors below the feed, aggregate
- preferences, and a choice between duplicate copies and splicing an
- epochless restart into an old copy. A listing plus ordinary SUBSCRIBEs
- needs none of that.
-
-Scope is one broadcast, decided by the maintainer on 2026-10-19. ANNOUNCE already
-discovers broadcasts under a prefix, with their epochs and restarts; a
-prefix-scoped TRACKS would duplicate that and need every route handler to
-answer for a whole prefix (#5931's `Lister`). A prefix consumer composes the
-two: ANNOUNCE for broadcasts, TRACKS per announced broadcast. A route is
-capability, not inventory: a covering-prefix announcement names no
-broadcast, and a service serving paths under it on request lists nothing,
-like an on-demand track. A prefix consumer therefore covers the broadcasts
-announced at their own path (the lite draft already says an advertiser
-SHOULD announce a concrete path once it is producing) and treats TRACKS
-refused with NOT_FOUND on an announced path as "not a broadcast". Any other
-refusal, UNAUTHORIZED included, keeps its reason and reaches the caller as
-that broadcast's error, since a real broadcast refuses a lister without
-permission. TRACKS names a
-broadcast path and an Epoch and resolves like TRACK and SUBSCRIBE, so the
-listing is pinned to the instance that answers it and ends with that
-instance, never spliced into the next one. Rejected: a prefix-scoped TRACKS,
-and a `.tracks` track (a track carrying a listing reuses delivery but mixes
-control into the media namespace and needs its own retraction encoding).
-
-Decided by the maintainer on 2026-10-19: TRACKS still gates the lite-07 cut
-([Finalize moq-lite-07](/quest/m1/lite07-finalize.md)), so the archive line
-has its discovery on the published wire.
-
-Listing events, decided by the maintainer on 2026-10-19 ("for TRACKS, you
-should report the TRACK_INFO as well for each track (maybe reuse the message
-entirely?) as well as have an event for knowing when we're caught up, and
-when a track no longer exists"):
-
-- **Track added, with its TRACK_INFO.** Reuse the TRACK_INFO message
- encoding wholesale: the entry is the track name followed by an embedded,
- length-prefixed TRACK_INFO, so one decoder serves both streams and any
- field TRACK_INFO gains (refresh, compress) reaches listings without a second
- wire change. It fits because TRACK_INFO holds only fixed per-track
- properties and no name or stream-specific field; the name is the only thing
- wrapping it. A lister MAY skip the Track Stream for a track it learned this
- way, since the properties are the same immutable ones.
-- **Synced.** An ordered SYNCED event, sent once, at the first of two
- points: the first time the reader's queue drains (its `poll_next` returns
- Pending), or once the reader has been sent N events, where N is the
- snapshot size it recorded when it subscribed. Decided by the maintainer on
- 2026-10-19 (renamed from CAUGHT_UP the same day), with the bound added so
- live churn cannot postpone SYNCED ("It doesn't even need to be the exact
- count, it could be something like count * 2 as an upper bound"). N is
- enough, with no slack, because the reader's queue delivers in insertion
- order: the snapshot entries go in first, and collapsing only removes them
- or rewrites them in place, so nothing ever lands ahead of them. A removal may land before SYNCED, and an add
- and removal the reader has not reached collapse (see churn below), so the
- lister then holds every track this hop held that is still live. Entries
- after it are live. There is no
- count anywhere, decided by the maintainer on 2026-10-19 ("We don't need the
- count at all"): a count sent first commits to that many adds, which a track
- removed before a slow reader reaches its add would break. The event itself
- is the whole wire cost. The announce stream already carries the same
- event in lite-07, identical in shape.
- Synced means synced with this hop, decided by the maintainer on
- 2026-10-19: a relay answers at once with what it currently holds and never
- waits on its upstream, since relays never block on peers. A cold relay may
- report zero; the upstream's tracks then arrive as live adds.
-- **Track removed.** Names the track, sent when it leaves the broadcast's
- track table, the enumerable inventory. A `broadcast::Dynamic` handler may
- still serve that name on demand, so a later SUBSCRIBE may still succeed;
- removal promises only that the track is no longer listed. There are no entry IDs: a name is unique among a
- broadcast's live tracks, so the name identifies the entry, and a track
- created again under it is a later add of the same track: within one
- broadcast instance a name always means the same content, so its group
- sequences continue rather than restart. A publisher that restarts them is
- buggy and publishes a new broadcast (a new Epoch) instead, so an archive
- keyed by broadcast, track, and first group never collides on a re-add. Removing a name that is not live on
- the stream is a protocol violation. A removal costs the name's bytes instead
- of a varint, which is worth it: the receiver keys tracks by name anyway, and
- the sender needs no per-reader ID state (below).
-
-Costs, accepted:
-
-- **An RTT per new track** before its first group, on top of the listing's
- one-way delay. The cache absorbs it while groups are retained.
-- **A subscription per track.** Each SUBSCRIBE takes a slot in the session's
- subscription cap (`session.subscriptions`, 1000 by default in
- `rs/moq-relay/src/limits.rs`; 10,000 for peers), so an archive of more than
- about a thousand tracks per session hits it. The cap does not change: it
- measures per-track serving state a relay holds either way, and
- SUBSCRIBE_ALL only hid that cost behind one slot per request. A large
- archive shards its prefix across sessions, or its operator raises the
- existing setting for that deployment. No new constant.
-
-Guidance:
-
-- Wire: a new lite-07-wip bidi stream carrying the three events above. The
- request names the broadcast path and Epoch. The stream ends when the
- broadcast instance does. Update
- `drafts/draft-lcurley-moq-lite.md` and its lite-07 changelog, then run
- `just drafts check` and `just test interop --all`. Older versions refuse the
- stream type; no emulation over SUBSCRIBE.
-- Model: a broadcast published locally lists the tracks its producer holds.
- A broadcast served on request (`broadcast::Dynamic`, or a relay's copy of an
- upstream broadcast) answers through its handler; a session forwards the
- request upstream, and a handler that does not answer lists nothing. A relay
- never answers from its own track table, which holds only what was
- subscribed. The listing hangs off the broadcast copy a SUBSCRIBE already
- resolves, so it needs no new copy registry. #5931's
- `broadcast::Consumer::tracks()` is a starting point.
-- Auth: TRACKS needs subscribe permission on the broadcast path, as TRACK
- does. Listing exposes names, not access; each SUBSCRIBE is authorized as
- usual.
-- Untrusted input:
- - A hostile publisher can list without bound. Each listed track it makes a
- relay hold counts against that session's existing `announces` cap, the
- budget for discovery state a peer pushes at us; past it, the relay resets
- the listing rather than holding more. Names keep the existing length caps.
- - A hostile publisher can churn, adding and removing tracks as fast as it
- can send. Each reader keeps a pending queue keyed by name, as origin
- announcement consumers do (`OriginConsumerState` in
- `rs/moq-net/src/model/origin.rs`), decided by the maintainer on
- 2026-10-19. It delivers in insertion order rather than origin's
- lexicographic `BTreeMap` order, which the SYNCED bound needs. A removal for an add still queued for that reader cancels
- both, before or after SYNCED. A removal for an add it already saw is
- queued once, and a later add of the name joins it, as origin's
- `UnannounceAnnounce` does. A reader's state is therefore bounded by the
- names it saw plus the live set (bounded by the `announces` cap), however
- long it stalls, with no global budget. Churn costs per-event work across
- a broadcast's listings (the same fan-out an Announce stream pays), never
- a backlog.
- - A hostile subscriber can open many TRACKS. Each takes a subscription slot,
- downstream listings of one broadcast share one upstream TRACKS, and a
- slow or stalled reader holds only its pending queue, bounded as above,
- not a copy of the listing's history.
-- Fan-out: benchmark downstream listings against tracks per broadcast and
- broadcasts per relay, per the AGENTS.md fan-out rule; a new track's cost
- must not grow with the broadcast count.
-- Split the JS half into its own quest if the PR grows too large to review.
-
-Test on mock time, directly and through a relay: tracks present at the
-request arriving before SYNCED, SYNCED sent the first time the reader's
-queue drains, a cold relay answering SYNCED at once with what it holds and
-the upstream's tracks following as
-live adds, a track added later (a
-SUBSCRIBE from the listing gets its first group from the cache, and its
-datagrams only from the SUBSCRIBE on), a track
-removed and created again under its name (removal sent before the new add),
-add and remove churn collapsing for a stalled reader (including an initial
-track removed before the reader reaches it, with SYNCED still arriving), a
-stalled reader under continuous churn of new names getting SYNCED once it
-has been sent N events, a
-removal of a track the reader saw landing before SYNCED, a stalled reader
-holding no more than the names it saw plus the live set under churn, a removal
-naming a track that is not live refused, a TRACKS refused on a
-covering-prefix route, the broadcast ending the listing, a new epoch at the same path not continuing an old
-listing, a dynamic-only track never created, two downstream listings sharing
-one upstream TRACKS, and the `announces` cap resetting an oversized listing.
-
-Public API: a track-listing hook on `broadcast::Consumer` in Rust and
-`@moq/net`, mirrored names, and a way for a `broadcast::Dynamic` handler to
-answer it. Wire: a new lite-07-wip stream.
-
-## Related
-
-- [SUBSCRIBE_TRACKS](/quest/m1/archive/subscribe-tracks.md) - moq-transport answers and learns listings through this hook
-- [Subscribe ranges](/quest/m1/subscribe-ranges/README.md) - the subscription shape each per-track SUBSCRIBE uses
diff --git a/quest/m1/lite07-finalize.md b/quest/m1/lite07-finalize.md
index 2c0e9fed356..4c35225c53d 100644
--- a/quest/m1/lite07-finalize.md
+++ b/quest/m1/lite07-finalize.md
@@ -89,7 +89,7 @@ is published; older versions are unchanged.
- [Announcement takeover](/quest/m1/announce-takeover.md) - ANNOUNCE_TAKEOVER preserves a proven instance under a new independent route
- [Compressed tracks in Rust](/quest/m1/compress/core.md) - TRACK_INFO carries the compress flag and the frame header each compressed frame's inflated size
- [Compressed tracks in js/net](/quest/m1/compress/js.md) - JS reads and writes compressed lite-07 tracks instead of refusing them
-- [TRACKS](/quest/m1/archive/tracks.md) - lite-07 carries the request listing a broadcast's tracks as they appear
+- [TRACKS in js/net](/quest/m1/archive/tracks-js.md) - JS speaks lite-07's Tracks Stream, which Rust already does
- [Ingress-version provenance](/quest/m1/ietf-extension/lite.md) - the `ietf` extension carries a track's ingress version once instead of a code per block
## Related
diff --git a/rs/moq-net/Cargo.toml b/rs/moq-net/Cargo.toml
index fd3f53810a2..0f1809f8aee 100644
--- a/rs/moq-net/Cargo.toml
+++ b/rs/moq-net/Cargo.toml
@@ -130,6 +130,10 @@ name = "track"
harness = false
required-features = ["async"]
+[[bench]]
+name = "tracks"
+harness = false
+
# Declares a pending tail through the hidden `fuzz` module.
[[bench]]
name = "tail"
diff --git a/rs/moq-net/benches/tracks.rs b/rs/moq-net/benches/tracks.rs
new file mode 100644
index 00000000000..5ccb8ebf5c1
--- /dev/null
+++ b/rs/moq-net/benches/tracks.rs
@@ -0,0 +1,119 @@
+//! What a broadcast's track listing costs as it fans out.
+//!
+//! - change: a track is created and dropped on one broadcast, and every listing of it
+//! reads both events. Swept over the listings and the tracks it already lists, and
+//! over idle broadcasts with listings of their own, so a cost that grows with the
+//! table rather than the touched broadcast shows up as a slope.
+//! - list: a new listing reads a broadcast's tracks through SYNCED, swept the same way.
+//!
+//! Run with `cargo bench -p moq-net --bench tracks`.
+
+use std::task::Poll;
+
+use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
+use moq_net::broadcast::{self, Tracks, TracksEvent};
+
+/// `(listings, tracks, broadcasts)` shapes: listings and tracks per broadcast, and the
+/// broadcasts beside the touched one.
+const SHAPES: [(usize, usize, usize); 6] = [
+ (1, 10, 1),
+ (1, 1_000, 1),
+ (100, 10, 1),
+ (100, 1_000, 1),
+ (10, 10, 1_000),
+ (10, 10, 1),
+];
+
+/// Broadcasts with their tracks and listings, every listing drained to SYNCED.
+struct Table {
+ broadcasts: Vec,
+ _tracks: Vec,
+ listings: Vec>,
+}
+
+fn next(tracks: &mut Tracks) -> Option {
+ match tracks.poll_next(&kio::Waiter::noop()) {
+ Poll::Ready(event) => event.expect("listing failed"),
+ Poll::Pending => None,
+ }
+}
+
+fn drain(tracks: &mut Tracks) -> usize {
+ let mut events = 0;
+ while next(tracks).is_some() {
+ events += 1;
+ }
+ events
+}
+
+fn table(listings: usize, tracks: usize, broadcasts: usize) -> Table {
+ let mut table = Table {
+ broadcasts: Vec::new(),
+ _tracks: Vec::new(),
+ listings: Vec::new(),
+ };
+ for _ in 0..broadcasts {
+ let broadcast = broadcast::Info::new().produce();
+ for i in 0..tracks {
+ table
+ ._tracks
+ .push(broadcast.create_track(format!("t{i}"), None).unwrap());
+ }
+ let consumer = broadcast.consume();
+ let mut readers: Vec = (0..listings).map(|_| consumer.tracks().unwrap()).collect();
+ for reader in &mut readers {
+ assert_eq!(drain(reader), tracks + 1);
+ }
+ table.broadcasts.push(broadcast);
+ table.listings.push(readers);
+ }
+ table
+}
+
+fn bench_change(c: &mut Criterion) {
+ let mut group = c.benchmark_group("tracks/change");
+ for (listings, tracks, broadcasts) in SHAPES {
+ let id = BenchmarkId::from_parameter(format!("{listings}l_{tracks}t_{broadcasts}b"));
+ group.bench_function(id, |b| {
+ let mut table = table(listings, tracks, broadcasts);
+ let broadcast = table.broadcasts[0].clone();
+ let readers = &mut table.listings[0];
+ b.iter(|| {
+ let track = broadcast.create_track("new", None).unwrap();
+ drop(track);
+ for reader in readers.iter_mut() {
+ // The unread add and removal cancel; read the next pair as it lands.
+ assert_eq!(drain(reader), 0);
+ }
+ let track = broadcast.create_track("new", None).unwrap();
+ for reader in readers.iter_mut() {
+ assert_eq!(drain(reader), 1);
+ }
+ drop(track);
+ for reader in readers.iter_mut() {
+ assert_eq!(drain(reader), 1);
+ }
+ });
+ });
+ }
+ group.finish();
+}
+
+fn bench_list(c: &mut Criterion) {
+ let mut group = c.benchmark_group("tracks/list");
+ for (listings, tracks, broadcasts) in SHAPES {
+ let id = BenchmarkId::from_parameter(format!("{listings}l_{tracks}t_{broadcasts}b"));
+ group.bench_function(id, |b| {
+ let table = table(listings, tracks, broadcasts);
+ let consumer = table.broadcasts[0].consume();
+ b.iter(|| {
+ let mut reader = consumer.tracks().unwrap();
+ assert_eq!(drain(&mut reader), tracks + 1);
+ });
+ });
+ }
+ group.finish();
+}
+
+criterion_group!(benches, bench_change, bench_list);
+criterion_main!(benches);
diff --git a/rs/moq-net/src/lite/mod.rs b/rs/moq-net/src/lite/mod.rs
index d80b29e8c73..c2453f181b8 100644
--- a/rs/moq-net/src/lite/mod.rs
+++ b/rs/moq-net/src/lite/mod.rs
@@ -35,6 +35,7 @@ mod subscriber;
#[cfg(all(test, feature = "async"))]
pub(crate) mod test_transport;
mod track;
+mod tracks;
mod version;
pub use announce::*;
@@ -58,4 +59,5 @@ pub use subscribe::*;
#[cfg(feature = "async")]
use subscriber::*;
pub use track::*;
+pub use tracks::*;
pub use version::Version;
diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs
index 2850cf0f487..63504585370 100644
--- a/rs/moq-net/src/lite/publisher.rs
+++ b/rs/moq-net/src/lite/publisher.rs
@@ -82,6 +82,8 @@ struct Shared {
// Control streams still serving the peer data, which a draining close waits for.
owed: AtomicUsize,
interests: Interests,
+ /// Holds this session's listings: one per broadcast, the newest replacing the rest.
+ lister: crate::broadcast::Owner,
fetches: crate::session::Slots,
// The send time an untimed track's frames carry on Lite05/06, which can't mark them
// untimed (see `wire_timestamp`).
@@ -204,6 +206,7 @@ impl Publisher {
peer_grant: config.peer_grant,
owed: AtomicUsize::new(0),
interests: Interests::new(config.subscriptions),
+ lister: crate::broadcast::Owner::new(),
fetches: config.fetches,
runtime: config.runtime.clone(),
estimate: config.estimate,
@@ -299,6 +302,7 @@ enum ControlState {
Subscribe(RequestServe>),
Fetch(RequestServe),
TrackInfo(RequestServe),
+ Tracks(RequestServe),
Probe(ProbeServe),
Auth(AuthServe),
/// Decoding the peer's GOAWAY, surfaced through [`crate::Session::draining`].
@@ -334,12 +338,13 @@ impl Control {
};
let version = self.shared.version;
// PROBE is lite-03+, GOAWAY lite-04+, the Track Stream and FETCH lite-05+, and the
- // Auth Stream lite-07+.
+ // Auth and Tracks Streams lite-07+.
let kind = kind.filter(|kind| match kind {
lite::ControlType::Probe => !matches!(version, Version::Lite01 | Version::Lite02),
lite::ControlType::Goaway => version.has_goaway(),
lite::ControlType::Fetch | lite::ControlType::Track => version.has_track_stream(),
lite::ControlType::Auth => version.has_auth(),
+ lite::ControlType::Tracks => version.has_tracks(),
_ => true,
});
@@ -363,6 +368,9 @@ impl Control {
lite::ControlType::Track => {
ControlState::TrackInfo(RequestServe::new(self.shared.clone(), stream))
}
+ lite::ControlType::Tracks => {
+ ControlState::Tracks(RequestServe::new(self.shared.clone(), stream))
+ }
lite::ControlType::Probe => {
ControlState::Probe(ProbeServe::new(self.shared.clone(), self.runtime.clone(), stream))
}
@@ -375,6 +383,7 @@ impl Control {
ControlState::Subscribe(serve) => return serve.poll(waiter),
ControlState::Fetch(serve) => return serve.poll(waiter),
ControlState::TrackInfo(serve) => return serve.poll(waiter),
+ ControlState::Tracks(serve) => return serve.poll(waiter),
ControlState::Probe(serve) => return serve.poll(waiter),
ControlState::Auth(serve) => return serve.poll(waiter),
ControlState::Goaway { stream } => {
@@ -1809,6 +1818,11 @@ enum Charge {
Track,
/// A subscription.
Subscribe,
+ /// A TRACKS stream listing the broadcast, charged under the empty track name on top
+ /// of any interest in a track of that name. Each listing is charged until it is gone,
+ /// replaced or not: which listing a newer one replaces is known only once both
+ /// resolve, so like a repeated SUBSCRIBE, a replacement must fit under the cap.
+ Tracks,
}
/// A session's subscription cap, charged per track.
@@ -1826,6 +1840,7 @@ struct Interests {
struct Interest {
tracks: usize,
subscribes: usize,
+ listings: usize,
slots: Vec,
}
@@ -1834,11 +1849,12 @@ impl Interest {
match charge {
Charge::Track => &mut self.tracks,
Charge::Subscribe => &mut self.subscribes,
+ Charge::Tracks => &mut self.listings,
}
}
fn cost(&self) -> usize {
- self.tracks.max(self.subscribes)
+ self.tracks.max(self.subscribes) + self.listings
}
}
@@ -1954,6 +1970,73 @@ impl Request for TrackInfoServe {
}
}
+/// Answers a TRACKS stream: the broadcast's listed tracks, SYNCED, then each change,
+/// until the broadcast ends or a newer listing of it on the session replaces this one.
+///
+/// Each listing queues the broadcast's whole listed set, so the session lists each
+/// broadcast once: duplicates would multiply that memory and every change's fanout. A
+/// newer listing replaces the older rather than being refused, since a subscriber that
+/// stops listing and lists again can open the new stream before we see the old one close.
+struct TracksServe {
+ tracks: crate::broadcast::Tracks,
+}
+
+impl Request for TracksServe {
+ const KIND: &'static str = "tracks";
+ const GRACEFUL: bool = false;
+ const CHARGE: Option = Some(Charge::Tracks);
+ const HOLDS: bool = false;
+ type Message = lite::Tracks<'static>;
+ type Update = NoUpdate;
+
+ fn target(msg: &Self::Message) -> (&crate::Path<'static>, &str) {
+ (&msg.broadcast, "")
+ }
+
+ fn epoch(msg: &Self::Message) -> Option<&crate::Epoch> {
+ msg.epoch.as_ref()
+ }
+
+ fn start(shared: &Shared, _: Self::Message, broadcast: crate::broadcast::Consumer) -> Result {
+ Ok(Self {
+ tracks: broadcast.tracks_as(shared.lister)?,
+ })
+ }
+
+ fn update(&mut self, update: NoUpdate) {
+ match update {}
+ }
+
+ fn poll(
+ &mut self,
+ _: &Shared,
+ writer: &mut Writer,
+ waiter: &kio::Waiter,
+ ) -> Poll, Error>> {
+ // Pull an event only once the last is out, so a stalled requester's changes collapse
+ // in the listing's queue rather than pile up here.
+ ready!(writer.poll_flush(&mut waiter.context()))?;
+ let event = match ready!(self.tracks.poll_next(waiter))? {
+ Some(crate::broadcast::TracksEvent::Added { name, info }) => lite::TracksEvent::Added {
+ name: name.to_string().into(),
+ info: lite::TrackInfo {
+ refresh: info.refresh,
+ priority: info.priority,
+ max_age: info.max_age,
+ timescale: info.timescale,
+ },
+ },
+ Some(crate::broadcast::TracksEvent::Removed { name }) => lite::TracksEvent::Removed {
+ name: name.to_string().into(),
+ },
+ Some(crate::broadcast::TracksEvent::Synced) => lite::TracksEvent::Synced,
+ None => return Poll::Ready(Ok(ControlFlow::Break(()))),
+ };
+ writer.buffer(&event)?;
+ Poll::Ready(Ok(ControlFlow::Continue(())))
+ }
+}
+
/// Answers a SUBSCRIBE stream: streams the track's groups (and best-effort datagrams)
/// until the track ends.
enum SubscribeServe {
@@ -6719,15 +6802,16 @@ mod tests {
async fn unknown_control_types_reset_only_their_stream() {
use kio::Task;
// An unassigned type everywhere, then types a version predates: PROBE before lite-03,
- // GOAWAY before lite-04, FETCH and TRACK before lite-05, AUTH before lite-07.
+ // GOAWAY before lite-04, FETCH and TRACK before lite-05, AUTH and TRACKS before lite-07.
let cases = [
- (Version::Lite06, 8),
- (Version::Lite07, 8),
+ (Version::Lite06, 9),
+ (Version::Lite07, 9),
(Version::Lite02, lite::ControlType::Probe as u8),
(Version::Lite03, lite::ControlType::Goaway as u8),
(Version::Lite04, lite::ControlType::Fetch as u8),
(Version::Lite04, lite::ControlType::Track as u8),
(Version::Lite06, lite::ControlType::Auth as u8),
+ (Version::Lite06, lite::ControlType::Tracks as u8),
];
for (version, kind) in cases {
let mut session = ScriptedSession::new(vec![kind]);
@@ -7681,6 +7765,14 @@ mod tests {
drop(slots.acquire().expect("the slot was not returned"));
}
+ // Each listing is its own interest, even one that will replace another.
+ let listing = interests.charge(&room, "", Charge::Tracks).expect("the listing fits");
+ assert!(matches!(
+ interests.charge(&room, "", Charge::Tracks),
+ Err(Error::TooManyRequests)
+ ));
+ drop(listing);
+
// Two of a kind are two interests.
let _a = interests.charge(&room, "video", Charge::Subscribe).unwrap();
assert!(matches!(
@@ -7804,6 +7896,52 @@ mod tests {
}
}
+ /// A second listing of a broadcast on one session replaces the first, so a peer cannot
+ /// multiply the listed set's memory and fanout by listing it again.
+ #[moq_clock::test]
+ async fn a_newer_listing_of_a_broadcast_replaces_the_older() {
+ use kio::Task;
+ let version = Version::Lite07;
+ let origin = crate::origin::Config::new(Hop::random()).produce();
+ let broadcast = origin.create_broadcast("room").unwrap();
+ broadcast.announce(Default::default()).unwrap();
+ let request = lite::Tracks {
+ broadcast: crate::Path::new("room"),
+ epoch: None,
+ };
+ let request = request.encode_bytes(version).unwrap().to_vec();
+ let mut session = ScriptedSession::per_stream(vec![request.clone(), request]);
+ let log = session.log.clone();
+ let older = Stream::open(&mut session, version).await.unwrap();
+ let newer = Stream::open(&mut session, version).await.unwrap();
+ let estimate = kio::Producer::default();
+ let probe = probe_server(session.clone(), older, version, &estimate);
+ probe.shared.peer_setup.set(lite::Setup::default());
+ let mut shared = probe.shared;
+ Arc::get_mut(&mut shared).expect("one owner").origin = origin.consume();
+ let control = |stream| Control {
+ shared: shared.clone(),
+ runtime: crate::time::sim(),
+ state: ControlState::Tracks(RequestServe::new(shared.clone(), stream)),
+ };
+
+ // Whether the control is still serving after the runtime settles.
+ async fn serving(control: &mut Control) -> bool {
+ moq_clock::timeout(Duration::from_millis(1), kio::wait(|waiter| control.poll(waiter)))
+ .await
+ .is_err()
+ }
+
+ let mut older = control(probe.stream.unwrap());
+ assert!(serving(&mut older).await, "the listing ended early");
+ let mut newer = control(newer);
+ assert!(serving(&mut newer).await, "the newer listing ended early");
+ assert!(!serving(&mut older).await, "the older listing outlived its replacement");
+ assert_eq!(log.resets(), vec![crate::StreamError::Cancel.to_code()]);
+ assert!(log.closes().is_empty(), "a repeated listing closed the session");
+ assert!(serving(&mut newer).await, "the newer listing ended");
+ }
+
#[moq_clock::test]
async fn a_producer_decode_error_stays_on_its_request() {
use kio::Task;
diff --git a/rs/moq-net/src/lite/stream.rs b/rs/moq-net/src/lite/stream.rs
index 4ccadbe4140..f0e3844688e 100644
--- a/rs/moq-net/src/lite/stream.rs
+++ b/rs/moq-net/src/lite/stream.rs
@@ -15,6 +15,7 @@ pub enum ControlType {
Goaway = 5,
Track = 6,
Auth = 7,
+ Tracks = 8,
}
impl Decode for ControlType {
diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs
index 825dcbe86ec..2254f3c7014 100644
--- a/rs/moq-net/src/lite/subscriber.rs
+++ b/rs/moq-net/src/lite/subscriber.rs
@@ -1731,12 +1731,89 @@ struct SourceServe {
tracks: kio::Tasks>,
// The source ended: no more track requests will arrive.
ended: bool,
+ /// Answers listings of the source with the peer's TRACKS.
+ lister: crate::broadcast::Lister,
+ /// The peer's listing, while anyone lists the source.
+ listing: Option>,
+}
+
+/// Forwards the peer's TRACKS listing of a source into the source's lister.
+struct TracksRecv {
+ session: S,
+ stream: Option>,
+ /// What the peer lists, each holding an `announces` slot: discovery state the peer
+ /// makes us hold.
+ listed: HashMap, crate::session::Slot>,
+ synced: bool,
+ /// Each event fans out to every reader, so a peer streaming add/remove churn must not
+ /// hold the thread for as long as its bytes keep arriving.
+ budget: kio::coop::Budget,
+}
+
+impl TracksRecv {
+ /// Apply the peer's events until it ends the listing, or the error that ends it.
+ fn poll(&mut self, source: &SourceServe, waiter: &kio::Waiter) -> Poll> {
+ let mut cx = waiter.context();
+ let version = source.subscriber.version;
+ let stream = match &mut self.stream {
+ Some(stream) => stream,
+ None => {
+ let mut stream = ready!(Stream::poll_open(&mut self.session, version, &mut cx))?;
+ stream.writer.buffer(&lite::ControlType::Tracks)?;
+ stream.writer.buffer(&lite::Tracks {
+ broadcast: source.path.as_path(),
+ epoch: source.epoch.clone(),
+ })?;
+ self.stream.insert(stream)
+ }
+ };
+ ready!(stream.writer.poll_flush(&mut cx))?;
+ loop {
+ ready!(self.budget.poll_yield(waiter));
+ let Some(event) = ready!(stream.reader.poll_decode_maybe::(&mut cx))? else {
+ return Poll::Ready(Ok(()));
+ };
+ match event {
+ lite::TracksEvent::Added { name, info } => {
+ let name: Arc = name.as_ref().into();
+ if self.listed.contains_key(&name) {
+ return Poll::Ready(Err(Error::ProtocolViolation));
+ }
+ let slot = source.subscriber.announces.acquire()?;
+ let info = track::Info::default()
+ .with_timescale(info.timescale)
+ .with_max_age(info.max_age)
+ .with_priority(info.priority)
+ .with_refresh(info.refresh);
+ source.lister.add(name.clone(), info)?;
+ self.listed.insert(name, slot);
+ }
+ lite::TracksEvent::Removed { name } => {
+ if self.listed.remove(name.as_ref()).is_none() {
+ return Poll::Ready(Err(Error::ProtocolViolation));
+ }
+ source.lister.remove(&name)?;
+ }
+ lite::TracksEvent::Synced => {
+ // This hop synced its readers when the listing began; only the order matters here.
+ if std::mem::replace(&mut self.synced, true) {
+ return Poll::Ready(Err(Error::ProtocolViolation));
+ }
+ }
+ }
+ }
+ }
}
impl SourceServe {
fn new(subscriber: Subscriber, minted: MintedSource) -> Self {
let closed = subscriber.session.clone();
Self {
+ lister: minted
+ .dynamic
+ .lister()
+ .expect("only the source answers its broadcast's listings"),
+ listing: None,
subscriber,
validity: minted.validity,
path: minted.path,
@@ -1749,6 +1826,60 @@ impl SourceServe {
ended: false,
}
}
+
+ /// Answer the source's listings while anyone lists it, from the peer's TRACKS.
+ fn poll_listing(&mut self, waiter: &kio::Waiter) {
+ // Taken out while it runs, since it reads the rest of the source.
+ let mut listing = self.listing.take();
+ loop {
+ match &mut listing {
+ None => {
+ if !matches!(self.lister.poll_used(waiter), Poll::Ready(Ok(()))) {
+ break;
+ }
+ if !self.subscriber.version.has_tracks() {
+ // An empty answer would claim the peer lists nothing.
+ self.lister.abort(Error::Unsupported);
+ continue;
+ }
+ // Synced with this hop, which holds nothing yet: a relay never waits on its
+ // upstream, so the peer's tracks follow as live adds.
+ self.lister.synced();
+ listing = Some(TracksRecv {
+ session: self.subscriber.session.clone(),
+ stream: None,
+ listed: HashMap::new(),
+ synced: false,
+ budget: kio::coop::Budget::new(32),
+ });
+ }
+ Some(_) if self.lister.poll_unused(waiter).is_ready() => {
+ // Dropping the stream resets it.
+ listing = None;
+ self.lister.clear();
+ }
+ Some(recv) => match recv.poll(self, waiter) {
+ Poll::Pending => break,
+ // The peer's broadcast ended, whether or not its retraction has arrived:
+ // end the listing and let go of what it listed.
+ Poll::Ready(Ok(())) => {
+ listing = None;
+ self.lister.finish();
+ }
+ Poll::Ready(Err(err)) => {
+ let err = lite::error::control(&mut self.subscriber.session.clone(), err);
+ tracing::debug!(broadcast = %self.path, %err, "tracks failed");
+ if let Some(stream) = recv.stream.take() {
+ stream.writer.abort(&err);
+ }
+ listing = None;
+ self.lister.abort(err);
+ }
+ },
+ }
+ }
+ self.listing = listing;
+ }
}
impl kio::Task for SourceServe {
@@ -1763,6 +1894,7 @@ impl kio::Task for SourceServe {
// Session gone.
return Poll::Ready(());
}
+ self.poll_listing(waiter);
if self.ended {
// Done once the tracks in flight are.
return self.tracks.poll(waiter);
diff --git a/rs/moq-net/src/lite/tracks.rs b/rs/moq-net/src/lite/tracks.rs
new file mode 100644
index 00000000000..c39fdeb40cb
--- /dev/null
+++ b/rs/moq-net/src/lite/tracks.rs
@@ -0,0 +1,200 @@
+use std::borrow::Cow;
+
+use crate::{
+ Path,
+ coding::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder},
+};
+
+use super::{Message, TrackInfo, Version, message::MAX_MESSAGE_SIZE, message::decode_size};
+
+const TRACKS_ADD: u64 = 0x0;
+const TRACKS_REMOVE: u64 = 0x1;
+// The same event the announce stream marks its initial set with.
+const SYNCED: u64 = 0x4;
+
+/// Sent by the subscriber on a Tracks Stream (0x8) to list one broadcast's tracks.
+///
+/// Lite07+ only.
+#[derive(Clone, Debug)]
+pub struct Tracks<'a> {
+ pub broadcast: Path<'a>,
+ /// The publisher instance the subscriber expects; see [`crate::origin::Route::epoch`].
+ pub epoch: Option,
+}
+
+impl Message for Tracks<'_> {
+ fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result {
+ if !version.has_tracks() {
+ return Err(DecodeError::Version);
+ }
+ let broadcast = Path::decode(r, version)?;
+ let epoch = super::epoch::decode_epoch(r, version)?;
+ Ok(Self { broadcast, epoch })
+ }
+
+ fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> {
+ if !version.has_tracks() {
+ return Err(EncodeError::Version);
+ }
+ self.broadcast.encode(w, version)?;
+ super::epoch::encode_epoch(w, version, self.epoch.as_ref())
+ }
+}
+
+/// One event the publisher sends on a Tracks Stream, each a type, then a size-prefixed body.
+///
+/// Lite07+ only.
+#[derive(Clone, Debug)]
+pub enum TracksEvent<'a> {
+ /// TRACKS_ADD: a listed track, with the TRACK_INFO a Track Stream would answer.
+ Added { name: Cow<'a, str>, info: TrackInfo },
+ /// TRACKS_REMOVE: a track named by an earlier TRACKS_ADD is no longer listed.
+ Removed { name: Cow<'a, str> },
+ /// SYNCED: every track this hop listed when the stream opened, and still lists, was sent.
+ Synced,
+}
+
+impl Encode for TracksEvent<'_> {
+ fn encode(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> {
+ if !version.has_tracks() {
+ return Err(EncodeError::Version);
+ }
+ w.varint(match self {
+ Self::Added { .. } => TRACKS_ADD,
+ Self::Removed { .. } => TRACKS_REMOVE,
+ Self::Synced => SYNCED,
+ })?;
+ let prefix = w.prefix_varint();
+ match self {
+ Self::Added { name, info } => {
+ w.string(name)?;
+ info.encode(w, version)?;
+ }
+ Self::Removed { name } => w.string(name)?,
+ Self::Synced => {}
+ }
+ if w.since(&prefix) > MAX_MESSAGE_SIZE {
+ w.discard(prefix);
+ return Err(EncodeError::TooLarge);
+ }
+ w.fill(prefix)
+ }
+}
+
+impl Decode for TracksEvent<'_> {
+ fn decode(r: &mut Decoder<'_>, version: Version) -> Result {
+ if !version.has_tracks() {
+ return Err(DecodeError::Version);
+ }
+ let typ = r.varint()?;
+ let size = decode_size(r, MAX_MESSAGE_SIZE)?;
+ let mut body = r.sub(size)?;
+ // The body is complete, so running short inside it is malformed, not a wait for more.
+ let msg = (|| {
+ Ok(match typ {
+ TRACKS_ADD => Self::Added {
+ name: Cow::Owned(body.string()?),
+ info: TrackInfo::decode(&mut body, version)?,
+ },
+ TRACKS_REMOVE => Self::Removed {
+ name: Cow::Owned(body.string()?),
+ },
+ SYNCED => Self::Synced,
+ // A new stream with no earlier builds to tolerate.
+ _ => return Err(DecodeError::InvalidValue),
+ })
+ })()
+ .map_err(DecodeError::complete)?;
+ match body.is_empty() {
+ true => Ok(msg),
+ false => Err(DecodeError::Long),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use std::time::Duration;
+
+ use super::*;
+ use crate::Timescale;
+
+ fn roundtrip(event: &TracksEvent<'_>) -> TracksEvent<'static> {
+ let buf = event.encode_bytes(Version::Lite07).unwrap();
+ TracksEvent::decode_slice(&buf, Version::Lite07).unwrap().0
+ }
+
+ #[test]
+ fn events_roundtrip() {
+ let info = TrackInfo {
+ refresh: Some(4),
+ priority: 3,
+ max_age: Some(Duration::from_secs(2)),
+ timescale: Some(Timescale::MICRO),
+ };
+ let TracksEvent::Added { name, info: got } = roundtrip(&TracksEvent::Added {
+ name: "video".into(),
+ info,
+ }) else {
+ panic!("expected an add");
+ };
+ assert_eq!(name, "video");
+ assert_eq!(got.refresh, Some(4));
+ assert_eq!(got.priority, 3);
+ assert_eq!(got.max_age, Some(Duration::from_secs(2)));
+ assert_eq!(got.timescale, Some(Timescale::MICRO));
+
+ let TracksEvent::Removed { name } = roundtrip(&TracksEvent::Removed { name: "video".into() }) else {
+ panic!("expected a removal");
+ };
+ assert_eq!(name, "video");
+ assert!(matches!(roundtrip(&TracksEvent::Synced), TracksEvent::Synced));
+ }
+
+ #[test]
+ fn synced_is_an_empty_type_four() {
+ assert_eq!(
+ TracksEvent::Synced.encode_bytes(Version::Lite07).unwrap(),
+ &[0x04u8, 0x00][..]
+ );
+ }
+
+ #[test]
+ fn an_unknown_event_is_refused() {
+ assert!(matches!(
+ TracksEvent::decode_slice(&[0x02, 0x00], Version::Lite07),
+ Err(DecodeError::InvalidValue)
+ ));
+ }
+
+ #[test]
+ fn a_trailing_byte_is_refused() {
+ assert!(matches!(
+ TracksEvent::decode_slice(&[0x04, 0x01, 0x00], Version::Lite07),
+ Err(DecodeError::Long)
+ ));
+ }
+
+ #[test]
+ fn the_request_roundtrips() {
+ let epoch: crate::Epoch = "01900000-0000-7000-8000-000000000001".parse().unwrap();
+ let msg = Tracks {
+ broadcast: Path::new("room/alice").to_owned(),
+ epoch: Some(epoch.clone()),
+ };
+ let buf = msg.encode_bytes(Version::Lite07).unwrap();
+ let (got, _) = Tracks::decode_slice(&buf, Version::Lite07).unwrap();
+ assert_eq!(got.broadcast, Path::new("room/alice"));
+ assert_eq!(got.epoch, Some(epoch));
+ }
+
+ #[test]
+ fn older_versions_have_no_tracks_stream() {
+ let msg = Tracks {
+ broadcast: Path::new("room").to_owned(),
+ epoch: None,
+ };
+ assert!(msg.encode_bytes(Version::Lite06).is_err());
+ assert!(TracksEvent::Synced.encode_bytes(Version::Lite06).is_err());
+ }
+}
diff --git a/rs/moq-net/src/lite/version.rs b/rs/moq-net/src/lite/version.rs
index 51eed85f5f0..543028c8419 100644
--- a/rs/moq-net/src/lite/version.rs
+++ b/rs/moq-net/src/lite/version.rs
@@ -124,6 +124,17 @@ impl Version {
}
}
+ /// Whether a subscriber may open a Tracks Stream (0x8) to list a broadcast's
+ /// tracks. Added in lite-07.
+ #[allow(clippy::match_like_matches_macro)]
+ pub fn has_tracks(self) -> bool {
+ // Match form so future versions default forward (AGENTS.md convention).
+ match self {
+ Self::Lite01 | Self::Lite02 | Self::Lite03 | Self::Lite04 | Self::Lite05 | Self::Lite06 => false,
+ _ => true,
+ }
+ }
+
/// Whether announcements carry implicit announce ids: each `active`
/// ANNOUNCE_BROADCAST assigns the next per-stream ordinal, and `ended`/`restart`
/// reference that id instead of repeating the path. Added in lite-06.
diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs
index f21764656c2..c84c445b631 100644
--- a/rs/moq-net/src/model/broadcast.rs
+++ b/rs/moq-net/src/model/broadcast.rs
@@ -22,6 +22,15 @@ use crate::origin::Route;
use super::origin_impl::Announcer;
use super::{Requests, WeakCache};
+#[path = "listing.rs"]
+mod listing;
+// private: capability gap
+// Sessions dedup a peer's listings per broadcast; a custom session has no public owner yet.
+#[cfg(feature = "async")]
+pub(crate) use listing::Owner;
+pub(super) use listing::{ListOnAccept, Unlist};
+pub use listing::{Lister, Tracks, TracksEvent};
+
/// A collection of media tracks that can be published and subscribed to.
///
/// Create via [`Info::produce`] to obtain both [`Producer`] and [`Consumer`] pair.
@@ -107,6 +116,9 @@ struct BroadcastState {
// swept as the map grows, so requests for names never served stay bounded.
sequences: HashMap, track::Sequence>,
+ // The tracks the broadcast lists, and the readers listing them; see [`Tracks`].
+ listing: listing::ListingState,
+
// Set once the broadcast ends: `Producer::close()` or the last producer-side
// handle dropping. Every lookup after it answers `Unroutable`.
closing: bool,
@@ -314,20 +326,22 @@ impl Producer {
// this they would be stranded, since the name is taken the moment the
// track exists, so no handler could ever serve their queue entry.
if let Some(request) = state.requests.take(name.as_ref()) {
- let track = request.with_stats(self.stats.clone()).accept(info);
+ let track = request.with_stats(self.stats.clone()).accept(info.clone());
// Cache it like a served request so concurrent lookups coalesce; a
// live same-name entry cannot exist (its presence would have kept
// the request from queuing).
- let _ = state.tracks.insert(name, track.weak());
- return Ok(track);
+ let _ = state.tracks.insert(name.clone(), track.weak());
+ let unlist = Unlist::list(&self.state, &mut state.listing, name, &info);
+ return Ok(track.listed(unlist));
}
let sequence = state.sequence(&name);
- let track = track::Producer::new(self.info.clone(), name, info)
+ let track = track::Producer::new(self.info.clone(), name.clone(), info.clone())
.with_stats(self.stats.clone())
.with_sequence(sequence);
state.insert_track(track.weak())?;
- Ok(track)
+ let unlist = Unlist::list(&self.state, &mut state.listing, name, &info);
+ Ok(track.listed(unlist))
}
/// Reserve a track by name without finalizing its [`track::Info`].
@@ -348,7 +362,10 @@ impl Producer {
.with_stats(self.stats.clone())
.with_sequence(state.sequence(&name));
state.insert_track(request.weak())?;
- Ok(request)
+ Ok(request.listed(ListOnAccept {
+ state: self.state.clone(),
+ name,
+ }))
}
/// Create a track with a unique name using the given suffix.
@@ -435,13 +452,10 @@ impl Producer {
/// the broadcast; `Finish::wait` does both on a runtime. Dropping it early is how an
/// interrupt ends the linger.
pub fn finish(self) -> Finish {
- let held: Vec = self
- .state
- .lock()
- .tracks
- .values()
- .filter_map(track::TrackWeak::hold_finished)
- .collect();
+ let tracks: Vec = self.state.read().tracks.values().cloned().collect();
+ // Held outside the lock: a track whose last producer drops meanwhile unlists itself
+ // under it.
+ let held: Vec = tracks.iter().filter_map(track::TrackWeak::hold_finished).collect();
let linger = held.iter().filter_map(|hold| hold.max_age).max().unwrap_or_default();
Finish {
producer: self,
@@ -586,6 +600,7 @@ impl Alive {
// and `Consumer::track` answers `Unroutable` for one asked about after this
// point. Say the same to whoever asked earlier.
state.reject_unserved(Error::Unroutable);
+ state.listing.close();
}
let _ = self.token.close();
self.retract();
@@ -611,6 +626,7 @@ impl Alive {
};
state.closing = true;
state.reject_unserved(Error::Unroutable);
+ state.listing.close();
token
};
token.close();
@@ -860,6 +876,15 @@ impl Dynamic {
}
}
+ /// Answer the broadcast's track listings, for a handler that knows the tracks it
+ /// would serve, such as a relay listing its upstream's. See [`Lister`].
+ ///
+ /// A handler that serves any name on request takes none, so it lists nothing. One
+ /// answer per broadcast: fails with [`Error::Duplicate`] while another lister exists.
+ pub fn lister(&self) -> Result {
+ Lister::new(self.state.clone())
+ }
+
/// Block until the broadcast ends, by [`Producer::close`] or every producer dropping.
#[cfg(feature = "async")]
pub async fn closed(&self) {
diff --git a/rs/moq-net/src/model/listing.rs b/rs/moq-net/src/model/listing.rs
new file mode 100644
index 00000000000..50d755a1df9
--- /dev/null
+++ b/rs/moq-net/src/model/listing.rs
@@ -0,0 +1,1008 @@
+//! A broadcast's track listing: the tracks it lists, reported to each reader in order.
+//!
+//! A track is listed while it is in the broadcast's inventory: created by its
+//! [`Producer`](super::Producer) (until it leaves the track table), or answered by a
+//! handler through a [`Lister`], as a relay's copy lists its upstream's tracks. A track
+//! served only on request is never listed, and listing never requests one.
+//!
+//! Each [`Tracks`] reader keeps its own queue, keyed by name in insertion order, so a
+//! stalled reader holds at most one pending change per name: an add and a removal it
+//! has not reached cancel, and a removal and re-add of a name it saw collapse in place.
+//! Its state is bounded by the names it saw plus the live set, however long it stalls.
+
+use std::{
+ sync::Arc,
+ task::{Poll, ready},
+};
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+use hashlink::LinkedHashMap;
+
+use super::{BroadcastState, Consumer};
+use crate::{Error, track};
+
+/// What a [`Tracks`] listing reports, in order.
+#[derive(Clone, Debug)]
+pub enum TracksEvent {
+ /// A track the broadcast lists, with its fixed properties.
+ Added {
+ /// The track's name, unique among the broadcast's listed tracks.
+ name: Arc,
+ /// The track's properties, the same its TRACK_INFO carries.
+ info: track::Info,
+ },
+ /// Every track this hop listed when the listing began, and still lists, has been
+ /// reported. Sent once; later events are live.
+ Synced,
+ /// A track is no longer listed. A handler may still serve its name on request.
+ Removed {
+ /// The name an earlier [`Self::Added`] reported.
+ name: Arc,
+ },
+}
+
+/// One listed track and who lists it.
+struct Entry {
+ info: track::Info,
+ /// The producer's listing, numbered so a stale unlist never removes a later track
+ /// of the name.
+ own: Option,
+ /// Whether a handler's answer lists it.
+ answered: bool,
+}
+
+/// Who holds a listing, such as a session serving a peer: at most one listing of each
+/// broadcast at a time. A newer listing by the same owner ends the older with
+/// [`Error::Cancel`], so an owner's listings cost one queue per broadcast however many
+/// paths or requests reach it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+// private: capability gap
+// Sessions dedup a peer's listings per broadcast; a custom session has no public owner yet.
+pub(crate) struct Owner(u64);
+
+impl Owner {
+ // private: capability gap
+ // Sessions dedup a peer's listings per broadcast; a custom session has no public owner yet.
+ #[cfg_attr(not(feature = "async"), allow(dead_code))]
+ pub(crate) fn new() -> Self {
+ static NEXT: AtomicU64 = AtomicU64::new(0);
+ Self(NEXT.fetch_add(1, Ordering::Relaxed))
+ }
+}
+
+/// The listing half of a broadcast's state, guarded by the broadcast's lock.
+#[derive(Default)]
+pub(super) struct ListingState {
+ /// Every listed track, in the order it was listed.
+ live: LinkedHashMap, Entry>,
+ /// The queue of every reader of the current answer.
+ readers: slab::Slab>,
+ /// Bumped whenever every reader is detached at once, so a reader of an earlier
+ /// answer releases nothing on drop.
+ generation: u64,
+ /// Each owner's reader, by its key in `readers`.
+ owners: HashMap,
+ /// Whether a [`Lister`] exists. While one does, readers wait for its answer to sync.
+ lister: bool,
+ /// Whether the handler's answer has synced.
+ answered: bool,
+ next_token: u64,
+}
+
+impl ListingState {
+ fn synced(&self) -> bool {
+ !self.lister || self.answered
+ }
+
+ fn each(&self, mut f: impl FnMut(&mut Queue)) {
+ for (_, queue) in &self.readers {
+ f(&mut queue.lock());
+ }
+ }
+
+ /// Start a reader with every listed track queued, ending `owner`'s older one.
+ fn read(&mut self, owner: Option) -> (kio::Shared, usize, u64) {
+ let mut queue = Queue::default();
+ for (name, entry) in &self.live {
+ queue.pending.insert(name.clone(), Pending::Add(entry.info.clone()));
+ }
+ if self.synced() {
+ queue.bound = Some(queue.pending.len());
+ }
+ let queue = kio::Shared::new(queue);
+ let key = self.readers.insert(queue.clone());
+ if let Some(older) = owner.and_then(|owner| self.owners.insert(owner, key)) {
+ let older = self.readers.remove(older);
+ let mut older = older.lock();
+ older.end = Some(Err(Error::Cancel));
+ older.detached = true;
+ }
+ (queue, key, self.generation)
+ }
+
+ fn release(&mut self, key: usize, generation: u64, owner: Option, queue: &kio::Shared) {
+ // A replaced reader already left, and its key may be another's now.
+ if generation != self.generation || queue.read().detached {
+ return;
+ }
+ self.readers.try_remove(key);
+ if let Some(owner) = owner {
+ self.owners.remove(&owner);
+ }
+ }
+
+ /// Re-evaluate whether the listing has synced, telling readers when it changed.
+ fn resync(&mut self, was: bool) {
+ match (was, self.synced()) {
+ (false, true) => self.each(Queue::sync),
+ (true, false) => self.each(Queue::unsync),
+ _ => {}
+ }
+ }
+
+ fn insert(&mut self, name: Arc, entry: Entry) {
+ let info = entry.info.clone();
+ self.live.insert(name.clone(), entry);
+ self.each(|queue| queue.add(name.clone(), info.clone()));
+ }
+
+ fn remove(&mut self, name: &str) {
+ if let Some((name, _)) = self.live.remove_entry(name) {
+ self.each(|queue| queue.remove(&name));
+ }
+ }
+
+ /// List a track the producer created, returning the token that unlists it.
+ pub(super) fn list_own(&mut self, name: Arc, info: track::Info) -> u64 {
+ let token = self.next_token;
+ self.next_token += 1;
+ match self.live.get_mut(&name) {
+ // The earlier track of the name has not unlisted yet, but it left the table
+ // for this one to be created: readers see it go and the new one arrive.
+ Some(entry) if entry.own.is_some() && !entry.answered => {
+ self.remove(&name);
+ let own = Some(token);
+ self.insert(
+ name,
+ Entry {
+ info,
+ own,
+ answered: false,
+ },
+ );
+ }
+ // Listed already, by the handler if not by the producer, and it never stopped
+ // being listed: only the token moves.
+ Some(entry) => entry.own = Some(token),
+ None => {
+ let own = Some(token);
+ self.insert(
+ name,
+ Entry {
+ info,
+ own,
+ answered: false,
+ },
+ );
+ }
+ }
+ token
+ }
+
+ /// Unlist a track the producer created, unless a later one took its name.
+ pub(super) fn unlist_own(&mut self, name: &str, token: u64) {
+ let Some(entry) = self.live.get_mut(name) else {
+ return;
+ };
+ if entry.own != Some(token) {
+ return;
+ }
+ entry.own = None;
+ if !entry.answered {
+ self.remove(name);
+ }
+ }
+
+ fn answer_add(&mut self, name: Arc, info: track::Info) -> Result<(), Error> {
+ match self.live.get_mut(&name) {
+ Some(entry) if entry.answered => Err(Error::Duplicate),
+ Some(entry) => {
+ entry.answered = true;
+ Ok(())
+ }
+ None => {
+ self.insert(
+ name,
+ Entry {
+ info,
+ own: None,
+ answered: true,
+ },
+ );
+ Ok(())
+ }
+ }
+ }
+
+ fn answer_remove(&mut self, name: &str) -> Result<(), Error> {
+ let Some(entry) = self.live.get_mut(name).filter(|entry| entry.answered) else {
+ return Err(Error::NotFound);
+ };
+ entry.answered = false;
+ if entry.own.is_none() {
+ self.remove(name);
+ }
+ Ok(())
+ }
+
+ /// Drop the handler's answer: every track it listed, and its sync.
+ fn answer_clear(&mut self) {
+ let was = self.synced();
+ self.unanswer();
+ self.resync(was);
+ }
+
+ /// Unlist every track the handler's answer listed.
+ fn unanswer(&mut self) {
+ let answered: Vec> = self
+ .live
+ .iter()
+ .filter(|(_, entry)| entry.answered)
+ .map(|(name, _)| name.clone())
+ .collect();
+ for name in answered {
+ let _ = self.answer_remove(&name);
+ }
+ self.answered = false;
+ }
+
+ /// End every reader with `end` and detach them.
+ fn detach(&mut self, end: Result<(), Error>) {
+ self.each(|queue| queue.end = Some(end.clone()));
+ self.readers.clear();
+ self.owners.clear();
+ self.generation += 1;
+ }
+
+ /// The broadcast ended: so does every listing of it.
+ pub(super) fn close(&mut self) {
+ self.detach(Ok(()));
+ }
+}
+
+/// Unlists a track the producer created once it leaves the track table. Held by the
+/// track's teardown guard, so it drops with the last producer, or when the track aborts.
+pub(in crate::model) struct Unlist {
+ state: kio::Shared,
+ name: Arc,
+ token: u64,
+}
+
+impl Unlist {
+ /// List `name` now, from inside the broadcast's lock.
+ pub(super) fn list(
+ state: &kio::Shared,
+ listing: &mut ListingState,
+ name: Arc,
+ info: &track::Info,
+ ) -> Self {
+ let token = listing.list_own(name.clone(), info.clone());
+ Self {
+ state: state.clone(),
+ name,
+ token,
+ }
+ }
+}
+
+impl Drop for Unlist {
+ fn drop(&mut self) {
+ self.state.lock().listing.unlist_own(&self.name, self.token);
+ }
+}
+
+/// Lists a reserved track once it is accepted with its info.
+pub(in crate::model) struct ListOnAccept {
+ pub(super) state: kio::Shared,
+ pub(super) name: Arc,
+}
+
+impl ListOnAccept {
+ /// List the track with the info it was accepted with. Called outside the broadcast's lock.
+ pub(in crate::model) fn list(self, info: &track::Info) -> Unlist {
+ let mut state = self.state.lock();
+ Unlist::list(&self.state, &mut state.listing, self.name.clone(), info)
+ }
+}
+
+/// A change a reader has yet to read.
+enum Pending {
+ Add(track::Info),
+ Remove,
+ /// A removal of a track the reader saw, then a track of the same name listed again.
+ Readd(track::Info),
+}
+
+/// One reader's pending changes, keyed by name in the order they happened.
+#[derive(Default)]
+pub(super) struct Queue {
+ pending: LinkedHashMap, Pending>,
+ /// Events left to send before SYNCED, once the listing has synced.
+ bound: Option,
+ /// SYNCED was sent.
+ synced: bool,
+ end: Option>,
+ /// A newer reader of the same owner replaced this one.
+ detached: bool,
+}
+
+impl Queue {
+ fn add(&mut self, name: Arc, info: track::Info) {
+ match self.pending.get_mut(&name) {
+ Some(pending @ Pending::Remove) => *pending = Pending::Readd(info),
+ // A name is listed once at a time, so only its removal can be pending.
+ Some(_) => debug_assert!(false, "a listed track was listed again"),
+ None => {
+ self.pending.insert(name, Pending::Add(info));
+ }
+ }
+ }
+
+ fn remove(&mut self, name: &Arc) {
+ match self.pending.get_mut(name) {
+ // Never read: the two cancel.
+ Some(Pending::Add(_)) => {
+ self.pending.remove(name);
+ }
+ Some(pending) => *pending = Pending::Remove,
+ None => {
+ self.pending.insert(name.clone(), Pending::Remove);
+ }
+ }
+ }
+
+ /// The events the pending changes take to read.
+ fn events(&self) -> usize {
+ self.pending
+ .values()
+ .map(|pending| match pending {
+ Pending::Readd(_) => 2,
+ _ => 1,
+ })
+ .sum()
+ }
+
+ /// The listing synced: SYNCED goes out once what is queued now has been read, or
+ /// earlier if the queue drains first.
+ fn sync(&mut self) {
+ if !self.synced && self.bound.is_none() {
+ self.bound = Some(self.events());
+ }
+ }
+
+ /// The listing's answer restarted before this reader was told it synced.
+ fn unsync(&mut self) {
+ if !self.synced {
+ self.bound = None;
+ }
+ }
+
+ fn is_ready(&self) -> bool {
+ self.end.is_some() || !self.pending.is_empty() || (!self.synced && self.bound.is_some())
+ }
+
+ fn next(&mut self) -> Result