@moq/net 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/broadcast.d.ts +21 -7
  2. package/broadcast.d.ts.map +1 -1
  3. package/broadcast.js +38 -16
  4. package/broadcast.js.map +1 -1
  5. package/connection/accept.js +6 -4
  6. package/connection/accept.js.map +1 -1
  7. package/connection/connect.d.ts.map +1 -1
  8. package/connection/connect.js +5 -4
  9. package/connection/connect.js.map +1 -1
  10. package/connection/forward.js +54 -47
  11. package/connection/forward.js.map +1 -1
  12. package/connection/goaway.d.ts +34 -0
  13. package/connection/goaway.d.ts.map +1 -0
  14. package/connection/goaway.js +176 -0
  15. package/connection/goaway.js.map +1 -0
  16. package/connection/handshake.d.ts +4 -2
  17. package/connection/handshake.d.ts.map +1 -1
  18. package/connection/handshake.js +42 -10
  19. package/connection/handshake.js.map +1 -1
  20. package/connection/pool.d.ts +16 -1
  21. package/connection/pool.d.ts.map +1 -1
  22. package/connection/pool.js +32 -10
  23. package/connection/pool.js.map +1 -1
  24. package/connection/reload.d.ts.map +1 -1
  25. package/connection/reload.js +184 -30
  26. package/connection/reload.js.map +1 -1
  27. package/error.d.ts +11 -0
  28. package/error.d.ts.map +1 -1
  29. package/error.js +14 -0
  30. package/error.js.map +1 -1
  31. package/errors.d.ts +1 -1
  32. package/errors.d.ts.map +1 -1
  33. package/errors.js +1 -1
  34. package/errors.js.map +1 -1
  35. package/group.d.ts.map +1 -1
  36. package/group.js +5 -4
  37. package/group.js.map +1 -1
  38. package/hop.d.ts +8 -0
  39. package/hop.d.ts.map +1 -1
  40. package/hop.js +16 -0
  41. package/hop.js.map +1 -1
  42. package/ietf/adapter.d.ts +4 -0
  43. package/ietf/adapter.d.ts.map +1 -1
  44. package/ietf/adapter.js +19 -8
  45. package/ietf/adapter.js.map +1 -1
  46. package/ietf/cluster.d.ts +3 -3
  47. package/ietf/cluster.js +3 -3
  48. package/ietf/cluster.js.map +1 -1
  49. package/ietf/connection.d.ts.map +1 -1
  50. package/ietf/connection.js +110 -37
  51. package/ietf/connection.js.map +1 -1
  52. package/ietf/fetch.d.ts +7 -20
  53. package/ietf/fetch.d.ts.map +1 -1
  54. package/ietf/fetch.js +52 -22
  55. package/ietf/fetch.js.map +1 -1
  56. package/ietf/filter.d.ts +2 -0
  57. package/ietf/filter.d.ts.map +1 -1
  58. package/ietf/filter.js +4 -0
  59. package/ietf/filter.js.map +1 -1
  60. package/ietf/goaway.d.ts +9 -1
  61. package/ietf/goaway.d.ts.map +1 -1
  62. package/ietf/goaway.js +20 -0
  63. package/ietf/goaway.js.map +1 -1
  64. package/ietf/hidden.js +1 -1
  65. package/ietf/hidden.js.map +1 -1
  66. package/ietf/index.d.ts +1 -1
  67. package/ietf/index.d.ts.map +1 -1
  68. package/ietf/index.js +1 -1
  69. package/ietf/index.js.map +1 -1
  70. package/ietf/object.d.ts +7 -6
  71. package/ietf/object.d.ts.map +1 -1
  72. package/ietf/object.js +37 -33
  73. package/ietf/object.js.map +1 -1
  74. package/ietf/parameters.d.ts +7 -0
  75. package/ietf/parameters.d.ts.map +1 -1
  76. package/ietf/parameters.js +62 -12
  77. package/ietf/parameters.js.map +1 -1
  78. package/ietf/publish_namespace.d.ts +2 -2
  79. package/ietf/publish_namespace.js +2 -2
  80. package/ietf/publish_namespace.js.map +1 -1
  81. package/ietf/publisher.js +287 -172
  82. package/ietf/publisher.js.map +1 -1
  83. package/ietf/subscribe.d.ts +7 -1
  84. package/ietf/subscribe.d.ts.map +1 -1
  85. package/ietf/subscribe.js +22 -14
  86. package/ietf/subscribe.js.map +1 -1
  87. package/ietf/subscribe_namespace.d.ts.map +1 -1
  88. package/ietf/subscribe_namespace.js +2 -3
  89. package/ietf/subscribe_namespace.js.map +1 -1
  90. package/ietf/subscriber.js +57 -42
  91. package/ietf/subscriber.js.map +1 -1
  92. package/ietf/token.d.ts +2 -0
  93. package/ietf/token.d.ts.map +1 -0
  94. package/ietf/token.js +99 -0
  95. package/ietf/token.js.map +1 -0
  96. package/ietf/track.d.ts +4 -0
  97. package/ietf/track.d.ts.map +1 -1
  98. package/ietf/track.js +6 -20
  99. package/ietf/track.js.map +1 -1
  100. package/index.d.ts +1 -1
  101. package/index.d.ts.map +1 -1
  102. package/index.js.map +1 -1
  103. package/internal.d.ts +12 -3
  104. package/internal.d.ts.map +1 -1
  105. package/internal.js +32 -0
  106. package/internal.js.map +1 -1
  107. package/lite/announce.d.ts.map +1 -1
  108. package/lite/announce.js +7 -4
  109. package/lite/announce.js.map +1 -1
  110. package/lite/connection.d.ts.map +1 -1
  111. package/lite/connection.js +22 -7
  112. package/lite/connection.js.map +1 -1
  113. package/lite/datagram.d.ts +3 -2
  114. package/lite/datagram.d.ts.map +1 -1
  115. package/lite/datagram.js +7 -8
  116. package/lite/datagram.js.map +1 -1
  117. package/lite/group.d.ts +12 -8
  118. package/lite/group.d.ts.map +1 -1
  119. package/lite/group.js +37 -16
  120. package/lite/group.js.map +1 -1
  121. package/lite/message.d.ts +2 -2
  122. package/lite/message.d.ts.map +1 -1
  123. package/lite/message.js +14 -5
  124. package/lite/message.js.map +1 -1
  125. package/lite/publisher.js +19 -37
  126. package/lite/publisher.js.map +1 -1
  127. package/lite/setup.d.ts +1 -1
  128. package/lite/setup.d.ts.map +1 -1
  129. package/lite/setup.js +22 -19
  130. package/lite/setup.js.map +1 -1
  131. package/lite/subscriber.d.ts.map +1 -1
  132. package/lite/subscriber.js +206 -127
  133. package/lite/subscriber.js.map +1 -1
  134. package/origin.d.ts +9 -1
  135. package/origin.d.ts.map +1 -1
  136. package/origin.js +341 -146
  137. package/origin.js.map +1 -1
  138. package/package.json +2 -2
  139. package/stream.d.ts +77 -12
  140. package/stream.d.ts.map +1 -1
  141. package/stream.js +359 -122
  142. package/stream.js.map +1 -1
  143. package/tail.d.ts +7 -0
  144. package/tail.d.ts.map +1 -1
  145. package/tail.js +68 -22
  146. package/tail.js.map +1 -1
  147. package/track.d.ts +14 -3
  148. package/track.d.ts.map +1 -1
  149. package/track.js +170 -76
  150. package/track.js.map +1 -1
  151. package/util/abort.d.ts +2 -0
  152. package/util/abort.d.ts.map +1 -0
  153. package/util/abort.js +20 -0
  154. package/util/abort.js.map +1 -0
  155. package/util/u64.d.ts +39 -0
  156. package/util/u64.d.ts.map +1 -0
  157. package/util/u64.js +83 -0
  158. package/util/u64.js.map +1 -0
  159. package/util/varint.d.ts +29 -0
  160. package/util/varint.d.ts.map +1 -0
  161. package/util/varint.js +198 -0
  162. package/util/varint.js.map +1 -0
  163. package/varint.d.ts +10 -6
  164. package/varint.d.ts.map +1 -1
  165. package/varint.js +40 -237
  166. package/varint.js.map +1 -1
  167. package/wire.d.ts +17 -3
  168. package/wire.d.ts.map +1 -1
  169. package/wire.js.map +1 -1
  170. package/ietf/control.d.ts +0 -135
  171. package/ietf/control.d.ts.map +0 -1
  172. package/ietf/control.js +0 -242
  173. package/ietf/control.js.map +0 -1
