@moq/net 0.3.4 → 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 (215) hide show
  1. package/README.md +2 -2
  2. package/announce.d.ts +7 -0
  3. package/announce.d.ts.map +1 -0
  4. package/announce.js +8 -0
  5. package/announce.js.map +1 -0
  6. package/announced.d.ts +35 -91
  7. package/announced.d.ts.map +1 -1
  8. package/announced.js +21 -156
  9. package/announced.js.map +1 -1
  10. package/bandwidth.d.ts +163 -0
  11. package/bandwidth.d.ts.map +1 -0
  12. package/bandwidth.js +304 -0
  13. package/bandwidth.js.map +1 -0
  14. package/bandwidth_api.d.ts +7 -0
  15. package/bandwidth_api.d.ts.map +1 -0
  16. package/bandwidth_api.js +8 -0
  17. package/bandwidth_api.js.map +1 -0
  18. package/broadcast.d.ts +20 -28
  19. package/broadcast.d.ts.map +1 -1
  20. package/broadcast.js +60 -42
  21. package/broadcast.js.map +1 -1
  22. package/connection/accept.d.ts +16 -1
  23. package/connection/accept.d.ts.map +1 -1
  24. package/connection/accept.js +39 -24
  25. package/connection/accept.js.map +1 -1
  26. package/connection/browser.d.ts.map +1 -1
  27. package/connection/browser.js +9 -7
  28. package/connection/browser.js.map +1 -1
  29. package/connection/connect.d.ts +30 -6
  30. package/connection/connect.d.ts.map +1 -1
  31. package/connection/connect.js +97 -50
  32. package/connection/connect.js.map +1 -1
  33. package/connection/established.d.ts +16 -21
  34. package/connection/established.d.ts.map +1 -1
  35. package/connection/established.js.map +1 -1
  36. package/connection/forward.d.ts +2 -0
  37. package/connection/forward.d.ts.map +1 -0
  38. package/connection/forward.js +159 -0
  39. package/connection/forward.js.map +1 -0
  40. package/connection/handshake.d.ts.map +1 -1
  41. package/connection/handshake.js +2 -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 +188 -0
  48. package/connection/pool.d.ts.map +1 -0
  49. package/connection/pool.js +351 -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 +216 -80
  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 +310 -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/aliases.d.ts +1 -78
  81. package/ietf/aliases.d.ts.map +1 -1
  82. package/ietf/cluster.d.ts +6 -120
  83. package/ietf/cluster.d.ts.map +1 -1
  84. package/ietf/cluster.js +81 -41
  85. package/ietf/cluster.js.map +1 -1
  86. package/ietf/connection.d.ts +6 -72
  87. package/ietf/connection.d.ts.map +1 -1
  88. package/ietf/connection.js +11 -47
  89. package/ietf/connection.js.map +1 -1
  90. package/ietf/error.d.ts +11 -0
  91. package/ietf/error.d.ts.map +1 -0
  92. package/ietf/error.js +168 -0
  93. package/ietf/error.js.map +1 -0
  94. package/ietf/filter.d.ts.map +1 -1
  95. package/ietf/filter.js +6 -1
  96. package/ietf/filter.js.map +1 -1
  97. package/ietf/goaway.d.ts.map +1 -1
  98. package/ietf/goaway.js +22 -5
  99. package/ietf/goaway.js.map +1 -1
  100. package/ietf/parameters.d.ts +2 -2
  101. package/ietf/parameters.d.ts.map +1 -1
  102. package/ietf/parameters.js +15 -17
  103. package/ietf/parameters.js.map +1 -1
  104. package/ietf/publish_namespace.d.ts +25 -0
  105. package/ietf/publish_namespace.d.ts.map +1 -1
  106. package/ietf/publish_namespace.js +63 -0
  107. package/ietf/publish_namespace.js.map +1 -1
  108. package/ietf/publisher.d.ts +1 -82
  109. package/ietf/publisher.d.ts.map +1 -1
  110. package/ietf/publisher.js +219 -125
  111. package/ietf/publisher.js.map +1 -1
  112. package/ietf/solicit.d.ts +1 -40
  113. package/ietf/solicit.d.ts.map +1 -1
  114. package/ietf/subscribe.d.ts +1 -5
  115. package/ietf/subscribe.d.ts.map +1 -1
  116. package/ietf/subscribe.js +8 -9
  117. package/ietf/subscribe.js.map +1 -1
  118. package/ietf/subscriber.d.ts +1 -65
  119. package/ietf/subscriber.d.ts.map +1 -1
  120. package/ietf/subscriber.js +154 -73
  121. package/ietf/subscriber.js.map +1 -1
  122. package/ietf/version.d.ts +12 -1
  123. package/ietf/version.d.ts.map +1 -1
  124. package/ietf/version.js +13 -0
  125. package/ietf/version.js.map +1 -1
  126. package/index.d.ts +11 -6
  127. package/index.d.ts.map +1 -1
  128. package/index.js +10 -5
  129. package/index.js.map +1 -1
  130. package/internal.d.ts +99 -1
  131. package/internal.d.ts.map +1 -1
  132. package/internal.js +65 -0
  133. package/internal.js.map +1 -1
  134. package/lite/announce.d.ts +15 -9
  135. package/lite/announce.d.ts.map +1 -1
  136. package/lite/announce.js +47 -20
  137. package/lite/announce.js.map +1 -1
  138. package/lite/connection.d.ts +9 -59
  139. package/lite/connection.d.ts.map +1 -1
  140. package/lite/connection.js +20 -32
  141. package/lite/connection.js.map +1 -1
  142. package/lite/fetch.d.ts +15 -1
  143. package/lite/fetch.d.ts.map +1 -1
  144. package/lite/fetch.js +39 -7
  145. package/lite/fetch.js.map +1 -1
  146. package/lite/goaway.d.ts.map +1 -1
  147. package/lite/goaway.js +7 -1
  148. package/lite/goaway.js.map +1 -1
  149. package/lite/group.d.ts +18 -4
  150. package/lite/group.d.ts.map +1 -1
  151. package/lite/group.js +31 -10
  152. package/lite/group.js.map +1 -1
  153. package/lite/priority.d.ts +1 -61
  154. package/lite/priority.d.ts.map +1 -1
  155. package/lite/priority.js +4 -5
  156. package/lite/priority.js.map +1 -1
  157. package/lite/publisher.d.ts +1 -69
  158. package/lite/publisher.d.ts.map +1 -1
  159. package/lite/publisher.js +559 -232
  160. package/lite/publisher.js.map +1 -1
  161. package/lite/setup.d.ts +7 -7
  162. package/lite/setup.d.ts.map +1 -1
  163. package/lite/setup.js +13 -13
  164. package/lite/setup.js.map +1 -1
  165. package/lite/subscribe.d.ts +61 -13
  166. package/lite/subscribe.d.ts.map +1 -1
  167. package/lite/subscribe.js +186 -44
  168. package/lite/subscribe.js.map +1 -1
  169. package/lite/subscriber.d.ts +8 -57
  170. package/lite/subscriber.d.ts.map +1 -1
  171. package/lite/subscriber.js +179 -117
  172. package/lite/subscriber.js.map +1 -1
  173. package/lite/track.d.ts +4 -10
  174. package/lite/track.d.ts.map +1 -1
  175. package/lite/track.js +34 -29
  176. package/lite/track.js.map +1 -1
  177. package/lite/version.d.ts +31 -6
  178. package/lite/version.d.ts.map +1 -1
  179. package/lite/version.js +71 -11
  180. package/lite/version.js.map +1 -1
  181. package/origin.d.ts +229 -29
  182. package/origin.d.ts.map +1 -1
  183. package/origin.js +1087 -37
  184. package/origin.js.map +1 -1
  185. package/package.json +3 -2
  186. package/path.d.ts +25 -7
  187. package/path.d.ts.map +1 -1
  188. package/path.js +5 -3
  189. package/path.js.map +1 -1
  190. package/stream.d.ts.map +1 -1
  191. package/stream.js +25 -16
  192. package/stream.js.map +1 -1
  193. package/time.d.ts +15 -2
  194. package/time.d.ts.map +1 -1
  195. package/time.js +28 -9
  196. package/time.js.map +1 -1
  197. package/track.d.ts +171 -82
  198. package/track.d.ts.map +1 -1
  199. package/track.js +633 -184
  200. package/track.js.map +1 -1
  201. package/util/log.d.ts +5 -0
  202. package/util/log.d.ts.map +1 -0
  203. package/util/log.js +17 -0
  204. package/util/log.js.map +1 -0
  205. package/wire.d.ts +67 -0
  206. package/wire.d.ts.map +1 -0
  207. package/wire.js +32 -0
  208. package/wire.js.map +1 -0
  209. package/zod.d.ts +1 -1
  210. package/zod.d.ts.map +1 -1
  211. package/zod.js.map +1 -1
  212. package/mock.d.ts +0 -66
  213. package/mock.d.ts.map +0 -1
  214. package/mock.js +0 -243
  215. package/mock.js.map +0 -1
