@moq/net 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/announced.d.ts +14 -0
  2. package/announced.d.ts.map +1 -1
  3. package/announced.js.map +1 -1
  4. package/broadcast.d.ts +6 -3
  5. package/broadcast.d.ts.map +1 -1
  6. package/broadcast.js +9 -5
  7. package/broadcast.js.map +1 -1
  8. package/connection/accept.js +9 -1
  9. package/connection/accept.js.map +1 -1
  10. package/connection/connect.d.ts.map +1 -1
  11. package/connection/connect.js +10 -1
  12. package/connection/connect.js.map +1 -1
  13. package/connection/established.d.ts +2 -1
  14. package/connection/established.d.ts.map +1 -1
  15. package/connection/established.js.map +1 -1
  16. package/connection/forward.js +9 -2
  17. package/connection/forward.js.map +1 -1
  18. package/connection/handshake.d.ts +1 -0
  19. package/connection/handshake.d.ts.map +1 -1
  20. package/connection/handshake.js +3 -0
  21. package/connection/handshake.js.map +1 -1
  22. package/connection/pool.d.ts +8 -10
  23. package/connection/pool.d.ts.map +1 -1
  24. package/connection/pool.js +18 -8
  25. package/connection/pool.js.map +1 -1
  26. package/connection/reload.js +6 -6
  27. package/connection/reload.js.map +1 -1
  28. package/error.d.ts.map +1 -1
  29. package/error.js +21 -0
  30. package/error.js.map +1 -1
  31. package/ietf/adapter.d.ts +5 -1
  32. package/ietf/adapter.d.ts.map +1 -1
  33. package/ietf/adapter.js +27 -9
  34. package/ietf/adapter.js.map +1 -1
  35. package/ietf/connection.d.ts +1 -1
  36. package/ietf/connection.d.ts.map +1 -1
  37. package/ietf/connection.js +9 -5
  38. package/ietf/connection.js.map +1 -1
  39. package/ietf/error.js +27 -2
  40. package/ietf/error.js.map +1 -1
  41. package/ietf/hidden.d.ts +2 -0
  42. package/ietf/hidden.d.ts.map +1 -0
  43. package/ietf/hidden.js +30 -0
  44. package/ietf/hidden.js.map +1 -0
  45. package/ietf/index.d.ts +1 -0
  46. package/ietf/index.d.ts.map +1 -1
  47. package/ietf/index.js +1 -0
  48. package/ietf/index.js.map +1 -1
  49. package/ietf/object.d.ts +8 -2
  50. package/ietf/object.d.ts.map +1 -1
  51. package/ietf/object.js +17 -3
  52. package/ietf/object.js.map +1 -1
  53. package/ietf/parameters.d.ts +5 -0
  54. package/ietf/parameters.d.ts.map +1 -1
  55. package/ietf/parameters.js +20 -0
  56. package/ietf/parameters.js.map +1 -1
  57. package/ietf/properties.d.ts +1 -0
  58. package/ietf/properties.d.ts.map +1 -1
  59. package/ietf/properties.js +14 -0
  60. package/ietf/properties.js.map +1 -1
  61. package/ietf/publish.d.ts +19 -2
  62. package/ietf/publish.d.ts.map +1 -1
  63. package/ietf/publish.js +40 -6
  64. package/ietf/publish.js.map +1 -1
  65. package/ietf/publisher.js +114 -60
  66. package/ietf/publisher.js.map +1 -1
  67. package/ietf/subscribe.d.ts.map +1 -1
  68. package/ietf/subscribe.js +3 -4
  69. package/ietf/subscribe.js.map +1 -1
  70. package/ietf/subscribe_namespace.d.ts +8 -2
  71. package/ietf/subscribe_namespace.d.ts.map +1 -1
  72. package/ietf/subscribe_namespace.js +18 -8
  73. package/ietf/subscribe_namespace.js.map +1 -1
  74. package/ietf/subscriber.js +189 -66
  75. package/ietf/subscriber.js.map +1 -1
  76. package/internal.d.ts +7 -0
  77. package/internal.d.ts.map +1 -1
  78. package/internal.js +11 -0
  79. package/internal.js.map +1 -1
  80. package/lite/announce.d.ts +46 -2
  81. package/lite/announce.d.ts.map +1 -1
  82. package/lite/announce.js +126 -11
  83. package/lite/announce.js.map +1 -1
  84. package/lite/connection.d.ts +1 -1
  85. package/lite/connection.d.ts.map +1 -1
  86. package/lite/connection.js +9 -3
  87. package/lite/connection.js.map +1 -1
  88. package/lite/publisher.js +168 -109
  89. package/lite/publisher.js.map +1 -1
  90. package/lite/subscribe.d.ts +10 -4
  91. package/lite/subscribe.d.ts.map +1 -1
  92. package/lite/subscribe.js +20 -10
  93. package/lite/subscribe.js.map +1 -1
  94. package/lite/subscriber.d.ts +10 -2
  95. package/lite/subscriber.d.ts.map +1 -1
  96. package/lite/subscriber.js +159 -93
  97. package/lite/subscriber.js.map +1 -1
  98. package/lite/version.d.ts +11 -0
  99. package/lite/version.d.ts.map +1 -1
  100. package/lite/version.js +56 -0
  101. package/lite/version.js.map +1 -1
  102. package/origin.d.ts +37 -18
  103. package/origin.d.ts.map +1 -1
  104. package/origin.js +248 -103
  105. package/origin.js.map +1 -1
  106. package/package.json +7 -3
  107. package/stream.d.ts +2 -2
  108. package/stream.d.ts.map +1 -1
  109. package/stream.js +16 -11
  110. package/stream.js.map +1 -1
  111. package/tail.d.ts +11 -0
  112. package/tail.d.ts.map +1 -0
  113. package/tail.js +121 -0
  114. package/tail.js.map +1 -0
  115. package/track.d.ts +33 -5
  116. package/track.d.ts.map +1 -1
  117. package/track.js +98 -30
  118. package/track.js.map +1 -1
  119. package/wire.d.ts +2 -0
  120. package/wire.d.ts.map +1 -1
  121. package/wire.js.map +1 -1
