@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,908 @@
1
+ /**
2
+ * Pure MOQT session protocol driver (moq-transport draft-22), subscribe side only.
3
+ *
4
+ * Owns the protocol mechanics over an established transport: the SETUP exchange on paired unidirectional control
5
+ * streams (§6.3), request-stream bookkeeping keyed by Request ID (§6.4.2.1 — client IDs are even, starting at 0), routing
6
+ * of incoming data streams to subscriptions (by Track Alias) and fetches (by Request ID), GOAWAY handling, and session
7
+ * termination.
8
+ *
9
+ * Deliberately callback-shaped with NO signals (like `onMediaSourceReadyStateChange`) — signal awareness enters at the
10
+ * `playback/` layer, where the moq-session actor binds these callbacks to SPF state. The transport is a structural
11
+ * subset of `WebTransport`, so tests drive the driver with an in-memory fake and the DOM layer passes a real
12
+ * `WebTransport` unchanged.
13
+ *
14
+ * Version negotiation happens at connection time (ALPN / `WT-Available-Protocols`, `MOQT_PROTOCOL_ID`), before this
15
+ * driver sees the transport.
16
+ *
17
+ * Datagram reception is not implemented: MSF maps every object to its own stream, so a subscribe-only MSF engine never
18
+ * legitimately receives OBJECT_DATAGRAMs.
19
+ */
20
+ import { StreamReader, utf8Encode } from './bytes.js';
21
+ import { decodeControlMessage, encodeFetch, encodeRequestError, encodeRequestOk, encodeRequestUpdate, encodeSetup, encodeSubscribe, encodeSubscribeNamespace, encodeTrackStatus, MESSAGE_TYPE, REQUEST_ERROR_CODE, resolveMoqtProtocol, SETUP_OPTION, } from './control-messages.js';
22
+ import { isMoqtProtocolError, MoqtProtocolError, SESSION_ERROR } from './errors.js';
23
+ import { isSubgroupHeaderType, readFetchEntries, readFetchHeader, readSubgroupHeader, readSubgroupObjects, STREAM_TYPE, } from './object-stream.js';
24
+ import { openRequestStream } from './request-stream.js';
25
+ /** Validate once; returned promises are diagnosed and observed, never awaited by delivery. */
26
+ function synchronousSubscriptionHandlers(handlers) {
27
+ const result = {};
28
+ const names = [
29
+ 'onOk',
30
+ 'onError',
31
+ 'onObject',
32
+ 'onSubgroupEnd',
33
+ 'onSubgroupReset',
34
+ 'onDone',
35
+ 'onUpdateOk',
36
+ 'onStateNotify',
37
+ 'onGoaway',
38
+ ];
39
+ for (const name of names) {
40
+ const callback = handlers[name];
41
+ if (!callback)
42
+ continue;
43
+ if (Object.prototype.toString.call(callback) === '[object AsyncFunction]') {
44
+ throw new TypeError(`${name} must be synchronous; use Relay subscribeEvents() for async consumption`);
45
+ }
46
+ let reportedAsyncResult = false;
47
+ Object.assign(result, {
48
+ [name]: (...args) => {
49
+ const returned = Reflect.apply(callback, handlers, args);
50
+ if (returned &&
51
+ (typeof returned === 'object' || typeof returned === 'function') &&
52
+ 'then' in returned &&
53
+ typeof returned.then === 'function') {
54
+ // JS promises cannot be cancelled. Observe failures without serializing delivery.
55
+ void Promise.resolve(returned).catch(() => { });
56
+ if (!reportedAsyncResult) {
57
+ reportedAsyncResult = true;
58
+ // biome-ignore lint/suspicious/noConsole: public diagnostic for unsupported async callbacks
59
+ console.error(new TypeError(`${name} returned a promise; callbacks must be synchronous; use Relay subscribeEvents()`));
60
+ }
61
+ }
62
+ },
63
+ });
64
+ }
65
+ return result;
66
+ }
67
+ const DEFAULT_UNKNOWN_ALIAS_TIMEOUT_MS = 2000;
68
+ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
69
+ const DEFAULT_IMPLEMENTATION_NAME = '@caprid/moq-core';
70
+ /**
71
+ * A request failure that arrives as a _stream_ event — FIN before any response, a transport reset, or the response
72
+ * timeout — rather than as a REQUEST_ERROR message. Shaped as a `RequestError` so consumers have one failure path
73
+ * regardless of how the request died.
74
+ */
75
+ function streamFailure(reason, errorCode = REQUEST_ERROR_CODE.INTERNAL_ERROR) {
76
+ const failure = { errorCode, retryInterval: 0, reason };
77
+ streamFailures.add(failure);
78
+ return failure;
79
+ }
80
+ const streamFailures = new WeakSet();
81
+ /**
82
+ * Whether the session synthesized this request failure from a stream event (FIN before any response, a stream reset,
83
+ * a failed stream open, the response timeout, or the session ending) rather than receiving a REQUEST_ERROR message.
84
+ * A real transport can fail a request's stream some tasks before it reports its own closure, so a consumer that wants
85
+ * to tell a lost connection from a rejection waits for `closed` before trusting such a failure.
86
+ */
87
+ export function isStreamFailure(error) {
88
+ return streamFailures.has(error);
89
+ }
90
+ // ============================================================================
91
+ // Session driver
92
+ // ============================================================================
93
+ class MoqtSessionImpl {
94
+ ready;
95
+ #transport;
96
+ /** The negotiated draft, which selects the parameter codec. */
97
+ #protocol;
98
+ #config;
99
+ #callbacks;
100
+ #nextRequestId = 0; // client request IDs: even, starting at 0 (§6.4.2.1)
101
+ /** Every inbound request ID ever seen. Reuse, or the client's (even) parity, closes the session (§6.4.2.1). */
102
+ #peerRequestIds = new Set();
103
+ #subscriptions = new Map();
104
+ #fetches = new Map();
105
+ #trackStatuses = new Map();
106
+ #namespaceSubscriptions = new Map();
107
+ #aliasRoutes = new Map();
108
+ #aliasWaiters = new Map();
109
+ #resolveReady;
110
+ #rejectReady;
111
+ #controlWriter;
112
+ #receivedServerSetup = false;
113
+ #receivedControlGoaway = false;
114
+ #destroyed = false;
115
+ constructor(transport, config = {}) {
116
+ this.#transport = transport;
117
+ this.#protocol = resolveMoqtProtocol(transport.protocol);
118
+ this.#config = config;
119
+ this.#callbacks = config.callbacks ?? {};
120
+ this.ready = new Promise((resolve, reject) => {
121
+ this.#resolveReady = resolve;
122
+ this.#rejectReady = reject;
123
+ });
124
+ // Consumers may observe readiness through `onClosed` alone.
125
+ this.ready.catch(() => { });
126
+ void this.#start();
127
+ }
128
+ // --------------------------------------------------------------------------
129
+ // Session lifecycle
130
+ // --------------------------------------------------------------------------
131
+ async #start() {
132
+ // Accept loops start first: the peer's streams must be processed even
133
+ // while our own SETUP write is still propagating (either peer may send
134
+ // stream data first, §6.3).
135
+ void this.#acceptUnidirectionalStreams();
136
+ void this.#acceptBidirectionalStreams();
137
+ void this.#transport.closed.then(() => this.#handleClosed(undefined), (error) => this.#handleClosed(error));
138
+ try {
139
+ const control = await this.#transport.createUnidirectionalStream();
140
+ this.#controlWriter = control.getWriter();
141
+ const options = [
142
+ {
143
+ type: SETUP_OPTION.MOQT_IMPLEMENTATION,
144
+ value: utf8Encode(this.#config.implementationName ?? DEFAULT_IMPLEMENTATION_NAME),
145
+ },
146
+ ...(this.#config.setupOptions ?? []),
147
+ ];
148
+ await this.#controlWriter.write(encodeSetup(options));
149
+ }
150
+ catch (error) {
151
+ this.#fatal(error);
152
+ }
153
+ }
154
+ #fatal(error) {
155
+ if (this.#destroyed)
156
+ return;
157
+ const closeCode = isMoqtProtocolError(error) ? error.code : SESSION_ERROR.INTERNAL_ERROR;
158
+ try {
159
+ this.#transport.close({ closeCode, reason: error instanceof Error ? error.message : 'session error' });
160
+ }
161
+ catch {
162
+ // transport already gone
163
+ }
164
+ this.#handleClosed(error);
165
+ }
166
+ #handleClosed(error, { expected = false } = {}) {
167
+ if (this.#destroyed)
168
+ return;
169
+ this.#destroyed = true;
170
+ const setupError = this.#receivedServerSetup
171
+ ? undefined
172
+ : (error ?? new MoqtProtocolError('session closed before server SETUP'));
173
+ if (setupError !== undefined)
174
+ this.#rejectReady(setupError);
175
+ for (const waiters of this.#aliasWaiters.values()) {
176
+ for (const waiter of waiters) {
177
+ clearTimeout(waiter.timer);
178
+ waiter.resolve(undefined);
179
+ }
180
+ }
181
+ this.#aliasWaiters.clear();
182
+ // Requests still awaiting their first response die with the session. An
183
+ // unexpected close (transport drop) is a failure each of them has to
184
+ // hear about — otherwise a dropped transport leaves subscribers pending
185
+ // forever. A deliberate `close()` is ordinary teardown, and cancelled
186
+ // requests already have their answer.
187
+ const records = [
188
+ ...this.#subscriptions.values(),
189
+ ...this.#fetches.values(),
190
+ ...this.#trackStatuses.values(),
191
+ ...this.#namespaceSubscriptions.values(),
192
+ ];
193
+ const pending = expected ? [] : records.filter((r) => !r.settled && !r.cancelled);
194
+ for (const record of records) {
195
+ this.#settleRequest(record);
196
+ record.stream?.cancel(error);
197
+ }
198
+ for (const record of this.#subscriptions.values())
199
+ this.#removeSubscription(record);
200
+ this.#subscriptions.clear();
201
+ this.#fetches.clear();
202
+ this.#trackStatuses.clear();
203
+ this.#namespaceSubscriptions.clear();
204
+ this.#aliasRoutes.clear();
205
+ this.#controlWriter = undefined;
206
+ const failure = streamFailure(error instanceof Error ? error.message : 'session closed before the request was answered');
207
+ for (const record of pending)
208
+ record.handlers.onError?.(failure);
209
+ // A transport that drops before server SETUP is a session failure even
210
+ // when the close itself was clean — callback-only consumers observing
211
+ // `onClosed` alone must see the error too. A deliberate local `close()`
212
+ // stays a clean close.
213
+ const closeError = error ?? (expected ? undefined : setupError);
214
+ this.#callbacks.onClosed?.(closeError === undefined ? {} : { error: closeError });
215
+ }
216
+ close(closeCode = SESSION_ERROR.NO_ERROR, reason = '') {
217
+ this.#close(closeCode, reason);
218
+ }
219
+ #close(closeCode, reason, error) {
220
+ if (this.#destroyed)
221
+ return;
222
+ // No GOAWAY: one written as the transport closes gives the peer nothing to act on, and the
223
+ // session has no drain to offer. The publisher follows the same rule; see spec/behavior.md,
224
+ // "Relay interop deviations".
225
+ try {
226
+ this.#transport.close({ closeCode, reason });
227
+ }
228
+ catch {
229
+ // transport already gone
230
+ }
231
+ this.#handleClosed(error, { expected: error === undefined });
232
+ }
233
+ destroy(error) {
234
+ this.#close(SESSION_ERROR.NO_ERROR, '', error);
235
+ }
236
+ // --------------------------------------------------------------------------
237
+ // Requests
238
+ // --------------------------------------------------------------------------
239
+ #allocateRequestId() {
240
+ const id = this.#nextRequestId;
241
+ this.#nextRequestId += 2;
242
+ return id;
243
+ }
244
+ /**
245
+ * Request IDs are consumed once per session (§6.4.2.1), by every request-initiating message, accepted or not. This
246
+ * endpoint is always the client, so the peer's ids are odd; a reused id or an even one closes the session with
247
+ * INVALID_REQUEST_ID.
248
+ */
249
+ #claimPeerRequestId(requestId) {
250
+ if (requestId % 2 !== 1) {
251
+ throw new MoqtProtocolError(`peer sent even request id ${requestId}`, SESSION_ERROR.INVALID_REQUEST_ID);
252
+ }
253
+ if (this.#peerRequestIds.has(requestId)) {
254
+ throw new MoqtProtocolError(`peer reused request id ${requestId}`, SESSION_ERROR.INVALID_REQUEST_ID);
255
+ }
256
+ this.#peerRequestIds.add(requestId);
257
+ }
258
+ subscribe(options, callbacks = {}) {
259
+ const handlers = synchronousSubscriptionHandlers(callbacks);
260
+ const requestId = this.#allocateRequestId();
261
+ const record = { requestId, handlers, cancelled: false, settled: false, readers: new Set() };
262
+ this.#subscriptions.set(requestId, record);
263
+ const message = encodeSubscribe({
264
+ requestId,
265
+ trackNamespace: options.trackNamespace,
266
+ trackName: options.trackName,
267
+ parameters: options.parameters,
268
+ }, this.#protocol);
269
+ void this.#openRequest(message, record, (msg) => this.#handleSubscriptionMessage(record, msg), (error) => {
270
+ this.#removeSubscription(record);
271
+ handlers.onError?.(error);
272
+ }, () => {
273
+ // §6.4.2.2: once the publisher's FIN after PUBLISH_DONE completes the request, the requester
274
+ // SHOULD FIN too. A publisher closing waits for it before closing the transport.
275
+ if (record.publisherDone)
276
+ record.stream?.finWrite().catch(() => { });
277
+ });
278
+ return {
279
+ requestId,
280
+ update: (parameters) => {
281
+ // REQUEST_UPDATE consumes a Request ID of its own (§6.4.2.1); the stream
282
+ // it travels on is what names the subscription. Reusing the
283
+ // subscription's id would be a duplicate the peer MUST close on.
284
+ record.stream?.send(encodeRequestUpdate(this.#allocateRequestId(), parameters, this.#protocol)).catch(() => { });
285
+ },
286
+ cancel: (reason) => this.#cancelSubscription(record, reason),
287
+ };
288
+ }
289
+ fetch(options, handlers = {}) {
290
+ const requestId = this.#allocateRequestId();
291
+ const record = {
292
+ requestId,
293
+ handlers,
294
+ groupOrder: options.parameters?.groupOrder ?? 'ascending',
295
+ cancelled: false,
296
+ settled: false,
297
+ };
298
+ this.#fetches.set(requestId, record);
299
+ const request = { requestId, ...options };
300
+ void this.#openRequest(encodeFetch(request, this.#protocol), record, (msg) => this.#handleFetchMessage(record, msg), (error) => {
301
+ this.#fetches.delete(requestId);
302
+ handlers.onError?.(error);
303
+ });
304
+ return {
305
+ requestId,
306
+ cancel: (reason) => this.#cancelFetch(record, reason),
307
+ };
308
+ }
309
+ trackStatus(options, handlers = {}) {
310
+ const requestId = this.#allocateRequestId();
311
+ const record = { requestId, handlers, cancelled: false, settled: false };
312
+ // Tracked so session teardown fails a still-pending TRACK_STATUS the
313
+ // same way it fails pending subscriptions and fetches. Answered
314
+ // requests leave the map — nothing else arrives on their stream.
315
+ this.#trackStatuses.set(requestId, record);
316
+ const message = encodeTrackStatus({
317
+ requestId,
318
+ trackNamespace: options.trackNamespace,
319
+ trackName: options.trackName,
320
+ parameters: options.parameters,
321
+ }, this.#protocol);
322
+ void this.#openRequest(message, record, (msg) => {
323
+ if (msg.kind === 'request-ok') {
324
+ this.#settleRequest(record);
325
+ this.#trackStatuses.delete(requestId);
326
+ handlers.onOk?.({ parameters: msg.parameters, trackProperties: msg.trackProperties });
327
+ record.stream?.finWrite().catch(() => { });
328
+ }
329
+ else if (msg.kind === 'request-error') {
330
+ this.#settleRequest(record);
331
+ this.#trackStatuses.delete(requestId);
332
+ handlers.onError?.(msg);
333
+ record.stream?.finWrite().catch(() => { });
334
+ }
335
+ }, (error) => {
336
+ this.#trackStatuses.delete(requestId);
337
+ handlers.onError?.(error);
338
+ });
339
+ }
340
+ subscribeNamespace(options, handlers = {}) {
341
+ const requestId = this.#allocateRequestId();
342
+ const record = {
343
+ requestId,
344
+ handlers,
345
+ cancelled: false,
346
+ settled: false,
347
+ active: new Map(),
348
+ };
349
+ const message = encodeSubscribeNamespace({
350
+ requestId,
351
+ trackNamespacePrefix: options.trackNamespacePrefix,
352
+ parameters: options.parameters,
353
+ }, this.#protocol);
354
+ this.#namespaceSubscriptions.set(requestId, record);
355
+ // Once only, and never after REQUEST_ERROR answered the request: that removes the record first.
356
+ const end = (error) => {
357
+ if (!this.#namespaceSubscriptions.delete(requestId))
358
+ return;
359
+ // A failed stream is dropped here: session teardown only reaches the records it still holds.
360
+ if (error !== undefined)
361
+ record.stream?.cancel(error);
362
+ // §9.15: a FIN or reset on the response stream SHOULD read as NAMESPACE_DONE for each active namespace.
363
+ const active = [...record.active.values()];
364
+ record.active.clear();
365
+ for (const suffix of active)
366
+ handlers.onNamespaceDone?.(suffix);
367
+ handlers.onEnd?.(error === undefined ? {} : { error });
368
+ };
369
+ void this.#openRequest(message, record, (msg) => this.#handleNamespaceMessage(record, msg), (error) => {
370
+ // Removing the record puts the stream out of teardown's reach, so drop it now.
371
+ record.stream?.cancel(error);
372
+ this.#namespaceSubscriptions.delete(requestId);
373
+ handlers.onError?.(error);
374
+ }, () => {
375
+ // §6.4.2.2: the requester SHOULD FIN once the peer's FIN completes the request.
376
+ record.stream?.finWrite().catch(() => { });
377
+ end();
378
+ }, end);
379
+ return {
380
+ requestId,
381
+ cancel: (reason) => {
382
+ if (record.cancelled)
383
+ return;
384
+ record.cancelled = true;
385
+ record.pendingCancelReason = reason;
386
+ this.#settleRequest(record);
387
+ record.stream?.cancel(reason);
388
+ this.#namespaceSubscriptions.delete(requestId);
389
+ },
390
+ };
391
+ }
392
+ /**
393
+ * Open a request stream and bind its lifecycle to `record`.
394
+ *
395
+ * `onFailure` is the caller's "this request died without answering me" path — `request-stream` deliberately leaves
396
+ * that judgement here, since only the session knows which messages a given request kind requires. It fires for a FIN
397
+ * before any response, a non-protocol stream error (transport reset), and the response timeout; a protocol error
398
+ * still kills the whole session. Once `record.settled` is set the same events are ordinary end-of-request signals and
399
+ * are ignored, except that a FIN calls `onEnd` and a stream error calls `onSettledError` when given.
400
+ */
401
+ async #openRequest(message, record, onMessage, onFailure, onEnd, onSettledError) {
402
+ const fail = (error) => {
403
+ if (record.settled || record.cancelled || this.#destroyed)
404
+ return;
405
+ this.#settleRequest(record);
406
+ onFailure(error);
407
+ };
408
+ let stream;
409
+ try {
410
+ stream = await this.#transport.createBidirectionalStream();
411
+ }
412
+ catch (error) {
413
+ // Losing the ability to open streams is a session-level failure, but
414
+ // this request also has to hear about it.
415
+ fail(streamFailure(error instanceof Error ? error.message : 'failed to open request stream'));
416
+ if (!this.#destroyed)
417
+ this.#fatal(error);
418
+ return;
419
+ }
420
+ const timeout = this.#config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
421
+ if (timeout > 0 && !record.settled && !record.cancelled) {
422
+ record.responseTimer = setTimeout(() => {
423
+ const failure = streamFailure('no response before the request timeout', REQUEST_ERROR_CODE.TIMEOUT);
424
+ // The stream dies with the request: left open, a late SUBSCRIBE_OK
425
+ // would fire onOk after onError and re-register the alias route of
426
+ // a subscription already reported dead.
427
+ record.stream?.cancel(failure);
428
+ fail(failure);
429
+ }, timeout);
430
+ }
431
+ record.stream = openRequestStream(stream, message, {
432
+ onMessage,
433
+ onFin: () => {
434
+ if (!record.settled) {
435
+ fail(streamFailure('request stream closed before a response'));
436
+ }
437
+ else if (!record.cancelled && !this.#destroyed) {
438
+ onEnd?.();
439
+ }
440
+ },
441
+ onError: (error) => {
442
+ if (isMoqtProtocolError(error)) {
443
+ this.#fatal(error);
444
+ return;
445
+ }
446
+ if (record.settled) {
447
+ if (!record.cancelled && !this.#destroyed)
448
+ onSettledError?.(error);
449
+ return;
450
+ }
451
+ fail(streamFailure(error instanceof Error ? error.message : 'request stream failed'));
452
+ },
453
+ }, this.#protocol);
454
+ // A cancel that raced the stream opening lands here.
455
+ if (record.cancelled)
456
+ record.stream.cancel(record.pendingCancelReason);
457
+ }
458
+ /** Mark a request answered (or dead) and disarm its response timeout. */
459
+ #settleRequest(record) {
460
+ record.settled = true;
461
+ if (record.responseTimer !== undefined) {
462
+ clearTimeout(record.responseTimer);
463
+ record.responseTimer = undefined;
464
+ }
465
+ }
466
+ #handleSubscriptionMessage(record, message) {
467
+ if (record.cancelled)
468
+ return;
469
+ switch (message.kind) {
470
+ case 'subscribe-ok': {
471
+ if (record.trackAlias !== undefined && record.trackAlias !== message.trackAlias) {
472
+ this.#fatal(new MoqtProtocolError('SUBSCRIBE_OK changed track alias'));
473
+ return;
474
+ }
475
+ const existing = this.#aliasRoutes.get(message.trackAlias);
476
+ if (existing && existing !== record) {
477
+ this.#fatal(new MoqtProtocolError('duplicate track alias', SESSION_ERROR.DUPLICATE_TRACK_ALIAS));
478
+ return;
479
+ }
480
+ this.#settleRequest(record);
481
+ record.trackAlias = message.trackAlias;
482
+ this.#aliasRoutes.set(message.trackAlias, record);
483
+ const waiters = this.#aliasWaiters.get(message.trackAlias);
484
+ if (waiters) {
485
+ this.#aliasWaiters.delete(message.trackAlias);
486
+ for (const waiter of waiters) {
487
+ clearTimeout(waiter.timer);
488
+ waiter.resolve(record);
489
+ }
490
+ }
491
+ record.handlers.onOk?.({
492
+ trackAlias: message.trackAlias,
493
+ parameters: message.parameters,
494
+ trackProperties: message.trackProperties,
495
+ });
496
+ break;
497
+ }
498
+ case 'request-ok':
499
+ record.handlers.onUpdateOk?.();
500
+ break;
501
+ case 'request-error':
502
+ this.#settleRequest(record);
503
+ this.#removeSubscription(record);
504
+ record.handlers.onError?.(message);
505
+ break;
506
+ case 'publish-done':
507
+ // Data streams may still be inbound; the alias route stays until
508
+ // the subscription is cancelled or the session ends, so late
509
+ // subgroups still deliver (§9.9 leaves the timing policy to us).
510
+ record.publisherDone = true;
511
+ record.handlers.onDone?.(message);
512
+ break;
513
+ case 'publish-state-notify':
514
+ // Unilateral (§9.10): no REQUEST_OK back, and it does not count
515
+ // against MAX_REQUEST_UPDATES.
516
+ record.handlers.onStateNotify?.(message.parameters);
517
+ break;
518
+ case 'goaway':
519
+ record.handlers.onGoaway?.(message);
520
+ break;
521
+ default:
522
+ this.#fatal(new MoqtProtocolError(`unexpected ${message.kind} on a subscribe request stream`));
523
+ }
524
+ }
525
+ #handleFetchMessage(record, message) {
526
+ switch (message.kind) {
527
+ case 'fetch-ok':
528
+ this.#settleRequest(record);
529
+ record.handlers.onOk?.({
530
+ endOfTrack: message.endOfTrack,
531
+ endLocation: message.endLocation,
532
+ parameters: message.parameters,
533
+ trackProperties: message.trackProperties,
534
+ });
535
+ break;
536
+ // Some deployed relays accept a FETCH with the generic REQUEST_OK
537
+ // instead of the FETCH_OK §9.11 mandates. It
538
+ // carries no End Location/End Of Track, so `onOk` can't fire — the
539
+ // fetch's actual completion still surfaces via onEntry/onEnd on the
540
+ // data stream, which this response has no bearing on. It is still
541
+ // the response, so it has to settle the request: leaving the timer
542
+ // armed would fail an answered fetch (and drop its data stream)
543
+ // once the deadline passed.
544
+ case 'request-ok':
545
+ this.#settleRequest(record);
546
+ break;
547
+ case 'request-error':
548
+ this.#settleRequest(record);
549
+ this.#fetches.delete(record.requestId);
550
+ record.handlers.onError?.(message);
551
+ break;
552
+ case 'goaway':
553
+ record.handlers.onGoaway?.(message);
554
+ break;
555
+ default:
556
+ this.#fatal(new MoqtProtocolError(`unexpected ${message.kind} on a fetch request stream`));
557
+ }
558
+ }
559
+ #handleNamespaceMessage(record, message) {
560
+ // Frames decoded in one read keep arriving after a frame among them closed the session.
561
+ if (record.cancelled || this.#destroyed)
562
+ return;
563
+ switch (message.kind) {
564
+ case 'request-ok':
565
+ if (record.settled) {
566
+ this.#fatal(new MoqtProtocolError('second REQUEST_OK on a subscribe-namespace request stream'));
567
+ return;
568
+ }
569
+ this.#settleRequest(record);
570
+ record.accepted = true;
571
+ record.handlers.onOk?.();
572
+ break;
573
+ case 'request-error':
574
+ // After REQUEST_OK the response is spent: an error then is outside the stream's grammar.
575
+ if (record.settled) {
576
+ this.#fatal(new MoqtProtocolError('REQUEST_ERROR after REQUEST_OK on a subscribe-namespace request stream'));
577
+ return;
578
+ }
579
+ this.#settleRequest(record);
580
+ this.#namespaceSubscriptions.delete(record.requestId);
581
+ record.handlers.onError?.(message);
582
+ record.stream?.finWrite().catch(() => { });
583
+ break;
584
+ case 'namespace':
585
+ case 'namespace-done':
586
+ // Entries follow REQUEST_OK (§9.15); one before it, or after REQUEST_ERROR, is outside the
587
+ // stream's grammar.
588
+ if (!record.accepted) {
589
+ this.#fatal(new MoqtProtocolError(`${message.kind} before REQUEST_OK on a subscribe-namespace request stream`));
590
+ return;
591
+ }
592
+ if (message.kind === 'namespace') {
593
+ record.active.set(JSON.stringify(message.trackNamespaceSuffix), message.trackNamespaceSuffix);
594
+ record.handlers.onNamespace?.(message.trackNamespaceSuffix);
595
+ }
596
+ else if (record.active.delete(JSON.stringify(message.trackNamespaceSuffix))) {
597
+ record.handlers.onNamespaceDone?.(message.trackNamespaceSuffix);
598
+ }
599
+ else {
600
+ // §9.15: NAMESPACE_DONE before the corresponding NAMESPACE MUST close the session.
601
+ this.#fatal(new MoqtProtocolError('NAMESPACE_DONE before its NAMESPACE on a subscribe-namespace request stream'));
602
+ }
603
+ break;
604
+ case 'goaway':
605
+ record.handlers.onGoaway?.(message);
606
+ break;
607
+ default:
608
+ this.#fatal(new MoqtProtocolError(`unexpected ${message.kind} on a subscribe-namespace request stream`));
609
+ }
610
+ }
611
+ #cancelSubscription(record, reason) {
612
+ if (record.cancelled)
613
+ return;
614
+ record.cancelled = true;
615
+ record.pendingCancelReason = reason;
616
+ this.#settleRequest(record);
617
+ record.stream?.cancel(reason);
618
+ this.#removeSubscription(record);
619
+ }
620
+ #removeSubscription(record) {
621
+ record.cancelled = true;
622
+ record.stream?.cancel(record.pendingCancelReason);
623
+ for (const reader of record.readers)
624
+ void reader.cancel(record.pendingCancelReason).catch(() => { });
625
+ record.readers.clear();
626
+ this.#subscriptions.delete(record.requestId);
627
+ if (record.trackAlias !== undefined && this.#aliasRoutes.get(record.trackAlias) === record) {
628
+ this.#aliasRoutes.delete(record.trackAlias);
629
+ }
630
+ }
631
+ #cancelFetch(record, reason) {
632
+ if (record.cancelled)
633
+ return;
634
+ record.cancelled = true;
635
+ record.pendingCancelReason = reason;
636
+ this.#settleRequest(record);
637
+ record.stream?.cancel(reason);
638
+ this.#fetches.delete(record.requestId);
639
+ }
640
+ // --------------------------------------------------------------------------
641
+ // Incoming unidirectional streams (control, subgroup, fetch, padding)
642
+ // --------------------------------------------------------------------------
643
+ async #acceptUnidirectionalStreams() {
644
+ const reader = this.#transport.incomingUnidirectionalStreams.getReader();
645
+ try {
646
+ while (true) {
647
+ const { done, value } = await reader.read();
648
+ if (done)
649
+ break;
650
+ void this.#handleUnidirectionalStream(value).catch((error) => {
651
+ if (isMoqtProtocolError(error))
652
+ this.#fatal(error);
653
+ });
654
+ }
655
+ }
656
+ catch {
657
+ // Transport went away; `closed` handles the surfacing.
658
+ }
659
+ finally {
660
+ reader.releaseLock();
661
+ }
662
+ }
663
+ async #handleUnidirectionalStream(stream) {
664
+ const reader = new StreamReader(stream);
665
+ const streamType = await reader.readVarint();
666
+ if (streamType === STREAM_TYPE.SETUP) {
667
+ await this.#runControlStream(reader);
668
+ return;
669
+ }
670
+ if (isSubgroupHeaderType(streamType)) {
671
+ const header = await readSubgroupHeader(reader, streamType);
672
+ await this.#runSubgroupStream(reader, header);
673
+ return;
674
+ }
675
+ if (streamType === STREAM_TYPE.FETCH_HEADER) {
676
+ const { requestId } = await readFetchHeader(reader);
677
+ await this.#runFetchStream(reader, requestId);
678
+ return;
679
+ }
680
+ if (streamType === STREAM_TYPE.PADDING) {
681
+ await reader.cancel();
682
+ return;
683
+ }
684
+ await reader.cancel();
685
+ throw new MoqtProtocolError(`unknown unidirectional stream type 0x${streamType.toString(16)}`);
686
+ }
687
+ /** Read one control-message frame using the pull-based stream reader. */
688
+ async #readControlFrame(reader, type) {
689
+ const high = await reader.readUint8();
690
+ const low = await reader.readUint8();
691
+ const body = await reader.readBytes(high * 256 + low);
692
+ return decodeControlMessage({ type, body }, this.#protocol);
693
+ }
694
+ async #runControlStream(reader) {
695
+ // The stream-type varint (0x2F00) doubles as the first message's type.
696
+ const setup = await this.#readControlFrame(reader, MESSAGE_TYPE.SETUP);
697
+ if (setup.kind !== 'setup')
698
+ throw new MoqtProtocolError('control stream did not begin with SETUP');
699
+ if (this.#receivedServerSetup) {
700
+ throw new MoqtProtocolError('received a second control stream');
701
+ }
702
+ this.#receivedServerSetup = true;
703
+ this.#resolveReady();
704
+ this.#callbacks.onReady?.(setup.options);
705
+ // Subsequent control-stream messages: GOAWAY (at most once).
706
+ while (!(await reader.atEnd())) {
707
+ const type = await reader.readVarint();
708
+ const message = await this.#readControlFrame(reader, type);
709
+ if (message.kind !== 'goaway')
710
+ throw new MoqtProtocolError(`unexpected ${message.kind} on the control stream`);
711
+ if (this.#receivedControlGoaway) {
712
+ throw new MoqtProtocolError('received more than one GOAWAY on the control stream');
713
+ }
714
+ this.#receivedControlGoaway = true;
715
+ this.#callbacks.onGoaway?.(message);
716
+ }
717
+ // A closed control stream ends the session (§6.3).
718
+ if (!this.#destroyed) {
719
+ this.#fatal(new MoqtProtocolError('peer closed its control stream'));
720
+ }
721
+ }
722
+ /** Wait briefly for a subscription to claim `trackAlias` (§11.3.1 buffering). */
723
+ #waitForAlias(trackAlias) {
724
+ const known = this.#aliasRoutes.get(trackAlias);
725
+ if (known || this.#destroyed)
726
+ return Promise.resolve(known);
727
+ return new Promise((resolve) => {
728
+ const waiters = this.#aliasWaiters.get(trackAlias) ?? [];
729
+ const timeout = this.#config.unknownAliasTimeoutMs ?? DEFAULT_UNKNOWN_ALIAS_TIMEOUT_MS;
730
+ const waiter = {
731
+ resolve,
732
+ timer: setTimeout(() => {
733
+ const remaining = this.#aliasWaiters.get(trackAlias)?.filter((w) => w !== waiter);
734
+ if (remaining?.length)
735
+ this.#aliasWaiters.set(trackAlias, remaining);
736
+ else
737
+ this.#aliasWaiters.delete(trackAlias);
738
+ resolve(undefined);
739
+ }, timeout),
740
+ };
741
+ waiters.push(waiter);
742
+ this.#aliasWaiters.set(trackAlias, waiters);
743
+ });
744
+ }
745
+ async #runSubgroupStream(reader, header) {
746
+ const record = await this.#waitForAlias(header.trackAlias);
747
+ if (!record || record.cancelled) {
748
+ await reader.cancel();
749
+ return;
750
+ }
751
+ record.readers.add(reader);
752
+ let lastSubgroupId = header.subgroupIdMode === 'explicit' ? header.subgroupId : 0;
753
+ try {
754
+ for await (const object of readSubgroupObjects(reader, header)) {
755
+ if (record.cancelled) {
756
+ await reader.cancel();
757
+ return;
758
+ }
759
+ lastSubgroupId = object.subgroupId;
760
+ record.handlers.onObject?.(object);
761
+ }
762
+ if (record.cancelled)
763
+ return;
764
+ record.handlers.onSubgroupEnd?.({
765
+ groupId: header.groupId,
766
+ subgroupId: lastSubgroupId,
767
+ endOfGroup: header.endOfGroup,
768
+ });
769
+ }
770
+ catch (error) {
771
+ if (record.cancelled)
772
+ return;
773
+ if (isMoqtProtocolError(error))
774
+ throw error;
775
+ // A reset stream is a delivery event (timeout, cancellation), not a
776
+ // session error — surface it to the subscription.
777
+ record.handlers.onSubgroupReset?.({ groupId: header.groupId, error });
778
+ }
779
+ finally {
780
+ record.readers.delete(reader);
781
+ }
782
+ }
783
+ async #runFetchStream(reader, requestId) {
784
+ const record = this.#fetches.get(requestId);
785
+ // A FETCH_HEADER naming no fetch of ours is dropped, not fatal. That
786
+ // includes a fill fetch stream (§3.4), keyed by a SUBSCRIBE's Request
787
+ // ID — this subscriber never asks for one, so none is expected.
788
+ if (!record || record.cancelled) {
789
+ await reader.cancel();
790
+ return;
791
+ }
792
+ try {
793
+ for await (const entry of readFetchEntries(reader, record.groupOrder)) {
794
+ if (record.cancelled) {
795
+ await reader.cancel();
796
+ return;
797
+ }
798
+ record.handlers.onEntry?.(entry);
799
+ }
800
+ record.handlers.onEnd?.();
801
+ }
802
+ catch (error) {
803
+ if (isMoqtProtocolError(error))
804
+ throw error;
805
+ // A reset mid-replay means entries may be missing — never report it
806
+ // as the clean FIN `onEnd` promises.
807
+ record.handlers.onReset?.({ error });
808
+ }
809
+ }
810
+ // --------------------------------------------------------------------------
811
+ // Incoming bidirectional streams (server-initiated requests)
812
+ // --------------------------------------------------------------------------
813
+ async #acceptBidirectionalStreams() {
814
+ const reader = this.#transport.incomingBidirectionalStreams.getReader();
815
+ try {
816
+ while (true) {
817
+ const { done, value } = await reader.read();
818
+ if (done)
819
+ break;
820
+ void this.#handleIncomingRequest(value).catch((error) => {
821
+ if (isMoqtProtocolError(error))
822
+ this.#fatal(error);
823
+ });
824
+ }
825
+ }
826
+ catch {
827
+ // Transport went away.
828
+ }
829
+ finally {
830
+ reader.releaseLock();
831
+ }
832
+ }
833
+ async #handleIncomingRequest(stream) {
834
+ const reader = new StreamReader(stream.readable);
835
+ const type = await reader.readVarint();
836
+ const message = await this.#readControlFrame(reader, type);
837
+ const initiatingRequestId = message.kind === 'fetch'
838
+ ? message.request.requestId
839
+ : message.kind === 'subscribe' ||
840
+ message.kind === 'subscribe-namespace' ||
841
+ message.kind === 'publish' ||
842
+ message.kind === 'publish-namespace' ||
843
+ message.kind === 'track-status'
844
+ ? message.requestId
845
+ : undefined;
846
+ // Before answering: a request this client rejects still consumes its id.
847
+ if (initiatingRequestId !== undefined)
848
+ this.#claimPeerRequestId(initiatingRequestId);
849
+ const respond = async (bytes) => {
850
+ const writer = stream.writable.getWriter();
851
+ try {
852
+ await writer.write(bytes);
853
+ await writer.close();
854
+ }
855
+ catch {
856
+ // Peer cancelled; nothing to clean up.
857
+ }
858
+ await reader.cancel();
859
+ };
860
+ if (message.kind === 'publish') {
861
+ const callbacks = this.#callbacks;
862
+ if (callbacks.onIncomingPublish) {
863
+ let responded = false;
864
+ callbacks.onIncomingPublish(message, {
865
+ accept: () => {
866
+ if (responded)
867
+ return;
868
+ responded = true;
869
+ void respond(encodeRequestOk({}, this.#protocol));
870
+ },
871
+ reject: (errorCode = REQUEST_ERROR_CODE.UNINTERESTED, reason = '') => {
872
+ if (responded)
873
+ return;
874
+ responded = true;
875
+ void respond(encodeRequestError(errorCode, reason));
876
+ },
877
+ });
878
+ return;
879
+ }
880
+ await respond(encodeRequestError(REQUEST_ERROR_CODE.UNINTERESTED, 'subscribe-only client'));
881
+ return;
882
+ }
883
+ // Any other server-initiated request: this client doesn't serve them.
884
+ await respond(encodeRequestError(REQUEST_ERROR_CODE.NOT_SUPPORTED, 'subscribe-only client'));
885
+ }
886
+ }
887
+ /**
888
+ * Create a MOQT session driver over an established transport.
889
+ *
890
+ * @example
891
+ * ```ts
892
+ * // TypeScript's DOM lib does not declare WebTransport's `protocol` yet.
893
+ * const transport = new WebTransport(url, { protocols: [MOQT_PROTOCOL_ID] }) as WebTransport & MoqtTransport;
894
+ * await transport.ready;
895
+ * if (transport.protocol !== MOQT_PROTOCOL_ID) throw new Error(`negotiated ${transport.protocol || 'none'}`);
896
+ * const session = createMoqtSession(transport, {
897
+ * callbacks: { onGoaway: (g) => migrate(g.newSessionUri) },
898
+ * });
899
+ * const subscription = session.subscribe(
900
+ * { trackNamespace: ['live', 'stream1'], trackName: 'catalog' },
901
+ * { onObject: (object) => handleCatalogObject(object) }
902
+ * );
903
+ * ```;
904
+ */
905
+ export function createMoqtSession(transport, config = {}) {
906
+ return new MoqtSessionImpl(transport, config);
907
+ }
908
+ //# sourceMappingURL=session.js.map