@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
package/lite/publisher.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /* @ts-self-types="./publisher.d.ts" */
2
- import { Signal } from "@moq/signals";
2
+ import { race, Signal } from "@moq/signals";
3
3
  import { error, NotFound, reason, StreamCode, StreamError } from "../error.js";
4
4
  import { routesEqual } from "../hop.js";
5
- import { hooks } from "../internal.js";
5
+ import { hiddenBelow, hooks } from "../internal.js";
6
6
  import * as Path from "../path.js";
7
7
  import { Writer } from "../stream.js";
8
8
  import { Milli, Timescale } from "../time.js";
@@ -15,11 +15,11 @@ import { Priority, sendOrder } from "./priority.js";
15
15
  import { Probe } from "./probe.js";
16
16
  import { encodeSubscribeResponse, exclusiveGroupEnd, SubscribeEnd, SubscribeOk, SubscribeStart, SubscribeUpdate, } from "./subscribe.js";
17
17
  import { TrackInfo as TrackInfoMessage } from "./track.js";
18
- import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, resolvesStart, Version } from "./version.js";
18
+ import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, hasStreamCount, resolvesStart, Version, } from "./version.js";
19
19
  // Where each originated route lands under the requested prefix: its suffix beneath
20
20
  // the prefix, or the empty suffix for a route above it, where the most specific
21
21
  // such route wins the way a request through the prefix would resolve.
