diff --git a/apps/sandbox/templates/moq-publisher/loopback-relay.ts b/apps/sandbox/templates/moq-publisher/loopback-relay.ts index 0a867e1ef5..c8ef534155 100644 --- a/apps/sandbox/templates/moq-publisher/loopback-relay.ts +++ b/apps/sandbox/templates/moq-publisher/loopback-relay.ts @@ -37,12 +37,16 @@ const MESSAGE_TYPE = { REQUEST_ERROR: 0x5, REQUEST_OK: 0x7, NAMESPACE: 0x8, + PUBLISH_DONE: 0xb, NAMESPACE_DONE: 0xe, FETCH: 0x16, PUBLISH: 0x1d, SUBSCRIBE_NAMESPACE: 0x50, } as const; +/** PUBLISH_DONE status codes (§10.12) this relay sends its players. */ +const PUBLISH_DONE_INTERNAL_ERROR = 0x0; + /** REQUEST_ERROR code for "nothing published in that range" (§10.6.1). */ const ERROR_INVALID_RANGE = 0x11; @@ -334,6 +338,11 @@ function encodeSubscribeOk(trackAlias: number): Uint8Array { return frame(MESSAGE_TYPE.SUBSCRIBE_OK, new Writer().varint(trackAlias).varint(0).toBytes()); } +function encodePublishDone(statusCode: number, streamCount: number): Uint8Array { + // Status Code + Stream Count + an empty Reason Phrase. + return frame(MESSAGE_TYPE.PUBLISH_DONE, new Writer().varint(statusCode).varint(streamCount).varint(0).toBytes()); +} + /** * SUBSCRIBE_NAMESPACE toward the publisher (§10.18): the empty prefix solicits every namespace the publisher will * announce — the same solicitation moq-relay 0.14.7 opens right after SETUP. @@ -414,10 +423,11 @@ interface PlayerSubscription { trackAlias: number; deliver(object: BufferedObject): void; /** - * End this subscription from the relay side: FIN toward the player and cancel its request stream, so its teardown - * removes the entry. Used when the upstream track is aborted for every viewer. + * End this subscription from the relay side: with a `statusCode`, PUBLISH_DONE (§10.12, counting the streams this + * subscription was sent) and then FIN; without one, a bare FIN. Then cancel its request stream, so its teardown + * removes the entry. */ - end(): void; + end(statusCode?: number): void; } interface TrackBuffer { @@ -662,8 +672,8 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp /** * One live upstream subscription per track: SUBSCRIBE, bind the SUBSCRIBE_OK's alias for the data-stream router, - * then hold the stream open. It ends by FIN alone (no PUBLISH_DONE exists in this flow) — the publisher's, ending - * the track for good, or our own via `handle.release()`, withdrawing a track no player watches. + * then hold the stream open. It ends with the publisher's PUBLISH_DONE and FIN, ending the track for good, or with + * our own FIN via `handle.release()`, withdrawing a track no player watches. */ const runUpstreamSubscription = async ( track: TrackBuffer, @@ -692,7 +702,7 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp const reason = fields.string(); if (errorCode === ERROR_DOES_NOT_EXIST && track.ended) { - // Done, not late: the publisher FINed this track and has + // Done, not late: the publisher ended this track and has // not re-registered it, so DOES_NOT_EXIST is terminal — // mirror the real relay, which aborts the request rather // than retrying, by ending the late subscribers. Each @@ -767,20 +777,35 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp `upstream SUBSCRIBE ${track.name} → alias ${trackAlias}${timescale === undefined ? '' : ` (timescale ${timescale})`}` ); - // Hold for the FIN — the publisher's clean track end, or our own - // release. A subscription ends by FIN *alone*: any byte after - // SUBSCRIBE_OK is a protocol violation, and the real relay - // aborts the track for every viewer — mirror that by ending each - // downstream subscription rather than silently draining. + // Hold for the end — the publisher's PUBLISH_DONE then FIN (the + // clean track end), or our own release. Anything else after + // SUBSCRIBE_OK aborts the track for every viewer. + let publishDoneStatus: number | undefined; + if (!(await reader.atEnd())) { - log(`upstream ${track.name}: data after SUBSCRIBE_OK — aborting the track for its viewers`); + // A truncated or malformed frame aborts the track too — never + // leave its viewers attached to an upstream that is gone. + const message = await readControlFrame(reader).catch(() => undefined); + const clean = message?.type === MESSAGE_TYPE.PUBLISH_DONE && (await reader.atEnd().catch(() => false)); + + if (!message || !clean) { + const what = message ? `unexpected 0x${message.type.toString(16)}` : 'malformed frame'; + + log(`upstream ${track.name}: ${what} after SUBSCRIBE_OK — aborting the track`); + + for (const subscriber of [...track.subscribers]) subscriber.end(PUBLISH_DONE_INTERNAL_ERROR); + + return; + } + + publishDoneStatus = new Reader(message.body).varint(); + } - for (const subscriber of [...track.subscribers]) subscriber.end(); - } else if (handle.released) { + if (handle.released && publishDoneStatus === undefined) { log(`upstream unsubscribe ${track.name} — no player interest`); } else { - // The publisher's FIN is the END of the track: propagate it — - // the same clean FIN toward every attached viewer — so no + // The publisher's PUBLISH_DONE + FIN is the END of the track: + // propagate it to every attached viewer, so no // player hangs on a dead track and a later publisher session // cannot resume stale subscriptions. The downstream teardowns' // releaseUpstream calls land after this routine's finally has @@ -793,7 +818,11 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp // handed the final frames of a track that is over. track.groups.clear(); - for (const subscriber of [...track.subscribers]) subscriber.end(); + // Forward the publisher's status, the way moq-relay 0.17.0 does + // — a bare FIN reaches its viewers as INTERNAL_ERROR. + for (const subscriber of [...track.subscribers]) { + subscriber.end(publishDoneStatus ?? PUBLISH_DONE_INTERNAL_ERROR); + } } } catch { // Stream reset or session teardown — the close path owns cleanup. @@ -1234,15 +1263,25 @@ export function createPublisherLoopbackRelay({ onLog }: PublisherLoopbackRelayOp // Announce-and-serve: player interest is what makes the relay // SUBSCRIBE upstream (catalog first, then the catalog's tracks). requestUpstreamTrack?.(track); + // One stream per delivered object — the PUBLISH_DONE Stream Count. + let deliveredStreams = 0; + subscription = { trackAlias, - deliver: (object) => + deliver: (object) => { + deliveredStreams++; publishObject( encodeObjectStream(trackAlias, object.groupId, object.objectId, object.properties, object.payload) - ), - end: () => { - // FIN toward the player (the clean track end), then cancel - // our read side — the loop's teardown removes the entry. + ); + }, + end: (statusCode) => { + // PUBLISH_DONE (when ending with a status) and FIN toward the + // player, then cancel our read side — the loop's teardown + // removes the entry. + if (statusCode !== undefined) { + void writer.write(encodePublishDone(statusCode, deliveredStreams)).catch(() => {}); + } + writer.close().catch(() => {}); abort(); }, diff --git a/internal/design/spf/features/moq-publish.md b/internal/design/spf/features/moq-publish.md index 1526f4b6f3..8c69433b9a 100644 --- a/internal/design/spf/features/moq-publish.md +++ b/internal/design/spf/features/moq-publish.md @@ -49,7 +49,7 @@ none is separately composable today. |---|---|---| | Capture | Device enumeration (`devicechange`-reactive, label refresh on grant); capture-source acquisition (`getUserMedia` camera, `getDisplayMedia` + microphone-merge screen share, re-acquire on selection-identity change, stale-async guards); preview mirroring via `srcObject` (forced muted + playsInline); mute toggles via `track.enabled` (capture keeps running) | **Implemented** | | Encode | `isConfigSupported` probing over a candidate ladder (default `avc1.42E01F` in `avc` bitstream format with a `vp8` fallback; Opus with a 48 kHz fallback; `config.video.codec` prepends rather than replaces); `selectEncoderConfig` strategy resolves support → active encodings; per-kind WebCodecs encoder actors, each stamping one epoch of the kind's `TrackTimeline` — a rebuilt actor (capture-source switch, encoding change) continues the track's published clock domain plus the real monotonic acquisition gap instead of opening a fresh wallclock anchor; frame pumping with a timestamp-driven forced-keyframe cadence so **GoP = MoQ group** (`groupDurationSec`, default 2 s); LOC packaging of every chunk (Timestamp / Timescale / Config-on-keyframes) | **Implemented** | -| Transport | Publish session speaking draft-19 with **announce-and-serve ingest** (see the decision below): SETUP exchange; inbound SUBSCRIBE_NAMESPACE solicitations answered with REQUEST_OK and held as the announce carrier; the namespace announced as a NAMESPACE entry on every covering solicitation (`'live'` = announced); inbound SUBSCRIBEs answered with SUBSCRIBE_OK carrying alias = the request ID and a microsecond TIMESCALE track property; REQUEST_UPDATE routing; GOAWAY → `draining`; track end = a bare FIN of each subscription stream; close retracts the announce (NAMESPACE_DONE) and sends **no GOAWAY**; one `TrackPublisherActor` per track writing subgroup streams **only while bound to a live subscription** (video: new group per keyframe, joins at the next keyframe on bind; audio + catalog: group-per-frame; catalog replays its latest frame on every bind); MSF catalog derivation re-sent on any input-identity change | **Implemented** | +| Transport | Publish session speaking draft-19 with **announce-and-serve ingest** (see the decision below): SETUP exchange; inbound SUBSCRIBE_NAMESPACE solicitations answered with REQUEST_OK and held as the announce carrier; the namespace announced as a NAMESPACE entry on every covering solicitation (`'live'` = announced); inbound SUBSCRIBEs answered with SUBSCRIBE_OK carrying alias = the request ID and a microsecond TIMESCALE track property; REQUEST_UPDATE routing; GOAWAY → `draining`; track end = PUBLISH_DONE (TRACK_ENDED, exact Stream Count) then FIN on each subscription stream; close retracts the announce (NAMESPACE_DONE) and sends **no GOAWAY**; one `TrackPublisherActor` per track writing subgroup streams **only while bound to a live subscription** (video: new group per keyframe, joins at the next keyframe on bind; audio + catalog: group-per-frame; catalog replays its latest frame on every bind); MSF catalog derivation re-sent on any input-identity change | **Implemented** | | Observability | ~1 Hz `publishStats` sampling from the encoder actor counters (`encodedFps`, bitrates, `droppedFrames`, `bytesSent`) | **Implemented** — `droppedGroups` is counted on the track publishers but not yet folded into `publishStats`; `subscriberCount` is tracked on the session actor but surfaces as `NaN` | ### Ingest model: announce-and-serve (2026-08-07) @@ -78,10 +78,12 @@ own reference clients use: next keyframe; the catalog track replays its latest frame on every bind because catalog frames flow on change, and a fresh subscription must not wait for the next one. -- **Three peer-verified teardown rules** (moq-relay 0.14.7 source): - a track ends by a bare FIN of the subscription stream — any trailing - byte (the old PUBLISH_DONE) makes the relay *abort* the track for - every viewer; a client GOAWAY closes the whole session (code 17); and +- **Three peer-verified teardown rules**: a track ends with + PUBLISH_DONE (TRACK_ENDED, exact Stream Count) then a FIN of the + subscription stream — moq-relay 0.17.0 forwards that as "track ended", + but reports a bare FIN as "internal error" (older moq-relay builds + abort the track on any byte after SUBSCRIBE_OK; they are not + supported); a client GOAWAY closes the whole session (code 17); and SUBSCRIBE_OK should declare the TIMESCALE track property or the relay discards object TIMESTAMP extensions and re-stamps frames on arrival. - **Per-stream failures are ordinary lifecycle now** — the relay resets @@ -144,7 +146,7 @@ Behaviors (`packages/spf/src/publish/behaviors/`; DOM-bound ones under | `pumpMediaFrames` | `dom/pump-media-frames.ts` | `MediaStreamTrackProcessor` read loops → `encode` messages; keyframe cadence | | `trackPublishStats` | `track-publish-stats.ts` | Sample encoder counters into `publishStats` (DOM-free via a structural actor view) | | `openPublishSession` | `open-publish-session.ts` | Own the publish session actor; gate on `endpoint` + `publishActivated` + capture `'active'`; mirror lifecycle into `sessionStatus` | -| `setupTrackPublishers` | `setup-track-publishers.ts` | Register each track on the session's serve registry; own the per-track publisher actors; sync subscription bindings into them; FIN each track's subscriptions on teardown | +| `setupTrackPublishers` | `setup-track-publishers.ts` | Register each track on the session's serve registry; own the per-track publisher actors; sync subscription bindings into them; on teardown, close each track's data streams, then end its subscriptions with PUBLISH_DONE (TRACK_ENDED) and a FIN | | `deriveCatalog` | `derive-catalog.ts` | Build + send the MSF catalog as object 0 of a fresh group on every input change | Actors and session: @@ -267,8 +269,9 @@ publisher initiates no requests, so there is no response to bound. half (solicitation acceptance, suffix-relative NAMESPACE entries, announce-loss → `onAnnounceEnded`, NAMESPACE_DONE + no-GOAWAY close) and the serve half (alias = request ID, TIMESCALE declaration, - newest-subscription binding with clean replacement FINs, bare-FIN - track end) through `network/moqt/tests/helpers/raw-peer.ts`, the relay's + newest-subscription binding with bare-FIN ends for superseded + subscriptions, PUBLISH_DONE + FIN track end with exact Stream Counts) + through `network/moqt/tests/helpers/raw-peer.ts`, the relay's side of the flow the subscribe driver does not initiate. - **Full pipeline** — `publish/engines/moq/tests/publish-transport.test.ts`: real capture diff --git a/packages/spf/src/network/moqt/control-messages.ts b/packages/spf/src/network/moqt/control-messages.ts index 5329201dd6..d759f2030d 100644 --- a/packages/spf/src/network/moqt/control-messages.ts +++ b/packages/spf/src/network/moqt/control-messages.ts @@ -1028,12 +1028,21 @@ export function encodeSubscribeOk( return frameMessage(MESSAGE_TYPE.SUBSCRIBE_OK, body); } -/** PUBLISH_DONE (§10.12). */ -export function encodePublishDone(statusCode: number, streamCount: number, reason = ''): Uint8Array { +/** 2^64−1, PUBLISH_DONE's "unknown" Stream Count, has one encoding: the 9-byte form with every bit set. */ +const UNKNOWN_STREAM_COUNT = new Uint8Array(9).fill(0xff); + +/** + * PUBLISH_DONE (§10.12). An `undefined` Stream Count is the publisher that cannot count its streams, encoded as the + * 2^64−1 sentinel the draft mandates (and `readCountVarint` reads back as `undefined`). + */ +export function encodePublishDone(statusCode: number, streamCount: number | undefined, reason = ''): Uint8Array { const body = new ByteWriter(); body.writeVarint(statusCode); - body.writeVarint(streamCount); + + if (streamCount === undefined) body.writeBytes(UNKNOWN_STREAM_COUNT); + else body.writeVarint(streamCount); + writeReasonPhrase(body, reason); return frameMessage(MESSAGE_TYPE.PUBLISH_DONE, body); } diff --git a/packages/spf/src/network/moqt/session.ts b/packages/spf/src/network/moqt/session.ts index 105b4f1d74..e849db2543 100644 --- a/packages/spf/src/network/moqt/session.ts +++ b/packages/spf/src/network/moqt/session.ts @@ -60,9 +60,9 @@ import { type BidirectionalStreamLike, openRequestStream, type RequestStream } f * Structural subset of `WebTransport` the session driver needs. A real `WebTransport` instance satisfies this; tests * provide an in-memory fake (the same seam pattern as SPF's fetch injection). * - * Publish-side fill failure signaling requires writers with WebTransport's `commit()` method, which preserves the - * written prefix across a reset. Support is detected on the control stream's writer and must be consistent across - * outgoing streams. Without it, nonempty fill requests are rejected with NOT_SUPPORTED. + * Publish-side fill failure signaling uses WebTransport's `commit()` writer method where it exists, which preserves the + * written FETCH_HEADER across the reset. Without it the subscription is still served, and the reset that fails the fill + * may discard its header. */ export interface MoqtTransport { readonly incomingUnidirectionalStreams: ReadableStream>; diff --git a/packages/spf/src/network/moqt/tests/publish-direction.test.ts b/packages/spf/src/network/moqt/tests/publish-direction.test.ts index e23394ff33..faf05148f9 100644 --- a/packages/spf/src/network/moqt/tests/publish-direction.test.ts +++ b/packages/spf/src/network/moqt/tests/publish-direction.test.ts @@ -66,6 +66,13 @@ describe('encodePublishDone', () => { reason: 'stopped', }); }); + + it('encodes an unknown stream count as the 2^64−1 sentinel', () => { + const bytes = encodePublishDone(PUBLISH_DONE_STATUS.TRACK_ENDED, undefined); + + expect(bytes.subarray(-10, -1)).toEqual(new Uint8Array(9).fill(0xff)); + expect(decodeOne(bytes)).toMatchObject({ kind: 'publish-done', streamCount: undefined, reason: '' }); + }); }); describe('encodeSubscribeOk', () => { diff --git a/packages/spf/src/publish/actors/tests/track-publisher.test.ts b/packages/spf/src/publish/actors/tests/track-publisher.test.ts index c0228255f4..315535b42a 100644 --- a/packages/spf/src/publish/actors/tests/track-publisher.test.ts +++ b/packages/spf/src/publish/actors/tests/track-publisher.test.ts @@ -338,6 +338,36 @@ describe('createTrackPublisherActor', () => { ]); }); + it('counts the data streams opened under each subscription alias, pruning superseded ones', async () => { + const factory = makeStreamFactory(); + const publisher = createTrackPublisherActor({ openUniStream: factory.openUniStream, groupPerFrame: true }); + const frame = (timestampUs: number) => + ({ type: 'frame', payload: new Uint8Array([1]), properties: [], keyframe: true, timestampUs }) as const; + + // Unbound frames open nothing and count for no one. + publisher.send(frame(0)); + publisher.send({ type: 'bind', trackAlias: 3 }); + publisher.send(frame(1)); + publisher.send(frame(2)); + await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(2)); + + // A Forward State toggle unbinds and rebinds the same alias: its + // count must survive, or PUBLISH_DONE would under-report. + publisher.send({ type: 'unbind' }); + publisher.send({ type: 'bind', trackAlias: 3 }); + publisher.send(frame(3)); + await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(3)); + expect(publisher.streamCount(3)).toBe(3); + + // A new alias supersedes the old subscription, whose count is pruned. + publisher.send({ type: 'bind', trackAlias: 5 }); + publisher.send(frame(4)); + await vi.waitFor(() => expect(counters(publisher).publishedGroups).toBe(4)); + + expect([publisher.streamCount(3), publisher.streamCount(5), publisher.streamCount(7)]).toEqual([0, 1, 0]); + publisher.destroy(); + }); + it('ignores delta frames before the first keyframe', async () => { const factory = makeStreamFactory(); const publisher = createTrackPublisherActor({ openUniStream: factory.openUniStream }); diff --git a/packages/spf/src/publish/actors/track-publisher.ts b/packages/spf/src/publish/actors/track-publisher.ts index b9397d7c47..494bceb4e9 100644 --- a/packages/spf/src/publish/actors/track-publisher.ts +++ b/packages/spf/src/publish/actors/track-publisher.ts @@ -111,6 +111,12 @@ export interface TrackPublisherActor extends MessageActor< * as it is written.) */ flushed(): Promise; + /** + * Data streams opened under the subscription bound as `trackAlias` — PUBLISH_DONE's Stream Count (§10.12). Counted at + * the commit to writing the subgroup header (the `openedGroups` boundary), so a stream reset before its header — one + * the peer cannot attribute to the subscription — is excluded. + */ + streamCount(trackAlias: number): number; } export interface TrackPublisherOptions { @@ -191,6 +197,8 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track let currentGroupFrames: Extract[] = []; /** Detached FIN settlements (see `finishCell`) — `flushed()` waits on them past the runner. */ const pendingFins = new Set>(); + /** Opened data streams per subscription alias (see `streamCount`); pruned to the current alias on each bind. */ + const streamsByAlias = new Map(); // Assigned right after createMachineActor returns; the runner tasks only // complete asynchronously, well after construction. @@ -296,6 +304,7 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track // counting at queue time inflated the opened-stream count with // groups that were dropped before they ever opened one. inner?.send({ type: 'group-opened' }); + streamsByAlias.set(cell.trackAlias, (streamsByAlias.get(cell.trackAlias) ?? 0) + 1); cell.writer = createSubgroupWriter(stream, { trackAlias: cell.trackAlias, groupId: cell.groupId, @@ -521,6 +530,14 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track boundAlias = msg.trackAlias; + // A new alias binds only after the session has ended every + // older subscription on the track, so their counts are dead + // weight. The current alias keeps its count across an unbind + // (a Forward State toggle rebinds the same alias). + for (const alias of streamsByAlias.keys()) { + if (alias !== msg.trackAlias) streamsByAlias.delete(alias); + } + // Instant join: catalog-shaped tracks re-send their latest // change-driven frame (queued behind this message, boundAlias // already set); keyframe-grouped tracks replay the in-progress @@ -590,6 +607,9 @@ export function createTrackPublisherActor(options: TrackPublisherOptions): Track await runner.settled; await Promise.all(pendingFins); }, + streamCount(trackAlias: number): number { + return streamsByAlias.get(trackAlias) ?? 0; + }, destroy(): void { // Every opened stream must end deterministically: the open group // (or the one `{type:'end'}` just closed gracefully) gets a diff --git a/packages/spf/src/publish/behaviors/setup-track-publishers.ts b/packages/spf/src/publish/behaviors/setup-track-publishers.ts index ae966a87b3..9ff117efe6 100644 --- a/packages/spf/src/publish/behaviors/setup-track-publishers.ts +++ b/packages/spf/src/publish/behaviors/setup-track-publishers.ts @@ -20,10 +20,11 @@ * * Cluster-owner reactor per the per-type setup-actor convention: the encoder chunk router (the engine's default * `chunkSink`) and `deriveCatalog` only read the slots — they never create the actors. On session loss, endpoint - * change, or teardown the actors are destroyed in reverse creation order, each track's live subscriptions get their - * clean FIN (`handle.end()`), and the slots are cleared. When the session is still serving at teardown, the broadcast - * is ending on purpose, so the catalog track's last group is the MSF end-of-broadcast catalog (§11.3) — never on a - * session loss, which may yet reconnect and must not mark the broadcast complete. + * change, or teardown the actors are ended in reverse creation order: each track's data streams close first, then its + * live subscriptions get their clean end — PUBLISH_DONE with TRACK_ENDED, then FIN (`handle.end()`) — and the slots are + * cleared. When the session is still serving at teardown, the broadcast is ending on purpose, so the catalog track's + * last group is the MSF end-of-broadcast catalog (§11.3) — never on a session loss, which may yet reconnect and must + * not mark the broadcast complete. * * Sole writer of the track-publisher context slots (the four media slots plus `dataTrackProducers`). Per-stream * failures are deliberately not surfaced as `publishError` anymore: under pull-through ingest the peer resets in-flight @@ -242,10 +243,31 @@ function hasEncoding(encodings: ActiveEncodingsFacts | undefined): boolean { const textEncoder = new TextEncoder(); /** - * End the catalog track with the MSF end-of-broadcast catalog (§11.3: `isComplete`, no tracks) as its last group. The - * subscription FINs wait for that group to land — bounded by the session's close drain window, so a stalled stream - * cannot hold the teardown — and only then is the publisher destroyed. + * How long a track's teardown waits for its last groups to flush. Half the session's close drain window: the + * PUBLISH_DONE that follows still has to reach the wire before the drain closes the transport. */ +const TRACK_FLUSH_TIMEOUT_MS = CLOSE_FLUSH_TIMEOUT_MS / 2; + +/** + * End one track in the order §10.12 requires — every data stream closed before PUBLISH_DONE: `end` FINs the open group, + * the queued groups get a bounded window to flush, `destroy()` FINs or resets whatever is left, and only then does the + * session send each subscription PUBLISH_DONE and its FIN. + */ +function endTrack(handle: RegisteredTrack, publisher: TrackPublisherActor): void { + publisher.send({ type: 'end' }); + + let timer: ReturnType | undefined; + const flushed = Promise.race([ + publisher.flushed(), + new Promise((resolve) => { + timer = setTimeout(resolve, TRACK_FLUSH_TIMEOUT_MS); + }), + ]).finally(() => clearTimeout(timer)); + + handle.end({ after: flushed.then(() => publisher.destroy()) }); +} + +/** End the catalog track with the MSF end-of-broadcast catalog (§11.3: `isComplete`, no tracks) as its last group. */ function endCatalogTrack( handle: RegisteredTrack, publisher: TrackPublisherActor, @@ -259,18 +281,7 @@ function endCatalogTrack( keyframe: true, timestampUs: 0, }); - publisher.send({ type: 'end' }); - - let timer: ReturnType | undefined; - const flushed = Promise.race([ - publisher.flushed(), - new Promise((resolve) => { - timer = setTimeout(resolve, CLOSE_FLUSH_TIMEOUT_MS); - }), - ]).finally(() => clearTimeout(timer)); - - handle.end({ after: flushed }); - void flushed.then(() => publisher.destroy()); + endTrack(handle, publisher); } /** @@ -317,6 +328,9 @@ function addTrackPublisher( return largestGroupId >= 0 ? { group: largestGroupId, object: largestObjectId } : undefined; }, + // ...and the streams it opened per subscription, for the Stream Count + // a track end reports in PUBLISH_DONE (§10.12). + getStreamCount: (trackAlias) => publisher.streamCount(trackAlias), }); cluster.created.push({ handle, publisher, boundAlias: undefined }); @@ -471,14 +485,7 @@ function setupTrackPublishersSetup({ continue; } - // Quiesce: 'end' FINs the open group, then the track's - // live subscriptions get their clean stream FIN (the - // clean track end — no trailing message; a relay - // aborts the track on any post-SUBSCRIBE_OK byte), then - // destroy() force-ends whatever is left. - publisher.send({ type: 'end' }); - handle.end(); - publisher.destroy(); + endTrack(handle, publisher); } }; }, diff --git a/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts b/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts index 84b3bd15a5..248aee5f7a 100644 --- a/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts +++ b/packages/spf/src/publish/behaviors/tests/open-publish-session.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { createComposition } from '../../../core/composition/create-composition'; import { signal } from '../../../core/signals/primitives'; +import { PUBLISH_DONE_STATUS } from '../../../network/moqt/control-messages'; import { createMoqtSession } from '../../../network/moqt/session'; import { type RawRequest, rawSubscribe, solicitNamespace } from '../../../network/moqt/tests/helpers/raw-peer'; import { createTransportPair, type TransportPair } from '../../../network/moqt/tests/helpers/transport-pair'; @@ -217,7 +218,7 @@ describe('openPublishSession', () => { }); // Hold live subscriptions on both tracks so the teardown's clean - // end (a bare stream FIN) is observable, and open one video group + // end (PUBLISH_DONE + FIN) is observable, and open one video group // so an in-flight data stream rides through the teardown too. subscriptions.catalog = await rawSubscribe(pair.server, ENDPOINT.namespace, 'catalog', 11); subscriptions.video = await rawSubscribe(pair.server, ENDPOINT.namespace, 'video', 13); @@ -237,7 +238,17 @@ describe('openPublishSession', () => { return { composition, subscriptions, goLive }; } - it('FINs every track subscription cleanly when the composition is destroyed', async () => { + /** The clean track end: PUBLISH_DONE with TRACK_ENDED, then FIN. Video carried exactly the one group `goLive` sent. */ + function expectTrackEnded(subscriptions: { catalog: RawRequest; video: RawRequest }) { + for (const subscription of [subscriptions.catalog, subscriptions.video]) { + expect(subscription.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); + expect(subscription.received[1]).toMatchObject({ statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED }); + } + + expect(subscriptions.video.received[1]).toMatchObject({ streamCount: 1 }); + } + + it('ends every track subscription cleanly when the composition is destroyed', async () => { const pair = createTransportPair(); const { composition, subscriptions, goLive } = makeTransportStage(pair); @@ -250,13 +261,10 @@ describe('openPublishSession', () => { expect(subscriptions.catalog.ended()).toBe(true); expect(subscriptions.video.ended()).toBe(true); }); - // A bare FIN is the clean track end — any trailing message - // (the old PUBLISH_DONE) makes moq-lite-rs abort the track instead. - expect(subscriptions.catalog.received.map((m) => m.kind)).toEqual(['subscribe-ok']); - expect(subscriptions.video.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expectTrackEnded(subscriptions); }); - it('FINs every track subscription when unpublish collapses the gate', async () => { + it('ends every track subscription cleanly when unpublish collapses the gate', async () => { const pair = createTransportPair(); const { composition, subscriptions, goLive } = makeTransportStage(pair); @@ -268,8 +276,7 @@ describe('openPublishSession', () => { expect(subscriptions.catalog.ended()).toBe(true); expect(subscriptions.video.ended()).toBe(true); }); - expect(subscriptions.catalog.received.map((m) => m.kind)).toEqual(['subscribe-ok']); - expect(subscriptions.video.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expectTrackEnded(subscriptions); // An orderly stop, not a failure. await vi.waitFor(() => { expect(composition.state.sessionStatus.get()).toBe('closed'); diff --git a/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts b/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts index 5849cdf903..9dd4a03f9c 100644 --- a/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts +++ b/packages/spf/src/publish/behaviors/tests/setup-track-publishers.test.ts @@ -333,6 +333,43 @@ describe('setupTrackPublishers', () => { expect(onSubgroupReset).not.toHaveBeenCalled(); }); + it("closes a track's open group before its PUBLISH_DONE (§10.12)", async () => { + const { actor, peer, server } = makeSessionActor(); + const { state, context } = setupBehavior(); + const events: string[] = []; + + state.endpoint.set(ENDPOINT); + state.activeEncodings.set({ camera: VIDEO_CONFIG }); + context.publishSessionActor.set(actor); + void solicitNamespace(server, []); + await vi.waitFor(() => expect(context.videoTrackPublisher.get()).toBeDefined()); + peer.subscribe( + { trackNamespace: ENDPOINT.namespace, trackName: 'video' }, + { + onObject: (object) => events.push(`object g${object.groupId}`), + onSubgroupEnd: ({ groupId }) => events.push(`fin g${groupId}`), + onDone: (done) => events.push(`done status=${done.statusCode} streams=${done.streamCount}`), + } + ); + await vi.waitFor(() => expect(actor.snapshot.get().context.trackBindings.video).toBeDefined()); + // A keyframe opens group 0 and leaves it open — only the next + // keyframe or the track's end FINs it. + context.videoTrackPublisher.get()!.send({ + type: 'frame', + payload: new Uint8Array([1]), + properties: [], + keyframe: true, + timestampUs: 0, + }); + await vi.waitFor(() => expect(events).toEqual(['object g0'])); + + context.publishSessionActor.set(undefined); + actor.destroy(); + + await vi.waitFor(() => expect(events).toHaveLength(3)); + expect(events).toEqual(['object g0', 'fin g0', 'done status=2 streams=1']); + }); + it('never marks the broadcast complete when the session is lost', async () => { const { actor, server, client } = makeSessionActor(); const { state, context } = setupBehavior(); diff --git a/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts b/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts index 99dc918b7e..0e57ca7d9c 100644 --- a/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts +++ b/packages/spf/src/publish/behaviors/tests/track-publish-stats.test.ts @@ -83,7 +83,7 @@ function makePublisher(counters: Partial): TrackPublishe context: { ...ZERO_PUBLISHER_COUNTERS, ...counters }, }); - return { snapshot, send: () => {}, flushed: async () => {}, destroy: () => {} }; + return { snapshot, send: () => {}, flushed: async () => {}, streamCount: () => 0, destroy: () => {} }; } function makeSessionActor(subscriberCount: number): PublishSessionActor { diff --git a/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts b/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts index 873979335a..855f1496db 100644 --- a/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts +++ b/packages/spf/src/publish/engines/moq/tests/cross-engine.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { PUBLISH_DONE_STATUS } from '../../../../network/moqt/control-messages'; import { createRelayHub } from '../../../tests/helpers/relay-hub'; import { createMoqPublishEngine } from '../engine'; import { createSubscriber, makeSyntheticStream } from './helpers/cross-engine-harness'; @@ -219,13 +220,14 @@ describe('publish engine ↔ playback engine (relay hub)', () => { expect(hub.publisherConnections()).toBe(connectionsBeforeScreen); expect(publisher.state.sessionStatus.get()).toBe('live'); - // Orderly unpublish ends every track — now including screen — by - // FINing the hub's subscribe streams (a bare FIN is the clean track - // end; PUBLISH_DONE never appears under announce-and-serve). + // Orderly unpublish ends every track — now including screen — with + // PUBLISH_DONE (TRACK_ENDED) and a FIN on the hub's subscribe streams. publisher.state.publishActivated.set(false); await vi.waitFor( () => { - const endedTracks = hub.trackEnds.filter((end) => end.kind === 'subscribe-fin').map((end) => end.trackName); + const endedTracks = hub.trackEnds + .filter((end) => end.kind === 'track-end' && end.statusCode === PUBLISH_DONE_STATUS.TRACK_ENDED) + .map((end) => (end.kind === 'track-end' ? end.trackName : '')); expect(endedTracks).toContain('video'); expect(endedTracks).toContain('screen'); diff --git a/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts b/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts index 9eb853514b..2db841da2e 100644 --- a/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts +++ b/packages/spf/src/publish/engines/moq/tests/publish-transport.test.ts @@ -221,8 +221,8 @@ describe('MoqPublishMediaMixin transport (M3)', () => { expect(overlay.objects[0]!.objectId).toBe(0); // Unpublish: the announce is retracted with NAMESPACE_DONE on the - // solicitation stream (each subscribe stream ends with a bare FIN — - // PUBLISH_DONE never appears) and the session returns to idle. + // solicitation stream (each subscribe stream ends with PUBLISH_DONE + // and a FIN) and the session returns to idle. media.unpublish(); await vi.waitFor( () => { diff --git a/packages/spf/src/publish/session/publish-session.ts b/packages/spf/src/publish/session/publish-session.ts index 769e2bfd49..9424d1f32f 100644 --- a/packages/spf/src/publish/session/publish-session.ts +++ b/packages/spf/src/publish/session/publish-session.ts @@ -12,11 +12,12 @@ * (upstream `de336492`: every PUBLISH is answered with a request error), and it solicits namespaces itself — one * SUBSCRIBE_NAMESPACE per authorized prefix, sent immediately after SETUP. Announcing rides the solicitation stream as * NAMESPACE entries (suffix-relative, parameterless — the relay treats even an empty parameter count as malformed); - * data flows only on aliases bound by our own SUBSCRIBE_OKs, per subscription. Three hard-won peer constraints shape - * the teardown paths: a subscription ends by FIN alone (any byte after SUBSCRIBE_OK — a PUBLISH_DONE, say — makes the - * relay abort the track for every viewer instead of finishing it), a client-sent GOAWAY closes the whole session (code - * 17), and a track alias bound to two live request IDs closes it too (code 12) — so aliases are the peer's own request - * IDs, unique by construction. + * data flows only on aliases bound by our own SUBSCRIBE_OKs, per subscription. A track end sends each subscription + * PUBLISH_DONE (TRACK_ENDED, with the exact count of data streams it received) and then FINs it — moq-relay 0.17.0 + * forwards that downstream as "track ended", where a bare FIN reaches viewers as "internal error" (older moq-relay + * builds abort the track on any byte after SUBSCRIBE_OK; they are not supported). Two more hard-won peer constraints + * shape the teardown paths: a client-sent GOAWAY closes the whole session (code 17), and a track alias bound to two + * live request IDs closes it too (code 12) — so aliases are the peer's own request IDs, unique by construction. * * Deliberately callback-shaped with NO signals, mirroring the subscribe driver — signal awareness enters at the * `publish/` behavior layer through the actor below. Lives in `publish/` rather than `network/moqt` so the parent-owned @@ -32,6 +33,7 @@ import { decodeControlMessage, encodeNamespace, encodeNamespaceDone, + encodePublishDone, encodeRequestError, encodeRequestOk, encodeSetup, @@ -41,6 +43,7 @@ import { type KeyValuePair, type Location, MESSAGE_TYPE, + PUBLISH_DONE_STATUS, type MessageParameters, MOQT_PROTOCOL_ID, REQUEST_ERROR_CODE, @@ -118,13 +121,18 @@ export interface RegisterTrackOptions { * parameter is left off. */ getLargestObject?: () => Location | undefined; + /** + * Data streams opened under the subscription with this alias — the PUBLISH_DONE Stream Count (§10.12) the track's end + * reports, plus the fill streams the session opens itself. Omitted, the count is reported as unknown (2^64−1). + */ + getStreamCount?: (trackAlias: number) => number; } export interface RegisteredTrack { readonly trackName: string; /** - * End the track: FIN every live subscription's request stream (a FIN with no trailing bytes is the clean track end) - * and refuse future SUBSCRIBEs with DOES_NOT_EXIST. Idempotent. + * End the track: send every live subscription PUBLISH_DONE with TRACK_ENDED and its Stream Count, FIN its request + * stream, and refuse future SUBSCRIBEs with DOES_NOT_EXIST. Idempotent. * * `after` holds the FINs (not the refusal) until it settles, so a last object still in flight — the MSF * end-of-broadcast catalog — reaches subscribers before their subscription ends. An orderly `close()` waits on it @@ -171,7 +179,10 @@ export const CLOSE_FLUSH_TIMEOUT_MS = 250; interface SubscriberStream { requestId: number; trackAlias: number; + /** Bare FIN — ends a subscription the peer superseded, which is not a track end. */ fin(): Promise; + /** PUBLISH_DONE, then FIN — the track ended (§10.12). */ + done(statusCode: number, streamCount: number | undefined): Promise; cancel(): Promise; /** SUBSCRIBE_OK reached the wire — only accepted subscriptions may carry the binding. */ accepted: boolean; @@ -182,6 +193,8 @@ interface SubscriberStream { finished: boolean; /** Includes pending stream opens, so cancellation also catches late arrivals. */ fills: Set; + /** Fill streams opened for this subscription — they count toward PUBLISH_DONE's Stream Count. */ + fillStreams: number; } interface FillStream { @@ -203,6 +216,8 @@ interface TrackRecord { doneFlushed?: Promise; /** Reads the track's Largest Object for responses (see `RegisterTrackOptions.getLargestObject`). */ getLargestObject?: () => Location | undefined; + /** Reads a subscription's data-stream count (see `RegisterTrackOptions.getStreamCount`). */ + getStreamCount?: (trackAlias: number) => number; } /** One accepted inbound SUBSCRIBE_NAMESPACE — the announce carrier. */ @@ -358,11 +373,11 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { } /** - * Orderly close: closing the transport discards queued data (WebTransport semantics), so the subscription FINs and - * NAMESPACE_DONE retractions must be given a bounded window to land first — a peer should observe every track ending - * cleanly, not an abrupt transport end. Neither GOAWAY nor PUBLISH_DONE is sent: moq-lite-rs closes the session on a - * client GOAWAY, and treats any post-SUBSCRIBE_OK byte on a subscribe stream as an error that aborts the track (see - * the module doc). + * Orderly close: closing the transport discards queued data (WebTransport semantics), so the track ends (PUBLISH_DONE + * + * - FIN per subscription) and NAMESPACE_DONE retractions must be given a bounded window to land first — a peer should + * observe every track ending cleanly, not an abrupt transport end. No GOAWAY is sent: moq-lite-rs closes the + * session on a client GOAWAY (see the module doc). */ async #drainAndClose(closeCode: number, reason: string): Promise { // One macrotask beat before the last-resort sweep below: track owners @@ -501,6 +516,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { done: false, pendingFins: [], getLargestObject: options.getLargestObject, + getStreamCount: options.getStreamCount, }; this.#tracks.set(track.key, track); @@ -520,9 +536,9 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { } /** - * FIN every live subscription's request stream — with no trailing bytes, which is the clean track end — and refuse - * future SUBSCRIBEs. The aggregated write completion lands on `track.doneFlushed` so `close()` can hold the transport - * open until the FINs reach the wire. + * End every live subscription with PUBLISH_DONE (TRACK_ENDED) and a FIN, and refuse future SUBSCRIBEs. The aggregated + * write completion lands on `track.doneFlushed` so `close()` can hold the transport open until the ends reach the + * wire. */ #endTrack(track: TrackRecord, after?: Promise): void { if (track.done) return; @@ -547,7 +563,13 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { for (const subscriber of track.subscribers) { if (!subscriber.finished) { subscriber.finished = true; - writes.push(subscriber.fin().catch(() => {})); + // Read at the end, not at subscribe time: the count must cover + // every stream the subscription received (§10.12). + const streamCount = track.getStreamCount + ? track.getStreamCount(subscriber.trackAlias) + subscriber.fillStreams + : undefined; + + writes.push(subscriber.done(PUBLISH_DONE_STATUS.TRACK_ENDED, streamCount).catch(() => {})); } // The local end is authoritative: report each live subscription @@ -621,8 +643,15 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { * Answer a nonempty fill request (see `#fillRequested`). This origin serves no fills, so it meets the §5.1.3.1 * requirement the honest way: open a uni stream, write the FETCH_HEADER carrying the initiating Request ID so the * subscriber can correlate the failure, then reset it. A reset is the fill-failure signal — a FIN would falsely claim - * the fill range was delivered in full. Moq-relay 0.14.17 requests the current group this way; the reliable reset - * keeps that join from waiting on a fill that never arrives. + * the fill range was delivered in full. Moq-relay requests the current group this way (0.14.17 through 0.17.0) on + * every upstream SUBSCRIBE once the track has content. + * + * The header survives the reset only where the writer has WebTransport's `commit()` (RESET_STREAM_AT's reliable + * prefix). Without it (Chromium as of 147) the subscription is still served: the reset may discard the header, and + * the subscriber then sees no fill at all — which, like a failed one, leaves its join at the next group boundary. + * Refusing the SUBSCRIBE instead would fail every relay's second pull of a live track (the real subscribe after a + * cross-relay TRACK_INFO probe, or any re-subscribe after the last viewer left), so nothing would play across a relay + * mesh. */ #openAndResetFill(requestId: number, subscriber: SubscriberStream): void { const fill: FillStream = {}; @@ -638,19 +667,26 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { if (!subscriber.fills.has(fill) || subscriber.finished) return; - // All WebTransport writers expose the same capabilities, probed - // on the control writer before accepting a nonempty fill. Check - // this stream too so an inconsistent injected transport never - // writes a header it cannot preserve through the reset. - if (!hasMethods(writer, ['commit'])) return; - + // PUBLISH_DONE's Stream Count includes fill fetch streams + // (§10.12). Count in the same synchronous step that commits this + // stream to its FETCH_HEADER — the track publisher's rule for + // subgroup streams — so any PUBLISH_DONE covers every fill that + // carries a header. A fill still opening when the track ended + // was stopped by the guard above: it is reset with no header, so + // the subscriber cannot attribute it to this subscription and + // leaving it uncounted cannot put the subscriber over the count. + // A counted fill whose reset discards its header (no commit()) + // or whose write rejects over-counts by one; for that §10.12 has + // the subscriber fall back to a timeout. + subscriber.fillStreams++; await writer.write(encodeFetchHeader(requestId)); if (!subscriber.fills.has(fill) || subscriber.finished) return; // write() only hands bytes to the transport. commit() includes - // them in the reliable prefix of RESET_STREAM_AT. - writer.commit(); + // them in the reliable prefix of RESET_STREAM_AT; without it the + // reset below is best-effort for the header. + if (hasMethods(writer, ['commit'])) writer.commit(); } catch { // Session closing or the peer went away before the header landed. } finally { @@ -985,6 +1021,11 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { this.#resetFills(subscriber); return writer.close(); }, + done: async (statusCode, streamCount) => { + this.#resetFills(subscriber); + await writer.write(encodePublishDone(statusCode, streamCount)); + await writer.close(); + }, cancel: async () => { subscriber.finished = true; this.#resetFills(subscriber); @@ -1003,6 +1044,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { forwarding: subscribe.parameters.forward !== 0, finished: false, fills: new Set(), + fillStreams: 0, }; // Use one snapshot for both the response and its fill range, even if @@ -1015,18 +1057,6 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { subscribe.parameters.fillParameters ); - if (fillRequested && !hasMethods(this.#controlWriter, ['commit'])) { - try { - await writer.write(encodeRequestError(REQUEST_ERROR_CODE.NOT_SUPPORTED, 'fill requires reliable stream reset')); - await writer.close(); - } catch { - // Peer cancelled. - } - - await reader.cancel(); - return; - } - track.subscribers.push(subscriber); // STOP_SENDING on the response direction cancels the subscription @@ -1137,7 +1167,6 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { // here, immediately resets) a fill fetch stream keyed by the // update's own Request ID (§5.1.3.1); an empty range opens none. const fillRequested = this.#fillRequested(largestObject, subscriber, subscribe.parameters, fillParameters); - const unsupportedFill = fillRequested && !hasMethods(this.#controlWriter, ['commit']); this.#callbacks.onRequestUpdate?.({ requestId: subscribe.requestId, @@ -1146,7 +1175,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { }); if (!subscriber.finished) { - if (Object.keys(unsupported).length > 0 || unsupportedFill) { + if (Object.keys(unsupported).length > 0) { // Acknowledging an update we did not apply would leave the // peer serving stale expectations (a filter or range it // believes is in effect). Forward State is applied above @@ -1169,8 +1198,7 @@ class MoqtPublishSessionImpl implements MoqtPublishSession { } else { // The subscribe driver treats REQUEST_OK as the update's // completion (`onUpdateOk`). Strictly reactive: a peer that - // never sends REQUEST_UPDATE (moq-lite-rs parks on end-of- - // stream after SUBSCRIBE_OK) never sees a trailing byte. + // never sends REQUEST_UPDATE sees nothing here. void writer.write(encodeRequestOk(largestObject ? { largestObject } : {})).catch(() => {}); if (fillRequested) this.#openAndResetFill(message.requestId, subscriber); diff --git a/packages/spf/src/publish/session/tests/publish-session.test.ts b/packages/spf/src/publish/session/tests/publish-session.test.ts index de352ea07f..099e38f975 100644 --- a/packages/spf/src/publish/session/tests/publish-session.test.ts +++ b/packages/spf/src/publish/session/tests/publish-session.test.ts @@ -14,6 +14,7 @@ import { encodeRequestUpdate, encodeSetup, encodeSubscribe, + PUBLISH_DONE_STATUS, REQUEST_ERROR_CODE, SETUP_OPTION, TRACK_PROPERTY, @@ -79,9 +80,11 @@ function collectTrack( async function makeFillHarness({ reliableReset = true, openFillStream, + callbacks, }: { reliableReset?: boolean; openFillStream?: () => Promise>; + callbacks?: MoqtPublishSessionCallbacks; } = {}) { const pair = createTransportPair(); const openUniStream = pair.client.createUnidirectionalStream.bind(pair.client); @@ -101,7 +104,7 @@ async function makeFillHarness({ return stream; }; - const session = createMoqtPublishSession(pair.client); + const session = createMoqtPublishSession(pair.client, { callbacks }); const fills: { requestId: number; reset: boolean }[] = []; const streams = pair.server.incomingUnidirectionalStreams.getReader(); @@ -145,8 +148,11 @@ async function makeFillHarness({ }; } -/** A buffered send stream: reset discards everything except the explicitly committed prefix. */ -function makeBufferedFillStream() { +/** + * A buffered send stream: reset discards everything except the explicitly committed prefix. Without `reliableReset` the + * writer has no `commit()` — a browser WebTransport today — so a reset discards everything still unread. + */ +function makeBufferedFillStream({ reliableReset = true }: { reliableReset?: boolean } = {}) { const chunks: Uint8Array[] = []; let committed = 0; let readIndex = 0; @@ -187,12 +193,14 @@ function makeBufferedFillStream() { }); const getWriter = writable.getWriter.bind(writable); - writable.getWriter = () => - Object.assign(getWriter(), { - commit() { - committed = chunks.length; - }, - }); + if (reliableReset) { + writable.getWriter = () => + Object.assign(getWriter(), { + commit() { + committed = chunks.length; + }, + }); + } return { writable, readable, reset: () => reset }; } @@ -534,7 +542,7 @@ describe('createMoqtPublishSession', () => { subscriber.destroy(); }); - it('ends a track by FINing its subscription streams with no trailing message', async () => { + it('ends a track with PUBLISH_DONE (TRACK_ENDED and the stream count), then FIN', async () => { const endedRequests: number[] = []; const bindings: (number | undefined)[] = []; const { pair, session, subscriber } = makePublishHarness({ @@ -543,7 +551,11 @@ describe('createMoqtPublishSession', () => { }); await session.ready; - const track = session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'video' }); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getStreamCount: (trackAlias) => (trackAlias === 21 ? 4 : 0), + }); const subscribe = await rawSubscribe(pair.server, 'video', 21); @@ -560,10 +572,10 @@ describe('createMoqtPublishSession', () => { await vi.waitFor(() => { expect(subscribe.ended()).toBe(true); }); - // A bare FIN is the clean track end. Any byte after - // SUBSCRIBE_OK — the old PUBLISH_DONE — makes moq-lite-rs abort the - // track for every downstream viewer instead of finishing it. - expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + // moq-relay 0.17.0 forwards this as "track ended"; a bare FIN + // reaches viewers as "internal error". + expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); + expect(subscribe.received[1]).toMatchObject({ statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, streamCount: 4 }); // The peer closing its side afterwards must not double-report. void subscribe.fin(); @@ -600,7 +612,13 @@ describe('createMoqtPublishSession', () => { await vi.waitFor(() => { expect(subscribe.ended()).toBe(true); }); - expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + // No stream-count source registered: the count is the 2^64−1 + // "unknown" sentinel, which decodes as undefined. + expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); + expect(subscribe.received[1]).toMatchObject({ + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: undefined, + }); subscriber.destroy(); }); @@ -1088,6 +1106,45 @@ describe('createMoqtPublishSession', () => { await finish(); }); + it('counts fill fetch streams in the PUBLISH_DONE Stream Count (§10.12)', async () => { + const { pair, session, fills, finish } = await makeFillHarness(); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getLargestObject: () => ({ group: 4, object: 2 }), + getStreamCount: () => 3, + }); + const request = await openRawRequest( + pair.server, + encodeSubscribe({ + requestId: 207, + trackNamespace: NAMESPACE, + trackName: 'video', + parameters: { + forward: 1, + locationFilter: { type: 'next-object' }, + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + }, + }) + ); + + await vi.waitFor(() => { + expect(fills).toEqual([{ requestId: 207, reset: true }]); + }); + + track.end(); + await vi.waitFor(() => { + expect(request.ended()).toBe(true); + }); + // Three data streams from the track publisher plus the reset fill. + expect(request.received.at(-1)).toMatchObject({ + kind: 'publish-done', + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: 4, + }); + await finish(); + }); + it('opens no fill fetch stream for an empty fill range (§5.1.3)', async () => { const { pair, session, fills, finish } = await makeFillHarness(); let largest: { group: number; object: number } | undefined; @@ -1270,39 +1327,230 @@ describe('createMoqtPublishSession', () => { await finish(); }); - it('rejects nonempty fills without reliable reset support while allowing ordinary subscriptions', async () => { - const { pair, session, fills, finish } = await makeFillHarness({ reliableReset: false }); + it.each([{ reliableReset: true }, { reliableReset: false }])( + 'leaves a fill still opening when the track ends out of the Stream Count, headerless (reliable reset: $reliableReset)', + async ({ reliableReset }) => { + let resolveOpen!: (stream: WritableStream) => void; + const openFillStream = vi.fn( + () => + new Promise>((resolve) => { + resolveOpen = resolve; + }) + ); + const { pair, session, finish } = await makeFillHarness({ reliableReset, openFillStream }); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getLargestObject: () => ({ group: 4, object: 2 }), + getStreamCount: () => 3, + }); + const sub = await rawSubscribe(pair.server, 'video', 245); + + await vi.waitFor(() => expect(sub.received[0]?.kind).toBe('subscribe-ok')); + await sub.send(encodeRequestUpdate(247, { fillParameters: {} })); + await vi.waitFor(() => expect(openFillStream).toHaveBeenCalledOnce()); + + // The track ends while the fill's stream is still opening. + track.end(); + await vi.waitFor(() => expect(sub.ended()).toBe(true)); + + const write = vi.fn(); + const abort = vi.fn(); + + resolveOpen(new WritableStream({ write, abort })); + await vi.waitFor(() => expect(abort).toHaveBeenCalledOnce()); + + // A fill is counted in the same step that commits it to its + // FETCH_HEADER, as the track publisher counts subgroup streams. + // This one opened after PUBLISH_DONE, so it gets no header and is + // reset bare: the peer cannot attribute it to the subscription, so + // leaving it out of the count cannot put the peer over it. + expect(write).not.toHaveBeenCalled(); + expect(sub.received.at(-1)).toMatchObject({ + kind: 'publish-done', + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: 3, + }); + await finish(); + } + ); + + it.each([{ probeEnds: 'before' }, { probeEnds: 'after' }])( + "serves a relay's second pull of a live track without reliable reset support (probe ends $probeEnds the pull)", + async ({ probeEnds }) => { + const bindings: (number | undefined)[] = []; + const ended: number[] = []; + const { pair, session, fills, finish } = await makeFillHarness({ + reliableReset: false, + callbacks: { + onTrackBinding: ({ trackAlias }) => bindings.push(trackAlias), + onSubscribeEnd: ({ requestId }) => ended.push(requestId), + }, + }); + let largest: { group: number; object: number } | undefined; + + session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'catalog', getLargestObject: () => largest }); + + // Moq-relay's upstream SUBSCRIBE (0.14.17 through 0.17.0): Next Object, + // plus a fill of the current group's head. + const relayPull = (requestId: number) => + openRawRequest( + pair.server, + encodeSubscribe({ + requestId, + trackNamespace: NAMESPACE, + trackName: 'catalog', + parameters: { + forward: 1, + subscriberPriority: 128, + locationFilter: { type: 'next-object' }, + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + groupOrder: 'descending', + includeProperties: 1, + }, + }) + ); + + // A cross-relay viewer's first pull is the relay's TRACK_INFO probe: + // nothing published yet, so there is nothing to fill. + const probe = await relayPull(235); + + await vi.waitFor(() => expect(probe.received.map((m) => m.kind)).toEqual(['subscribe-ok'])); + + // The probe's bind put the catalog on the wire, then the relay + // cancelled it and pulled again for the viewer — now with a nonempty + // fill this transport cannot fail reliably. The pull is served anyway. + largest = { group: 0, object: 0 }; + + if (probeEnds === 'before') await probe.reset(); + + const pull = await relayPull(237); + + await vi.waitFor(() => { + expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expect(bindings.at(-1)).toBe(237); + expect(fills).toEqual([{ requestId: 237, reset: true }]); + }); + + // The probe's end may be handled after the pull is bound: it reports + // the newest live binding, not an unbind, so the pull keeps it. + if (probeEnds === 'after') await probe.reset(); + + await vi.waitFor(() => expect(ended).toContain(235)); + expect(bindings.at(-1)).toBe(237); + expect(pull.ended()).toBe(false); + + // A fill requested by REQUEST_UPDATE is acknowledged and failed the same way. + await pull.send( + encodeRequestUpdate(239, { + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + }) + ); + await vi.waitFor(() => { + expect(pull.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'request-ok']); + expect(fills).toEqual([ + { requestId: 237, reset: true }, + { requestId: 239, reset: true }, + ]); + }); + expect(pull.ended()).toBe(false); + await finish(); + } + ); + + it('still resets the fill when the reset may discard its header (no reliable reset)', async () => { + const fill = makeBufferedFillStream({ reliableReset: false }); + const { pair, session, finish } = await makeFillHarness({ + reliableReset: false, + openFillStream: async () => fill.writable, + }); session.registerTrack({ trackNamespace: NAMESPACE, trackName: 'video', getLargestObject: () => ({ group: 4, object: 2 }), }); - const rejected = await openRawRequest( + const sub = await openRawRequest( pair.server, encodeSubscribe({ - requestId: 235, + requestId: 241, trackNamespace: NAMESPACE, trackName: 'video', parameters: { fillParameters: {} }, }) ); - await vi.waitFor(() => expect(rejected.ended()).toBe(true)); - expect(rejected.received).toMatchObject([{ kind: 'request-error', errorCode: REQUEST_ERROR_CODE.NOT_SUPPORTED }]); + await vi.waitFor(() => { + expect(sub.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expect(fill.reset()).toBeDefined(); + }); - const sub = await rawSubscribe(pair.server, 'video', 237); + // Nothing preserved the header through the reset: the peer sees only + // the reset, and the subscription is unaffected. + const reader = new StreamReader(fill.readable); - await vi.waitFor(() => expect(sub.received[0]?.kind).toBe('subscribe-ok')); - await sub.send(encodeRequestUpdate(239, { fillParameters: { locationFilter: { type: 'next-object' } } })); - await vi.waitFor(() => expect(sub.received[1]?.kind).toBe('request-ok')); - await sub.send(encodeRequestUpdate(241, { fillParameters: {} })); - await vi.waitFor(() => expect(sub.ended()).toBe(true)); - expect(sub.received[2]).toMatchObject({ kind: 'request-error', errorCode: REQUEST_ERROR_CODE.NOT_SUPPORTED }); - expect(fills).toEqual([]); + await expect(reader.readVarint()).rejects.toThrow('fill fetch streams are not served'); + expect(sub.ended()).toBe(false); await finish(); }); + it.each([{ headerSurvives: true }, { headerSurvives: false }])( + 'counts a fill reset without reliable reset in the PUBLISH_DONE Stream Count (header survives: $headerSurvives)', + async ({ headerSurvives }) => { + const buffered = makeBufferedFillStream({ reliableReset: false }); + const { pair, session, fills, finish } = await makeFillHarness({ + reliableReset: false, + openFillStream: headerSurvives ? undefined : async () => buffered.writable, + }); + const track = session.registerTrack({ + trackNamespace: NAMESPACE, + trackName: 'video', + getLargestObject: () => ({ group: 4, object: 2 }), + getStreamCount: () => 3, + }); + const sub = await openRawRequest( + pair.server, + encodeSubscribe({ + requestId: 243, + trackNamespace: NAMESPACE, + trackName: 'video', + parameters: { fillParameters: {} }, + }) + ); + + await vi.waitFor(() => { + expect(sub.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + + if (headerSurvives) expect(fills).toEqual([{ requestId: 243, reset: true }]); + else expect(buffered.reset()).toBeDefined(); + }); + + if (!headerSurvives) { + // The peer saw only the reset, so it cannot tell the stream + // belonged to this subscription. + await expect(new StreamReader(buffered.readable).readVarint()).rejects.toThrow( + 'fill fetch streams are not served' + ); + } + + track.end(); + await vi.waitFor(() => { + expect(sub.ended()).toBe(true); + }); + // §10.12 counts the streams the publisher opened, fill fetch + // streams included: three from the track publisher plus the fill, + // whether or not its header outlived the reset. A subscriber waits + // out a timeout for a stream reset before its header, but one that + // receives more streams than the count may close the session. + expect(sub.received.at(-1)).toMatchObject({ + kind: 'publish-done', + statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, + streamCount: 4, + }); + await finish(); + } + ); + it('rejects a subscription update it cannot apply instead of acknowledging it', async () => { const endedRequests: number[] = []; const bindings: (number | undefined)[] = []; @@ -1432,12 +1680,12 @@ describe('createMoqtPublishSession', () => { session.close(); await vi.waitFor(() => { - // The announce is retracted and the subscription FINed cleanly - // before the transport goes away. + // The announce is retracted and the track ended cleanly before the + // transport goes away. expect(solicitation.received.map((m) => m.kind)).toEqual(['request-ok', 'namespace', 'namespace-done']); expect(subscribe.ended()).toBe(true); }); - expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok']); + expect(subscribe.received.map((m) => m.kind)).toEqual(['subscribe-ok', 'publish-done']); expect(controlFrames.map((m) => m.kind)).toEqual(['setup']); }); diff --git a/packages/spf/src/publish/tests/helpers/relay-hub.ts b/packages/spf/src/publish/tests/helpers/relay-hub.ts index a1bb7925bb..bca23d1027 100644 --- a/packages/spf/src/publish/tests/helpers/relay-hub.ts +++ b/packages/spf/src/publish/tests/helpers/relay-hub.ts @@ -8,8 +8,8 @@ * one upstream SUBSCRIBE per track (downstream demand dedupes onto it), with the publisher's SUBSCRIBE_OK assigning the * alias its subgroup data streams carry. A proactive PUBLISH is answered with REQUEST_ERROR 400 "PUBLISH is not * supported" exactly like the real relay, so a regression to the old ingest model fails loudly. The publisher ends a - * track by FINing the hub's SUBSCRIBE stream — no PUBLISH_DONE ever arrives — and retracts a namespace with - * NAMESPACE_DONE; both land in `trackEnds`, the churn signal the source-switch regression tests assert on. + * track with PUBLISH_DONE and a FIN on the hub's SUBSCRIBE stream, and retracts a namespace with NAMESPACE_DONE; both + * land in `trackEnds`, the churn signal the source-switch regression tests assert on. * * Subscriber side (`connectSubscriber`): answers SUBSCRIBE with SUBSCRIBE_OK (carrying LARGEST_OBJECT once the track * has content) and forwards objects one-per-subgroup-stream, resolving the request's Location Filter (draft-20 §5.1.2) @@ -17,8 +17,9 @@ * (catalog joins), `relative-group 0` forwards only groups that start after the subscribe (video joins), and * `next-object` is strict: nothing already published is replayed (audio joins). FETCH is answered with REQUEST_ERROR; * the draft-20 player never sends one. A downstream subscribe registers standing upstream demand for its track; an - * upstream FIN ends the track's downstream subscriptions with PUBLISH_DONE, the way a real relay ends the track for - * every viewer. + * upstream end ends the track's downstream subscriptions with PUBLISH_DONE, the way a real relay ends the track for + * every viewer — forwarding the publisher's status like moq-relay 0.17.0, which reports a bare FIN (no PUBLISH_DONE) as + * INTERNAL_ERROR. * * Tracks and demand persist across publisher sessions (a reconnecting publisher is re-solicited and its demanded tracks * re-subscribed), so the hub can also observe teardown/reconnect churn instead of crashing on it. @@ -83,12 +84,12 @@ interface TrackRecord { } /** - * One upstream end observed from the publisher. Under announce-and-serve there is no PUBLISH_DONE: a bare FIN on the - * hub's SUBSCRIBE stream is the clean track end, and NAMESPACE_DONE retracts an announce. These replace the old - * `publishDones` as the source-switch churn signal. + * One upstream end observed from the publisher: a track's SUBSCRIBE stream ending cleanly (with the PUBLISH_DONE that + * preceded the FIN, if any — `statusCode` is `undefined` for a bare FIN), or NAMESPACE_DONE retracting an announce. The + * source-switch churn signal. */ export type ObservedTrackEnd = - | { kind: 'subscribe-fin'; trackName: string } + | { kind: 'track-end'; trackName: string; statusCode: number | undefined; streamCount?: number | undefined } | { kind: 'namespace-done'; namespace: TrackNamespace }; export interface RelayHub { @@ -177,6 +178,11 @@ export function createRelayHub( options: { /** Delay individual downstream object streams to exercise jitter and late arrivals. */ deliveryDelayMs?: (trackName: string, object: Readonly) => number; + /** + * Give the publisher's stream writers WebTransport's `commit()` (RESET_STREAM_AT). Default `true`; `false` models + * the browsers that ship WebTransport without it (Chromium 147). + */ + reliableReset?: boolean; } = {} ): RelayHub { let destroyed = false; @@ -253,7 +259,8 @@ export function createRelayHub( // These zero-buffer pipes settle writes only after the peer reads // them, so the reliable prefix is already delivered at commit time. - stream.getWriter = () => Object.assign(getWriter(), { commit() {} }); + if (options.reliableReset !== false) stream.getWriter = () => Object.assign(getWriter(), { commit() {} }); + return stream; }; @@ -308,8 +315,8 @@ export function createRelayHub( /** * Pull one announced track: a fresh bidi stream per SUBSCRIBE, alias recorded from the publisher's SUBSCRIBE_OK, - * held open until one side ends it. A bare FIN from the publisher is the clean track end — recorded as churn, and - * forwarded to the track's downstream subscribers as PUBLISH_DONE the way a real relay ends the track. + * held open until one side ends it. The publisher's FIN (after its PUBLISH_DONE) is the track end — recorded as + * churn, and forwarded to the track's downstream subscribers as PUBLISH_DONE the way a real relay ends the track. */ const subscribeUpstream = (trackName: string): void => { if (destroyed || connectionClosed || upstreamTracks.has(trackName)) return; @@ -325,6 +332,7 @@ export function createRelayHub( nextRequestId += 2; const track = trackFor(trackName); let accepted = false; + let publishDone: Extract | undefined; try { await writer.write( @@ -352,6 +360,8 @@ export function createRelayHub( if (message.kind === 'subscribe-ok') { accepted = true; aliasToTrack.set(message.trackAlias, track); + } else if (message.kind === 'publish-done') { + publishDone = message; } else if (message.kind === 'request-error') { // DOES_NOT_EXIST usually means the demand raced the // publisher's registerTrack — retry while the demand stands @@ -365,9 +375,16 @@ export function createRelayHub( } if (accepted) { - trackEnds.push({ kind: 'subscribe-fin', trackName }); + trackEnds.push({ + kind: 'track-end', + trackName, + statusCode: publishDone?.statusCode, + streamCount: publishDone?.streamCount, + }); + + const status = publishDone?.statusCode ?? PUBLISH_DONE_STATUS.INTERNAL_ERROR; - for (const subscriber of [...track.subscribers]) subscriber.end(PUBLISH_DONE_STATUS.TRACK_ENDED); + for (const subscriber of [...track.subscribers]) subscriber.end(status); track.subscribers.clear(); } diff --git a/packages/spf/src/publish/tests/relay-hub.test.ts b/packages/spf/src/publish/tests/relay-hub.test.ts index 80be5135f4..e0033621a3 100644 --- a/packages/spf/src/publish/tests/relay-hub.test.ts +++ b/packages/spf/src/publish/tests/relay-hub.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vite-plus/test'; +import { PUBLISH_DONE_STATUS } from '../../network/moqt/control-messages'; import { createSubgroupWriter } from '../../network/moqt/subgroup-writer'; import { createMoqtPublishSession } from '../session/publish-session'; import { createRelayHub } from './helpers/relay-hub'; @@ -9,54 +10,61 @@ import { createRelayHub } from './helpers/relay-hub'; * cross-engine suites are too coarse to pin down. */ describe('createRelayHub', () => { - it.each([false, true])('follows live after a relay 0.14.17 pull (existing content: %s)', async (hasContent) => { - const hub = createRelayHub(); - const { transport } = hub.connectPublisher({ url: 'https://relay.test/moq', namespace: ['live'] }); - const onSubscribe = vi.fn(); - const onTrackBinding = vi.fn(); - const onClosed = vi.fn(); - const session = createMoqtPublishSession(transport, { callbacks: { onSubscribe, onTrackBinding, onClosed } }); + it.each([ + { hasContent: false, reliableReset: true }, + { hasContent: true, reliableReset: true }, + { hasContent: true, reliableReset: false }, + ])( + 'follows live after a relay 0.14.17 pull (existing content: $hasContent, reliable reset: $reliableReset)', + async ({ hasContent, reliableReset }) => { + const hub = createRelayHub({ reliableReset }); + const { transport } = hub.connectPublisher({ url: 'https://relay.test/moq', namespace: ['live'] }); + const onSubscribe = vi.fn(); + const onTrackBinding = vi.fn(); + const onClosed = vi.fn(); + const session = createMoqtPublishSession(transport, { callbacks: { onSubscribe, onTrackBinding, onClosed } }); - try { - await session.ready; - session.announce(['live']); - session.registerTrack({ - trackNamespace: ['live'], - trackName: 'video', - getLargestObject: () => (hasContent ? { group: 255, object: 128 } : undefined), - }); - hub.subscribeUpstream('video'); - await vi.waitFor(() => { - expect(onSubscribe).toHaveBeenCalledWith( - expect.objectContaining({ - parameters: expect.objectContaining({ - subscriberPriority: 255, - locationFilter: { type: 'next-object' }, - fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, - }), - }) - ); - expect(onTrackBinding).toHaveBeenCalledWith({ trackName: 'video', trackAlias: expect.any(Number) }); - expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); - }); + try { + await session.ready; + session.announce(['live']); + session.registerTrack({ + trackNamespace: ['live'], + trackName: 'video', + getLargestObject: () => (hasContent ? { group: 255, object: 128 } : undefined), + }); + hub.subscribeUpstream('video'); + await vi.waitFor(() => { + expect(onSubscribe).toHaveBeenCalledWith( + expect.objectContaining({ + parameters: expect.objectContaining({ + subscriberPriority: 255, + locationFilter: { type: 'next-object' }, + fillParameters: { locationFilter: { type: 'relative-group', groupsBeforeNext: 1 } }, + }), + }) + ); + expect(onTrackBinding).toHaveBeenCalledWith({ trackName: 'video', trackAlias: expect.any(Number) }); + expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); + }); - const trackAlias = onTrackBinding.mock.calls[0]![0].trackAlias; - const stream = createSubgroupWriter(await session.openUniStream(), { - trackAlias, - groupId: 256, - endOfGroup: true, - }); + const trackAlias = onTrackBinding.mock.calls[0]![0].trackAlias; + const stream = createSubgroupWriter(await session.openUniStream(), { + trackAlias, + groupId: 256, + endOfGroup: true, + }); - await stream.writeObject({ objectId: 0, payload: Uint8Array.of(1, 2, 3) }); - await stream.fin(); - await vi.waitFor(() => expect(hub.objectCount('video')).toBe(1)); - expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); - expect(onClosed).not.toHaveBeenCalled(); - } finally { - session.destroy(); - hub.destroy(); + await stream.writeObject({ objectId: 0, payload: Uint8Array.of(1, 2, 3) }); + await stream.fin(); + await vi.waitFor(() => expect(hub.objectCount('video')).toBe(1)); + expect(hub.fills).toEqual(hasContent ? [{ requestId: 3, reset: true }] : []); + expect(onClosed).not.toHaveBeenCalled(); + } finally { + session.destroy(); + hub.destroy(); + } } - }); + ); it('re-pulls a track the publisher ended and re-registered while demand stands', async () => { const hub = createRelayHub(); @@ -78,11 +86,14 @@ describe('createRelayHub', () => { expect(served).toEqual(['video']); }); - // The publisher ends the track: a bare FIN on the hub's SUBSCRIBE - // stream, recorded as the churn signal. + // The publisher ends the track: PUBLISH_DONE + FIN on the hub's + // SUBSCRIBE stream, recorded as the churn signal. No stream-count + // source was registered, so the count is unknown. first.end(); await vi.waitFor(() => { - expect(hub.trackEnds).toEqual([{ kind: 'subscribe-fin', trackName: 'video' }]); + expect(hub.trackEnds).toEqual([ + { kind: 'track-end', trackName: 'video', statusCode: PUBLISH_DONE_STATUS.TRACK_ENDED, streamCount: undefined }, + ]); }); // The same name comes back in the same session — the churn shape the