@moq/net 0.3.5 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) 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 +49 -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 +23 -28
  18. package/broadcast.d.ts.map +1 -1
  19. package/broadcast.js +61 -40
  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 +48 -25
  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 +95 -46
  31. package/connection/connect.js.map +1 -1
  32. package/connection/established.d.ts +17 -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 +166 -0
  38. package/connection/forward.js.map +1 -0
  39. package/connection/handshake.d.ts +1 -0
  40. package/connection/handshake.d.ts.map +1 -1
  41. package/connection/handshake.js +5 -2
  42. package/connection/handshake.js.map +1 -1
  43. package/connection/index.d.ts +5 -5
  44. package/connection/index.d.ts.map +1 -1
  45. package/connection/index.js +4 -5
  46. package/connection/index.js.map +1 -1
  47. package/connection/pool.d.ts +186 -0
  48. package/connection/pool.d.ts.map +1 -0
  49. package/connection/pool.js +361 -0
  50. package/connection/pool.js.map +1 -0
  51. package/connection/reload.d.ts +14 -93
  52. package/connection/reload.d.ts.map +1 -1
  53. package/connection/reload.js +217 -81
  54. package/connection/reload.js.map +1 -1
  55. package/connection/stats.d.ts +3 -26
  56. package/connection/stats.d.ts.map +1 -1
  57. package/connection/stats.js.map +1 -1
  58. package/connection/transport.d.ts +0 -7
  59. package/connection/transport.d.ts.map +1 -1
  60. package/consume.d.ts +1 -43
  61. package/consume.d.ts.map +1 -1
  62. package/consume.js +1 -1
  63. package/consume.js.map +1 -1
  64. package/error.d.ts +180 -29
  65. package/error.d.ts.map +1 -1
  66. package/error.js +331 -16
  67. package/error.js.map +1 -1
  68. package/errors.d.ts +7 -0
  69. package/errors.d.ts.map +1 -0
  70. package/errors.js +8 -0
  71. package/errors.js.map +1 -0
  72. package/group.d.ts +9 -43
  73. package/group.d.ts.map +1 -1
  74. package/group.js +283 -69
  75. package/group.js.map +1 -1
  76. package/hop.d.ts +107 -0
  77. package/hop.d.ts.map +1 -0
  78. package/hop.js +103 -0
  79. package/hop.js.map +1 -0
  80. package/ietf/adapter.d.ts +5 -1
  81. package/ietf/adapter.d.ts.map +1 -1
  82. package/ietf/adapter.js +27 -9
  83. package/ietf/adapter.js.map +1 -1
  84. package/ietf/aliases.d.ts +1 -78
  85. package/ietf/aliases.d.ts.map +1 -1
  86. package/ietf/cluster.d.ts +6 -120
  87. package/ietf/cluster.d.ts.map +1 -1
  88. package/ietf/cluster.js +81 -41
  89. package/ietf/cluster.js.map +1 -1
  90. package/ietf/connection.d.ts +6 -72
  91. package/ietf/connection.d.ts.map +1 -1
  92. package/ietf/connection.js +17 -49
  93. package/ietf/connection.js.map +1 -1
  94. package/ietf/error.d.ts +11 -0
  95. package/ietf/error.d.ts.map +1 -0
  96. package/ietf/error.js +193 -0
  97. package/ietf/error.js.map +1 -0
  98. package/ietf/filter.d.ts.map +1 -1
  99. package/ietf/filter.js +6 -1
  100. package/ietf/filter.js.map +1 -1
  101. package/ietf/goaway.d.ts.map +1 -1
  102. package/ietf/goaway.js +22 -5
  103. package/ietf/goaway.js.map +1 -1
  104. package/ietf/hidden.d.ts +2 -0
  105. package/ietf/hidden.d.ts.map +1 -0
  106. package/ietf/hidden.js +30 -0
  107. package/ietf/hidden.js.map +1 -0
  108. package/ietf/index.d.ts +1 -0
  109. package/ietf/index.d.ts.map +1 -1
  110. package/ietf/index.js +1 -0
  111. package/ietf/index.js.map +1 -1
  112. package/ietf/object.d.ts +8 -2
  113. package/ietf/object.d.ts.map +1 -1
  114. package/ietf/object.js +17 -3
  115. package/ietf/object.js.map +1 -1
  116. package/ietf/parameters.d.ts +7 -2
  117. package/ietf/parameters.d.ts.map +1 -1
  118. package/ietf/parameters.js +35 -17
  119. package/ietf/parameters.js.map +1 -1
  120. package/ietf/properties.d.ts +1 -0
  121. package/ietf/properties.d.ts.map +1 -1
  122. package/ietf/properties.js +14 -0
  123. package/ietf/properties.js.map +1 -1
  124. package/ietf/publish.d.ts +19 -2
  125. package/ietf/publish.d.ts.map +1 -1
  126. package/ietf/publish.js +40 -6
  127. package/ietf/publish.js.map +1 -1
  128. package/ietf/publish_namespace.d.ts +25 -0
  129. package/ietf/publish_namespace.d.ts.map +1 -1
  130. package/ietf/publish_namespace.js +63 -0
  131. package/ietf/publish_namespace.js.map +1 -1
  132. package/ietf/publisher.d.ts +1 -82
  133. package/ietf/publisher.d.ts.map +1 -1
  134. package/ietf/publisher.js +302 -181
  135. package/ietf/publisher.js.map +1 -1
  136. package/ietf/solicit.d.ts +1 -40
  137. package/ietf/solicit.d.ts.map +1 -1
  138. package/ietf/subscribe.d.ts +1 -5
  139. package/ietf/subscribe.d.ts.map +1 -1
  140. package/ietf/subscribe.js +11 -13
  141. package/ietf/subscribe.js.map +1 -1
  142. package/ietf/subscribe_namespace.d.ts +8 -2
  143. package/ietf/subscribe_namespace.d.ts.map +1 -1
  144. package/ietf/subscribe_namespace.js +18 -8
  145. package/ietf/subscribe_namespace.js.map +1 -1
  146. package/ietf/subscriber.d.ts +1 -65
  147. package/ietf/subscriber.d.ts.map +1 -1
  148. package/ietf/subscriber.js +325 -121
  149. package/ietf/subscriber.js.map +1 -1
  150. package/ietf/version.d.ts +12 -1
  151. package/ietf/version.d.ts.map +1 -1
  152. package/ietf/version.js +13 -0
  153. package/ietf/version.js.map +1 -1
  154. package/index.d.ts +11 -6
  155. package/index.d.ts.map +1 -1
  156. package/index.js +10 -5
  157. package/index.js.map +1 -1
  158. package/internal.d.ts +104 -1
  159. package/internal.d.ts.map +1 -1
  160. package/internal.js +76 -0
  161. package/internal.js.map +1 -1
  162. package/lite/announce.d.ts +60 -10
  163. package/lite/announce.d.ts.map +1 -1
  164. package/lite/announce.js +173 -31
  165. package/lite/announce.js.map +1 -1
  166. package/lite/connection.d.ts +9 -59
  167. package/lite/connection.d.ts.map +1 -1
  168. package/lite/connection.js +26 -32
  169. package/lite/connection.js.map +1 -1
  170. package/lite/fetch.d.ts +15 -1
  171. package/lite/fetch.d.ts.map +1 -1
  172. package/lite/fetch.js +39 -7
  173. package/lite/fetch.js.map +1 -1
  174. package/lite/goaway.d.ts.map +1 -1
  175. package/lite/goaway.js +7 -1
  176. package/lite/goaway.js.map +1 -1
  177. package/lite/group.d.ts +18 -4
  178. package/lite/group.d.ts.map +1 -1
  179. package/lite/group.js +31 -10
  180. package/lite/group.js.map +1 -1
  181. package/lite/priority.d.ts +1 -61
  182. package/lite/priority.d.ts.map +1 -1
  183. package/lite/priority.js +4 -5
  184. package/lite/priority.js.map +1 -1
  185. package/lite/publisher.d.ts +1 -69
  186. package/lite/publisher.d.ts.map +1 -1
  187. package/lite/publisher.js +593 -227
  188. package/lite/publisher.js.map +1 -1
  189. package/lite/setup.d.ts +7 -7
  190. package/lite/setup.d.ts.map +1 -1
  191. package/lite/setup.js +13 -13
  192. package/lite/setup.js.map +1 -1
  193. package/lite/subscribe.d.ts +71 -17
  194. package/lite/subscribe.d.ts.map +1 -1
  195. package/lite/subscribe.js +205 -53
  196. package/lite/subscribe.js.map +1 -1
  197. package/lite/subscriber.d.ts +15 -56
  198. package/lite/subscriber.d.ts.map +1 -1
  199. package/lite/subscriber.js +316 -188
  200. package/lite/subscriber.js.map +1 -1
  201. package/lite/track.d.ts +4 -10
  202. package/lite/track.d.ts.map +1 -1
  203. package/lite/track.js +34 -29
  204. package/lite/track.js.map +1 -1
  205. package/lite/version.d.ts +42 -6
  206. package/lite/version.d.ts.map +1 -1
  207. package/lite/version.js +126 -10
  208. package/lite/version.js.map +1 -1
  209. package/origin.d.ts +248 -29
  210. package/origin.d.ts.map +1 -1
  211. package/origin.js +1232 -37
  212. package/origin.js.map +1 -1
  213. package/package.json +8 -3
  214. package/path.d.ts +25 -7
  215. package/path.d.ts.map +1 -1
  216. package/path.js +5 -3
  217. package/path.js.map +1 -1
  218. package/stream.d.ts +2 -2
  219. package/stream.d.ts.map +1 -1
  220. package/stream.js +39 -25
  221. package/stream.js.map +1 -1
  222. package/tail.d.ts +11 -0
  223. package/tail.d.ts.map +1 -0
  224. package/tail.js +121 -0
  225. package/tail.js.map +1 -0
  226. package/time.d.ts +15 -2
  227. package/time.d.ts.map +1 -1
  228. package/time.js +28 -9
  229. package/time.js.map +1 -1
  230. package/track.d.ts +195 -84
  231. package/track.d.ts.map +1 -1
  232. package/track.js +694 -196
  233. package/track.js.map +1 -1
  234. package/wire.d.ts +69 -0
  235. package/wire.d.ts.map +1 -0
  236. package/wire.js +32 -0
  237. package/wire.js.map +1 -0
  238. package/zod.d.ts +1 -1
  239. package/zod.d.ts.map +1 -1
  240. package/zod.js.map +1 -1
  241. package/mock.d.ts +0 -66
  242. package/mock.d.ts.map +0 -1
  243. package/mock.js +0 -243
  244. package/mock.js.map +0 -1
