@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
@@ -1,37 +1,36 @@
1
1
  /* @ts-self-types="./subscriber.d.ts" */
2
- import { Signal } from "@moq/signals";
2
+ import { race, Signal } from "@moq/signals";
3
3
  import * as announce from "../announced.js";
4
4
  import * as broadcast from "../broadcast.js";
5
5
  import { BroadcastCache } from "../consume.js";
6
- import { controlTimeout, error, ProtocolViolation, reason, StreamCode, StreamError } from "../error.js";
6
+ import { controlTimeout, error, ProtocolViolation, reason, StreamCode, StreamError, sessionCause } from "../error.js";
7
7
  import * as netGroup from "../group.js";
8
- import { Cost, MAX_HOPS, routesEqual, UNKNOWN_HOP } from "../hop.js";
9
- import { groupBounds, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.js";
8
+ import { Cost, MAX_HOPS, randomHop, routesEqual, stampHops, UNKNOWN_HOP } from "../hop.js";
9
+ import { groupBounds, hiddenBelow, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.js";
10
10
  import * as Path from "../path.js";
11
11
  import { Stream } from "../stream.js";
12
+ import { TAIL_GRACE_MS, Tail } from "../tail.js";
12
13
  import * as Time from "../time.js";
14
+ import { untilAborted } from "../util/abort.js";
13
15
  import { TimeoutError, withTimeout } from "../util/timeout.js";
14
16
  import { overrideBroadcastWire, wireOf } from "../wire.js";
15
- import { AnnounceInit, AnnounceOk, AnnounceRequest, decodeAnnounceBroadcastMaybe } from "./announce.js";
17
+ import { AnnounceHistory, AnnounceInit, AnnounceOk, AnnounceRequest, decodeAnnounceBroadcastMaybe, } from "./announce.js";
16
18
  import { Datagram as DatagramMessage } from "./datagram.js";
17
19
  import * as DatagramStream from "./datagram_stream.js";
18
20
  import { Fetch as FetchMessage } from "./fetch.js";
21
+ import { frameDecoder, readFrames } from "./group.js";
19
22
  import { sendOrder } from "./priority.js";
20
23
  import { Probe } from "./probe.js";
21
24
  import { ProbeLevel } from "./setup.js";
22
25
  import { StreamId } from "./stream.js";
23
26
  import { decodeSubscribeResponse, decodeSubscribeResponseMaybe, EMPTY_RANGE, emptyRange, exclusiveGroupEnd, inclusiveGroupEnd, Subscribe, SubscribeUpdate, } from "./subscribe.js";
24
27
  import { TrackInfo, Track as TrackMessage } from "./track.js";
25
- import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, restartSupported, Version } from "./version.js";
28
+ import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, hasStreamCount, restartSupported, Version, } from "./version.js";
26
29
  // Bound on how long stream-open plus the first response (SUBSCRIBE_OK on older
27
30
  // drafts, or TRACK_INFO on lite-05+) may take. Browsers cap concurrent QUIC streams
28
31
  // (Chrome ~100) and we open with waitUntilAvailable, so past the cap the open blocks
29
32
  // until the peer frees a slot. The timeout turns a stall into a clear error.
30
33
  const SUBSCRIBE_SETUP_TIMEOUT_MS = 10_000;
31
- /** Decode an unsigned zigzag varint back to a signed delta (mirrors Rust `VarInt::to_zigzag`). */
32
- function unzigzag(v) {
33
- return (v >> 1n) ^ -(v & 1n);
34
- }
35
34
  // The TRACK stream and implicit SUBSCRIBE acceptance are lite-05+.
