@moq/net 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/announce.d.ts +7 -0
  2. package/announce.d.ts.map +1 -0
  3. package/announce.js +8 -0
  4. package/announce.js.map +1 -0
  5. package/announced.d.ts +35 -91
  6. package/announced.d.ts.map +1 -1
  7. package/announced.js +21 -156
  8. package/announced.js.map +1 -1
  9. package/bandwidth.d.ts +163 -0
  10. package/bandwidth.d.ts.map +1 -0
  11. package/bandwidth.js +304 -0
  12. package/bandwidth.js.map +1 -0
  13. package/bandwidth_api.d.ts +7 -0
  14. package/bandwidth_api.d.ts.map +1 -0
  15. package/bandwidth_api.js +8 -0
  16. package/bandwidth_api.js.map +1 -0
  17. package/broadcast.d.ts +20 -28
  18. package/broadcast.d.ts.map +1 -1
  19. package/broadcast.js +55 -38
  20. package/broadcast.js.map +1 -1
  21. package/connection/accept.d.ts +16 -1
  22. package/connection/accept.d.ts.map +1 -1
  23. package/connection/accept.js +39 -24
  24. package/connection/accept.js.map +1 -1
  25. package/connection/browser.d.ts.map +1 -1
  26. package/connection/browser.js +9 -7
  27. package/connection/browser.js.map +1 -1
  28. package/connection/connect.d.ts +30 -6
  29. package/connection/connect.d.ts.map +1 -1
  30. package/connection/connect.js +85 -45
  31. package/connection/connect.js.map +1 -1
  32. package/connection/established.d.ts +16 -21
  33. package/connection/established.d.ts.map +1 -1
  34. package/connection/established.js.map +1 -1
  35. package/connection/forward.d.ts +2 -0
  36. package/connection/forward.d.ts.map +1 -0
  37. package/connection/forward.js +159 -0
  38. package/connection/forward.js.map +1 -0
  39. package/connection/handshake.d.ts.map +1 -1
  40. package/connection/handshake.js +2 -2
  41. package/connection/handshake.js.map +1 -1
  42. package/connection/index.d.ts +5 -5
  43. package/connection/index.d.ts.map +1 -1
  44. package/connection/index.js +4 -5
  45. package/connection/index.js.map +1 -1
  46. package/connection/pool.d.ts +188 -0
  47. package/connection/pool.d.ts.map +1 -0
  48. package/connection/pool.js +351 -0
  49. package/connection/pool.js.map +1 -0
  50. package/connection/reload.d.ts +14 -93
  51. package/connection/reload.d.ts.map +1 -1
  52. package/connection/reload.js +216 -80
  53. package/connection/reload.js.map +1 -1
  54. package/connection/stats.d.ts +3 -26
  55. package/connection/stats.d.ts.map +1 -1
  56. package/connection/stats.js.map +1 -1
  57. package/connection/transport.d.ts +0 -7
  58. package/connection/transport.d.ts.map +1 -1
  59. package/consume.d.ts +1 -43
  60. package/consume.d.ts.map +1 -1
  61. package/consume.js +1 -1
  62. package/consume.js.map +1 -1
  63. package/error.d.ts +180 -29
  64. package/error.d.ts.map +1 -1
  65. package/error.js +310 -16
  66. package/error.js.map +1 -1
  67. package/errors.d.ts +7 -0
  68. package/errors.d.ts.map +1 -0
  69. package/errors.js +8 -0
  70. package/errors.js.map +1 -0
  71. package/group.d.ts +9 -43
  72. package/group.d.ts.map +1 -1
  73. package/group.js +283 -69
  74. package/group.js.map +1 -1
  75. package/hop.d.ts +107 -0
  76. package/hop.d.ts.map +1 -0
  77. package/hop.js +103 -0
  78. package/hop.js.map +1 -0
  79. package/ietf/aliases.d.ts +1 -78
  80. package/ietf/aliases.d.ts.map +1 -1
  81. package/ietf/cluster.d.ts +6 -120
  82. package/ietf/cluster.d.ts.map +1 -1
  83. package/ietf/cluster.js +81 -41
  84. package/ietf/cluster.js.map +1 -1
  85. package/ietf/connection.d.ts +6 -72
  86. package/ietf/connection.d.ts.map +1 -1
  87. package/ietf/connection.js +11 -47
  88. package/ietf/connection.js.map +1 -1
  89. package/ietf/error.d.ts +11 -0
  90. package/ietf/error.d.ts.map +1 -0
  91. package/ietf/error.js +168 -0
  92. package/ietf/error.js.map +1 -0
  93. package/ietf/filter.d.ts.map +1 -1
  94. package/ietf/filter.js +6 -1
  95. package/ietf/filter.js.map +1 -1
  96. package/ietf/goaway.d.ts.map +1 -1
  97. package/ietf/goaway.js +22 -5
  98. package/ietf/goaway.js.map +1 -1
  99. package/ietf/parameters.d.ts +2 -2
  100. package/ietf/parameters.d.ts.map +1 -1
  101. package/ietf/parameters.js +15 -17
  102. package/ietf/parameters.js.map +1 -1
  103. package/ietf/publish_namespace.d.ts +25 -0
  104. package/ietf/publish_namespace.d.ts.map +1 -1
  105. package/ietf/publish_namespace.js +63 -0
  106. package/ietf/publish_namespace.js.map +1 -1
  107. package/ietf/publisher.d.ts +1 -82
  108. package/ietf/publisher.d.ts.map +1 -1
  109. package/ietf/publisher.js +203 -136
  110. package/ietf/publisher.js.map +1 -1
  111. package/ietf/solicit.d.ts +1 -40
  112. package/ietf/solicit.d.ts.map +1 -1
  113. package/ietf/subscribe.d.ts +1 -5
  114. package/ietf/subscribe.d.ts.map +1 -1
  115. package/ietf/subscribe.js +8 -9
  116. package/ietf/subscribe.js.map +1 -1
  117. package/ietf/subscriber.d.ts +1 -65
  118. package/ietf/subscriber.d.ts.map +1 -1
  119. package/ietf/subscriber.js +154 -73
  120. package/ietf/subscriber.js.map +1 -1
  121. package/ietf/version.d.ts +12 -1
  122. package/ietf/version.d.ts.map +1 -1
  123. package/ietf/version.js +13 -0
  124. package/ietf/version.js.map +1 -1
  125. package/index.d.ts +11 -6
  126. package/index.d.ts.map +1 -1
  127. package/index.js +10 -5
  128. package/index.js.map +1 -1
  129. package/internal.d.ts +97 -1
  130. package/internal.d.ts.map +1 -1
  131. package/internal.js +65 -0
  132. package/internal.js.map +1 -1
  133. package/lite/announce.d.ts +15 -9
  134. package/lite/announce.d.ts.map +1 -1
  135. package/lite/announce.js +47 -20
  136. package/lite/announce.js.map +1 -1
  137. package/lite/connection.d.ts +9 -59
  138. package/lite/connection.d.ts.map +1 -1
  139. package/lite/connection.js +20 -32
  140. package/lite/connection.js.map +1 -1
  141. package/lite/fetch.d.ts +15 -1
  142. package/lite/fetch.d.ts.map +1 -1
  143. package/lite/fetch.js +39 -7
  144. package/lite/fetch.js.map +1 -1
  145. package/lite/goaway.d.ts.map +1 -1
  146. package/lite/goaway.js +7 -1
  147. package/lite/goaway.js.map +1 -1
  148. package/lite/group.d.ts +18 -4
  149. package/lite/group.d.ts.map +1 -1
  150. package/lite/group.js +31 -10
  151. package/lite/group.js.map +1 -1
  152. package/lite/priority.d.ts +1 -61
  153. package/lite/priority.d.ts.map +1 -1
  154. package/lite/priority.js +4 -5
  155. package/lite/priority.js.map +1 -1
  156. package/lite/publisher.d.ts +1 -69
  157. package/lite/publisher.d.ts.map +1 -1
  158. package/lite/publisher.js +507 -200
  159. package/lite/publisher.js.map +1 -1
  160. package/lite/setup.d.ts +7 -7
  161. package/lite/setup.d.ts.map +1 -1
  162. package/lite/setup.js +13 -13
  163. package/lite/setup.js.map +1 -1
  164. package/lite/subscribe.d.ts +61 -13
  165. package/lite/subscribe.d.ts.map +1 -1
  166. package/lite/subscribe.js +186 -44
  167. package/lite/subscribe.js.map +1 -1
  168. package/lite/subscriber.d.ts +8 -57
  169. package/lite/subscriber.d.ts.map +1 -1
  170. package/lite/subscriber.js +179 -117
  171. package/lite/subscriber.js.map +1 -1
  172. package/lite/track.d.ts +4 -10
  173. package/lite/track.d.ts.map +1 -1
  174. package/lite/track.js +34 -29
  175. package/lite/track.js.map +1 -1
  176. package/lite/version.d.ts +31 -6
  177. package/lite/version.d.ts.map +1 -1
  178. package/lite/version.js +71 -11
  179. package/lite/version.js.map +1 -1
  180. package/origin.d.ts +229 -29
  181. package/origin.d.ts.map +1 -1
  182. package/origin.js +1087 -37
  183. package/origin.js.map +1 -1
  184. package/package.json +3 -2
  185. package/path.d.ts +25 -7
  186. package/path.d.ts.map +1 -1
  187. package/path.js +5 -3
  188. package/path.js.map +1 -1
  189. package/stream.d.ts.map +1 -1
  190. package/stream.js +23 -14
  191. package/stream.js.map +1 -1
  192. package/time.d.ts +15 -2
  193. package/time.d.ts.map +1 -1
  194. package/time.js +28 -9
  195. package/time.js.map +1 -1
  196. package/track.d.ts +166 -83
  197. package/track.d.ts.map +1 -1
  198. package/track.js +617 -187
  199. package/track.js.map +1 -1
  200. package/wire.d.ts +67 -0
  201. package/wire.d.ts.map +1 -0
  202. package/wire.js +32 -0
  203. package/wire.js.map +1 -0
  204. package/zod.d.ts +1 -1
  205. package/zod.d.ts.map +1 -1
  206. package/zod.js.map +1 -1
  207. package/mock.d.ts +0 -66
  208. package/mock.d.ts.map +0 -1
  209. package/mock.js +0 -243
  210. package/mock.js.map +0 -1
