@moq/net 0.3.3 → 0.3.5

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 (101) hide show
  1. package/README.md +2 -2
  2. package/broadcast.d.ts.map +1 -1
  3. package/broadcast.js +5 -4
  4. package/broadcast.js.map +1 -1
  5. package/connection/accept.d.ts.map +1 -1
  6. package/connection/accept.js +3 -0
  7. package/connection/accept.js.map +1 -1
  8. package/connection/browser.d.ts.map +1 -1
  9. package/connection/browser.js +3 -0
  10. package/connection/browser.js.map +1 -1
  11. package/connection/connect.d.ts.map +1 -1
  12. package/connection/connect.js +23 -12
  13. package/connection/connect.js.map +1 -1
  14. package/group.d.ts +19 -1
  15. package/group.d.ts.map +1 -1
  16. package/group.js +35 -11
  17. package/group.js.map +1 -1
  18. package/ietf/adapter.d.ts.map +1 -1
  19. package/ietf/adapter.js +76 -45
  20. package/ietf/adapter.js.map +1 -1
  21. package/ietf/fetch.d.ts +17 -0
  22. package/ietf/fetch.d.ts.map +1 -1
  23. package/ietf/fetch.js +21 -0
  24. package/ietf/fetch.js.map +1 -1
  25. package/ietf/filter.d.ts +87 -0
  26. package/ietf/filter.d.ts.map +1 -0
  27. package/ietf/filter.js +292 -0
  28. package/ietf/filter.js.map +1 -0
  29. package/ietf/namespace.d.ts +6 -0
  30. package/ietf/namespace.d.ts.map +1 -1
  31. package/ietf/namespace.js +27 -2
  32. package/ietf/namespace.js.map +1 -1
  33. package/ietf/object.d.ts +44 -2
  34. package/ietf/object.d.ts.map +1 -1
  35. package/ietf/object.js +74 -9
  36. package/ietf/object.js.map +1 -1
  37. package/ietf/parameters.d.ts +16 -4
  38. package/ietf/parameters.d.ts.map +1 -1
  39. package/ietf/parameters.js +54 -10
  40. package/ietf/parameters.js.map +1 -1
  41. package/ietf/properties.d.ts +5 -0
  42. package/ietf/properties.d.ts.map +1 -1
  43. package/ietf/properties.js +5 -0
  44. package/ietf/properties.js.map +1 -1
  45. package/ietf/publisher.d.ts.map +1 -1
  46. package/ietf/publisher.js +426 -53
  47. package/ietf/publisher.js.map +1 -1
  48. package/ietf/subscribe.d.ts +38 -7
  49. package/ietf/subscribe.d.ts.map +1 -1
  50. package/ietf/subscribe.js +94 -29
  51. package/ietf/subscribe.js.map +1 -1
  52. package/ietf/subscriber.d.ts.map +1 -1
  53. package/ietf/subscriber.js +27 -4
  54. package/ietf/subscriber.js.map +1 -1
  55. package/ietf/version.d.ts +7 -1
  56. package/ietf/version.d.ts.map +1 -1
  57. package/ietf/version.js +7 -0
  58. package/ietf/version.js.map +1 -1
  59. package/internal.d.ts +2 -0
  60. package/internal.d.ts.map +1 -1
  61. package/internal.js.map +1 -1
  62. package/lite/announce.d.ts.map +1 -1
  63. package/lite/announce.js +7 -7
  64. package/lite/announce.js.map +1 -1
  65. package/lite/publisher.d.ts.map +1 -1
  66. package/lite/publisher.js +98 -78
  67. package/lite/publisher.js.map +1 -1
  68. package/lite/setup.d.ts.map +1 -1
  69. package/lite/setup.js +2 -1
  70. package/lite/setup.js.map +1 -1
  71. package/lite/subscriber.d.ts +1 -6
  72. package/lite/subscriber.d.ts.map +1 -1
  73. package/lite/subscriber.js +98 -23
  74. package/lite/subscriber.js.map +1 -1
  75. package/lite/version.d.ts +4 -0
  76. package/lite/version.d.ts.map +1 -1
  77. package/lite/version.js +15 -0
  78. package/lite/version.js.map +1 -1
  79. package/origin.d.ts +1 -1
  80. package/origin.d.ts.map +1 -1
  81. package/origin.js +1 -1
  82. package/origin.js.map +1 -1
  83. package/package.json +4 -3
  84. package/stream.d.ts.map +1 -1
  85. package/stream.js +5 -7
  86. package/stream.js.map +1 -1
  87. package/track.d.ts +45 -1
  88. package/track.d.ts.map +1 -1
  89. package/track.js +90 -13
  90. package/track.js.map +1 -1
  91. package/util/log.d.ts +5 -0
  92. package/util/log.d.ts.map +1 -0
  93. package/util/log.js +17 -0
  94. package/util/log.js.map +1 -0
  95. package/util/utf8.d.ts +3 -0
  96. package/util/utf8.d.ts.map +1 -0
  97. package/util/utf8.js +7 -0
  98. package/util/utf8.js.map +1 -0
  99. package/zod.d.ts +1 -1
  100. package/zod.d.ts.map +1 -1
  101. package/zod.js.map +1 -1