package/track.js CHANGED
@@ -13,8 +13,13 @@ import { registerTrackConsumer } from "./wire.js";
13
13
  // The largest delay setTimeout keeps: anything more truncates to a signed 32-bit int
14
14
  // and fires right away.
15
15
  const MAX_TIMEOUT_MS = 2 ** 31 - 1;
16
+ // The cache scans at most this many times per retention window.
17
+ const PRUNE_SLICES = 8;
16
18
  /** Default {@link Info.maxAge} window (milliseconds) when the publisher does not set one. */
17
19
  export const DEFAULT_MAX_AGE_MS = Milli(5000);
20
+ // The higher-first midpoint. IETF flips priority (lower first), so this goes out as 128, the
21
+ // draft's usual publisher priority, while moq-lite carries 127 as written: one urgency on both.
22
+ const DEFAULT_PRIORITY = 127;
18
23
  /** Maximum buffered datagrams per subscriber; mirrors Rust's bounded send buffer. */
19
24
  const MAX_DATAGRAMS = 64;
20
25
  /**
@@ -50,7 +55,7 @@ export function infoDefaults(info = {}) {
50
55
  return {
51
56
  timescale: Timescale(info.timescale ?? Timescale.MILLI),
52
57
  maxAge: maxAgeMillis(info.maxAge ?? DEFAULT_MAX_AGE_MS),
53
- priority: priorityByte(info.priority ?? 0),
58
+ priority: priorityByte(info.priority ?? DEFAULT_PRIORITY),
54
59
  };
55
60
  }
56
61
  // Materialize the defaults at the model boundary so every layer observes a complete
@@ -173,6 +178,33 @@ export class Consumer {
173
178
  return this.#broadcast.fetchGroup(this.name, sequence, options);
174
179
  }
175
180
  }
181
+ // The index of the first timeline group at or after `sequence`.
182
+ function timelineIndex(timeline, sequence) {
183
+ let lo = 0;
184
+ let hi = timeline.length;
185
+ while (lo < hi) {
186
+ const mid = (lo + hi) >>> 1;
187
+ if (timeline[mid].sequence < sequence)
188
+ lo = mid + 1;
189
+ else
190
+ hi = mid;
191
+ }
192
+ return lo;
193
+ }
194
+ // Add a group to a sorted timeline, replacing any group with the same sequence. Groups
195
+ // usually arrive in order, so the append is checked first.
196
+ function timelineInsert(timeline, group) {
197
+ const last = timeline.at(-1);
198
+ if (!last || last.sequence < group.sequence) {
199
+ timeline.push(group);
200
+ return;
201
+ }
202
+ const index = timelineIndex(timeline, group.sequence);
203
+ if (timeline[index]?.sequence === group.sequence)
204
+ timeline[index] = group;
205
+ else
206
+ timeline.splice(index, 0, group);
207
+ }
176
208
  // The shared state behind a Producer / Subscriber pair. Package-internal
177
209
  // wiring, unexported so it never appears in the published type declarations.
178
210
  class TrackState {
@@ -180,9 +212,10 @@ class TrackState {
180
212
  producer;
181
213
  groups = new Signal([]);
182
214
  // Every group still in the producer's replay cache, including groups this
183
- // subscriber already consumed, paired with its source queue time. Drift anchors
184
- // have the same lifetime as content.
185
- timeline = new Map();
215
+ // subscriber already consumed, sorted by sequence. Drift anchors have the same
216
+ // lifetime as content. Sorted so the latency guard, evaluated per group and per
217
+ // arrival, searches it instead of scanning the whole retained window.
218
+ timeline = [];
186
219
  // First timestamps mutate group state rather than track state, so held groups
187
220
  // watch this revision as well as arrivals when enforcing latency after handoff.
188
221
  timelineChanged = new Signal(0);
@@ -267,15 +300,24 @@ export class Producer {
267
300
  // read mirrored sinks, never this state directly.
268
301
  #state = new TrackState();
269
302
  #sequence = { next: 0 };
303
+ // One past the highest group or datagram this producer received, like the Rust
304
+ // `max_sequence`. The shared counter above can run ahead of it: sibling producers of
305
+ // the same track advance it too.
306
+ #received = 0;
270
307
  // Recently written source groups, retained for replay to late subscribers and
271
308
  // pruned once idle for longer than the cache window. Each entry tracks the mirror
272
309
  // it handed to every sink so eviction can drop them too: otherwise a slow consumer
273
310
  // that never reads would pin old groups (and their frame bytes) forever.
274
311
  #cache = [];
312
+ // The same entries by sequence, so a write finds a duplicate without a scan.
313
+ #cached = new Map();
314
+ // When the cache was last scanned. See #prune.
315
+ #pruned = Number.NEGATIVE_INFINITY;
275
316
  // Wakeup for the next entry due to age out. Writes settle retention inline, but a
276
317
  // publisher that stalls stops writing, so without this an abandoned group (and any
277
318
  // reader parked in it) would wait for a write that never comes.
278
319
  #pruneTimer;
320
+ #pruneTimerAt = 0;
279
321
  // One independent downstream state per live subscriber.
280
322
  #sinks = new Set();
281
323
  // Whether any subscriber is currently attached. Exposed as {@link used}; the consumer wire
@@ -297,13 +339,13 @@ export class Producer {
297
339
  return resolveInfo(this.#state);
298
340
  }
299
341
  /**
300
- * Publisher priority from the committed {@link Info}, or 0 before {@link accept}.
342
+ * Publisher priority from the committed {@link Info}, or the default before {@link accept}.
301
343
  *
302
344
  * Higher is served first. Hang publishers set this from `Catalog.PRIORITY` so
303
345
  * audio outranks video on the wire and in the bandwidth allocator.
304
346
  */