package/lite/publisher.js CHANGED
@@ -1,18 +1,41 @@
1
1
  /* @ts-self-types="./publisher.d.ts" */
2
2
  import { Signal } from "@moq/signals";
3
- import { error, reason } from "../error.js";
3
+ import { error, NotFound, reason, StreamCode, StreamError } from "../error.js";
4
+ import { routesEqual } from "../hop.js";
5
+ import { hooks } from "../internal.js";
4
6
  import * as Path from "../path.js";
5
7
  import { Writer } from "../stream.js";
6
- import { Timescale } from "../time.js";
8
+ import { Milli, Timescale } from "../time.js";
9
+ import { wireOf } from "../wire.js";
7
10
  import { AnnounceInit, AnnounceOk, encodeAnnounceBroadcast } from "./announce.js";
8
11
  import { Datagram as DatagramMessage } from "./datagram.js";
9
12
  import * as DatagramStream from "./datagram_stream.js";
10
13
  import { Group as GroupMessage } from "./group.js";
11
14
  import { Priority, sendOrder } from "./priority.js";
12
15
  import { Probe } from "./probe.js";
13
- import { encodeSubscribeResponse, SubscribeEnd, SubscribeOk, SubscribeStart, SubscribeUpdate, } from "./subscribe.js";
16
+ import { encodeSubscribeResponse, exclusiveGroupEnd, SubscribeEnd, SubscribeOk, SubscribeStart, SubscribeUpdate, } from "./subscribe.js";
14
17
  import { TrackInfo as TrackInfoMessage } from "./track.js";
15
- import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, Version } from "./version.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
+ }
16
39
  const PROBE_INTERVAL = 100; // ms
17
40
  const PROBE_MAX_AGE = 10_000; // ms
18
41
  const PROBE_MAX_DELTA = 0.25;
@@ -34,6 +57,169 @@ function supportsTrackStream(version) {
34
57
  return true;
35
58
  }
36
59
  }
