@moq/net 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/announce.d.ts +7 -0
  2. package/announce.d.ts.map +1 -0
  3. package/announce.js +8 -0
  4. package/announce.js.map +1 -0
  5. package/announced.d.ts +35 -91
  6. package/announced.d.ts.map +1 -1
  7. package/announced.js +21 -156
  8. package/announced.js.map +1 -1
  9. package/bandwidth.d.ts +163 -0
  10. package/bandwidth.d.ts.map +1 -0
  11. package/bandwidth.js +304 -0
  12. package/bandwidth.js.map +1 -0
  13. package/bandwidth_api.d.ts +7 -0
  14. package/bandwidth_api.d.ts.map +1 -0
  15. package/bandwidth_api.js +8 -0
  16. package/bandwidth_api.js.map +1 -0
  17. package/broadcast.d.ts +20 -28
  18. package/broadcast.d.ts.map +1 -1
  19. package/broadcast.js +55 -38
  20. package/broadcast.js.map +1 -1
  21. package/connection/accept.d.ts +16 -1
  22. package/connection/accept.d.ts.map +1 -1
  23. package/connection/accept.js +39 -24
  24. package/connection/accept.js.map +1 -1
  25. package/connection/browser.d.ts.map +1 -1
  26. package/connection/browser.js +9 -7
  27. package/connection/browser.js.map +1 -1
  28. package/connection/connect.d.ts +30 -6
  29. package/connection/connect.d.ts.map +1 -1
  30. package/connection/connect.js +85 -45
  31. package/connection/connect.js.map +1 -1
  32. package/connection/established.d.ts +16 -21
  33. package/connection/established.d.ts.map +1 -1
  34. package/connection/established.js.map +1 -1
  35. package/connection/forward.d.ts +2 -0
  36. package/connection/forward.d.ts.map +1 -0
  37. package/connection/forward.js +159 -0
  38. package/connection/forward.js.map +1 -0
  39. package/connection/handshake.d.ts.map +1 -1
  40. package/connection/handshake.js +2 -2
  41. package/connection/handshake.js.map +1 -1
  42. package/connection/index.d.ts +5 -5
  43. package/connection/index.d.ts.map +1 -1
  44. package/connection/index.js +4 -5
  45. package/connection/index.js.map +1 -1
  46. package/connection/pool.d.ts +188 -0
  47. package/connection/pool.d.ts.map +1 -0
  48. package/connection/pool.js +351 -0
  49. package/connection/pool.js.map +1 -0
  50. package/connection/reload.d.ts +14 -93
  51. package/connection/reload.d.ts.map +1 -1
  52. package/connection/reload.js +216 -80
  53. package/connection/reload.js.map +1 -1
  54. package/connection/stats.d.ts +3 -26
  55. package/connection/stats.d.ts.map +1 -1
  56. package/connection/stats.js.map +1 -1
  57. package/connection/transport.d.ts +0 -7
  58. package/connection/transport.d.ts.map +1 -1
  59. package/consume.d.ts +1 -43
  60. package/consume.d.ts.map +1 -1
  61. package/consume.js +1 -1
  62. package/consume.js.map +1 -1
  63. package/error.d.ts +180 -29
  64. package/error.d.ts.map +1 -1
  65. package/error.js +310 -16
  66. package/error.js.map +1 -1
  67. package/errors.d.ts +7 -0
  68. package/errors.d.ts.map +1 -0
  69. package/errors.js +8 -0
  70. package/errors.js.map +1 -0
  71. package/group.d.ts +9 -43
  72. package/group.d.ts.map +1 -1
  73. package/group.js +283 -69
  74. package/group.js.map +1 -1
  75. package/hop.d.ts +107 -0
  76. package/hop.d.ts.map +1 -0
  77. package/hop.js +103 -0
  78. package/hop.js.map +1 -0
  79. package/ietf/aliases.d.ts +1 -78
  80. package/ietf/aliases.d.ts.map +1 -1
  81. package/ietf/cluster.d.ts +6 -120
  82. package/ietf/cluster.d.ts.map +1 -1
  83. package/ietf/cluster.js +81 -41
  84. package/ietf/cluster.js.map +1 -1
  85. package/ietf/connection.d.ts +6 -72
  86. package/ietf/connection.d.ts.map +1 -1
  87. package/ietf/connection.js +11 -47
  88. package/ietf/connection.js.map +1 -1
  89. package/ietf/error.d.ts +11 -0
  90. package/ietf/error.d.ts.map +1 -0
  91. package/ietf/error.js +168 -0
  92. package/ietf/error.js.map +1 -0
  93. package/ietf/filter.d.ts.map +1 -1
  94. package/ietf/filter.js +6 -1
  95. package/ietf/filter.js.map +1 -1
  96. package/ietf/goaway.d.ts.map +1 -1
  97. package/ietf/goaway.js +22 -5
  98. package/ietf/goaway.js.map +1 -1
  99. package/ietf/parameters.d.ts +2 -2
  100. package/ietf/parameters.d.ts.map +1 -1
  101. package/ietf/parameters.js +15 -17
  102. package/ietf/parameters.js.map +1 -1
  103. package/ietf/publish_namespace.d.ts +25 -0
  104. package/ietf/publish_namespace.d.ts.map +1 -1
  105. package/ietf/publish_namespace.js +63 -0
  106. package/ietf/publish_namespace.js.map +1 -1
  107. package/ietf/publisher.d.ts +1 -82
  108. package/ietf/publisher.d.ts.map +1 -1
  109. package/ietf/publisher.js +203 -136
  110. package/ietf/publisher.js.map +1 -1
  111. package/ietf/solicit.d.ts +1 -40
  112. package/ietf/solicit.d.ts.map +1 -1
  113. package/ietf/subscribe.d.ts +1 -5
  114. package/ietf/subscribe.d.ts.map +1 -1
  115. package/ietf/subscribe.js +8 -9
  116. package/ietf/subscribe.js.map +1 -1
  117. package/ietf/subscriber.d.ts +1 -65
  118. package/ietf/subscriber.d.ts.map +1 -1
  119. package/ietf/subscriber.js +154 -73
  120. package/ietf/subscriber.js.map +1 -1
  121. package/ietf/version.d.ts +12 -1
  122. package/ietf/version.d.ts.map +1 -1
  123. package/ietf/version.js +13 -0
  124. package/ietf/version.js.map +1 -1
  125. package/index.d.ts +11 -6
  126. package/index.d.ts.map +1 -1
  127. package/index.js +10 -5
  128. package/index.js.map +1 -1
  129. package/internal.d.ts +97 -1
  130. package/internal.d.ts.map +1 -1
  131. package/internal.js +65 -0
  132. package/internal.js.map +1 -1
  133. package/lite/announce.d.ts +15 -9
  134. package/lite/announce.d.ts.map +1 -1
  135. package/lite/announce.js +47 -20
  136. package/lite/announce.js.map +1 -1
  137. package/lite/connection.d.ts +9 -59
  138. package/lite/connection.d.ts.map +1 -1
  139. package/lite/connection.js +20 -32
  140. package/lite/connection.js.map +1 -1
  141. package/lite/fetch.d.ts +15 -1
  142. package/lite/fetch.d.ts.map +1 -1
  143. package/lite/fetch.js +39 -7
  144. package/lite/fetch.js.map +1 -1
  145. package/lite/goaway.d.ts.map +1 -1
  146. package/lite/goaway.js +7 -1
  147. package/lite/goaway.js.map +1 -1
  148. package/lite/group.d.ts +18 -4
  149. package/lite/group.d.ts.map +1 -1
  150. package/lite/group.js +31 -10
  151. package/lite/group.js.map +1 -1
  152. package/lite/priority.d.ts +1 -61
  153. package/lite/priority.d.ts.map +1 -1
  154. package/lite/priority.js +4 -5
  155. package/lite/priority.js.map +1 -1
  156. package/lite/publisher.d.ts +1 -69
  157. package/lite/publisher.d.ts.map +1 -1
  158. package/lite/publisher.js +507 -200
  159. package/lite/publisher.js.map +1 -1
  160. package/lite/setup.d.ts +7 -7
  161. package/lite/setup.d.ts.map +1 -1
  162. package/lite/setup.js +13 -13
  163. package/lite/setup.js.map +1 -1
  164. package/lite/subscribe.d.ts +61 -13
  165. package/lite/subscribe.d.ts.map +1 -1
  166. package/lite/subscribe.js +186 -44
  167. package/lite/subscribe.js.map +1 -1
  168. package/lite/subscriber.d.ts +8 -57
  169. package/lite/subscriber.d.ts.map +1 -1
  170. package/lite/subscriber.js +179 -117
  171. package/lite/subscriber.js.map +1 -1
  172. package/lite/track.d.ts +4 -10
  173. package/lite/track.d.ts.map +1 -1
  174. package/lite/track.js +34 -29
  175. package/lite/track.js.map +1 -1
  176. package/lite/version.d.ts +31 -6
  177. package/lite/version.d.ts.map +1 -1
  178. package/lite/version.js +71 -11
  179. package/lite/version.js.map +1 -1
  180. package/origin.d.ts +229 -29
  181. package/origin.d.ts.map +1 -1
  182. package/origin.js +1087 -37
  183. package/origin.js.map +1 -1
  184. package/package.json +3 -2
  185. package/path.d.ts +25 -7
  186. package/path.d.ts.map +1 -1
  187. package/path.js +5 -3
  188. package/path.js.map +1 -1
  189. package/stream.d.ts.map +1 -1
  190. package/stream.js +23 -14
  191. package/stream.js.map +1 -1
  192. package/time.d.ts +15 -2
  193. package/time.d.ts.map +1 -1
  194. package/time.js +28 -9
  195. package/time.js.map +1 -1
  196. package/track.d.ts +166 -83
  197. package/track.d.ts.map +1 -1
  198. package/track.js +617 -187
  199. package/track.js.map +1 -1
  200. package/wire.d.ts +67 -0
  201. package/wire.d.ts.map +1 -0
  202. package/wire.js +32 -0
  203. package/wire.js.map +1 -0
  204. package/zod.d.ts +1 -1
  205. package/zod.d.ts.map +1 -1
  206. package/zod.js.map +1 -1
  207. package/mock.d.ts +0 -66
  208. package/mock.d.ts.map +0 -1
  209. package/mock.js +0 -243
  210. package/mock.js.map +0 -1