package/ietf/publisher.js CHANGED
@@ -5,8 +5,11 @@ import * as Path from "../path.js";
5
5
  import { Writer } from "../stream.js";
6
6
  import { withTimeout } from "../util/timeout.js";
7
7
  import * as Cluster from "./cluster.js";
8
- import { Frame, Group as GroupMessage } from "./object.js";
8
+ import { FetchHeader } from "./fetch.js";
9
+ import * as Filter from "./filter.js";
10
+ import { FetchFrame, Frame, Group as GroupMessage } from "./object.js";
9
11
  import { fromWire } from "./priority.js";
12
+ import * as Properties from "./properties.js";
10
13
  import { PublishDone } from "./publish.js";
11
14
  import { PublishNamespace, PublishNamespaceDone, PublishNamespaceOk } from "./publish_namespace.js";
12
15
  import { RequestError, RequestOk } from "./request.js";
@@ -18,6 +21,11 @@ import { Version } from "./version.js";
18
21
  const RETRY_BASE = 100;
19
22
  /** Ceiling on that wait. The loop retries for the life of the session, so it must not spin. */
20
23
  const RETRY_MAX = 5000;
24
+ /** PUBLISH_DONE statuses this implementation emits. Stable across drafts 14 through 19. */
25
+ const PUBLISH_DONE_STATUS = {
26
+ INTERNAL_ERROR: 0x0,
27
+ TRACK_ENDED: 0x2,
28
+ };
21
29
  /**
22
30
  * How long one advertisement may take to be answered. Matches the Rust publisher, and the
23
31
  * peer accepting the stream is only half the exchange: one it never answers on holds the
@@ -109,11 +117,37 @@ export class Publisher {
109
117
  stream.close();
110
118
  return;
111
119
  }
112
- const track = broadcast.subscribe(msg.trackName, { priority: fromWire(msg.subscriberPriority) });
120
+ const priority = fromWire(msg.subscriberPriority);
121
+ const track = broadcast.subscribe(msg.trackName, { priority });
122
+ // Hoisted so the cleanup below reaches it: the fork happens before SUBSCRIBE_OK is
123
+ // written, and a write that throws must not strand the sink it attached.
124
+ let cache;
113
125
  try {
114
- // Declaring the timescale is what opts the track into timestamps; every object
115
- // Timestamp below is in these units.
116
126
  const timescale = (await track.info()).timescale;
127
+ // The filter and any fill are relative to the live edge, so snapshot it once: the
128
+ // fill ends exactly where a Next Object subscription begins, which is what lets
129
+ // the draft's current-group join (Next Object plus a StartGroup=1 fill) cover the
130
+ // group with no gap and no overlap.
131
+ const edge = liveEdge(track);
132
+ const range = subscribeRange(msg, edge, version);
133
+ // The wire request tells an upstream what we need; the cursor is what actually
134
+ // trims this subscriber, since the producer fans every cached group out to every
135
+ // sink regardless. An absent start joins at the latest group, which is what
136
+ // moq-lite means by joining a live track.
137
+ track.update({
138
+ priority,
139
+ startGroup: range.start && Number(range.start.group),
140
+ endGroup: range.end && Number(range.end.group),
141
+ });
142
+ const startGroup = range.start ? Number(range.start.group) : track.latest();
143
+ if (startGroup !== undefined)
144
+ track.startAt(startGroup);
145
+ // A fill reads the group cache through its own consumer, independent of the
146
+ // subscription's cursor. Forked from this subscriber rather than resolved through
147
+ // the broadcast again: a dynamic serve is one request per peer subscription, so
148
+ // asking the broadcast would mint a second producer nobody has accepted.
149
+ const fill = msg.fill && Filter.isDraft20(version) ? fillRange(msg.fill, msg.filter, edge.largest) : undefined;
150
+ cache = fill && fill.kind !== "empty" ? track.fork({ priority }) : undefined;
117
151
  // Send SUBSCRIBE_OK
118
152
  await stream.writer.u53(SubscribeOk.id);
119
153
  const ok = new SubscribeOk({
@@ -121,7 +155,17 @@ export class Publisher {
121
155
  ? msg.requestId
122
156
  : undefined,
123
157
  trackAlias: msg.requestId,
124
- timescale,
158
+ // Required once the track has content; a fill-requesting subscriber sizes its
159
+ // backfill against this.
160
+ largest: edge.largest && { groupId: edge.largest.group, objectId: edge.largest.object },
161
+ properties: msg.propertiesWanted
162
+ ? // Declaring the timescale is what opts the track into timestamps; every
163
+ // object Timestamp below is in these units. We serve the newest group
164
+ // first, matching moq-lite.
165
+ { timescale, groupOrder: Properties.DESCENDING }
166
+ : // INCLUDE_PROPERTIES=0. The block stays present but empty, which also means
167
+ // the track opts out of timestamps for this subscriber.
168
+ {},
125
169
  });
126
170
  await ok.encode(stream.writer, version);
127
171
  console.debug(`publish ok: broadcast=${name} track=${track.name}`);
@@ -145,25 +189,64 @@ export class Publisher {
145
189
  const group = await track.recvGroup();
146
190
  if (!group)
147
191
  return;
148
- void this.#runGroup({ requestId: msg.requestId, group, timescale, unsubscribed });
149
- }
150
- })();
151
- await Promise.race([serving, stream.reader.closed]);
152
- console.debug(`publish done: broadcast=${name} track=${track.name}`);
153
- // v14-v16: send PublishDone before closing
154
- if (version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16) {
155
- try {
156
- await stream.writer.u53(PublishDone.id);
157
- const done = new PublishDone({
192
+ // Past the filter's end. Dropped here rather than through `endAt`, which
193
+ // parks a capped group instead: this range is fixed for the life of the
194
+ // subscription, so a group above it is never coming back in, and holding
195
+ // one keeps the loop from ever ending. A producer that publishes beyond
196
+ // the end and then closes would otherwise strand PUBLISH_DONE.
197
+ if (range.end !== undefined && BigInt(group.sequence) > range.end.group) {
198
+ group.close();
199
+ continue;
200
+ }
201
+ void this.#runGroup({
158
202
  requestId: msg.requestId,
159
- statusCode: 200,
160
- reasonPhrase: "OK",
203
+ group,
204
+ timescale,
205
+ stamped: msg.propertiesWanted,
206
+ slice: groupSlice(range, group.sequence),
207
+ unsubscribed,
161
208
  });
162
- await done.encode(stream.writer, version);
163
- }
164
- catch {
165
- // Stream might already be closed by peer
166
209
  }
210
+ })();
211
+ // The fill (when one was requested) runs alongside on its own fetch stream; its
212
+ // failures reset that stream and never touch the subscription.
213
+ const filling = fill && cache
214
+ ? this.#runFill({
215
+ requestId: msg.requestId,
216
+ priority,
217
+ fill,
218
+ cache,
219
+ timescale,
220
+ stamped: msg.propertiesWanted,
221
+ unsubscribed,
222
+ })
223
+ : Promise.resolve();
224
+ let publishError;
225
+ try {
226
+ await Promise.race([Promise.all([serving, filling]), stream.reader.closed]);
227
+ }
228
+ catch (err) {
229
+ publishError = error(err);
230
+ }
231
+ console.debug(`publish done: broadcast=${name} track=${track.name}`);
232
+ if (publishError) {
233
+ console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(publishError)}`);
234
+ }
235
+ // PUBLISH_DONE is required for every supported draft. The peer may have already
236
+ // closed its side to unsubscribe, in which case there is nowhere to send it.
237
+ try {
238
+ await stream.writer.u53(PublishDone.id);
239
+ const done = new PublishDone({
240
+ requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
241
+ ? msg.requestId
242
+ : undefined,
243
+ statusCode: publishError ? PUBLISH_DONE_STATUS.INTERNAL_ERROR : PUBLISH_DONE_STATUS.TRACK_ENDED,
244
+ reasonPhrase: publishError ? "internal error" : "track ended",
245
+ });
246
+ await done.encode(stream.writer, version);
247
+ }
248
+ catch {
249
+ // Stream might already be closed by peer.
167
250
  }
168
251
  // Only now is the close below ours. Claiming it any earlier would read a peer FIN
169
252
  // that lands while PublishDone is still going out as our own completion, leaving
@@ -178,13 +261,16 @@ export class Publisher {
178
261
  }
179
262
  finally {
180
263
  track.close();
264
+ // Idempotent, and the backstop for a throw between the fork and the fill starting:
265
+ // #runFill closes it itself on every path it reaches.
266
+ cache?.close();
181
267
  }
182
268
  }
183
269
  /**
184
270
  * Runs a group and sends its frames using ObjectStream (Subgroup delivery mode).
185
271
  */
