@caprid/moq-core 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +20 -0
  2. package/NOTICE +5 -0
  3. package/README.md +37 -2
  4. package/UPSTREAM.json +38 -0
  5. package/dist/index.d.ts +18 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +10 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/protocol/bytes.d.ts +59 -0
  10. package/dist/protocol/bytes.d.ts.map +1 -0
  11. package/dist/protocol/bytes.js +211 -0
  12. package/dist/protocol/bytes.js.map +1 -0
  13. package/dist/protocol/control-messages.d.ts +560 -0
  14. package/dist/protocol/control-messages.d.ts.map +1 -0
  15. package/dist/protocol/control-messages.js +1146 -0
  16. package/dist/protocol/control-messages.js.map +1 -0
  17. package/dist/protocol/errors.d.ts +64 -0
  18. package/dist/protocol/errors.d.ts.map +1 -0
  19. package/dist/protocol/errors.js +67 -0
  20. package/dist/protocol/errors.js.map +1 -0
  21. package/dist/protocol/object-stream.d.ts +133 -0
  22. package/dist/protocol/object-stream.d.ts.map +1 -0
  23. package/dist/protocol/object-stream.js +265 -0
  24. package/dist/protocol/object-stream.js.map +1 -0
  25. package/dist/protocol/publish-session.d.ts +196 -0
  26. package/dist/protocol/publish-session.d.ts.map +1 -0
  27. package/dist/protocol/publish-session.js +1174 -0
  28. package/dist/protocol/publish-session.js.map +1 -0
  29. package/dist/protocol/request-stream.d.ts +51 -0
  30. package/dist/protocol/request-stream.d.ts.map +1 -0
  31. package/dist/protocol/request-stream.js +94 -0
  32. package/dist/protocol/request-stream.js.map +1 -0
  33. package/dist/protocol/session.d.ts +340 -0
  34. package/dist/protocol/session.d.ts.map +1 -0
  35. package/dist/protocol/session.js +908 -0
  36. package/dist/protocol/session.js.map +1 -0
  37. package/dist/protocol/stream-reset.d.ts +10 -0
  38. package/dist/protocol/stream-reset.d.ts.map +1 -0
  39. package/dist/protocol/stream-reset.js +24 -0
  40. package/dist/protocol/stream-reset.js.map +1 -0
  41. package/dist/protocol/subgroup-writer.d.ts +67 -0
  42. package/dist/protocol/subgroup-writer.d.ts.map +1 -0
  43. package/dist/protocol/subgroup-writer.js +172 -0
  44. package/dist/protocol/subgroup-writer.js.map +1 -0
  45. package/dist/protocol/transport-error.d.ts +29 -0
  46. package/dist/protocol/transport-error.d.ts.map +1 -0
  47. package/dist/protocol/transport-error.js +39 -0
  48. package/dist/protocol/transport-error.js.map +1 -0
  49. package/dist/protocol/varint.d.ts +20 -0
  50. package/dist/protocol/varint.d.ts.map +1 -0
  51. package/dist/protocol/varint.js +99 -0
  52. package/dist/protocol/varint.js.map +1 -0
  53. package/dist/track-source.d.ts +13 -0
  54. package/dist/track-source.d.ts.map +1 -0
  55. package/dist/track-source.js +2 -0
  56. package/dist/track-source.js.map +1 -0
  57. package/package.json +31 -4