305
347
  get priority() {
306
- return this.#state.info.peek()?.priority ?? 0;
348
+ return this.#state.info.peek()?.priority ?? DEFAULT_PRIORITY;
307
349
  }
308
350
  /**
309
351
  * Settles once the track closes: `null` on a clean close, or the abort {@link Error}.
@@ -387,6 +429,15 @@ export class Producer {
387
429
  forward();
388
430
  this.#sinks.delete(sink);
389
431
  this.#updateSubscription();
432
+ // Update demand: once the last subscriber leaves, the consumer wire (watching
433
+ // {@link unused}) tears the upstream down instead of downloading to nobody.
434
+ this.#used.set(this.#sinks.size > 0);
435
+ // The producer closing every sink keeps its mirrors tracked, so what the sink
436
+ // still buffers ages out with the cache instead of staying pinned.
437
+ if (this.#state.closed.peek() !== undefined) {
438
+ dispose();
439
+ return;
440
+ }
390
441
  for (const entry of this.#cache) {
391
442
  const mirror = entry.mirrors.get(sink);
392
443
  if (mirror) {
@@ -397,9 +448,6 @@ export class Producer {
397
448
  for (const group of sink.groups.peek())
398
449
  group.close(abort);
399
450
  dispose();
400
- // Update demand: once the last subscriber leaves, the consumer wire (watching
401
- // {@link unused}) tears the upstream down instead of downloading to nobody.
402
- this.#used.set(this.#sinks.size > 0);
403
451
  });
404
452
  }
405
453
  this.#prune();
@@ -424,7 +472,7 @@ export class Producer {
424
472
  #mirror(entry, sink) {
425
473
  const dst = entry.group.mirror();
426
474
  entry.mirrors.set(sink, dst);
427
- sink.timeline.set(dst.sequence, { group: dst, time: entry.time });
475
+ timelineInsert(sink.timeline, dst);
428
476
  void dst.readable().then(() => sink.timelineChanged.update((revision) => revision + 1));
429
477
  sink.latest = Math.max(sink.latest ?? 0, dst.sequence);
430
478
  sink.groups.mutate((groups) => {
@@ -440,19 +488,33 @@ export class Producer {
440
488
  // terminal state.
441
489
  if (!entry.group.isClosed)
442
490
  entry.group.close(new TooFarBehind());
443
- for (const [sink, mirror] of entry.mirrors) {
491
+ const mirrors = [...entry.mirrors.values()];
492
+ for (const mirror of mirrors)
444
493
  hooks.evictGroup(mirror);
494
+ this.#unlink(entry);
495
+ for (const mirror of mirrors)
496
+ mirror.close();
497
+ }
498
+ // Take a cached group's mirrors out of every sink, so a subscriber can no longer
499
+ // receive them. A reader already holding one keeps it as is.
500
+ #unlink(entry) {
501
+ for (const [sink, mirror] of entry.mirrors) {
445
502
  sink.groups.mutate((groups) => {
446
503
  const i = groups.indexOf(mirror);
447
504
  if (i >= 0)
448
505
  groups.splice(i, 1);
449
506
  });
450
- if (sink.timeline.get(mirror.sequence)?.group === mirror)
451
- sink.timeline.delete(mirror.sequence);
452
- mirror.close();
507
+ const index = timelineIndex(sink.timeline, mirror.sequence);
508
+ if (sink.timeline[index] === mirror)
509
+ sink.timeline.splice(index, 1);
453
510
  }
454
511
  entry.mirrors.clear();
455
512
  }
513
+ // Take a cached group out of the cache lookups.
514
+ #uncache(entry) {
515
+ this.#cache.splice(this.#cache.indexOf(entry), 1);
516
+ this.#cached.delete(entry.group.sequence);
517
+ }
456
518
  // The one group retention never takes: the newest, while it is still open. That is
457
519
  // the live edge a publisher is appending to, and a track may legitimately keep it
458
520
  // open across a long quiet stretch (a catalog snapshot, a JSON stream). Every other
@@ -464,46 +526,57 @@ export class Producer {
464
526
  // Evict cached groups idle for longer than the cache window. Idle means nothing
465
527
  // written, so an abandoned open group ages out instead of pinning its buffer (and
466
528
  // any reader parked in it) forever.
529
+ //
530
+ // Scans at most once per slice of the window, so a track publishing faster than that
531
+ // evicts a run of groups per scan instead of scanning everything to evict one per
532
+ // write. A group can outlive the window by up to one slice.
467
533
  #prune() {
468
534
  const maxAgeMs = this.#state.info.peek()?.maxAge ?? DEFAULT_MAX_AGE_MS;
469
- const cutoff = performance.now() - maxAgeMs;
535
+ const now = performance.now();
536
+ const slice = maxAgeMs / PRUNE_SLICES;
537
+ if (now < this.#pruned + slice) {
538
+ // Something may have come due since the last scan, so make sure another follows.
539
+ this.#wake(this.#pruned + slice);
540
+ return;
541
+ }
542
+ this.#pruned = now;
543
+ const cutoff = now - maxAgeMs;
470
544
  const live = this.#liveEdge();
545
+ let oldest;
471
546
  const retained = [];
472
547
  for (const entry of this.#cache) {
473
- if (entry.group === live || entry.group.activity >= cutoff) {
548
+ if (entry.group === live) {
474
549
  retained.push(entry);
475
- continue;
476
550
  }
477
- this.#evict(entry);
551
+ else if (entry.group.activity >= cutoff) {
552
+ retained.push(entry);
553
+ if (oldest === undefined || entry.group.activity < oldest)
554
+ oldest = entry.group.activity;
555
+ }
556
+ else {
557
+ this.#cached.delete(entry.group.sequence);
558
+ this.#evict(entry);
559
+ }
478
560
  }
479
561
  this.#cache = retained;
480
- this.#schedulePrune();
481
- }
482
- // Arm the wakeup for the next entry due to age out, replacing any pending one.
483
- // Writes settle retention inline, so this only has to cover the case no write
484
- // follows. Cheap to over-arm: an entry written since is retained and re-armed.
485
- #schedulePrune() {
562
+ // Replace the wakeup with one for the next entry due to age out. Writes settle
563
+ // retention inline, so this only has to cover the case no write follows. Cheap to
564
+ // over-arm: an entry written since is retained and re-armed.
486
565
  clearTimeout(this.#pruneTimer);
487
566
  this.#pruneTimer = undefined;
488
- if (this.#state.closed.peek() !== undefined)
489
- return;
490
- // One pass, no intermediate arrays: this runs on every publish, and a spread
491
- // over the cache would also cap how many groups a track can hold.
492
- const live = this.#liveEdge();
493
- let oldest;
494
- for (const entry of this.#cache) {
495
- if (entry.group === live)
496
- continue;
497
- if (oldest === undefined || entry.group.activity < oldest)
498
- oldest = entry.group.activity;
499
- }
500
- if (oldest === undefined)
567
+ if (oldest !== undefined)
568
+ this.#wake(Math.max(oldest + maxAgeMs, now + slice));
569
+ }
570
+ // Arm the prune wakeup for `at`, unless one is already armed sooner. Kept after a close,
571
+ // until the cache empties, so what the track left behind still ages out.
572
+ #wake(at) {
573
+ if (this.#pruneTimer !== undefined && this.#pruneTimerAt <= at)
501
574
  return;
502
- const maxAgeMs = this.#state.info.peek()?.maxAge ?? DEFAULT_MAX_AGE_MS;
575
+ clearTimeout(this.#pruneTimer);
503
576
  // setTimeout truncates its delay to a signed 32-bit int, so a longer window
504
577
  // would fire immediately and spin. Wake at the cap instead and re-arm: #prune
505
578
  // retains anything still fresh, so the extra wakeups are the only cost.
506
- const delay = Math.min(MAX_TIMEOUT_MS, Math.max(0, oldest + maxAgeMs - performance.now()));
579
+ const delay = Math.min(MAX_TIMEOUT_MS, Math.max(0, at - performance.now()));
507
580
  const timer = setTimeout(() => {
508
581
  this.#pruneTimer = undefined;
509
582
  this.#prune();
@@ -511,11 +584,14 @@ export class Producer {
511
584
  // A cache prune is never a reason to hold a Node/Bun process open.
512
585
  timer.unref?.();
513
586
  this.#pruneTimer = timer;
587
+ this.#pruneTimerAt = at;
514
588
  }
515
589
  // Retain a source group and fan it out to every live sink.
516
590
  #publish(group) {
517
- const entry = { group, time: performance.now(), mirrors: new Map() };
591
+ const entry = { group, mirrors: new Map() };
518
592
  this.#cache.push(entry);
593
+ this.#cached.set(group.sequence, entry);
594
+ this.#received = Math.max(this.#received, group.sequence + 1);
519
595
  for (const sink of this.#sinks)
520
596
  this.#mirror(entry, sink);
521
597
  // Give held mirrors the new live edge before pruning their timeline entry,
@@ -550,14 +626,13 @@ export class Producer {
550
626
  */