22
- function presented(prefix, table) {
22
+ function presented(prefix, table, hidden) {
23
23
  const out = new Map();
24
24
  let rootLen = -1;
25
25
  for (const [covered, snap] of table) {
@@ -30,6 +30,9 @@ function presented(prefix, table) {
30
30
  out.set(Path.empty(), snap);
31
31
  continue;
32
32
  }
33
+ // A hidden route stays off the wire unless the request opted in.
34
+ if (!hidden && hiddenBelow(prefix, covered))
35
+ continue;
33
36
  const suffix = Path.stripPrefix(prefix, covered);
34
37
  if (suffix !== null)
35
38
  out.set(suffix, snap);
@@ -124,20 +127,26 @@ class SubscriptionControls {
124
127
  }
125
128
  /** Returns false when peer departure supersedes a blocked response write. */
126
129
  async response(pending) {
127
- const result = await Promise.race([
130
+ // `#ended` lives as long as the stream, so it is raced as-is rather than mapped per call.
131
+ const result = await race([
128
132
  pending.then(() => ({ kind: "sent" }), (err) => ({ kind: "error", error: error(err) })),
129
- this.#ended.then((end) => ({ kind: "ended", end })),
133
+ this.#ended,
130
134
  ]);
131
- if (result.kind === "sent")
132
- return true;
133
- if (result.kind === "error")
135
+ if (result !== null && !(result instanceof Error)) {
136
+ if (result.kind === "sent")
137
+ return true;
134
138
  throw result.error;
135
- // Promise.race leaves the blocked encode running, so reset the writable half too.
136
- this.#writer.reset(result.end ?? new StreamError(StreamCode.Cancel, { message: "cancel" }));
137
- if (result.end)
138
- throw result.end;
139
+ }
140
+ // The race leaves the blocked encode running, so reset the writable half too.
141
+ this.#writer.reset(result ?? new StreamError(StreamCode.Cancel, { message: "cancel" }));
142
+ if (result)
143
+ throw result;
139
144
  return false;
140
145
  }
146
+ /** Settles once the stream is over: `null` when it ended cleanly, or the failure. */
147
+ get ended() {
148
+ return this.#ended;
149
+ }
141
150
  #finish(end) {
142
151
  if (this.#end !== undefined)
143
152
  return;
@@ -239,12 +248,7 @@ export class Publisher {
239
248
  // presence is the gate: undefined means datagrams aren't served on this connection. All
240
249
  // subscriptions share it, since a second getWriter on the same stream would throw.
241
250
  #datagramWriter;
242
- // The published broadcasts, borrowed from the origin this session serves. The origin
243
- // outlives the session, so this is read-only here: subscribe/fetch look it up, and
244
- // closing the session leaves the broadcasts alone.
245
- #broadcasts;
246
- // Originated advertisements this session forwards. Unadvertised local broadcasts
247
- // stay reachable by exact path without appearing here.
251
+ // Originated advertisements this session forwards.
248
252
  #advertised;
249
253
  #publish;
250
254
  // TRACK_INFO is immutable per track, so resolve it from the application once
@@ -268,7 +272,6 @@ export class Publisher {
268
272
  this.version = version;
269
273
  this.hop = hop;
270
274
  const origin = publish && wireOf(publish);
271
- this.#broadcasts = origin?.broadcasts ?? new Signal(new Map());
272
275
  this.#advertised = origin?.advertised ?? new Signal(new Map());
273
276
  this.#publish = publish;
274
277
  // Grab the datagram writer up front when the transport carries datagrams (no group
@@ -345,7 +348,7 @@ export class Publisher {
345
348
  const initial = this.#advertised.peek();
346
349
  if (!initial)
347
350
  return; // closed
348
- for (const [name, snap] of presented(msg.prefix, initial)) {
351
+ for (const [name, snap] of presented(msg.prefix, initial, msg.hidden)) {
349
352
  active.set(name, snap);
350
353
  }
351
354
  switch (this.version) {
@@ -374,7 +377,7 @@ export class Publisher {
374
377
  }
375
378
  }
376
379
  for (;;) {
377
- const advertised = await Promise.race([changed, stream.reader.closed]);
380
+ const advertised = await race([changed, stream.reader.closed]);
378
381
  dispose();
379
382
  if (!advertised)
380
383
  break;
@@ -386,7 +389,7 @@ export class Publisher {
386
389
  if (!latest)
387
390
  break;
388
391
  const updated = new Map();
389
- for (const [name, snap] of presented(msg.prefix, latest)) {
392
+ for (const [name, snap] of presented(msg.prefix, latest, msg.hidden)) {
390
393
  updated.set(name, snap);
391
394
  }
392
395
  for (const [suffix, snap] of active) {
@@ -421,8 +424,8 @@ export class Publisher {
421
424
  let front;
422
425
  try {
423
426
  front =
424
- this.#broadcasts.peek()?.get(msg.broadcast) ??
425
- (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
427
+ this.#publish &&
428
+ (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
426
429
  }
427
430
  catch (err) {
428
431
  stream.writer.reset(error(err));
@@ -534,8 +537,8 @@ export class Publisher {
534
537
  let front;
535
538
  try {
536
539
  front =
537
- this.#broadcasts.peek()?.get(msg.broadcast) ??
538
- (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
540
+ this.#publish &&
541
+ (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
539
542
  }
540
543
  catch (err) {
541
544
  stream.writer.reset(error(err));
@@ -587,24 +590,38 @@ export class Publisher {
587
590
  const emitRange = supportsTrackStream(this.version);
588
591
  let startSent = false;
589
592
  let endSent = false;
593
+ // Lite-07+ counts the group streams in SUBSCRIBE_END, so it goes out only once every
594
+ // served group has opened its stream or given up, and a cap holding groups back
595
+ // delays it until they are released.
596
+ const countStreams = hasStreamCount(this.version);
597
+ let streams = 0;
598
+ const opening = new Set();
590
599
  // The track's exclusive final boundary. A Rust subscriber feeds SUBSCRIBE_END
591
600
  // straight into finish_at, so it must name the track's boundary (which counts
592
601
  // datagram sequences too), not the delivered range: a subscription cap can hold
593
602
  // produced groups back. The latest() fallback covers a subscription torn down
594
603
  // before the producer declared it.
595
604
  const boundary = () => track.final() ?? (track.latest() ?? -1) + 1;
596
- // SUBSCRIBE_END names that boundary, which a cap can hold groups back from, so it goes
597
- // out as soon as the producer finishes and the subscription keeps serving whatever a
598
- // later cap raise releases (see the Rust publisher's Recv::Boundary).
605
+ // Before lite-07, SUBSCRIBE_END names that boundary, which a cap can hold groups back
606
+ // from, so it goes out as soon as the producer finishes and the subscription keeps
607
+ // serving whatever a later cap raise releases (see the Rust publisher's Recv::Boundary).
599
608
  const sendEnd = async () => {
600
609
  endSent = true;
601
- if (emitRange) {
602
- return controls.response(encodeSubscribeResponse(stream, { end: new SubscribeEnd(boundary()) }, this.version));
603
- }
604
- return true;
610
+ if (!emitRange)
611
+ return true;
612
+ return controls.response((async () => {
613
+ // A group that gives up before its stream opens is never counted.
614
+ if (countStreams)
615
+ while (opening.size > 0)
616
+ await Promise.all(opening);
617
+ const end = new SubscribeEnd(boundary(), streams);
618
+ await encodeSubscribeResponse(stream, { end }, this.version);
619
+ })());
605
620
  };
606
621
  // One ranking for the whole subscription, shared by every group it serves.
607
622
  const priority = new Priority(track);
623
+ // Every group this subscription started serving, until its stream finishes or resets.
624
+ const groups = new Set();
608
625
  // Cancels groups still queued for a stream slot. Only the subscriber leaving counts:
609
626
  // a track that ran out of groups still has to flush the ones already queued, and the
610
627
  // caller FINs the subscribe stream to say so.
@@ -651,26 +668,44 @@ export class Publisher {
651
668
  case "error":
652
669
  throw recv.error;
653
670
  case "idle":
671
+ // Before lite-07, an end declared ahead of the live edge goes out as
672
+ // soon as it is known, while the remaining groups are still being
673
+ // produced. The lite-07 count is not final until those groups open.
674
+ if (!endSent && !countStreams && track.final() !== undefined) {
675
+ if (!(await sendEnd()))
676
+ return;
677
+ continue;
678
+ }
654
679
  await waitForSubscription(controls, track);
655
680
  continue;
656
681
  case "boundary":
657
682
  // The producer finished but is still holding groups above the cap.
658
683
  // Declare the boundary, then wait for an update to release them.
659
- if (!endSent) {
684
+ if (!endSent && !countStreams) {
660
685
  if (!(await sendEnd()))
661
686
  return;
662
687
  continue;
663
688
  }
664
689
  await waitForSubscription(controls, track);
665
690
  continue;
666
- case "done":
691
+ case "done": {
667
692
  if (!endSent) {
668
693
  if (!(await sendEnd()))
669
694
  return;
670
695
  continue;
671
696
  }
697
+ // The FIN tells the subscriber every group is accounted for, so it waits
698
+ // until each group stream finished or reset. The subscriber leaving
699
+ // instead cancels whatever is still queued.
700
+ const drained = Symbol("drained");
701
+ const end = await Promise.race([Promise.all(groups).then(() => drained), controls.ended]);
702
+ if (end instanceof Error)
703
+ throw end;
704
+ if (end !== drained)
705
+ return;
672
706
  finished = true;
673
707
  return;
708
+ }
674
709
  }
675
710
  const group = recv.group;
676
711
  const range = frameRange(bounds, group.sequence);
@@ -686,7 +721,7 @@ export class Publisher {
686
721
  if (!(await controls.response(encodeSubscribeResponse(stream, { start: new SubscribeStart(group.sequence) }, this.version))))
687
722
  return;
688
723
  }
689
- void this.#runGroup({
724
+ const options = {
690
725
  sub,
691
726
  group,
692
727
  timescale,
@@ -694,7 +729,21 @@ export class Publisher {
694
729
  unsubscribed,
695
730
  start: range.start,
696
731
  end: range.end,
732
+ };
733
+ // `opening` settles when the stream opens so the lite-07 count can be sent.
734
+ // `groups` covers the serve too, so the FIN still waits for every stream to
735
+ // finish or reset, including one that has not opened yet.
736
+ const opened = this.#openGroup(options);
737
+ const task = opened.then(async (writer) => {
738
+ if (!writer)
739
+ return;
740
+ streams += 1;
741
+ await this.#serveGroup(writer, options);
697
742
  });
743
+ groups.add(task);
744
+ void task.finally(() => groups.delete(task));
745
+ opening.add(opened);
746
+ void opened.finally(() => opening.delete(opened));
698
747
  }
699
748
  }
700
749
  finally {
@@ -710,8 +759,8 @@ export class Publisher {
710
759
  */
711
760
  async runTrackInfo(msg, stream) {
712
761
  try {
713
- const front = this.#broadcasts.peek()?.get(msg.broadcast) ??
714
- (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
762
+ const front = this.#publish &&
763
+ (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
715
764
  if (!front)
716
765
  throw new NotFound(`broadcast ${msg.broadcast}`);
717
766
  const info = await this.#resolveTrackInfo(front, msg.track);
@@ -745,7 +794,7 @@ export class Publisher {
745
794
  // relays re-serve with the same window.
746
795
  maxAge: info.maxAge,
747
796
  // Lite05 mandates per-frame timestamps. Advertise the track's timescale;
748
- // `#runGroup` emits each frame converted to it.
797
+ // `#serveGroup` emits each frame converted to it.
749
798
  timescale: info.timescale,
750
799
  });
751
800
  })();
@@ -772,7 +821,7 @@ export class Publisher {
772
821
  const datagram = await track.recvDatagram();
773
822
  if (!datagram)
774
823
  return; // Track finished; #runTrack tears the subscription down.
775
- // Convert the timestamp to the track's advertised timescale, matching #runGroup.
824
+ // Convert the timestamp to the track's advertised timescale, matching #serveGroup.
776
825
  const ts = Math.round(datagram.timestamp.as(timescale));
777
826
  const body = new DatagramMessage(sub, datagram.sequence, ts, datagram.payload).encode();
778
827
  // No group fallback: drop anything that doesn't fit a single datagram.
@@ -796,13 +845,13 @@ export class Publisher {
796
845
  // as `startFrame`. Skipping the head here is the only thing keeping those numbers
797
846
  // honest; a group that ends before we reach it can't be served at all.
798
847
  for (let i = 0; i < startFrame; i++) {
799
- if (!(await Promise.race([group.readFrame(), stream.closed]))) {
848
+ if (!(await race([group.readFrame(), stream.closed]))) {
800
849
  throw new Error(`fetch group ended at frame ${i}, before the requested start ${startFrame}`);
801
850
  }
802
851
  }
803
852
  let prevTs = 0n;
804
853
  for (let index = startFrame; endFrame === undefined || index <= endFrame; index++) {
805
- const frame = await Promise.race([group.readFrame(), stream.closed]);
854
+ const frame = await race([group.readFrame(), stream.closed]);
806
855
  if (!frame)
807
856
  break;
808
857
  const ts = BigInt(Math.round(frame.timestamp.as(timescale)));
@@ -813,15 +862,13 @@ export class Publisher {
813
862
  }
814
863
  }
815
864
  /**
816
- * Serves one group on its own unidirectional stream.
865
+ * Opens the unidirectional stream for one group, or closes the group and resolves
866
+ * `undefined` when it cannot get one.
817
867
  *
818
868
  * @internal
819
869
  */
820
- async #runGroup(options) {
821
- const { sub, group, timescale, priority, unsubscribed, start: startFrame, end: endFrame } = options;
822
- // This model holds whole groups, so frame `startFrame` is always reachable unless
823
- // the group ends first. Declaring it up front keeps the stream self-describing.
824
- const msg = new GroupMessage({ subscribe: sub, sequence: group.sequence, frameStart: startFrame });
870
+ async #openGroup(options) {
871
+ const { group, priority, unsubscribed } = options;
825
872
  try {
826
873
  // The transport drains streams by send order, so this is what makes a high-priority
827
874
  // track (and a newer group within it) win the link when there isn't room for both.
@@ -835,75 +882,87 @@ export class Publisher {
835
882
  cancel: unsubscribed,
836
883
  waitUntilAvailable: false,
837
884
  });
838
- if (!stream) {
885
+ if (!stream)
839
886
  group.close(new Error("no stream slot"));
840
- return;
841
- }
842
- // Everything past this point runs inside the cleanup scope, so a failure never leaves
843
- // a finished group's stream being ranked.
844
- try {
845
- // A SUBSCRIBE_UPDATE re-ranks the subscription, so a group already on the wire
846
- // follows it too rather than keeping a stale rank until it finishes.
847
- priority.add(stream, group.sequence);
848
- await hooks.guardGroup(group, (async () => {
849
- await stream.u53(0); // stream type
850
- await msg.encode(stream, this.version);
851
- })());
852
- // Lite05+ prefixes every frame with a zigzag-delta timestamp at the track's
853
- // advertised timescale; older drafts omit it.
854
- const timestamps = supportsTrackStream(this.version);
855
- let prevTs = 0n;
856
- // Whether the cursor ever reached the requested start, which decides how the
857
- // end of the group is read below.
858
- let reached = startFrame === 0;
859
- for (;;) {
860
- const read = await Promise.race([hooks.readGroupFrame(group), stream.closed]);
861
- if (!read) {
862
- // The group ended before the frame the subscriber asked to start
863
- // at, so this publisher can't serve the range at all. FINning here
864
- // would claim an empty group under that index; reset so it reads
865
- // as the gap it is.
866
- if (!reached)
867
- throw new Error(`group ended before frame ${startFrame}`);
868
- break;
869
- }
870
- try {
871
- // Frames below the requested start were excluded, and the receiver
872
- // numbers what it gets from `startFrame`.
873
- if (read.sequence < startFrame)
874
- continue;
875
- if (endFrame !== undefined && read.sequence > endFrame)
876
- break;
887
+ return stream;
888
+ }
889
+ catch (err) {
890
+ group.close(error(err));
891
+ return undefined;
892
+ }
893
+ }
894
+ /**
895
+ * Serves one group on the stream {@link #openGroup} opened for it.
896
+ *
897
+ * @internal
898
+ */
899
+ async #serveGroup(stream, options) {
900
+ const { sub, group, timescale, priority, start: startFrame, end: endFrame } = options;
901
+ // This model holds whole groups, so frame `startFrame` is always reachable unless
902
+ // the group ends first. Declaring it up front keeps the stream self-describing.
903
+ const msg = new GroupMessage({ subscribe: sub, sequence: group.sequence, frameStart: startFrame });
904
+ // Everything past this point runs inside the cleanup scope, so a failure never leaves
905
+ // a finished group's stream being ranked.
906
+ try {
907
+ // A SUBSCRIBE_UPDATE re-ranks the subscription, so a group already on the wire
908
+ // follows it too rather than keeping a stale rank until it finishes.
909
+ priority.add(stream, group.sequence);
910
+ await hooks.guardGroup(group, (async () => {
911
+ await stream.u53(0); // stream type
912
+ await msg.encode(stream, this.version);
913
+ })());
914
+ // Lite05+ prefixes every frame with a zigzag-delta timestamp at the track's
915
+ // advertised timescale; older drafts omit it.
916
+ const timestamps = supportsTrackStream(this.version);
917
+ let prevTs = 0n;
918
+ // Whether the cursor ever reached the requested start, which decides how the
919
+ // end of the group is read below.
920
+ let reached = startFrame === 0;
921
+ for (;;) {
922
+ const read = await race([hooks.readGroupFrame(group), stream.closed]);
923
+ if (!read) {
924
+ // The group ended before the frame the subscriber asked to start
925
+ // at, so this publisher can't serve the range at all. FINning here
926
+ // would claim an empty group under that index; reset so it reads
927
+ // as the gap it is.
928
+ if (!reached)
929
+ throw new Error(`group ended before frame ${startFrame}`);
930
+ break;
931
+ }
932
+ try {
933
+ // A group that ends exactly at the start is a valid, empty range.
934
+ if (read.sequence + 1 >= startFrame)
877
935
  reached = true;
878
- if (timestamps) {
879
- // Convert each frame to the track's advertised timescale.
880
- const ts = BigInt(Math.round(read.frame.timestamp.as(timescale)));
881
- await hooks.guardGroup(group, stream.u62(zigzag(ts - prevTs)));
882
- prevTs = ts;
883
- }
884
- await hooks.guardGroup(group, stream.u53(read.frame.payload.byteLength));
885
- await hooks.guardGroup(group, stream.write(read.frame.payload));
886
- }
887
- finally {
888
- read.complete();
936
+ // Frames below the requested start were excluded, and the receiver
937
+ // numbers what it gets from `startFrame`.
938
+ if (read.sequence < startFrame)
939
+ continue;
940
+ if (endFrame !== undefined && read.sequence > endFrame)
941
+ break;
942
+ if (timestamps) {
943
+ // Convert each frame to the track's advertised timescale.
944
+ const ts = BigInt(Math.round(read.frame.timestamp.as(timescale)));
945
+ await hooks.guardGroup(group, stream.u62(zigzag(ts - prevTs)));
946
+ prevTs = ts;
889
947
  }
948
+ await hooks.guardGroup(group, stream.u53(read.frame.payload.byteLength));
949
+ await hooks.guardGroup(group, stream.write(read.frame.payload));
950
+ }
951
+ finally {
952
+ read.complete();
890
953
  }
891
- stream.close();
892
- group.close();
893
- }
894
- catch (err) {
895
- const e = error(err);
896
- stream.reset(e);
897
- group.close(e);
898
- }
899
- finally {
900
- priority.remove(stream);
901
954
  }
955
+ stream.close();
956
+ group.close();
902
957
  }
903
958
  catch (err) {
904
959
  const e = error(err);
960
+ stream.reset(e);
905
961
  group.close(e);
906
962
  }
963
+ finally {
964
+ priority.remove(stream);
965
+ }
907
966
  }
908
967
  /**
909
968
  * Handles a probe stream by periodically reporting estimated bitrate.
@@ -936,7 +995,7 @@ export class Publisher {
936
995
  try {
937
996
  for (;;) {
938
997
  const timeout = new Promise((resolve) => setTimeout(() => resolve("timeout"), PROBE_INTERVAL));
939
- const result = await Promise.race([timeout, stream.reader.closed]);
998
+ const result = await race([timeout, stream.reader.closed]);
940
999
  if (result !== "timeout")
941
1000
  break;
942
1001
  // The two fields are independent on the wire, each using 0 for