@moq/net 0.4.0 → 0.4.2

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 (204) 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 +27 -10
  5. package/broadcast.d.ts.map +1 -1
  6. package/broadcast.js +47 -21
  7. package/broadcast.js.map +1 -1
  8. package/connection/accept.js +14 -4
  9. package/connection/accept.js.map +1 -1
  10. package/connection/connect.d.ts.map +1 -1
  11. package/connection/connect.js +14 -4
  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 +61 -47
  17. package/connection/forward.js.map +1 -1
  18. package/connection/goaway.d.ts +34 -0
  19. package/connection/goaway.d.ts.map +1 -0
  20. package/connection/goaway.js +176 -0
  21. package/connection/goaway.js.map +1 -0
  22. package/connection/handshake.d.ts +5 -2
  23. package/connection/handshake.d.ts.map +1 -1
  24. package/connection/handshake.js +45 -10
  25. package/connection/handshake.js.map +1 -1
  26. package/connection/pool.d.ts +24 -11
  27. package/connection/pool.d.ts.map +1 -1
  28. package/connection/pool.js +50 -18
  29. package/connection/pool.js.map +1 -1
  30. package/connection/reload.d.ts.map +1 -1
  31. package/connection/reload.js +189 -35
  32. package/connection/reload.js.map +1 -1
  33. package/error.d.ts +11 -0
  34. package/error.d.ts.map +1 -1
  35. package/error.js +35 -0
  36. package/error.js.map +1 -1
  37. package/errors.d.ts +1 -1
  38. package/errors.d.ts.map +1 -1
  39. package/errors.js +1 -1
  40. package/errors.js.map +1 -1
  41. package/group.d.ts.map +1 -1
  42. package/group.js +5 -4
  43. package/group.js.map +1 -1
  44. package/hop.d.ts +8 -0
  45. package/hop.d.ts.map +1 -1
  46. package/hop.js +16 -0
  47. package/hop.js.map +1 -1
  48. package/ietf/adapter.d.ts +9 -1
  49. package/ietf/adapter.d.ts.map +1 -1
  50. package/ietf/adapter.js +46 -17
  51. package/ietf/adapter.js.map +1 -1
  52. package/ietf/cluster.d.ts +3 -3
  53. package/ietf/cluster.js +3 -3
  54. package/ietf/cluster.js.map +1 -1
  55. package/ietf/connection.d.ts +1 -1
  56. package/ietf/connection.d.ts.map +1 -1
  57. package/ietf/connection.js +118 -41
  58. package/ietf/connection.js.map +1 -1
  59. package/ietf/error.js +27 -2
  60. package/ietf/error.js.map +1 -1
  61. package/ietf/fetch.d.ts +7 -20
  62. package/ietf/fetch.d.ts.map +1 -1
  63. package/ietf/fetch.js +52 -22
  64. package/ietf/fetch.js.map +1 -1
  65. package/ietf/filter.d.ts +2 -0
  66. package/ietf/filter.d.ts.map +1 -1
  67. package/ietf/filter.js +4 -0
  68. package/ietf/filter.js.map +1 -1
  69. package/ietf/goaway.d.ts +9 -1
  70. package/ietf/goaway.d.ts.map +1 -1
  71. package/ietf/goaway.js +20 -0
  72. package/ietf/goaway.js.map +1 -1
  73. package/ietf/hidden.d.ts +2 -0
  74. package/ietf/hidden.d.ts.map +1 -0
  75. package/ietf/hidden.js +30 -0
  76. package/ietf/hidden.js.map +1 -0
  77. package/ietf/index.d.ts +2 -1
  78. package/ietf/index.d.ts.map +1 -1
  79. package/ietf/index.js +2 -1
  80. package/ietf/index.js.map +1 -1
  81. package/ietf/object.d.ts +15 -8
  82. package/ietf/object.d.ts.map +1 -1
  83. package/ietf/object.js +54 -36
  84. package/ietf/object.js.map +1 -1
  85. package/ietf/parameters.d.ts +12 -0
  86. package/ietf/parameters.d.ts.map +1 -1
  87. package/ietf/parameters.js +82 -12
  88. package/ietf/parameters.js.map +1 -1
  89. package/ietf/properties.d.ts +1 -0
  90. package/ietf/properties.d.ts.map +1 -1
  91. package/ietf/properties.js +14 -0
  92. package/ietf/properties.js.map +1 -1
  93. package/ietf/publish.d.ts +19 -2
  94. package/ietf/publish.d.ts.map +1 -1
  95. package/ietf/publish.js +40 -6
  96. package/ietf/publish.js.map +1 -1
  97. package/ietf/publish_namespace.d.ts +2 -2
  98. package/ietf/publish_namespace.js +2 -2
  99. package/ietf/publish_namespace.js.map +1 -1
  100. package/ietf/publisher.js +383 -214
  101. package/ietf/publisher.js.map +1 -1
  102. package/ietf/subscribe.d.ts +7 -1
  103. package/ietf/subscribe.d.ts.map +1 -1
  104. package/ietf/subscribe.js +25 -18
  105. package/ietf/subscribe.js.map +1 -1
  106. package/ietf/subscribe_namespace.d.ts +8 -2
  107. package/ietf/subscribe_namespace.d.ts.map +1 -1
  108. package/ietf/subscribe_namespace.js +20 -11
  109. package/ietf/subscribe_namespace.js.map +1 -1
  110. package/ietf/subscriber.js +226 -88
  111. package/ietf/subscriber.js.map +1 -1
  112. package/ietf/token.d.ts +2 -0
  113. package/ietf/token.d.ts.map +1 -0
  114. package/ietf/token.js +99 -0
  115. package/ietf/token.js.map +1 -0
  116. package/ietf/track.d.ts +4 -0
  117. package/ietf/track.d.ts.map +1 -1
  118. package/ietf/track.js +6 -20
  119. package/ietf/track.js.map +1 -1
  120. package/index.d.ts +1 -1
  121. package/index.d.ts.map +1 -1
  122. package/index.js.map +1 -1
  123. package/internal.d.ts +19 -3
  124. package/internal.d.ts.map +1 -1
  125. package/internal.js +43 -0
  126. package/internal.js.map +1 -1
  127. package/lite/announce.d.ts +46 -2
  128. package/lite/announce.d.ts.map +1 -1
  129. package/lite/announce.js +133 -15
  130. package/lite/announce.js.map +1 -1
  131. package/lite/connection.d.ts +1 -1
  132. package/lite/connection.d.ts.map +1 -1
  133. package/lite/connection.js +30 -9
  134. package/lite/connection.js.map +1 -1
  135. package/lite/datagram.d.ts +3 -2
  136. package/lite/datagram.d.ts.map +1 -1
  137. package/lite/datagram.js +7 -8
  138. package/lite/datagram.js.map +1 -1
  139. package/lite/group.d.ts +12 -8
  140. package/lite/group.d.ts.map +1 -1
  141. package/lite/group.js +37 -16
  142. package/lite/group.js.map +1 -1
  143. package/lite/message.d.ts +2 -2
  144. package/lite/message.d.ts.map +1 -1
  145. package/lite/message.js +14 -5
  146. package/lite/message.js.map +1 -1
  147. package/lite/publisher.js +174 -133
  148. package/lite/publisher.js.map +1 -1
  149. package/lite/setup.d.ts +1 -1
  150. package/lite/setup.d.ts.map +1 -1
  151. package/lite/setup.js +22 -19
  152. package/lite/setup.js.map +1 -1
  153. package/lite/subscribe.d.ts +10 -4
  154. package/lite/subscribe.d.ts.map +1 -1
  155. package/lite/subscribe.js +20 -10
  156. package/lite/subscribe.js.map +1 -1
  157. package/lite/subscriber.d.ts +10 -2
  158. package/lite/subscriber.d.ts.map +1 -1
  159. package/lite/subscriber.js +333 -188
  160. package/lite/subscriber.js.map +1 -1
  161. package/lite/version.d.ts +11 -0
  162. package/lite/version.d.ts.map +1 -1
  163. package/lite/version.js +56 -0
  164. package/lite/version.js.map +1 -1
  165. package/origin.d.ts +46 -19
  166. package/origin.d.ts.map +1 -1
  167. package/origin.js +529 -189
  168. package/origin.js.map +1 -1
  169. package/package.json +8 -4
  170. package/stream.d.ts +79 -14
  171. package/stream.d.ts.map +1 -1
  172. package/stream.js +375 -133
  173. package/stream.js.map +1 -1
  174. package/tail.d.ts +18 -0
  175. package/tail.d.ts.map +1 -0
  176. package/tail.js +167 -0
  177. package/tail.js.map +1 -0
  178. package/track.d.ts +46 -7
  179. package/track.d.ts.map +1 -1
  180. package/track.js +263 -101
  181. package/track.js.map +1 -1
  182. package/util/abort.d.ts +2 -0
  183. package/util/abort.d.ts.map +1 -0
  184. package/util/abort.js +20 -0
  185. package/util/abort.js.map +1 -0
  186. package/util/u64.d.ts +39 -0
  187. package/util/u64.d.ts.map +1 -0
  188. package/util/u64.js +83 -0
  189. package/util/u64.js.map +1 -0
  190. package/util/varint.d.ts +29 -0
  191. package/util/varint.d.ts.map +1 -0
  192. package/util/varint.js +198 -0
  193. package/util/varint.js.map +1 -0
  194. package/varint.d.ts +10 -6
  195. package/varint.d.ts.map +1 -1
  196. package/varint.js +40 -237
  197. package/varint.js.map +1 -1
  198. package/wire.d.ts +19 -3
  199. package/wire.d.ts.map +1 -1
  200. package/wire.js.map +1 -1
  201. package/ietf/control.d.ts +0 -135
  202. package/ietf/control.d.ts.map +0 -1
  203. package/ietf/control.js +0 -242
  204. package/ietf/control.js.map +0 -1