package/track.js CHANGED
@@ -5,19 +5,18 @@
5
5
  * @module
6
6
  */
7
7
  import { Once, Signal } from "@moq/signals";
8
- import { Producer as GroupProducer, Lagged } from "./group.js";
9
- import { hooks } from "./internal.js";
10
- import { Timescale } from "./time.js";
11
- /** Default {@link Info.latencyMax} window (milliseconds) when the publisher does not set one. */
12
- export const DEFAULT_LATENCY_MAX_MS = 5000;
13
- /**
14
- * How long (milliseconds) a datagram stays in the per-subscriber buffer before it is dropped.
15
- *
16
- * Datagrams are a best-effort send buffer, not a replay cache (unlike groups): only the last few
17
- * tens of milliseconds are kept, so a consumer that stalls loses stale datagrams instead of
18
- * replaying them. Mirrors the Rust `MAX_DATAGRAM_AGE`.
19
- */
20
- const MAX_DATAGRAM_AGE_MS = 50;
8
+ import { GroupTooLarge, TooFarBehind } from "./error.js";
9
+ import { Producer as GroupProducer } from "./group.js";
10
+ import { groupBounds, hooks, } from "./internal.js";
11
+ import { Milli, Timescale } from "./time.js";
12
+ import { registerTrackConsumer } from "./wire.js";
13
+ // The largest delay setTimeout keeps: anything more truncates to a signed 32-bit int
14
+ // and fires right away.
15
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
16
+ /** Default {@link Info.maxAge} window (milliseconds) when the publisher does not set one. */
17
+ export const DEFAULT_MAX_AGE_MS = Milli(5000);
18
+ /** Maximum buffered datagrams per subscriber; mirrors Rust's bounded send buffer. */
19
+ const MAX_DATAGRAMS = 64;
21
20
  /**
22
21
  * Sanity cap on a datagram payload: the QUIC DATAGRAM frame ceiling. The real limit is
23
22
  * per-hop (the negotiated transport datagram size minus a small header) and oversize
@@ -30,30 +29,41 @@ const MAX_DATAGRAM_BYTES = 65535;
30
29
  // millisecond is expected; ceil rather than round, because a budget shortened by rounding
31
30
  // skips a group the subscriber still wants. Anything that is not a duration is refused
32
31
  // here, where the field is named, rather than deep in the encoder.
33
- function latencyMaxMillis(value) {
32
+ function maxAgeMillis(value) {
34
33
  if (!Number.isFinite(value) || value < 0) {
35
- throw new RangeError(`latencyMax must be a non-negative number of milliseconds: ${value}`);
34
+ throw new RangeError(`maxAge must be a non-negative number of milliseconds: ${value}`);
35
+ }
36
+ const millis = Math.ceil(value);
37
+ if (!Number.isSafeInteger(millis)) {
38
+ throw new RangeError(`maxAge exceeds the safe integer millisecond range: ${value}`);
39
+ }
40
+ return Milli(millis);
41
+ }
42
+ function priorityByte(value) {
43
+ if (!Number.isInteger(value) || value < 0 || value > 255) {
44
+ throw new RangeError(`priority must be an integer in 0..=255: ${value}`);
36
45
  }
37
- return Math.ceil(value);
46
+ return value;
38
47
  }
39
48
  /** Fill in any unset {@link Info} fields with their defaults. */
40
49
  export function infoDefaults(info = {}) {
41
50
  return {
42
- timescale: info.timescale ?? Timescale.MILLI,
43
- latencyMax: latencyMaxMillis(info.latencyMax ?? DEFAULT_LATENCY_MAX_MS),
44
- priority: info.priority ?? 0,
45
- ordered: info.ordered ?? false,
51
+ timescale: Timescale(info.timescale ?? Timescale.MILLI),
52
+ maxAge: maxAgeMillis(info.maxAge ?? DEFAULT_MAX_AGE_MS),
53
+ priority: priorityByte(info.priority ?? 0),
46
54
  };
47
55
  }
48
56
  // Materialize the defaults at the model boundary so every layer observes a complete
49
57
  // subscription rather than interpreting an omitted field differently.
50
58
  function subscriptionDefaults(subscription = {}) {
59
+ const bounds = groupBounds(subscription.groups ?? {});
51
60
  return {
52
- priority: subscription.priority ?? 0,
53
- ordered: subscription.ordered ?? false,
54
- latencyMax: latencyMaxMillis(subscription.latencyMax ?? 0),
55
- startGroup: subscription.startGroup,
56
- endGroup: subscription.endGroup,
61
+ priority: priorityByte(subscription.priority ?? 0),
62
+ maxAge: maxAgeMillis(subscription.maxAge ?? Milli.zero),
63
+ groups: {
64
+ start: subscription.groups?.start === undefined ? undefined : { included: bounds.start },
65
+ end: bounds.end === undefined ? undefined : { excluded: bounds.end },
66
+ },
57
67
  };
58
68
  }
59
69
  // Aggregate the preferences of every live subscriber, matching Rust's Subscription::poll_combined.
@@ -68,25 +78,22 @@ function combineSubscriptions(states) {
68
78
  continue;
69
79
  }
70
80
  combined.priority = Math.max(combined.priority ?? 0, subscription.priority ?? 0);
71
- combined.ordered = (combined.ordered ?? false) && (subscription.ordered ?? false);
72
- combined.latencyMax = Math.max(combined.latencyMax ?? 0, subscription.latencyMax ?? 0);
73
- if (subscription.startGroup !== undefined) {
74
- combined.startGroup =
75
- combined.startGroup === undefined
76
- ? subscription.startGroup
77
- : Math.min(combined.startGroup, subscription.startGroup);
78
- }
79
- if (combined.endGroup === undefined || subscription.endGroup === undefined) {
80
- combined.endGroup = undefined;
81
- }
82
- else {
83
- combined.endGroup = Math.max(combined.endGroup, subscription.endGroup);
84
- }
81
+ combined.maxAge = Milli(Math.max(combined.maxAge ?? Milli.zero, subscription.maxAge ?? Milli.zero));
82
+ // A floor only restricts, so a subscriber without one clears the aggregate:
83
+ // its budget may reach below any floor the others set.
84
+ const a = groupBounds(combined.groups ?? {});
85
+ const b = groupBounds(subscription.groups ?? {});
86
+ combined.groups = {
87
+ start: combined.groups?.start === undefined || subscription.groups?.start === undefined
88
+ ? undefined
89
+ : { included: Math.min(a.start, b.start) },
90
+ end: a.end === undefined || b.end === undefined ? undefined : { excluded: Math.max(a.end, b.end) },
91
+ };
85
92
  }
