@moq/net 0.3.2 → 0.3.4

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 (100) hide show
  1. package/broadcast.d.ts.map +1 -1
  2. package/broadcast.js +3 -2
  3. package/broadcast.js.map +1 -1
  4. package/connection/accept.d.ts.map +1 -1
  5. package/connection/accept.js +3 -0
  6. package/connection/accept.js.map +1 -1
  7. package/connection/browser.d.ts.map +1 -1
  8. package/connection/browser.js +3 -0
  9. package/connection/browser.js.map +1 -1
  10. package/connection/connect.d.ts.map +1 -1
  11. package/connection/connect.js +11 -7
  12. package/connection/connect.js.map +1 -1
  13. package/group.d.ts +19 -1
  14. package/group.d.ts.map +1 -1
  15. package/group.js +35 -11
  16. package/group.js.map +1 -1
  17. package/ietf/adapter.d.ts.map +1 -1
  18. package/ietf/adapter.js +76 -45
  19. package/ietf/adapter.js.map +1 -1
  20. package/ietf/aliases.d.ts +73 -5
  21. package/ietf/aliases.d.ts.map +1 -1
  22. package/ietf/aliases.js +121 -14
  23. package/ietf/aliases.js.map +1 -1
  24. package/ietf/fetch.d.ts +17 -0
  25. package/ietf/fetch.d.ts.map +1 -1
  26. package/ietf/fetch.js +21 -0
  27. package/ietf/fetch.js.map +1 -1
  28. package/ietf/filter.d.ts +87 -0
  29. package/ietf/filter.d.ts.map +1 -0
  30. package/ietf/filter.js +292 -0
  31. package/ietf/filter.js.map +1 -0
  32. package/ietf/namespace.d.ts +6 -0
  33. package/ietf/namespace.d.ts.map +1 -1
  34. package/ietf/namespace.js +27 -2
  35. package/ietf/namespace.js.map +1 -1
  36. package/ietf/object.d.ts +44 -2
  37. package/ietf/object.d.ts.map +1 -1
  38. package/ietf/object.js +74 -9
  39. package/ietf/object.js.map +1 -1
  40. package/ietf/parameters.d.ts +16 -4
  41. package/ietf/parameters.d.ts.map +1 -1
  42. package/ietf/parameters.js +54 -10
  43. package/ietf/parameters.js.map +1 -1
  44. package/ietf/properties.d.ts +5 -0
  45. package/ietf/properties.d.ts.map +1 -1
  46. package/ietf/properties.js +5 -0
  47. package/ietf/properties.js.map +1 -1
  48. package/ietf/publisher.d.ts.map +1 -1
  49. package/ietf/publisher.js +375 -27
  50. package/ietf/publisher.js.map +1 -1
  51. package/ietf/subscribe.d.ts +38 -7
  52. package/ietf/subscribe.d.ts.map +1 -1
  53. package/ietf/subscribe.js +94 -29
  54. package/ietf/subscribe.js.map +1 -1
  55. package/ietf/subscriber.d.ts.map +1 -1
  56. package/ietf/subscriber.js +148 -35
  57. package/ietf/subscriber.js.map +1 -1
  58. package/ietf/version.d.ts +7 -1
  59. package/ietf/version.d.ts.map +1 -1
  60. package/ietf/version.js +7 -0
  61. package/ietf/version.js.map +1 -1
  62. package/internal.d.ts +16 -1
  63. package/internal.d.ts.map +1 -1
  64. package/internal.js.map +1 -1
  65. package/lite/announce.d.ts.map +1 -1
  66. package/lite/announce.js +7 -7
  67. package/lite/announce.js.map +1 -1
  68. package/lite/publisher.d.ts.map +1 -1
  69. package/lite/publisher.js +4 -2
  70. package/lite/publisher.js.map +1 -1
  71. package/lite/setup.d.ts.map +1 -1
  72. package/lite/setup.js +2 -1
  73. package/lite/setup.js.map +1 -1
  74. package/lite/subscriber.d.ts +1 -6
  75. package/lite/subscriber.d.ts.map +1 -1
  76. package/lite/subscriber.js +98 -23
  77. package/lite/subscriber.js.map +1 -1
  78. package/lite/version.d.ts +4 -0
  79. package/lite/version.d.ts.map +1 -1
  80. package/lite/version.js +15 -0
  81. package/lite/version.js.map +1 -1
  82. package/origin.d.ts +1 -1
  83. package/origin.d.ts.map +1 -1
  84. package/origin.js +1 -1
  85. package/origin.js.map +1 -1
  86. package/package.json +4 -3
  87. package/stream.d.ts.map +1 -1
  88. package/stream.js +3 -5
  89. package/stream.js.map +1 -1
  90. package/track.d.ts +38 -0
  91. package/track.d.ts.map +1 -1
  92. package/track.js +104 -25
  93. package/track.js.map +1 -1
  94. package/util/utf8.d.ts +3 -0
  95. package/util/utf8.d.ts.map +1 -0
  96. package/util/utf8.js +7 -0
  97. package/util/utf8.js.map +1 -0
  98. package/zod.d.ts +1 -1
  99. package/zod.d.ts.map +1 -1
  100. package/zod.js.map +1 -1
