@caprid/moq-core 0.4.1 → 0.5.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.
@@ -39,6 +39,7 @@ import { StreamReader, utf8Encode } from './bytes.js';
39
39
  import { compareLocations, 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';
40
40
  import { isMoqtProtocolError, MoqtProtocolError, SESSION_ERROR } from './errors.js';
41
41
  import { encodeFetchHeader, isSubgroupHeaderType, STREAM_TYPE } from './object-stream.js';
42
+ import { readRequest } from './request-stream.js';
42
43
  import { streamResetReason } from './stream-reset.js';
43
44
  import { isSessionError } from './transport-error.js';
44
45
  /**
@@ -149,8 +150,13 @@ function readLargestObjectForUpdate(track) {
149
150
  return undefined;
150
151
  }
151
152
  }
153
+ /** A namespace as a map key: fields may contain any character, so they are not joined. */
154
+ function namespaceKey(namespace) {
155
+ return JSON.stringify(namespace);
156
+ }
157
+ /** A track as a map key: namespace fields and the name may contain any character, so nothing is joined. */
152
158
  function trackKey(namespace, name) {
153
- return `${namespace.join('/')}--${name}`;
159
+ return JSON.stringify([namespace, name]);
154
160
  }
155
161
  function isNamespacePrefix(prefix, namespace) {
156
162
  return prefix.length <= namespace.length && prefix.every((part, i) => namespace[i] === part);
@@ -189,10 +195,16 @@ class MoqtPublishSessionImpl {
189
195
  * request IDs, a reused ID would hand two subscriptions the same alias and make their subgroup streams
190
196
  * indistinguishable — session-fatal, per the draft.
191
197
  */
192
- #peerRequestIds = new Set();
193
- #desiredNamespace;
194
- #announcedFired = false;
198
+ #peerRequestIds;
199
+ /** The namespaces to announce, by {@link namespaceKey}. */
200
+ #announces = new Map();
201
+ /** NAMESPACE_DONE writes `withdraw()` started; an orderly close drains them with its own retractions. */
202
+ #pendingWithdrawals = new Set();
203
+ /** Namespaces with at least one registered track, by {@link namespaceKey}: an announce waits for its first. */
204
+ #trackNamespaces = new Set();
195
205
  #receivedNamespaceSolicitation = false;
206
+ /** The reader of every incoming request stream still being served: the end of the session stops them all. */
207
+ #requestReaders = new Set();
196
208
  #resolveReady;
197
209
  #rejectReady;
198
210
  #controlWriter;
@@ -207,6 +219,7 @@ class MoqtPublishSessionImpl {
207
219
  this.#transport = transport;
208
220
  this.#protocol = resolveMoqtProtocol(transport.protocol);
209
221
  this.#config = config;
222
+ this.#peerRequestIds = config.peerRequestIds ?? new Set();
210
223
  this.#callbacks = config.callbacks ?? {};
211
224
  this.ready = new Promise((resolve, reject) => {
212
225
  this.#resolveReady = resolve;
@@ -216,10 +229,14 @@ class MoqtPublishSessionImpl {
216
229
  void this.#start();
217
230
  }
218
231
  get namespaceSolicited() {
219
- const namespace = this.#desiredNamespace;
220
- if (namespace === undefined || !this.#receivedNamespaceSolicitation)
232
+ if (this.#announces.size === 0 || !this.#receivedNamespaceSolicitation)
233
+ return undefined;
234
+ return [...this.#announces.values()].some(({ namespace }) => [...this.#namespaceStreams].some((stream) => isNamespacePrefix(stream.prefix, namespace)));
235
+ }
236
+ isSolicited(trackNamespace) {
237
+ if (!this.#receivedNamespaceSolicitation)
221
238
  return undefined;
222
- return [...this.#namespaceStreams].some((stream) => isNamespacePrefix(stream.prefix, namespace));
239
+ return [...this.#namespaceStreams].some((stream) => isNamespacePrefix(stream.prefix, trackNamespace));
223
240
  }
224
241
  // ---------------------------------------------------------------------------
225
242
  // Session lifecycle
@@ -278,6 +295,9 @@ class MoqtPublishSessionImpl {
278
295
  for (const subscriber of track.subscribers)
279
296
  void subscriber.cancel();
280
297
  }
298
+ for (const reader of this.#requestReaders)
299
+ void reader.cancel().catch(() => { });
300
+ this.#requestReaders.clear();
281
301
  this.#tracks.clear();
282
302
  this.#namespaceStreams.clear();
283
303
  this.#controlWriter = undefined;
@@ -313,7 +333,7 @@ class MoqtPublishSessionImpl {
313
333
  for (const track of this.#tracks.values()) {
314
334
  this.#endTrack(track);
315
335
  }
316
- const writes = [];
336
+ const writes = [...this.#pendingWithdrawals];
317
337
  for (const track of this.#tracks.values()) {
318
338
  if (track.doneFlushed)
319
339
  writes.push(track.doneFlushed);
@@ -377,83 +397,156 @@ class MoqtPublishSessionImpl {
377
397
  destroy(error) {
378
398
  this.#close(SESSION_ERROR.NO_ERROR, '', error);
379
399
  }
400
+ /**
401
+ * Whether the session still takes new work for `track`. Once closing it takes none and only reports ends, except for
402
+ * a track whose `end({ after })` is still waiting, which is served until that end.
403
+ */
404
+ #serving(track) {
405
+ return !this.#destroyed && (!this.#closing || track.endNow !== undefined);
406
+ }
407
+ /** The peer is migrating. A session already closing has nothing to move, so its application is not told. */
408
+ #reportGoaway(goaway) {
409
+ this.#receivedGoaway = true;
410
+ if (!this.#closing)
411
+ this.#callbacks.onGoaway?.(goaway);
412
+ }
413
+ /** Report `track`'s binding. An unbinding is an end, reported until `onClosed`; a binding is new work. */
414
+ #reportBinding(track, trackAlias) {
415
+ if (this.#destroyed || (trackAlias !== undefined && !this.#serving(track)))
416
+ return;
417
+ this.#callbacks.onTrackBinding?.({ trackNamespace: track.namespace, trackName: track.trackName, trackAlias });
418
+ }
380
419
  // ---------------------------------------------------------------------------
381
420
  // Announcing and the track registry
382
421
  // ---------------------------------------------------------------------------
383
422
  announce(trackNamespace) {
384
423
  if (this.#destroyed || this.#closing)
385
424
  return;
386
- this.#desiredNamespace = trackNamespace;
425
+ const key = namespaceKey(trackNamespace);
426
+ if (this.#announces.has(key))
427
+ return;
428
+ const record = { namespace: [...trackNamespace], fired: false };
429
+ this.#announces.set(key, record);
430
+ for (const stream of this.#namespaceStreams) {
431
+ this.#reconcileAnnounce(stream, record);
432
+ }
433
+ }
434
+ withdraw(trackNamespace) {
435
+ if (this.#destroyed || this.#closing)
436
+ return;
437
+ const key = namespaceKey(trackNamespace);
438
+ const record = this.#announces.get(key);
439
+ if (!record)
440
+ return;
441
+ this.#announces.delete(key);
387
442
  for (const stream of this.#namespaceStreams) {
388
- this.#reconcileAnnounce(stream);
443
+ if (!isNamespacePrefix(stream.prefix, record.namespace))
444
+ continue;
445
+ const suffix = namespaceKey(record.namespace.slice(stream.prefix.length));
446
+ const index = stream.announced.findIndex((existing) => namespaceKey(existing) === suffix);
447
+ if (index === -1)
448
+ continue;
449
+ const [entry] = stream.announced.splice(index, 1);
450
+ // A failed write means the carrier is dead: drop it and report what it still carried, as a failed announce does.
451
+ const write = stream.writer
452
+ .write(encodeNamespaceDone(entry))
453
+ .catch((error) => this.#dropCarrier(stream, error));
454
+ this.#pendingWithdrawals.add(write);
455
+ void write.then(() => this.#pendingWithdrawals.delete(write));
389
456
  }
390
457
  }
391
458
  /**
392
- * Write the desired namespace onto a solicitation stream whose prefix covers it. Solicitations, `announce()`, and the
393
- * first `registerTrack()` arrive in any order — the relay's SUBSCRIBE_NAMESPACE races our post-SETUP setup — so all
394
- * three paths funnel here. The announce is deferred until at least one track is registered: an announced namespace
395
- * invites immediate SUBSCRIBEs, and answering one with DOES_NOT_EXIST is terminal on moq-lite-rs (the relay aborts
396
- * the request rather than retrying), so advertising an empty registry would permanently break the first viewer in the
397
- * pre-registration window.
459
+ * Write announced namespaces onto a solicitation stream whose prefix covers them: every one, or only `only`.
460
+ * Solicitations, `announce()`, and each namespace's first `registerTrack()` arrive in any order — the relay's
461
+ * SUBSCRIBE_NAMESPACE races our post-SETUP setup — so all three paths funnel here. A namespace's announce is deferred
462
+ * until a track in it is registered: an announced namespace invites immediate SUBSCRIBEs, and answering one with
463
+ * DOES_NOT_EXIST is terminal on moq-lite-rs (the relay aborts the request rather than retrying), so advertising an
464
+ * empty registry would permanently break the first viewer in the pre-registration window.
398
465
  */
399
- #reconcileAnnounce(stream) {
400
- const namespace = this.#desiredNamespace;
401
- if (namespace === undefined || this.#tracks.size === 0)
466
+ #reconcileAnnounce(stream, only) {
467
+ for (const record of only ? [only] : [...this.#announces.values()]) {
468
+ this.#announceOn(stream, record);
469
+ }
470
+ }
471
+ #announceOn(stream, record) {
472
+ const { namespace } = record;
473
+ if (!this.#trackNamespaces.has(namespaceKey(namespace)))
402
474
  return;
403
475
  if (!isNamespacePrefix(stream.prefix, namespace))
404
476
  return;
405
477
  const suffix = namespace.slice(stream.prefix.length);
406
- if (stream.announced.some((existing) => existing.join('/') === suffix.join('/')))
478
+ const key = namespaceKey(suffix);
479
+ if (stream.announced.some((existing) => namespaceKey(existing) === key))
407
480
  return;
408
481
  stream.announced.push(suffix);
409
482
  stream.writer
410
483
  .write(encodeNamespace(suffix))
411
484
  .then(() => {
412
- if (this.#destroyed || this.#announcedFired)
485
+ if (this.#destroyed || this.#closing || record.fired)
413
486
  return;
414
- this.#announcedFired = true;
487
+ if (this.#announces.get(namespaceKey(namespace)) !== record)
488
+ return;
489
+ record.fired = true;
415
490
  this.#callbacks.onAnnounced?.({ namespace });
416
491
  })
417
- .catch((error) => {
418
- // The response half died alone (a reset the request half may
419
- // never mirror): the entry never reached the peer, no future
420
- // write can, and the read loop may stay open forever — the
421
- // carrier is dead. Deregister it so the peer's replacement
422
- // solicitation is a fresh start rather than a PREFIX_OVERLAP
423
- // against a corpse; if another path already swept it, the loss
424
- // was reported there.
425
- if (!this.#namespaceStreams.delete(stream))
426
- return;
427
- stream.announced = stream.announced.filter((existing) => existing !== suffix);
428
- void stream.writer.close().catch(() => { });
429
- void this.#reportAnnounceLoss(error);
430
- });
492
+ .catch((error) => this.#dropCarrier(stream, error));
431
493
  }
432
494
  /**
433
- * Fire `onAnnounceEnded` when no solicitation carries the announce anymore — shared by the read-loop cleanup and the
434
- * response-write failure path; `cause` is the stream failure that ended the carrier. Silent while closing,
495
+ * A write on a solicitation stream failed: the response half died alone (a reset the request half may never mirror),
496
+ * so no future write can reach the peer and the read loop may stay open forever. Deregister the carrier, so the peer's
497
+ * replacement solicitation is a fresh start rather than a PREFIX_OVERLAP against a corpse, and report the namespaces
498
+ * it carried. If another path already swept it, the loss was reported there.
499
+ */
500
+ #dropCarrier(stream, error) {
501
+ if (!this.#namespaceStreams.delete(stream))
502
+ return;
503
+ const lost = this.#carriedBy(stream);
504
+ stream.announced = [];
505
+ void stream.writer.close().catch(() => { });
506
+ void this.#reportAnnounceLoss(error, lost);
507
+ }
508
+ /** The announced namespaces a solicitation stream carries entries for. */
509
+ #carriedBy(stream) {
510
+ const suffixes = new Set(stream.announced.map(namespaceKey));
511
+ return [...this.#announces.values()].filter(({ namespace }) => isNamespacePrefix(stream.prefix, namespace) && suffixes.has(namespaceKey(namespace.slice(stream.prefix.length))));
512
+ }
513
+ /**
514
+ * Fire `onAnnounceEnded` for each of `lost` that no solicitation carries anymore — shared by the read-loop cleanup
515
+ * and the response-write failure path; `cause` is the stream failure that ended the carrier. Silent while closing,
435
516
  * destroyed, or migrating (a GOAWAY makes the peer's streams ending the orderly drain), and once the transport has
436
517
  * ended: an ended transport fails every stream as it settles `closed`, and that is connection loss, which
437
518
  * `#handleClosed` reports, not a withdrawal. A failure with `source` `'session'` (TA-23) or the settled `closed`
438
- * decides, not whether the `closed` handler happened to run first.
519
+ * decides, not whether the `closed` handler happened to run first. A namespace withdrawn meanwhile is not reported.
439
520
  */
440
- async #reportAnnounceLoss(cause) {
441
- if (this.#announceLossSilenced() || this.#announceCarried())
521
+ async #reportAnnounceLoss(cause, lost) {
522
+ const stillLost = () => lost.filter((record) => this.#announces.get(namespaceKey(record.namespace)) === record && !this.#announceCarried(record.namespace));
523
+ if (this.#announceLossSilenced() || stillLost().length === 0)
442
524
  return;
443
525
  if (isSessionError(cause) || (await hasSettled(this.#transport.closed)))
444
526
  return;
445
- // A replacement solicitation may have picked the announce up during that turn.
446
- if (this.#announceLossSilenced() || this.#announceCarried())
527
+ // A replacement solicitation may have picked an announce up during that turn.
528
+ if (this.#announceLossSilenced())
447
529
  return;
448
- const error = new MoqtProtocolError('the namespace solicitation carrying the announce ended');
449
- error.cause = cause;
450
- this.#callbacks.onAnnounceEnded?.({ error });
530
+ for (const record of stillLost()) {
531
+ // A handler may withdraw another namespace or end the session: check each again before telling it.
532
+ if (this.#announceLossSilenced() || !stillLost().includes(record))
533
+ continue;
534
+ const { namespace } = record;
535
+ const error = new MoqtProtocolError('the namespace solicitation carrying the announce ended');
536
+ error.cause = cause;
537
+ this.#callbacks.onAnnounceEnded?.({ namespace, error });
538
+ }
451
539
  }
452
540
  #announceLossSilenced() {
453
541
  return this.#destroyed || this.#closing || this.#receivedGoaway;
454
542
  }
455
- #announceCarried() {
456
- return [...this.#namespaceStreams].some((stream) => stream.announced.length > 0);
543
+ #announceCarried(namespace) {
544
+ return [...this.#namespaceStreams].some((stream) => {
545
+ if (!isNamespacePrefix(stream.prefix, namespace))
546
+ return false;
547
+ const suffix = namespaceKey(namespace.slice(stream.prefix.length));
548
+ return stream.announced.some((existing) => namespaceKey(existing) === suffix);
549
+ });
457
550
  }
458
551
  registerTrack(options) {
459
552
  if (this.#destroyed || this.#closing) {
@@ -466,17 +559,23 @@ class MoqtPublishSessionImpl {
466
559
  getLargestObject: options.getLargestObject,
467
560
  largestObject: undefined,
468
561
  key: trackKey(options.trackNamespace, options.trackName),
562
+ namespace: [...options.trackNamespace],
563
+ namespaceKey: namespaceKey(options.trackNamespace),
469
564
  trackName: options.trackName,
470
565
  subscribers: [],
471
566
  done: false,
472
567
  pendingEnds: [],
473
568
  };
474
569
  this.#tracks.set(track.key, track);
475
- // The first registration may be what the deferred announce was
476
- // waiting for (see #reconcileAnnounce).
477
- if (this.#tracks.size === 1) {
478
- for (const stream of this.#namespaceStreams) {
479
- this.#reconcileAnnounce(stream);
570
+ // The namespace's first registration may be what its deferred announce
571
+ // was waiting for (see #reconcileAnnounce).
572
+ if (!this.#trackNamespaces.has(track.namespaceKey)) {
573
+ this.#trackNamespaces.add(track.namespaceKey);
574
+ const record = this.#announces.get(track.namespaceKey);
575
+ if (record) {
576
+ for (const stream of this.#namespaceStreams) {
577
+ this.#reconcileAnnounce(stream, record);
578
+ }
480
579
  }
481
580
  }
482
581
  return {
@@ -530,9 +629,8 @@ class MoqtPublishSessionImpl {
530
629
  this.#callbacks.onSubscribeEnd?.({ requestId: subscriber.requestId });
531
630
  }
532
631
  }
533
- if (hadReported && !this.#destroyed) {
534
- this.#callbacks.onTrackBinding?.({ trackName: track.trackName, trackAlias: undefined });
535
- }
632
+ if (hadReported)
633
+ this.#reportBinding(track, undefined);
536
634
  return Promise.all([...track.pendingEnds]).then(() => { });
537
635
  }
538
636
  /**
@@ -728,6 +826,8 @@ class MoqtPublishSessionImpl {
728
826
  async #runControlStream(reader) {
729
827
  // The stream-type varint (0x2F00) doubles as the first message's type.
730
828
  const setup = await this.#readControlFrame(reader, MESSAGE_TYPE.SETUP);
829
+ if (this.#destroyed)
830
+ return;
731
831
  if (setup.kind !== 'setup')
732
832
  throw new MoqtProtocolError('control stream did not begin with SETUP');
733
833
  if (this.#receivedServerSetup) {
@@ -735,18 +835,20 @@ class MoqtPublishSessionImpl {
735
835
  }
736
836
  this.#receivedServerSetup = true;
737
837
  this.#resolveReady();
738
- this.#callbacks.onReady?.(setup.options);
838
+ if (!this.#closing)
839
+ this.#callbacks.onReady?.(setup.options);
739
840
  while (!(await reader.atEnd())) {
740
841
  const type = await reader.readVarint();
741
842
  const message = await this.#readControlFrame(reader, type);
843
+ if (this.#destroyed)
844
+ return;
742
845
  if (message.kind !== 'goaway')
743
846
  throw new MoqtProtocolError(`unexpected ${message.kind} on the control stream`);
744
847
  if (this.#receivedControlGoaway) {
745
848
  throw new MoqtProtocolError('received more than one GOAWAY on the control stream');
746
849
  }
747
850
  this.#receivedControlGoaway = true;
748
- this.#receivedGoaway = true;
749
- this.#callbacks.onGoaway?.(message);
851
+ this.#reportGoaway(message);
750
852
  }
751
853
  // A closed control stream ends the session (§6.3).
752
854
  if (!this.#destroyed) {
@@ -778,8 +880,22 @@ class MoqtPublishSessionImpl {
778
880
  }
779
881
  async #handleIncomingRequest(stream) {
780
882
  const reader = new StreamReader(stream.readable);
781
- const type = await reader.readVarint();
782
- const message = await this.#readControlFrame(reader, type);
883
+ this.#requestReaders.add(reader);
884
+ try {
885
+ await this.#serveRequest(stream, reader);
886
+ }
887
+ finally {
888
+ this.#requestReaders.delete(reader);
889
+ }
890
+ }
891
+ async #serveRequest(stream, reader) {
892
+ const message = await readRequest(stream, reader, (type) => this.#readControlFrame(reader, type));
893
+ // A request still arriving when the session ended is dropped.
894
+ if (this.#destroyed) {
895
+ void reader.cancel().catch(() => { });
896
+ void stream.writable.abort().catch(() => { });
897
+ return;
898
+ }
783
899
  // Reserve the request ID for EVERY request-initiating kind — the
784
900
  // uniqueness invariant is session-wide, so an ID burned on a
785
901
  // rejected PUBLISH or FETCH must not be reusable by a later
@@ -836,6 +952,12 @@ class MoqtPublishSessionImpl {
836
952
  }
837
953
  this.#peerRequestIds.add(requestId);
838
954
  }
955
+ /** The next message on a request stream being served: none once the peer has ended it. */
956
+ async #nextMessage(reader) {
957
+ if (await reader.atEnd())
958
+ return undefined;
959
+ return this.#readControlFrame(reader, await reader.readVarint());
960
+ }
839
961
  /**
840
962
  * A peer's namespace solicitation — the announce carrier. Accepted with REQUEST_OK, then held open for the session's
841
963
  * lifetime: NAMESPACE / NAMESPACE_DONE entries for every announced namespace under the prefix ride this stream. A
@@ -845,6 +967,11 @@ class MoqtPublishSessionImpl {
845
967
  async #handleSubscribeNamespace(stream, reader, subscribeNamespace) {
846
968
  const writer = stream.writable.getWriter();
847
969
  const prefix = subscribeNamespace.trackNamespacePrefix;
970
+ // A carrier accepted now would miss the drain's NAMESPACE_DONE retractions.
971
+ if (this.#closing) {
972
+ await refuse(writer, reader, REQUEST_ERROR_CODE.GOING_AWAY, 'the session is closing');
973
+ return;
974
+ }
848
975
  // §9.17: a solicitation overlapping an established one (either
849
976
  // prefix containing the other) is refused with PREFIX_OVERLAP —
850
977
  // announcing on both would hand the peer duplicate namespace state
@@ -881,6 +1008,12 @@ class MoqtPublishSessionImpl {
881
1008
  await reader.cancel();
882
1009
  return;
883
1010
  }
1011
+ // The close began during the write: the accepted solicitation ends empty, with nothing announced on it.
1012
+ if (this.#closing || this.#destroyed) {
1013
+ void writer.close().catch(() => { });
1014
+ await reader.cancel().catch(() => { });
1015
+ return;
1016
+ }
884
1017
  const record = {
885
1018
  prefix,
886
1019
  writer,
@@ -893,12 +1026,13 @@ class MoqtPublishSessionImpl {
893
1026
  let failedUpdate = false;
894
1027
  let cause;
895
1028
  try {
896
- while (!(await reader.atEnd())) {
897
- const type = await reader.readVarint();
898
- const message = await this.#readControlFrame(reader, type);
1029
+ for (;;) {
1030
+ const message = await this.#nextMessage(reader);
1031
+ // Checked here, in the turn that dispatches: the session can end between the read and this resumption.
1032
+ if (message === undefined || this.#destroyed)
1033
+ break;
899
1034
  if (message.kind === 'goaway') {
900
- this.#receivedGoaway = true;
901
- this.#callbacks.onGoaway?.(message);
1035
+ this.#reportGoaway(message);
902
1036
  }
903
1037
  else if (message.kind === 'request-update') {
904
1038
  this.#claimPeerRequestId(message.requestId);
@@ -907,11 +1041,13 @@ class MoqtPublishSessionImpl {
907
1041
  // entry), so per §9.5.1 the update is answered with an error
908
1042
  // and the request stream closes below — never session-fatal
909
1043
  // (only the reused Request ID above is).
910
- this.#callbacks.onRequestUpdate?.({
911
- requestId: subscribeNamespace.requestId,
912
- updateRequestId: message.requestId,
913
- parameters: message.parameters,
914
- });
1044
+ if (!this.#closing) {
1045
+ this.#callbacks.onRequestUpdate?.({
1046
+ requestId: subscribeNamespace.requestId,
1047
+ updateRequestId: message.requestId,
1048
+ parameters: message.parameters,
1049
+ });
1050
+ }
915
1051
  void writer
916
1052
  .write(encodeRequestError(REQUEST_ERROR_CODE.NOT_SUPPORTED, 'namespace update not supported'))
917
1053
  .catch(() => { });
@@ -941,8 +1077,10 @@ class MoqtPublishSessionImpl {
941
1077
  // Withdrawal (reset) or a failed update: the carrier is over.
942
1078
  this.#namespaceStreams.delete(record);
943
1079
  void writer.close().catch(() => { });
944
- if (record.announced.length > 0)
945
- await this.#reportAnnounceLoss(cause);
1080
+ const lost = this.#carriedBy(record);
1081
+ record.announced = [];
1082
+ if (lost.length > 0)
1083
+ await this.#reportAnnounceLoss(cause, lost);
946
1084
  }
947
1085
  /**
948
1086
  * TRACK_STATUS (draft-22 §9.13, the same on draft-20): answered as the SUBSCRIBE for the same track would be, without
@@ -959,6 +1097,10 @@ class MoqtPublishSessionImpl {
959
1097
  async #handleTrackStatus(stream, reader, request) {
960
1098
  const track = this.#tracks.get(trackKey(request.trackNamespace, request.trackName));
961
1099
  const writer = stream.writable.getWriter();
1100
+ if (this.#closing) {
1101
+ await refuse(writer, reader, REQUEST_ERROR_CODE.GOING_AWAY, 'the session is closing');
1102
+ return;
1103
+ }
962
1104
  if (!track || track.done) {
963
1105
  await refuse(writer, reader, REQUEST_ERROR_CODE.DOES_NOT_EXIST, 'unknown track');
964
1106
  return;
@@ -992,6 +1134,10 @@ class MoqtPublishSessionImpl {
992
1134
  async #handleIncomingSubscribe(stream, reader, subscribe) {
993
1135
  const track = this.#tracks.get(trackKey(subscribe.trackNamespace, subscribe.trackName));
994
1136
  const writer = stream.writable.getWriter();
1137
+ if (this.#closing) {
1138
+ await refuse(writer, reader, REQUEST_ERROR_CODE.GOING_AWAY, 'the session is closing');
1139
+ return;
1140
+ }
995
1141
  if (!track || track.done) {
996
1142
  await refuse(writer, reader, REQUEST_ERROR_CODE.DOES_NOT_EXIST, 'unknown track');
997
1143
  return;
@@ -1014,8 +1160,13 @@ class MoqtPublishSessionImpl {
1014
1160
  catch (error) {
1015
1161
  // The encoder refused the response; the peer did nothing wrong.
1016
1162
  await refuse(writer, reader, REQUEST_ERROR_CODE.INTERNAL_ERROR, 'could not encode SUBSCRIBE_OK');
1017
- if (!this.#destroyed) {
1018
- this.#callbacks.onSubscribeFailed?.({ requestId: subscribe.requestId, trackName: track.trackName, error });
1163
+ if (!this.#destroyed && !this.#closing) {
1164
+ this.#callbacks.onSubscribeFailed?.({
1165
+ requestId: subscribe.requestId,
1166
+ trackNamespace: track.namespace,
1167
+ trackName: track.trackName,
1168
+ error,
1169
+ });
1019
1170
  }
1020
1171
  return;
1021
1172
  }
@@ -1069,7 +1220,7 @@ class MoqtPublishSessionImpl {
1069
1220
  // an alias whose stream is already ending, and a subscription that
1070
1221
  // was never live is never reported (`onSubscribeEnd` pairs on the
1071
1222
  // same flag, keeping subscriber counts balanced).
1072
- if (!subscriber.finished) {
1223
+ if (!subscriber.finished && this.#serving(track)) {
1073
1224
  subscriber.reported = true;
1074
1225
  this.#callbacks.onSubscribe?.(subscribe);
1075
1226
  // The newest subscription wins the binding, and every live
@@ -1089,19 +1240,18 @@ class MoqtPublishSessionImpl {
1089
1240
  // it), and the newer subscription carries the track on.
1090
1241
  this.#endSubscription(track, other, PUBLISH_DONE_STATUS.TRACK_ENDED, 'superseded by a newer subscription');
1091
1242
  }
1092
- this.#callbacks.onTrackBinding?.({
1093
- trackName: track.trackName,
1094
- trackAlias: subscriber.forwarding ? trackAlias : undefined,
1095
- });
1243
+ this.#reportBinding(track, subscriber.forwarding ? trackAlias : undefined);
1096
1244
  }
1097
- if (this.#fillRequested(subscriber, subscribe.parameters.fillParameters, largestObject)) {
1245
+ if (this.#serving(track) && this.#fillRequested(subscriber, subscribe.parameters.fillParameters, largestObject)) {
1098
1246
  this.#failFill(subscriber, subscribe.requestId);
1099
1247
  }
1100
1248
  // Keep serving the request stream: REQUEST_UPDATEs arrive here.
1101
1249
  try {
1102
- while (!(await reader.atEnd())) {
1103
- const type = await reader.readVarint();
1104
- const message = await this.#readControlFrame(reader, type);
1250
+ for (;;) {
1251
+ const message = await this.#nextMessage(reader);
1252
+ // Checked here, in the turn that dispatches: the session can end between the read and this resumption.
1253
+ if (message === undefined || this.#destroyed)
1254
+ break;
1105
1255
  if (message.kind === 'request-update') {
1106
1256
  this.#claimPeerRequestId(message.requestId);
1107
1257
  // The delivery timeouts (§5.2) are applied by the caller, through `onRequestUpdate`, to the groups it opens
@@ -1114,17 +1264,16 @@ class MoqtPublishSessionImpl {
1114
1264
  if (forward !== undefined) {
1115
1265
  subscriber.forwarding = forward !== 0;
1116
1266
  if (!subscriber.finished && subscriber.accepted) {
1117
- this.#callbacks.onTrackBinding?.({
1118
- trackName: track.trackName,
1119
- trackAlias: subscriber.forwarding ? subscriber.trackAlias : undefined,
1120
- });
1267
+ this.#reportBinding(track, subscriber.forwarding ? subscriber.trackAlias : undefined);
1121
1268
  }
1122
1269
  }
1123
- this.#callbacks.onRequestUpdate?.({
1124
- requestId: subscribe.requestId,
1125
- updateRequestId: message.requestId,
1126
- parameters: message.parameters,
1127
- });
1270
+ if (this.#serving(track)) {
1271
+ this.#callbacks.onRequestUpdate?.({
1272
+ requestId: subscribe.requestId,
1273
+ updateRequestId: message.requestId,
1274
+ parameters: message.parameters,
1275
+ });
1276
+ }
1128
1277
  if (!subscriber.finished) {
1129
1278
  if (Object.keys(unsupported).length > 0) {
1130
1279
  // Acknowledging an update we did not apply would leave the
@@ -1141,7 +1290,7 @@ class MoqtPublishSessionImpl {
1141
1290
  subscriber.reported = false;
1142
1291
  this.#callbacks.onSubscribeEnd?.({ requestId: subscribe.requestId });
1143
1292
  const binding = track.subscribers.filter((s) => !s.finished && s.accepted && s.forwarding).at(-1);
1144
- this.#callbacks.onTrackBinding?.({ trackName: track.trackName, trackAlias: binding?.trackAlias });
1293
+ this.#reportBinding(track, binding?.trackAlias);
1145
1294
  }
1146
1295
  }
1147
1296
  else {
@@ -1150,19 +1299,18 @@ class MoqtPublishSessionImpl {
1150
1299
  // never sends REQUEST_UPDATE (moq-relay 0.15.8 writes nothing
1151
1300
  // after SUBSCRIBE until it cancels) never sees a trailing byte.
1152
1301
  // LARGEST_OBJECT rides it as in SUBSCRIBE_OK (§9.20.17).
1153
- const largestObject = readLargestObjectForUpdate(track);
1302
+ const largestObject = this.#serving(track) ? readLargestObjectForUpdate(track) : undefined;
1154
1303
  void writer
1155
1304
  .write(encodeRequestOk(largestObject ? { largestObject } : {}, this.#protocol))
1156
1305
  .catch(() => { });
1157
- if (this.#fillRequested(subscriber, fillParameters, largestObject)) {
1306
+ if (this.#serving(track) && this.#fillRequested(subscriber, fillParameters, largestObject)) {
1158
1307
  this.#failFill(subscriber, message.requestId);
1159
1308
  }
1160
1309
  }
1161
1310
  }
1162
1311
  }
1163
1312
  else if (message.kind === 'goaway') {
1164
- this.#receivedGoaway = true;
1165
- this.#callbacks.onGoaway?.(message);
1313
+ this.#reportGoaway(message);
1166
1314
  }
1167
1315
  else {
1168
1316
  throw new MoqtProtocolError(`unexpected ${message.kind} on an incoming subscribe stream`);
@@ -1206,7 +1354,7 @@ class MoqtPublishSessionImpl {
1206
1354
  // registered), and one with Forward State 0 forbids data. When a
1207
1355
  // pending one accepts, it emits its own binding.
1208
1356
  const binding = track.subscribers.filter((s) => !s.finished && s.accepted && s.forwarding).at(-1);
1209
- this.#callbacks.onTrackBinding?.({ trackName: track.trackName, trackAlias: binding?.trackAlias });
1357
+ this.#reportBinding(track, binding?.trackAlias);
1210
1358
  }
1211
1359
  }
1212
1360
  }