package/lite/publisher.js CHANGED
@@ -1,9 +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
- import { routesEqual } from "../hop.js";
5
- import { hooks } from "../internal.js";
6
- import * as Path from "../path.js";
4
+ import { Cost, routesEqual } from "../hop.js";
5
+ import { hiddenBelow, hooks, presented } from "../internal.js";
7
6
  import { Writer } from "../stream.js";
8
7
  import { Milli, Timescale } from "../time.js";
9
8
  import { wireOf } from "../wire.js";
@@ -15,27 +14,7 @@ import { Priority, sendOrder } from "./priority.js";
15
14
  import { Probe } from "./probe.js";
16
15
  import { encodeSubscribeResponse, exclusiveGroupEnd, SubscribeEnd, SubscribeOk, SubscribeStart, SubscribeUpdate, } from "./subscribe.js";
17
16
  import { TrackInfo as TrackInfoMessage } from "./track.js";
18
- import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, resolvesStart, Version } from "./version.js";
19
- // Where each originated route lands under the requested prefix: its suffix beneath
20
- // the prefix, or the empty suffix for a route above it, where the most specific
21
- // such route wins the way a request through the prefix would resolve.
22
- function presented(prefix, table) {
23
- const out = new Map();
24
- let rootLen = -1;
25
- for (const [covered, snap] of table) {
26
- if (Path.hasPrefix(covered, prefix)) {
27
- if (covered.length < rootLen)
28
- continue;
29
- rootLen = covered.length;
30
- out.set(Path.empty(), snap);
31
- continue;
32
- }
33
- const suffix = Path.stripPrefix(prefix, covered);
34
- if (suffix !== null)
35
- out.set(suffix, snap);
36
- }
37
- return out;
38
- }
17
+ import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, hasRouteCost, hasStreamCount, resolvesStart, Version, } from "./version.js";
39
18
  const PROBE_INTERVAL = 100; // ms