package/group.js CHANGED
@@ -26,9 +26,14 @@ class GroupState {
26
26
  frames = new Signal([]);
27
27
  closed = new Once();
28
28
  total = new Signal(0); // The total number of frames in the group thus far
29
- // Frames evicted from the front by the cache cap. A reader that had not consumed
30
- // them has a gap, so its next read throws Lagged rather than skipping silently.
31
- offset = 0;
29
+ // Absolute sequence of the frame at the front of `frames`, advanced by a read and by an
30
+ // eviction alike: the sequence the next read returns.
31
+ start = 0;
32
+ // One past the newest frame the cache cap evicted before it could be read, or 0 when
33
+ // none was. A read that wanted a frame below it has a gap, so it throws Lagged rather
34
+ // than skipping silently; a read that starts above it never asked for the missing
35
+ // frames, so it proceeds.
36
+ evicted = 0;
32
37
  cacheBytes = 0;
33
38
  constructor(sequence) {
34
39
  this.sequence = sequence;
@@ -45,7 +50,8 @@ function appendFrame(state, frame) {
45
50
  if (!evicted)
46
51
  break;
47
52
  state.cacheBytes -= evicted.payload.byteLength;
48
- state.offset++;
53
+ state.start++;
54
+ state.evicted = state.start;
49
55
  }
50
56
  });
51
57
  state.total.update((total) => total + 1);