36
35
  function supportsTrackStream(version) {
37
36
  switch (version) {
@@ -80,6 +79,9 @@ export class Subscriber {
80
79
  #subscribeNext = 0n;
81
80
  // Dedup consumed broadcasts per path: repeat consume() calls share one subscription.
82
81
  #consumes = new BroadcastCache();
82
+ // A random Hop ID of this connection's own, written as the first hop of any chain that
83
+ // names no publisher, so a publisher that reconnects reads as a new one.
84
+ #stamp;
83
85
  // Dedup in-flight one-shot fetches, keyed by [broadcast, track, sequence]. Concurrent (or
84
86
  // repeat, while still open) fetchGroup() calls for the same group share one FETCH stream and
85
87
  // each get an independent mirror; the entry is evicted once the group closes.
@@ -105,6 +107,7 @@ export class Subscriber {
105
107
  this.#quic = quic;
106
108
  this.version = version;
107
109
  this.hop = hop;
110
+ this.#stamp = randomHop();
108
111
  this.#probe = probe;
109
112
  this.#peerSetup = peerSetup;
110
113
  }
@@ -115,25 +118,30 @@ export class Subscriber {
115
118
  * Reflected announces (those whose hop chain already includes this
116
119
  * connection) are always dropped: moq-lite-06 has none to keep, and older
117
120
  * versions stay consistent with that.
121
+ *
122
+ * Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless
123
+ * `options.hidden` opts in. The opt-in rides the request on lite-07+; an older peer
124
+ * never hides anything, so the rule is also applied here.
118
125
  */
119
- announced(scope = Path.Pattern.all()) {
126
+ announced(scope = Path.Pattern.all(), options) {
120
127
  const announced = new announce.Producer();
121
128
  // The wire speaks announce interest by prefix, and echoes suffixes beneath it.
122
- void this.#runAnnounced(announced, scopeHead(scope), scope);
129
+ void this.#runAnnounced(announced, scopeHead(scope), scope, options?.hidden ?? false);
123
130
  return announced.consume();
124
131
  }
125
- async #runAnnounced(announced, prefix, scope) {
132
+ async #runAnnounced(announced, prefix, scope, hidden) {
126
133
  console.debug(`announced: prefix=${prefix}`);
127
134
  // Lite04/05: send our own session-level Hop ID so the peer can skip announces
128
135
  // whose hop chain already passed through us. Encoding drops it on every other
129
136
  // version, where we drop the reflected announce on receipt instead. Matches the
130
137
  // Rust subscriber's `exclude_hop: self.self_origin.id` in `run_announce_prefix`.
131
- const msg = new AnnounceRequest(prefix, this.hop);
138
+ const msg = new AnnounceRequest(prefix, this.hop, hidden);
139
+ const visible = (path) => scopeOverlaps(scope, path) && (hidden || !hiddenBelow(prefix, path));
132
140
  // Opened outside the try so the catch can reach it: a protocol violation below has
133
141
  // to reset the stream, not just close our side of it.
134
142
  let stream;
135
143
  try {
136
- stream = await Stream.open(this.#quic);
144
+ stream = await Stream.open(this.#quic, { version: this.version });
137
145
  }
138
146
  catch (err) {
139
147
  announced.close(error(err));
@@ -164,16 +172,16 @@ export class Subscriber {
164
172
  // they go on record and obey the same one-per-path rule: the initial set
165
173
  // naming a path twice is the same violation as two ANNOUNCE_STARTs for it,
166
174
  // and the record is what catches either. Draft01/02 carry no hop ids and no
167
- // ANNOUNCE_OK, so nothing names the publisher.
175
+ // ANNOUNCE_OK, so this connection's stamp names the publisher.
168
176
  for (const suffix of init.suffixes) {
169
177
  const path = Path.join(prefix, suffix);
170
178
  if (advertised.has(path)) {
171
179
  throw new ProtocolViolation(`duplicate announce for ${path}`);
172
180
  }
173
- const route = { hops: [UNKNOWN_HOP], cost: Cost.zero };
174
- const live = scopeOverlaps(scope, path);
181
+ const route = { hops: [this.#stamp, UNKNOWN_HOP], cost: Cost.zero };
182
+ const live = visible(path);
175
183
  const captures = scopeCaptures(scope, path);
176
- advertised.set(path, { publisher: undefined, live, route, captures });
184
+ advertised.set(path, { publisher: this.#stamp, live, route, captures });
177
185
  if (!live)
178
186
  continue;
179
187
  console.debug(`announced: broadcast=${path} active=true`);
@@ -186,13 +194,13 @@ export class Subscriber {
186
194
  break;
187
195
  }
188
196
  // Lite06+: announce ids. Each received `active` implicitly assigns the next
189
- // per-stream ordinal; `endedId`/`restart` reference it. Tracked even for
190
- // announces we skip as reflected, since the sender doesn't know we skipped.
191
- let nextAnnounceId = 0n;
192
- const announcedById = new Map();
197
+ // per-stream ordinal; `endedId`/`restart` reference it, and lite-07 bases copy
198
+ // from it. Tracked even for announces we skip as reflected, since the sender
199
+ // doesn't know we skipped.
200
+ const history = new AnnounceHistory();
193
201
  // Receive announce updates (for Draft03, this includes initial state)
194
202
  for (;;) {
195
- const announce = await Promise.race([
203
+ const announce = await race([
196
204
  decodeAnnounceBroadcastMaybe(stream.reader, this.version),
197
205
  announced.closed,
198
206
  ]);
@@ -207,43 +215,31 @@ export class Subscriber {
207
215
  let hops;
208
216
  let cost;
209
217
  switch (announce.status) {
210
- case "active":
218
+ case "active": {
219
+ const resolved = hasAnnounceId(this.version) ? history.start(announce) : announce;
211
220
  // The wire names the suffix beneath the interest prefix; the consumer
212
221
  // sees the covered path from the session root.
213
- path = Path.join(prefix, announce.suffix);
222
+ path = Path.join(prefix, resolved.suffix);
214
223
  active = true;
215
- hops = announce.hops;
224
+ hops = resolved.hops;
216
225
  cost = announce.cost;
217
- if (hasAnnounceId(this.version)) {
218
- announcedById.set(nextAnnounceId++, path);
219
- }
220
226
  break;
227
+ }
221
228
  case "ended":
222
229
  path = Path.join(prefix, announce.suffix);
223
230
  active = false;
224
231
  break;
225
- case "endedId": {
232
+ case "endedId":
226
233
  // Resolve and retire the id; an unknown or retired id is a protocol violation.
227
- const resolved = announcedById.get(announce.id);
228
- if (resolved === undefined)
229
- throw new ProtocolViolation(`unknown announce id: ${announce.id}`);
230
- announcedById.delete(announce.id);
231
- if (resolved === null)
232
- continue;
233
- path = resolved;
234
+ path = Path.join(prefix, history.end(announce.id));
234
235
  active = false;
235
236
  break;
236
- }
237
237
  case "restart": {
238
238
  // Resolve the id; it stays live (the replacement reuses it).
239
- const resolved = announcedById.get(announce.id);
240
- if (resolved === undefined)
241
- throw new ProtocolViolation(`unknown announce id: ${announce.id}`);
242
- if (resolved === null)
243
- continue;
244
- path = resolved;
239
+ const resolved = history.update(announce);
240
+ path = Path.join(prefix, resolved.suffix);
245
241
  active = true;
246
- hops = announce.hops;
242
+ hops = resolved.hops;
247
243
  cost = announce.cost;
248
244
  break;
249
245
  }
@@ -307,22 +303,14 @@ export class Subscriber {
307
303
  continue;
308
304
  }
309
305
  // The first hop identifies the original publisher; an empty chain means the
310
- // peer itself originated it. See `restart_announce` in the Rust subscriber.
311
- const publisher = hops?.[0] ?? responderOrigin;
312
- // A publisher with no identity (an empty chain from a peer that withheld its
313
- // own id, or a lite-03 UNKNOWN placeholder) never proves continuity: two such
314
- // advertisements can be unrelated publishers. Mirrors the
315
- // `publisher == Hop::UNKNOWN` arm of the Rust `restart_announce`.
316
- const identified = publisher !== undefined && publisher !== UNKNOWN_HOP;
317
- const fullHops = hops !== undefined && responderOrigin !== undefined
306
+ // peer itself originated it. One that names nobody (lite-01..03, or a peer
307
+ // reporting 0) gets this connection's stamp in front of its 0.
308
+ const fullHops = stampHops(hops !== undefined && responderOrigin !== undefined
318
309
  ? [...hops, responderOrigin]
319
- : [...(hops ?? [])];
320
- // A received empty list is the anonymous mark, not a local announcement.
321
- if (fullHops.length === 0)
322
- fullHops.push(UNKNOWN_HOP);
310
+ : [...(hops ?? [])], this.#stamp);
323
311
  // Appending a withheld AnnounceOk(0) onto a 32-entry list is the same
324
312
  // drop Rust's Hops::push makes: do not expose an overlong chain.
325
- if (fullHops.length > MAX_HOPS) {
313
+ if (fullHops === undefined || fullHops.length > MAX_HOPS) {
326
314
  console.debug(`announced: broadcast=${path} dropped (hop chain at MAX_HOPS)`);
327
315
  advertised.set(path, {
328
316
  publisher: undefined,
@@ -332,36 +320,30 @@ export class Subscriber {
332
320
  });
333
321
  continue;
334
322
  }
323
+ const publisher = fullHops[0];
335
324
  const route = { hops: fullHops, cost: cost ?? Cost.zero };
336
325
  const captures = scopeCaptures(scope, path);
337
- if (!scopeOverlaps(scope, path)) {
326
+ if (!visible(path)) {
338
327
  advertised.set(path, { publisher, live: false, route, captures });
339
328
  continue;
340
329
  }
341
330
  // A second advertisement for a path we already carry is a restart: either an
342
- // explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE.
331
+ // explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE. It updates the
332
+ // route in place, so a forwarder re-prices without retracting.
343
333
  const previous = advertised.get(path);
344
334
  if (previous?.live) {
345
- if (identified && previous.publisher === publisher) {
346
- // Same publisher, new route. In-flight subscriptions resume across it.
347
- // Emit the route so a forwarder can re-price without retracting.
348
- if (!routesEqual(previous.route, route)) {
349
- advertised.set(path, { publisher, live: true, route, captures });
350
- console.debug(`announced: broadcast=${path} rerouted`);
351
- announced.append({ prefix: path, captures, kind: "updated", route });
352
- }
353
- else {
354
- console.debug(`announced: broadcast=${path} rerouted`);
355
- }
356
- continue;
335
+ // A different publisher took the path. Subscriptions already open drain
336
+ // the old copy, but the next consume starts fresh rather than reusing the
337
+ // old publisher's cached track info.
338
+ if (previous.publisher !== publisher)
339
+ this.#consumes.evict(path);
340
+ advertised.set(path, { publisher, live: true, route, captures });
341
+ console.debug(`announced: broadcast=${path} rerouted`);
342
+ if (!routesEqual(previous.route, route)) {
343
+ announced.append({ prefix: path, captures, kind: "updated", route });
357
344
  }
358
- // A different publisher took the path, so cached track info and existing
359
- // subscriptions must not carry over. Surface a real end before the start.
360
- retract();
345
+ continue;
361
346
  }
362
- // After `retract()`, which clears the entry: the path is advertised again, by
363
- // whoever just took it over. Recording it before would leave nothing behind, so
364
- // the *next* takeover would read as a first announcement and skip its own end.
365
347
  advertised.set(path, { publisher, live: true, route, captures });
366
348
  console.debug(`announced: broadcast=${path} active=true`);
367
349
  announced.append({ prefix: path, captures, kind: "announced", route });
@@ -446,7 +428,7 @@ export class Subscriber {
446
428
  catch (err) {
447
429
  // The setup outlived its deadline waiting for the first response: a control
448
430
  // timeout, not content that arrived late.
449
- const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
431
+ const e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);
450
432
  request.reject(e);
451
433
  this.#subscribes.delete(id);
452
434
  console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
@@ -456,31 +438,40 @@ export class Subscriber {
456
438
  setup.then(() => state.stream?.abort(e), () => state.stream?.abort(e));
457
439
  return;
458
440
  }
459
- const { stream, producer } = opened;
441
+ const { stream, entry } = opened;
442
+ const producer = entry.track;
460
443
  try {
461
444
  // Watch for subscription changes and send SUBSCRIBE_UPDATE. Lite01/Lite02
462
445
  // don't carry SUBSCRIBE_UPDATE on the wire, so skip the watcher there
463
446
  // and just wait on the stream/track like before.
464
447
  //
465
- // On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream;
466
- // drain them (we don't drive delivery off the resolved range) so the FIN is
467
- // observed. Older drafts just wait for the stream to close.
468
- const closed = supportsTrackStream(this.version) ? this.#drainResponses(stream) : stream.reader.closed;
448
+ // On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream until
449
+ // its FIN; older drafts just close it. Either way group streams can still be in
450
+ // flight, so the track ends only once the tail is accounted for. A reset rejects
451
+ // instead, so the track ends with that error rather than a clean tail.
452
+ const responses = supportsTrackStream(this.version)
453
+ ? this.#runResponses(stream, entry)
454
+ : stream.reader.closed;
455
+ const closed = responses.then(() => this.#settleTail(entry));
456
+ // A reset that lands after the race below settled is moot; the race observes one before.
457
+ closed.catch(() => { });
469
458
  const subscriptionUpdates = this.version === Version.DRAFT_01 || this.version === Version.DRAFT_02
470
459
  ? undefined
471
- : this.#runSubscriptionUpdates(id, broadcast, producer, msg, stream);
460
+ : this.#runSubscriptionUpdates(id, broadcast, entry, msg, stream);
472
461
  // Terminal conditions (stream end, track close, a failed subscription update) settle at most
473
462
  // once; race them into one stable promise so the demand loop doesn't re-subscribe each pass.
463
+ // Updates stop quietly at the FIN, which can land before the responses ahead of it are
464
+ // decoded, so only their failure is terminal on its own.
474
465
  const terminal = [closed, producer.closed];
475
466
  if (subscriptionUpdates !== undefined)
476
- terminal.push(subscriptionUpdates);
477
- const done = Promise.race(terminal);
467
+ terminal.push(subscriptionUpdates.then(() => closed));
468
+ const done = race(terminal);
478
469
  // Serve until a terminal condition fires or the last local subscriber leaves. The unused
479
470
  // wake is level-triggered: re-check demand so a subscriber that returns before we tear
480
471
  // down (e.g. a quickly unmuted tile) resumes on the same subscription.
481
472
  const idle = Symbol("idle");
482
473
  for (;;) {
483
- const reason = await Promise.race([done, producer.unused().then(() => idle)]);
474
+ const reason = await race([done, producer.unused().then(() => idle)]);
484
475
  if (reason === idle && producer.closed.peek() === undefined && producer.used.peek())
485
476
  continue;
486
477
  break;
@@ -490,7 +481,7 @@ export class Subscriber {
490
481
  console.debug(`subscribe close: id=${id} broadcast=${broadcast} track=${request.name}`);
491
482
  }
492
483
  catch (err) {
493
- const e = error(err);
484
+ const e = await sessionCause(this.#quic, err);
494
485
  producer.close(e);
495
486
  console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
496
487
  stream.abort(e);
@@ -524,8 +515,22 @@ export class Subscriber {
524
515
  drainOk = true;
525
516
  }
526
517
  // Register before opening SUBSCRIBE so a racing GROUP stream finds the entry.
527
- this.#subscribes.set(id, { track: producer, timescale });
528
- state.stream = await Stream.open(this.#quic);
518
+ const entry = {
519
+ track: producer,
520
+ timescale,
521
+ // The effective max age is the stopgap grace: the wrong clock (it bounds
522
+ // presentation-time drift), but it is how long the subscriber was willing to wait
523
+ // for a late group anyway. Already the smaller of the subscriber's and the track's.
524
+ tail: new Tail({
525
+ grace: () => {
526
+ const maxAge = producer.subscription.peek()?.maxAge ?? Time.Milli.zero;
527
+ return maxAge > 0 ? maxAge : TAIL_GRACE_MS;
528
+ },
529
+ }),
530
+ requested: msg.startGroup,
531
+ };
532
+ this.#subscribes.set(id, entry);
533
+ state.stream = await Stream.open(this.#quic, { version: this.version });
529
534
  await state.stream.writer.u53(StreamId.Subscribe);
530
535
  await msg.encode(state.stream.writer, this.version);
531
536
  if (drainOk) {
@@ -535,23 +540,39 @@ export class Subscriber {
535
540
  throw new Error("first subscribe response must be SUBSCRIBE_OK");
536
541
  }
537
542
  }
538
- return { stream: state.stream, producer };
543
+ return { stream: state.stream, entry };
539
544
  }
540
545
  // Opens a TRACK stream, reads the single TRACK_INFO, and FINs. Lite-05+ only.
541
546
  async #trackInfo(broadcast, track) {
542
- const stream = await Stream.open(this.#quic);
543
- try {
547
+ return this.#exchange({ version: this.version }, async (stream) => {
544
548
  await stream.writer.u53(StreamId.Track);
545
549
  await new TrackMessage(broadcast, track).encode(stream.writer, this.version);
546
550
  const info = await TrackInfo.decode(stream.reader, this.version);
547
551
  // The publisher FINs after TRACK_INFO; FIN our side too.
548
552
  stream.close();
549
553
  return info;
554
+ });
555
+ }
556
+ // Opens a stream and runs a request/response exchange on it, resetting the stream if `run`
557
+ // fails. Subscriber.close() also resets it while `run` is pending, so a peer that never
558
+ // answers cannot hold it open, and a stream that opens after the close is reset at once.
559
+ async #exchange(options, run) {
560
+ const closed = this.#closed.signal;
561
+ closed.throwIfAborted();
562
+ const stream = await Stream.open(this.#quic, options);
563
+ const abort = () => stream.abort(error(closed.reason));
564
+ closed.addEventListener("abort", abort);
565
+ try {
566
+ closed.throwIfAborted();
567
+ return await run(stream);
550
568
  }
551
569
  catch (err) {
552
570
  stream.abort(error(err));
553
571
  throw err;
554
572
  }
573
+ finally {
574
+ closed.removeEventListener("abort", abort);
575
+ }
555
576
  }
556
577
  // Map the wire TRACK_INFO onto the model track.Info a producer/consumer holds.
557
578
  #toModelInfo(info) {
@@ -574,83 +595,118 @@ export class Subscriber {
574
595
  }
575
596
  // Open a FETCH stream for one group and stream its bare frames into a group, for the
576
597
  // ConsumeBroadcast backing track.Consumer.fetchGroup() (lite-05+).
577
- fetchGroup(broadcast, track, sequence, options = {}) {
598
+ async fetchGroup(broadcast, track, sequence, options = {}) {
599
+ options.signal?.throwIfAborted();
578
600
  // Coalesce onto a still-open fetch of the same group so we don't open a second FETCH
579
601
  // stream (and re-download it); each caller reads an independent mirror.
602
+ //
603
+ // Reserve each caller's mirror before the fetch starts or is awaited: the fetch watches
604
+ // demand from the start, and a fast FIN cannot discard frames before these callers
605
+ // receive their handles. An abort closes only this caller's mirror, so the stream is
606
+ // cancelled once the last one leaves.
580
607
  const key = JSON.stringify([broadcast, track, sequence]);
581
- const existing = this.#fetches.get(key);
582
- if (existing && !existing.isClosed)
583
- return Promise.resolve(existing.mirror());
584
- // Create and cache the group synchronously (before any await) so a concurrent fetch for
585
- // the same group finds it and coalesces rather than racing to open its own stream.
586
- const group = new netGroup.Producer(sequence);
587
- this.#fetches.set(key, group);
588
- void group.closed.then(() => {
589
- if (this.#fetches.get(key) === group)
590
- this.#fetches.delete(key);
591
- });
592
- return this.#runFetch(broadcast, track, sequence, options, group);
608
+ let entry = this.#fetches.get(key);
609
+ let consumer;
610
+ if (entry && !entry.group.isClosed) {
611
+ consumer = entry.group.mirror();
612
+ }
613
+ else {
614
+ const group = new netGroup.Producer(sequence);
615
+ consumer = group.mirror();
616
+ entry = { group, accepted: this.#runFetch(broadcast, track, sequence, options.priority ?? 0, group) };
617
+ this.#fetches.set(key, entry);
618
+ void group.closed.then(() => {
619
+ if (this.#fetches.get(key)?.group === group)
620
+ this.#fetches.delete(key);
621
+ });
622
+ }
623
+ try {
624
+ await untilAborted(entry.accepted, options.signal);
625
+ return consumer;
626
+ }
627
+ catch (err) {
628
+ consumer.close();
629
+ throw err;
630
+ }
593
631
  }
594
632
  // Open the FETCH stream and pump the response into the shared group. Setup errors close the
595
- // group (so coalesced mirrors observe them and the entry evicts) and reject this caller.
596
- async #runFetch(broadcast, track, sequence, options, group) {
633
+ // group, evict the entry, and reject every caller waiting for acceptance. A setup every caller
634
+ // has abandoned is cancelled the same way.
635
+ async #runFetch(broadcast, track, sequence, priority, group) {
597
636
  try {
598
637
  if (!supportsTrackStream(this.version)) {
599
638
  throw new Error("fetch group requires moq-lite-05 or newer");
600
639
  }
601
- const info = await this.#trackInfo(broadcast, track);
602
- const priority = options.priority ?? 0;
603
- const stream = await Stream.open(this.#quic, { sendOrder: sendOrder({ priority }) });
640
+ // Lite has no FETCH_OK, so a publisher that never answers would hold the setup forever.
641
+ // Subscriber.close() closing the group releases every caller at any stage, and resets
642
+ // the streams the setup opened.
643
+ const setup = this.#fetchSetup(broadcast, track, sequence, priority, group);
644
+ let accepted;
604
645
  try {
605
- await stream.writer.u53(StreamId.Fetch);
606
- await new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version);
646
+ accepted = await untilAbandoned(group, setup);
607
647
  }
608
648
  catch (err) {
609
- stream.abort(error(err));
649
+ // A setup that finishes just after the close hands back a stream nobody will read.
650
+ void setup.then(({ stream }) => stream.abort(error(err)), () => void 0);
610
651
  throw err;
611
652
  }
612
- // Mint this caller's reader before starting the pump, so the group has demand when the
613
- // pump begins watching it (an abandoned fetch cancels once every reader has left).
614
- const consumer = group.mirror();
615
- void this.#runFetchResponse(stream, group, Time.Timescale(info.timescale));
616
- return consumer;
653
+ void this.#runFetchResponse(accepted.stream, group, Time.Timescale(accepted.info.timescale));
617
654
  }
618
655
  catch (err) {
619
656
  group.close(error(err));
620
657
  throw err;
621
658
  }
622
659
  }
660
+ // Resolve the track's timescale, then open the FETCH stream and wait for it to be accepted.
661
+ // Closing the group during that wait resets the stream.
662
+ async #fetchSetup(broadcast, track, sequence, priority, group) {
663
+ const info = await untilClosed(group, this.#trackInfo(broadcast, track));
664
+ return this.#exchange({ sendOrder: sendOrder({ priority }), version: this.version }, async (stream) => {
665
+ await stream.writer.u53(StreamId.Fetch);
666
+ await new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version);
667
+ // A byte or an empty-group FIN accepts the fetch; a reset rejects it.
668
+ // done() buffers that byte so the response pump can decode it normally.
669
+ await untilClosed(group, stream.reader.done());
670
+ return { stream, info };
671
+ });
672
+ }
623
673
  // Read the FETCH response (bare zigzag-delta-timestamped frames) into the group, then
624
674
  // FIN. A stream-level failure aborts the group so its reader observes the gap.
625
675
  async #runFetchResponse(stream, group, timescale) {
626
676
  try {
627
- let prevTs = 0n;
677
+ const decode = frameDecoder(timescale);
628
678
  // Serve until the stream FINs, the group closes, or every reader leaves. A group can
629
679
  // stay open indefinitely (a catalog or JSON stream), so an abandoned fetch is stopped by
630
- // demand, not by the stream ending. `closed` and `unused` are watched across frames as
631
- // stable promises (not re-subscribed to the signals each frame); the unused check is
632
- // level-triggered, so a coalesced fetch that arrives before we cancel re-arms and resumes.
680
+ // demand, not by the stream ending. `unused` is watched across frames as one stable
681
+ // promise; the check is level-triggered, so a coalesced fetch that arrives before we
682
+ // cancel re-arms and resumes.
633
683
  const idle = Symbol("idle");
634
- const closed = Promise.resolve(group.closed);
635
684
  let unused = group.unused().then(() => idle);
685
+ // A decode consumes its frame whenever it lands, so one outstanding across a re-arm is
686
+ // kept and awaited again rather than abandoned with its frame.
687
+ let pending;
636
688
  for (;;) {
637
- const done = await Promise.race([stream.reader.done(), closed, unused]);
638
- if (done === idle) {
639
- if (!group.isClosed && group.used.peek()) {
640
- unused = group.unused().then(() => idle);
641
- continue;
689
+ // Buffered frames are written without an await, as in a group stream.
690
+ let frame = pending === undefined ? stream.reader.tryDecode(decode) : undefined;
691
+ if (!frame) {
692
+ pending ??= stream.reader.decodeMaybe(decode);
693
+ const next = await race([pending, group.closed, unused]);
694
+ if (next === idle) {
695
+ if (group.isClosed)
696
+ break;
697
+ if (group.used.peek()) {
698
+ unused = group.unused().then(() => idle);
699
+ continue;
700
+ }
701
+ // Abandoned mid-group: the truncated group must never end clean.
702
+ throw new StreamError(StreamCode.Cancel, { message: "cancel" });
642
703
  }
643
- break;
704
+ pending = undefined;
705
+ if (!next || next instanceof Error)
706
+ break;
707
+ frame = next;
644
708
  }
645
- if (done !== false)
646
- break;
647
- prevTs += unzigzag(await stream.reader.u62());
648
- const timestamp = new Time.Timestamp(Number(prevTs), timescale);
649
- const size = await stream.reader.u53();
650
- const payload = await stream.reader.read(size);
651
- if (!payload)
652
- break;
653
- group.writeFrame({ payload, timestamp });
709
+ group.writeFrame(frame);
654
710
  }
655
711
  group.close();
656
712
  stream.close();
@@ -661,35 +717,94 @@ export class Subscriber {
661
717
  stream.abort(e);
662
718
  }
663
719
  }
664
- // Drains SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+).
665
- // The resolved range is informational here; the producer already orders groups.
666
- // Resolves (never rejects) on FIN or on the stream being reset out from under it,
667
- // so it's safe to drop from a Promise.race without an unhandled rejection.
668
- async #drainResponses(stream) {
669
- try {
670
- for (;;) {
671
- const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
672
- if (!resp)
673
- return;
720
+ // Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording
721
+ // the range the tail is accounted against. SUBSCRIBE_END declares the track's end right
722
+ // away, so a consumer learns it before the last groups arrive. The publisher must declare
723
+ // the end before FIN; resets and malformed responses reject with their failure.
724
+ async #runResponses(stream, entry) {
725
+ for (;;) {
726
+ const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
727
+ if (!resp) {
728
+ if (entry.end === undefined)
729
+ throw new ProtocolViolation("subscribe stream ended without SUBSCRIBE_END");
730
+ return;
731
+ }
732
+ if ("start" in resp) {
733
+ entry.start = resp.start.group;
734
+ // The groups the SUBSCRIBE asked for below it are unavailable, whatever the
735
+ // demand asks later.
736
+ if (entry.requested !== undefined)
737
+ entry.tail.account(entry.requested, entry.start);
738
+ }
739
+ else if ("end" in resp) {
740
+ if (entry.end !== undefined)
741
+ throw new ProtocolViolation("duplicate SUBSCRIBE_END");
742
+ entry.end = resp.end.group;
743
+ if (hasStreamCount(this.version))
744
+ entry.streams = resp.end.streams;
745
+ // A local close can win the race with the response; there is nothing left to end.
746
+ if (entry.track.closed.peek() !== undefined)
747
+ continue;
748
+ try {
749
+ entry.track.finishAt(entry.end);
750
+ }
751
+ catch (err) {
752
+ // lite-05 specified an inclusive end, and @moq/net 0.1.3 to 0.1.9 sent one, so
753
+ // there an end below a received group only costs the early boundary: the FIN
754
+ // still finishes the track. Later drafts made it exclusive.
755
+ if (this.version !== Version.DRAFT_05) {
756
+ throw new ProtocolViolation(`invalid SUBSCRIBE_END: ${reason(error(err))}`);
757
+ }
758
+ console.warn(`invalid SUBSCRIBE_END: ${reason(error(err))}`);
759
+ }
760
+ }
761
+ else if ("drop" in resp) {
762
+ entry.tail.account(resp.drop.start, resp.drop.end + 1);
674
763
  }
675
- }
676
- catch {
677
- // Stream closed or reset; nothing more to drain.
678
764
  }
679
765
  }
766
+ // Wait for the group streams the publisher still owes once it has ended the subscription.
767
+ //
768
+ // lite-07 counts streams, so skipped sequences owe nothing. Older drafts account for
769
+ // the range using received headers and SUBSCRIBE_DROP. A counted stream reset before
770
+ // its header leaves no trace, so the grace still bounds that wait. Streams whose
771
+ // headers arrived keep reading until their own FIN or reset.
772
+ #settleTail(entry) {
773
+ const { tail, track } = entry;
774
+ const complete = () => {
775
+ if (entry.streams !== undefined)
776
+ return tail.streams >= entry.streams;
777
+ // Without SUBSCRIBE_END (older drafts) nothing says which groups are owed.
778
+ if (entry.end === undefined)
779
+ return false;
780
+ // Without SUBSCRIBE_START the publisher served no group at all.
781
+ if (entry.start === undefined)
782
+ return true;
783
+ // Owed from the floor the demand last asked for, which an update can move either
784
+ // way, or where SUBSCRIBE_START resolved a live-edge one. The groups the SUBSCRIBE
785
+ // asked for below its SUBSCRIBE_START were accounted for when it arrived.
786
+ const groups = track.subscription.peek()?.groups;
787
+ const bounds = groupBounds(groups ?? {});
788
+ const start = groups?.start === undefined ? entry.start : bounds.start;
789
+ const end = bounds.end === undefined ? entry.end : Math.min(entry.end, bounds.end);
790
+ return tail.covers(start, end);
791
+ };
792
+ return tail.settle(complete, track.closed);
793
+ }
680
794
  /**
681
795
  * Send SUBSCRIBE_UPDATE messages whenever the track's aggregate subscription changes.
682
796
  *
683
797
  * Resolves cleanly when the stream or track closes, so the caller can include
684
- * this in Promise.race without leaving a dangling pending write that would
798
+ * this in a race without leaving a dangling pending write that would
685
799
  * become an unhandled rejection if the user calls update after close.
686
800
  *
687
801
  * Peeks the signal at the top of every iteration so that updates which landed
688
802
  * before SubscribeOk arrived (or between iterations, before .next() registered
689
803
  * its listener) aren't lost.
690
804
  */
691
- async #runSubscriptionUpdates(id, broadcast, track, msg, stream) {
692
- const stopped = Promise.race([track.closed, stream.reader.closed]).then(() => null);
805
+ async #runSubscriptionUpdates(id, broadcast, entry, msg, stream) {
806
+ const track = entry.track;
807
+ const stopped = race([track.closed, stream.reader.closed]).then(() => null);
693
808
  let lastSent = {
694
809
  priority: msg.priority,
695
810
  maxAge: Time.Milli(msg.maxAge),
@@ -702,7 +817,7 @@ export class Subscriber {
702
817
  const current = track.subscription.peek();
703
818
  if (current === undefined || this.#sameSubscription(current, lastSent)) {
704
819
  // Nothing new to send; wait for a change or termination.
705
- const next = await Promise.race([track.subscription.changed(), stopped]);
820
+ const next = await race([track.subscription.changed(), stopped]);
706
821
  if (next === null)
707
822
  return;
708
823
  continue;
@@ -712,6 +827,11 @@ export class Subscriber {
712
827
  const bounds = groupBounds(current.groups);
713
828
  if (emptyRange({ startGroup: bounds.start, endGroup: bounds.end }))
714
829
  throw new Error(EMPTY_RANGE);
830
+ // A lowered floor owes groups nobody asked for until now.
831
+ if (current.groups?.start !== undefined) {
832
+ const floor = lastSent.groups?.start === undefined ? entry.start : groupBounds(lastSent.groups).start;
833
+ entry.tail.demand(bounds.start, floor ?? Number.POSITIVE_INFINITY);
834
+ }
715
835
  // Round-trip the other Subscribe parameters so the publisher doesn't
716
836
  // interpret SUBSCRIBE_UPDATE as a reset of ordered/maxAge/etc.
717
837
  const update = new SubscribeUpdate({
@@ -748,10 +868,19 @@ export class Subscriber {
748
868
  }
749
869
  return;
750
870
  }
751
- const { track, timescale } = entry;
871
+ const { track, timescale, tail } = entry;
752
872
  const producer = new netGroup.Producer(group.sequence);
753
- track.writeGroup(producer);
873
+ const read = tail.open(group.sequence);
754
874
  try {
875
+ // The publisher contradicted its own end, which no later group can repair. lite-05
876
+ // specified an inclusive end, so its last group lands on it: the write below drops
877
+ // only that group there.
878
+ if (entry.end !== undefined && group.sequence >= entry.end && this.version !== Version.DRAFT_05) {
879
+ const violation = new ProtocolViolation(`group ${group.sequence} is at or past the declared end ${entry.end}`);
880
+ track.close(violation);
881
+ throw violation;
882
+ }
883
+ track.writeGroup(producer);
755
884
  // Block until the timescale is known; the group's stream can arrive before
756
885
  // TRACK_INFO (or implicit defaults) resolves it on the subscribe stream.
757
886
  let scale = timescale.peek();
@@ -765,36 +894,18 @@ export class Subscriber {
765
894
  await Signal.race(timescale, track.closed);
766
895
  scale = timescale.peek();
767
896
  }
768
- // A non-zero scale means every frame is prefixed with a zigzag-delta timestamp
769
- // (the lite-05 FRAME format), which we decode into a Timestamp at that scale.
770
- // Scale 0 (pre-lite-05) carries no timestamp, so we wall-clock-stamp.
771
- let prevTs = 0n;
772
- for (;;) {
773
- const done = await Promise.race([stream.done(), track.closed, producer.closed]);
774
- if (done !== false)
775
- break;
776
- let timestamp;
777
- if (scale !== 0) {
778
- prevTs += unzigzag(await stream.u62());
779
- timestamp = new Time.Timestamp(Number(prevTs), Time.Timescale(scale));
780
- }
781
- else {
782
- timestamp = Time.Timestamp.now();
783
- }
784
- const size = await stream.u53();
785
- const payload = await stream.read(size);
786
- if (!payload)
787
- break;
788
- producer.writeFrame({ payload, timestamp });
789
- }
897
+ await readFrames(stream, producer, scale);
790
898
  producer.close();
791
899
  stream.stop(new StreamError(StreamCode.Cancel, { message: "cancel" }));
792
900
  }
793
901
  catch (err) {
794
- const e = error(err);
902
+ const e = await sessionCause(this.#quic, err);
795
903
  producer.close(e);
796
904
  stream.stop(e);
797
905
  }
906
+ finally {
907
+ read();
908
+ }
798
909
  }
799
910
  /**
800
911
  * Receives QUIC datagrams and routes each to its subscription's track producer (lite-05 §6.4).
@@ -847,7 +958,7 @@ export class Subscriber {
847
958
  // Decode one datagram body and hand it to the matching subscription's producer. Drops the
848
959
  // datagram (best-effort) if the subscription is unknown/closed or its timescale isn't resolved.
849
960
  async #routeDatagram(payload) {
850
- const dg = await DatagramMessage.decode(payload);
961
+ const dg = await DatagramMessage.decode(payload, this.version);
851
962
  const entry = this.#subscribes.get(dg.subscribe);
852
963
  if (!entry)
853
964
  return; // Unknown or already-closed subscription.
@@ -857,6 +968,8 @@ export class Subscriber {
857
968
  if (!scale)
858
969
  return;
859
970
  const timestamp = new Time.Timestamp(dg.timestamp, Time.Timescale(scale));
971
+ // A datagram's sequence is never owed a stream, so it never holds the tail open.
972
+ entry.tail.account(dg.sequence, dg.sequence + 1);
860
973
  entry.track.insertDatagram(dg.sequence, timestamp, dg.payload);
861
974
  }
862
975
  /**
@@ -896,7 +1009,7 @@ export class Subscriber {
896
1009
  // transport hiccup) MUST NOT tear down the connection. On error, drop the
897
1010
  // estimates so consumers know they're stale.
898
1011
  try {
899
- const stream = await Stream.open(this.#quic);
1012
+ const stream = await Stream.open(this.#quic, { version: this.version });
900
1013
  await stream.writer.u53(StreamId.Probe);
901
1014
  for (;;) {
902
1015
  const probe = await Probe.decodeMaybe(stream.reader, this.version);
@@ -925,12 +1038,44 @@ export class Subscriber {
925
1038
  this.#probe.set({});
926
1039
  }
927
1040
  }
928
- close() {
929
- this.#closed.abort();
1041
+ /**
1042
+ * Ends every subscribed track: cleanly for a deliberate close, or with `err` when the
1043
+ * session died, since those tracks were cut off rather than ended.
1044
+ */
1045
+ close(err) {
1046
+ // A fetch or setup exchange cut off by the session is incomplete even on a deliberate
1047
+ // close, so it always ends with an error.
1048
+ const cut = err ?? new StreamError(StreamCode.SessionClosed, { message: "session closed" });
1049
+ this.#closed.abort(cut);
930
1050
  for (const { track } of this.#subscribes.values()) {
931
- track.close();
1051
+ track.close(err);
932
1052
  }
933
1053
  this.#subscribes.clear();
1054
+ // This also releases callers still awaiting acceptance.
1055
+ for (const { group } of this.#fetches.values()) {
1056
+ group.close(cut);
1057
+ }
1058
+ }
1059
+ }
1060
+ // Settles with `step`, or rejects with the group's error once it closes first. A publisher
1061
+ // may never answer a FETCH, so Subscriber.close() closing the group is what releases it.
1062
+ async function untilClosed(group, step) {
1063
+ const value = await race([step, group.closed]);
1064
+ const closed = group.closed.peek();
1065
+ if (closed !== undefined)
1066
+ throw closed ?? new Error("fetch closed before it was accepted");
1067
+ return value;
1068
+ }
1069
+ // Like untilClosed, but also cancels once every reader has left. Demand is level-triggered, so a
1070
+ // caller that coalesces onto the group before the check re-arms it.
1071
+ async function untilAbandoned(group, step) {
1072
+ const idle = Symbol("idle");
1073
+ for (;;) {
1074
+ const value = await untilClosed(group, race([step, group.unused().then(() => idle)]));
1075
+ if (value !== idle)
1076
+ return value;
1077
+ if (!group.used.peek())
1078
+ throw new StreamError(StreamCode.Cancel, { message: "cancel" });
934
1079
  }
935
1080
  }
936
1081
  /**