40
19
  const PROBE_MAX_AGE = 10_000; // ms
41
20
  const PROBE_MAX_DELTA = 0.25;
@@ -124,20 +103,26 @@ class SubscriptionControls {
124
103
  }
125
104
  /** Returns false when peer departure supersedes a blocked response write. */
126
105
  async response(pending) {
127
- const result = await Promise.race([
106
+ // `#ended` lives as long as the stream, so it is raced as-is rather than mapped per call.
107
+ const result = await race([
128
108
  pending.then(() => ({ kind: "sent" }), (err) => ({ kind: "error", error: error(err) })),
129
- this.#ended.then((end) => ({ kind: "ended", end })),
109
+ this.#ended,
130
110
  ]);
131
- if (result.kind === "sent")
132
- return true;
133
- if (result.kind === "error")
111
+ if (result !== null && !(result instanceof Error)) {
112
+ if (result.kind === "sent")
113
+ return true;
134
114
  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;
115
+ }
116
+ // The race leaves the blocked encode running, so reset the writable half too.
117
+ this.#writer.reset(result ?? new StreamError(StreamCode.Cancel, { message: "cancel" }));
118
+ if (result)
119
+ throw result;
139
120
  return false;
140
121
  }
122
+ /** Settles once the stream is over: `null` when it ended cleanly, or the failure. */
123
+ get ended() {
124
+ return this.#ended;
125
+ }
141
126
  #finish(end) {
142
127
  if (this.#end !== undefined)
143
128
  return;
@@ -239,12 +224,7 @@ export class Publisher {
239
224
  // presence is the gate: undefined means datagrams aren't served on this connection. All
240
225
  // subscriptions share it, since a second getWriter on the same stream would throw.
241
226
  #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.
227
+ // Originated advertisements this session forwards.
248
228
  #advertised;
249
229
  #publish;
250
230
  // TRACK_INFO is immutable per track, so resolve it from the application once
@@ -268,7 +248,6 @@ export class Publisher {
268
248
  this.version = version;
269
249
  this.hop = hop;
270
250
  const origin = publish && wireOf(publish);
271
- this.#broadcasts = origin?.broadcasts ?? new Signal(new Map());
272
251
  this.#advertised = origin?.advertised ?? new Signal(new Map());
273
252
  this.#publish = publish;
274
253
  // Grab the datagram writer up front when the transport carries datagrams (no group
@@ -298,6 +277,9 @@ export class Publisher {
298
277
  return route.hops;
299
278
  return [...route.hops, this.hop];
300
279
  };
280
+ // What the peer decodes for a route: pre-lite-06 wires carry no cost, so a re-price
281
+ // there must not restart.
282
+ const onWire = (route) => (hasRouteCost(this.version) ? route : { ...route, cost: Cost.zero });
301
283
  const announce = async (suffix, route) => {
302
284
  console.debug(`announce: broadcast=${suffix} active=true`);
303
285
  if (hasAnnounceId(this.version))
@@ -341,11 +323,13 @@ export class Publisher {
341
323
  let changed = new Promise((resolve) => {
342
324
  dispose = this.#advertised.changed(resolve);
343
325
  });
326
+ // A hidden route stays off the wire unless the request opted in.
327
+ const carries = (covered) => msg.hidden || !hiddenBelow(msg.prefix, covered);
344
328
  try {
345
329
  const initial = this.#advertised.peek();
346
330
  if (!initial)
347
331
  return; // closed
348
- for (const [name, snap] of presented(msg.prefix, initial)) {
332
+ for (const [name, snap] of presented(msg.prefix, initial, carries)) {
349
333
  active.set(name, snap);
350
334
  }
351
335
  switch (this.version) {
@@ -374,7 +358,7 @@ export class Publisher {
374
358
  }
375
359
  }
376
360
  for (;;) {
377
- const advertised = await Promise.race([changed, stream.reader.closed]);
361
+ const advertised = await race([changed, stream.reader.closed]);
378
362
  dispose();
379
363
  if (!advertised)
380
364
  break;
@@ -386,7 +370,7 @@ export class Publisher {
386
370
  if (!latest)
387
371
  break;
388
372
  const updated = new Map();
389
- for (const [name, snap] of presented(msg.prefix, latest)) {
373
+ for (const [name, snap] of presented(msg.prefix, latest, carries)) {
390
374
  updated.set(name, snap);
391
375
  }
392
376
  for (const [suffix, snap] of active) {
@@ -399,7 +383,7 @@ export class Publisher {
399
383
  if (!prev || prev.identity !== snap.identity) {
400
384
  await announce(suffix, snap.route);
401
385
  }
402
- else if (!routesEqual(prev.route, snap.route)) {
386
+ else if (!routesEqual(onWire(prev.route), onWire(snap.route))) {
403
387
  await restart(suffix, snap.route);
404
388
  }
405
389
  }
@@ -421,8 +405,8 @@ export class Publisher {
421
405
  let front;
422
406
  try {
423
407
  front =
424
- this.#broadcasts.peek()?.get(msg.broadcast) ??
425
- (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
408
+ this.#publish &&
409
+ (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
426
410
  }
427
411
  catch (err) {
428
412
  stream.writer.reset(error(err));
@@ -534,8 +518,8 @@ export class Publisher {
534
518
  let front;
535
519
  try {
536
520
  front =
537
- this.#broadcasts.peek()?.get(msg.broadcast) ??
538
- (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
521
+ this.#publish &&
522
+ (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
539
523
  }
540
524
  catch (err) {
541
525
  stream.writer.reset(error(err));
@@ -587,24 +571,38 @@ export class Publisher {
587
571
  const emitRange = supportsTrackStream(this.version);
588
572
  let startSent = false;
589
573
  let endSent = false;
574
+ // Lite-07+ counts the group streams in SUBSCRIBE_END, so it goes out only once every
575
+ // served group has opened its stream or given up, and a cap holding groups back
576
+ // delays it until they are released.
577
+ const countStreams = hasStreamCount(this.version);
578
+ let streams = 0;
579
+ const opening = new Set();
590
580
  // The track's exclusive final boundary. A Rust subscriber feeds SUBSCRIBE_END
591
581
  // straight into finish_at, so it must name the track's boundary (which counts
592
582
  // datagram sequences too), not the delivered range: a subscription cap can hold
593
583
  // produced groups back. The latest() fallback covers a subscription torn down
594
584
  // before the producer declared it.
595
585
  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).
586
+ // Before lite-07, SUBSCRIBE_END names that boundary, which a cap can hold groups back
587
+ // from, so it goes out as soon as the producer finishes and the subscription keeps
588
+ // serving whatever a later cap raise releases (see the Rust publisher's Recv::Boundary).
599
589
  const sendEnd = async () => {
600
590
  endSent = true;
601
- if (emitRange) {
602
- return controls.response(encodeSubscribeResponse(stream, { end: new SubscribeEnd(boundary()) }, this.version));
603
- }
604
- return true;
591
+ if (!emitRange)
592
+ return true;
593
+ return controls.response((async () => {
594
+ // A group that gives up before its stream opens is never counted.
595
+ if (countStreams)
596
+ while (opening.size > 0)
597
+ await Promise.all(opening);
598
+ const end = new SubscribeEnd(boundary(), streams);
599
+ await encodeSubscribeResponse(stream, { end }, this.version);
600
+ })());
605
601
  };
606
602
  // One ranking for the whole subscription, shared by every group it serves.
607
603
  const priority = new Priority(track);
604
+ // Every group this subscription started serving, until its stream finishes or resets.
605
+ const groups = new Set();
608
606
  // Cancels groups still queued for a stream slot. Only the subscriber leaving counts:
609
607
  // a track that ran out of groups still has to flush the ones already queued, and the
610
608
  // caller FINs the subscribe stream to say so.
@@ -651,26 +649,44 @@ export class Publisher {
651
649
  case "error":
652
650
  throw recv.error;
653
651
  case "idle":
652
+ // Before lite-07, an end declared ahead of the live edge goes out as
653
+ // soon as it is known, while the remaining groups are still being
654
+ // produced. The lite-07 count is not final until those groups open.
655
+ if (!endSent && !countStreams && track.final() !== undefined) {
656
+ if (!(await sendEnd()))
657
+ return;
658
+ continue;
659
+ }
654
660
  await waitForSubscription(controls, track);
655
661
  continue;
656
662
  case "boundary":
657
663
  // The producer finished but is still holding groups above the cap.
658
664
  // Declare the boundary, then wait for an update to release them.
659
- if (!endSent) {
665
+ if (!endSent && !countStreams) {
660
666
  if (!(await sendEnd()))
661
667
  return;
662
668
  continue;
663
669
  }
664
670
  await waitForSubscription(controls, track);
665
671
  continue;
666
- case "done":
672
+ case "done": {
667
673
  if (!endSent) {
668
674
  if (!(await sendEnd()))
669
675
  return;
670
676
  continue;
671
677
  }
678
+ // The FIN tells the subscriber every group is accounted for, so it waits
679
+ // until each group stream finished or reset. The subscriber leaving
680
+ // instead cancels whatever is still queued.
681
+ const drained = Symbol("drained");
682
+ const end = await Promise.race([Promise.all(groups).then(() => drained), controls.ended]);
683
+ if (end instanceof Error)
684
+ throw end;
685
+ if (end !== drained)
686
+ return;
672
687
  finished = true;
673
688
  return;
689
+ }
674
690
  }
675
691
  const group = recv.group;
676
692
  const range = frameRange(bounds, group.sequence);
@@ -686,7 +702,7 @@ export class Publisher {
686
702
  if (!(await controls.response(encodeSubscribeResponse(stream, { start: new SubscribeStart(group.sequence) }, this.version))))
687
703
  return;
688
704
  }
689
- void this.#runGroup({
705
+ const options = {
690
706
  sub,
691
707
  group,
692
708
  timescale,
@@ -694,7 +710,21 @@ export class Publisher {
694
710
  unsubscribed,
695
711
  start: range.start,
696
712
  end: range.end,
713
+ };
714
+ // `opening` settles when the stream opens so the lite-07 count can be sent.
715
+ // `groups` covers the serve too, so the FIN still waits for every stream to
716
+ // finish or reset, including one that has not opened yet.
717
+ const opened = this.#openGroup(options);
718
+ const task = opened.then(async (writer) => {
719
+ if (!writer)
720
+ return;
721
+ streams += 1;
722
+ await this.#serveGroup(writer, options);
697
723
  });
724
+ groups.add(task);
725
+ void task.finally(() => groups.delete(task));
726
+ opening.add(opened);
727
+ void opened.finally(() => opening.delete(opened));
698
728
  }
699
729
  }
700
730
  finally {
@@ -710,8 +740,8 @@ export class Publisher {
710
740
  */
711
741
  async runTrackInfo(msg, stream) {
712
742
  try {
713
- const front = this.#broadcasts.peek()?.get(msg.broadcast) ??
714
- (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
743
+ const front = this.#publish &&
744
+ (wireOf(this.#publish).local(msg.broadcast) ?? (await wireOf(this.#publish).demand(msg.broadcast)));
715
745
  if (!front)
716
746
  throw new NotFound(`broadcast ${msg.broadcast}`);
717
747
  const info = await this.#resolveTrackInfo(front, msg.track);
@@ -735,7 +765,7 @@ export class Publisher {
735
765
  this.#trackInfo.set(front, tracks);
736
766
  }
737
767
  const cached = tracks.get(track);
738
- if (cached)
768
+ if (cached !== undefined)
739
769
  return cached;
740
770
  const pending = (async () => {
741
771
  const info = await wireOf(front).resolveTrackInfo(track);
@@ -745,7 +775,7 @@ export class Publisher {
745
775
  // relays re-serve with the same window.
746
776
  maxAge: info.maxAge,
747
777
  // Lite05 mandates per-frame timestamps. Advertise the track's timescale;
748
- // `#runGroup` emits each frame converted to it.
778
+ // `#serveGroup` emits each frame converted to it.
749
779
  timescale: info.timescale,
750
780
  });
751
781
  })();
@@ -772,9 +802,9 @@ export class Publisher {
772
802
  const datagram = await track.recvDatagram();
773
803
  if (!datagram)
774
804
  return; // Track finished; #runTrack tears the subscription down.
775
- // Convert the timestamp to the track's advertised timescale, matching #runGroup.
805
+ // Convert the timestamp to the track's advertised timescale, matching #serveGroup.
776
806
  const ts = Math.round(datagram.timestamp.as(timescale));
777
- const body = new DatagramMessage(sub, datagram.sequence, ts, datagram.payload).encode();
807
+ const body = new DatagramMessage(sub, datagram.sequence, ts, datagram.payload).encode(this.version);
778
808
  // No group fallback: drop anything that doesn't fit a single datagram.
779
809
  if (body.byteLength > maxSize) {
780
810
  console.debug(`dropping oversize datagram: sub=${sub} size=${body.byteLength} max=${maxSize}`);
@@ -796,13 +826,13 @@ export class Publisher {
796
826
  // as `startFrame`. Skipping the head here is the only thing keeping those numbers
797
827
  // honest; a group that ends before we reach it can't be served at all.
798
828
  for (let i = 0; i < startFrame; i++) {
799
- if (!(await Promise.race([group.readFrame(), stream.closed]))) {
829
+ if (!(await race([group.readFrame(), stream.closed]))) {
800
830
  throw new Error(`fetch group ended at frame ${i}, before the requested start ${startFrame}`);
801
831
  }
802
832
  }
803
833
  let prevTs = 0n;
804
834
  for (let index = startFrame; endFrame === undefined || index <= endFrame; index++) {
805
- const frame = await Promise.race([group.readFrame(), stream.closed]);
835
+ const frame = await race([group.readFrame(), stream.closed]);
806
836
  if (!frame)
807
837
  break;
808
838
  const ts = BigInt(Math.round(frame.timestamp.as(timescale)));
@@ -813,15 +843,13 @@ export class Publisher {
813
843
  }
814
844
  }
815
845
  /**
816
- * Serves one group on its own unidirectional stream.
846
+ * Opens the unidirectional stream for one group, or closes the group and resolves
847
+ * `undefined` when it cannot get one.
817
848
  *
818
849
  * @internal
819
850
  */
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 });
851
+ async #openGroup(options) {
852
+ const { group, priority, unsubscribed } = options;
825
853
  try {
826
854
  // The transport drains streams by send order, so this is what makes a high-priority
827
855
  // track (and a newer group within it) win the link when there isn't room for both.
@@ -831,79 +859,92 @@ export class Publisher {
831
859
  // in the order we asked, which is oldest-first, exactly backwards for live media.
832
860
  // Failing here drops the group and lets the next one compete for the next slot.
833
861
  const stream = await Writer.tryOpen(this.#quic, {
862
+ version: this.version,
834
863
  sendOrder: priority.rank(group.sequence),
835
864
  cancel: unsubscribed,
836
865
  waitUntilAvailable: false,
837
866
  });
838
- if (!stream) {
867
+ if (!stream)
839
868
  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;
869
+ return stream;
870
+ }
871
+ catch (err) {
872
+ group.close(error(err));
873
+ return undefined;
874
+ }
875
+ }
876
+ /**
877
+ * Serves one group on the stream {@link #openGroup} opened for it.
878
+ *
879
+ * @internal
880
+ */
881
+ async #serveGroup(stream, options) {
882
+ const { sub, group, timescale, priority, start: startFrame, end: endFrame } = options;
883
+ // This model holds whole groups, so frame `startFrame` is always reachable unless
884
+ // the group ends first. Declaring it up front keeps the stream self-describing.
885
+ const msg = new GroupMessage({ subscribe: sub, sequence: group.sequence, frameStart: startFrame });
886
+ // Everything past this point runs inside the cleanup scope, so a failure never leaves
887
+ // a finished group's stream being ranked.
888
+ try {
889
+ // A SUBSCRIBE_UPDATE re-ranks the subscription, so a group already on the wire
890
+ // follows it too rather than keeping a stale rank until it finishes.
891
+ priority.add(stream, group.sequence);
892
+ await hooks.guardGroup(group, async () => {
893
+ await stream.u53(0); // stream type
894
+ await msg.encode(stream, this.version);
895
+ });
896
+ // Lite05+ prefixes every frame with a zigzag-delta timestamp at the track's
897
+ // advertised timescale; older drafts omit it.
898
+ const timestamps = supportsTrackStream(this.version);
899
+ let prevTs = 0n;
900
+ // Whether the cursor ever reached the requested start, which decides how the
901
+ // end of the group is read below.
902
+ let reached = startFrame === 0;
903
+ for (;;) {
904
+ const read = await race([hooks.readGroupFrame(group), stream.closed]);
905
+ if (!read) {
906
+ // The group ended before the frame the subscriber asked to start
907
+ // at, so this publisher can't serve the range at all. FINning here
908
+ // would claim an empty group under that index; reset so it reads
909
+ // as the gap it is.
910
+ if (!reached)
911
+ throw new Error(`group ended before frame ${startFrame}`);
912
+ break;
913
+ }
914
+ try {
915
+ // A group that ends exactly at the start is a valid, empty range.
916
+ if (read.sequence + 1 >= startFrame)
877
917
  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();
918
+ // Frames below the requested start were excluded, and the receiver
919
+ // numbers what it gets from `startFrame`.
920
+ if (read.sequence < startFrame)
921
+ continue;
922
+ if (endFrame !== undefined && read.sequence > endFrame)
923
+ break;
924
+ if (timestamps) {
925
+ // Convert each frame to the track's advertised timescale.
926
+ const ts = BigInt(Math.round(read.frame.timestamp.as(timescale)));
927
+ await hooks.guardGroup(group, () => stream.u62(zigzag(ts - prevTs)));
928
+ prevTs = ts;
889
929
  }
930
+ await hooks.guardGroup(group, () => stream.u53(read.frame.payload.byteLength));
931
+ await hooks.guardGroup(group, () => stream.write(read.frame.payload));
932
+ }
933
+ finally {
934
+ read.complete();
890
935
  }
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
936
  }
937
+ stream.close();
938
+ group.close();
902
939
  }
903
940
  catch (err) {
904
941
  const e = error(err);
942
+ stream.reset(e);
905
943
  group.close(e);
906
944
  }
945
+ finally {
946
+ priority.remove(stream);
947
+ }
907
948
  }
908
949
  /**
909
950
  * Handles a probe stream by periodically reporting estimated bitrate.
@@ -936,7 +977,7 @@ export class Publisher {
936
977
  try {
937
978
  for (;;) {
938
979
  const timeout = new Promise((resolve) => setTimeout(() => resolve("timeout"), PROBE_INTERVAL));
939
- const result = await Promise.race([timeout, stream.reader.closed]);
980
+ const result = await race([timeout, stream.reader.closed]);
940
981
  if (result !== "timeout")
941
982
  break;
942
983
  // The two fields are independent on the wire, each using 0 for