186
272
  async #runGroup(options) {
187
- const { requestId, group, timescale, unsubscribed } = options;
273
+ const { requestId, group, timescale, stamped, slice, unsubscribed } = options;
188
274
  try {
189
275
  // One stream per group is faster than a peer at its limit can retire them, so this
190
276
  // is the one path that doesn't wait for a slot: the transport would serve the opens
@@ -205,21 +291,47 @@ export class Publisher {
205
291
  subGroupId: 0,
206
292
  publisherPriority: 0,
207
293
  flags: {
208
- hasExtensions: true,
294
+ // The object properties carry the timestamp, so there is nothing to write
295
+ // when the track declared no units to read one in.
296
+ hasExtensions: stamped,
209
297
  hasSubgroup: false,
210
298
  hasSubgroupObject: false,
211
299
  hasEnd: true,
212
300
  hasPriority: true,
301
+ // Only honest when the stream really starts at the group's first object;
302
+ // a trimmed head starts partway through.
303
+ firstObject: slice.skip === 0,
213
304
  },
214
305
  });
215
306
  await header.encode(stream, this.#session.version);
216
307
  try {
308
+ // The first written object goes on the wire as its absolute id, so a trimmed
309
+ // head shows the true numbering rather than a silently renumbered group.
310
+ let first = true;
311
+ // The next object id that could be written, which starts at the filter rather
312
+ // than at zero. A backwards range (`startObject` above `endObject` in the same
313
+ // group) is empty, and starting here is what lets the check below see that
314
+ // before the read parks on an object the range already excludes.
315
+ let next = slice.skip;
217
316
  for (;;) {
218
- const frame = await Promise.race([group.readFrame(), stream.closed]);
317
+ // The filter ends inside this group: everything at `until` and beyond is
318
+ // outside the requested range, so stop without waiting for the group's end.
319
+ if (slice.until !== undefined && next >= slice.until)
320
+ break;
321
+ // Reading from the filter's start drops the objects below it, including any the
322
+ // group's cache evicted: they are outside the requested range, so losing them is
323
+ // not the gap that would otherwise reset this stream and forfeit the rest of the
324
+ // group. An eviction at or above the start is a real gap and still throws.
325
+ const frame = await Promise.race([group.readFrameSequence({ from: slice.skip }), stream.closed]);
219
326
  if (!frame)
220
327
  break;
328
+ next = frame.sequence + 1;
329
+ if (slice.until !== undefined && frame.sequence >= slice.until)
330
+ break;
221
331
  const obj = new Frame({ payload: frame.payload, timestamp: frame.timestamp });
222
- await obj.encode(stream, header.flags, timescale, this.#session.version);
332
+ const delta = first ? frame.sequence : 0;
333
+ first = false;
334
+ await obj.encode(stream, header.flags, timescale, this.#session.version, delta);
223
335
  }
224
336
  stream.close();
225
337
  }
@@ -231,6 +343,95 @@ export class Publisher {
231
343
  group.close();
232
344
  }
233
345
  }
346
+ /**
347
+ * Serve a draft-20 fill on its own fetch stream: the requested range, read from the
348
+ * group cache, capped at the Largest Object snapshot.
349
+ *
350
+ * A fill is a promise once requested. An empty range opens no stream, but a range we
351
+ * cannot serve still opens one and resets it right after the FETCH_HEADER, the draft's
352
+ * fill-failure signal. Nothing here touches the subscription either way.
353
+ */
354
+ async #runFill(options) {
355
+ const { requestId, fill, cache, timescale, stamped, unsubscribed } = options;
356
+ const version = this.#session.version;
357
+ // Everything is inside the try so the cache fork is released on every path out,
358
+ // including a transport failure while opening the stream.
359
+ let stream;
360
+ try {
361
+ if (fill.kind === "empty")
362
+ return;
363
+ stream = await Writer.tryOpen(this.#quic, { cancel: unsubscribed, version });
364
+ if (!stream) {
365
+ console.debug(`fill stream failed to open: fill=${requestId}`);
366
+ return;
367
+ }
368
+ await stream.u53(FetchHeader.type);
369
+ await new FetchHeader({ requestId }).encode(stream, version);
370
+ if (fill.kind !== "group") {
371
+ throw new Error("a fill spanning several groups is not supported");
372
+ }
373
+ const group = takeGroup(cache, Number(fill.sequence));
374
+ try {
375
+ await this.#writeFillGroup(stream, group, fill, timescale, stamped, unsubscribed);
376
+ }
377
+ finally {
378
+ group.close();
379
+ }
380
+ stream.close();
381
+ console.debug(`fill complete: fill=${requestId}`);
382
+ }
383
+ catch (err) {
384
+ // A fill never fails the subscription; its own stream carries the failure.
385
+ const e = error(err);
386
+ console.debug(`fill failed, resetting its stream: fill=${requestId} error=${reason(e)}`);
387
+ stream?.reset(e);
388
+ }
389
+ finally {
390
+ cache.close();
391
+ }
392
+ }
393
+ /**
394
+ * Write one cached group's frames as draft-20 fetch objects.
395
+ *
396
+ * The cap is the Largest Object snapshot: the group may keep growing, but everything
397
+ * past the snapshot belongs to the subscription, not the fill.
398
+ */
399
+ async #writeFillGroup(stream, group, fill, timescale, stamped, unsubscribed) {
400
+ let first = true;
401
+ let next = 0n;
402
+ // The subscriber leaving has to end the fill too. An absolute filter ending below the
403
+ // edge with no end object leaves `until` unset, so this reads until the group closes,
404
+ // which a still-open past group may never do. Watching only the fetch stream would
405
+ // then pin the group and the cache subscription behind it for the life of the track.
406
+ let left = false;
407
+ const cancelled = unsubscribed.then(() => {
408
+ left = true;
409
+ return undefined;
410
+ });
411
+ for (;;) {
412
+ // The group may keep growing, but everything at `until` and beyond belongs to the
413
+ // subscription, so stop without waiting for the group's end.
414
+ if (fill.until !== undefined && next >= fill.until)
415
+ break;
416
+ // Reading from the fill's start drops everything below it, evicted objects included;
417
+ // see the same read in #runGroup.
418
+ const frame = await Promise.race([
419
+ group.readFrameSequence({ from: Number(fill.skip) }),
420
+ stream.closed,
421
+ cancelled,
422
+ ]);
423
+ if (left)
424
+ throw new Error("unsubscribed before the fill finished");
425
+ if (!frame)
426
+ break;
427
+ next = BigInt(frame.sequence) + 1n;
428
+ if (fill.until !== undefined && BigInt(frame.sequence) >= fill.until)
429
+ break;
430
+ const obj = new FetchFrame({ payload: frame.payload, timestamp: stamped ? frame.timestamp : undefined });
431
+ await obj.encode(stream, { group: Number(fill.sequence), object: frame.sequence, first }, timescale, this.#session.version);
432
+ first = false;
433
+ }
434
+ }
234
435
  /**
235
436
  * Handles an incoming SUBSCRIBE_NAMESPACE on a bidi stream.
236
437
  *
@@ -287,7 +488,10 @@ export class Publisher {
287
488
  await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
288
489
  }
289
490
  };
290
- let active = new Set();
491
+ // Which producer holds each advertised suffix. Keyed on the producer rather than
492
+ // the path alone, so a path handed to a new producer is withdrawn and re-offered
493
+ // instead of diffing away to nothing and leaving the peer on the dead generation.
494
+ let active = new Map();
291
495
  let retry = 0;
292
496
  // What the peer refused, and whether coming back is worth anything.
293
497
  const refused = new Map();
@@ -305,16 +509,16 @@ export class Publisher {
305
509
  dispose();
306
510
  break;
307
511
  }
308
- const updated = new Set();
309
- for (const name of broadcasts.keys()) {
512
+ const updated = new Map();
513
+ for (const [name, producer] of broadcasts) {
310
514
  const suffix = Path.stripPrefix(prefix, name);
311
515
  if (suffix === null)
312
516
  continue;
313
- updated.add(suffix);
517
+ updated.set(suffix, producer);
314
518
  }
315
519
  // A namespace that is gone takes its refusal with it, so re-announcing the
316
520
  // path offers it again.
317
- const live = new Set([...updated].map((suffix) => Path.join(prefix, suffix)));
521
+ const live = new Set([...updated.keys()].map((suffix) => Path.join(prefix, suffix)));
318
522
  for (const path of [...refused.keys()]) {
319
523
  if (!live.has(path))
320
524
  refused.delete(path);
@@ -322,22 +526,27 @@ export class Publisher {
322
526
  // Track what the peer holds rather than what we attempted: a declined
323
527
  // advertisement stays out of `held`, so the next turn retries it instead of
324
528
  // believing the namespace is already up.
325
- const held = new Set(active);
326
- for (const added of updated.difference(active)) {
327
- if (this.#offerable(Path.join(prefix, added), refused)) {
328
- if (await advertise(added))
329
- held.add(added);
330
- }
529
+ const held = new Map(active);
530
+ // Withdraw first, so a replacement reads as an end followed by a start.
531
+ for (const [suffix, producer] of active) {
532
+ if (updated.get(suffix) === producer)
533
+ continue;
534
+ await withdraw(suffix);
535
+ held.delete(suffix);
331
536
  }
332
- for (const removed of active.difference(updated)) {
333
- await withdraw(removed);
334
- held.delete(removed);
537
+ for (const [suffix, producer] of updated) {
538
+ if (active.get(suffix) === producer)
539
+ continue;
540
+ if (this.#offerable(Path.join(prefix, suffix), refused)) {
541
+ if (await advertise(suffix))
542
+ held.set(suffix, producer);
543
+ }
335
544
  }
336
545
  active = held;
337
546
  // Whatever we wanted up and could not get up, as {@link runPublishNamespaces}
338
547
  // does: only a legacy request can be declined, and nothing about the peer
339
548
  // starting to answer raises a signal this loop is watching.
340
- const outstanding = [...updated.difference(active)].some((suffix) => this.#pending(Path.join(prefix, suffix), refused));
549
+ const outstanding = [...updated].some(([suffix, producer]) => active.get(suffix) !== producer && this.#pending(Path.join(prefix, suffix), refused));
341
550
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
342
551
  // Wait for the next change, or for the peer to unsubscribe.
343
552
  const next = await (retry
@@ -380,8 +589,10 @@ export class Publisher {
380
589
  }
381
590
  // The open PUBLISH_NAMESPACE request per advertised path.
382
591
  const requests = new Map();
592
+ let dispose;
383
593
  try {
384
- let active = new Set();
594
+ // Which producer holds each advertised path; see {@link runSubscribeNamespace}.
595
+ let active = new Map();
385
596
  let retry = 0;
386
597
  // What the peer refused, and whether coming back is worth anything.
387
598
  const refused = new Map();
@@ -392,43 +603,53 @@ export class Publisher {
392
603
  // through it and leave the namespace unadvertised until something unrelated
393
604
  // changed.
394
605
  // TODO Make a better helper within Signals.
395
- let dispose;
396
606
  const changed = new Promise((resolve) => {
397
607
  dispose = this.#broadcasts.changed(resolve);
398
608
  });
399
609
  const broadcasts = this.#broadcasts.peek();
400
610
  if (!broadcasts) {
401
- dispose();
611
+ dispose?.();
402
612
  break;
403
613
  }
404
- const updated = new Set(broadcasts.keys());
614
+ const updated = new Map(broadcasts);
405
615
  // A namespace that is gone takes its refusal with it, so re-announcing the
406
616
  // path offers it again. Rust gets this by rebuilding the watched entry.
407
617
  for (const path of [...refused.keys()]) {
408
618
  if (!updated.has(path))
409
619
  refused.delete(path);
410
620
  }
411
- for (const added of updated.difference(active)) {
412
- if (this.#offerable(added, refused)) {
413
- await this.#advertise(added, requests, refused);
414
- }
621
+ // Withdraw first, so a replacement reads as an end followed by a start.
622
+ for (const [path, producer] of active) {
623
+ if (updated.get(path) === producer)
624
+ continue;
625
+ await this.#withdraw(path, requests);
415
626
  }
416
- for (const removed of active.difference(updated)) {
417
- await this.#withdraw(removed, requests);
627
+ for (const [path, producer] of updated) {
628
+ if (active.get(path) === producer)
629
+ continue;
630
+ if (this.#offerable(path, refused)) {
631
+ await this.#advertise(path, requests, refused);
632
+ }
418
633
  }
419
634
  // What the peer holds, not what we attempted: a declined PUBLISH_NAMESPACE
420
635
  // leaves no request behind, so it stays outstanding below.
421
- active = new Set(requests.keys());
636
+ const held = new Map();
637
+ for (const path of requests.keys()) {
638
+ const producer = updated.get(path);
639
+ if (producer)
640
+ held.set(path, producer);
641
+ }
642
+ active = held;
422
643
  // Whatever we wanted up and could not get up. Stream credit freeing, a
423
644
  // transient failure clearing, or the peer starting to answer raises no
424
645
  // signal of its own, so the only way back is to ask again on a timer.
425
- const outstanding = [...updated.difference(active)].some((path) => this.#pending(path, refused));
646
+ const outstanding = [...updated].some(([path, producer]) => active.get(path) !== producer && this.#pending(path, refused));
426
647
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
427
648
  // Wait for the next change, which has already fired if one landed above.
428
649
  const next = await (retry
429
650
  ? Promise.race([changed, retryAfter(retry).then(() => broadcasts)])
430
651
  : changed);
431
- dispose();
652
+ dispose?.();
432
653
  if (!next)
433
654
  break;
434
655
  }
@@ -439,6 +660,7 @@ export class Publisher {
439
660
  console.warn(`publish_namespace loop failed: ${reason(error(err))}`);
440
661
  }
441
662
  finally {
663
+ dispose?.();
442
664
  // Close out every open PUBLISH_NAMESPACE request.
443
665
  for (const path of [...requests.keys()]) {
444
666
  await this.#withdraw(path, requests);
@@ -552,8 +774,14 @@ export class Publisher {
552
774
  catch {
553
775
  // Stream might already be closed
554
776
  }
777
+ request.stream.close();
778
+ return;
555
779
  }
556
780
  request.stream.close();
781
+ // Wait for transport acknowledgment before opening a replacement request.
782
+ // This assumes the peer processes the withdrawal by then; FIN acknowledgment
783
+ // does not itself acknowledge application processing across streams.
784
+ await request.stream.writer.closed;
557
785
  }
558
786
  /**
559
787
  * Handles an incoming TRACK_STATUS_REQUEST on a bidi stream.
@@ -598,4 +826,149 @@ export class Publisher {
598
826
  });
599
827
  }
600
828
  }
829
+ /**
830
+ * Take one group out of a cache view, without waiting.
831
+ *
832
+ * A fill's group is at or below the Largest Object snapshot, so it is either still in the
833
+ * retained window or gone for good: nothing republishes an old sequence, and waiting for one
834
+ * would park for the life of the track. Scanning past it, or running dry, is a cache miss,
835
+ * which the caller turns into the draft's fill-failure reset.
836
+ */
837
+ function takeGroup(cache, sequence) {
838
+ for (;;) {
839
+ const group = cache.tryRecvGroup();
840
+ if (!group)
841
+ throw new Error(`group not found: ${sequence}`);
842
+ if (group.sequence === sequence)
843
+ return group;
844
+ group.close();
845
+ if (group.sequence > sequence)
846
+ throw new Error(`group not found: ${sequence}`);
847
+ }
848
+ }
849
+ /** `a - b`, saturating at zero the way the draft's unsigned arithmetic does. */
850
+ function saturatingSub(a, b) {
851
+ return a > b ? a - b : 0n;
852
+ }
853
+ /** Snapshot the live edge of a track. */
854
+ function liveEdge(track) {
855
+ const latest = track.latest();
856
+ if (latest === undefined)
857
+ return {};
858
+ const largest = track.largest();
859
+ if (!largest)
860
+ return { latest: BigInt(latest), next: { group: BigInt(latest), object: 0n } };
861
+ const group = BigInt(largest.group);
862
+ const object = BigInt(largest.frame);
863
+ return { latest: BigInt(latest), largest: { group, object }, next: { group, object: object + 1n } };
864
+ }
865
+ /**
866
+ * Resolve a SUBSCRIBE's Location Filter into the range to serve.
867
+ *
868
+ * Only draft-20 is honored. Earlier drafts have a Filter Type tag whose absolute forms we
869
+ * never served, and starting to interpret them now would change what an existing peer
870
+ * receives; draft-20 is also the first version whose relative forms can name a past group
871
+ * without the subscriber knowing Largest Object.
872
+ */
873
+ function subscribeRange(msg, edge, version) {
874
+ if (!Filter.isDraft20(version)) {
875
+ if (msg.filter.kind !== "nextObject" && msg.filter.kind !== "unfiltered") {
876
+ console.warn(`filter not supported before draft-20, ignoring: ${msg.filter.kind}`);
877
+ }
878
+ return {};
879
+ }
880
+ return filterRange(msg.filter, edge);
881
+ }
882
+ /** The Locations a single Location Filter selects, resolved against the live edge. */
883
+ function filterRange(filter, edge) {
884
+ switch (filter.kind) {
885
+ // No restriction. moq-lite starts at the beginning of the latest group, which is the
886
+ // join point it is built around; a subscription passes objects as they are published,
887
+ // so an absent filter is not a request to replay history.
888
+ case "unfiltered":
889
+ return {};
890
+ // `{Largest.Group, Largest.Object + 1}`. Everything below it, including the already
891
+ // published head of the current group, is outside the requested range, so the join is
892
+ // mid-group by construction. The draft pairs this with a fill when the subscriber
893
+ // wants the head; see {@link Publisher.runFill}.
894
+ case "nextObject":
895
+ return { start: edge.next };
896
+ // `{Largest.Group + 1 - groups, 0}`: 0 is the next group and 1 is the current one.
897
+ // Counted from `Largest.Group`, which sits below the newest group while that group has
898
+ // no objects yet; only with no largest at all does the newest group stand in for it.
899
+ case "relative": {
900
+ const base = edge.largest?.group ?? edge.latest;
901
+ if (base === undefined)
902
+ return {};
903
+ return { start: { group: saturatingSub(base + 1n, filter.groups), object: 0n } };
904
+ }
905
+ case "absolute":
906
+ return {
907
+ start: { group: filter.startGroup, object: filter.startObject },
908
+ end: filter.endGroup === undefined ? undefined : { group: filter.endGroup, object: filter.endObject },
909
+ };
910
+ }
911
+ }
912
+ /**
913
+ * Trim a group to the filter's object bounds, so nothing outside the requested range is
914
+ * sent. Interior groups are served whole.
915
+ */
916
+ function groupSlice(range, sequence) {
917
+ const at = BigInt(sequence);
918
+ return {
919
+ skip: range.start?.group === at ? Number(range.start.object) : 0,
920
+ until: range.end?.group === at && range.end.object !== undefined ? Number(range.end.object) + 1 : undefined,
921
+ };
922
+ }
923
+ /**
924
+ * Resolve a fill request using the Fetch rules: relative to Largest Object and never
925
+ * extending beyond it. An omitted Location Filter inherits the subscription's.
926
+ */
927
+ function fillRange(fill, subscription, largest) {
928
+ // A Range Filter narrows which objects pass, which we do not implement; serving the
929
+ // unfiltered range instead would deliver objects the peer excluded, so refuse it.
930
+ if (fill.rangeFilters)
931
+ return { kind: "unsupported" };
932
+ const filter = fill.filter ?? subscription;
933
+ // Nothing published (or no precise edge to cap at) means no fill is servable; an empty
934
+ // range opens no stream.
935
+ if (!largest)
936
+ return { kind: "empty" };
937
+ let start;
938
+ switch (filter.kind) {
939
+ // A Fetch without a filter is the whole track up to Largest Object.
940
+ case "unfiltered":
941
+ start = { group: 0n, object: 0n };
942
+ break;
943
+ // One past the edge, which for a Fetch is always empty.
944
+ case "nextObject":
945
+ return { kind: "empty" };
946
+ case "relative":
947
+ start = { group: saturatingSub(largest.group + 1n, filter.groups), object: 0n };
948
+ break;
949
+ case "absolute":
950
+ start = { group: filter.startGroup, object: filter.startObject };
951
+ break;
952
+ }
953
+ // Cap the requested end at Largest Object.
954
+ let end = { group: largest.group, object: largest.object };
955
+ if (filter.kind === "absolute" && filter.endGroup !== undefined) {
956
+ const below = filter.endGroup < largest.group ||
957
+ (filter.endGroup === largest.group && filter.endObject !== undefined && filter.endObject < largest.object);
958
+ if (below)
959
+ end = { group: filter.endGroup, object: filter.endObject };
960
+ }
961
+ if (start.group > end.group ||
962
+ (start.group === end.group && end.object !== undefined && end.object < start.object)) {
963
+ return { kind: "empty" };
964
+ }
965
+ if (start.group !== end.group)
966
+ return { kind: "unsupported" };
967
+ return {
968
+ kind: "group",
969
+ sequence: start.group,
970
+ skip: start.object,
971
+ until: end.object === undefined ? undefined : end.object + 1n,
972
+ };
973
+ }
601
974
  //# sourceMappingURL=publisher.js.map