package/track.js CHANGED
@@ -5,43 +5,65 @@
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
24
23
  * datagrams are dropped there; a payload above this cap could never fit anywhere.
25
24
  */
26
25
  const MAX_DATAGRAM_BYTES = 65535;
26
+ // Normalize a latency budget for the wire, which carries it as an unsigned varint.
27
+ //
28
+ // Callers derive it from measurements (a jitter estimate scaled off RTT), so a fractional
29
+ // millisecond is expected; ceil rather than round, because a budget shortened by rounding
30
+ // skips a group the subscriber still wants. Anything that is not a duration is refused
31
+ // here, where the field is named, rather than deep in the encoder.
32
+ function maxAgeMillis(value) {
33
+ if (!Number.isFinite(value) || value < 0) {
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}`);
45
+ }
46
+ return value;
47
+ }
27
48
  /** Fill in any unset {@link Info} fields with their defaults. */
28
49
  export function infoDefaults(info = {}) {
29
50
  return {
30
- timescale: info.timescale ?? Timescale.MILLI,
31
- latencyMax: info.latencyMax ?? DEFAULT_LATENCY_MAX_MS,
32
- priority: info.priority ?? 0,
33
- 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),
34
54
  };
35
55
  }
36
56
  // Materialize the defaults at the model boundary so every layer observes a complete
37
57
  // subscription rather than interpreting an omitted field differently.
38
58
  function subscriptionDefaults(subscription = {}) {
59
+ const bounds = groupBounds(subscription.groups ?? {});
39
60
  return {
40
- priority: subscription.priority ?? 0,
41
- ordered: subscription.ordered ?? false,
42
- latencyMax: subscription.latencyMax ?? 0,
43
- startGroup: subscription.startGroup,
44
- 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
+ },
45
67
  };
46
68
  }
47
69
  // Aggregate the preferences of every live subscriber, matching Rust's Subscription::poll_combined.
@@ -56,25 +78,22 @@ function combineSubscriptions(states) {
56
78
  continue;
57
79
  }
58
80
  combined.priority = Math.max(combined.priority ?? 0, subscription.priority ?? 0);
59
- combined.ordered = (combined.ordered ?? false) && (subscription.ordered ?? false);
60
- combined.latencyMax = Math.max(combined.latencyMax ?? 0, subscription.latencyMax ?? 0);
61
- if (subscription.startGroup !== undefined) {
62
- combined.startGroup =
63
- combined.startGroup === undefined
64
- ? subscription.startGroup
65
- : Math.min(combined.startGroup, subscription.startGroup);
66
- }
67
- if (combined.endGroup === undefined || subscription.endGroup === undefined) {
68
- combined.endGroup = undefined;
69
- }
70
- else {
71
- combined.endGroup = Math.max(combined.endGroup, subscription.endGroup);
72
- }
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
+ };
73
92
  }
74
93
  return combined;
75
94
  }
76
95
  /**
77
- * 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.
78
97
  *
79
98
  * Created internally by the broadcast when a subscription (or info lookup) needs a track
80
99
  * served; answer it with {@link accept} or {@link reject}.
@@ -86,10 +105,13 @@ export class Request {
86
105
  name;
87
106
  #producer;
88
107
  #sequences;
108
+ #pending;
89
109
  constructor(options) {
90
110
  this.name = options.name;
91
111
  this.#producer = options.producer;
92
112
  this.#sequences = options.sequences;
113
+ this.#pending = options.pending;
114
+ this.#pending.add(this);
93
115
  }
94
116
  static {
95
117
  hooks.makeRequest = (options) => new Request(options);
@@ -104,11 +126,13 @@ export class Request {
104
126
  }
105
127
  /** Accept the request, committing the track's immutable {@link Info}. */
106
128
  accept(info = {}) {
129
+ this.#pending.delete(this);
107
130
  bindProducer(this.name, this.#producer, this.#sequences);
108
131
  return this.#producer.accept(info);
109
132
  }
110
133
  /** Reject the request, closing the track optionally with an error. */
111
134
  reject(err) {
135
+ this.#pending.delete(this);
112
136
  this.#producer.close(err);
113
137
  }
114
138
  }
@@ -125,7 +149,17 @@ export class Consumer {
125
149
  this.name = name;
126
150
  this.#broadcast = broadcast;
127
151
  }
128
- /** 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
+ */
129
163
  subscribe(options) {
130
164
  return this.#broadcast.subscribe(this.name, options);
131
165
  }
@@ -144,9 +178,22 @@ class TrackState {
144
178
  /** The producer fanning into this sink, so a subscriber can mint a sibling of itself. */
145
179
  producer;
146
180
  groups = new Signal([]);
147
- /** 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. */
148
189
  datagrams = new Signal([]);
149
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;
150
197
  closed = new Once();
151
198
  update;
152
199
  /** Resolved once the producer commits the immutable properties. */
@@ -190,6 +237,11 @@ function bindProducer(name, producer, sequences) {
190
237
  bindProducerSequence(producer, shared);
191
238
  }
192
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_;
193
245
  // Constructs a Subscriber from within this module without exposing a public
194
246
  // constructor that would leak the unexported TrackState. Assigned in the class's
195
247
  // static block.
@@ -201,7 +253,7 @@ let makeSubscriber;
201
253
  * subscription the publisher serves from it) gets an independent
202
254
  * {@link Subscriber} that receives a full copy of the groups, each with its own
203
255
  * read cursor. Groups are mirrored into every live subscriber and retained for the
204
- * 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.
205
257
  *
206
258
  * Obtained from {@link Request.accept} (the wire asks the application for a track to
207
259
  * serve) or constructed directly for an in-process track.
@@ -214,10 +266,14 @@ export class Producer {
214
266
  #state = new TrackState();
215
267
  #sequence = { next: 0 };
216
268
  // Recently written source groups, retained for replay to late subscribers and
217
- // 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
218
270
  // it handed to every sink so eviction can drop them too: otherwise a slow consumer
219
271
  // that never reads would pin old groups (and their frame bytes) forever.
220
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;
221
277
  // One independent downstream state per live subscriber.
222
278
  #sinks = new Set();
223
279
  // Whether any subscriber is currently attached. Exposed as {@link used}; the consumer wire
@@ -238,6 +294,15 @@ export class Producer {
238
294
  info() {
239
295
  return resolveInfo(this.#state);
240
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
+ }
241
306
  /**
242
307
  * Settles once the track closes: `null` on a clean close, or the abort {@link Error}.
243
308
  * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
@@ -254,14 +319,24 @@ export class Producer {
254
319
  }
255
320
  /** Commit the immutable publisher properties, resolving {@link info}. Returns `this`. */
256
321
  accept(info = {}) {
322
+ if (this.#state.closed.peek() !== undefined)
323
+ return this;
257
324
  const resolved = infoDefaults(info);
258
325
  this.#state.info.set(resolved);
259
326
  // Propagate to any sink handed out before accept (the on-demand path).
260
327
  for (const sink of this.#sinks)
261
328
  sink.info.set(resolved);
329
+ this.#updateSubscription();
262
330
  return this;
263
331
  }
264
- /** 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
+ */
265
340
  subscribe(options = {}) {
266
341
  const sink = new TrackState(options);
267
342
  this.#addSink(sink);
@@ -328,13 +403,19 @@ export class Producer {
328
403
  this.#prune();
329
404
  for (const entry of this.#cache)
330
405
  this.#mirror(entry, sink);
331
- if (closed !== undefined)
406
+ if (closed !== undefined) {
407
+ sink.final = this.#state.final;
332
408
  closeTrackState(sink, closed instanceof Error ? closed : undefined);
409
+ }
333
410
  }
334
411
  // Recompute from every live sink because an update or close can narrow as well as widen
335
412
  // the aggregate. The wire layer observes this signal and emits SUBSCRIBE_UPDATE.
336
413
  #updateSubscription() {
337
- 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);
338
419
  }
339
420
  // Mirror a cached source group into a sink. The mirror fills synchronously as the
340
421
  // source is written and keeps its own read cursor; frame bytes are shared by
@@ -342,6 +423,8 @@ export class Producer {
342
423
  #mirror(entry, sink) {
343
424
  const dst = entry.group.mirror();
344
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));
345
428
  sink.latest = Math.max(sink.latest ?? 0, dst.sequence);
346
429
  sink.groups.mutate((groups) => {
347
430
  groups.push(dst);
@@ -350,37 +433,93 @@ export class Producer {
350
433
  }
351
434
  // Drop a cached group's mirror from every sink so no consumer can pin it.
352
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());
353
442
  for (const [sink, mirror] of entry.mirrors) {
443
+ hooks.evictGroup(mirror);
354
444
  sink.groups.mutate((groups) => {
355
445
  const i = groups.indexOf(mirror);
356
446
  if (i >= 0)
357
447
  groups.splice(i, 1);
358
448
  });
449
+ if (sink.timeline.get(mirror.sequence)?.group === mirror)
450
+ sink.timeline.delete(mirror.sequence);
359
451
  mirror.close();
360
452
  }
361
453
  entry.mirrors.clear();
362
454
  }
363
- // 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.
364
466
  #prune() {
365
- const latencyMaxMs = this.#state.info.peek()?.latencyMax ?? DEFAULT_LATENCY_MAX_MS;
366
- 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();
367
470
  const retained = [];
368
471
  for (const entry of this.#cache) {
369
- if (entry.time > cutoff || entry.group.closed.peek() === undefined) {
472
+ if (entry.group === live || entry.group.activity >= cutoff) {
370
473
  retained.push(entry);
371
474
  continue;
372
475
  }
373
476
  this.#evict(entry);
374
477
  }
375
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;
376
513
  }
377
514
  // Retain a source group and fan it out to every live sink.
378
515
  #publish(group) {
379
- const entry = { group, time: Date.now(), mirrors: new Map() };
516
+ const entry = { group, time: performance.now(), mirrors: new Map() };
380
517
  this.#cache.push(entry);
381
- this.#prune();
382
518
  for (const sink of this.#sinks)
383
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();
384
523
  }
385
524
  /** Append a new group with the next sequence number. */
386
525
  appendGroup() {
@@ -422,13 +561,11 @@ export class Producer {
422
561
  // Fan a datagram out to every live subscriber, dropping the oldest once the ring is full.
423
562
  // Late subscribers do NOT replay old datagrams (best-effort, unlike the group cache).
424
563
  #publishDatagram(datagram) {
425
- const now = performance.now();
426
564
  for (const sink of this.#sinks) {
427
565
  sink.datagrams.mutate((list) => {
428
- list.push({ datagram, time: now });
429
- // Drop anything older than the send-buffer window.
430
- while (list.length > 0 && now - list[0].time > MAX_DATAGRAM_AGE_MS)
566
+ if (list.length === MAX_DATAGRAMS)
431
567
  list.shift();
568
+ list.push(datagram);
432
569
  });
433
570
  }
434
571
  }
@@ -442,7 +579,7 @@ export class Producer {
442
579
  * keep datagram payloads small (e.g. a single audio frame). Datagrams are never delivered
443
580
  * over IETF moq-transport or stream-only transports (the WebSocket fallback). A payload over
444
581
  * 65535 bytes (the QUIC datagram frame ceiling) throws. An origin publisher uses this; a
445
- * relay preserving upstream numbering uses {@link writeDatagram}.
582
+ * relay preserving upstream numbering uses {@link insertDatagram}.
446
583
  */
447
584
  appendDatagram(timestamp, payload) {
448
585
  if (this.#state.closed.peek() !== undefined)
@@ -456,26 +593,34 @@ export class Producer {
456
593
  return sequence;
457
594
  }
458
595
  /**
459
- * Write a datagram with an explicit sequence number.
596
+ * Insert a datagram with an explicit sequence number.
460
597
  *
461
598
  * Preserves the supplied sequence (advancing the shared counter if needed) so a relay can
462
599
  * forward a datagram without renumbering it. The size limits of {@link appendDatagram}
463
600
  * apply. Most origin publishers want {@link appendDatagram} instead.
464
601
  */
465
- writeDatagram(datagram) {
602
+ insertDatagram(sequence, timestamp, payload) {
466
603
  if (this.#state.closed.peek() !== undefined)
467
604
  throw new Error("track is closed");
468
- if (datagram.payload.byteLength > MAX_DATAGRAM_BYTES)
605
+ if (payload.byteLength > MAX_DATAGRAM_BYTES)
469
606
  throw new Error("datagram payload too large");
470
- const sequence = this.#sequence;
471
- if (datagram.sequence >= sequence.next) {
472
- sequence.next = datagram.sequence + 1;
607
+ const counter = this.#sequence;
608
+ if (sequence >= counter.next) {
609
+ counter.next = sequence + 1;
473
610
  }
474
- this.#publishDatagram(datagram);
611
+ this.#publishDatagram({ sequence, timestamp, payload });
475
612
  }
476
613
  /** Close the track and every subscriber, mirroring the abort to their groups. Idempotent. */
477
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
+ }
478
621
  closeTrackState(this.#state, abort);
622
+ clearTimeout(this.#pruneTimer);
623
+ this.#pruneTimer = undefined;
479
624
  for (const { group } of this.#cache)
480
625
  group.close(abort);
481
626
  for (const sink of this.#sinks) {
@@ -523,12 +668,140 @@ export class Subscriber {
523
668
  #state;
524
669
  #nextSequence = 0;
525
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
+ }
526
773
  constructor(name, state) {
527
774
  this.name = name;
528
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 });
529
780
  }
530
781
  static {
531
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");
532
805
  }
533
806
  /**
534
807
  * Resolve this track's immutable publisher properties.
@@ -552,6 +825,15 @@ export class Subscriber {
552
825
  latest() {
553
826
  return this.#state.latest;
554
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
+ }
555
837
  /**
556
838
  * The newest frame this track has produced, or `undefined` while it has none.
557
839
  *
@@ -592,22 +874,33 @@ export class Subscriber {
592
874
  throw new Error("track has no producer to fork from");
593
875
  return producer.subscribe(options);
594
876
  }
595
- /** Start this subscriber's local read cursor at `sequence`, without changing its wire request. */
596
- startAt(sequence) {
597
- 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;
598
881
  }
599
882
  /**
600
- * Cap {@link nextGroup} and {@link recvGroup} at `sequence` inclusively, or omit it to
601
- * remove the cap. Groups above the cap remain buffered and become readable if the cap
602
- * 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.
603
886
  */
604
- endAt(sequence) {
605
- 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
+ }));
606
899
  }
607
900
  /** Close the track (optionally with an error), closing any pending groups. Idempotent. */
608
901
  close(abort) {
609
902
  // Settle if we're first (the producer may already have); either way drop anything
610
- // 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
611
904
  // producer close, so the subscriber leaving is what must release them: closing
612
905
  // and clearing wakes a pending read to observe the end instead of hanging.
613
906
  closeTrackState(this.#state, abort);
@@ -616,55 +909,102 @@ export class Subscriber {
616
909
  group.close(abort);
617
910
  groups.length = 0;
618
911
  });
912
+ this.#frameGroup?.close(abort);
913
+ this.#frameGroup = undefined;
914
+ this.#state.timeline.clear();
619
915
  }
620
916
  /**
621
917
  * Receive every group on this track exactly once, as it becomes available.
622
918
  *
623
919
  * Groups may arrive out of order or with gaps due to network conditions; unlike
624
- * {@link nextGroup}, one that arrives after a newer group was already returned is
625
- * 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
626
922
  * returned first.
627
923
  *
628
- * 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
629
925
  * beyond the cap stays buffered (not dropped) and is offered once the cap rises, even
630
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.
631
933
  */
632
934
  async recvGroup() {
935
+ this.#live();
936
+ this.#mode = "arrival";
633
937
  for (;;) {
634
- const group = this.tryRecvGroup();
635
- if (group)
636
- return group;
637
- const closed = this.#state.closed.peek();
638
- if (closed instanceof Error)
639
- throw closed;
640
- // A group beyond the cap outlives a clean close: it becomes deliverable if
641
- // the cap rises, so the track isn't over while any are held.
642
- if (closed !== undefined && !this.#state.groups.peek()[0])
643
- 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.
644
948
  await Signal.race(this.#state.groups, this.#cursor, this.#state.closed);
645
949
  }
646
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
+ }
647
991
  /**
648
992
  * Take the next buffered group without blocking, honoring the same cursor bounds as
649
993
  * {@link recvGroup}.
650
994
  *
651
995
  * Returns `undefined` when nothing is deliverable right now, which is not by itself the
652
996
  * end of the track: a group may still arrive, or one may be parked beyond the
653
- * {@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
654
998
  * waiting for a sequence nothing will republish would park forever.
655
999
  */
656
1000
  tryRecvGroup() {
657
- const groups = this.#state.groups.peek();
658
- const { start, end } = this.#cursor.peek();
659
- while (groups.length > 0 && groups[0].sequence < start)
660
- groups.shift()?.close();
661
- // The buffer is sequence-sorted, so an in-range group that arrives behind a
662
- // beyond-cap one sorts in front of it and is never blocked by it.
663
- const group = groups[0];
664
- if (group && (end === undefined || group.sequence <= end)) {
665
- groups.shift();
666
- return group;
667
- }
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;
668
1008
  return undefined;
669
1009
  }
670
1010
  /**
@@ -673,23 +1013,20 @@ export class Subscriber {
673
1013
  * Datagrams are a separate best-effort channel from groups (see
674
1014
  * {@link Producer.appendDatagram}); they share only the sequence namespace. A consumer
675
1015
  * that falls too far behind silently loses the oldest datagrams. Read this alongside
676
- * {@link recvGroup} (e.g. in a separate loop) to receive both channels concurrently. Returning
677
- * 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.
678
1018
  */
679
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() {
680
1026
  for (;;) {
681
1027
  const datagrams = this.#state.datagrams.peek();
682
- // Evict datagrams older than the send-buffer window (also enforced on write), so a
683
- // reader that stalled skips stale datagrams instead of replaying them.
684
- const cutoff = performance.now() - MAX_DATAGRAM_AGE_MS;
685
- while (datagrams.length > 0 && datagrams[0].time < cutoff)
686
- datagrams.shift();
687
1028
  if (datagrams.length > 0) {
688
- const datagram = datagrams.shift()?.datagram;
689
- if (datagram) {
690
- this.#nextSequence = Math.max(this.#nextSequence, datagram.sequence + 1);
691
- }
692
- return datagram;
1029
+ return datagrams.shift();
693
1030
  }
694
1031
  const closed = this.#state.closed.peek();
695
1032
  if (closed instanceof Error)
@@ -699,128 +1036,111 @@ export class Subscriber {
699
1036
  await Signal.race(this.#state.datagrams, this.#state.closed);
700
1037
  }
701
1038
  }
702
- /**
703
- * Return the next group with a strictly-greater sequence number than the last returned.
704
- *
705
- * Late arrivals (sequence at or below the last returned) are silently skipped.
706
- * Use {@link recvGroup} to see every group in arrival order instead.
707
- */
708
- async nextGroup() {
1039
+ // The sequence cursor behind {@link Ordered}, which owns the only public door to it.
1040
+ async #nextGroup() {
709
1041
  for (;;) {
710
1042
  const groups = this.#state.groups.peek();
711
1043
  const cursor = this.#cursor.peek();
712
1044
  const start = Math.max(cursor.start, this.#nextSequence);
713
1045
  while (groups.length > 0 && groups[0].sequence < start)
714
1046
  groups.shift()?.close();
715
- const group = groups[0];
716
- 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;
717
1053
  groups.shift();
718
1054
  this.#nextSequence = group.sequence + 1;
719
- 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);
720
1068
  }
721
1069
  const closed = this.#state.closed.peek();
722
1070
  if (closed instanceof Error)
723
1071
  throw closed;
724
- 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])
725
1076
  return undefined;
726
1077
  await Signal.race(this.#state.groups, this.#cursor, this.#state.closed);
727
1078
  }
728
1079
  }
729
1080
  /**
730
- * Reads the next frame across all groups, discarding older groups.
731
- * Treat the returned frame bytes as read-only; they are shared with other consumers.
732
- */
733
- async readFrame() {
734
- const next = await this.readFrameSequence();
735
- return next ? { payload: next.payload, timestamp: next.timestamp } : undefined;
736
- }
737
- /**
738
- * 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.
739
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}.
740
1089
  */
741
- async readFrameSequence() {
1090
+ async #readFrame() {
742
1091
  for (;;) {
743
- const groups = this.#state.groups.peek();
744
- const { start } = this.#cursor.peek();
745
- while (groups.length > 0 && groups[0].sequence < start)
746
- groups.shift()?.close();
747
- // Drain older groups first, dropping each once empty.
748
- while (groups.length > 1) {
749
- if (groups[0].skipped) {
750
- // The reader fell behind this group's eviction window. Drop it and
751
- // signal the gap; the next read resyncs from the following group.
752
- groups.shift()?.close();
753
- throw new Lagged();
754
- }
755
- const next = groups[0].tryReadFrameSequence();
756
- if (next) {
757
- return {
758
- group: groups[0].sequence,
759
- frame: next.sequence,
760
- payload: next.payload,
761
- timestamp: next.timestamp,
762
- };
763
- }
764
- groups.shift()?.close();
1092
+ if (!this.#frameGroup) {
1093
+ this.#frameGroup = await this.#nextGroup();
1094
+ if (!this.#frameGroup)
1095
+ return undefined;
1096
+ }
1097
+ const group = this.#frameGroup;
1098
+ let next;
1099
+ try {
1100
+ next = await group.readFrameSequence();
765
1101
  }
766
- if (groups.length === 0) {
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;
767
1109
  const closed = this.#state.closed.peek();
768
1110
  if (closed instanceof Error)
769
1111
  throw closed;
770
- if (closed !== undefined)
771
- return undefined;
772
- await Signal.race(this.#state.groups, this.#cursor, this.#state.closed);
773
1112
  continue;
774
1113
  }
775
- const group = groups[0];
776
- if (group.skipped) {
777
- // Fell behind this group's eviction window. Drop it and signal the gap;
778
- // the next read resyncs from the following group.
779
- groups.shift()?.close();
780
- throw new Lagged();
781
- }
782
- const next = group.tryReadFrameSequence();
783
- if (next)
1114
+ if (next) {
784
1115
  return {
785
1116
  group: group.sequence,
786
1117
  frame: next.sequence,
787
1118
  payload: next.payload,
788
1119
  timestamp: next.timestamp,
789
1120
  };
790
- const closed = this.#state.closed.peek();
791
- if (closed instanceof Error)
792
- throw closed;
793
- if (closed !== undefined)
794
- return undefined;
795
- // A finished (drained + closed) group has nothing left: drop it and loop, rather than
796
- // busy-waiting on its already-resolved readable() (which would livelock and starve the
797
- // macrotask that delivers the next group).
798
- if (group.done) {
799
- groups.shift()?.close();
800
- continue;
801
1121
  }
802
- // Lone open group with nothing buffered yet: wait for a frame on it, a new group, or
803
- // the track closing.
804
- 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();
805
1125
  }
806
1126
  }
807
1127
  /** Reads the next frame and decodes it as a UTF-8 string. */
808
- async readString() {
809
- const next = await this.readFrame();
1128
+ async #readString() {
1129
+ const next = await this.#readFrame();
810
1130
  if (!next)
811
1131
  return undefined;
812
1132
  return new TextDecoder().decode(next.payload);
813
1133
  }
814
1134
  /** Reads the next frame and parses it as JSON. */
815
- async readJson() {
816
- const next = await this.readString();
1135
+ async #readJson() {
1136
+ const next = await this.#readString();
817
1137
  if (!next)
818
1138
  return undefined;
819
1139
  return JSON.parse(next);
820
1140
  }
821
1141
  /** Reads the next frame and decodes it as a one-byte boolean, throwing on a malformed frame. */
822
- async readBool() {
823
- const next = await this.readFrame();
1142
+ async #readBool() {
1143
+ const next = await this.#readFrame();
824
1144
  if (!next)
825
1145
  return undefined;
826
1146
  const payload = next.payload;
@@ -828,6 +1148,25 @@ export class Subscriber {
828
1148
  throw new Error("invalid bool frame");
829
1149
  return payload[0] === 1;
830
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
+ }
831
1170
  /**
832
1171
  * Update this subscription's options (e.g. priority), triggering a SUBSCRIBE_UPDATE to the
833
1172
  * publisher. Mirrors the Rust `Subscriber::update`.
@@ -836,4 +1175,114 @@ export class Subscriber {
836
1175
  this.#state.update.set(subscriptionDefaults(options));
837
1176
  }
838
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
+ }
839
1288
  //# sourceMappingURL=track.js.map