@@ -1,18 +1,19 @@
1
1
  /* @ts-self-types="./subscriber.d.ts" */
2
- import { Signal } from "@moq/signals";
2
+ import { race, Signal } from "@moq/signals";
3
3
  import * as announce from "../announced.js";
4
4
  import * as broadcast from "../broadcast.js";
5
5
  import { BroadcastCache } from "../consume.js";
6
- import { controlTimeout, error, ProtocolViolation, reason, StreamCode, StreamError } from "../error.js";
6
+ import { controlTimeout, error, ProtocolViolation, reason, StreamCode, StreamError, sessionCause } from "../error.js";
7
7
  import * as netGroup from "../group.js";
8
8
  import { Cost, MAX_HOPS, routesEqual, UNKNOWN_HOP } from "../hop.js";
9
- import { groupBounds, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.js";
9
+ import { groupBounds, hiddenBelow, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.js";
10
10
  import * as Path from "../path.js";
11
11
  import { Stream } from "../stream.js";
12
+ import { TAIL_GRACE_MS, Tail } from "../tail.js";
12
13
  import * as Time from "../time.js";
13
14
  import { TimeoutError, withTimeout } from "../util/timeout.js";
14
15
  import { overrideBroadcastWire, wireOf } from "../wire.js";
15
- import { AnnounceInit, AnnounceOk, AnnounceRequest, decodeAnnounceBroadcastMaybe } from "./announce.js";
16
+ import { AnnounceHistory, AnnounceInit, AnnounceOk, AnnounceRequest, decodeAnnounceBroadcastMaybe, } from "./announce.js";
16
17
  import { Datagram as DatagramMessage } from "./datagram.js";
17
18
  import * as DatagramStream from "./datagram_stream.js";
18
19
  import { Fetch as FetchMessage } from "./fetch.js";
@@ -115,20 +116,25 @@ export class Subscriber {
115
116
  * Reflected announces (those whose hop chain already includes this
116
117
  * connection) are always dropped: moq-lite-06 has none to keep, and older
117
118
  * versions stay consistent with that.
119
+ *
120
+ * Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless
121
+ * `options.hidden` opts in. The opt-in rides the request on lite-07+; an older peer
122
+ * never hides anything, so the rule is also applied here.
118
123
  */
119
- announced(scope = Path.Pattern.all()) {
124
+ announced(scope = Path.Pattern.all(), options) {
120
125
  const announced = new announce.Producer();
121
126
  // The wire speaks announce interest by prefix, and echoes suffixes beneath it.
122
- void this.#runAnnounced(announced, scopeHead(scope), scope);
127
+ void this.#runAnnounced(announced, scopeHead(scope), scope, options?.hidden ?? false);
123
128
  return announced.consume();
124
129
  }
125
- async #runAnnounced(announced, prefix, scope) {
130
+ async #runAnnounced(announced, prefix, scope, hidden) {
126
131
  console.debug(`announced: prefix=${prefix}`);
127
132
  // Lite04/05: send our own session-level Hop ID so the peer can skip announces
128
133
  // whose hop chain already passed through us. Encoding drops it on every other
129
134
  // version, where we drop the reflected announce on receipt instead. Matches the
130
135
  // Rust subscriber's `exclude_hop: self.self_origin.id` in `run_announce_prefix`.
131
- const msg = new AnnounceRequest(prefix, this.hop);
136
+ const msg = new AnnounceRequest(prefix, this.hop, hidden);
137
+ const visible = (path) => scopeOverlaps(scope, path) && (hidden || !hiddenBelow(prefix, path));
132
138
  // Opened outside the try so the catch can reach it: a protocol violation below has
133
139
  // to reset the stream, not just close our side of it.
134
140
  let stream;
@@ -171,7 +177,7 @@ export class Subscriber {
171
177
  throw new ProtocolViolation(`duplicate announce for ${path}`);
172
178
  }
173
179
  const route = { hops: [UNKNOWN_HOP], cost: Cost.zero };
174
- const live = scopeOverlaps(scope, path);
180
+ const live = visible(path);
175
181
  const captures = scopeCaptures(scope, path);
176
182
  advertised.set(path, { publisher: undefined, live, route, captures });
177
183
  if (!live)
@@ -186,13 +192,13 @@ export class Subscriber {
186
192
  break;
187
193
  }
188
194
  // Lite06+: announce ids. Each received `active` implicitly assigns the next
189
- // per-stream ordinal; `endedId`/`restart` reference it. Tracked even for
190
- // announces we skip as reflected, since the sender doesn't know we skipped.
191
- let nextAnnounceId = 0n;
192
- const announcedById = new Map();
195
+ // per-stream ordinal; `endedId`/`restart` reference it, and lite-07 bases copy
196
+ // from it. Tracked even for announces we skip as reflected, since the sender
197
+ // doesn't know we skipped.
198
+ const history = new AnnounceHistory();
193
199
  // Receive announce updates (for Draft03, this includes initial state)
194
200
  for (;;) {
195
- const announce = await Promise.race([
201
+ const announce = await race([
196
202
  decodeAnnounceBroadcastMaybe(stream.reader, this.version),
197
203
  announced.closed,
198
204
  ]);
@@ -207,43 +213,31 @@ export class Subscriber {
207
213
  let hops;
208
214
  let cost;
209
215
  switch (announce.status) {
210
- case "active":
216
+ case "active": {
217
+ const resolved = hasAnnounceId(this.version) ? history.start(announce) : announce;
211
218
  // The wire names the suffix beneath the interest prefix; the consumer
212
219
  // sees the covered path from the session root.
213
- path = Path.join(prefix, announce.suffix);
220
+ path = Path.join(prefix, resolved.suffix);
214
221
  active = true;
215
- hops = announce.hops;
222
+ hops = resolved.hops;
216
223
  cost = announce.cost;
217
- if (hasAnnounceId(this.version)) {
218
- announcedById.set(nextAnnounceId++, path);
219
- }
220
224
  break;
225
+ }
221
226
  case "ended":
222
227
  path = Path.join(prefix, announce.suffix);
223
228
  active = false;
224
229
  break;
225
- case "endedId": {
230
+ case "endedId":
226
231
  // Resolve and retire the id; an unknown or retired id is a protocol violation.
227
- const resolved = announcedById.get(announce.id);
228
- if (resolved === undefined)
229
- throw new ProtocolViolation(`unknown announce id: ${announce.id}`);
230
- announcedById.delete(announce.id);
231
- if (resolved === null)
232
- continue;
233
- path = resolved;
232
+ path = Path.join(prefix, history.end(announce.id));
234
233
  active = false;
235
234
  break;
236
- }
237
235
  case "restart": {
238
236
  // Resolve the id; it stays live (the replacement reuses it).
239
- const resolved = announcedById.get(announce.id);
240
- if (resolved === undefined)
241
- throw new ProtocolViolation(`unknown announce id: ${announce.id}`);
242
- if (resolved === null)
243
- continue;
244
- path = resolved;
237
+ const resolved = history.update(announce);
238
+ path = Path.join(prefix, resolved.suffix);
245
239
  active = true;
246
- hops = announce.hops;
240
+ hops = resolved.hops;
247
241
  cost = announce.cost;
248
242
  break;
249
243
  }
@@ -334,7 +328,7 @@ export class Subscriber {
334
328
  }
335
329
  const route = { hops: fullHops, cost: cost ?? Cost.zero };
336
330
  const captures = scopeCaptures(scope, path);
337
- if (!scopeOverlaps(scope, path)) {
331
+ if (!visible(path)) {
338
332
  advertised.set(path, { publisher, live: false, route, captures });
339
333
  continue;
340
334
  }
@@ -446,7 +440,7 @@ export class Subscriber {
446
440
  catch (err) {
447
441
  // The setup outlived its deadline waiting for the first response: a control
448
442
  // timeout, not content that arrived late.
449
- const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
443
+ const e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);
450
444
  request.reject(e);
451
445
  this.#subscribes.delete(id);
452
446
  console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
@@ -456,31 +450,40 @@ export class Subscriber {
456
450
  setup.then(() => state.stream?.abort(e), () => state.stream?.abort(e));
457
451
  return;
458
452
  }
459
- const { stream, producer } = opened;
453
+ const { stream, entry } = opened;
454
+ const producer = entry.track;
460
455
  try {
461
456
  // Watch for subscription changes and send SUBSCRIBE_UPDATE. Lite01/Lite02
462
457
  // don't carry SUBSCRIBE_UPDATE on the wire, so skip the watcher there
463
458
  // and just wait on the stream/track like before.
464
459
  //
465
- // On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream;
466
- // drain them (we don't drive delivery off the resolved range) so the FIN is
467
- // observed. Older drafts just wait for the stream to close.
468
- const closed = supportsTrackStream(this.version) ? this.#drainResponses(stream) : stream.reader.closed;
460
+ // On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream until
461
+ // its FIN; older drafts just close it. Either way group streams can still be in
462
+ // flight, so the track ends only once the tail is accounted for. A reset rejects
463
+ // instead, so the track ends with that error rather than a clean tail.
464
+ const responses = supportsTrackStream(this.version)
465
+ ? this.#runResponses(stream, entry)
466
+ : stream.reader.closed;
467
+ const closed = responses.then(() => this.#settleTail(entry));
468
+ // A reset that lands after the race below settled is moot; the race observes one before.
469
+ closed.catch(() => { });
469
470
  const subscriptionUpdates = this.version === Version.DRAFT_01 || this.version === Version.DRAFT_02
470
471
  ? undefined
471
472
  : this.#runSubscriptionUpdates(id, broadcast, producer, msg, stream);
472
473
  // Terminal conditions (stream end, track close, a failed subscription update) settle at most
473
474
  // once; race them into one stable promise so the demand loop doesn't re-subscribe each pass.
475
+ // Updates stop quietly at the FIN, which can land before the responses ahead of it are
476
+ // decoded, so only their failure is terminal on its own.
474
477
  const terminal = [closed, producer.closed];
475
478
  if (subscriptionUpdates !== undefined)
476
- terminal.push(subscriptionUpdates);
477
- const done = Promise.race(terminal);
479
+ terminal.push(subscriptionUpdates.then(() => closed));
480
+ const done = race(terminal);
478
481
  // Serve until a terminal condition fires or the last local subscriber leaves. The unused
479
482
  // wake is level-triggered: re-check demand so a subscriber that returns before we tear
480
483
  // down (e.g. a quickly unmuted tile) resumes on the same subscription.
481
484
  const idle = Symbol("idle");
482
485
  for (;;) {
483
- const reason = await Promise.race([done, producer.unused().then(() => idle)]);
486
+ const reason = await race([done, producer.unused().then(() => idle)]);
484
487
  if (reason === idle && producer.closed.peek() === undefined && producer.used.peek())
485
488
  continue;
486
489
  break;
@@ -490,7 +493,7 @@ export class Subscriber {
490
493
  console.debug(`subscribe close: id=${id} broadcast=${broadcast} track=${request.name}`);
491
494
  }
492
495
  catch (err) {
493
- const e = error(err);
496
+ const e = await sessionCause(this.#quic, err);
494
497
  producer.close(e);
495
498
  console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
496
499
  stream.abort(e);
@@ -524,7 +527,8 @@ export class Subscriber {
524
527
  drainOk = true;
525
528
  }
526
529
  // Register before opening SUBSCRIBE so a racing GROUP stream finds the entry.
527
- this.#subscribes.set(id, { track: producer, timescale });
530
+ const entry = { track: producer, timescale, tail: new Tail() };
531
+ this.#subscribes.set(id, entry);
528
532
  state.stream = await Stream.open(this.#quic);
529
533
  await state.stream.writer.u53(StreamId.Subscribe);
530
534
  await msg.encode(state.stream.writer, this.version);
@@ -535,7 +539,7 @@ export class Subscriber {
535
539
  throw new Error("first subscribe response must be SUBSCRIBE_OK");
536
540
  }
537
541
  }
538
- return { stream: state.stream, producer };
542
+ return { stream: state.stream, entry };
539
543
  }
540
544
  // Opens a TRACK stream, reads the single TRACK_INFO, and FINs. Lite-05+ only.
541
545
  async #trackInfo(broadcast, track) {
@@ -574,25 +578,34 @@ export class Subscriber {
574
578
  }
575
579
  // Open a FETCH stream for one group and stream its bare frames into a group, for the
576
580
  // ConsumeBroadcast backing track.Consumer.fetchGroup() (lite-05+).
577
- fetchGroup(broadcast, track, sequence, options = {}) {
581
+ async fetchGroup(broadcast, track, sequence, options = {}) {
578
582
  // Coalesce onto a still-open fetch of the same group so we don't open a second FETCH
579
583
  // stream (and re-download it); each caller reads an independent mirror.
580
584
  const key = JSON.stringify([broadcast, track, sequence]);
581
- const existing = this.#fetches.get(key);
582
- if (existing && !existing.isClosed)
583
- return Promise.resolve(existing.mirror());
584
- // Create and cache the group synchronously (before any await) so a concurrent fetch for
585
- // the same group finds it and coalesces rather than racing to open its own stream.
586
- const group = new netGroup.Producer(sequence);
587
- this.#fetches.set(key, group);
588
- void group.closed.then(() => {
589
- if (this.#fetches.get(key) === group)
590
- this.#fetches.delete(key);
591
- });
592
- return this.#runFetch(broadcast, track, sequence, options, group);
585
+ let entry = this.#fetches.get(key);
586
+ if (!entry || entry.group.isClosed) {
587
+ const group = new netGroup.Producer(sequence);
588
+ entry = { group, accepted: this.#runFetch(broadcast, track, sequence, options, group) };
589
+ this.#fetches.set(key, entry);
590
+ void group.closed.then(() => {
591
+ if (this.#fetches.get(key)?.group === group)
592
+ this.#fetches.delete(key);
593
+ });
594
+ }
595
+ // Reserve each caller's mirror before awaiting acceptance so the pump sees demand,
596
+ // and a fast FIN cannot discard frames before these callers receive their handles.
597
+ const consumer = entry.group.mirror();
598
+ try {
599
+ await entry.accepted;
600
+ return consumer;
601
+ }
602
+ catch (err) {
603
+ consumer.close();
604
+ throw err;
605
+ }
593
606
  }
594
607
  // Open the FETCH stream and pump the response into the shared group. Setup errors close the
595
- // group (so coalesced mirrors observe them and the entry evicts) and reject this caller.
608
+ // group, evict the entry, and reject every caller waiting for acceptance.
596
609
  async #runFetch(broadcast, track, sequence, options, group) {
597
610
  try {
598
611
  if (!supportsTrackStream(this.version)) {
@@ -604,16 +617,15 @@ export class Subscriber {
604
617
  try {
605
618
  await stream.writer.u53(StreamId.Fetch);
606
619
  await new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version);
620
+ // A byte or an empty-group FIN accepts the fetch; a reset rejects it.
621
+ // done() buffers that byte so the response pump can decode it normally.
622
+ await stream.reader.done();
607
623
  }
608
624
  catch (err) {
609
625
  stream.abort(error(err));
610
626
  throw err;
611
627
  }
612
- // Mint this caller's reader before starting the pump, so the group has demand when the
613
- // pump begins watching it (an abandoned fetch cancels once every reader has left).
614
- const consumer = group.mirror();
615
628
  void this.#runFetchResponse(stream, group, Time.Timescale(info.timescale));
616
- return consumer;
617
629
  }
618
630
  catch (err) {
619
631
  group.close(error(err));
@@ -627,14 +639,13 @@ export class Subscriber {
627
639
  let prevTs = 0n;
628
640
  // Serve until the stream FINs, the group closes, or every reader leaves. A group can
629
641
  // stay open indefinitely (a catalog or JSON stream), so an abandoned fetch is stopped by
630
- // demand, not by the stream ending. `closed` and `unused` are watched across frames as
631
- // stable promises (not re-subscribed to the signals each frame); the unused check is
632
- // level-triggered, so a coalesced fetch that arrives before we cancel re-arms and resumes.
642
+ // demand, not by the stream ending. `unused` is watched across frames as one stable
643
+ // promise; the check is level-triggered, so a coalesced fetch that arrives before we
644
+ // cancel re-arms and resumes.
633
645
  const idle = Symbol("idle");
634
- const closed = Promise.resolve(group.closed);
635
646
  let unused = group.unused().then(() => idle);
636
647
  for (;;) {
637
- const done = await Promise.race([stream.reader.done(), closed, unused]);
648
+ const done = await race([stream.reader.done(), group.closed, unused]);
638
649
  if (done === idle) {
639
650
  if (!group.isClosed && group.used.peek()) {
640
651
  unused = group.unused().then(() => idle);
@@ -661,27 +672,70 @@ export class Subscriber {
661
672
  stream.abort(e);
662
673
  }
663
674
  }
664
- // Drains SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+).
665
- // The resolved range is informational here; the producer already orders groups.
666
- // Resolves (never rejects) on FIN or on the stream being reset out from under it,
667
- // so it's safe to drop from a Promise.race without an unhandled rejection.
668
- async #drainResponses(stream) {
669
- try {
670
- for (;;) {
671
- const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
672
- if (!resp)
673
- return;
675
+ // Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording
676
+ // the range the tail is accounted against. SUBSCRIBE_END declares the track's end right
677
+ // away, so a consumer learns it before the last groups arrive. Resolves on FIN and rejects
678
+ // when the stream is reset, so the track ends with the publisher's error rather than cleanly.
679
+ async #runResponses(stream, entry) {
680
+ for (;;) {
681
+ const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
682
+ if (!resp)
683
+ return;
684
+ if ("start" in resp) {
685
+ entry.start = resp.start.group;
686
+ }
687
+ else if ("end" in resp) {
688
+ if (entry.end !== undefined)
689
+ throw new ProtocolViolation("duplicate SUBSCRIBE_END");
690
+ entry.end = resp.end.group;
691
+ // A local close can win the race with the response; there is nothing left to end.
692
+ if (entry.track.closed.peek() !== undefined)
693
+ continue;
694
+ try {
695
+ entry.track.finishAt(entry.end);
696
+ }
697
+ catch (err) {
698
+ throw new ProtocolViolation(`invalid SUBSCRIBE_END: ${reason(error(err))}`);
699
+ }
700
+ }
701
+ else if ("drop" in resp) {
702
+ entry.tail.account(resp.drop.start, resp.drop.end + 1);
674
703
  }
675
704
  }
676
- catch {
677
- // Stream closed or reset; nothing more to drain.
678
- }
705
+ }
706
+ // Wait for the group streams the publisher still owes once it has ended the subscription.
707
+ //
708
+ // Its FIN says every group below the end is accounted for, but QUIC does not order streams,
709
+ // so one can still be in flight. Wait until each group from SUBSCRIBE_START to the end has
710
+ // a stream (read to its end) or a SUBSCRIBE_DROP. A group reset before its header arrived
711
+ // never shows up, so give up on missing groups after the subscription's effective max age,
712
+ // then end cleanly with them skipped like any stale group. That is a wall-clock stopgap for
713
+ // a presentation-time budget; a publisher sending SUBSCRIBE_DROP for every group it reset
714
+ // would account for them with no timer at all.
715
+ #settleTail(entry) {
716
+ const { tail, track } = entry;
717
+ // Already the smaller of the subscriber's and the track's max age.
718
+ const maxAge = track.subscription.peek()?.maxAge ?? Time.Milli.zero;
719
+ const grace = maxAge > 0 ? maxAge : TAIL_GRACE_MS;
720
+ const complete = () => {
721
+ // Without SUBSCRIBE_END (older drafts) nothing says which groups are owed.
722
+ if (entry.end === undefined)
723
+ return false;
724
+ // Without SUBSCRIBE_START the publisher served no group at all.
725
+ if (entry.start === undefined)
726
+ return true;
727
+ const bounds = groupBounds(track.subscription.peek()?.groups ?? {});
728
+ const start = Math.max(entry.start, bounds.start);
729
+ const end = bounds.end === undefined ? entry.end : Math.min(entry.end, bounds.end);
730
+ return tail.covers(start, end);
731
+ };
732
+ return tail.settle(complete, grace, track.closed);
679
733
  }
680
734
  /**
681
735
  * Send SUBSCRIBE_UPDATE messages whenever the track's aggregate subscription changes.
682
736
  *
683
737
  * Resolves cleanly when the stream or track closes, so the caller can include
684
- * this in Promise.race without leaving a dangling pending write that would
738
+ * this in a race without leaving a dangling pending write that would
685
739
  * become an unhandled rejection if the user calls update after close.
686
740
  *
687
741
  * Peeks the signal at the top of every iteration so that updates which landed
@@ -689,7 +743,7 @@ export class Subscriber {
689
743
  * its listener) aren't lost.
690
744
  */
691
745
  async #runSubscriptionUpdates(id, broadcast, track, msg, stream) {
692
- const stopped = Promise.race([track.closed, stream.reader.closed]).then(() => null);
746
+ const stopped = race([track.closed, stream.reader.closed]).then(() => null);
693
747
  let lastSent = {
694
748
  priority: msg.priority,
695
749
  maxAge: Time.Milli(msg.maxAge),
@@ -702,7 +756,7 @@ export class Subscriber {
702
756
  const current = track.subscription.peek();
703
757
  if (current === undefined || this.#sameSubscription(current, lastSent)) {
704
758
  // Nothing new to send; wait for a change or termination.
705
- const next = await Promise.race([track.subscription.changed(), stopped]);
759
+ const next = await race([track.subscription.changed(), stopped]);
706
760
  if (next === null)
707
761
  return;
708
762
  continue;
@@ -748,10 +802,11 @@ export class Subscriber {
748
802
  }
749
803
  return;
750
804
  }
751
- const { track, timescale } = entry;
805
+ const { track, timescale, tail } = entry;
752
806
  const producer = new netGroup.Producer(group.sequence);
753
- track.writeGroup(producer);
807
+ const read = tail.open(group.sequence);
754
808
  try {
809
+ track.writeGroup(producer);
755
810
  // Block until the timescale is known; the group's stream can arrive before
756
811
  // TRACK_INFO (or implicit defaults) resolves it on the subscribe stream.
757
812
  let scale = timescale.peek();
@@ -770,7 +825,9 @@ export class Subscriber {
770
825
  // Scale 0 (pre-lite-05) carries no timestamp, so we wall-clock-stamp.
771
826
  let prevTs = 0n;
772
827
  for (;;) {
773
- const done = await Promise.race([stream.done(), track.closed, producer.closed]);
828
+ // Only the group's own stream ends it: a track that closes first has already
829
+ // closed (or aborted) this group through its cache.
830
+ const done = await race([stream.done(), producer.closed]);
774
831
  if (done !== false)
775
832
  break;
776
833
  let timestamp;
@@ -795,6 +852,9 @@ export class Subscriber {
795
852
  producer.close(e);
796
853
  stream.stop(e);
797
854
  }
855
+ finally {
856
+ read();
857
+ }
798
858
  }
799
859
  /**
800
860
  * Receives QUIC datagrams and routes each to its subscription's track producer (lite-05 §6.4).
@@ -857,6 +917,8 @@ export class Subscriber {
857
917
  if (!scale)
858
918
  return;
859
919
  const timestamp = new Time.Timestamp(dg.timestamp, Time.Timescale(scale));
920
+ // A datagram's sequence is never owed a stream, so it never holds the tail open.
921
+ entry.tail.account(dg.sequence, dg.sequence + 1);
860
922
  entry.track.insertDatagram(dg.sequence, timestamp, dg.payload);
861
923
  }
862
924
  /**
@@ -925,10 +987,14 @@ export class Subscriber {
925
987
  this.#probe.set({});
926
988
  }
927
989
  }
928
- close() {
990
+ /**
991
+ * Ends every subscribed track: cleanly for a deliberate close, or with `err` when the
992
+ * session died, since those tracks were cut off rather than ended.
993
+ */
994
+ close(err) {
929
995
  this.#closed.abort();
930
996
  for (const { track } of this.#subscribes.values()) {
931
- track.close();
997
+ track.close(err);
932
998
  }
933
999
  this.#subscribes.clear();
934
1000
  }