@@ -91,7 +97,12 @@ export class Producer {
91
97
  const dst = new GroupState(this.sequence);
92
98
  for (const frame of this.#state.frames.peek())
93
99
  appendFrame(dst, frame);
94
- dst.offset = this.#state.offset;
100
+ dst.start = this.#state.start;
101
+ dst.evicted = this.#state.evicted;
102
+ // The replay only covers what is still buffered, so the count has to come from the
103
+ // source: it is what names a frame's absolute sequence, and what a publisher reads
104
+ // to resolve the live edge.
105
+ dst.total.set(this.#state.total.peek());
95
106
  const closed = this.#state.closed.peek();
96
107
  if (closed !== undefined) {
97
108
  dst.closed.set(closed);
@@ -208,7 +219,7 @@ export class Consumer {
208
219
  if (!frame)
209
220
  return undefined;
210
221
  this.#state.cacheBytes -= frame.payload.byteLength;
211
- return { sequence: this.#state.total.peek() - frames.length - 1, frame };
222
+ return { sequence: this.#state.start++, frame };
212
223
  }
213
224
  /** True once no further frames can be read: the group has closed and every buffered frame is read. */
214
225
  get done() {
@@ -220,7 +231,16 @@ export class Consumer {
220
231
  }
221
232
  /** True if frames were evicted from the front of this group before being read. */
222
233
  get skipped() {
223
- return this.#state.offset > 0;
234
+ return this.#state.evicted > 0;
235
+ }
236
+ /**
237
+ * How many frames the group has held, including any already read or evicted.
238
+ *
239
+ * It is also the next frame's sequence number, so `frameCount - 1` names the newest
240
+ * frame written so far. A publisher snapshots it to resolve the track's live edge.
241
+ */
242
+ get frameCount() {
243
+ return this.#state.total.peek();
224
244
  }
225
245
  /**
226
246
  * Reads the next already-buffered frame without blocking.
@@ -256,7 +276,7 @@ export class Consumer {
256
276
  */
257
277
  async readFrame() {
258
278
  for (;;) {
259
- if (this.#state.offset > 0)
279
+ if (this.#state.evicted > 0)
260
280
  throw new Lagged();
261
281
  const read = this.#readBufferedFrame();
262
282
  if (read)
@@ -273,13 +293,17 @@ export class Consumer {
273
293
  * Reads the next frame along with its sequence number within the group.
274
294
  * Treat the returned frame bytes as read-only; they are shared with other consumers.
275
295
  */
276
- async readFrameSequence() {
296
+ async readFrameSequence(options) {
297
+ const from = options?.from ?? 0;
277
298
  for (;;) {
278
- if (this.#state.offset > 0)
299
+ if (this.#state.evicted > from)
279
300
  throw new Lagged();
280
301
  const read = this.#readBufferedFrame();
281
- if (read)
302
+ if (read) {
303
+ if (read.sequence < from)
304
+ continue;
282
305
  return { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };
306
+ }
283
307
  const closed = this.#state.closed.peek();
284
308
  if (closed instanceof Error)
285
309
  throw closed;
package/group.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"group.js","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAgC,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC1E,OA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;IACF,CAAC;IAED,sEAAsE;IACtE,KAAK,CAAC,UAAU;QACf,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpE,CAAC;IAED,2DAA2D;IAC3D,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QACtC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9C,CAAC;IAED,0EAA0E;IAC1E,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,+EAA+E;IAC/E,KAAK,CAAC,KAAa;QAClB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;YAAE,OAAO,CAAC,iBAAiB;QACtE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;IACvC,CAAC;CACD","sourcesContent":["/**\n * Group role handles: an ordered stream of frames within a track, delivered over one QUIC stream.\n *\n * @module\n */\nimport { type GetPromise, type Getter, Once, Signal } from \"@moq/signals\";\nimport { Timestamp } from \"./time.ts\";\n\n/** Maximum bytes of frames cached in a group before old frames are evicted from the front. */\nexport const MAX_GROUP_CACHE_BYTES = 32 * 1024 * 1024;\n\n/** Maximum number of frames cached in a group before old frames are evicted from the front. */\nexport const MAX_GROUP_FRAMES = 1024;\n\n/**\n * A frame buffered in a group: its presentation {@link Timestamp} and payload bytes.\n *\n * The timestamp carries its own scale, so a track can pick its units; the wire layer\n * converts it into the track's negotiated timescale.\n */\nexport interface Frame {\n\t/** The frame payload. */\n\tpayload: Uint8Array;\n\t/**\n\t * Presentation timestamp. Required: for a payload with no presentation time of its own\n\t * (a JSON catalog, control state) pass {@link Timestamp.now} explicitly.\n\t */\n\ttimestamp: Timestamp;\n}\n\n/** Immutable group metadata. */\nexport interface Info {\n\t/** Sequence number of this group within its track. */\n\tsequence: number;\n}\n\n/**\n * Thrown by a frame read when the reader fell behind the group's eviction window: frames\n * it had not yet read were dropped to stay under the cache cap, so the stream has a gap.\n */\nexport class Lagged extends Error {\n\tconstructor() {\n\t\tsuper(\"lagged: frames were evicted before being read\");\n\t\tthis.name = \"Lagged\";\n\t}\n}\n\n/** Reactive backing state shared by the group producer and one consumer. */\nclass GroupState {\n\treadonly sequence: number;\n\tframes = new Signal<Frame[]>([]);\n\tclosed = new Once<Error | null>();\n\ttotal = new Signal<number>(0); // The total number of frames in the group thus far\n\n\t// Frames evicted from the front by the cache cap. A reader that had not consumed\n\t// them has a gap, so its next read throws Lagged rather than skipping silently.\n\toffset = 0;\n\tcacheBytes = 0;\n\n\tconstructor(sequence: number) {\n\t\tthis.sequence = sequence;\n\t}\n}\n\nfunction appendFrame(state: GroupState, frame: Frame) {\n\tif (state.closed.peek() !== undefined) throw new Error(\"group is closed\");\n\n\tstate.cacheBytes += frame.payload.byteLength;\n\tstate.frames.mutate((frames) => {\n\t\tframes.push(frame);\n\n\t\twhile (frames.length > MAX_GROUP_FRAMES || state.cacheBytes > MAX_GROUP_CACHE_BYTES) {\n\t\t\tconst evicted = frames.shift();\n\t\t\tif (!evicted) break;\n\t\t\tstate.cacheBytes -= evicted.payload.byteLength;\n\t\t\tstate.offset++;\n\t\t}\n\t});\n\n\tstate.total.update((total) => total + 1);\n}\n\n/**\n * The write side of an ordered stream of frames within a track.\n *\n * @public\n */\nexport class Producer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\t#mirrors?: Set<GroupState>;\n\n\t// Whether any mirror reader is attached (see {@link used}). Fetch coalescing watches it to\n\t// cancel an abandoned download; a group can stay open indefinitely (a catalog or JSON stream),\n\t// so this is what stops a reader-less fetch instead of the stream ending on its own.\n\t#used = new Signal<boolean>(false);\n\n\tconstructor(sequence: number) {\n\t\tthis.#state = new GroupState(sequence);\n\t\tthis.sequence = sequence;\n\t}\n\n\t/**\n\t * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/** A read handle for this group. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.#state);\n\t}\n\n\t/**\n\t * Create an independent read handle that receives every frame written here.\n\t *\n\t * Frames written so far are replayed synchronously; later writes and close are teed\n\t * in as they happen.\n\t *\n\t * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.\n\t */\n\tmirror(): Consumer {\n\t\tconst dst = new GroupState(this.sequence);\n\t\tfor (const frame of this.#state.frames.peek()) appendFrame(dst, frame);\n\t\tdst.offset = this.#state.offset;\n\n\t\tconst closed = this.#state.closed.peek();\n\t\tif (closed !== undefined) {\n\t\t\tdst.closed.set(closed);\n\t\t\treturn makeConsumer(dst);\n\t\t}\n\n\t\tthis.#mirrors ??= new Set();\n\t\tthis.#mirrors.add(dst);\n\t\tthis.#used.set(true);\n\n\t\t// Track this mirror's close eagerly (not just lazily on the next write) so demand drops the\n\t\t// moment the last reader leaves, letting an abandoned fetch cancel even with no more frames.\n\t\tconst dispose = dst.closed.subscribe((c) => {\n\t\t\tif (c === undefined) return;\n\t\t\tthis.#mirrors?.delete(dst);\n\t\t\tthis.#used.set((this.#mirrors?.size ?? 0) > 0);\n\t\t\tdispose();\n\t\t});\n\n\t\treturn makeConsumer(dst);\n\t}\n\n\t/**\n\t * Whether any mirror reader is currently attached.\n\t *\n\t * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader\n\t * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't\n\t * rely on the stream ending on its own.\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tget used(): Getter<boolean> {\n\t\treturn this.#used;\n\t}\n\n\t/**\n\t * Resolves once no mirror reader remains (or the group closes).\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tasync unused(): Promise<void> {\n\t\twhile (this.#used.peek() && this.#state.closed.peek() === undefined) {\n\t\t\tawait Signal.race(this.#used, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Writes a frame to the group. */\n\twriteFrame(frame: Frame) {\n\t\tappendFrame(this.#state, frame);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() !== undefined) this.#mirrors.delete(mirror);\n\t\t\t\telse appendFrame(mirror, frame);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */\n\twriteString(str: string) {\n\t\tthis.writeFrame({ payload: new TextEncoder().encode(str), timestamp: Timestamp.now() });\n\t}\n\n\t/** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */\n\twriteJson(json: unknown) {\n\t\tthis.writeString(JSON.stringify(json));\n\t}\n\n\t/** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */\n\twriteBool(bool: boolean) {\n\t\tthis.writeFrame({ payload: new Uint8Array([bool ? 1 : 0]), timestamp: Timestamp.now() });\n\t}\n\n\t/** True once the group has been closed. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\tthis.#state.closed.set(abort ?? null);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() === undefined) mirror.closed.set(abort ?? null);\n\t\t\t}\n\t\t\tthis.#mirrors.clear();\n\t\t}\n\t}\n}\n\nlet makeConsumer: (state: GroupState) => Consumer;\n\n/**\n * The read side of an ordered stream of frames within a track.\n *\n * Created internally: obtain one from {@link Producer.consume} or a track subscriber's\n * group reads.\n *\n * @public\n */\nexport class Consumer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\n\tprivate constructor(state: GroupState) {\n\t\tthis.#state = state;\n\t\tthis.sequence = state.sequence;\n\t}\n\n\t/**\n\t * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (state) => new Consumer(state);\n\t}\n\n\t#readBufferedFrame(): { sequence: number; frame: Frame } | undefined {\n\t\tconst frames = this.#state.frames.peek();\n\t\tconst frame = frames.shift();\n\t\tif (!frame) return undefined;\n\n\t\tthis.#state.cacheBytes -= frame.payload.byteLength;\n\t\treturn { sequence: this.#state.total.peek() - frames.length - 1, frame };\n\t}\n\n\t/** True once no further frames can be read: the group has closed and every buffered frame is read. */\n\tget done(): boolean {\n\t\treturn this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** True if frames were evicted from the front of this group before being read. */\n\tget skipped(): boolean {\n\t\treturn this.#state.offset > 0;\n\t}\n\n\t/**\n\t * Reads the next already-buffered frame without blocking.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t *\n\t * Returns `undefined` when nothing is buffered right now. That is not by itself\n\t * end-of-group: check {@link done} to tell \"no frame buffered yet\" from \"finished\".\n\t */\n\ttryReadFrame(): Frame | undefined {\n\t\tconst read = this.#readBufferedFrame();\n\t\treturn read?.frame;\n\t}\n\n\t/** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */\n\ttryReadFrameSequence(): ({ sequence: number } & Frame) | undefined {\n\t\tconst read = this.#readBufferedFrame();\n\t\tif (!read) return undefined;\n\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t}\n\n\t/** Resolves once {@link readFrame} would not block. */\n\tasync readable(): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.frames.peek().length > 0) return;\n\t\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame from the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrame(): Promise<Frame | undefined> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.offset > 0) throw new Lagged();\n\n\t\t\tconst read = this.#readBufferedFrame();\n\t\t\tif (read) return read.frame;\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return;\n\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame along with its sequence number within the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrameSequence(): Promise<({ sequence: number } & Frame) | undefined> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.offset > 0) throw new Lagged();\n\n\t\t\tconst read = this.#readBufferedFrame();\n\t\t\tif (read) return { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return;\n\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Reads the next frame and decodes its payload as a UTF-8 string. */\n\tasync readString(): Promise<string | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? new TextDecoder().decode(frame.payload) : undefined;\n\t}\n\n\t/** Reads the next frame and parses its payload as JSON. */\n\tasync readJson(): Promise<unknown | undefined> {\n\t\tconst frame = await this.readString();\n\t\treturn frame ? JSON.parse(frame) : undefined;\n\t}\n\n\t/** Reads the next frame and decodes its payload as a one-byte boolean. */\n\tasync readBool(): Promise<boolean | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? frame.payload[0] === 1 : undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. Idempotent. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return; // already closed\n\t\tthis.#state.closed.set(abort ?? null);\n\t}\n}\n"]}
1
+ {"version":3,"file":"group.js","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAgC,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,8FAA8F;AAC9F,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEtD,+FAA+F;AAC/F,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAoCrC;;;GAGG;AACH,MAAM,OAAO,MAAO,SAAQ,KAAK;IAChC;QACC,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACvD,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;IACtB,CAAC;CACD;AAED,4EAA4E;AAC5E,MAAM,UAAU;IACN,QAAQ,CAAS;IAC1B,MAAM,GAAG,IAAI,MAAM,CAAU,EAAE,CAAC,CAAC;IACjC,MAAM,GAAG,IAAI,IAAI,EAAgB,CAAC;IAClC,KAAK,GAAG,IAAI,MAAM,CAAS,CAAC,CAAC,CAAC,C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QAC3D,CAAC;IACF,CAAC;IAED,sEAAsE;IACtE,KAAK,CAAC,UAAU;QACf,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpE,CAAC;IAED,2DAA2D;IAC3D,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QACtC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9C,CAAC;IAED,0EAA0E;IAC1E,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,+EAA+E;IAC/E,KAAK,CAAC,KAAa;QAClB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;YAAE,OAAO,CAAC,iBAAiB;QACtE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;IACvC,CAAC;CACD","sourcesContent":["/**\n * Group role handles: an ordered stream of frames within a track, delivered over one QUIC stream.\n *\n * @module\n */\nimport { type GetPromise, type Getter, Once, Signal } from \"@moq/signals\";\nimport { Timestamp } from \"./time.ts\";\n\n/** Maximum bytes of frames cached in a group before old frames are evicted from the front. */\nexport const MAX_GROUP_CACHE_BYTES = 32 * 1024 * 1024;\n\n/** Maximum number of frames cached in a group before old frames are evicted from the front. */\nexport const MAX_GROUP_FRAMES = 1024;\n\n/**\n * A frame buffered in a group: its presentation {@link Timestamp} and payload bytes.\n *\n * The timestamp carries its own scale, so a track can pick its units; the wire layer\n * converts it into the track's negotiated timescale.\n */\nexport interface Frame {\n\t/** The frame payload. */\n\tpayload: Uint8Array;\n\t/**\n\t * Presentation timestamp. Required: for a payload with no presentation time of its own\n\t * (a JSON catalog, control state) pass {@link Timestamp.now} explicitly.\n\t */\n\ttimestamp: Timestamp;\n}\n\n/** Options for a sequence-aware frame read. */\nexport interface ReadOptions {\n\t/**\n\t * The lowest sequence number the caller wants; defaults to the whole group.\n\t *\n\t * Frames below it are discarded instead of returned, and frames evicted below it are not\n\t * a gap: the read resumes at the next retained frame rather than throwing {@link Lagged}.\n\t * An eviction at or above it still throws, because the caller asked for that frame.\n\t */\n\tfrom?: number;\n}\n\n/** Immutable group metadata. */\nexport interface Info {\n\t/** Sequence number of this group within its track. */\n\tsequence: number;\n}\n\n/**\n * Thrown by a frame read when the reader fell behind the group's eviction window: frames\n * it had not yet read were dropped to stay under the cache cap, so the stream has a gap.\n */\nexport class Lagged extends Error {\n\tconstructor() {\n\t\tsuper(\"lagged: frames were evicted before being read\");\n\t\tthis.name = \"Lagged\";\n\t}\n}\n\n/** Reactive backing state shared by the group producer and one consumer. */\nclass GroupState {\n\treadonly sequence: number;\n\tframes = new Signal<Frame[]>([]);\n\tclosed = new Once<Error | null>();\n\ttotal = new Signal<number>(0); // The total number of frames in the group thus far\n\n\t// Absolute sequence of the frame at the front of `frames`, advanced by a read and by an\n\t// eviction alike: the sequence the next read returns.\n\tstart = 0;\n\n\t// One past the newest frame the cache cap evicted before it could be read, or 0 when\n\t// none was. A read that wanted a frame below it has a gap, so it throws Lagged rather\n\t// than skipping silently; a read that starts above it never asked for the missing\n\t// frames, so it proceeds.\n\tevicted = 0;\n\n\tcacheBytes = 0;\n\n\tconstructor(sequence: number) {\n\t\tthis.sequence = sequence;\n\t}\n}\n\nfunction appendFrame(state: GroupState, frame: Frame) {\n\tif (state.closed.peek() !== undefined) throw new Error(\"group is closed\");\n\n\tstate.cacheBytes += frame.payload.byteLength;\n\tstate.frames.mutate((frames) => {\n\t\tframes.push(frame);\n\n\t\twhile (frames.length > MAX_GROUP_FRAMES || state.cacheBytes > MAX_GROUP_CACHE_BYTES) {\n\t\t\tconst evicted = frames.shift();\n\t\t\tif (!evicted) break;\n\t\t\tstate.cacheBytes -= evicted.payload.byteLength;\n\t\t\tstate.start++;\n\t\t\tstate.evicted = state.start;\n\t\t}\n\t});\n\n\tstate.total.update((total) => total + 1);\n}\n\n/**\n * The write side of an ordered stream of frames within a track.\n *\n * @public\n */\nexport class Producer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\t#mirrors?: Set<GroupState>;\n\n\t// Whether any mirror reader is attached (see {@link used}). Fetch coalescing watches it to\n\t// cancel an abandoned download; a group can stay open indefinitely (a catalog or JSON stream),\n\t// so this is what stops a reader-less fetch instead of the stream ending on its own.\n\t#used = new Signal<boolean>(false);\n\n\tconstructor(sequence: number) {\n\t\tthis.#state = new GroupState(sequence);\n\t\tthis.sequence = sequence;\n\t}\n\n\t/**\n\t * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/** A read handle for this group. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.#state);\n\t}\n\n\t/**\n\t * Create an independent read handle that receives every frame written here.\n\t *\n\t * Frames written so far are replayed synchronously; later writes and close are teed\n\t * in as they happen.\n\t *\n\t * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.\n\t */\n\tmirror(): Consumer {\n\t\tconst dst = new GroupState(this.sequence);\n\t\tfor (const frame of this.#state.frames.peek()) appendFrame(dst, frame);\n\t\tdst.start = this.#state.start;\n\t\tdst.evicted = this.#state.evicted;\n\t\t// The replay only covers what is still buffered, so the count has to come from the\n\t\t// source: it is what names a frame's absolute sequence, and what a publisher reads\n\t\t// to resolve the live edge.\n\t\tdst.total.set(this.#state.total.peek());\n\n\t\tconst closed = this.#state.closed.peek();\n\t\tif (closed !== undefined) {\n\t\t\tdst.closed.set(closed);\n\t\t\treturn makeConsumer(dst);\n\t\t}\n\n\t\tthis.#mirrors ??= new Set();\n\t\tthis.#mirrors.add(dst);\n\t\tthis.#used.set(true);\n\n\t\t// Track this mirror's close eagerly (not just lazily on the next write) so demand drops the\n\t\t// moment the last reader leaves, letting an abandoned fetch cancel even with no more frames.\n\t\tconst dispose = dst.closed.subscribe((c) => {\n\t\t\tif (c === undefined) return;\n\t\t\tthis.#mirrors?.delete(dst);\n\t\t\tthis.#used.set((this.#mirrors?.size ?? 0) > 0);\n\t\t\tdispose();\n\t\t});\n\n\t\treturn makeConsumer(dst);\n\t}\n\n\t/**\n\t * Whether any mirror reader is currently attached.\n\t *\n\t * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader\n\t * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't\n\t * rely on the stream ending on its own.\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tget used(): Getter<boolean> {\n\t\treturn this.#used;\n\t}\n\n\t/**\n\t * Resolves once no mirror reader remains (or the group closes).\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tasync unused(): Promise<void> {\n\t\twhile (this.#used.peek() && this.#state.closed.peek() === undefined) {\n\t\t\tawait Signal.race(this.#used, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Writes a frame to the group. */\n\twriteFrame(frame: Frame) {\n\t\tappendFrame(this.#state, frame);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() !== undefined) this.#mirrors.delete(mirror);\n\t\t\t\telse appendFrame(mirror, frame);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */\n\twriteString(str: string) {\n\t\tthis.writeFrame({ payload: new TextEncoder().encode(str), timestamp: Timestamp.now() });\n\t}\n\n\t/** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */\n\twriteJson(json: unknown) {\n\t\tthis.writeString(JSON.stringify(json));\n\t}\n\n\t/** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */\n\twriteBool(bool: boolean) {\n\t\tthis.writeFrame({ payload: new Uint8Array([bool ? 1 : 0]), timestamp: Timestamp.now() });\n\t}\n\n\t/** True once the group has been closed. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\tthis.#state.closed.set(abort ?? null);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() === undefined) mirror.closed.set(abort ?? null);\n\t\t\t}\n\t\t\tthis.#mirrors.clear();\n\t\t}\n\t}\n}\n\nlet makeConsumer: (state: GroupState) => Consumer;\n\n/**\n * The read side of an ordered stream of frames within a track.\n *\n * Created internally: obtain one from {@link Producer.consume} or a track subscriber's\n * group reads.\n *\n * @public\n */\nexport class Consumer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\n\tprivate constructor(state: GroupState) {\n\t\tthis.#state = state;\n\t\tthis.sequence = state.sequence;\n\t}\n\n\t/**\n\t * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (state) => new Consumer(state);\n\t}\n\n\t#readBufferedFrame(): { sequence: number; frame: Frame } | undefined {\n\t\tconst frames = this.#state.frames.peek();\n\t\tconst frame = frames.shift();\n\t\tif (!frame) return undefined;\n\n\t\tthis.#state.cacheBytes -= frame.payload.byteLength;\n\t\treturn { sequence: this.#state.start++, frame };\n\t}\n\n\t/** True once no further frames can be read: the group has closed and every buffered frame is read. */\n\tget done(): boolean {\n\t\treturn this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** True if frames were evicted from the front of this group before being read. */\n\tget skipped(): boolean {\n\t\treturn this.#state.evicted > 0;\n\t}\n\n\t/**\n\t * How many frames the group has held, including any already read or evicted.\n\t *\n\t * It is also the next frame's sequence number, so `frameCount - 1` names the newest\n\t * frame written so far. A publisher snapshots it to resolve the track's live edge.\n\t */\n\tget frameCount(): number {\n\t\treturn this.#state.total.peek();\n\t}\n\n\t/**\n\t * Reads the next already-buffered frame without blocking.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t *\n\t * Returns `undefined` when nothing is buffered right now. That is not by itself\n\t * end-of-group: check {@link done} to tell \"no frame buffered yet\" from \"finished\".\n\t */\n\ttryReadFrame(): Frame | undefined {\n\t\tconst read = this.#readBufferedFrame();\n\t\treturn read?.frame;\n\t}\n\n\t/** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */\n\ttryReadFrameSequence(): ({ sequence: number } & Frame) | undefined {\n\t\tconst read = this.#readBufferedFrame();\n\t\tif (!read) return undefined;\n\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t}\n\n\t/** Resolves once {@link readFrame} would not block. */\n\tasync readable(): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.frames.peek().length > 0) return;\n\t\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame from the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrame(): Promise<Frame | undefined> {\n\t\tfor (;;) {\n\t\t\tif (this.#state.evicted > 0) throw new Lagged();\n\n\t\t\tconst read = this.#readBufferedFrame();\n\t\t\tif (read) return read.frame;\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return;\n\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame along with its sequence number within the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrameSequence(options?: ReadOptions): Promise<({ sequence: number } & Frame) | undefined> {\n\t\tconst from = options?.from ?? 0;\n\n\t\tfor (;;) {\n\t\t\tif (this.#state.evicted > from) throw new Lagged();\n\n\t\t\tconst read = this.#readBufferedFrame();\n\t\t\tif (read) {\n\t\t\t\tif (read.sequence < from) continue;\n\t\t\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t\t\t}\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) return;\n\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Reads the next frame and decodes its payload as a UTF-8 string. */\n\tasync readString(): Promise<string | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? new TextDecoder().decode(frame.payload) : undefined;\n\t}\n\n\t/** Reads the next frame and parses its payload as JSON. */\n\tasync readJson(): Promise<unknown | undefined> {\n\t\tconst frame = await this.readString();\n\t\treturn frame ? JSON.parse(frame) : undefined;\n\t}\n\n\t/** Reads the next frame and decodes its payload as a one-byte boolean. */\n\tasync readBool(): Promise<boolean | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? frame.payload[0] === 1 : undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. Idempotent. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return; // already closed\n\t\tthis.#state.closed.set(abort ?? null);\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/ietf/adapter.ts"],"names":[],"mappings":"AACA,OAAO,EAAU,MAAM,EAAe,MAAM,cAAc,CAAC;AAG3D,OAAO,EAAE,KAAK,WAAW,EAAW,MAAM,cAAc,CAAC;AAEzD;;;GAGG;AACH,MAAM,WAAW,OAAO;IACvB,MAAM,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACnC,YAAY,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACjC,QAAQ,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACxC,aAAa,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC7C,KAAK,IAAI,IAAI,CAAC;IACd,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;CAC9B;AAED;;;GAGG;AACH,qBAAa,aAAc,YAAW,OAAO;;IAK5C,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAE9B,YAAY,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,EAIpE;IAEK,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,CAE9B;IAEK,QAAQ,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAE5C;IAEK,aAAa,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAIjD;IAED,kDAAkD;IAClD,KAAK,SAEJ;CACD;AAmBD;;;;;;GAMG;AACH,qBAAa,oBAAqB,YAAW,OAAO;;IAQnD,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IA+B9B,YACC,IAAI,EAAE,YAAY,EAClB,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,WAAW,EACpB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE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CAIjD;IAED,kDAAkD;IAClD,KAAK,SAEJ;CACD;AAqBD;;;;;;GAMG;AACH,qBAAa,oBAAqB,YAAW,OAAO;;IAQnD,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAmC9B,YACC,IAAI,EAAE,YAAY,EAClB,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,WAAW,EACpB,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,OAAO,EAUf;IAED;;;OAGG;IACG,QAAQ,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAS5C;IAED;;;;;OAKG;IACH,MAAM,IAAI,MAAM,CAsDf;IAED;;OAEG;IACG,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAEpC;IAED;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAYjD;IAED;;;OAGG;IACG,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAmDzB;IAoaD,KAAK,SA8BJ;CACD"}
package/ietf/adapter.js CHANGED
@@ -63,9 +63,13 @@ export class ControlStreamAdapter {
63
63
  version;
64
64
  // Virtual streams keyed by requestId
65
65
  #streams = new Map();
66
- // Namespace → requestId reverse lookup (v14/v15 namespace-keyed messages)
67
- #namespaces = new Map();
68
- // requestId → namespace reverse lookup (for cleanup in #closeStream)
66
+ // Namespace → requestId reverse lookups for v14/v15 namespace-keyed messages.
67
+ // DONE names an incoming announcement and CANCEL names an outgoing one, so a relay
68
+ // may legitimately hold the same namespace in both maps at once.
69
+ #incomingNamespaces = new Map();
70
+ #outgoingNamespaces = new Map();
71
+ // requestId → namespace reverse lookup, one entry per request including a refused
72
+ // duplicate, so #forget can clean up whichever request goes away.
69
73
  #namespacesByRequestId = new Map();
70
74
  // SubscribeNamespace requestIds — for routing 0x08/0x0E entries that lack requestId (v14/v15)
71
75
  #subscribeNamespaces = new Set();
@@ -122,7 +126,7 @@ export class ControlStreamAdapter {
122
126
  },
123
127
  cancel: () => {
124
128
  if (registeredRequestId !== undefined) {
125
- this.#streams.delete(registeredRequestId);
129
+ this.#forget(registeredRequestId);
126
130
  }
127
131
  },
128
132
  });
@@ -145,7 +149,7 @@ export class ControlStreamAdapter {
145
149
  buffer = buffer.subarray(boundary);
146
150
  if (!registered) {
147
151
  // First message: extract requestId and register before flushing
148
- const parsed = this.#tryParseOutgoing(toFlush);
152
+ const parsed = await this.#tryParseOutgoing(toFlush);
149
153
  if (parsed) {
150
154
  registeredRequestId = parsed.requestId;
151
155
  this.#streams.set(parsed.requestId, { controller });
@@ -264,7 +268,7 @@ export class ControlStreamAdapter {
264
268
  controller = c;
265
269
  },
266
270
  cancel: () => {
267
- this.#streams.delete(requestId);
271
+ this.#forget(requestId);
268
272
  },
269
273
  });
270
274
  const sendWritable = this.#createSendWritable();
@@ -298,16 +302,10 @@ export class ControlStreamAdapter {
298
302
  }
299
303
  #closeStream(requestId) {
300
304
  const entry = this.#streams.get(requestId);
305
+ this.#forget(requestId);
301
306
  if (!entry)
302
307
  return;
303
308
  console.debug(`adapter: closing stream requestId=${requestId}`);
304
- this.#streams.delete(requestId);
305
- this.#subscribeNamespaces.delete(requestId);
306
- const namespace = this.#namespacesByRequestId.get(requestId);
307
- if (namespace !== undefined) {
308
- this.#namespaces.delete(namespace);
309
- this.#namespacesByRequestId.delete(requestId);
310
- }
311
309
  try {
312
310
  entry.controller.close();
313
311
  }
@@ -315,6 +313,26 @@ export class ControlStreamAdapter {
315
313
  // Already closed
316
314
  }
317
315
  }
316
+ /**
317
+ * Drop every routing entry a request owns, keeping the two namespace maps in step.
318
+ *
319
+ * Runs even when the virtual stream is already gone, so a request that was torn down
320
+ * locally still gives its namespace back.
321
+ */
322
+ #forget(requestId) {
323
+ this.#streams.delete(requestId);
324
+ this.#subscribeNamespaces.delete(requestId);
325
+ const registered = this.#namespacesByRequestId.get(requestId);
326
+ if (registered === undefined)
327
+ return;
328
+ this.#namespacesByRequestId.delete(requestId);
329
+ const namespaces = this.#namespaceRequests(registered.direction);
330
+ // Only the request holding the live announcement may retract it. A refused duplicate
331
+ // carries the same name, and letting its close withdraw the name would strand the
332
+ // original: its own DONE would then resolve to nothing.
333
+ if (namespaces.get(registered.namespace) === requestId)
334
+ namespaces.delete(registered.namespace);
335
+ }
318
336
  /**
319
337
  * Returns the total byte size of the first complete message in buffer,
320
338
  * or undefined if the buffer doesn't contain a complete message yet.
@@ -339,7 +357,7 @@ export class ControlStreamAdapter {
339
357
  * Try to parse the first outgoing message from accumulated bytes.
340
358
  * Returns the requestId if enough data is available, undefined otherwise.
341
359
  */
342
- #tryParseOutgoing(buffer) {
360
+ async #tryParseOutgoing(buffer) {
343
361
  if (buffer.length === 0)
344
362
  return undefined;
345
363
  // Check typeId varint size before decoding
@@ -362,8 +380,7 @@ export class ControlStreamAdapter {
362
380
  // PublishNamespace (0x06): also parse namespace for v14/v15 reverse lookup
363
381
  if (typeId === 0x06) {
364
382
  try {
365
- const [, afterReqId] = Varint.decode(body);
366
- this.#parseAndRegisterNamespace(afterReqId, requestId);
383
+ await this.#registerNamespace(body, "outgoing");
367
384
  }
368
385
  catch {
369
386
  // Non-critical: only needed for v14/v15 PublishNamespaceDone/Cancel
@@ -376,21 +393,28 @@ export class ControlStreamAdapter {
376
393
  return { requestId };
377
394
  }
378
395
  /**
379
- * Parse a namespace from raw bytes and register it for reverse lookup.
396
+ * Decode a PublishNamespace body and register its namespace for the v14/v15
397
+ * namespace-keyed withdrawals. Returns the request ID it carried.
398
+ *
399
+ * The one decode site for both directions: outgoing announcements go through
400
+ * #tryParseOutgoing and incoming ones through #classify. The direction selects the
401
+ * map that the peer's DONE or CANCEL will later consult.
380
402
  */
381
- #parseAndRegisterNamespace(buf, requestId) {
382
- const decoder = new TextDecoder();
383
- const [partCount, afterCount] = Varint.decode(buf);
384
- let cursor = afterCount;
385
- const parts = [];
386
- for (let i = 0; i < partCount; i++) {
387
- const [len, afterLen] = Varint.decode(cursor);
388
- parts.push(decoder.decode(afterLen.subarray(0, len)));
389
- cursor = afterLen.subarray(len);
390
- }
391
- const namespace = parts.join("/");
392
- this.#namespaces.set(namespace, requestId);
393
- this.#namespacesByRequestId.set(requestId, namespace);
403
+ async #registerNamespace(body, direction) {
404
+ const r = new Reader(undefined, body, this.version);
405
+ const requestId = await r.u62();
406
+ const namespace = await Namespace.decode(r);
407
+ const namespaces = this.#namespaceRequests(direction);
408
+ this.#namespacesByRequestId.set(requestId, { namespace, direction });
409
+ // First announcement in this direction wins. A duplicate is refused with 409, and
410
+ // overwriting here would point the first request's withdrawal at the refused one,
411
+ // which has no stream left, leaving the namespace announced forever.
412
+ if (!namespaces.has(namespace))
413
+ namespaces.set(namespace, requestId);
414
+ return requestId;
415
+ }
416
+ #namespaceRequests(direction) {
417
+ return direction === "incoming" ? this.#incomingNamespaces : this.#outgoingNamespaces;
394
418
  }
395
419
  /** Create a WritableStream that buffers and writes complete messages to the control stream under mutex. */
396
420
  #createSendWritable() {
@@ -431,13 +455,17 @@ export class ControlStreamAdapter {
431
455
  const r = new Reader(undefined, body, this.version);
432
456
  return await r.u62();
433
457
  };
434
- const readNamespaceRequestId = async () => {
458
+ // v14/v15 name their withdrawals instead of numbering them. A name we have no
459
+ // announcement for is dropped, not fatal: it belongs to a duplicate we already
460
+ // refused, or to a request that is already gone, so there is nothing left to close.
461
+ // The mapping itself is released by #forget when the stream goes.
462
+ const readNamespaceRequestId = async (direction) => {
435
463
  const r = new Reader(undefined, body, this.version);
436
464
  const namespace = await Namespace.decode(r);
437
- const requestId = this.#namespaces.get(namespace);
465
+ const namespaces = this.#namespaceRequests(direction);
466
+ const requestId = namespaces.get(namespace);
438
467
  if (requestId === undefined)
439
- throw new Error(`unknown namespace: ${namespace}`);
440
- this.#namespaces.delete(namespace);
468
+ console.warn(`adapter: no announcement for namespace: ${namespace}`);
441
469
  return requestId;
442
470
  };
443
471
  switch (typeId) {
@@ -457,12 +485,8 @@ export class ControlStreamAdapter {
457
485
  return { route: Route.NewRequest, requestId };
458
486
  }
459
487
  case 0x06: {
460
- // PublishNamespace — also store namespace for v14/v15 reverse lookup
461
- const r = new Reader(undefined, body, this.version);
462
- const requestId = await r.u62();
463
- const namespace = await Namespace.decode(r);
464
- this.#namespaces.set(namespace, requestId);
465
- this.#namespacesByRequestId.set(requestId, namespace);
488
+ // PublishNamespace: also store the namespace for v14/v15 reverse lookup
489
+ const requestId = await this.#registerNamespace(body, "incoming");
466
490
  return { route: Route.NewRequest, requestId };
467
491
  }
468
492
  case 0x11: {
@@ -564,21 +588,27 @@ export class ControlStreamAdapter {
564
588
  return { route: Route.CloseStream, requestId };
565
589
  }
566
590
  case 0x09: {
567
- // PublishNamespaceDone: v16 uses requestId, v14/v15 uses namespace
591
+ // PublishNamespaceDone: v16 uses requestId, v14/v15 names the incoming
592
+ // announcement its sender is withdrawing.
568
593
  if (this.version === Version.DRAFT_16) {
569
594
  const requestId = await readRequestId();
570
595
  return { route: Route.CloseStream, requestId };
571
596
  }
572
- const requestId = await readNamespaceRequestId();
597
+ const requestId = await readNamespaceRequestId("incoming");
598
+ if (requestId === undefined)
599
+ return { route: Route.Ignore, requestId: 0n };
573
600
  return { route: Route.CloseStream, requestId };
574
601
  }
575
602
  case 0x0c: {
576
- // PublishNamespaceCancel: v16 uses requestId, v14/v15 uses namespace
603
+ // PublishNamespaceCancel: v16 uses requestId, v14/v15 names the outgoing
604
+ // announcement its sender is rejecting.
577
605
  if (this.version === Version.DRAFT_16) {
578
606
  const requestId = await readRequestId();
579
607
  return { route: Route.CloseStream, requestId };
580
608
  }
581
- const requestId = await readNamespaceRequestId();
609
+ const requestId = await readNamespaceRequestId("outgoing");
610
+ if (requestId === undefined)
611
+ return { route: Route.Ignore, requestId: 0n };
582
612
  return { route: Route.CloseStream, requestId };
583
613
  }
584
614
  case 0x14: {
@@ -628,7 +658,8 @@ export class ControlStreamAdapter {
628
658
  }
629
659
  this.#incomingWaiters = [];
630
660
  // Clear namespace mappings
631
- this.#namespaces.clear();
661
+ this.#incomingNamespaces.clear();
662
+ this.#outgoingNamespaces.clear();
632
663
  this.#namespacesByRequestId.clear();
633
664
  this.#subscribeNamespaces.clear();
634
665
  // Unblock maxRequestId waiters