@@ -1,16 +1,19 @@
1
1
  /* @ts-self-types="./subscriber.d.ts" */
2
- import { Signal } from "@moq/signals";
2
+ import { race, Signal } from "@moq/signals";
3
3
  import * as announce from "../announced.js";
4
4
  import * as broadcast from "../broadcast.js";
5
5
  import { BroadcastCache } from "../consume.js";
6
- import { error, ProtocolViolation, reason } 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 { UNKNOWN_ORIGIN } from "../origin.js";
8
+ import { Cost, MAX_HOPS, routesEqual, UNKNOWN_HOP } from "../hop.js";
9
+ import { groupBounds, hiddenBelow, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.js";
9
10
  import * as Path from "../path.js";
10
11
  import { Stream } from "../stream.js";
12
+ import { TAIL_GRACE_MS, Tail } from "../tail.js";
11
13
  import * as Time from "../time.js";
12
- import { withTimeout } from "../util/timeout.js";
13
- import { AnnounceInit, AnnounceOk, AnnounceRequest, decodeAnnounceBroadcastMaybe } from "./announce.js";
14
+ import { TimeoutError, withTimeout } from "../util/timeout.js";
15
+ import { overrideBroadcastWire, wireOf } from "../wire.js";
16
+ import { AnnounceHistory, AnnounceInit, AnnounceOk, AnnounceRequest, decodeAnnounceBroadcastMaybe, } from "./announce.js";
14
17
  import { Datagram as DatagramMessage } from "./datagram.js";
15
18
  import * as DatagramStream from "./datagram_stream.js";
16
19
  import { Fetch as FetchMessage } from "./fetch.js";
@@ -18,9 +21,9 @@ import { sendOrder } from "./priority.js";
18
21
  import { Probe } from "./probe.js";
19
22
  import { ProbeLevel } from "./setup.js";
20
23
  import { StreamId } from "./stream.js";
21
- import { decodeSubscribeResponse, decodeSubscribeResponseMaybe, Subscribe, SubscribeUpdate } from "./subscribe.js";
24
+ import { decodeSubscribeResponse, decodeSubscribeResponseMaybe, EMPTY_RANGE, emptyRange, exclusiveGroupEnd, inclusiveGroupEnd, Subscribe, SubscribeUpdate, } from "./subscribe.js";
22
25
  import { TrackInfo, Track as TrackMessage } from "./track.js";
23
- import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasExcludeHop, hasProbeRtt, restartSupported, Version, } from "./version.js";
26
+ import { hasAnnounceId, hasAnnounceOk, hasDatagrams, hasProbeRtt, restartSupported, Version } from "./version.js";
24
27
  // Bound on how long stream-open plus the first response (SUBSCRIBE_OK on older
25
28
  // drafts, or TRACK_INFO on lite-05+) may take. Browsers cap concurrent QUIC streams
26
29
  // (Chrome ~100) and we open with waitUntilAvailable, so past the cap the open blocks