60
+ /**
61
+ * The frames of `sequence` a subscription asked for, as a start index and an inclusive end.
62
+ *
63
+ * The frame bounds qualify the start and end group only; every other group is served whole.
64
+ * Which groups are served at all is the subscriber's read cursor (`replaceGroups`),
65
+ * applied when a group is popped rather than re-checked here.
66
+ *
67
+ * The serving loop calls this synchronously after the pop, before any SUBSCRIBE_UPDATE can
68
+ * change `bounds`. Nothing downstream trims the frame range: it is a wire request,
69
+ * deliberately decoupled from the receiver's local read cursor.
70
+ */
71
+ function frameRange(bounds, sequence) {
72
+ return {
73
+ start: bounds.startGroup === sequence ? bounds.startFrame : 0,
74
+ end: bounds.endGroup === sequence ? bounds.endFrame : undefined,
75
+ };
76
+ }
77
+ /**
78
+ * The subscribe stream's control half, decoded ahead of the serving loop.
79
+ *
80
+ * Decoding runs on its own and publishes each full subscription update immediately, so a
81
+ * blocked response write cannot delay re-ranking streams already in flight. It separately
82
+ * stores only the latest range state for the serving loop, which owns the local track cursor
83
+ * and frame bounds. That keeps a group pop and its frame-range snapshot one indivisible step.
84
+ *
85
+ * Reading ahead makes control-first ordering hold for a burst. Coalescing bounds memory while
86
+ * preserving the newest state decoded before the next group pop. The Rust publisher gets the
87
+ * same ordering from `poll_decode_maybe`, which decodes straight out of the reader's buffer;
88
+ * nothing here can decode synchronously, so it reads ahead instead.
89
+ */
90
+ class SubscriptionControls {
91
+ #writer;
92
+ #update;
93
+ // Sticky, first one wins: null once the stream is over, an Error once it failed.
94
+ #end;
95
+ #ended;
96
+ #resolveEnd;
97
+ #changed = new Signal(0);
98
+ /** Settles once decoding stops, so teardown can wait for it rather than leaving it running. */
99
+ decoding;
100
+ constructor({ reader, writer, version, apply }) {
101
+ this.#writer = writer;
102
+ this.#ended = new Promise((resolve) => {
103
+ this.#resolveEnd = resolve;
104
+ });
105
+ this.decoding = this.#decode(reader, version, apply);
106
+ // Our own half going away ends the loop too, and has to reach it the same way: the
107
+ // loop looks at nothing else.
108
+ void writer.closed.then(() => this.#finish(null), (err) => this.#finish(error(err)));
109
+ }
110
+ /** The next control to apply, or undefined while the peer is quiet. */
111
+ take() {
112
+ const update = this.#update;
113
+ this.#update = undefined;
114
+ // An update decoded before the stream ended still applies before the sticky end.
115
+ if (update)
116
+ return { kind: "update", update };
117
+ if (this.#end === undefined)
118
+ return undefined;
119
+ return this.#end === null ? { kind: "done" } : { kind: "error", error: this.#end };
120
+ }
121
+ /** Calls `fn` once {@link take} may answer differently. */
122
+ changed(fn) {
123
+ return this.#changed.changed(fn);
124
+ }
125
+ /** Returns false when peer departure supersedes a blocked response write. */
126
+ async response(pending) {
127
+ const result = await Promise.race([
128
+ pending.then(() => ({ kind: "sent" }), (err) => ({ kind: "error", error: error(err) })),
129
+ this.#ended.then((end) => ({ kind: "ended", end })),
130
+ ]);
131
+ if (result.kind === "sent")
132
+ return true;
133
+ if (result.kind === "error")
134
+ 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
+ return false;
140
+ }
141
+ #finish(end) {
142
+ if (this.#end !== undefined)
143
+ return;
144
+ this.#end = end;
145
+ this.#resolveEnd(end);
146
+ this.#changed.update((value) => value + 1);
147
+ }
148
+ async #decode(reader, version, apply) {
149
+ try {
150
+ while (this.#end === undefined) {
151
+ const update = await SubscribeUpdate.decodeMaybe(reader, version);
152
+ if (!update)
153
+ break;
154
+ apply(update);
155
+ this.#update = update;
156
+ this.#changed.update((value) => value + 1);
157
+ }
158
+ }
159
+ catch (err) {
160
+ this.#finish(error(err));
161
+ return;
162
+ }
163
+ this.#finish(null);
164
+ }
165
+ }
166
+ // A microtask is too short: decoding one framed update crosses several awaits, each of which
167
+ // can requeue behind the serving continuation. A task boundary lets the decoder finish whatever
168
+ // the transport already delivered before the next group pop. Updates are rare, so groups do not
169
+ // pay this scheduling cost on the normal path.
170
+ const yieldToControls = () => new Promise((resolve) => setTimeout(resolve, 0));
171
+ // Register both readiness sources in the same turn after the caller observed neither ready.
172
+ // The winner disposes both registrations, so an idle subscription accumulates nothing no
173
+ // matter how many times it wakes.
174
+ function waitForSubscription(controls, subscriber) {
175
+ return new Promise((resolve) => {
176
+ let settled = false;
177
+ const dispose = [];
178
+ const wake = () => {
179
+ if (settled)
180
+ return;
181
+ settled = true;
182
+ for (const close of dispose)
183
+ close();
184
+ resolve();
185
+ };
186
+ dispose.push(controls.changed(wake), hooks.groupChanged(subscriber, wake));
187
+ });
188
+ }
189
+ /**
190
+ * The budget to serve a peer with, given what its wire could tell us.
191
+ *
192
+ * A version without the field decodes as `0`, which is indistinguishable from a peer
193
+ * genuinely asking for the live edge. Serving that as real time would discard backlog
194
+ * a legacy subscriber never declined, so fall back to a window wide enough not to drop
195
+ * and leave enforcement to the receiver, as the IETF path does for the same reason.
196
+ */
197
+ function servingMaxAge(version, requested) {
198
+ return carriesMaxAge(version) ? (requested ?? 0) : Number.MAX_SAFE_INTEGER;
199
+ }
200
+ /** Whether this version's SUBSCRIBE carries Subscriber Max Age at all. */
201
+ function carriesMaxAge(version) {
202
+ return version !== Version.DRAFT_01 && version !== Version.DRAFT_02;
203
+ }
204
+ /**
205
+ * Position a subscription's read cursor for the wire serving it.
206
+ *
207
+ * On lite-06 there is nothing to do: the cursor is floored at the group the subscription
208
+ * named (or 0), and its Max Age decides what above the floor is worth delivering.
209
+ *
210
+ * Pre-06 wires are the exception: their drafts define an absent `Group Start` as the
211
+ * latest group, so say so explicitly rather than letting the budget reach back. Lite-03/04/05
212
+ * carry a Max Age, but there it is a staleness tolerance only; lite-01/02 additionally get
213
+ * an unbounded budget so nothing is dropped under them (see {@link servingMaxAge}), which
214
+ * must not read as a request to replay the whole cache on join.
215
+ */
216
+ function positionCursor(track, version, startGroup) {
217
+ if (resolvesStart(version) || startGroup !== undefined)
218
+ return;
219
+ const latest = track.latest();
220
+ if (latest !== undefined)
221
+ hooks.replaceGroups(track, { start: { included: latest } });
222
+ }
37
223
  /**
38
224
  * Handles publishing broadcasts and managing their lifecycle.
39
225
  *
@@ -46,58 +232,51 @@ export class Publisher {
46
232
  // can detect loops and prefer shorter paths. Created by Connection and
47
233
  // shared with Subscriber, which can optionally use it to filter out its
48
234
  // own announcements.
49
- origin;
235
+ hop;
50
236
  #quic;
51
237
  // The one writer for the outbound datagram stream (getWriter locks it), acquired once at
52
238
  // construction when this version + transport carry datagrams, released in close(). Its
53
239
  // presence is the gate: undefined means datagrams aren't served on this connection. All
54
240
  // subscriptions share it, since a second getWriter on the same stream would throw.
55
241
  #datagramWriter;
56
- // Our published broadcasts.
57
- // It's a signal so we can live update any announce streams.
58
- #broadcasts = new Signal(new Map());
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.
248
+ #advertised;
249
+ #publish;
59
250
  // TRACK_INFO is immutable per track, so resolve it from the application once
60
251
  // (via a throwaway subscribe whose info() resolves when the app calls accept)
61
- // and reuse it for every later TRACK request of the same track. Keyed by
62
- // `broadcast\0track`. A rejected lookup is evicted so a retry can re-probe.
63
- #trackInfo = new Map();
252
+ // and reuse it for every later TRACK request of the same track. Keyed by the
253
+ // routing front rather than the path: immutability holds for one broadcast, and a
254
+ // republish puts a different one on the path, so its entries must not be reused.
255
+ // A rejected lookup is evicted so a retry can re-probe.
256
+ #trackInfo = new WeakMap();
64
257
  /**
65
258
  * Creates a new Publisher instance.
66
259
  * @param quic - The WebTransport session to use
67
260
  * @param version - Negotiated protocol version
68
- * @param origin - Origin id shared with the Subscriber
261
+ * @param origin - Hop id shared with the Subscriber
262
+ * @param publish - The origin whose broadcasts this session serves; omit to publish nothing
69
263
  *
70
264
  * @internal
71
265
  */