86
93
  return combined;
87
94
  }
88
95
  /**
89
- * A request for a track the peer wants, yielded by `Broadcast.Producer.requested`.
96
+ * A request for a track the peer wants, delivered to the publishing wire layer.
90
97
  *
91
98
  * Created internally by the broadcast when a subscription (or info lookup) needs a track
92
99
  * served; answer it with {@link accept} or {@link reject}.
@@ -142,7 +149,17 @@ export class Consumer {
142
149
  this.name = name;
143
150
  this.#broadcast = broadcast;
144
151
  }
145
- /** Open a live subscription to the track. */
152
+ static {
153
+ registerTrackConsumer((name, broadcast) => new Consumer(name, broadcast));
154
+ }
155
+ /**
156
+ * Open a live subscription to the track.
157
+ *
158
+ * The cursor starts at the group the subscription named (its floor), or 0.
159
+ * {@link Subscription.maxAge} is what asks for data: delivery skips everything above
160
+ * the floor that the budget convicts, so the default budget of zero delivers only the
161
+ * latest group and a larger one reaches back over what it can still use.
162
+ */
146
163
  subscribe(options) {
147
164
  return this.#broadcast.subscribe(this.name, options);
148
165
  }
@@ -161,9 +178,22 @@ class TrackState {
161
178
  /** The producer fanning into this sink, so a subscriber can mint a sibling of itself. */
162
179
  producer;
163
180
  groups = new Signal([]);
164
- /** Best-effort datagram channel, parallel to {@link groups}; an age-evicted send buffer per subscriber. */
181
+ // Every group still in the producer's replay cache, including groups this
182
+ // subscriber already consumed, paired with its source queue time. Drift anchors
183
+ // have the same lifetime as content.
184
+ timeline = new Map();
185
+ // First timestamps mutate group state rather than track state, so held groups
186
+ // watch this revision as well as arrivals when enforcing latency after handoff.
187
+ timelineChanged = new Signal(0);
188
+ /** Best-effort datagram channel, parallel to {@link groups}; a bounded send buffer per subscriber. */
165
189
  datagrams = new Signal([]);
166
190
  latest;
191
+ /**
192
+ * The exclusive final boundary, stamped when the producer closes cleanly: one past the
193
+ * highest sequence produced. Groups and datagrams share the namespace, so this can
194
+ * exceed `latest + 1` (which only tracks groups). Mirrors the Rust `final_sequence`.
195
+ */
196
+ final;
167
197
  closed = new Once();
168
198
  update;
169
199
  /** Resolved once the producer commits the immutable properties. */
@@ -207,6 +237,11 @@ function bindProducer(name, producer, sequences) {
207
237
  bindProducerSequence(producer, shared);
208
238
  }
209
239
  let bindProducerSequence;
240
+ // The sequence-order cursor lives inside `Subscriber` (it shares the group buffer and the
241
+ // drift anchor with the arrival cursor), so `Ordered` reaches it through this bridge,
242
+ // assigned in the class's static block.
243
+ let makeOrdered;
244
+ let ordered_;
210
245
  // Constructs a Subscriber from within this module without exposing a public
211
246
  // constructor that would leak the unexported TrackState. Assigned in the class's
212
247
  // static block.
@@ -218,7 +253,7 @@ let makeSubscriber;
218
253
  * subscription the publisher serves from it) gets an independent
219
254
  * {@link Subscriber} that receives a full copy of the groups, each with its own
220
255
  * read cursor. Groups are mirrored into every live subscriber and retained for the
221
- * track's `latencyMax` window so a late subscriber replays the recent groups.
256
+ * track's `maxAge` window so a late subscriber replays the recent groups.
222
257
  *
223
258
  * Obtained from {@link Request.accept} (the wire asks the application for a track to
224
259
  * serve) or constructed directly for an in-process track.