@@ -69,9 +72,8 @@ export class Subscriber {
69
72
  #quic;
70
73
  // The version of the connection.
71
74
  version;
72
- // Shared with the Publisher so callers can optionally filter out their
73
- // own announcements on a per-call basis (see {@link AnnouncedOptions}).
74
- origin;
75
+ // Shared with the Publisher so reflected announces can be dropped on receipt.
76
+ hop;
75
77
  // Our subscribed tracks. `timescale` resolves once known (from TRACK_INFO on
76
78
  // lite-05+, or implicit defaults on older drafts); group streams block on it
77
79
  // before decoding any frame, since a group's QUIC stream can race ahead.
@@ -94,43 +96,45 @@ export class Subscriber {
94
96
  * Creates a new Subscriber instance.
95
97
  * @param quic - The WebTransport session to use
96
98
  * @param version - The protocol version
97
- * @param origin - Origin id shared with the Publisher
99
+ * @param origin - Hop id shared with the Publisher
98
100
  * @param probe - Optional sink for the peer's PROBE estimates
99
101
  * @param peerSetup - Optional peer SETUP slot for capability gating (lite-05+)
100
102
  *
101
103
  * @internal
102
104
  */
103
- constructor(quic, version, origin, probe, peerSetup) {
105
+ constructor(quic, version, hop, probe, peerSetup) {
104
106
  this.#quic = quic;
105
107
  this.version = version;
106
- this.origin = origin;
108
+ this.hop = hop;
107
109
  this.#probe = probe;
108
110
  this.#peerSetup = peerSetup;
109
111
  }
110
112
  /**
111
- * Subscribe to broadcast announcements under `prefix`.
113
+ * Subscribe to broadcast announcements matching `scope`. Paths are relative
114
+ * to the session, not the scope.
112
115
  *
113
- * Pass `{ ignoreSelf: true }` to skip announces that have already traversed
114
- * this connection's {@link origin}.
116
+ * Reflected announces (those whose hop chain already includes this
117
+ * connection) are always dropped: moq-lite-06 has none to keep, and older
118
+ * versions stay consistent with that.
119
+ *
120
+ * Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless
121
+ * `options.hidden` opts in. The opt-in rides the request on lite-07+; an older peer
122
+ * never hides anything, so the rule is also applied here.
115
123
  */
116
- announced(prefix = Path.empty(), options = {}) {
117
- const announced = new announce.Producer(prefix);
118
- void this.#runAnnounced(announced, prefix, options);
124
+ announced(scope = Path.Pattern.all(), options) {
125
+ const announced = new announce.Producer();
126
+ // The wire speaks announce interest by prefix, and echoes suffixes beneath it.
127
+ void this.#runAnnounced(announced, scopeHead(scope), scope, options?.hidden ?? false);
119
128
  return announced.consume();
120
129
  }
121
- async #runAnnounced(announced, prefix, options) {
130
+ async #runAnnounced(announced, prefix, scope, hidden) {
122
131
  console.debug(`announced: prefix=${prefix}`);
123
- // Lite04/05: send our own session-level origin id so the peer can skip announces
132
+ // Lite04/05: send our own session-level Hop ID so the peer can skip announces
124
133
  // whose hop chain already passed through us. Encoding drops it on every other
125
134
  // version, where we drop the reflected announce on receipt instead. Matches the
126
135
  // Rust subscriber's `exclude_hop: self.self_origin.id` in `run_announce_prefix`.
127
- const msg = new AnnounceRequest(prefix, this.origin);
128
- // Drop reflected announces so callers asking for "someone else's broadcasts"
129
- // don't re-see their own publishes. A caller can always ask for this, and it is
130
- // required on versions that don't carry excludeHop above: there the peer isn't
131
- // filtering them out for us, so filtering here keeps what the app sees the same
132
- // as lite-05. Lite01-03 carry no real hop ids, so the check never matches there.
133
- const dropReflected = options.ignoreSelf || !hasExcludeHop(this.version);
136
+ const msg = new AnnounceRequest(prefix, this.hop, hidden);
137
+ const visible = (path) => scopeOverlaps(scope, path) && (hidden || !hiddenBelow(prefix, path));
134
138
  // Opened outside the try so the catch can reach it: a protocol violation below has
135
139
  // to reset the stream, not just close our side of it.
136
140
  let stream;
@@ -145,17 +149,16 @@ export class Subscriber {
145
149
  // Send the announce interest.
146
150
  await stream.writer.u53(StreamId.Announce);
147
151
  await msg.encode(stream.writer, this.version);
148
- // Lite05+: the publisher reports its own origin id before any announces.
152
+ // Lite05+: the publisher reports its own Hop ID before any announces.
149
153
  // It no longer stamps itself onto each hop chain, so we append it here to
150
- // keep the ignoreSelf loop check seeing the full chain.
154
+ // keep the reflected-announce loop check seeing the full chain.
151
155
  let responderOrigin;
152
156
  if (hasAnnounceOk(this.version)) {
153
157
  const ok = await AnnounceOk.decode(stream.reader, this.version);
154
- // A responder that withholds its identity sends the reserved 0. It names
155
- // nobody, so folding it into a chain would stamp a placeholder that cannot
156
- // close a loop or tell two publishers apart. Treat it as absent instead,
157
- // which is the loop-blind route the draft describes.
158
- responderOrigin = ok.origin === UNKNOWN_ORIGIN ? undefined : ok.origin;
158
+ // Keep a withheld 0: it names nobody for loop detection, but it is the
159
+ // anonymous mark and must travel the reconstructed chain. Assigned identities
160
+ // stay off this hop and are never forwarded.
161
+ responderOrigin = ok.hop;
159
162
  }
160
163
  const advertised = new Map();
161
164
  switch (this.version) {
@@ -170,12 +173,17 @@ export class Subscriber {
170
173
  // ANNOUNCE_OK, so nothing names the publisher.
171
174
  for (const suffix of init.suffixes) {
172
175
  const path = Path.join(prefix, suffix);
173
- if (advertised.has(suffix)) {
176
+ if (advertised.has(path)) {
174
177
  throw new ProtocolViolation(`duplicate announce for ${path}`);
175
178
  }
176
- advertised.set(suffix, { publisher: undefined, live: true });
179
+ const route = { hops: [UNKNOWN_HOP], cost: Cost.zero };
180
+ const live = visible(path);
181
+ const captures = scopeCaptures(scope, path);
182
+ advertised.set(path, { publisher: undefined, live, route, captures });
183
+ if (!live)
184
+ continue;
177
185
  console.debug(`announced: broadcast=${path} active=true`);
178
- announced.append({ path: suffix, active: true });
186
+ announced.append({ prefix: path, captures, kind: "announced", route });
179
187
  }
180
188
  break;
181
189
  }
@@ -184,13 +192,13 @@ export class Subscriber {
184
192
  break;
185
193
  }
186
194
  // Lite06+: announce ids. Each received `active` implicitly assigns the next
187
- // per-stream ordinal; `endedId`/`restart` reference it. Tracked even for
188
- // announces we skip via ignoreSelf, since the sender doesn't know we skipped.
189
- let nextAnnounceId = 0n;
190
- const announcedById = new Map();
195
+ // per-stream ordinal; `endedId`/`restart` reference it, and lite-07 bases copy
196
+ // from it. Tracked even for announces we skip as reflected, since the sender
197
+ // doesn't know we skipped.
198
+ const history = new AnnounceHistory();
191
199
  // Receive announce updates (for Draft03, this includes initial state)
192
200
  for (;;) {
193
- const announce = await Promise.race([
201
+ const announce = await race([
194
202
  decodeAnnounceBroadcastMaybe(stream.reader, this.version),
195
203
  announced.closed,
196
204
  ]);
@@ -199,45 +207,43 @@ export class Subscriber {
199
207
  break;
200
208
  if (announce instanceof Error)
201
209
  throw announce;
202
- let suffix;
210
+ let path;
203
211
  let active;
204
212
  // Present on active/restart; ended messages never carry hops worth checking.
205
213
  let hops;
214
+ let cost;
206
215
  switch (announce.status) {
207
- case "active":
208
- suffix = announce.suffix;
216
+ case "active": {
217
+ const resolved = hasAnnounceId(this.version) ? history.start(announce) : announce;
218
+ // The wire names the suffix beneath the interest prefix; the consumer
219
+ // sees the covered path from the session root.
220
+ path = Path.join(prefix, resolved.suffix);
209
221
  active = true;
210
- hops = announce.hops;
211
- if (hasAnnounceId(this.version)) {
212
- announcedById.set(nextAnnounceId++, announce.suffix);
213
- }
222
+ hops = resolved.hops;
223
+ cost = announce.cost;
214
224
  break;
225
+ }
215
226
  case "ended":
216
- suffix = announce.suffix;
227
+ path = Path.join(prefix, announce.suffix);
217
228
  active = false;
218
229
  break;
219
- case "endedId": {
230
+ case "endedId":
220
231
  // Resolve and retire the id; an unknown or retired id is a protocol violation.
221
- const path = announcedById.get(announce.id);
222
- if (path === undefined)
223
- throw new ProtocolViolation(`unknown announce id: ${announce.id}`);
224
- announcedById.delete(announce.id);
225
- suffix = path;
232
+ path = Path.join(prefix, history.end(announce.id));
226
233
  active = false;
227
234
  break;
228
- }
229
235
  case "restart": {
230
236
  // Resolve the id; it stays live (the replacement reuses it).
231
- const path = announcedById.get(announce.id);
232
- if (path === undefined)
233
- throw new ProtocolViolation(`unknown announce id: ${announce.id}`);
234
- suffix = path;
237
+ const resolved = history.update(announce);
238
+ path = Path.join(prefix, resolved.suffix);
235
239
  active = true;
236
- hops = announce.hops;
240
+ hops = resolved.hops;
241
+ cost = announce.cost;
237
242
  break;
238
243
  }
244
+ case "skipped":
245
+ continue;
239
246
  }
240
- const path = Path.join(prefix, suffix);
241
247
  // One current advertisement per path per stream, decided before anything below
242
248
  // can skip this announcement. A second ANNOUNCE_START for a path the peer
243
249
  // already advertised is a violation whether or not its route would be usable
@@ -250,7 +256,7 @@ export class Subscriber {
250
256
  // a duplicate means the same thing on both sides of it. Mirrors the branch the
251
257
  // Rust announce loop takes before `start_announce`.
252
258
  const duplicateIsRestart = restartSupported(this.version) && !hasAnnounceId(this.version);
253
- if (announce.status === "active" && !duplicateIsRestart && advertised.has(suffix)) {
259
+ if (announce.status === "active" && !duplicateIsRestart && advertised.has(path)) {
254
260
  throw new ProtocolViolation(`duplicate announce for ${path}`);
255
261
  }
256
262
  // Retract the path: forget the advertisement, drop the shared consume entry so a
@@ -258,63 +264,101 @@ export class Subscriber {
258
264
  // and tell the consumer. A no-op for an advertisement never surfaced, which is
259
265
  // what an id retiring a skipped announce resolves to.
260
266
  const retract = () => {
261
- const previous = advertised.get(suffix);
262
- advertised.delete(suffix);
267
+ const previous = advertised.get(path);
268
+ advertised.delete(path);
263
269
  if (!previous?.live)
264
270
  return;
265
271
  this.#consumes.evict(path);
266
272
  console.debug(`announced: broadcast=${path} active=false`);
267
- announced.append({ path: suffix, active: false });
273
+ announced.append({
274
+ prefix: path,
275
+ captures: previous.captures,
276
+ kind: "retracted",
277
+ route: previous.route,
278
+ });
268
279
  };
269
280
  // In Lite05+ the sender's origin arrives via AnnounceOk, not in each hop
270
281
  // list, so fold it back in before checking.
271
- if (hops !== undefined && dropReflected) {
282
+ if (hops !== undefined) {
272
283
  const full = responderOrigin !== undefined ? [...hops, responderOrigin] : hops;
273
- if (full.includes(this.origin)) {
284
+ if (full.includes(this.hop)) {
274
285
  // A reflected restart means the peer's remaining route loops back through
275
286
  // us, so the route is gone even though the message says active. The
276
287
  // advertisement stays live: the peer still holds the path and its id still
277
288
  // resolves here.
278
289
  retract();
279
- advertised.set(suffix, { publisher: undefined, live: false });
290
+ advertised.set(path, {
291
+ publisher: undefined,
292
+ live: false,
293
+ route: { hops: full, cost: Cost.zero },
294
+ captures: undefined,
295
+ });
280
296
  continue;
281
297
  }
282
298
  }
283
- if (active) {
284
- // The first hop identifies the original publisher; an empty chain means the
285
- // peer itself originated it. See `restart_announce` in the Rust subscriber.
286
- const publisher = hops?.[0] ?? responderOrigin;
287
- // A publisher with no identity (an empty chain from a peer that withheld its
288
- // own id, or a lite-03 UNKNOWN placeholder) never proves continuity: two such
289
- // advertisements can be unrelated publishers. Mirrors the
290
- // `publisher == Origin::UNKNOWN` arm of the Rust `restart_announce`.
291
- const identified = publisher !== undefined && publisher !== UNKNOWN_ORIGIN;
292
- // A second advertisement for a path we already carry is a restart: either an
293
- // explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE.
294
- const previous = advertised.get(suffix);
295
- if (previous?.live) {
296
- if (identified && previous.publisher === publisher) {
297
- // Same publisher, new route. In-flight subscriptions resume across it,
298
- // so there is nothing for a consumer to react to. An unidentified
299
- // publisher falls through to the replacement path below instead.
299
+ if (!active) {
300
+ retract();
301
+ continue;
302
+ }
303
+ // The first hop identifies the original publisher; an empty chain means the
304
+ // peer itself originated it. See `restart_announce` in the Rust subscriber.
305
+ const publisher = hops?.[0] ?? responderOrigin;
306
+ // A publisher with no identity (an empty chain from a peer that withheld its
307
+ // own id, or a lite-03 UNKNOWN placeholder) never proves continuity: two such
308
+ // advertisements can be unrelated publishers. Mirrors the
309
+ // `publisher == Hop::UNKNOWN` arm of the Rust `restart_announce`.
310
+ const identified = publisher !== undefined && publisher !== UNKNOWN_HOP;
311
+ const fullHops = hops !== undefined && responderOrigin !== undefined
312
+ ? [...hops, responderOrigin]
313
+ : [...(hops ?? [])];
314
+ // A received empty list is the anonymous mark, not a local announcement.
315
+ if (fullHops.length === 0)
316
+ fullHops.push(UNKNOWN_HOP);
317
+ // Appending a withheld AnnounceOk(0) onto a 32-entry list is the same
318
+ // drop Rust's Hops::push makes: do not expose an overlong chain.
319
+ if (fullHops.length > MAX_HOPS) {
320
+ console.debug(`announced: broadcast=${path} dropped (hop chain at MAX_HOPS)`);
321
+ advertised.set(path, {
322
+ publisher: undefined,
323
+ live: false,
324
+ route: { hops: [], cost: Cost.zero },
325
+ captures: undefined,
326
+ });
327
+ continue;
328
+ }
329
+ const route = { hops: fullHops, cost: cost ?? Cost.zero };
330
+ const captures = scopeCaptures(scope, path);
331
+ if (!visible(path)) {
332
+ advertised.set(path, { publisher, live: false, route, captures });
333
+ continue;
334
+ }
335
+ // A second advertisement for a path we already carry is a restart: either an
336
+ // explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE.
337
+ const previous = advertised.get(path);
338
+ if (previous?.live) {
339
+ if (identified && previous.publisher === publisher) {
340
+ // Same publisher, new route. In-flight subscriptions resume across it.
341
+ // Emit the route so a forwarder can re-price without retracting.
342
+ if (!routesEqual(previous.route, route)) {
343
+ advertised.set(path, { publisher, live: true, route, captures });
300
344
  console.debug(`announced: broadcast=${path} rerouted`);
301
- continue;
345
+ announced.append({ prefix: path, captures, kind: "updated", route });
302
346
  }
303
- // A different publisher took the path, so cached track info and existing
304
- // subscriptions must not carry over. Surface a real end before the start.
305
- retract();
347
+ else {
348
+ console.debug(`announced: broadcast=${path} rerouted`);
349
+ }
350
+ continue;
306
351
  }
307
- // After `retract()`, which clears the entry: the path is advertised again, by
308
- // whoever just took it over. Recording it before would leave nothing behind, so
309
- // the *next* takeover would read as a first announcement and skip its own end.
310
- advertised.set(suffix, { publisher, live: true });
311
- }
312
- else {
352
+ // A different publisher took the path, so cached track info and existing
353
+ // subscriptions must not carry over. Surface a real end before the start.
313
354
  retract();
314
- continue;
315
355
  }
356
+ // After `retract()`, which clears the entry: the path is advertised again, by
357
+ // whoever just took it over. Recording it before would leave nothing behind, so
358
+ // the *next* takeover would read as a first announcement and skip its own end.
359
+ advertised.set(path, { publisher, live: true, route, captures });
316
360
  console.debug(`announced: broadcast=${path} active=true`);
317
- announced.append({ path: suffix, active: true });
361
+ announced.append({ prefix: path, captures, kind: "announced", route });
318
362
  }
319
363
  announced.close();
320
364
  }
@@ -354,7 +398,7 @@ export class Subscriber {
354
398
  const consumer = new ConsumeBroadcast(this, path);
355
399
  void (async () => {
356
400
  for (;;) {
357
- const request = await consumer.requested();
401
+ const request = await wireOf(consumer).requested();
358
402
  if (!request)
359
403
  break;
360
404
  void this.#runSubscribe(path, request);
@@ -365,19 +409,24 @@ export class Subscriber {
365
409
  async #runSubscribe(broadcast, request) {
366
410
  const id = this.#subscribeNext++;
367
411
  const subscription = request.subscription;
412
+ const initialBounds = groupBounds(subscription.groups);
413
+ if (emptyRange({ startGroup: initialBounds.start, endGroup: initialBounds.end })) {
414
+ request.reject(new Error(EMPTY_RANGE));
415
+ return;
416
+ }
368
417
  // `timescale` stays undefined until TRACK_INFO (or, on older drafts,
369
418
  // implicit defaults) resolves it; runGroup blocks on it before decoding.
370
419
  const timescale = new Signal(undefined);
371
420
  console.debug(`subscribe start: id=${id} broadcast=${broadcast} track=${request.name}`);
421
+ const bounds = groupBounds(subscription.groups);
372
422
  const msg = new Subscribe({
373
423
  id,
374
424
  broadcast,
375
425
  track: request.name,
376
426
  priority: subscription.priority ?? 0,
377
- ordered: subscription.ordered,
378
- maxLatency: subscription.latencyMax,
379
- startGroup: subscription.startGroup,
380
- endGroup: subscription.endGroup,
427
+ maxAge: subscription.maxAge,
428
+ startGroup: subscription.groups?.start === undefined ? undefined : bounds.start,
429
+ endGroup: inclusiveGroupEnd(bounds.end),
381
430
  });
382
431
  // Open the stream under a timeout. The stream handle flows back via `state`
383
432
  // so the timeout path can abort it if it finishes opening after the deadline.
@@ -389,7 +438,9 @@ export class Subscriber {
389
438
  console.debug(`subscribe ok: id=${id} broadcast=${broadcast} track=${request.name}`);
390
439
  }
391
440
  catch (err) {
392
- const e = error(err);
441
+ // The setup outlived its deadline waiting for the first response: a control
442
+ // timeout, not content that arrived late.
443
+ const e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);
393
444
  request.reject(e);
394
445
  this.#subscribes.delete(id);
395
446
  console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
@@ -399,31 +450,40 @@ export class Subscriber {
399
450
  setup.then(() => state.stream?.abort(e), () => state.stream?.abort(e));
400
451
  return;
401
452
  }
402
- const { stream, producer } = opened;
453
+ const { stream, entry } = opened;
454
+ const producer = entry.track;
403
455
  try {
404
456
  // Watch for subscription changes and send SUBSCRIBE_UPDATE. Lite01/Lite02
405
457
  // don't carry SUBSCRIBE_UPDATE on the wire, so skip the watcher there
406
458
  // and just wait on the stream/track like before.
407
459
  //
408
- // On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream;
409
- // drain them (we don't drive delivery off the resolved range) so the FIN is
410
- // observed. Older drafts just wait for the stream to close.
411
- const closed = supportsTrackStream(this.version) ? this.#drainResponses(stream) : stream.reader.closed;
460
+ // On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream until
461
+ // its FIN; older drafts just close it. Either way group streams can still be in
462
+ // flight, so the track ends only once the tail is accounted for. A reset rejects
463
+ // instead, so the track ends with that error rather than a clean tail.
464
+ const responses = supportsTrackStream(this.version)
465
+ ? this.#runResponses(stream, entry)
466
+ : stream.reader.closed;
467
+ const closed = responses.then(() => this.#settleTail(entry));
468
+ // A reset that lands after the race below settled is moot; the race observes one before.
469
+ closed.catch(() => { });
412
470
  const subscriptionUpdates = this.version === Version.DRAFT_01 || this.version === Version.DRAFT_02
413
471
  ? undefined
414
472
  : this.#runSubscriptionUpdates(id, broadcast, producer, msg, stream);
415
473
  // Terminal conditions (stream end, track close, a failed subscription update) settle at most
416
474
  // once; race them into one stable promise so the demand loop doesn't re-subscribe each pass.
475
+ // Updates stop quietly at the FIN, which can land before the responses ahead of it are
476
+ // decoded, so only their failure is terminal on its own.
417
477
  const terminal = [closed, producer.closed];
418
478
  if (subscriptionUpdates !== undefined)
419
- terminal.push(subscriptionUpdates);
420
- const done = Promise.race(terminal);
479
+ terminal.push(subscriptionUpdates.then(() => closed));
480
+ const done = race(terminal);
421
481
  // Serve until a terminal condition fires or the last local subscriber leaves. The unused
422
482
  // wake is level-triggered: re-check demand so a subscriber that returns before we tear
423
483
  // down (e.g. a quickly unmuted tile) resumes on the same subscription.
424
484
  const idle = Symbol("idle");
425
485
  for (;;) {
426
- const reason = await Promise.race([done, producer.unused().then(() => idle)]);
486
+ const reason = await race([done, producer.unused().then(() => idle)]);
427
487
  if (reason === idle && producer.closed.peek() === undefined && producer.used.peek())
428
488
  continue;
429
489
  break;
@@ -433,7 +493,7 @@ export class Subscriber {
433
493
  console.debug(`subscribe close: id=${id} broadcast=${broadcast} track=${request.name}`);
434
494
  }
435
495
  catch (err) {
436
- const e = error(err);
496
+ const e = await sessionCause(this.#quic, err);
437
497
  producer.close(e);
438
498
  console.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);
439
499
  stream.abort(e);
@@ -467,7 +527,8 @@ export class Subscriber {
467
527
  drainOk = true;
468
528
  }
469
529
  // Register before opening SUBSCRIBE so a racing GROUP stream finds the entry.
470
- this.#subscribes.set(id, { track: producer, timescale });
530
+ const entry = { track: producer, timescale, tail: new Tail() };
531
+ this.#subscribes.set(id, entry);
471
532
  state.stream = await Stream.open(this.#quic);
472
533
  await state.stream.writer.u53(StreamId.Subscribe);
473
534
  await msg.encode(state.stream.writer, this.version);
@@ -478,7 +539,7 @@ export class Subscriber {
478
539
  throw new Error("first subscribe response must be SUBSCRIBE_OK");
479
540
  }
480
541
  }
481
- return { stream: state.stream, producer };
542
+ return { stream: state.stream, entry };
482
543
  }
483
544
  // Opens a TRACK stream, reads the single TRACK_INFO, and FINs. Lite-05+ only.
484
545
  async #trackInfo(broadcast, track) {
@@ -500,15 +561,14 @@ export class Subscriber {
500
561
  #toModelInfo(info) {
501
562
  return {
502
563
  timescale: Time.Timescale(info.timescale),
503
- // Publisher Max Latency rides on the wire, so the local retention window
564
+ // Publisher Max Age rides on the wire, so the local retention window
504
565
  // matches what the upstream advertises (relays re-serve with the same bound).
505
- latencyMax: info.latencyMax,
566
+ maxAge: Time.Milli(info.maxAge),
506
567
  priority: info.priority,
507
- ordered: info.ordered,
508
568
  };
509
569
  }
510
570
  // Resolve a track's immutable model info via a TRACK stream (lite-05+), for the
511
- // ConsumeBroadcast backing track.Consumer.info(). On older drafts there's no TRACK
571
+ // ConsumeBroadcast backing track.Consumer.query(). On older drafts there's no TRACK
512
572
  // stream, so this rejects rather than fabricating defaults.
513
573
  async resolveTrackInfo(broadcast, track) {
514
574
  if (!supportsTrackStream(this.version)) {
@@ -518,25 +578,34 @@ export class Subscriber {
518
578
  }
519
579
  // Open a FETCH stream for one group and stream its bare frames into a group, for the
520
580
  // ConsumeBroadcast backing track.Consumer.fetchGroup() (lite-05+).
521
- fetchGroup(broadcast, track, sequence, options = {}) {
581
+ async fetchGroup(broadcast, track, sequence, options = {}) {
522
582
  // Coalesce onto a still-open fetch of the same group so we don't open a second FETCH
523
583
  // stream (and re-download it); each caller reads an independent mirror.
524
584
  const key = JSON.stringify([broadcast, track, sequence]);
525
- const existing = this.#fetches.get(key);
526
- if (existing && !existing.isClosed)
527
- return Promise.resolve(existing.mirror());
528
- // Create and cache the group synchronously (before any await) so a concurrent fetch for
529
- // the same group finds it and coalesces rather than racing to open its own stream.
530
- const group = new netGroup.Producer(sequence);
531
- this.#fetches.set(key, group);
532
- void group.closed.then(() => {
533
- if (this.#fetches.get(key) === group)
534
- this.#fetches.delete(key);
535
- });
536
- return this.#runFetch(broadcast, track, sequence, options, group);
585
+ let entry = this.#fetches.get(key);
586
+ if (!entry || entry.group.isClosed) {
587
+ const group = new netGroup.Producer(sequence);
588
+ entry = { group, accepted: this.#runFetch(broadcast, track, sequence, options, group) };
589
+ this.#fetches.set(key, entry);
590
+ void group.closed.then(() => {
591
+ if (this.#fetches.get(key)?.group === group)
592
+ this.#fetches.delete(key);
593
+ });
594
+ }
595
+ // Reserve each caller's mirror before awaiting acceptance so the pump sees demand,
596
+ // and a fast FIN cannot discard frames before these callers receive their handles.
597
+ const consumer = entry.group.mirror();
598
+ try {
599
+ await entry.accepted;
600
+ return consumer;
601
+ }
602
+ catch (err) {
603
+ consumer.close();
604
+ throw err;
605
+ }
537
606
  }
538
607
  // Open the FETCH stream and pump the response into the shared group. Setup errors close the
539
- // group (so coalesced mirrors observe them and the entry evicts) and reject this caller.
608
+ // group, evict the entry, and reject every caller waiting for acceptance.
540
609
  async #runFetch(broadcast, track, sequence, options, group) {
541
610
  try {
542
611
  if (!supportsTrackStream(this.version)) {
@@ -547,17 +616,16 @@ export class Subscriber {
547
616
  const stream = await Stream.open(this.#quic, { sendOrder: sendOrder({ priority }) });
548
617
  try {
549
618
  await stream.writer.u53(StreamId.Fetch);
550
- await new FetchMessage(broadcast, track, priority, sequence).encode(stream.writer, this.version);
619
+ await new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version);
620
+ // A byte or an empty-group FIN accepts the fetch; a reset rejects it.
621
+ // done() buffers that byte so the response pump can decode it normally.
622
+ await stream.reader.done();
551
623
  }
552
624
  catch (err) {
553
625
  stream.abort(error(err));
554
626
  throw err;
555
627
  }
556
- // Mint this caller's reader before starting the pump, so the group has demand when the
557
- // pump begins watching it (an abandoned fetch cancels once every reader has left).
558
- const consumer = group.mirror();
559
628
  void this.#runFetchResponse(stream, group, Time.Timescale(info.timescale));
560
- return consumer;
561
629
  }
562
630
  catch (err) {
563
631
  group.close(error(err));
@@ -571,14 +639,13 @@ export class Subscriber {
571
639
  let prevTs = 0n;
572
640
  // Serve until the stream FINs, the group closes, or every reader leaves. A group can
573
641
  // stay open indefinitely (a catalog or JSON stream), so an abandoned fetch is stopped by
574
- // demand, not by the stream ending. `closed` and `unused` are watched across frames as
575
- // stable promises (not re-subscribed to the signals each frame); the unused check is
576
- // level-triggered, so a coalesced fetch that arrives before we cancel re-arms and resumes.
642
+ // demand, not by the stream ending. `unused` is watched across frames as one stable
643
+ // promise; the check is level-triggered, so a coalesced fetch that arrives before we
644
+ // cancel re-arms and resumes.
577
645
  const idle = Symbol("idle");
578
- const closed = Promise.resolve(group.closed);
579
646
  let unused = group.unused().then(() => idle);
580
647
  for (;;) {
581
- const done = await Promise.race([stream.reader.done(), closed, unused]);
648
+ const done = await race([stream.reader.done(), group.closed, unused]);
582
649
  if (done === idle) {
583
650
  if (!group.isClosed && group.used.peek()) {
584
651
  unused = group.unused().then(() => idle);
@@ -605,27 +672,70 @@ export class Subscriber {
605
672
  stream.abort(e);
606
673
  }
607
674
  }
608
- // Drains SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+).
609
- // The resolved range is informational here; the producer already orders groups.
610
- // Resolves (never rejects) on FIN or on the stream being reset out from under it,
611
- // so it's safe to drop from a Promise.race without an unhandled rejection.
612
- async #drainResponses(stream) {
613
- try {
614
- for (;;) {
615
- const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
616
- if (!resp)
617
- return;
675
+ // Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording
676
+ // the range the tail is accounted against. SUBSCRIBE_END declares the track's end right
677
+ // away, so a consumer learns it before the last groups arrive. Resolves on FIN and rejects
678
+ // when the stream is reset, so the track ends with the publisher's error rather than cleanly.
679
+ async #runResponses(stream, entry) {
680
+ for (;;) {
681
+ const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
682
+ if (!resp)
683
+ return;
684
+ if ("start" in resp) {
685
+ entry.start = resp.start.group;
686
+ }
687
+ else if ("end" in resp) {
688
+ if (entry.end !== undefined)
689
+ throw new ProtocolViolation("duplicate SUBSCRIBE_END");
690
+ entry.end = resp.end.group;
691
+ // A local close can win the race with the response; there is nothing left to end.
692
+ if (entry.track.closed.peek() !== undefined)
693
+ continue;
694
+ try {
695
+ entry.track.finishAt(entry.end);
696
+ }
697
+ catch (err) {
698
+ throw new ProtocolViolation(`invalid SUBSCRIBE_END: ${reason(error(err))}`);
699
+ }
700
+ }
701
+ else if ("drop" in resp) {
702
+ entry.tail.account(resp.drop.start, resp.drop.end + 1);
618
703
  }
619
704
  }
620
- catch {
621
- // Stream closed or reset; nothing more to drain.
622
- }
705
+ }
706
+ // Wait for the group streams the publisher still owes once it has ended the subscription.
707
+ //
708
+ // Its FIN says every group below the end is accounted for, but QUIC does not order streams,
709
+ // so one can still be in flight. Wait until each group from SUBSCRIBE_START to the end has
710
+ // a stream (read to its end) or a SUBSCRIBE_DROP. A group reset before its header arrived
711
+ // never shows up, so give up on missing groups after the subscription's effective max age,
712
+ // then end cleanly with them skipped like any stale group. That is a wall-clock stopgap for
713
+ // a presentation-time budget; a publisher sending SUBSCRIBE_DROP for every group it reset
714
+ // would account for them with no timer at all.
715
+ #settleTail(entry) {
716
+ const { tail, track } = entry;
717
+ // Already the smaller of the subscriber's and the track's max age.
718
+ const maxAge = track.subscription.peek()?.maxAge ?? Time.Milli.zero;
719
+ const grace = maxAge > 0 ? maxAge : TAIL_GRACE_MS;
720
+ const complete = () => {
721
+ // Without SUBSCRIBE_END (older drafts) nothing says which groups are owed.
722
+ if (entry.end === undefined)
723
+ return false;
724
+ // Without SUBSCRIBE_START the publisher served no group at all.
725
+ if (entry.start === undefined)
726
+ return true;
727
+ const bounds = groupBounds(track.subscription.peek()?.groups ?? {});
728
+ const start = Math.max(entry.start, bounds.start);
729
+ const end = bounds.end === undefined ? entry.end : Math.min(entry.end, bounds.end);
730
+ return tail.covers(start, end);
731
+ };
732
+ return tail.settle(complete, grace, track.closed);
623
733
  }
624
734
  /**
625
735
  * Send SUBSCRIBE_UPDATE messages whenever the track's aggregate subscription changes.
626
736
  *
627
737
  * Resolves cleanly when the stream or track closes, so the caller can include
628
- * this in Promise.race without leaving a dangling pending write that would
738
+ * this in a race without leaving a dangling pending write that would
629
739
  * become an unhandled rejection if the user calls update after close.
630
740
  *
631
741
  * Peeks the signal at the top of every iteration so that updates which landed
@@ -633,29 +743,36 @@ export class Subscriber {
633
743
  * its listener) aren't lost.
634
744
  */
635
745
  async #runSubscriptionUpdates(id, broadcast, track, msg, stream) {
636
- const stopped = Promise.race([track.closed, stream.reader.closed]).then(() => null);
746
+ const stopped = race([track.closed, stream.reader.closed]).then(() => null);
637
747
  let lastSent = {
638
748
  priority: msg.priority,
639
- ordered: msg.ordered,
640
- latencyMax: msg.maxLatency,
641
- startGroup: msg.startGroup,
642
- endGroup: msg.endGroup,
749
+ maxAge: Time.Milli(msg.maxAge),
750
+ groups: {
751
+ start: msg.startGroup === undefined ? undefined : { included: msg.startGroup },
752
+ end: msg.endGroup === undefined ? undefined : { excluded: exclusiveGroupEnd(msg.endGroup) ?? 0 },
753
+ },
643
754
  };
644
755
  for (;;) {
645
756
  const current = track.subscription.peek();
646
757
  if (current === undefined || this.#sameSubscription(current, lastSent)) {
647
758
  // Nothing new to send; wait for a change or termination.
648
- const next = await Promise.race([track.subscription.changed(), stopped]);
759
+ const next = await race([track.subscription.changed(), stopped]);
649
760
  if (next === null)
650
761
  return;
651
762
  continue;
652
763
  }
764
+ // Demand collapsing to nothing is refused the same way an initial empty
765
+ // request is: the error closes the track, so every local subscriber sees it.
766
+ const bounds = groupBounds(current.groups);
767
+ if (emptyRange({ startGroup: bounds.start, endGroup: bounds.end }))
768
+ throw new Error(EMPTY_RANGE);
769
+ // Round-trip the other Subscribe parameters so the publisher doesn't
770
+ // interpret SUBSCRIBE_UPDATE as a reset of ordered/maxAge/etc.
653
771
  const update = new SubscribeUpdate({
654
772
  priority: current.priority ?? 0,
655
- ordered: current.ordered,
656
- maxLatency: current.latencyMax,
657
- startGroup: current.startGroup,
658
- endGroup: current.endGroup,
773
+ maxAge: current.maxAge,
774
+ startGroup: current.groups?.start === undefined ? undefined : bounds.start,
775
+ endGroup: inclusiveGroupEnd(bounds.end),
659
776
  });
660
777
  await update.encode(stream.writer, this.version);
661
778
  lastSent = { ...current };
@@ -663,11 +780,12 @@ export class Subscriber {
663
780
  }
664
781
  }
665
782
  #sameSubscription(a, b) {
783
+ const ag = groupBounds(a.groups);
784
+ const bg = groupBounds(b.groups);
666
785
  return ((a.priority ?? 0) === (b.priority ?? 0) &&
667
- (a.ordered ?? false) === (b.ordered ?? false) &&
668
- (a.latencyMax ?? 0) === (b.latencyMax ?? 0) &&
669
- a.startGroup === b.startGroup &&
670
- a.endGroup === b.endGroup);
786
+ (a.maxAge ?? 0) === (b.maxAge ?? 0) &&
787
+ ag.start === bg.start &&
788
+ ag.end === bg.end);
671
789
  }
672
790
  /**
673
791
  * Handles a group message.
@@ -684,10 +802,11 @@ export class Subscriber {
684
802
  }
685
803
  return;
686
804
  }
687
- const { track, timescale } = entry;
805
+ const { track, timescale, tail } = entry;
688
806
  const producer = new netGroup.Producer(group.sequence);
689
- track.writeGroup(producer);
807
+ const read = tail.open(group.sequence);
690
808
  try {
809
+ track.writeGroup(producer);
691
810
  // Block until the timescale is known; the group's stream can arrive before
692
811
  // TRACK_INFO (or implicit defaults) resolves it on the subscribe stream.
693
812
  let scale = timescale.peek();
@@ -695,7 +814,7 @@ export class Subscriber {
695
814
  if (track.closed.peek() !== undefined) {
696
815
  // Subscription ended before the scale resolved; nothing to decode.
697
816
  producer.close();
698
- stream.stop(new Error("cancel"));
817
+ stream.stop(new StreamError(StreamCode.Cancel, { message: "cancel" }));
699
818
  return;
700
819
  }
701
820
  await Signal.race(timescale, track.closed);
@@ -706,7 +825,9 @@ export class Subscriber {
706
825
  // Scale 0 (pre-lite-05) carries no timestamp, so we wall-clock-stamp.
707
826
  let prevTs = 0n;
708
827
  for (;;) {
709
- const done = await Promise.race([stream.done(), track.closed, producer.closed]);
828
+ // Only the group's own stream ends it: a track that closes first has already
829
+ // closed (or aborted) this group through its cache.
830
+ const done = await race([stream.done(), producer.closed]);
710
831
  if (done !== false)
711
832
  break;
712
833
  let timestamp;
@@ -724,13 +845,16 @@ export class Subscriber {
724
845
  producer.writeFrame({ payload, timestamp });
725
846
  }
726
847
  producer.close();
727
- stream.stop(new Error("cancel"));
848
+ stream.stop(new StreamError(StreamCode.Cancel, { message: "cancel" }));
728
849
  }
729
850
  catch (err) {
730
851
  const e = error(err);
731
852
  producer.close(e);
732
853
  stream.stop(e);
733
854
  }
855
+ finally {
856
+ read();
857
+ }
734
858
  }
735
859
  /**
736
860
  * Receives QUIC datagrams and routes each to its subscription's track producer (lite-05 §6.4).
@@ -793,7 +917,9 @@ export class Subscriber {
793
917
  if (!scale)
794
918
  return;
795
919
  const timestamp = new Time.Timestamp(dg.timestamp, Time.Timescale(scale));
796
- entry.track.writeDatagram({ sequence: dg.sequence, timestamp, payload: dg.payload });
920
+ // A datagram's sequence is never owed a stream, so it never holds the tail open.
921
+ entry.tail.account(dg.sequence, dg.sequence + 1);
922
+ entry.track.insertDatagram(dg.sequence, timestamp, dg.payload);
797
923
  }
798
924
  /**
799
925
  * Opens a PROBE bidi stream to receive bandwidth estimates from the publisher.
@@ -861,16 +987,20 @@ export class Subscriber {
861
987
  this.#probe.set({});
862
988
  }
863
989
  }
864
- close() {
990
+ /**
991
+ * Ends every subscribed track: cleanly for a deliberate close, or with `err` when the
992
+ * session died, since those tracks were cut off rather than ended.
993
+ */
994
+ close(err) {
865
995
  this.#closed.abort();
866
996
  for (const { track } of this.#subscribes.values()) {
867
- track.close();
997
+ track.close(err);
868
998
  }
869
999
  this.#subscribes.clear();
870
1000
  }
871
1001
  }
872
1002
  /**
873
- * A broadcast consumed from a lite session. It resolves `track.Consumer.info()` and
1003
+ * A broadcast consumed from a lite session. It resolves `track.Consumer.query()` and
874
1004
  * `.fetchGroup()` over the wire (lite-05+ TRACK / FETCH streams) by reaching into the
875
1005
  * {@link Subscriber} it was opened from, the way the Rust `BroadcastConsumer` holds its
876
1006
  * session. Live subscribes still flow through the inherited requested() queue.
@@ -880,6 +1010,10 @@ class ConsumeBroadcast extends broadcast.Consumer {
880
1010
  #path;
881
1011
  constructor(subscriber, path, state) {
882
1012
  super(state);
1013
+ overrideBroadcastWire(this, {
1014
+ resolveTrackInfo: (name) => subscriber.resolveTrackInfo(path, name),
1015
+ fetchGroup: (name, sequence, options) => subscriber.fetchGroup(path, name, sequence, options),
1016
+ });
883
1017
  this.#subscriber = subscriber;
884
1018
  this.#path = path;
885
1019
  }
@@ -888,11 +1022,5 @@ class ConsumeBroadcast extends broadcast.Consumer {
888
1022
  clone() {
889
1023
  return new ConsumeBroadcast(this.#subscriber, this.#path, this.shareState());
890
1024
  }
891
- resolveTrackInfo(name) {
892
- return this.#subscriber.resolveTrackInfo(this.#path, name);
893
- }
894
- fetchGroup(name, sequence, options) {
895
- return this.#subscriber.fetchGroup(this.#path, name, sequence, options);
896
- }
897
1025
  }
898
1026
  //# sourceMappingURL=subscriber.js.map