72
- constructor(quic, version, origin) {
266
+ constructor(quic, version, hop, publish) {
73
267
  this.#quic = quic;
74
268
  this.version = version;
75
- this.origin = origin;
269
+ this.hop = hop;
270
+ const origin = publish && wireOf(publish);
271
+ this.#broadcasts = origin?.broadcasts ?? new Signal(new Map());
272
+ this.#advertised = origin?.advertised ?? new Signal(new Map());
273
+ this.#publish = publish;
76
274
  // Grab the datagram writer up front when the transport carries datagrams (no group
77
275
  // fallback, so it stays undefined otherwise). One writer for all subscriptions.
78
276
  if (hasDatagrams(version)) {
79
277
  this.#datagramWriter = DatagramStream.datagramWriter(quic);
80
278
  }
81
279
  }
82
- /**
83
- * Publishes a broadcast with any associated tracks.
84
- * @param name - The broadcast to publish
85
- */
86
- publish(path, broadcast) {
87
- this.#broadcasts.mutate((broadcasts) => {
88
- if (!broadcasts)
89
- throw new Error("closed");
90
- broadcasts.set(path, broadcast);
91
- });
92
- // Remove the broadcast from the lookup when it's closed, unless the path was republished.
93
- void broadcast.closed.then(() => {
94
- this.#broadcasts.mutate((broadcasts) => {
95
- if (broadcasts?.get(path) === broadcast) {
96
- broadcasts.delete(path);
97
- }
98
- });
99
- });
100
- }
101
280
  /**
102
281
  * Handles an announce interest message.
103
282
  * @param msg - The announce interest message
@@ -107,20 +286,40 @@ export class Publisher {
107
286
  */