@@ -231,10 +266,14 @@ export class Producer {
231
266
  #state = new TrackState();
232
267
  #sequence = { next: 0 };
233
268
  // Recently written source groups, retained for replay to late subscribers and
234
- // pruned once closed and older than the cache window. Each entry tracks the mirror
269
+ // pruned once idle for longer than the cache window. Each entry tracks the mirror
235
270
  // it handed to every sink so eviction can drop them too: otherwise a slow consumer
236
271
  // that never reads would pin old groups (and their frame bytes) forever.
237
272
  #cache = [];
273
+ // Wakeup for the next entry due to age out. Writes settle retention inline, but a
274
+ // publisher that stalls stops writing, so without this an abandoned group (and any
275
+ // reader parked in it) would wait for a write that never comes.
276
+ #pruneTimer;
238
277
  // One independent downstream state per live subscriber.
239
278
  #sinks = new Set();
240
279
  // Whether any subscriber is currently attached. Exposed as {@link used}; the consumer wire
@@ -255,6 +294,15 @@ export class Producer {
255
294
  info() {
256
295
  return resolveInfo(this.#state);
257
296
  }
297
+ /**
298
+ * Publisher priority from the committed {@link Info}, or 0 before {@link accept}.
299
+ *
300
+ * Higher is served first. Hang publishers set this from `Catalog.PRIORITY` so
301
+ * audio outranks video on the wire and in the bandwidth allocator.
302
+ */
303
+ get priority() {
304
+ return this.#state.info.peek()?.priority ?? 0;
305
+ }
258
306
  /**
259
307
  * Settles once the track closes: `null` on a clean close, or the abort {@link Error}.
260
308
  * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
@@ -278,9 +326,17 @@ export class Producer {
278
326
  // Propagate to any sink handed out before accept (the on-demand path).
279
327
  for (const sink of this.#sinks)
280
328
  sink.info.set(resolved);
329
+ this.#updateSubscription();
281
330
  return this;
282
331
  }
283
- /** An independent {@link Subscriber} receiving a full copy of this track's groups. */
332
+ /**
333
+ * An independent {@link Subscriber} reading this track's groups.
334
+ *
335
+ * Its cursor starts at the group the subscription named (its floor), or 0.
336
+ * {@link Subscription.maxAge} is what asks for data: delivery skips everything above
337
+ * the floor that the budget convicts, so the default budget of zero delivers only the
338
+ * latest group and a larger one reaches back over what it can still use.
339
+ */
284
340
  subscribe(options = {}) {
285
341
  const sink = new TrackState(options);
286
342
  this.#addSink(sink);
@@ -347,13 +403,19 @@ export class Producer {
347
403
  this.#prune();
348
404
  for (const entry of this.#cache)
349
405
  this.#mirror(entry, sink);
350
- if (closed !== undefined)
406
+ if (closed !== undefined) {
407
+ sink.final = this.#state.final;
351
408
  closeTrackState(sink, closed instanceof Error ? closed : undefined);
409
+ }
352
410
  }
353
411
  // Recompute from every live sink because an update or close can narrow as well as widen
354
412
  // the aggregate. The wire layer observes this signal and emits SUBSCRIBE_UPDATE.
355
413
  #updateSubscription() {
356
- this.#state.update.set(combineSubscriptions(this.#sinks));
414
+ const combined = combineSubscriptions(this.#sinks);
415
+ const retained = this.#state.info.peek()?.maxAge;
416
+ if (combined && retained !== undefined)
417
+ combined.maxAge = Milli.min(combined.maxAge ?? Milli.zero, retained);
418
+ this.#state.update.set(combined);
357
419
  }
358
420
  // Mirror a cached source group into a sink. The mirror fills synchronously as the
359
421
  // source is written and keeps its own read cursor; frame bytes are shared by
@@ -361,6 +423,8 @@ export class Producer {
361
423
  #mirror(entry, sink) {
362
424
  const dst = entry.group.mirror();
363
425
  entry.mirrors.set(sink, dst);
426
+ sink.timeline.set(dst.sequence, { group: dst, time: entry.time });
427
+ void dst.readable().then(() => sink.timelineChanged.update((revision) => revision + 1));
364
428
  sink.latest = Math.max(sink.latest ?? 0, dst.sequence);
365
429
  sink.groups.mutate((groups) => {
366
430
  groups.push(dst);
@@ -369,37 +433,93 @@ export class Producer {
369
433
  }
370
434
  // Drop a cached group's mirror from every sink so no consumer can pin it.
371
435
  #evict(entry) {
436
+ // Reclaiming a group the publisher never closed ends it as the gap it is, before
437
+ // the mirrors below would otherwise report a clean finish to a reader that had
438
+ // drained it. The usual case, an already-closed group aging out, keeps its own
439
+ // terminal state.
440
+ if (!entry.group.isClosed)
441
+ entry.group.close(new TooFarBehind());
372
442
  for (const [sink, mirror] of entry.mirrors) {
443
+ hooks.evictGroup(mirror);
373
444
  sink.groups.mutate((groups) => {
374
445
  const i = groups.indexOf(mirror);
375
446
  if (i >= 0)
376
447
  groups.splice(i, 1);
377
448
  });
449
+ if (sink.timeline.get(mirror.sequence)?.group === mirror)
450
+ sink.timeline.delete(mirror.sequence);
378
451
  mirror.close();
379
452
  }
380
453
  entry.mirrors.clear();
381
454
  }
382
- // Evict cached groups that are closed and older than the cache window.
455
+ // The one group retention never takes: the newest, while it is still open. That is
456
+ // the live edge a publisher is appending to, and a track may legitimately keep it
457
+ // open across a long quiet stretch (a catalog snapshot, a JSON stream). Every other
458
+ // open group is an abandoned one, and ages out like a closed one.
459
+ #liveEdge() {
460
+ const latest = this.#cache.at(-1)?.group;
461
+ return latest?.closed.peek() === undefined ? latest : undefined;
462
+ }
463
+ // Evict cached groups idle for longer than the cache window. Idle means nothing
464
+ // written, so an abandoned open group ages out instead of pinning its buffer (and
465
+ // any reader parked in it) forever.
383
466
  #prune() {
384
- const latencyMaxMs = this.#state.info.peek()?.latencyMax ?? DEFAULT_LATENCY_MAX_MS;
385
- const cutoff = Date.now() - latencyMaxMs;
467
+ const maxAgeMs = this.#state.info.peek()?.maxAge ?? DEFAULT_MAX_AGE_MS;
468
+ const cutoff = performance.now() - maxAgeMs;
469
+ const live = this.#liveEdge();
386
470
  const retained = [];
387
471
  for (const entry of this.#cache) {
388
- if (entry.time > cutoff || entry.group.closed.peek() === undefined) {
472
+ if (entry.group === live || entry.group.activity >= cutoff) {
389
473
  retained.push(entry);
390
474
  continue;
391
475
  }
392
476
  this.#evict(entry);
393
477
  }
394
478
  this.#cache = retained;
479
+ this.#schedulePrune();
480
+ }
481
+ // Arm the wakeup for the next entry due to age out, replacing any pending one.
482
+ // Writes settle retention inline, so this only has to cover the case no write
483
+ // follows. Cheap to over-arm: an entry written since is retained and re-armed.
484
+ #schedulePrune() {
485
+ clearTimeout(this.#pruneTimer);
486
+ this.#pruneTimer = undefined;
487
+ if (this.#state.closed.peek() !== undefined)
488
+ return;
489
+ // One pass, no intermediate arrays: this runs on every publish, and a spread
490
+ // over the cache would also cap how many groups a track can hold.
491
+ const live = this.#liveEdge();
492
+ let oldest;
493
+ for (const entry of this.#cache) {
494
+ if (entry.group === live)
495
+ continue;
496
+ if (oldest === undefined || entry.group.activity < oldest)
497
+ oldest = entry.group.activity;
498
+ }
499
+ if (oldest === undefined)
500
+ return;
501
+ const maxAgeMs = this.#state.info.peek()?.maxAge ?? DEFAULT_MAX_AGE_MS;
502
+ // setTimeout truncates its delay to a signed 32-bit int, so a longer window
503
+ // would fire immediately and spin. Wake at the cap instead and re-arm: #prune
504
+ // retains anything still fresh, so the extra wakeups are the only cost.
505
+ const delay = Math.min(MAX_TIMEOUT_MS, Math.max(0, oldest + maxAgeMs - performance.now()));
506
+ const timer = setTimeout(() => {
507
+ this.#pruneTimer = undefined;
508
+ this.#prune();
509
+ }, delay);
510
+ // A cache prune is never a reason to hold a Node/Bun process open.
511
+ timer.unref?.();
512
+ this.#pruneTimer = timer;
395
513
  }
396
514
  // Retain a source group and fan it out to every live sink.
397
515
  #publish(group) {
398
- const entry = { group, time: Date.now(), mirrors: new Map() };
516
+ const entry = { group, time: performance.now(), mirrors: new Map() };
399
517
  this.#cache.push(entry);
400
- this.#prune();
401
518
  for (const sink of this.#sinks)
402
519
  this.#mirror(entry, sink);
520
+ // Give held mirrors the new live edge before pruning their timeline entry,
521
+ // so their latency guard can preserve a terminal expiry verdict.
522
+ this.#prune();
403
523
  }
404
524
  /** Append a new group with the next sequence number. */
405
525
  appendGroup() {
@@ -441,13 +561,11 @@ export class Producer {
441
561
  // Fan a datagram out to every live subscriber, dropping the oldest once the ring is full.
442
562
  // Late subscribers do NOT replay old datagrams (best-effort, unlike the group cache).
443
563
  #publishDatagram(datagram) {
444
- const now = performance.now();
445
564
  for (const sink of this.#sinks) {
446
565
  sink.datagrams.mutate((list) => {
447
- list.push({ datagram, time: now });
448
- // Drop anything older than the send-buffer window.
449
- while (list.length > 0 && now - list[0].time > MAX_DATAGRAM_AGE_MS)
566
+ if (list.length === MAX_DATAGRAMS)
450
567
  list.shift();
568
+ list.push(datagram);
451
569
  });
452
570
  }
453
571
  }
@@ -461,7 +579,7 @@ export class Producer {
461
579
  * keep datagram payloads small (e.g. a single audio frame). Datagrams are never delivered
462
580
  * over IETF moq-transport or stream-only transports (the WebSocket fallback). A payload over
463
581
  * 65535 bytes (the QUIC datagram frame ceiling) throws. An origin publisher uses this; a
464
- * relay preserving upstream numbering uses {@link writeDatagram}.
582
+ * relay preserving upstream numbering uses {@link insertDatagram}.
465
583
  */
466
584
  appendDatagram(timestamp, payload) {
467
585
  if (this.#state.closed.peek() !== undefined)
@@ -475,26 +593,34 @@ export class Producer {
475
593
  return sequence;
476
594
  }
477
595
  /**
478
- * Write a datagram with an explicit sequence number.
596
+ * Insert a datagram with an explicit sequence number.
479
597
  *
480
598
  * Preserves the supplied sequence (advancing the shared counter if needed) so a relay can
481
599
  * forward a datagram without renumbering it. The size limits of {@link appendDatagram}
482
600
  * apply. Most origin publishers want {@link appendDatagram} instead.
483
601
  */
484
- writeDatagram(datagram) {
602
+ insertDatagram(sequence, timestamp, payload) {
485
603
  if (this.#state.closed.peek() !== undefined)
486
604
  throw new Error("track is closed");
487
- if (datagram.payload.byteLength > MAX_DATAGRAM_BYTES)
605
+ if (payload.byteLength > MAX_DATAGRAM_BYTES)
488
606
  throw new Error("datagram payload too large");
489
- const sequence = this.#sequence;
490
- if (datagram.sequence >= sequence.next) {
491
- sequence.next = datagram.sequence + 1;
607
+ const counter = this.#sequence;
608
+ if (sequence >= counter.next) {
609
+ counter.next = sequence + 1;
492
610
  }
493
- this.#publishDatagram(datagram);
611
+ this.#publishDatagram({ sequence, timestamp, payload });
494
612
  }
495
613
  /** Close the track and every subscriber, mirroring the abort to their groups. Idempotent. */
496
614
  close(abort) {
615
+ // A clean close declares the final boundary; an abort ends without one.
616
+ if (abort === undefined && this.#state.closed.peek() === undefined) {
617
+ this.#state.final = this.#sequence.next;
618
+ for (const sink of this.#sinks)
619
+ sink.final = this.#state.final;
620
+ }
497
621
  closeTrackState(this.#state, abort);
622
+ clearTimeout(this.#pruneTimer);
623
+ this.#pruneTimer = undefined;
498
624
  for (const { group } of this.#cache)
499
625
  group.close(abort);
500
626
  for (const sink of this.#sinks) {
@@ -542,12 +668,140 @@ export class Subscriber {
542
668
  #state;
543
669
  #nextSequence = 0;
544
670
  #cursor = new Signal({ start: 0 });
671
+ #enforceLatency = true;
672
+ // Which cursor owns this subscription. Both cursors draw from one buffer, so the
673
+ // first group read commits the track to arrival order and {@link ordered} commits
674
+ // it to sequence order; whichever wins is the only one allowed from here on.
675
+ // Datagrams are a separate cursor and never commit.
676
+ #mode;
677
+ // The group the frame-level helpers are currently draining, acquired through the
678
+ // sequence cursor so frame reads and {@link Ordered.nextGroup} share one floor.
679
+ #frameGroup;
680
+ #drift() {
681
+ const { end } = this.#cursor.peek();
682
+ let presentation;
683
+ for (const { group } of this.#state.timeline.values()) {
684
+ if (end !== undefined && group.sequence >= end)
685
+ continue;
686
+ if (group.closed.peek() instanceof Error)
687
+ continue;
688
+ // The edge wants the newest content that exists, so it takes the newest
689
+ // stamped group's latest frame.
690
+ const timestamp = hooks.groupTimestamp(group);
691
+ if (timestamp !== undefined && (!presentation || group.sequence > presentation.sequence)) {
692
+ presentation = { sequence: group.sequence, timestamp: hooks.groupLatest(group) ?? timestamp };
693
+ }
694
+ }
695
+ const requested = this.#state.update.peek()?.maxAge ?? 0;
696
+ const retained = this.#state.info.peek()?.maxAge;
697
+ return {
698
+ budget: this.#enforceLatency
699
+ ? retained === undefined
700
+ ? requested
701
+ : Math.min(requested, retained)
702
+ : Number.POSITIVE_INFINITY,
703
+ presentation,
704
+ end,
705
+ };
706
+ }
707
+ // The furthest presentation time the group at `sequence` could still reach: where its
708
+ // immediate servable successor begins, or undefined when nothing proves where it
709
+ // stops. An upper bound, deliberately: a frame's duration is not on the wire, so a
710
+ // group's own last timestamp says where it starts presenting, not where it ends.
711
+ // Only the *immediate* successor counts: timestamps need not rise with sequence (a
712
+ // rewind reorders them), so a later stamped group proves nothing about where an
713
+ // unstamped successor will begin, and shrinking the bound is the unsafe direction.
714
+ // An unstamped successor leaves the reach unbounded until it presents a frame.
715
+ #reach(sequence, end) {
716
+ let successor;
717
+ for (const { group } of this.#state.timeline.values()) {
718
+ if (group.sequence <= sequence)
719
+ continue;
720
+ if (end !== undefined && group.sequence >= end)
721
+ continue;
722
+ if (group.closed.peek() instanceof Error)
723
+ continue;
724
+ if (!successor || group.sequence < successor.sequence)
725
+ successor = group;
726
+ }
727
+ if (!successor)
728
+ return undefined;
729
+ return hooks.groupTimestamp(successor)?.asMillis();
730
+ }
731
+ // Whether the drift budget says to give up on `group`.
732
+ //
733
+ // Presentation time measures a group by how far it could still reach, not by how far
734
+ // behind it started. Being behind is survivable: priority transmits newer groups first,
735
+ // so a backlog bursts at whatever rate is left over and closes the gap faster than the
736
+ // live edge advances. A group is abandoned only once everything it could still present
737
+ // falls outside the budget.
738
+ //
739
+ // A group's reach is bounded by its nearest successor: it cannot present past where the
740
+ // next group begins. Its own frames say nothing, since a frame's duration is not on the
741
+ // wire, and the candidate needs no timestamp of its own: an empty group is bounded by
742
+ // its stamped successor the same way. The bound is exclusive, so the comparison is `>=`:
743
+ // the freshest frame a group could still hold sits just below its reach, so an age equal
744
+ // to the budget already puts every frame in it strictly past the budget. A zero budget
745
+ // falls out for free. Only timestamps drive expiry; wall-clock reclamation of idle
746
+ // content is the cache's own policy, not the budget's.
747
+ #isStale(group, drift) {
748
+ const candidate = this.#state.timeline.get(group.sequence);
749
+ if (candidate?.group !== group)
750
+ return false;
751
+ const reach = this.#reach(group.sequence, drift.end);
752
+ return (drift.presentation !== undefined &&
753
+ drift.presentation.sequence > group.sequence &&
754
+ reach !== undefined &&
755
+ drift.presentation.timestamp.asMillis() - reach >= drift.budget);
756
+ }
757
+ #guard(group) {
758
+ if (!this.#enforceLatency)
759
+ return group;
760
+ hooks.expireGroup(group, {
761
+ expired: () => this.#isStale(group, this.#drift()),
762
+ changed: [
763
+ this.#state.groups,
764
+ this.#state.timelineChanged,
765
+ this.#state.update,
766
+ this.#state.info,
767
+ this.#cursor,
768
+ this.#state.closed,
769
+ ],
770
+ });
771
+ return group;
772
+ }
545
773
  constructor(name, state) {
546
774
  this.name = name;
547
775
  this.#state = state;
776
+ // The cursor's floor is the group the subscription named, or 0. A floor is the
777
+ // only thing a start contributes; {@link Subscription.maxAge} is what asks for
778
+ // data, and delivery skips everything above the floor that the budget convicts.
779
+ this.#cursor.set({ start: groupBounds(state.update.peek()?.groups ?? {}).start });
548
780
  }
549
781
  static {
550
782
  makeSubscriber = (name, state) => new Subscriber(name, state);
783
+ hooks.tryRecvGroup = (subscriber) => subscriber.#tryRecvGroup();
784
+ hooks.groupChanged = (subscriber, fn) => subscriber.#groupChanged(fn);
785
+ hooks.exemptFetch = (subscriber) => {
786
+ subscriber.#enforceLatency = false;
787
+ };
788
+ hooks.replaceGroups = (subscriber, groups) => subscriber.#replaceGroups(groups);
789
+ // The sequence cursor lives here (it shares the buffer and the drift anchor with
790
+ // the arrival cursor); `Ordered` is the handle that reaches it.
791
+ ordered_ = {
792
+ nextGroup: (subscriber) => subscriber.#nextGroup(),
793
+ readFrame: (subscriber) => subscriber.#readFrame(),
794
+ readString: (subscriber) => subscriber.#readString(),
795
+ readJson: (subscriber) => subscriber.#readJson(),
796
+ readBool: (subscriber) => subscriber.#readBool(),
797
+ // Unordered either way, so both handles reach the same cursor.
798
+ recvDatagram: (subscriber) => subscriber.#recvDatagram(),
799
+ };
800
+ }
801
+ // Refuse a read on this handle once `ordered()` has taken the subscription.
802
+ #live() {
803
+ if (this.#mode === "ordered")
804
+ throw new Error("track is read in sequence order; use the Ordered handle");
551
805
  }
552
806
  /**
553
807
  * Resolve this track's immutable publisher properties.
@@ -571,6 +825,15 @@ export class Subscriber {
571
825
  latest() {
572
826
  return this.#state.latest;
573
827
  }
828
+ /**
829
+ * The track's exclusive final boundary, known once the producer closes cleanly:
830
+ * one past the highest sequence produced, or 0 for a track that produced none.
831
+ * Groups and datagrams share the sequence namespace, so this can exceed
832
+ * `latest() + 1`. Undefined while the track is live or after an abort.
833
+ */
834
+ final() {
835
+ return this.#state.final;
836
+ }
574
837
  /**
575
838
  * The newest frame this track has produced, or `undefined` while it has none.
576
839
  *
@@ -611,22 +874,33 @@ export class Subscriber {
611
874
  throw new Error("track has no producer to fork from");
612
875
  return producer.subscribe(options);
613
876
  }
614
- /** Start this subscriber's local read cursor at `sequence`, without changing its wire request. */
615
- startAt(sequence) {
616
- this.#cursor.update((cursor) => ({ ...cursor, start: sequence }));
877
+ /** Limit subsequent reads to these groups and return this reader for chaining. */
878
+ withGroups(groups) {
879
+ this.setGroups(groups);
880
+ return this;
617
881
  }
618
882
  /**
619
- * Cap {@link nextGroup} and {@link recvGroup} at `sequence` inclusively, or omit it to
620
- * remove the cap. Groups above the cap remain buffered and become readable if the cap
621
- * is raised. This local cursor does not change the subscription's wire request.
883
+ * Limit subsequent reads without rewinding read progress or changing the wire request.
884
+ * An omitted start preserves the current floor; an omitted end removes the cap.
885
+ * Raising the end makes unread buffered groups available again.
622
886
  */
623
- endAt(sequence) {
624
- this.#cursor.update((cursor) => ({ ...cursor, end: sequence }));
887
+ setGroups(groups) {
888
+ const { start, end } = groupBounds(groups);
889
+ this.#cursor.update((cursor) => ({ start: Math.max(cursor.start, start), end }));
890
+ }
891
+ // Serving counterpart of setGroups: a named start replaces the floor, matching
892
+ // Rust `start_at`. Local readers stay monotonic; only the wire publisher lowers.
893
+ #replaceGroups(groups) {
894
+ const { start, end } = groupBounds(groups);
895
+ this.#cursor.update((cursor) => ({
896
+ start: groups.start === undefined ? cursor.start : start,
897
+ end,
898
+ }));
625
899
  }
626
900
  /** Close the track (optionally with an error), closing any pending groups. Idempotent. */
627
901
  close(abort) {
628
902
  // Settle if we're first (the producer may already have); either way drop anything
629
- // still buffered. Groups parked at the endAt cap deliberately outlive a clean
903
+ // still buffered. Groups parked at the setGroups cap deliberately outlive a clean
630
904
  // producer close, so the subscriber leaving is what must release them: closing
631
905
  // and clearing wakes a pending read to observe the end instead of hanging.
632
906
  closeTrackState(this.#state, abort);
@@ -635,55 +909,102 @@ export class Subscriber {
635
909
  group.close(abort);
636
910
  groups.length = 0;
637
911
  });
912
+ this.#frameGroup?.close(abort);
913
+ this.#frameGroup = undefined;
914
+ this.#state.timeline.clear();
638
915
  }
639
916
  /**
640
917
  * Receive every group on this track exactly once, as it becomes available.
641
918
  *
642
919
  * Groups may arrive out of order or with gaps due to network conditions; unlike
643
- * {@link nextGroup}, one that arrives after a newer group was already returned is
644
- * still delivered. When several groups are buffered, the lowest sequence is
920
+ * {@link Ordered.nextGroup}, one that arrives after a newer group was already returned
921
+ * is still delivered. When several groups are buffered, the lowest sequence is
645
922
  * returned first.
646
923
  *
647
- * Honors the floor set by {@link startAt} and the cap set by {@link endAt}: a group
924
+ * Honors the range set by {@link setGroups}: a group
648
925
  * beyond the cap stays buffered (not dropped) and is offered once the cap rises, even
649
926
  * after a clean close, without blocking in-range groups that arrive behind it.
927
+ * A group whose presentation time is further behind the live edge than this
928
+ * subscriber's `maxAge` is skipped. The default of zero takes the live edge.
929
+ * The budget remains attached after return, so a pending frame read rejects if a stalled
930
+ * group becomes stale while newer data advances.
931
+ *
932
+ * The first call commits this track to arrival order: {@link ordered} throws afterwards.
650
933
  */
651
934
  async recvGroup() {
935
+ this.#live();
936
+ this.#mode = "arrival";
652
937
  for (;;) {
653
- const group = this.tryRecvGroup();
654
- if (group)
655
- return group;
656
- const closed = this.#state.closed.peek();
657
- if (closed instanceof Error)
658
- throw closed;
659
- // A group beyond the cap outlives a clean close: it becomes deliverable if
660
- // the cap rises, so the track isn't over while any are held.
661
- if (closed !== undefined && !this.#state.groups.peek()[0])
662
- return undefined;
938
+ const recv = this.#tryRecvGroup();
939
+ switch (recv.kind) {
940
+ case "group":
941
+ return recv.group;
942
+ case "done":
943
+ return undefined;
944
+ case "error":
945
+ throw recv.error;
946
+ }
947
+ // Idle, or parked at the boundary waiting for the cap to rise.
663
948
  await Signal.race(this.#state.groups, this.#cursor, this.#state.closed);
664
949
  }
665
950
  }
951
+ // Package-internal synchronous half of recvGroup. The lite publisher uses this so applying
952
+ // control state, popping the group, and positioning its frames are one JavaScript turn.
953
+ #tryRecvGroup() {
954
+ const groups = this.#state.groups.peek();
955
+ const { start, end } = this.#cursor.peek();
956
+ while (groups.length > 0 && groups[0].sequence < start)
957
+ groups.shift()?.close();
958
+ const drift = this.#drift();
959
+ for (;;) {
960
+ // The buffer is sequence-sorted, so an in-range group that arrives behind a
961
+ // beyond-cap one sorts in front of it and is never blocked by it.
962
+ const group = groups[0];
963
+ if (!group || (end !== undefined && group.sequence >= end))
964
+ break;
965
+ groups.shift();
966
+ if (this.#isStale(group, drift)) {
967
+ group.close();
968
+ continue;
969
+ }
970
+ return { kind: "group", group: this.#guard(group) };
971
+ }
972
+ const group = groups[0];
973
+ const closed = this.#state.closed.peek();
974
+ if (closed instanceof Error)
975
+ return { kind: "error", error: closed };
976
+ if (closed === undefined)
977
+ return { kind: "idle" };
978
+ // A group beyond the cap outlives a clean close: it becomes deliverable if
979
+ // the cap rises, so the track isn't over while any are held.
980
+ return group ? { kind: "boundary" } : { kind: "done" };
981
+ }
982
+ // Package-internal readiness half of recvGroup. Each registration fires at most once, and
983
+ // the caller disposes the losers after whichever source wakes it.
984
+ #groupChanged(fn) {
985
+ const dispose = [this.#state.groups.changed(fn), this.#cursor.changed(fn), this.#state.closed.changed(fn)];
986
+ return () => {
987
+ for (const close of dispose)
988
+ close();
989
+ };
990
+ }
666
991
  /**
667
992
  * Take the next buffered group without blocking, honoring the same cursor bounds as
668
993
  * {@link recvGroup}.
669
994
  *
670
995
  * Returns `undefined` when nothing is deliverable right now, which is not by itself the
671
996
  * end of the track: a group may still arrive, or one may be parked beyond the
672
- * {@link endAt} cap. Use it to drain what the retained window already holds, where
997
+ * {@link setGroups} cap. Use it to drain what the retained window already holds, where
673
998
  * waiting for a sequence nothing will republish would park forever.
674
999
  */
675
1000
  tryRecvGroup() {
676
- const groups = this.#state.groups.peek();
677
- const { start, end } = this.#cursor.peek();
678
- while (groups.length > 0 && groups[0].sequence < start)
679
- groups.shift()?.close();
680
- // The buffer is sequence-sorted, so an in-range group that arrives behind a
681
- // beyond-cap one sorts in front of it and is never blocked by it.
682
- const group = groups[0];
683
- if (group && (end === undefined || group.sequence <= end)) {
684
- groups.shift();
685
- return group;
686
- }
1001
+ this.#live();
1002
+ this.#mode = "arrival";
1003
+ const recv = this.#tryRecvGroup();
1004
+ if (recv.kind === "group")
1005
+ return recv.group;
1006
+ if (recv.kind === "error")
1007
+ throw recv.error;
687
1008
  return undefined;
688
1009
  }
689
1010
  /**
@@ -692,23 +1013,20 @@ export class Subscriber {
692
1013
  * Datagrams are a separate best-effort channel from groups (see
693
1014
  * {@link Producer.appendDatagram}); they share only the sequence namespace. A consumer
694
1015
  * that falls too far behind silently loses the oldest datagrams. Read this alongside
695
- * {@link recvGroup} (e.g. in a separate loop) to receive both channels concurrently. Returning
696
- * a datagram advances {@link nextGroup} past that sequence.
1016
+ * {@link recvGroup} (e.g. in a separate loop) to receive both channels concurrently.
1017
+ * The two cursors are independent: a datagram never moves the group cursor.
697
1018
  */
698
1019
  async recvDatagram() {
1020
+ this.#live();
1021
+ return this.#recvDatagram();
1022
+ }
1023
+ // The datagram cursor, reachable from either handle: unordered by construction, so the
1024
+ // choice of group order says nothing about it.
1025
+ async #recvDatagram() {
699
1026
  for (;;) {
700
1027
  const datagrams = this.#state.datagrams.peek();
701
- // Evict datagrams older than the send-buffer window (also enforced on write), so a
702
- // reader that stalled skips stale datagrams instead of replaying them.
703
- const cutoff = performance.now() - MAX_DATAGRAM_AGE_MS;
704
- while (datagrams.length > 0 && datagrams[0].time < cutoff)
705
- datagrams.shift();
706
1028
  if (datagrams.length > 0) {
707
- const datagram = datagrams.shift()?.datagram;
708
- if (datagram) {
709
- this.#nextSequence = Math.max(this.#nextSequence, datagram.sequence + 1);
710
- }
711
- return datagram;
1029
+ return datagrams.shift();
712
1030
  }
713
1031
  const closed = this.#state.closed.peek();
714
1032
  if (closed instanceof Error)
@@ -718,128 +1036,111 @@ export class Subscriber {
718
1036
  await Signal.race(this.#state.datagrams, this.#state.closed);
719
1037
  }
720
1038
  }
721
- /**
722
- * Return the next group with a strictly-greater sequence number than the last returned.
723
- *
724
- * Late arrivals (sequence at or below the last returned) are silently skipped.
725
- * Use {@link recvGroup} to see every group in arrival order instead.
726
- */
727
- async nextGroup() {
1039
+ // The sequence cursor behind {@link Ordered}, which owns the only public door to it.
1040
+ async #nextGroup() {
728
1041
  for (;;) {
729
1042
  const groups = this.#state.groups.peek();
730
1043
  const cursor = this.#cursor.peek();
731
1044
  const start = Math.max(cursor.start, this.#nextSequence);
732
1045
  while (groups.length > 0 && groups[0].sequence < start)
733
1046
  groups.shift()?.close();
734
- const group = groups[0];
735
- if (group && (cursor.end === undefined || group.sequence <= cursor.end)) {
1047
+ // One anchor for the whole pass, so walking a backlog off stays linear.
1048
+ const drift = this.#drift();
1049
+ for (;;) {
1050
+ const group = groups[0];
1051
+ if (!group || (cursor.end !== undefined && group.sequence >= cursor.end))
1052
+ break;
736
1053
  groups.shift();
737
1054
  this.#nextSequence = group.sequence + 1;
738
- return group;
1055
+ // Every frame this group could still hold is past the budget, so keep
1056
+ // scanning: one pass walks a whole backlog off rather than replaying it.
1057
+ if (this.#isStale(group, drift)) {
1058
+ group.close();
1059
+ continue;
1060
+ }
1061
+ // One cursor: the frame helpers must not keep draining a group this
1062
+ // read just moved past, or interleaved reads would run backwards.
1063
+ if (this.#frameGroup && this.#frameGroup.sequence < group.sequence) {
1064
+ this.#frameGroup.close();
1065
+ this.#frameGroup = undefined;
1066
+ }
1067
+ return this.#guard(group);
739
1068
  }
740
1069
  const closed = this.#state.closed.peek();
741
1070
  if (closed instanceof Error)
742
1071
  throw closed;
743
- if (closed !== undefined && !group)
1072
+ // A group parked above the cap stays deliverable even after a clean close
1073
+ // (its frames remain buffered), so keep waiting for a cap raise. Only a
1074
+ // drained track reports finished.
1075
+ if (closed !== undefined && !groups[0])
744
1076
  return undefined;
745
1077
  await Signal.race(this.#state.groups, this.#cursor, this.#state.closed);
746
1078
  }
747
1079
  }
748
1080
  /**
749
- * Reads the next frame across all groups, discarding older groups.
750
- * Treat the returned frame bytes as read-only; they are shared with other consumers.
751
- */
752
- async readFrame() {
753
- const next = await this.readFrameSequence();
754
- return next ? { payload: next.payload, timestamp: next.timestamp } : undefined;
755
- }
756
- /**
757
- * Reads the next frame along with its group and frame sequence numbers.
1081
+ * Reads the next frame across groups, in sequence order, with its group and frame numbers.
758
1082
  * Treat the returned frame bytes as read-only; they are shared with other consumers.
1083
+ *
1084
+ * Groups are acquired through the same sequence cursor as {@link Ordered.nextGroup},
1085
+ * so frames never run backwards: a late lower-sequence group is skipped, and so is
1086
+ * one every frame of which `maxAge` proves is too old. A group the budget abandons
1087
+ * mid-stall ends cleanly and the cursor resyncs from the next group; a gap inside a
1088
+ * group still surfaces as {@link TooFarBehind} or {@link GroupTooLarge}.
759
1089
  */
760
- async readFrameSequence() {
1090
+ async #readFrame() {
761
1091
  for (;;) {
762
- const groups = this.#state.groups.peek();
763
- const { start } = this.#cursor.peek();
764
- while (groups.length > 0 && groups[0].sequence < start)
765
- groups.shift()?.close();
766
- // Drain older groups first, dropping each once empty.
767
- while (groups.length > 1) {
768
- if (groups[0].skipped) {
769
- // The reader fell behind this group's eviction window. Drop it and
770
- // signal the gap; the next read resyncs from the following group.
771
- groups.shift()?.close();
772
- throw new Lagged();
773
- }
774
- const next = groups[0].tryReadFrameSequence();
775
- if (next) {
776
- return {
777
- group: groups[0].sequence,
778
- frame: next.sequence,
779
- payload: next.payload,
780
- timestamp: next.timestamp,
781
- };
782
- }
783
- groups.shift()?.close();
1092
+ if (!this.#frameGroup) {
1093
+ this.#frameGroup = await this.#nextGroup();
1094
+ if (!this.#frameGroup)
1095
+ return undefined;
784
1096
  }
785
- if (groups.length === 0) {
1097
+ const group = this.#frameGroup;
1098
+ let next;
1099
+ try {
1100
+ next = await group.readFrameSequence();
1101
+ }
1102
+ catch (err) {
1103
+ // The group failed underneath us: resync from the next one, surfacing
1104
+ // only what the caller can act on (a gap, or the track's own abort).
1105
+ this.#frameGroup = undefined;
1106
+ group.close();
1107
+ if (err instanceof TooFarBehind || err instanceof GroupTooLarge)
1108
+ throw err;
786
1109
  const closed = this.#state.closed.peek();
787
1110
  if (closed instanceof Error)
788
1111
  throw closed;
789
- if (closed !== undefined)
790
- return undefined;
791
- await Signal.race(this.#state.groups, this.#cursor, this.#state.closed);
792
1112
  continue;
793
1113
  }
794
- const group = groups[0];
795
- if (group.skipped) {
796
- // Fell behind this group's eviction window. Drop it and signal the gap;
797
- // the next read resyncs from the following group.
798
- groups.shift()?.close();
799
- throw new Lagged();
800
- }
801
- const next = group.tryReadFrameSequence();
802
- if (next)
1114
+ if (next) {
803
1115
  return {
804
1116
  group: group.sequence,
805
1117
  frame: next.sequence,
806
1118
  payload: next.payload,
807
1119
  timestamp: next.timestamp,
808
1120
  };
809
- const closed = this.#state.closed.peek();
810
- if (closed instanceof Error)
811
- throw closed;
812
- if (closed !== undefined)
813
- return undefined;
814
- // A finished (drained + closed) group has nothing left: drop it and loop, rather than
815
- // busy-waiting on its already-resolved readable() (which would livelock and starve the
816
- // macrotask that delivers the next group).
817
- if (group.done) {
818
- groups.shift()?.close();
819
- continue;
820
1121
  }
821
- // Lone open group with nothing buffered yet: wait for a frame on it, a new group, or
822
- // the track closing.
823
- await Promise.race([Signal.race(this.#state.groups, this.#cursor, this.#state.closed), group.readable()]);
1122
+ // The group is exhausted (or the budget abandoned its stall); move on.
1123
+ this.#frameGroup = undefined;
1124
+ group.close();
824
1125
  }
825
1126
  }
826
1127
  /** Reads the next frame and decodes it as a UTF-8 string. */
827
- async readString() {
828
- const next = await this.readFrame();
1128
+ async #readString() {
1129
+ const next = await this.#readFrame();
829
1130
  if (!next)
830
1131
  return undefined;
831
1132
  return new TextDecoder().decode(next.payload);
832
1133
  }
833
1134
  /** Reads the next frame and parses it as JSON. */
834
- async readJson() {
835
- const next = await this.readString();
1135
+ async #readJson() {
1136
+ const next = await this.#readString();
836
1137
  if (!next)
837
1138
  return undefined;
838
1139
  return JSON.parse(next);
839
1140
  }
840
1141
  /** Reads the next frame and decodes it as a one-byte boolean, throwing on a malformed frame. */
841
- async readBool() {
842
- const next = await this.readFrame();
1142
+ async #readBool() {
1143
+ const next = await this.#readFrame();
843
1144
  if (!next)
844
1145
  return undefined;
845
1146
  const payload = next.payload;
@@ -847,6 +1148,25 @@ export class Subscriber {
847
1148
  throw new Error("invalid bool frame");
848
1149
  return payload[0] === 1;
849
1150
  }
1151
+ /**
1152
+ * Read this track's groups in sequence order instead of arrival order.
1153
+ *
1154
+ * Both cursors draw from the same buffer, so a track is read one way or the other: this
1155
+ * hands the subscription to the returned {@link Ordered} and leaves this handle inert.
1156
+ * {@link recvGroup} and {@link recvDatagram} throw afterwards. Throws once a
1157
+ * {@link recvGroup} call has already committed the track to arrival order.
1158
+ *
1159
+ * Datagrams come along: they are a separate cursor either way, so the choice of group
1160
+ * order says nothing about them, and reading them commits nothing.
1161
+ */
1162
+ ordered() {
1163
+ if (this.#mode === "ordered")
1164
+ throw new Error("track is already read in sequence order");
1165
+ if (this.#mode === "arrival")
1166
+ throw new Error("track is already read in arrival order");
1167
+ this.#mode = "ordered";
1168
+ return makeOrdered(this);
1169
+ }
850
1170
  /**
851
1171
  * Update this subscription's options (e.g. priority), triggering a SUBSCRIBE_UPDATE to the
852
1172
  * publisher. Mirrors the Rust `Subscriber::update`.
@@ -855,4 +1175,114 @@ export class Subscriber {
855
1175
  this.#state.update.set(subscriptionDefaults(options));
856
1176
  }
857
1177
  }
1178
+ /**
1179
+ * A {@link Subscriber} that reads groups in sequence order.
1180
+ *
1181
+ * Created by {@link Subscriber.ordered}, which takes the subscription over: the two
1182
+ * cursors draw from one buffer, so a track is read one way or the other and never both.
1183
+ * Every group this returns has a higher sequence than the last, so a late arrival is
1184
+ * skipped rather than delivered out of turn.
1185
+ *
1186
+ * `maxAge` applies as this cursor reads, exactly as it does on the arrival cursor: a
1187
+ * group is skipped once its reach, where its immediate successor begins, is that far
1188
+ * behind the newest frame on the track. Nothing weaker convicts it, since the reach is
1189
+ * the only proof that every frame it could still hold is past the budget, so a backlog
1190
+ * inside the budget is still delivered whole, as a burst in order. The budget follows a
1191
+ * group already handed out too: a stalled group's pending frame read rejects once newer
1192
+ * content has pulled that far ahead.
1193
+ */
1194
+ export class Ordered {
1195
+ /** The track name. */
1196
+ name;
1197
+ #subscriber;
1198
+ constructor(subscriber) {
1199
+ this.name = subscriber.name;
1200
+ this.#subscriber = subscriber;
1201
+ }
1202
+ static {
1203
+ makeOrdered = (subscriber) => new Ordered(subscriber);
1204
+ }
1205
+ /** Resolve this track's immutable publisher properties; see {@link Subscriber.info}. */
1206
+ info() {
1207
+ return this.#subscriber.info();
1208
+ }
1209
+ /** Settles once the track closes; see {@link Producer.closed}. */
1210
+ get closed() {
1211
+ return this.#subscriber.closed;
1212
+ }
1213
+ /** This subscriber's current options, including defaults and the last {@link update}. */
1214
+ get subscription() {
1215
+ return this.#subscriber.subscription;
1216
+ }
1217
+ /** The latest group sequence observed on this track, if any. */
1218
+ latest() {
1219
+ return this.#subscriber.latest();
1220
+ }
1221
+ /** The track's exclusive final boundary; see {@link Subscriber.final}. */
1222
+ final() {
1223
+ return this.#subscriber.final();
1224
+ }
1225
+ /** Limit subsequent reads to these groups and return this reader for chaining. */
1226
+ withGroups(groups) {
1227
+ this.setGroups(groups);
1228
+ return this;
1229
+ }
1230
+ /** Limit subsequent reads to these groups; see {@link Subscriber.setGroups}. */
1231
+ setGroups(groups) {
1232
+ this.#subscriber.setGroups(groups);
1233
+ }
1234
+ /** Update this subscription's options; see {@link Subscriber.update}. */
1235
+ update(options) {
1236
+ this.#subscriber.update(options);
1237
+ }
1238
+ /** Close the track (optionally with an error), closing any pending groups. Idempotent. */
1239
+ close(abort) {
1240
+ this.#subscriber.close(abort);
1241
+ }
1242
+ /**
1243
+ * Return the next group with a strictly-greater sequence number than the last returned.
1244
+ *
1245
+ * Late arrivals (sequence at or below the last returned) are silently skipped, as is a
1246
+ * group whose every frame is further behind the live edge than `maxAge` (the default of
1247
+ * zero keeps only what nothing newer has superseded). Honors the bounds set by
1248
+ * {@link setGroups}.
1249
+ */
1250
+ nextGroup() {
1251
+ return ordered_.nextGroup(this.#subscriber);
1252
+ }
1253
+ /**
1254
+ * Read the next frame across groups, in sequence order, with its group and frame numbers.
1255
+ *
1256
+ * Rides the same cursor as {@link nextGroup} and shares this handle's contract: a
1257
+ * buffered backlog is drained in full up to the point `maxAge` proves it useless.
1258
+ * Treat the returned frame bytes as read-only; they are shared with other consumers.
1259
+ */
1260
+ readFrame() {
1261
+ return ordered_.readFrame(this.#subscriber);
1262
+ }
1263
+ /** Read the next frame and decode it as a UTF-8 string. */
1264
+ readString() {
1265
+ return ordered_.readString(this.#subscriber);
1266
+ }
1267
+ /** Read the next frame and parse it as JSON. */
1268
+ readJson() {
1269
+ return ordered_.readJson(this.#subscriber);
1270
+ }
1271
+ /** Read the next frame and decode it as a one-byte boolean, throwing on a malformed frame. */
1272
+ readBool() {
1273
+ return ordered_.readBool(this.#subscriber);
1274
+ }
1275
+ /**
1276
+ * Receive the next datagram in arrival order.
1277
+ *
1278
+ * Datagrams are a separate best-effort channel from groups (see
1279
+ * {@link Producer.appendDatagram}); they share only the sequence namespace, and
1280
+ * neither cursor moves the other. Unordered by construction, so this behaves
1281
+ * identically on either handle; it is here so a track carrying both channels needs
1282
+ * one subscription rather than two.
1283
+ */
1284
+ recvDatagram() {
1285
+ return ordered_.recvDatagram(this.#subscriber);
1286
+ }
1287
+ }
858
1288
  //# sourceMappingURL=track.js.map