551
627
  writeGroup(group) {
552
628
  this.#writable(group.sequence);
553
- const existing = this.#cache.findIndex((entry) => entry.group.sequence === group.sequence);
554
- if (existing >= 0) {
555
- const entry = this.#cache[existing];
556
- if (!(entry.group.closed.peek() instanceof Error)) {
629
+ const existing = this.#cached.get(group.sequence);
630
+ if (existing) {
631
+ if (!(existing.group.closed.peek() instanceof Error)) {
557
632
  throw new Error(`duplicate group: sequence=${group.sequence}`);
558
633
  }
559
- this.#evict(entry);
560
- this.#cache.splice(existing, 1);
634
+ this.#evict(existing);
635
+ this.#uncache(existing);
561
636
  }
562
637
  // Only advance the shared counter upward (for appendGroup auto-increment).
563
638
  const sequence = this.#sequence;
@@ -569,6 +644,7 @@ export class Producer {
569
644
  // Fan a datagram out to every live subscriber, dropping the oldest once the ring is full.
570
645
  // Late subscribers do NOT replay old datagrams (best-effort, unlike the group cache).
571
646
  #publishDatagram(datagram) {
647
+ this.#received = Math.max(this.#received, datagram.sequence + 1);
572
648
  for (const sink of this.#sinks) {
573
649
  sink.datagrams.mutate((list) => {
574
650
  if (list.length === MAX_DATAGRAMS)
@@ -634,8 +710,8 @@ export class Producer {
634
710
  const declared = this.#state.final.peek();
635
711
  if (declared !== undefined)
636
712
  throw new Error(`track already ends at ${declared}`);
637
- if (final < this.#sequence.next) {
638
- throw new Error(`track end ${final} is below the next sequence ${this.#sequence.next}`);
713
+ if (final < this.#received) {
714
+ throw new Error(`track end ${final} is below the next sequence ${this.#received}`);
639
715
  }
640
716
  this.#declareFinal(final);
641
717
  }
@@ -648,23 +724,45 @@ export class Producer {
648
724
  * Close the track and every subscriber, mirroring the abort to their groups. Idempotent.
649
725
  *
650
726
  * A clean close keeps the end {@link finishAt} declared, or declares one past the highest
651
- * sequence produced; an abort ends without one.
727
+ * sequence produced; an abort ends without one. Subscribers still draining get the
728
+ * finished groups first, then the end or the abort. An abort after the declared end
729
+ * settled (reached, with every group below it finished) is a clean close. The groups
730
+ * left behind still age out after the track's `maxAge`, so a stale subscriber can't pin
731
+ * them.
652
732
  */
653
733
  close(abort) {
654
- if (abort === undefined && this.#state.closed.peek() === undefined && this.#state.final.peek() === undefined) {
655
- this.#declareFinal(this.#sequence.next);
734
+ if (this.#state.closed.peek() !== undefined)
735
+ return;
736
+ if (abort && this.#settled())
737
+ abort = undefined;
738
+ if (abort === undefined && this.#state.final.peek() === undefined) {
739
+ this.#declareFinal(this.#received);
656
740
  }
741
+ // Nobody will finish these, so a subscriber that has not taken one yet never sees it.
742
+ // Not evicted: a reader already holding one keeps its frames and sees the abort.
743
+ const open = abort ? this.#cache.filter((entry) => entry.group.closed.peek() === undefined) : [];
657
744
  closeTrackState(this.#state, abort);
658
- clearTimeout(this.#pruneTimer);
659
- this.#pruneTimer = undefined;
660
745
  for (const { group } of this.#cache)
661
746
  group.close(abort);
747
+ for (const entry of open) {
748
+ this.#unlink(entry);
749
+ this.#uncache(entry);
750
+ }
662
751
  for (const sink of this.#sinks) {
663
752
  for (const group of sink.groups.peek())
664
753
  group.close(abort);
665
754
  closeTrackState(sink, abort);
666
755
  }
667
756
  this.#sinks.clear();
757
+ this.#prune();
758
+ }
759
+ // Whether the declared end was reached and every cached group below it finished, so
760
+ // the track already holds everything it promised. Mirrors the Rust `is_settled`.
761
+ #settled() {
762
+ const final = this.#state.final.peek();
763
+ if (final === undefined || this.#received < final)
764
+ return false;
765
+ return this.#cache.every(({ group }) => group.sequence >= final || group.closed.peek() === null);
668
766
  }
669
767
  /** Append a frame as its own single-frame group. */
670
768
  writeFrame(frame) {
@@ -715,18 +813,19 @@ export class Subscriber {
715
813
  #frameGroup;
716
814
  #drift() {
717
815
  const { end } = this.#cursor.peek();
816
+ const timeline = this.#state.timeline;
718
817
  let presentation;
719
- for (const { group } of this.#state.timeline.values()) {
720
- if (end !== undefined && group.sequence >= end)
721
- continue;
818
+ // The edge wants the newest content that exists, so it takes the newest
819
+ // stamped group's latest frame: walk back from the cap to the first one.
820
+ for (let i = (end === undefined ? timeline.length : timelineIndex(timeline, end)) - 1; i >= 0; i--) {
821
+ const group = timeline[i];
722
822
  if (group.closed.peek() instanceof Error)
723
823
  continue;
724
- // The edge wants the newest content that exists, so it takes the newest
725
- // stamped group's latest frame.
726
824
  const timestamp = hooks.groupTimestamp(group);
727
- if (timestamp !== undefined && (!presentation || group.sequence > presentation.sequence)) {
728
- presentation = { sequence: group.sequence, timestamp: hooks.groupLatest(group) ?? timestamp };
729
- }
825
+ if (timestamp === undefined)
826
+ continue;
827
+ presentation = { sequence: group.sequence, timestamp: hooks.groupLatest(group) ?? timestamp };
828
+ break;
730
829
  }
731
830
  const requested = this.#state.update.peek()?.maxAge ?? 0;
732
831
  const retained = this.#state.info.peek()?.maxAge;
@@ -749,20 +848,16 @@ export class Subscriber {
749
848
  // unstamped successor will begin, and shrinking the bound is the unsafe direction.
750
849
  // An unstamped successor leaves the reach unbounded until it presents a frame.
751
850
  #reach(sequence, end) {
752
- let successor;
753
- for (const { group } of this.#state.timeline.values()) {
754
- if (group.sequence <= sequence)
755
- continue;
756
- if (end !== undefined && group.sequence >= end)
757
- continue;
758
- if (group.closed.peek() instanceof Error)
851
+ const timeline = this.#state.timeline;
852
+ for (let i = timelineIndex(timeline, sequence + 1); i < timeline.length; i++) {
853
+ const successor = timeline[i];
854
+ if (end !== undefined && successor.sequence >= end)
855
+ break;
856
+ if (successor.closed.peek() instanceof Error)
759
857
  continue;
760
- if (!successor || group.sequence < successor.sequence)
761
- successor = group;
858
+ return hooks.groupTimestamp(successor)?.asMillis();
762
859
  }
763
- if (!successor)
764
- return undefined;
765
- return hooks.groupTimestamp(successor)?.asMillis();
860
+ return undefined;
766
861
  }
767
862
  // Whether the drift budget says to give up on `group`.
768
863
  //
@@ -781,8 +876,7 @@ export class Subscriber {
781
876
  // falls out for free. Only timestamps drive expiry; wall-clock reclamation of idle
782
877
  // content is the cache's own policy, not the budget's.
783
878
  #isStale(group, drift) {
784
- const candidate = this.#state.timeline.get(group.sequence);
785
- if (candidate?.group !== group)
879
+ if (this.#state.timeline[timelineIndex(this.#state.timeline, group.sequence)] !== group)
786
880
  return false;
787
881
  const reach = this.#reach(group.sequence, drift.end);
788
882
  return (drift.presentation !== undefined &&
@@ -969,7 +1063,7 @@ export class Subscriber {
969
1063
  });
970
1064
  this.#frameGroup?.close(abort);
971
1065
  this.#frameGroup = undefined;
972
- this.#state.timeline.clear();
1066
+ this.#state.timeline.length = 0;
973
1067
  }
974
1068
  /**
975
1069
  * Receive every group on this track exactly once, as it becomes available.