@caprid/moq-core 0.0.0 → 0.1.0

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