108
287
  async runAnnounce(msg, stream) {
109
288
  console.debug(`announce: prefix=${msg.prefix}`);
110
- // Which producer holds each announced suffix. Keyed on the producer rather than the path
111
- // alone, so a path handed to a new producer is retracted and re-announced instead of
112
- // diffing away to nothing and leaving the subscriber on the dead generation.
289
+ // Keyed by suffix, valued by identity plus route, so a republish diffs as
290
+ // ended-then-active and a re-price as a restart.
113
291
  let active = new Map();
114
292
  // Lite06+: announce ids. Every active we send implicitly assigns the next
115
- // per-stream ordinal; ended references the id instead of repeating the path.
293
+ // per-stream ordinal; ended/restart reference the id instead of repeating the path.
116
294
  let nextAnnounceId = 0n;
117
295
  const announceIds = new Map();
118
- const announce = async (suffix, hops) => {
296
+ const wireHops = (route) => {
297
+ if (hasAnnounceOk(this.version))
298
+ return route.hops;
299
+ return [...route.hops, this.hop];
300
+ };
301
+ const announce = async (suffix, route) => {
119
302
  console.debug(`announce: broadcast=${suffix} active=true`);
120
303
  if (hasAnnounceId(this.version))
121
304
  announceIds.set(suffix, nextAnnounceId++);
122
- await encodeAnnounceBroadcast(stream.writer, { status: "active", suffix, hops }, this.version);
305
+ await encodeAnnounceBroadcast(stream.writer, { status: "active", suffix, hops: wireHops(route), cost: route.cost }, this.version);
123
306
  };
307
+ const restart = async (suffix, route) => {
308
+ if (!hasAnnounceId(this.version)) {
309
+ await retract(suffix);
310
+ await announce(suffix, route);
311
+ return;
312
+ }
313
+ const id = announceIds.get(suffix);
314
+ if (id === undefined) {
315
+ await announce(suffix, route);
316
+ return;
317
+ }
318
+ console.debug(`announce: broadcast=${suffix} restart=true`);
319
+ await encodeAnnounceBroadcast(stream.writer, { status: "restart", id, hops: wireHops(route), cost: route.cost }, this.version);
320
+ };
321
+ // Lite06+ retracts by announce id; older versions repeat the path (ended announces
322
+ // don't need hops).
124
323
  const retract = async (suffix) => {
125
324
  console.debug(`announce: broadcast=${suffix} active=false`);
126
325
  if (!hasAnnounceId(this.version)) {
@@ -140,17 +339,14 @@ export class Publisher {
140
339
  // TODO Make a better helper within Signals.
141
340
  let dispose;
142
341
  let changed = new Promise((resolve) => {
143
- dispose = this.#broadcasts.changed(resolve);
342
+ dispose = this.#advertised.changed(resolve);
144
343
  });
145
344
  try {
146
- const initial = this.#broadcasts.peek();
345
+ const initial = this.#advertised.peek();
147
346
  if (!initial)
148
347
  return; // closed
149
- for (const [name, producer] of initial) {
150
- const suffix = Path.stripPrefix(msg.prefix, name);
151
- if (suffix === null)
152
- continue;
153
- active.set(suffix, producer);
348
+ for (const [name, snap] of presented(msg.prefix, initial)) {
349
+ active.set(name, snap);
154
350
  }
155
351
  switch (this.version) {
156
352
  case Version.DRAFT_01:
@@ -164,56 +360,48 @@ export class Publisher {
164
360
  }
165
361
  default: {
166
362
  if (!hasAnnounceOk(this.version)) {
167
- // Draft03/04: send individual Announce messages, stamping our origin as a hop.
168
- for (const suffix of active.keys()) {
169
- await announce(suffix, [this.origin]);
363
+ for (const [suffix, snap] of active) {
364
+ await announce(suffix, snap.route);
170
365
  }
171
366
  break;
172
367
  }
173
- // Report our origin id once via AnnounceOk and the count of initial announces
174
- // that follow; the subscriber stamps our origin onto each hop chain, so we omit it.
175
- const ok = new AnnounceOk(this.origin, active.size);
368
+ const ok = new AnnounceOk(this.hop, active.size);
176
369
  await ok.encode(stream.writer, this.version);
177
- for (const suffix of active.keys()) {
178
- await announce(suffix, []);
370
+ for (const [suffix, snap] of active) {
371
+ await announce(suffix, snap.route);
179
372
  }
180
373
  break;
181
374
  }
182
375
  }
183
- // Wait for updates to the broadcasts.
184
376
  for (;;) {
185
- // Wait until the map of broadcasts changes.
186
- const broadcasts = await Promise.race([changed, stream.reader.closed]);
377
+ const advertised = await Promise.race([changed, stream.reader.closed]);
187
378
  dispose();
188
- if (!broadcasts)
379
+ if (!advertised)
189
380
  break;
190
- // Re-arm before writing, for the same reason as above.
381
+ // Re-arm before reading, so an advertise that lands while we write is not lost.
191
382
  changed = new Promise((resolve) => {
192
- dispose = this.#broadcasts.changed(resolve);
383
+ dispose = this.#advertised.changed(resolve);
193
384
  });
194
- // Rebuild who holds what.
195
- // This is SLOW, but it's not worth optimizing because we often have just 1 broadcast anyway.
385
+ const latest = this.#advertised.peek();
386
+ if (!latest)
387
+ break;
196
388
  const updated = new Map();
197
- for (const [name, producer] of broadcasts) {
198
- const suffix = Path.stripPrefix(msg.prefix, name);
199
- if (suffix === null)
200
- continue; // Not our prefix.
201
- updated.set(suffix, producer);
389
+ for (const [name, snap] of presented(msg.prefix, latest)) {
390
+ updated.set(name, snap);
202
391
  }
203
- // Retract first, so a replacement reads as an end followed by a start.
204
- for (const [suffix, producer] of active) {
205
- if (updated.get(suffix) === producer)
206
- continue;
207
- await retract(suffix);
392
+ for (const [suffix, snap] of active) {
393
+ const cur = updated.get(suffix);
394
+ if (!cur || cur.identity !== snap.identity)
395
+ await retract(suffix);
208
396
  }
209
- // Announce anything new, including a path a different producer now holds. Lite05+
210
- // reports our origin once via AnnounceOk, so the subscriber stamps it onto each hop
211
- // chain; older versions stamp it here.
212
- const hops = hasAnnounceOk(this.version) ? [] : [this.origin];
213
- for (const [suffix, producer] of updated) {
214
- if (active.get(suffix) === producer)
215
- continue;
216
- await announce(suffix, hops);
397
+ for (const [suffix, snap] of updated) {
398
+ const prev = active.get(suffix);
399
+ if (!prev || prev.identity !== snap.identity) {
400
+ await announce(suffix, snap.route);
401
+ }
402
+ else if (!routesEqual(prev.route, snap.route)) {
403
+ await restart(suffix, snap.route);
404
+ }
217
405
  }
218
406
  active = updated;
219
407
  }
@@ -230,27 +418,37 @@ export class Publisher {
230
418
  * @internal
231
419
  */
232
420
  async runSubscribe(msg, stream) {
233
- const broadcast = this.#broadcasts.peek()?.get(msg.broadcast);
234
- if (!broadcast) {
421
+ let front;
422
+ try {
423
+ front =
424
+ this.#broadcasts.peek()?.get(msg.broadcast) ??
425
+ (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
426
+ }
427
+ catch (err) {
428
+ stream.writer.reset(error(err));
429
+ return;
430
+ }
431
+ if (!front) {
235
432
  console.debug(`publish unknown: broadcast=${msg.broadcast}`);
236
- stream.writer.reset(new Error("not found"));
433
+ stream.writer.reset(new NotFound(`broadcast ${msg.broadcast}`));
237
434
  return;
238
435
  }
239
- const track = broadcast.subscribe(msg.track, {
436
+ const endGroup = exclusiveGroupEnd(msg.endGroup);
437
+ const track = wireOf(front).subscribe(msg.track, {
240
438
  priority: msg.priority,
241
- ordered: msg.ordered,
242
- latencyMax: msg.maxLatency,
243
- startGroup: msg.startGroup,
244
- endGroup: msg.endGroup,
439
+ maxAge: Milli(servingMaxAge(this.version, msg.maxAge)),
440
+ groups: {
441
+ start: msg.startGroup === undefined ? undefined : { included: msg.startGroup },
442
+ end: endGroup === undefined ? undefined : { excluded: endGroup },
443
+ },
245
444
  });
246
- const startGroup = msg.startGroup ?? track.latest();
247
- if (startGroup !== undefined)
248
- track.startAt(startGroup);
249
- track.endAt(msg.endGroup);
445
+ positionCursor(track, this.version, msg.startGroup);
446
+ hooks.replaceGroups(track, { end: endGroup === undefined ? undefined : { excluded: endGroup } });
250
447
  // The best-effort datagram loop, started once serving begins. It parks when the
251
448
  // track finishes (recvDatagram returns undefined), so #runTrack alone ends the
252
449
  // subscription; awaited during teardown so it doesn't outlive the subscription.
253
450
  let datagrams = Promise.resolve();
451
+ let controls;
254
452
  try {
255
453
  let timescale = Timescale.MILLI;
256
454
  if (supportsTrackStream(this.version)) {
@@ -270,51 +468,57 @@ export class Publisher {
270
468
  // Older drafts acknowledge with SUBSCRIBE_OK and stream frames verbatim.
271
469
  const ok = new SubscribeOk({
272
470
  priority: msg.priority,
273
- ordered: msg.ordered,
274
- maxLatency: msg.maxLatency,
471
+ maxAge: msg.maxAge,
275
472
  startGroup: msg.startGroup,
276
473
  endGroup: msg.endGroup,
277
474
  });
278
475
  await encodeSubscribeResponse(stream.writer, { ok }, this.version);
279
476
  }
280
477
  console.debug(`publish ok: broadcast=${msg.broadcast} track=${track.name}`);
281
- const serving = this.#runTrack(msg.id, msg.broadcast, track, stream.writer, timescale);
282
478
  // Serve datagrams concurrently with groups whenever the transport carries them
283
479
  // (the writer exists iff so). No group fallback: otherwise they simply aren't sent.
284
480
  if (this.#datagramWriter) {
285
481
  datagrams = this.#runDatagrams(msg.id, track, timescale);
286
482
  }
287
- for (;;) {
288
- const decode = SubscribeUpdate.decodeMaybe(stream.reader, this.version);
289
- const result = await Promise.any([serving, decode]);
290
- if (!result)
291
- break;
292
- if (result instanceof SubscribeUpdate) {
293
- console.debug(`subscribe update: broadcast=${msg.broadcast} track=${track.name}`);
483
+ controls = new SubscriptionControls({
484
+ reader: stream.reader,
485
+ writer: stream.writer,
486
+ version: this.version,
487
+ apply: (update) => {
488
+ const end = exclusiveGroupEnd(update.endGroup);
294
489
  track.update({
295
- priority: result.priority,
296
- ordered: result.ordered,
297
- latencyMax: result.maxLatency,
298
- startGroup: result.startGroup,
299
- endGroup: result.endGroup,
490
+ priority: update.priority,
491
+ maxAge: Milli(servingMaxAge(this.version, update.maxAge)),
492
+ groups: {
493
+ start: update.startGroup === undefined ? undefined : { included: update.startGroup },
494
+ end: end === undefined ? undefined : { excluded: end },
495
+ },
300
496
  });
301
- if (result.startGroup !== undefined)
302
- track.startAt(result.startGroup);
303
- track.endAt(result.endGroup);
304
- }
305
- }
497
+ },
498
+ });
499
+ await this.#runTrack(track, stream.writer, controls, {
500
+ sub: msg.id,
501
+ broadcast: msg.broadcast,
502
+ timescale,
503
+ bounds: {
504
+ startGroup: msg.startGroup,
505
+ startFrame: msg.startFrame,
506
+ endGroup: msg.endGroup,
507
+ endFrame: msg.endFrame,
508
+ },
509
+ });
306
510
  console.debug(`publish done: broadcast=${msg.broadcast} track=${track.name}`);
307
511
  stream.close();
308
512
  track.close();
309
- // track.close ends the datagram loop; wait so it doesn't leak past teardown.
310
- await datagrams;
513
+ // Closing the stream ends the decoder and track.close ends the datagram loop.
514
+ await Promise.all([datagrams, controls.decoding]);
311
515
  }
312
516
  catch (err) {
313
517
  const e = error(err);
314
518
  console.warn(`publish error: broadcast=${msg.broadcast} track=${track.name} error=${reason(e)}`);
315
519
  track.close(e);
316
520
  stream.abort(e);
317
- await datagrams;
521
+ await Promise.all([datagrams, controls?.decoding]);
318
522
  }
319
523
  }
320
524
  /**
@@ -327,10 +531,19 @@ export class Publisher {
327
531
  stream.writer.reset(new Error("fetch requires moq-lite-05 or newer"));
328
532
  return;
329
533
  }
330
- const broadcast = this.#broadcasts.peek()?.get(msg.broadcast);
331
- if (!broadcast) {
534
+ let front;
535
+ try {
536
+ front =
537
+ this.#broadcasts.peek()?.get(msg.broadcast) ??
538
+ (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
539
+ }
540
+ catch (err) {
541
+ stream.writer.reset(error(err));
542
+ return;
543
+ }
544
+ if (!front) {
332
545
  console.debug(`fetch unknown: broadcast=${msg.broadcast}`);
333
- stream.writer.reset(new Error("not found"));
546
+ stream.writer.reset(new NotFound(`broadcast ${msg.broadcast}`));
334
547
  return;
335
548
  }
336
549
  // The subscriber opened this stream, so its send order only ranked the request. Rank the
@@ -338,10 +551,15 @@ export class Publisher {
338
551
  stream.writer.setPriority(sendOrder({ priority: msg.priority }));
339
552
  let group;
340
553
  try {
341
- // The timescale is immutable, so serve exactly what TRACK_INFO advertised.
342
- const info = await this.#resolveTrackInfo(msg.broadcast, msg.track);
343
- group = await broadcast.track(msg.track).fetchGroup(msg.group, { priority: msg.priority });
344
- await this.#runFetchGroup(group, stream.writer, Timescale(info.timescale));
554
+ // The timescale is immutable, so serve exactly what TRACK_INFO advertised. Both
555
+ // come off the same front, so the metadata and the frames are one generation.
556
+ const info = await this.#resolveTrackInfo(front, msg.track);
557
+ group = await wireOf(front).fetchGroup(msg.track, msg.group, { priority: msg.priority });
558
+ await this.#runFetchGroup(group, stream.writer, {
559
+ timescale: Timescale(info.timescale),
560
+ start: msg.startFrame,
561
+ end: msg.endFrame,
562
+ });
345
563
  console.debug(`fetch done: broadcast=${msg.broadcast} track=${msg.track} group=${msg.group}`);
346
564
  stream.close();
347
565
  group.close();
@@ -362,70 +580,126 @@ export class Publisher {
362
580
  *
363
581
  * @internal
364
582
  */
365
- async #runTrack(sub, broadcast, track, stream, timescale) {
583
+ async #runTrack(track, stream, controls, serving) {
584
+ const { sub, broadcast, timescale, bounds } = serving;
366
585
  // Lite-05+ resolves the range on the subscribe stream: SUBSCRIBE_START once the
367
586
  // first group is known, SUBSCRIBE_END when the track finishes.
368
587
  const emitRange = supportsTrackStream(this.version);
369
588
  let startSent = false;
370
- // The exclusive end of the delivered range. recvGroup is arrival-ordered rather than
371
- // sequence-ordered, so this tracks the max and not the last group seen. 0 is already
372
- // the encoding for a track that produced no groups.
373
- let end = 0;
589
+ let endSent = false;
590
+ // The track's exclusive final boundary. A Rust subscriber feeds SUBSCRIBE_END
591
+ // straight into finish_at, so it must name the track's boundary (which counts
592
+ // datagram sequences too), not the delivered range: a subscription cap can hold
593
+ // produced groups back. The latest() fallback covers a subscription torn down
594
+ // before the producer declared it.
595
+ 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).
599
+ const sendEnd = async () => {
600
+ endSent = true;
601
+ if (emitRange) {
602
+ return controls.response(encodeSubscribeResponse(stream, { end: new SubscribeEnd(boundary()) }, this.version));
603
+ }
604
+ return true;
605
+ };
374
606
  // One ranking for the whole subscription, shared by every group it serves.
375
607
  const priority = new Priority(track);
376
608
  // Cancels groups still queued for a stream slot. Only the subscriber leaving counts:
377
- // a track that ran out of groups still has to flush the ones already queued, and we
378
- // FIN the subscribe stream ourselves below to say so.
609
+ // a track that ran out of groups still has to flush the ones already queued, and the
610
+ // caller FINs the subscribe stream to say so.
379
611
  let finished = false;
380
612
  let unsubscribe;
381
613
  const unsubscribed = new Promise((resolve) => {
382
614
  unsubscribe = resolve;
383
615
  });
384
- void stream.closed.then(() => {
385
- if (!finished)
386
- unsubscribe();
387
- },
388
- // A reset is always the peer.
389
- () => unsubscribe());
390
616
  try {
391
617
  for (;;) {
392
- // Exactly-once serving, not the sequence cursor: on a relay, a burst can be
393
- // ingested micro-reordered by the upstream leg, and a sequence cursor would
394
- // permanently skip the older group even though it is cached and in demand.
395
- // Staleness is the latency window's job (cache expiry), not arrival order's.
396
- const next = track.recvGroup();
397
- const group = await Promise.race([next, stream.closed]);
398
- if (!group) {
399
- next.then((group) => group?.close()).catch(() => { });
400
- break;
618
+ // Control before data, matching the Rust publisher: every control decoded while
619
+ // the loop was parked applies to the next pop, never to one already made. This
620
+ // drain is synchronous, so nothing the decoder holds can land between the pop
621
+ // below and its frame range.
622
+ const control = controls.take();
623
+ if (control) {
624
+ switch (control.kind) {
625
+ case "done":
626
+ // The subscriber left. Its queued groups are pointless now, which
627
+ // the finally below acts on since `finished` stays false.
628
+ return;
629
+ case "error":
630
+ throw control.error;
631
+ case "update": {
632
+ const update = control.update;
633
+ console.debug(`subscribe update: broadcast=${broadcast} track=${track.name}`);
634
+ hooks.replaceGroups(track, {
635
+ start: update.startGroup === undefined ? undefined : { included: update.startGroup },
636
+ end: update.endGroup === undefined ? undefined : { included: update.endGroup },
637
+ });
638
+ bounds.startGroup = update.startGroup;
639
+ bounds.startFrame = update.startFrame;
640
+ bounds.endGroup = update.endGroup;
641
+ bounds.endFrame = update.endFrame;
642
+ await yieldToControls();
643
+ continue;
644
+ }
645
+ }
401
646
  }
647
+ // Exactly-once arrival-order serving. This synchronous package-internal pop
648
+ // and frameRange call are the operation's linearization point.
649
+ const recv = hooks.tryRecvGroup(track);
650
+ switch (recv.kind) {
651
+ case "error":
652
+ throw recv.error;
653
+ case "idle":
654
+ await waitForSubscription(controls, track);
655
+ continue;
656
+ case "boundary":
657
+ // The producer finished but is still holding groups above the cap.
658
+ // Declare the boundary, then wait for an update to release them.
659
+ if (!endSent) {
660
+ if (!(await sendEnd()))
661
+ return;
662
+ continue;
663
+ }
664
+ await waitForSubscription(controls, track);
665
+ continue;
666
+ case "done":
667
+ if (!endSent) {
668
+ if (!(await sendEnd()))
669
+ return;
670
+ continue;
671
+ }
672
+ finished = true;
673
+ return;
674
+ }
675
+ const group = recv.group;
676
+ const range = frameRange(bounds, group.sequence);
402
677
  if (emitRange && !startSent) {
403
678
  startSent = true;
404
679
  // SUBSCRIBE_START promises nothing below this sequence will be delivered.
405
680
  // Arrival-order serving could later surface a straggler below the first
406
681
  // group, so pin the floor to what was announced.
407
- track.startAt(group.sequence);
408
- await encodeSubscribeResponse(stream, { start: new SubscribeStart(group.sequence) }, this.version);
682
+ hooks.replaceGroups(track, {
683
+ start: { included: group.sequence },
684
+ end: bounds.endGroup === undefined ? undefined : { included: bounds.endGroup },
685
+ });
686
+ if (!(await controls.response(encodeSubscribeResponse(stream, { start: new SubscribeStart(group.sequence) }, this.version))))
687
+ return;
409
688
  }
410
- end = Math.max(end, group.sequence + 1);
411
- void this.#runGroup({ sub, group, timescale, priority, unsubscribed });
412
- }
413
- if (emitRange) {
414
- await encodeSubscribeResponse(stream, { end: new SubscribeEnd(end) }, this.version);
689
+ void this.#runGroup({
690
+ sub,
691
+ group,
692
+ timescale,
693
+ priority,
694
+ unsubscribed,
695
+ start: range.start,
696
+ end: range.end,
697
+ });
415
698
  }
416
- console.debug(`publish close: broadcast=${broadcast} track=${track.name}`);
417
- finished = true;
418
- track.close();
419
- stream.close();
420
- }
421
- catch (err) {
422
- const e = error(err);
423
- console.warn(`publish error: broadcast=${broadcast} track=${track.name} error=${reason(e)}`);
424
- unsubscribe();
425
- track.close(e);
426
- stream.reset(e);
427
699
  }
428
700
  finally {
701
+ if (!finished)
702
+ unsubscribe();
429
703
  priority.close();
430
704
  }
431
705
  }
@@ -436,7 +710,11 @@ export class Publisher {
436
710
  */
437
711
  async runTrackInfo(msg, stream) {
438
712
  try {
439
- const info = await this.#resolveTrackInfo(msg.broadcast, msg.track);
713
+ const front = this.#broadcasts.peek()?.get(msg.broadcast) ??
714
+ (this.#publish && (await wireOf(this.#publish).demand(msg.broadcast)));
715
+ if (!front)
716
+ throw new NotFound(`broadcast ${msg.broadcast}`);
717
+ const info = await this.#resolveTrackInfo(front, msg.track);
440
718
  await info.encode(stream.writer, this.version);
441
719
  console.debug(`track info: broadcast=${msg.broadcast} track=${msg.track}`);
442
720
  stream.close();
@@ -447,34 +725,33 @@ export class Publisher {
447
725
  }
448
726
  }
449
727
  // Resolve (and cache) a track's immutable TRACK_INFO by asking the application.
450
- // `broadcast.track(name).info()` triggers a TrackRequest the app answers with
451
- // accept(TrackInfo); only the immutable properties are needed (not the groups).
452
- // Cached because they're fixed for the track's lifetime. Rejects if the broadcast
453
- // or track is unavailable.
454
- #resolveTrackInfo(broadcast, track) {
455
- const key = `${broadcast}\0${track}`;
456
- const cached = this.#trackInfo.get(key);
728
+ // `resolveTrackInfo` triggers a TrackRequest the app answers with accept(TrackInfo);
729
+ // only the immutable properties are needed (not the groups). Cached because they're
730
+ // fixed for the track's lifetime. Rejects if the track is unavailable.
731
+ #resolveTrackInfo(front, track) {
732
+ let tracks = this.#trackInfo.get(front);
733
+ if (!tracks) {
734
+ tracks = new Map();
735
+ this.#trackInfo.set(front, tracks);
736
+ }
737
+ const cached = tracks.get(track);
457
738
  if (cached)
458
739
  return cached;
459
740
  const pending = (async () => {
460
- const published = this.#broadcasts.peek()?.get(broadcast);
461
- if (!published)
462
- throw new Error("not found");
463
- const info = await published.track(track).info();
741
+ const info = await wireOf(front).resolveTrackInfo(track);
464
742
  return new TrackInfoMessage({
465
743
  priority: info.priority,
466
- ordered: info.ordered,
467
- // Publisher Max Latency: the publisher's retention bound, advertised so
744
+ // Publisher Max Age: the publisher's retention bound, advertised so
468
745
  // relays re-serve with the same window.
469
- latencyMax: info.latencyMax,
746
+ maxAge: info.maxAge,
470
747
  // Lite05 mandates per-frame timestamps. Advertise the track's timescale;
471
748
  // `#runGroup` emits each frame converted to it.
472
749
  timescale: info.timescale,
473
750
  });
474
751
  })();
475
752
  // Don't poison the cache on failure: a later request may succeed.
476
- pending.catch(() => this.#trackInfo.delete(key));
477
- this.#trackInfo.set(key, pending);
753
+ pending.catch(() => tracks.delete(track));
754
+ tracks.set(track, pending);
478
755
  return pending;
479
756
  }
480
757
  /**
@@ -514,9 +791,17 @@ export class Publisher {
514
791
  }
515
792
  // Serialize a fetched group's frames onto the FETCH stream as bare records: each a
516
793
  // zigzag-delta timestamp (at the track's advertised timescale) followed by size + bytes.
517
- async #runFetchGroup(group, stream, timescale) {
794
+ async #runFetchGroup(group, stream, { timescale, start: startFrame, end: endFrame }) {
795
+ // The response carries no header, so the receiver numbers the first frame it gets
796
+ // as `startFrame`. Skipping the head here is the only thing keeping those numbers
797
+ // honest; a group that ends before we reach it can't be served at all.
798
+ for (let i = 0; i < startFrame; i++) {
799
+ if (!(await Promise.race([group.readFrame(), stream.closed]))) {
800
+ throw new Error(`fetch group ended at frame ${i}, before the requested start ${startFrame}`);
801
+ }
802
+ }
518
803
  let prevTs = 0n;
519
- for (;;) {
804
+ for (let index = startFrame; endFrame === undefined || index <= endFrame; index++) {
520
805
  const frame = await Promise.race([group.readFrame(), stream.closed]);
521
806
  if (!frame)
522
807
  break;
@@ -533,8 +818,10 @@ export class Publisher {
533
818
  * @internal
534
819
  */
535
820
  async #runGroup(options) {
536
- const { sub, group, timescale, priority, unsubscribed } = options;
537
- const msg = new GroupMessage(sub, group.sequence);
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 });
538
825
  try {
539
826
  // The transport drains streams by send order, so this is what makes a high-priority
540
827
  // track (and a newer group within it) win the link when there isn't room for both.
@@ -558,24 +845,48 @@ export class Publisher {
558
845
  // A SUBSCRIBE_UPDATE re-ranks the subscription, so a group already on the wire
559
846
  // follows it too rather than keeping a stale rank until it finishes.
560
847
  priority.add(stream, group.sequence);
561
- await stream.u53(0); // stream type
562
- await msg.encode(stream);
848
+ await hooks.guardGroup(group, (async () => {
849
+ await stream.u53(0); // stream type
850
+ await msg.encode(stream, this.version);
851
+ })());
563
852
  // Lite05+ prefixes every frame with a zigzag-delta timestamp at the track's
564
853
  // advertised timescale; older drafts omit it.
565
854
  const timestamps = supportsTrackStream(this.version);
566
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;
567
859
  for (;;) {
568
- const frame = await Promise.race([group.readFrame(), stream.closed]);
569
- if (!frame)
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}`);
570
868
  break;
571
- if (timestamps) {
572
- // Convert each frame to the track's advertised timescale.
573
- const ts = BigInt(Math.round(frame.timestamp.as(timescale)));
574
- await stream.u62(zigzag(ts - prevTs));
575
- prevTs = ts;
576
869
  }
577
- await stream.u53(frame.payload.byteLength);
578
- await stream.write(frame.payload);
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;
877
+ 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();
889
+ }
579
890
  }
580
891
  stream.close();
581
892
  group.close();
@@ -678,12 +989,8 @@ export class Publisher {
678
989
  }
679
990
  }
680
991
  close() {
681
- this.#broadcasts.update((broadcasts) => {
682
- for (const broadcast of broadcasts?.values() ?? []) {
683
- broadcast.close();
684
- }
685
- return undefined;
686
- });
992
+ // The broadcasts belong to the origin, which outlives this session; closing here
993
+ // only drops the borrow. The peer sees the unannounce when the streams die.
687
994
  // Release the datagram writer's lock so the stream can be torn down.
688
995
  this.#datagramWriter?.releaseLock();
689
996
  this.#datagramWriter = undefined;