@@ -0,0 +1,1174 @@
1
+ /**
2
+ * Publish-capable MOQT session (moq-transport draft-22), the publish-side sibling of `network/moqt/session.ts`'s
3
+ * subscribe-only driver.
4
+ *
5
+ * Owns the protocol mechanics over an established transport: the SETUP exchange on paired unidirectional control
6
+ * streams (§6.3), and the announce-and-serve ingest flow — answering the peer's SUBSCRIBE_NAMESPACE solicitation with
7
+ * REQUEST_OK and a NAMESPACE entry for the announced namespace (§9.15, §9.16), then serving the per-track SUBSCRIBEs the
8
+ * peer routes back (answered with SUBSCRIBE_OK carrying a publisher-assigned track alias, §9.7) for as long as each
9
+ * subscription's request stream stays open.
10
+ *
11
+ * Flow choice: the publisher initiates no request streams at all. moq-relay 0.14.7 removed PUBLISH-based ingest
12
+ * (upstream `de336492`: every PUBLISH is answered with a request error), and it solicits namespaces itself — one
13
+ * SUBSCRIBE_NAMESPACE per authorized prefix, sent immediately after SETUP. Announcing rides the solicitation stream as
14
+ * NAMESPACE entries (suffix-relative, parameterless — the relay treats even an empty parameter count as malformed);
15
+ * data flows only on aliases bound by our own SUBSCRIBE_OKs, per subscription.
16
+ *
17
+ * The session retains no objects, so it serves no fills (§3.4): a nonempty fill range gets a fill fetch stream that is
18
+ * reset right after its FETCH_HEADER, the failure signal §3.4.1 requires. The range is nonempty only for a track whose
19
+ * owner reports a Largest Object (`RegisterTrackOptions.getLargestObject`); without one every fill range is empty and
20
+ * no stream opens.
21
+ *
22
+ * Teardown follows draft-22: every end of an Established subscription the publisher chooses resets the subscription's
23
+ * still-open data streams, then writes PUBLISH_DONE (status, the number of data streams opened for it, reason) and FINs
24
+ * the request stream (§6.4.2.2, §9.9). moq-relay 0.15.4 and later require that PUBLISH_DONE, and treat a bare FIN as a
25
+ * failed request; 0.15.1 to 0.15.3 abort the track on any byte after SUBSCRIBE_OK, PUBLISH_DONE included, so this core
26
+ * needs a relay at 0.15.4 or later for a clean end. An orderly `close()` holds the transport open, bounded, until the
27
+ * peer closes its side of each ended request stream, which moq-relay does only after it has read the PUBLISH_DONE and
28
+ * finished the track. The publisher sends no GOAWAY: 0.14.17 closes the session on a client GOAWAY (code 17), 0.15.1
29
+ * and later record it and keep the session. Aliases are the peer's own request IDs,
30
+ * unique by construction: moq-relay 0.15.x closes the session (PROTOCOL_VIOLATION) when one alias names two different
31
+ * tracks, and cancels the newer subscription when two live subscriptions to one track share an alias.
32
+ *
33
+ * Deliberately callback-shaped with NO signals, mirroring the subscribe driver — signal awareness enters at the
34
+ * `publish/` behavior layer through the actor below. Lives in `publish/` rather than `network/moqt` so the parent-owned
35
+ * wire layer keeps only additive sibling files.
36
+ */
37
+ import { StreamReader, utf8Encode } from './bytes.js';
38
+ import { decodeControlMessage, encodeNamespace, encodeNamespaceDone, encodePublishDone, encodeRequestError, encodeRequestOk, encodeSetup, encodeSubscribeOk, isEmptyFetchRange, MAX_CONTROL_MESSAGE_LENGTH, MESSAGE_TYPE, PUBLISH_DONE_STATUS, REQUEST_ERROR_CODE, resolveMoqtProtocol, SETUP_OPTION, STREAM_RESET_CODE, } from './control-messages.js';
39
+ import { isMoqtProtocolError, MoqtProtocolError, SESSION_ERROR } from './errors.js';
40
+ import { encodeFetchHeader, isSubgroupHeaderType, STREAM_TYPE } from './object-stream.js';
41
+ import { streamResetReason } from './stream-reset.js';
42
+ import { isSessionError } from './transport-error.js';
43
+ /**
44
+ * The largest encoded track property block every SUBSCRIBE_OK this session sends can carry. The
45
+ * properties ride in SUBSCRIBE_OK, a control message whose length field is 16 bits (§9). The rest
46
+ * of its body is the track alias, a varint of up to 9 bytes on the wire (it is the peer's request
47
+ * ID, so it is unknown until a subscription arrives), and the count of message parameters, of which
48
+ * this session sends none (1 byte) unless the track reports a Largest Object (see
49
+ * {@link RegisterTrackOptions.getLargestObject}). A longer block registers but can never answer a subscription.
50
+ */
51
+ export const MAX_TRACK_PROPERTIES_LENGTH = MAX_CONTROL_MESSAGE_LENGTH - 9 - 1;
52
+ const DEFAULT_IMPLEMENTATION_NAME = '@caprid/moq-core publisher';
53
+ /**
54
+ * How long `close()` waits for the PUBLISH_DONE + FIN / NAMESPACE_DONE writes to drain before closing the transport out
55
+ * from under them.
56
+ */
57
+ export const CLOSE_FLUSH_TIMEOUT_MS = 250;
58
+ /**
59
+ * How long `close()` then waits for the peer to close each ended subscription's request stream. A write reaching the
60
+ * wire does not mean the peer has read it: moq-relay reads PUBLISH_DONE, waits for Stream Count data streams (or a 1 s
61
+ * grace when it cannot count them), finishes the track and only then FINs its side. A transport closed before that
62
+ * aborts the track, which viewers see as PUBLISH_DONE status 0 `internal error`. The bound covers the relay's grace
63
+ * plus a round trip, so a peer that never closes its side costs at most this much.
64
+ */
65
+ export const CLOSE_END_ACK_TIMEOUT_MS = 2000;
66
+ /**
67
+ * The reason handed to a data stream the session resets when its subscription ends (§12.5 CANCELLED): a
68
+ * WebTransportError in a browser, which is the only form WebTransport reads the code from.
69
+ */
70
+ function dataStreamReset() {
71
+ return streamResetReason(STREAM_RESET_CODE.CANCELLED, 'the subscription ended');
72
+ }
73
+ /** The reason a fill fetch stream is reset with right after its FETCH_HEADER: the session serves no fills (§3.4.1). */
74
+ function fillReset() {
75
+ return streamResetReason(STREAM_RESET_CODE.INTERNAL_ERROR, 'fill fetch streams are not served');
76
+ }
77
+ /**
78
+ * Include what has been written in the reliable prefix of the coming reset, where the writer has WebTransport's
79
+ * `commit()` (RESET_STREAM_AT). Without it the reset may discard the bytes.
80
+ */
81
+ function commitWritten(writer) {
82
+ const { commit } = writer;
83
+ if (typeof commit === 'function')
84
+ commit.call(writer);
85
+ }
86
+ function resetDataStreams(subscriber) {
87
+ for (const reset of [...subscriber.dataStreams])
88
+ reset();
89
+ }
90
+ /**
91
+ * Hand the caller a data stream that leaves its subscription's open set once closed or reset. The abort signal forwards
92
+ * a reset at once, so a reset never waits behind a backpressured write.
93
+ */
94
+ function trackDataStream(stream, subscriber) {
95
+ const inner = stream.getWriter();
96
+ const reset = (reason) => {
97
+ subscriber.dataStreams.delete(sessionReset);
98
+ inner.abort(reason).catch(() => { });
99
+ };
100
+ const sessionReset = () => reset(dataStreamReset());
101
+ subscriber.dataStreams.add(sessionReset);
102
+ return new WritableStream({
103
+ start(controller) {
104
+ controller.signal.addEventListener('abort', () => reset(controller.signal.reason));
105
+ // A transport failure (STOP_SENDING, a reset) errors this side too, so a FIN the caller has not handed over yet
106
+ // sees the failure instead of a close that only fails later.
107
+ inner.closed.catch((error) => controller.error(error));
108
+ },
109
+ write: (chunk) => inner.write(chunk),
110
+ close: () => {
111
+ // The FIN is issued now as far as PUBLISH_DONE's ordering goes: every accepted write is already on this stream.
112
+ subscriber.dataStreams.delete(sessionReset);
113
+ return inner.close();
114
+ },
115
+ abort: (reason) => reset(reason),
116
+ });
117
+ }
118
+ const PENDING = Symbol('pending');
119
+ /**
120
+ * Whether `promise` had already settled when this was called. One microtask turn, and independent of which handlers
121
+ * run first: a settled promise's reaction is queued ahead of the already-resolved marker's.
122
+ */
123
+ async function hasSettled(promise) {
124
+ try {
125
+ return (await Promise.race([promise, Promise.resolve(PENDING)])) !== PENDING;
126
+ }
127
+ catch {
128
+ return true;
129
+ }
130
+ }
131
+ /**
132
+ * A copy of the track's Largest Object, so a caller that updates its object in place cannot change the snapshot a
133
+ * response advertised before the fill range is checked against it.
134
+ */
135
+ function readLargestObject(track) {
136
+ const largest = track.getLargestObject?.();
137
+ return largest === undefined ? undefined : { group: largest.group, object: largest.object };
138
+ }
139
+ /**
140
+ * The Largest Object for a REQUEST_OK. A callback that throws leaves the parameter off: unlike a SUBSCRIBE, an update
141
+ * has no failure path that keeps the subscription.
142
+ */
143
+ function readLargestObjectForUpdate(track) {
144
+ try {
145
+ return readLargestObject(track);
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ }
151
+ function trackKey(namespace, name) {
152
+ return `${namespace.join('/')}--${name}`;
153
+ }
154
+ function isNamespacePrefix(prefix, namespace) {
155
+ return prefix.length <= namespace.length && prefix.every((part, i) => namespace[i] === part);
156
+ }
157
+ /** Answer a request with REQUEST_ERROR and close it both ways. */
158
+ async function refuse(writer, reader, code, reason) {
159
+ try {
160
+ await writer.write(encodeRequestError(code, reason));
161
+ await writer.close();
162
+ }
163
+ catch {
164
+ // Peer cancelled.
165
+ }
166
+ await reader.cancel();
167
+ }
168
+ // =============================================================================
169
+ // Session driver
170
+ // =============================================================================
171
+ class MoqtPublishSessionImpl {
172
+ ready;
173
+ #transport;
174
+ /** The negotiated draft, which selects the parameter codec. */
175
+ #protocol;
176
+ #config;
177
+ #callbacks;
178
+ #tracks = new Map();
179
+ #namespaceStreams = new Set();
180
+ /**
181
+ * Prefixes whose solicitation is mid-acceptance. Request handlers run concurrently and registration happens only
182
+ * after the REQUEST_OK write settles, so an overlapping solicitation racing that await must be refused off this
183
+ * reservation, not just off the registered set.
184
+ */
185
+ #pendingNamespacePrefixes = new Set();
186
+ /**
187
+ * Every inbound request ID ever seen. Reuse closes the session with INVALID_REQUEST_ID (§6.4.2.1), and because aliases ARE the peer's
188
+ * request IDs, a reused ID would hand two subscriptions the same alias and make their subgroup streams
189
+ * indistinguishable — session-fatal, per the draft.
190
+ */
191
+ #peerRequestIds = new Set();
192
+ #desiredNamespace;
193
+ #announcedFired = false;
194
+ #receivedNamespaceSolicitation = false;
195
+ #resolveReady;
196
+ #rejectReady;
197
+ #controlWriter;
198
+ #receivedServerSetup = false;
199
+ #receivedControlGoaway = false;
200
+ /** Any GOAWAY (control or request stream) — the peer is migrating. */
201
+ #receivedGoaway = false;
202
+ #closing = false;
203
+ #closeError;
204
+ #destroyed = false;
205
+ constructor(transport, config = {}) {
206
+ this.#transport = transport;
207
+ this.#protocol = resolveMoqtProtocol(transport.protocol);
208
+ this.#config = config;
209
+ this.#callbacks = config.callbacks ?? {};
210
+ this.ready = new Promise((resolve, reject) => {
211
+ this.#resolveReady = resolve;
212
+ this.#rejectReady = reject;
213
+ });
214
+ this.ready.catch(() => { });
215
+ void this.#start();
216
+ }
217
+ get namespaceSolicited() {
218
+ const namespace = this.#desiredNamespace;
219
+ if (namespace === undefined || !this.#receivedNamespaceSolicitation)
220
+ return undefined;
221
+ return [...this.#namespaceStreams].some((stream) => isNamespacePrefix(stream.prefix, namespace));
222
+ }
223
+ // ---------------------------------------------------------------------------
224
+ // Session lifecycle
225
+ // ---------------------------------------------------------------------------
226
+ async #start() {
227
+ void this.#acceptUnidirectionalStreams();
228
+ void this.#acceptBidirectionalStreams();
229
+ void this.#transport.closed.then(() => this.#handleClosed(undefined), (error) => this.#handleClosed(error));
230
+ try {
231
+ const control = await this.#transport.createUnidirectionalStream();
232
+ this.#controlWriter = control.getWriter();
233
+ // A control stream MUST stay open for the session's lifetime
234
+ // (§6.3) — a peer stopping it has ended the session, so fail now
235
+ // rather than on the next control write or the transport's own
236
+ // `closed` (~an RTT later); the gap is long enough for a busy
237
+ // publisher to keep churning streams against a dying transport.
238
+ // A clean local close resolves the writer instead, and #fatal
239
+ // no-ops once #handleClosed has run.
240
+ void this.#controlWriter.closed.catch((error) => this.#fatal(error));
241
+ const options = [
242
+ {
243
+ type: SETUP_OPTION.MOQT_IMPLEMENTATION,
244
+ value: utf8Encode(this.#config.implementationName ?? DEFAULT_IMPLEMENTATION_NAME),
245
+ },
246
+ ...(this.#config.setupOptions ?? []),
247
+ ];
248
+ await this.#controlWriter.write(encodeSetup(options));
249
+ }
250
+ catch (error) {
251
+ this.#fatal(error);
252
+ }
253
+ }
254
+ #fatal(error) {
255
+ // Once an orderly close starts, late control-stream failures must not
256
+ // replace its reason/code or interrupt the bounded FIN/retraction drain.
257
+ if (this.#destroyed || this.#closing)
258
+ return;
259
+ const closeCode = isMoqtProtocolError(error) ? error.code : SESSION_ERROR.INTERNAL_ERROR;
260
+ try {
261
+ this.#transport.close({ closeCode, reason: error instanceof Error ? error.message : 'session error' });
262
+ }
263
+ catch {
264
+ // transport already gone
265
+ }
266
+ this.#handleClosed(error);
267
+ }
268
+ #handleClosed(receivedError, { expected = false } = {}) {
269
+ if (this.#destroyed)
270
+ return;
271
+ this.#destroyed = true;
272
+ const error = receivedError ?? this.#closeError;
273
+ if (!this.#receivedServerSetup) {
274
+ this.#rejectReady(error ?? new MoqtProtocolError('session closed before server SETUP'));
275
+ }
276
+ for (const track of this.#tracks.values()) {
277
+ for (const subscriber of track.subscribers)
278
+ void subscriber.cancel();
279
+ }
280
+ this.#tracks.clear();
281
+ this.#namespaceStreams.clear();
282
+ this.#controlWriter = undefined;
283
+ // Mirror the subscribe driver: a transport that drops before server
284
+ // SETUP is a session failure even when the close itself was clean.
285
+ const closeError = error ??
286
+ (expected || this.#receivedServerSetup ? undefined : new MoqtProtocolError('session closed before server SETUP'));
287
+ this.#callbacks.onClosed?.(closeError === undefined ? {} : { error: closeError });
288
+ }
289
+ close(closeCode = SESSION_ERROR.NO_ERROR, reason = '') {
290
+ this.#close(closeCode, reason);
291
+ }
292
+ #close(closeCode, reason, error) {
293
+ if (this.#destroyed || this.#closing)
294
+ return;
295
+ this.#closing = true;
296
+ this.#closeError = error;
297
+ void this.#drainAndClose(closeCode, reason, error);
298
+ }
299
+ /**
300
+ * Orderly close: closing the transport discards queued data (WebTransport semantics), so the subscription ends
301
+ * (PUBLISH_DONE + FIN) and NAMESPACE_DONE retractions must be given a bounded window to land first — a peer should
302
+ * observe every track ending cleanly, not an abrupt transport end. No GOAWAY is sent (see the module doc).
303
+ */
304
+ async #drainAndClose(closeCode, reason, error) {
305
+ // One macrotask beat before the last-resort sweep below: track owners
306
+ // tearing down in the same reactive flush (`setupTrackPublishers`'s
307
+ // cleanup runs on a microtask after ours on the unpublish path) get to
308
+ // end their tracks themselves.
309
+ await new Promise((resolve) => setTimeout(resolve, 0));
310
+ if (this.#destroyed)
311
+ return;
312
+ for (const track of this.#tracks.values()) {
313
+ this.#endTrack(track);
314
+ }
315
+ const writes = [];
316
+ for (const track of this.#tracks.values()) {
317
+ if (track.doneFlushed)
318
+ writes.push(track.doneFlushed);
319
+ // An end started after the track's own end (none should, but a stray one must not be cut off).
320
+ writes.push(...track.pendingEnds);
321
+ }
322
+ for (const stream of this.#namespaceStreams) {
323
+ for (const suffix of stream.announced.splice(0)) {
324
+ writes.push(stream.writer.write(encodeNamespaceDone(suffix)).catch(() => { }));
325
+ }
326
+ }
327
+ let flushTimer;
328
+ try {
329
+ await Promise.race([
330
+ Promise.all(writes),
331
+ new Promise((resolve) => {
332
+ flushTimer = setTimeout(resolve, CLOSE_FLUSH_TIMEOUT_MS);
333
+ }),
334
+ ]);
335
+ }
336
+ finally {
337
+ if (flushTimer !== undefined)
338
+ clearTimeout(flushTimer);
339
+ }
340
+ if (this.#destroyed)
341
+ return;
342
+ // A track end still waiting on its `after` has had the flush window: end its subscriptions now, so their
343
+ // PUBLISH_DONEs go out ahead of the transport close and the wait below covers them.
344
+ for (const track of this.#tracks.values())
345
+ track.endNow?.();
346
+ // The writes are on the wire, not yet read: a peer that has not consumed a PUBLISH_DONE when the transport closes
347
+ // aborts the track instead of finishing it (moq-relay 0.15.4 and later report that downstream as status 0). The
348
+ // peer closes its side of the request stream once it has, so wait for that on every subscription still being
349
+ // served, bounded for a peer that never does.
350
+ const requestEnds = [...this.#tracks.values()].flatMap((track) => track.subscribers.map((s) => s.requestEnded));
351
+ if (requestEnds.length > 0) {
352
+ let endTimer;
353
+ try {
354
+ await Promise.race([
355
+ Promise.all(requestEnds),
356
+ new Promise((resolve) => {
357
+ endTimer = setTimeout(resolve, CLOSE_END_ACK_TIMEOUT_MS);
358
+ }),
359
+ ]);
360
+ }
361
+ finally {
362
+ if (endTimer !== undefined)
363
+ clearTimeout(endTimer);
364
+ }
365
+ }
366
+ if (this.#destroyed)
367
+ return;
368
+ try {
369
+ this.#transport.close({ closeCode, reason });
370
+ }
371
+ catch {
372
+ // transport already gone
373
+ }
374
+ this.#handleClosed(error, { expected: error === undefined });
375
+ }
376
+ destroy(error) {
377
+ this.#close(SESSION_ERROR.NO_ERROR, '', error);
378
+ }
379
+ // ---------------------------------------------------------------------------
380
+ // Announcing and the track registry
381
+ // ---------------------------------------------------------------------------
382
+ announce(trackNamespace) {
383
+ if (this.#destroyed || this.#closing)
384
+ return;
385
+ this.#desiredNamespace = trackNamespace;
386
+ for (const stream of this.#namespaceStreams) {
387
+ this.#reconcileAnnounce(stream);
388
+ }
389
+ }
390
+ /**
391
+ * Write the desired namespace onto a solicitation stream whose prefix covers it. Solicitations, `announce()`, and the
392
+ * first `registerTrack()` arrive in any order — the relay's SUBSCRIBE_NAMESPACE races our post-SETUP setup — so all
393
+ * three paths funnel here. The announce is deferred until at least one track is registered: an announced namespace
394
+ * invites immediate SUBSCRIBEs, and answering one with DOES_NOT_EXIST is terminal on moq-lite-rs (the relay aborts
395
+ * the request rather than retrying), so advertising an empty registry would permanently break the first viewer in the
396
+ * pre-registration window.
397
+ */
398
+ #reconcileAnnounce(stream) {
399
+ const namespace = this.#desiredNamespace;
400
+ if (namespace === undefined || this.#tracks.size === 0)
401
+ return;
402
+ if (!isNamespacePrefix(stream.prefix, namespace))
403
+ return;
404
+ const suffix = namespace.slice(stream.prefix.length);
405
+ if (stream.announced.some((existing) => existing.join('/') === suffix.join('/')))
406
+ return;
407
+ stream.announced.push(suffix);
408
+ stream.writer
409
+ .write(encodeNamespace(suffix))
410
+ .then(() => {
411
+ if (this.#destroyed || this.#announcedFired)
412
+ return;
413
+ this.#announcedFired = true;
414
+ this.#callbacks.onAnnounced?.({ namespace });
415
+ })
416
+ .catch((error) => {
417
+ // The response half died alone (a reset the request half may
418
+ // never mirror): the entry never reached the peer, no future
419
+ // write can, and the read loop may stay open forever — the
420
+ // carrier is dead. Deregister it so the peer's replacement
421
+ // solicitation is a fresh start rather than a PREFIX_OVERLAP
422
+ // against a corpse; if another path already swept it, the loss
423
+ // was reported there.
424
+ if (!this.#namespaceStreams.delete(stream))
425
+ return;
426
+ stream.announced = stream.announced.filter((existing) => existing !== suffix);
427
+ void stream.writer.close().catch(() => { });
428
+ void this.#reportAnnounceLoss(error);
429
+ });
430
+ }
431
+ /**
432
+ * Fire `onAnnounceEnded` when no solicitation carries the announce anymore — shared by the read-loop cleanup and the
433
+ * response-write failure path; `cause` is the stream failure that ended the carrier. Silent while closing,
434
+ * destroyed, or migrating (a GOAWAY makes the peer's streams ending the orderly drain), and once the transport has
435
+ * ended: an ended transport fails every stream as it settles `closed`, and that is connection loss, which
436
+ * `#handleClosed` reports, not a withdrawal. A failure with `source` `'session'` (TA-23) or the settled `closed`
437
+ * decides, not whether the `closed` handler happened to run first.
438
+ */
439
+ async #reportAnnounceLoss(cause) {
440
+ if (this.#announceLossSilenced() || this.#announceCarried())
441
+ return;
442
+ if (isSessionError(cause) || (await hasSettled(this.#transport.closed)))
443
+ return;
444
+ // A replacement solicitation may have picked the announce up during that turn.
445
+ if (this.#announceLossSilenced() || this.#announceCarried())
446
+ return;
447
+ const error = new MoqtProtocolError('the namespace solicitation carrying the announce ended');
448
+ error.cause = cause;
449
+ this.#callbacks.onAnnounceEnded?.({ error });
450
+ }
451
+ #announceLossSilenced() {
452
+ return this.#destroyed || this.#closing || this.#receivedGoaway;
453
+ }
454
+ #announceCarried() {
455
+ return [...this.#namespaceStreams].some((stream) => stream.announced.length > 0);
456
+ }
457
+ registerTrack(options) {
458
+ if (this.#destroyed || this.#closing) {
459
+ // A closed session must not repopulate `#tracks` — hand back an
460
+ // inert handle so late callers still get the RegisteredTrack shape.
461
+ return { trackName: options.trackName, end: () => { } };
462
+ }
463
+ const track = {
464
+ trackProperties: options.trackProperties ?? [],
465
+ getLargestObject: options.getLargestObject,
466
+ key: trackKey(options.trackNamespace, options.trackName),
467
+ trackName: options.trackName,
468
+ subscribers: [],
469
+ done: false,
470
+ pendingEnds: [],
471
+ };
472
+ this.#tracks.set(track.key, track);
473
+ // The first registration may be what the deferred announce was
474
+ // waiting for (see #reconcileAnnounce).
475
+ if (this.#tracks.size === 1) {
476
+ for (const stream of this.#namespaceStreams) {
477
+ this.#reconcileAnnounce(stream);
478
+ }
479
+ }
480
+ return {
481
+ trackName: options.trackName,
482
+ end: (options) => this.#endTrack(track, options?.after),
483
+ };
484
+ }
485
+ /**
486
+ * Refuse future SUBSCRIBEs, and end every live subscription with PUBLISH_DONE `TRACK_ENDED`, now or once `after`
487
+ * settles. The aggregated write completion lands on `track.doneFlushed` so `close()` can hold the transport open
488
+ * until the PUBLISH_DONEs and FINs reach the wire.
489
+ */
490
+ #endTrack(track, after) {
491
+ if (track.done)
492
+ return;
493
+ track.done = true;
494
+ if (after === undefined) {
495
+ track.doneFlushed = this.#endSubscriptions(track);
496
+ return;
497
+ }
498
+ let ended;
499
+ const endNow = () => {
500
+ delete track.endNow;
501
+ ended ??= this.#endSubscriptions(track);
502
+ return ended;
503
+ };
504
+ track.endNow = endNow;
505
+ track.doneFlushed = Promise.resolve(after).then(endNow, endNow);
506
+ }
507
+ /** The ending half of `#endTrack`: every live subscription's end, reported at once. Settles when the ends land. */
508
+ #endSubscriptions(track) {
509
+ let hadReported = false;
510
+ for (const subscriber of track.subscribers) {
511
+ if (!subscriber.finished)
512
+ this.#endSubscription(track, subscriber, PUBLISH_DONE_STATUS.TRACK_ENDED, 'track ended');
513
+ // The local end is authoritative: report each live subscription
514
+ // ended NOW rather than when the peer eventually closes its
515
+ // request direction — otherwise `subscriberCount` and the binding
516
+ // stay live (and publishers keep opening data streams) until the
517
+ // peer notices the FIN. Clearing `reported` keeps the read loop's
518
+ // own end notification paired: it fires on the same flag.
519
+ if (subscriber.reported) {
520
+ subscriber.reported = false;
521
+ hadReported = true;
522
+ if (!this.#destroyed)
523
+ this.#callbacks.onSubscribeEnd?.({ requestId: subscriber.requestId });
524
+ }
525
+ }
526
+ if (hadReported && !this.#destroyed) {
527
+ this.#callbacks.onTrackBinding?.({ trackName: track.trackName, trackAlias: undefined });
528
+ }
529
+ return Promise.all([...track.pendingEnds]).then(() => { });
530
+ }
531
+ /**
532
+ * End an Established subscription from the publisher side (§6.4.2.2, §9.9). Marks it finished at once, so no new
533
+ * data stream opens on its alias. Then, in order: wait for data-stream opens in flight, reset every data stream the
534
+ * caller has not closed (a caller that follows the binding has closed them already), write `preceding` (a
535
+ * REQUEST_ERROR answering a failed update) and PUBLISH_DONE with the subscription's Stream Count, and FIN. Settles
536
+ * when the FIN lands or the stream fails; never rejects. It stays in `track.pendingEnds` until then, so `close()`
537
+ * drains it whichever path started it.
538
+ */
539
+ #endSubscription(track, subscriber, status, reason, preceding) {
540
+ subscriber.finished = true;
541
+ const ended = (async () => {
542
+ if (subscriber.opening.size > 0)
543
+ await Promise.all(subscriber.opening);
544
+ resetDataStreams(subscriber);
545
+ const done = encodePublishDone(status, subscriber.streamCount, reason);
546
+ if (preceding)
547
+ void subscriber.writer.write(preceding).catch(() => { });
548
+ await subscriber.writer.write(done);
549
+ await subscriber.writer.close();
550
+ })().catch(() => { });
551
+ track.pendingEnds.push(ended);
552
+ void ended.then(() => {
553
+ const index = track.pendingEnds.indexOf(ended);
554
+ if (index >= 0)
555
+ track.pendingEnds.splice(index, 1);
556
+ });
557
+ }
558
+ #liveSubscription(trackAlias) {
559
+ for (const track of this.#tracks.values()) {
560
+ for (const subscriber of track.subscribers) {
561
+ if (subscriber.trackAlias === trackAlias && subscriber.accepted && !subscriber.finished) {
562
+ return { track, subscriber };
563
+ }
564
+ }
565
+ }
566
+ return undefined;
567
+ }
568
+ async openUniStream(trackAlias, options) {
569
+ // Refuse rather than touch the transport once the session is going
570
+ // away. Encoders keep producing frames for a beat after a peer kills
571
+ // the session, and hammering createUnidirectionalStream() on a
572
+ // torn-down WebTransport segfaults Chromium's renderer (null deref in
573
+ // the native session teardown race) — observed against a relay that
574
+ // resets every stream on protocol disagreement. An orderly close
575
+ // keeps the transport alive through its drain window, and a track
576
+ // whose `end({ after })` is waiting there may still need a stream for
577
+ // its last group; nothing else opens once closing has begun.
578
+ if (this.#destroyed)
579
+ throw new Error('moq publish session: closed');
580
+ const live = this.#liveSubscription(trackAlias);
581
+ if (this.#closing && live?.track.endNow === undefined)
582
+ throw new Error('moq publish session: closed');
583
+ if (!live)
584
+ throw new Error(`moq publish session: no live subscription for track alias ${trackAlias}`);
585
+ const { subscriber } = live;
586
+ let settle;
587
+ const opening = new Promise((resolve) => {
588
+ settle = resolve;
589
+ });
590
+ subscriber.opening.add(opening);
591
+ try {
592
+ const stream = await this.#transport.createUnidirectionalStream(options);
593
+ if (subscriber.finished) {
594
+ // The subscription ended while this stream was opening. Its PUBLISH_DONE waits on `opening`, so the reset lands
595
+ // before it and the stream is not counted.
596
+ stream.abort(dataStreamReset()).catch(() => { });
597
+ throw new Error(`moq publish session: the subscription for track alias ${trackAlias} ended`);
598
+ }
599
+ subscriber.streamCount += 1;
600
+ return trackDataStream(stream, subscriber);
601
+ }
602
+ finally {
603
+ subscriber.opening.delete(opening);
604
+ settle();
605
+ }
606
+ }
607
+ /**
608
+ * Whether a SUBSCRIBE or REQUEST_UPDATE carrying FILL_PARAMETERS opens a fill fetch stream (§3.4.1): only while the
609
+ * subscription is live and not paused, and only for a nonempty fill range. The fill range is the filter inside
610
+ * FILL_PARAMETERS, else the subscription's, evaluated as a fetch against the track's Largest Object; an empty range,
611
+ * or one starting past Largest Object, opens no stream (§3.4).
612
+ */
613
+ #fillRequested(subscriber, fill, largestObject) {
614
+ if (fill === undefined || !subscriber.forwarding || subscriber.finished)
615
+ return false;
616
+ return !isEmptyFetchRange(fill.locationFilter ?? subscriber.locationFilter ?? { type: 'none' }, largestObject);
617
+ }
618
+ /**
619
+ * Fail a requested fill the way §3.4.1 requires of a publisher that cannot serve it: open a fill fetch stream, write
620
+ * the FETCH_HEADER naming the request that asked for it (`requestId`, the SUBSCRIBE's or the REQUEST_UPDATE's), and
621
+ * reset the stream. A FIN would claim the whole fill range was delivered. moq-relay (0.14.17 through 0.17.0) asks for
622
+ * the current group this way on every upstream SUBSCRIBE; refusing the SUBSCRIBE instead would fail every relay pull
623
+ * of a track that has content.
624
+ *
625
+ * The header survives the reset only where the writer has WebTransport's `commit()` (RESET_STREAM_AT's reliable
626
+ * prefix). Without it the subscriber may see a bare reset, which it cannot attribute to the subscription, and its join
627
+ * waits for the next group as after any failed fill. The subscription is served either way.
628
+ *
629
+ * The stream is a data stream of the subscription in every other respect: PUBLISH_DONE waits for its open, it counts
630
+ * toward the Stream Count from the step that commits it to its header (§9.9 counts fill fetch streams), so one that
631
+ * finishes opening after the subscription ended is reset bare and not counted, and the subscription's end resets it if
632
+ * its header write is still pending.
633
+ */
634
+ #failFill(subscriber, requestId) {
635
+ let settle;
636
+ const opening = new Promise((resolve) => {
637
+ settle = resolve;
638
+ });
639
+ subscriber.opening.add(opening);
640
+ void (async () => {
641
+ let writer;
642
+ try {
643
+ writer = (await this.#transport.createUnidirectionalStream()).getWriter();
644
+ }
645
+ catch {
646
+ // The session is going away; it resets nothing it never opened.
647
+ return;
648
+ }
649
+ finally {
650
+ subscriber.opening.delete(opening);
651
+ settle();
652
+ }
653
+ if (subscriber.finished) {
654
+ writer.abort(dataStreamReset()).catch(() => { });
655
+ return;
656
+ }
657
+ const reset = (reason) => {
658
+ subscriber.dataStreams.delete(sessionReset);
659
+ writer.abort(reason).catch(() => { });
660
+ };
661
+ const sessionReset = () => reset(dataStreamReset());
662
+ subscriber.dataStreams.add(sessionReset);
663
+ subscriber.streamCount += 1;
664
+ try {
665
+ await writer.write(encodeFetchHeader(requestId));
666
+ commitWritten(writer);
667
+ }
668
+ catch {
669
+ // Reset by the subscription's end, or the peer stopped it.
670
+ }
671
+ reset(fillReset());
672
+ })();
673
+ }
674
+ // ---------------------------------------------------------------------------
675
+ // Incoming unidirectional streams (control, padding)
676
+ // ---------------------------------------------------------------------------
677
+ async #acceptUnidirectionalStreams() {
678
+ const reader = this.#transport.incomingUnidirectionalStreams.getReader();
679
+ try {
680
+ while (true) {
681
+ const { done, value } = await reader.read();
682
+ if (done)
683
+ break;
684
+ void this.#handleUnidirectionalStream(value).catch((error) => {
685
+ if (isMoqtProtocolError(error))
686
+ this.#fatal(error);
687
+ });
688
+ }
689
+ }
690
+ catch {
691
+ // Transport went away; `closed` handles the surfacing.
692
+ }
693
+ finally {
694
+ reader.releaseLock();
695
+ }
696
+ }
697
+ async #handleUnidirectionalStream(stream) {
698
+ const reader = new StreamReader(stream);
699
+ const streamType = await reader.readVarint();
700
+ if (streamType === STREAM_TYPE.SETUP) {
701
+ await this.#runControlStream(reader);
702
+ return;
703
+ }
704
+ if (streamType === STREAM_TYPE.PADDING) {
705
+ await reader.cancel();
706
+ return;
707
+ }
708
+ await reader.cancel();
709
+ if (isSubgroupHeaderType(streamType) || streamType === STREAM_TYPE.FETCH_HEADER) {
710
+ throw new MoqtProtocolError('publish session received a data stream');
711
+ }
712
+ throw new MoqtProtocolError(`unknown unidirectional stream type 0x${streamType.toString(16)}`);
713
+ }
714
+ /** Read one control-message frame using the pull-based stream reader. */
715
+ async #readControlFrame(reader, type) {
716
+ const high = await reader.readUint8();
717
+ const low = await reader.readUint8();
718
+ const body = await reader.readBytes(high * 256 + low);
719
+ return decodeControlMessage({ type, body }, this.#protocol);
720
+ }
721
+ async #runControlStream(reader) {
722
+ // The stream-type varint (0x2F00) doubles as the first message's type.
723
+ const setup = await this.#readControlFrame(reader, MESSAGE_TYPE.SETUP);
724
+ if (setup.kind !== 'setup')
725
+ throw new MoqtProtocolError('control stream did not begin with SETUP');
726
+ if (this.#receivedServerSetup) {
727
+ throw new MoqtProtocolError('received a second control stream');
728
+ }
729
+ this.#receivedServerSetup = true;
730
+ this.#resolveReady();
731
+ this.#callbacks.onReady?.(setup.options);
732
+ while (!(await reader.atEnd())) {
733
+ const type = await reader.readVarint();
734
+ const message = await this.#readControlFrame(reader, type);
735
+ if (message.kind !== 'goaway')
736
+ throw new MoqtProtocolError(`unexpected ${message.kind} on the control stream`);
737
+ if (this.#receivedControlGoaway) {
738
+ throw new MoqtProtocolError('received more than one GOAWAY on the control stream');
739
+ }
740
+ this.#receivedControlGoaway = true;
741
+ this.#receivedGoaway = true;
742
+ this.#callbacks.onGoaway?.(message);
743
+ }
744
+ // A closed control stream ends the session (§6.3).
745
+ if (!this.#destroyed) {
746
+ this.#fatal(new MoqtProtocolError('peer closed its control stream'));
747
+ }
748
+ }
749
+ // ---------------------------------------------------------------------------
750
+ // Incoming bidirectional streams (peer-initiated requests)
751
+ // ---------------------------------------------------------------------------
752
+ async #acceptBidirectionalStreams() {
753
+ const reader = this.#transport.incomingBidirectionalStreams.getReader();
754
+ try {
755
+ while (true) {
756
+ const { done, value } = await reader.read();
757
+ if (done)
758
+ break;
759
+ void this.#handleIncomingRequest(value).catch((error) => {
760
+ if (isMoqtProtocolError(error))
761
+ this.#fatal(error);
762
+ });
763
+ }
764
+ }
765
+ catch {
766
+ // Transport went away.
767
+ }
768
+ finally {
769
+ reader.releaseLock();
770
+ }
771
+ }
772
+ async #handleIncomingRequest(stream) {
773
+ const reader = new StreamReader(stream.readable);
774
+ const type = await reader.readVarint();
775
+ const message = await this.#readControlFrame(reader, type);
776
+ // Reserve the request ID for EVERY request-initiating kind — the
777
+ // uniqueness invariant is session-wide, so an ID burned on a
778
+ // rejected PUBLISH or FETCH must not be reusable by a later
779
+ // SUBSCRIBE (whose alias it would become).
780
+ const initiatingRequestId = message.kind === 'fetch'
781
+ ? message.request.requestId
782
+ : message.kind === 'subscribe' ||
783
+ message.kind === 'subscribe-namespace' ||
784
+ message.kind === 'publish' ||
785
+ message.kind === 'publish-namespace' ||
786
+ message.kind === 'track-status'
787
+ ? message.requestId
788
+ : undefined;
789
+ if (initiatingRequestId !== undefined)
790
+ this.#claimPeerRequestId(initiatingRequestId);
791
+ if (message.kind === 'subscribe') {
792
+ await this.#handleIncomingSubscribe(stream, reader, message);
793
+ return;
794
+ }
795
+ if (message.kind === 'subscribe-namespace') {
796
+ await this.#handleSubscribeNamespace(stream, reader, message);
797
+ return;
798
+ }
799
+ // Everything else: this endpoint only serves its own published tracks.
800
+ const respond = async (bytes) => {
801
+ const writer = stream.writable.getWriter();
802
+ try {
803
+ await writer.write(bytes);
804
+ await writer.close();
805
+ }
806
+ catch {
807
+ // Peer cancelled; nothing to clean up.
808
+ }
809
+ await reader.cancel();
810
+ };
811
+ const errorCode = message.kind === 'publish' ? REQUEST_ERROR_CODE.UNINTERESTED : REQUEST_ERROR_CODE.NOT_SUPPORTED;
812
+ await respond(encodeRequestError(errorCode, 'publish-only endpoint'));
813
+ }
814
+ /**
815
+ * Request IDs are consumed once per session (§6.4.2.1) — by every request-initiating message and, since draft-20 gave it
816
+ * an id of its own, by REQUEST_UPDATE. This endpoint is always the client, so the peer's ids are odd; a reused id or
817
+ * an even one closes the session with INVALID_REQUEST_ID.
818
+ */
819
+ #claimPeerRequestId(requestId) {
820
+ if (requestId % 2 !== 1) {
821
+ throw new MoqtProtocolError(`peer sent even request id ${requestId}`, SESSION_ERROR.INVALID_REQUEST_ID);
822
+ }
823
+ if (this.#peerRequestIds.has(requestId)) {
824
+ throw new MoqtProtocolError(`peer reused request id ${requestId}`, SESSION_ERROR.INVALID_REQUEST_ID);
825
+ }
826
+ this.#peerRequestIds.add(requestId);
827
+ }
828
+ /**
829
+ * A peer's namespace solicitation — the announce carrier. Accepted with REQUEST_OK, then held open for the session's
830
+ * lifetime: NAMESPACE / NAMESPACE_DONE entries for every announced namespace under the prefix ride this stream. A
831
+ * clean requester-side FIN is half-closure, not withdrawal (§6.4.2.2); only a reset (or a rejected update, §9.5.1)
832
+ * ends the carrier, and its loss while the announce is live means the peer refused or withdrew the ingest path.
833
+ */
834
+ async #handleSubscribeNamespace(stream, reader, subscribeNamespace) {
835
+ const writer = stream.writable.getWriter();
836
+ const prefix = subscribeNamespace.trackNamespacePrefix;
837
+ // §9.17: a solicitation overlapping an established one (either
838
+ // prefix containing the other) is refused with PREFIX_OVERLAP —
839
+ // announcing on both would hand the peer duplicate namespace state
840
+ // with inconsistent withdrawals.
841
+ const overlaps = [...this.#namespaceStreams].some((existing) => isNamespacePrefix(existing.prefix, prefix) || isNamespacePrefix(prefix, existing.prefix)) ||
842
+ [...this.#pendingNamespacePrefixes].some((pending) => isNamespacePrefix(pending, prefix) || isNamespacePrefix(prefix, pending));
843
+ if (overlaps) {
844
+ try {
845
+ await writer.write(encodeRequestError(REQUEST_ERROR_CODE.PREFIX_OVERLAP, 'overlapping namespace prefix'));
846
+ await writer.close();
847
+ }
848
+ catch {
849
+ // Peer cancelled.
850
+ }
851
+ await reader.cancel();
852
+ return;
853
+ }
854
+ // Reserve the prefix across the acceptance write; the registration
855
+ // below happens in the same microtask as the release, so a racing
856
+ // overlapping solicitation always sees one or the other.
857
+ this.#pendingNamespacePrefixes.add(prefix);
858
+ let accepted = false;
859
+ try {
860
+ await writer.write(encodeRequestOk({}, this.#protocol));
861
+ accepted = true;
862
+ }
863
+ catch {
864
+ // Peer cancelled before the acceptance landed.
865
+ }
866
+ finally {
867
+ this.#pendingNamespacePrefixes.delete(prefix);
868
+ }
869
+ if (!accepted) {
870
+ await reader.cancel();
871
+ return;
872
+ }
873
+ const record = {
874
+ prefix,
875
+ writer,
876
+ announced: [],
877
+ };
878
+ this.#receivedNamespaceSolicitation = true;
879
+ this.#namespaceStreams.add(record);
880
+ this.#reconcileAnnounce(record);
881
+ // Hold the stream. The known peers write nothing further on it.
882
+ let failedUpdate = false;
883
+ let cause;
884
+ try {
885
+ while (!(await reader.atEnd())) {
886
+ const type = await reader.readVarint();
887
+ const message = await this.#readControlFrame(reader, type);
888
+ if (message.kind === 'goaway') {
889
+ this.#receivedGoaway = true;
890
+ this.#callbacks.onGoaway?.(message);
891
+ }
892
+ else if (message.kind === 'request-update') {
893
+ this.#claimPeerRequestId(message.requestId);
894
+ // Namespace subscriptions may legally be updated (§9.5). v1
895
+ // applies none of it (a prefix change would re-base every
896
+ // entry), so per §9.5.1 the update is answered with an error
897
+ // and the request stream closes below — never session-fatal
898
+ // (only the reused Request ID above is).
899
+ this.#callbacks.onRequestUpdate?.({
900
+ requestId: subscribeNamespace.requestId,
901
+ updateRequestId: message.requestId,
902
+ parameters: message.parameters,
903
+ });
904
+ void writer
905
+ .write(encodeRequestError(REQUEST_ERROR_CODE.NOT_SUPPORTED, 'namespace update not supported'))
906
+ .catch(() => { });
907
+ failedUpdate = true;
908
+ break;
909
+ }
910
+ else {
911
+ throw new MoqtProtocolError(`unexpected ${message.kind} on an incoming subscribe-namespace stream`);
912
+ }
913
+ }
914
+ if (!failedUpdate) {
915
+ // A clean requester-side FIN is NOT a cancellation (§6.4.2.2 — the
916
+ // peer merely commits to sending no updates): the response side
917
+ // keeps carrying NAMESPACE entries until a reset or the
918
+ // transport ends, so the carrier stays registered and open.
919
+ return;
920
+ }
921
+ }
922
+ catch (error) {
923
+ // A protocol violation is session-fatal; #handleClosed sweeps the
924
+ // carrier state with everything else.
925
+ if (isMoqtProtocolError(error))
926
+ throw error;
927
+ // Reset — the peer withdrew the namespace subscription.
928
+ cause = error;
929
+ }
930
+ // Withdrawal (reset) or a failed update: the carrier is over.
931
+ this.#namespaceStreams.delete(record);
932
+ void writer.close().catch(() => { });
933
+ if (record.announced.length > 0)
934
+ await this.#reportAnnounceLoss(cause);
935
+ }
936
+ async #handleIncomingSubscribe(stream, reader, subscribe) {
937
+ const track = this.#tracks.get(trackKey(subscribe.trackNamespace, subscribe.trackName));
938
+ const writer = stream.writable.getWriter();
939
+ if (!track || track.done) {
940
+ await refuse(writer, reader, REQUEST_ERROR_CODE.DOES_NOT_EXIST, 'unknown track');
941
+ return;
942
+ }
943
+ // The peer's request IDs are session-unique, so they double as the
944
+ // track alias — binding one alias to two live request IDs is a
945
+ // session-fatal Duplicate on moq-lite-rs.
946
+ const trackAlias = subscribe.requestId;
947
+ // Encoded before the write's guard: only a failed write is the peer
948
+ // cancelling. A response this side cannot build (the properties
949
+ // overflow the message, say) is refused promptly, so the peer is not
950
+ // left waiting on a request that never gets an answer.
951
+ let subscribeOk;
952
+ // One snapshot answers the SUBSCRIBE and bounds its fill range, however long the response write takes.
953
+ let largestObject;
954
+ try {
955
+ largestObject = readLargestObject(track);
956
+ subscribeOk = encodeSubscribeOk(trackAlias, largestObject ? { largestObject } : {}, track.trackProperties, this.#protocol);
957
+ }
958
+ catch (error) {
959
+ // The encoder refused the response; the peer did nothing wrong.
960
+ await refuse(writer, reader, REQUEST_ERROR_CODE.INTERNAL_ERROR, 'could not encode SUBSCRIBE_OK');
961
+ if (!this.#destroyed) {
962
+ this.#callbacks.onSubscribeFailed?.({ requestId: subscribe.requestId, trackName: track.trackName, error });
963
+ }
964
+ return;
965
+ }
966
+ let settleRequest;
967
+ const requestEnded = new Promise((resolve) => {
968
+ settleRequest = resolve;
969
+ });
970
+ const subscriber = {
971
+ requestId: subscribe.requestId,
972
+ trackAlias,
973
+ writer,
974
+ cancel: async () => {
975
+ subscriber.finished = true;
976
+ settleRequest();
977
+ writer.abort().catch(() => { });
978
+ try {
979
+ await reader.cancel();
980
+ }
981
+ catch {
982
+ // The stream already errored (e.g. the peer reset it first).
983
+ }
984
+ },
985
+ accepted: false,
986
+ reported: false,
987
+ // Forward State defaults to 1; `forward: 0` subscribes without
988
+ // authorizing data until a REQUEST_UPDATE flips it.
989
+ forwarding: subscribe.parameters.forward !== 0,
990
+ finished: false,
991
+ streamCount: 0,
992
+ dataStreams: new Set(),
993
+ opening: new Set(),
994
+ locationFilter: subscribe.parameters.locationFilter,
995
+ requestEnded,
996
+ };
997
+ track.subscribers.push(subscriber);
998
+ try {
999
+ await writer.write(subscribeOk);
1000
+ subscriber.accepted = true;
1001
+ }
1002
+ catch {
1003
+ // Peer cancelled before the response landed.
1004
+ track.subscribers = track.subscribers.filter((s) => s !== subscriber);
1005
+ settleRequest();
1006
+ await reader.cancel();
1007
+ return;
1008
+ }
1009
+ // Overlapping same-track subscriptions settle their SUBSCRIBE_OK
1010
+ // writes independently, so a newer subscription may have replaced
1011
+ // this one (marking it finished) while this acceptance was still in
1012
+ // flight — a stale completion must not steal the binding back onto
1013
+ // an alias whose stream is already ending, and a subscription that
1014
+ // was never live is never reported (`onSubscribeEnd` pairs on the
1015
+ // same flag, keeping subscriber counts balanced).
1016
+ if (!subscriber.finished) {
1017
+ subscriber.reported = true;
1018
+ this.#callbacks.onSubscribe?.(subscribe);
1019
+ // The newest subscription wins the binding, and every live
1020
+ // PREDECESSOR (arrival order — a successor may accept before an
1021
+ // older backpressured write settles, and must not be swept by it)
1022
+ // ends cleanly (FIN) so the peer's bookkeeping resolves. One live
1023
+ // subscription per track is a deliberate v1 constraint: the spec
1024
+ // permits concurrent same-track subscriptions, but serving them
1025
+ // means writing every group once per alias, and the known peers
1026
+ // (moq-lite-rs relays) hold at most one upstream subscription per
1027
+ // track and fan out on their side — the sweep also covers their
1028
+ // resubscribe races.
1029
+ for (const other of track.subscribers.slice(0, track.subscribers.indexOf(subscriber))) {
1030
+ if (other.finished)
1031
+ continue;
1032
+ // No status names a replacement. TRACK_ENDED is the one the relay finishes a track on (anything else aborts
1033
+ // it), and the newer subscription carries the track on.
1034
+ this.#endSubscription(track, other, PUBLISH_DONE_STATUS.TRACK_ENDED, 'superseded by a newer subscription');
1035
+ }
1036
+ this.#callbacks.onTrackBinding?.({
1037
+ trackName: track.trackName,
1038
+ trackAlias: subscriber.forwarding ? trackAlias : undefined,
1039
+ });
1040
+ }
1041
+ if (this.#fillRequested(subscriber, subscribe.parameters.fillParameters, largestObject)) {
1042
+ this.#failFill(subscriber, subscribe.requestId);
1043
+ }
1044
+ // Keep serving the request stream: REQUEST_UPDATEs arrive here.
1045
+ try {
1046
+ while (!(await reader.atEnd())) {
1047
+ const type = await reader.readVarint();
1048
+ const message = await this.#readControlFrame(reader, type);
1049
+ if (message.kind === 'request-update') {
1050
+ this.#claimPeerRequestId(message.requestId);
1051
+ // The delivery timeouts (§5.2) are applied by the caller, through `onRequestUpdate`, to the groups it opens
1052
+ // afterwards. FILL_PARAMETERS asks for one fill (§3.4.1) and changes nothing about the subscription.
1053
+ const { forward, subscriberPriority: _priority, objectDeliveryTimeout: _objectTimeout, subgroupDeliveryTimeout: _subgroupTimeout, fillParameters, ...unsupported } = message.parameters;
1054
+ // Forward State toggles ride REQUEST_UPDATE; the binding must
1055
+ // follow so data stops (or starts) with the subscription's
1056
+ // authorization. Newest-wins keeps this subscriber the track's
1057
+ // only live one, so its state IS the binding.
1058
+ if (forward !== undefined) {
1059
+ subscriber.forwarding = forward !== 0;
1060
+ if (!subscriber.finished && subscriber.accepted) {
1061
+ this.#callbacks.onTrackBinding?.({
1062
+ trackName: track.trackName,
1063
+ trackAlias: subscriber.forwarding ? subscriber.trackAlias : undefined,
1064
+ });
1065
+ }
1066
+ }
1067
+ this.#callbacks.onRequestUpdate?.({
1068
+ requestId: subscribe.requestId,
1069
+ updateRequestId: message.requestId,
1070
+ parameters: message.parameters,
1071
+ });
1072
+ if (!subscriber.finished) {
1073
+ if (Object.keys(unsupported).length > 0) {
1074
+ // Acknowledging an update we did not apply would leave the
1075
+ // peer serving stale expectations (a filter or range it
1076
+ // believes is in effect). Forward State is applied above,
1077
+ // priority is advisory (the known relays discard ours
1078
+ // too), the caller applies the delivery timeouts, and a fill
1079
+ // is answered below;
1080
+ // anything else ends this request honestly: the
1081
+ // update's REQUEST_ERROR, then PUBLISH_DONE UPDATE_FAILED
1082
+ // (§9.5.1).
1083
+ this.#endSubscription(track, subscriber, PUBLISH_DONE_STATUS.UPDATE_FAILED, 'unsupported subscription update', encodeRequestError(REQUEST_ERROR_CODE.NOT_SUPPORTED, 'unsupported subscription update'));
1084
+ if (subscriber.reported) {
1085
+ subscriber.reported = false;
1086
+ this.#callbacks.onSubscribeEnd?.({ requestId: subscribe.requestId });
1087
+ const binding = track.subscribers.filter((s) => !s.finished && s.accepted && s.forwarding).at(-1);
1088
+ this.#callbacks.onTrackBinding?.({ trackName: track.trackName, trackAlias: binding?.trackAlias });
1089
+ }
1090
+ }
1091
+ else {
1092
+ // The subscribe driver treats REQUEST_OK as the update's
1093
+ // completion (`onUpdateOk`). Strictly reactive: a peer that
1094
+ // never sends REQUEST_UPDATE (moq-relay 0.15.8 writes nothing
1095
+ // after SUBSCRIBE until it cancels) never sees a trailing byte.
1096
+ // LARGEST_OBJECT rides it as in SUBSCRIBE_OK (§9.20.17).
1097
+ const largestObject = readLargestObjectForUpdate(track);
1098
+ void writer
1099
+ .write(encodeRequestOk(largestObject ? { largestObject } : {}, this.#protocol))
1100
+ .catch(() => { });
1101
+ if (this.#fillRequested(subscriber, fillParameters, largestObject)) {
1102
+ this.#failFill(subscriber, message.requestId);
1103
+ }
1104
+ }
1105
+ }
1106
+ }
1107
+ else if (message.kind === 'goaway') {
1108
+ this.#receivedGoaway = true;
1109
+ this.#callbacks.onGoaway?.(message);
1110
+ }
1111
+ else {
1112
+ throw new MoqtProtocolError(`unexpected ${message.kind} on an incoming subscribe stream`);
1113
+ }
1114
+ }
1115
+ // The peer FINed its direction while the subscription was still ours
1116
+ // to end. moq-relay (0.15.8 `cancel_subscribe`) pairs that FIN with
1117
+ // STOP_SENDING (a cancellation, so the write fails harmlessly); a
1118
+ // peer that only half-closes still gets the PUBLISH_DONE §6.4.2.2
1119
+ // requires before our FIN. No status names this, so it reports the
1120
+ // publisher's own limitation.
1121
+ if (!subscriber.finished) {
1122
+ this.#endSubscription(track, subscriber, PUBLISH_DONE_STATUS.INTERNAL_ERROR, 'subscriber closed its request stream');
1123
+ }
1124
+ }
1125
+ catch (error) {
1126
+ if (isMoqtProtocolError(error))
1127
+ throw error;
1128
+ // Reset — the subscriber cancelled (§6.4.2.3); ordinary end-of-request.
1129
+ // A cancelled subscription gets no PUBLISH_DONE, and its open data
1130
+ // streams are reset (§3.1.2).
1131
+ resetDataStreams(subscriber);
1132
+ }
1133
+ finally {
1134
+ const alreadyEnding = subscriber.finished;
1135
+ subscriber.finished = true;
1136
+ track.subscribers = track.subscribers.filter((s) => s !== subscriber);
1137
+ settleRequest();
1138
+ // The subscription is over both ways — mirror of the namespace
1139
+ // stream's cleanup: an unclosed response direction would leak a
1140
+ // half-open stream per cancelled request until the transport closes.
1141
+ // An already-aborted writer rejects harmlessly. A subscription this
1142
+ // side ended closes its writer after PUBLISH_DONE instead.
1143
+ if (!alreadyEnding)
1144
+ void writer.close().catch(() => { });
1145
+ if (!this.#destroyed && subscriber.reported) {
1146
+ this.#callbacks.onSubscribeEnd?.({ requestId: subscribe.requestId });
1147
+ // Only accepted, forwarding subscriptions may carry the binding:
1148
+ // one whose SUBSCRIBE_OK is still in flight could yet fail (its
1149
+ // removal would strand `trackBindings` on an alias the peer never
1150
+ // registered), and one with Forward State 0 forbids data. When a
1151
+ // pending one accepts, it emits its own binding.
1152
+ const binding = track.subscribers.filter((s) => !s.finished && s.accepted && s.forwarding).at(-1);
1153
+ this.#callbacks.onTrackBinding?.({ trackName: track.trackName, trackAlias: binding?.trackAlias });
1154
+ }
1155
+ }
1156
+ }
1157
+ }
1158
+ /**
1159
+ * Create a publish-capable MOQT session driver over an established transport.
1160
+ *
1161
+ * @example
1162
+ * ```ts
1163
+ * const session = createMoqtPublishSession(transport, {
1164
+ * callbacks: { onSubscribe: (s) => console.log('serving', s.trackName) },
1165
+ * });
1166
+ * await session.ready;
1167
+ * session.announce(['live', 'abc123']);
1168
+ * const track = session.registerTrack({ trackNamespace: ['live', 'abc123'], trackName: 'video' });
1169
+ * ```;
1170
+ */
1171
+ export function createMoqtPublishSession(transport, config = {}) {
1172
+ return new MoqtPublishSessionImpl(transport, config);
1173
+ }
1174
+ //# sourceMappingURL=publish-session.js.map