@moq/net 0.4.0 → 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 (204) hide show
  1. package/announced.d.ts +14 -0
  2. package/announced.d.ts.map +1 -1
  3. package/announced.js.map +1 -1
  4. package/broadcast.d.ts +27 -10
  5. package/broadcast.d.ts.map +1 -1
  6. package/broadcast.js +47 -21
  7. package/broadcast.js.map +1 -1
  8. package/connection/accept.js +14 -4
  9. package/connection/accept.js.map +1 -1
  10. package/connection/connect.d.ts.map +1 -1
  11. package/connection/connect.js +14 -4
  12. package/connection/connect.js.map +1 -1
  13. package/connection/established.d.ts +2 -1
  14. package/connection/established.d.ts.map +1 -1
  15. package/connection/established.js.map +1 -1
  16. package/connection/forward.js +61 -47
  17. package/connection/forward.js.map +1 -1
  18. package/connection/goaway.d.ts +34 -0
  19. package/connection/goaway.d.ts.map +1 -0
  20. package/connection/goaway.js +176 -0
  21. package/connection/goaway.js.map +1 -0
  22. package/connection/handshake.d.ts +5 -2
  23. package/connection/handshake.d.ts.map +1 -1
  24. package/connection/handshake.js +45 -10
  25. package/connection/handshake.js.map +1 -1
  26. package/connection/pool.d.ts +24 -11
  27. package/connection/pool.d.ts.map +1 -1
  28. package/connection/pool.js +50 -18
  29. package/connection/pool.js.map +1 -1
  30. package/connection/reload.d.ts.map +1 -1
  31. package/connection/reload.js +189 -35
  32. package/connection/reload.js.map +1 -1
  33. package/error.d.ts +11 -0
  34. package/error.d.ts.map +1 -1
  35. package/error.js +35 -0
  36. package/error.js.map +1 -1
  37. package/errors.d.ts +1 -1
  38. package/errors.d.ts.map +1 -1
  39. package/errors.js +1 -1
  40. package/errors.js.map +1 -1
  41. package/group.d.ts.map +1 -1
  42. package/group.js +5 -4
  43. package/group.js.map +1 -1
  44. package/hop.d.ts +8 -0
  45. package/hop.d.ts.map +1 -1
  46. package/hop.js +16 -0
  47. package/hop.js.map +1 -1
  48. package/ietf/adapter.d.ts +9 -1
  49. package/ietf/adapter.d.ts.map +1 -1
  50. package/ietf/adapter.js +46 -17
  51. package/ietf/adapter.js.map +1 -1
  52. package/ietf/cluster.d.ts +3 -3
  53. package/ietf/cluster.js +3 -3
  54. package/ietf/cluster.js.map +1 -1
  55. package/ietf/connection.d.ts +1 -1
  56. package/ietf/connection.d.ts.map +1 -1
  57. package/ietf/connection.js +118 -41
  58. package/ietf/connection.js.map +1 -1
  59. package/ietf/error.js +27 -2
  60. package/ietf/error.js.map +1 -1
  61. package/ietf/fetch.d.ts +7 -20
  62. package/ietf/fetch.d.ts.map +1 -1
  63. package/ietf/fetch.js +52 -22
  64. package/ietf/fetch.js.map +1 -1
  65. package/ietf/filter.d.ts +2 -0
  66. package/ietf/filter.d.ts.map +1 -1
  67. package/ietf/filter.js +4 -0
  68. package/ietf/filter.js.map +1 -1
  69. package/ietf/goaway.d.ts +9 -1
  70. package/ietf/goaway.d.ts.map +1 -1
  71. package/ietf/goaway.js +20 -0
  72. package/ietf/goaway.js.map +1 -1
  73. package/ietf/hidden.d.ts +2 -0
  74. package/ietf/hidden.d.ts.map +1 -0
  75. package/ietf/hidden.js +30 -0
  76. package/ietf/hidden.js.map +1 -0
  77. package/ietf/index.d.ts +2 -1
  78. package/ietf/index.d.ts.map +1 -1
  79. package/ietf/index.js +2 -1
  80. package/ietf/index.js.map +1 -1
  81. package/ietf/object.d.ts +15 -8
  82. package/ietf/object.d.ts.map +1 -1
  83. package/ietf/object.js +54 -36
  84. package/ietf/object.js.map +1 -1
  85. package/ietf/parameters.d.ts +12 -0
  86. package/ietf/parameters.d.ts.map +1 -1
  87. package/ietf/parameters.js +82 -12
  88. package/ietf/parameters.js.map +1 -1
  89. package/ietf/properties.d.ts +1 -0
  90. package/ietf/properties.d.ts.map +1 -1
  91. package/ietf/properties.js +14 -0
  92. package/ietf/properties.js.map +1 -1
  93. package/ietf/publish.d.ts +19 -2
  94. package/ietf/publish.d.ts.map +1 -1
  95. package/ietf/publish.js +40 -6
  96. package/ietf/publish.js.map +1 -1
  97. package/ietf/publish_namespace.d.ts +2 -2
  98. package/ietf/publish_namespace.js +2 -2
  99. package/ietf/publish_namespace.js.map +1 -1
  100. package/ietf/publisher.js +383 -214
  101. package/ietf/publisher.js.map +1 -1
  102. package/ietf/subscribe.d.ts +7 -1
  103. package/ietf/subscribe.d.ts.map +1 -1
  104. package/ietf/subscribe.js +25 -18
  105. package/ietf/subscribe.js.map +1 -1
  106. package/ietf/subscribe_namespace.d.ts +8 -2
  107. package/ietf/subscribe_namespace.d.ts.map +1 -1
  108. package/ietf/subscribe_namespace.js +20 -11
  109. package/ietf/subscribe_namespace.js.map +1 -1
  110. package/ietf/subscriber.js +226 -88
  111. package/ietf/subscriber.js.map +1 -1
  112. package/ietf/token.d.ts +2 -0
  113. package/ietf/token.d.ts.map +1 -0
  114. package/ietf/token.js +99 -0
  115. package/ietf/token.js.map +1 -0
  116. package/ietf/track.d.ts +4 -0
  117. package/ietf/track.d.ts.map +1 -1
  118. package/ietf/track.js +6 -20
  119. package/ietf/track.js.map +1 -1
  120. package/index.d.ts +1 -1
  121. package/index.d.ts.map +1 -1
  122. package/index.js.map +1 -1
  123. package/internal.d.ts +19 -3
  124. package/internal.d.ts.map +1 -1
  125. package/internal.js +43 -0
  126. package/internal.js.map +1 -1
  127. package/lite/announce.d.ts +46 -2
  128. package/lite/announce.d.ts.map +1 -1
  129. package/lite/announce.js +133 -15
  130. package/lite/announce.js.map +1 -1
  131. package/lite/connection.d.ts +1 -1
  132. package/lite/connection.d.ts.map +1 -1
  133. package/lite/connection.js +30 -9
  134. package/lite/connection.js.map +1 -1
  135. package/lite/datagram.d.ts +3 -2
  136. package/lite/datagram.d.ts.map +1 -1
  137. package/lite/datagram.js +7 -8
  138. package/lite/datagram.js.map +1 -1
  139. package/lite/group.d.ts +12 -8
  140. package/lite/group.d.ts.map +1 -1
  141. package/lite/group.js +37 -16
  142. package/lite/group.js.map +1 -1
  143. package/lite/message.d.ts +2 -2
  144. package/lite/message.d.ts.map +1 -1
  145. package/lite/message.js +14 -5
  146. package/lite/message.js.map +1 -1
  147. package/lite/publisher.js +174 -133
  148. package/lite/publisher.js.map +1 -1
  149. package/lite/setup.d.ts +1 -1
  150. package/lite/setup.d.ts.map +1 -1
  151. package/lite/setup.js +22 -19
  152. package/lite/setup.js.map +1 -1
  153. package/lite/subscribe.d.ts +10 -4
  154. package/lite/subscribe.d.ts.map +1 -1
  155. package/lite/subscribe.js +20 -10
  156. package/lite/subscribe.js.map +1 -1
  157. package/lite/subscriber.d.ts +10 -2
  158. package/lite/subscriber.d.ts.map +1 -1
  159. package/lite/subscriber.js +333 -188
  160. package/lite/subscriber.js.map +1 -1
  161. package/lite/version.d.ts +11 -0
  162. package/lite/version.d.ts.map +1 -1
  163. package/lite/version.js +56 -0
  164. package/lite/version.js.map +1 -1
  165. package/origin.d.ts +46 -19
  166. package/origin.d.ts.map +1 -1
  167. package/origin.js +529 -189
  168. package/origin.js.map +1 -1
  169. package/package.json +8 -4
  170. package/stream.d.ts +79 -14
  171. package/stream.d.ts.map +1 -1
  172. package/stream.js +375 -133
  173. package/stream.js.map +1 -1
  174. package/tail.d.ts +18 -0
  175. package/tail.d.ts.map +1 -0
  176. package/tail.js +167 -0
  177. package/tail.js.map +1 -0
  178. package/track.d.ts +46 -7
  179. package/track.d.ts.map +1 -1
  180. package/track.js +263 -101
  181. package/track.js.map +1 -1
  182. package/util/abort.d.ts +2 -0
  183. package/util/abort.d.ts.map +1 -0
  184. package/util/abort.js +20 -0
  185. package/util/abort.js.map +1 -0
  186. package/util/u64.d.ts +39 -0
  187. package/util/u64.d.ts.map +1 -0
  188. package/util/u64.js +83 -0
  189. package/util/u64.js.map +1 -0
  190. package/util/varint.d.ts +29 -0
  191. package/util/varint.d.ts.map +1 -0
  192. package/util/varint.js +198 -0
  193. package/util/varint.js.map +1 -0
  194. package/varint.d.ts +10 -6
  195. package/varint.d.ts.map +1 -1
  196. package/varint.js +40 -237
  197. package/varint.js.map +1 -1
  198. package/wire.d.ts +19 -3
  199. package/wire.d.ts.map +1 -1
  200. package/wire.js.map +1 -1
  201. package/ietf/control.d.ts +0 -135
  202. package/ietf/control.d.ts.map +0 -1
  203. package/ietf/control.js +0 -242
  204. package/ietf/control.js.map +0 -1
package/ietf/publisher.js CHANGED
@@ -1,27 +1,25 @@
1
1
  /* @ts-self-types="./publisher.d.ts" */
2
- import { Signal } from "@moq/signals";
2
+ import { race, Signal } from "@moq/signals";
3
3
  import { controlTimeout, error, reason, StreamCode, StreamError } from "../error.js";
4
- import { routesEqual } from "../hop.js";
5
- import { hooks } from "../internal.js";
4
+ import { hiddenBelow, hooks, presented } from "../internal.js";
6
5
  import * as Path from "../path.js";
7
6
  import { Writer } from "../stream.js";
8
- import { Milli } from "../time.js";
7
+ import { Milli, Timescale } from "../time.js";
9
8
  import { TimeoutError, withTimeout } from "../util/timeout.js";
10
9
  import * as Varint from "../varint.js";
11
10
  import { wireOf } from "../wire.js";
12
11
  import * as Cluster from "./cluster.js";
13
12
  import { requestReason, toRequestCode } from "./error.js";
14
- import { FetchHeader } from "./fetch.js";
13
+ import { FetchError, FetchHeader } from "./fetch.js";
15
14
  import * as Filter from "./filter.js";
16
15
  import { FetchFrame, Frame, Group as GroupMessage } from "./object.js";
17
16
  import { fromWire, toWire } from "./priority.js";
18
17
  import * as Properties from "./properties.js";
19
- import { PublishDone } from "./publish.js";
20
- import { PublishNamespace, PublishNamespaceDone, PublishNamespaceOk } from "./publish_namespace.js";
18
+ import { PublishDone, PublishDoneStatus } from "./publish.js";
19
+ import { PublishNamespace, PublishNamespaceDone, PublishNamespaceOk, PublishNamespaceUpdate, } from "./publish_namespace.js";
21
20
  import { RequestError, RequestOk } from "./request.js";
22
21
  import { SubscribeError, SubscribeOk } from "./subscribe.js";
23
22
  import { SubscribeNamespaceEntry, SubscribeNamespaceEntryDone, SubscribeNamespaceOk, } from "./subscribe_namespace.js";
24
- import { TrackStatus } from "./track.js";
25
23
  import { Version } from "./version.js";
26
24
  /** First wait before re-offering a namespace the peer refused or we couldn't open for. */
27
25
  const RETRY_BASE = 100;
@@ -37,14 +35,31 @@ function clusterFor(base, route) {
37
35
  const hops = route.hops.at(-1) === self ? [...route.hops] : [...route.hops, self];
38
36
  return { hops, cost: route.cost.warm };
39
37
  }
40
- function sameAdvert(a, b) {
41
- return a !== undefined && b !== undefined && a.identity === b.identity && routesEqual(a.route, b.route);
38
+ /**
39
+ * What it takes to move the peer from `held` to `next`.
40
+ *
41
+ * - `"same"`: the peer would decode the same advertisement. The cold cost, and the whole
42
+ * route without Cluster, never reach the wire, so a change there sends nothing.
43
+ * - `"restart"`: nothing is held, nothing is wanted, or a different broadcast, which is
44
+ * withdrawn and advertised again.
45
+ * - Otherwise the same broadcast at a new hop chain or warm cost: the cluster parameters
46
+ * the peer holds and the ones it should, for the target to update.
47
+ */
48
+ function change(base, held, next) {
49
+ if (held === undefined || next === undefined || held.identity !== next.identity)
50
+ return "restart";
51
+ const from = clusterFor(base, held.route);
52
+ const to = clusterFor(base, next.route);
53
+ if (from === undefined || to === undefined)
54
+ return from === to ? "same" : "restart";
55
+ if (from.cost === to.cost && sameHops(from.hops, to.hops))
56
+ return "same";
57
+ return { from, to };
58
+ }
59
+ /** Whether two hop paths list the same hops in the same order. */
60
+ function sameHops(a, b) {
61
+ return a.length === b.length && a.every((hop, i) => hop === b[i]);
42
62
  }
43
- /** PUBLISH_DONE statuses this implementation emits. Stable across drafts 14 through 19. */
44
- const PUBLISH_DONE_STATUS = {
45
- INTERNAL_ERROR: 0x0,
46
- TRACK_ENDED: 0x2,
47
- };
48
63
  /**
49
64
  * How long one advertisement may take to be answered. Matches the Rust publisher, and the
50
65
  * peer accepting the stream is only half the exchange: one it never answers on holds the
@@ -65,12 +80,11 @@ export class Publisher {
65
80
  #quic;
66
81
  #session;
67
82
  #requiresSolicitation;
68
- // The published broadcasts, borrowed from the origin this session serves. The origin
69
- // outlives the session, so this is read-only here: subscribe_namespace streams watch it
70
- // for changes, and closing the session leaves the broadcasts alone. The namespaces are
71
- // advertised with an unsolicited PUBLISH_NAMESPACE (see {@link runPublishNamespaces}), or on
72
- // request if the peer asked for that (see {@link runSubscribeNamespace}).
73
- #broadcasts;
83
+ #hidden;
84
+ // The origin this session serves, borrowed: it outlives the session, and closing the
85
+ // session leaves its broadcasts alone. The namespaces are advertised with an unsolicited
86
+ // PUBLISH_NAMESPACE (see {@link runPublishNamespaces}), or on request if the peer asked
87
+ // for that (see {@link runSubscribeNamespace}).
74
88
  #advertised;
75
89
  #publish;
76
90
  // What every advertisement carries on a session that negotiated the MoQ Cluster
@@ -82,14 +96,14 @@ export class Publisher {
82
96
  *
83
97
  * @internal
84
98
  */
85
- constructor({ quic, session, publish, requiresSolicitation, cluster, }) {
99
+ constructor({ quic, session, publish, requiresSolicitation, hidden = false, cluster, }) {
86
100
  this.#quic = quic;
87
101
  this.#session = session;
88
102
  const origin = publish && wireOf(publish);
89
- this.#broadcasts = origin?.broadcasts ?? new Signal(new Map());
90
103
  this.#advertised = origin?.advertised ?? new Signal(new Map());
91
104
  this.#publish = publish;
92
105
  this.#requiresSolicitation = requiresSolicitation;
106
+ this.#hidden = hidden;
93
107
  this.#advert = Cluster.advertise(cluster);
94
108
  }
95
109
  /**
@@ -103,20 +117,33 @@ export class Publisher {
103
117
  const name = msg.trackNamespace;
104
118
  let broadcast;
105
119
  let refusal;
106
- try {
107
- broadcast =
108
- this.#broadcasts.peek()?.get(name) ?? (this.#publish && (await wireOf(this.#publish).demand(name)));
109
- if (!broadcast) {
110
- refusal = {
111
- errorCode: toRequestCode("does_not_exist", "subscribe", version),
112
- reasonPhrase: "broadcast not found",
113
- };
114
- }
120
+ // Legal requests we can't honor are refused one at a time. A subscription that
121
+ // forwards nothing is only useful to a subscriber that later turns forwarding on,
122
+ // and serving a Range Filter unfiltered would deliver objects it excluded.
123
+ const unsupported = !msg.forward
124
+ ? "FORWARD=0 not supported"
125
+ : msg.rangeFilters
126
+ ? "range filters not supported"
127
+ : undefined;
128
+ if (unsupported) {
129
+ refusal = { errorCode: toRequestCode("not_supported", "subscribe", version), reasonPhrase: unsupported };
115
130
  }
116
- catch (err) {
117
- const e = error(err);
118
- const condition = e instanceof StreamError && e.code === StreamCode.NotFound ? "does_not_exist" : "internal";
119
- refusal = { errorCode: toRequestCode(condition, "subscribe", version), reasonPhrase: reason(e) };
131
+ else {
132
+ try {
133
+ broadcast =
134
+ this.#publish && (wireOf(this.#publish).local(name) ?? (await wireOf(this.#publish).demand(name)));
135
+ if (!broadcast) {
136
+ refusal = {
137
+ errorCode: toRequestCode("does_not_exist", "subscribe", version),
138
+ reasonPhrase: "broadcast not found",
139
+ };
140
+ }
141
+ }
142
+ catch (err) {
143
+ const e = error(err);
144
+ const condition = e instanceof StreamError && e.code === StreamCode.NotFound ? "does_not_exist" : "internal";
145
+ refusal = { errorCode: toRequestCode(condition, "subscribe", version), reasonPhrase: reason(e) };
146
+ }
120
147
  }
121
148
  if (refusal) {
122
149
  if (version === Version.DRAFT_14) {
@@ -211,7 +238,7 @@ export class Publisher {
211
238
  ? // Declaring the timescale is what opts the track into timestamps; every
212
239
  // object Timestamp below is in these units. We serve the newest group
213
240
  // first, matching moq-lite.
214
- { timescale, groupOrder: Properties.DESCENDING }
241
+ { timescale, priority: publisherPriority, groupOrder: Properties.DESCENDING }
215
242
  : // INCLUDE_PROPERTIES=0. The block stays present but empty, which also means
216
243
  // the track opts out of timestamps for this subscriber.
217
244
  {},
@@ -232,6 +259,10 @@ export class Publisher {
232
259
  },
233
260
  // A reset is always the peer.
234
261
  () => unsubscribe());
262
+ // Every group started, until its stream finishes or resets, and the data streams
263
+ // opened for PUBLISH_DONE to report.
264
+ const groups = new Set();
265
+ const streams = { opened: 0 };
235
266
  // Serve track groups, racing with stream close (= Unsubscribe)
236
267
  const serving = (async () => {
237
268
  for (;;) {
@@ -247,7 +278,7 @@ export class Publisher {
247
278
  group.close();
248
279
  continue;
249
280
  }
250
- void this.#runGroup({
281
+ const task = this.#runGroup({
251
282
  requestId: msg.requestId,
252
283
  group,
253
284
  timescale,
@@ -255,7 +286,10 @@ export class Publisher {
255
286
  stamped: msg.propertiesWanted,
256
287
  slice: groupSlice(range, group.sequence),
257
288
  unsubscribed,
289
+ streams,
258
290
  });
291
+ groups.add(task);
292
+ void task.finally(() => groups.delete(task));
259
293
  }
260
294
  })();
261
295
  // The fill (when one was requested) runs alongside on its own fetch stream; its
@@ -269,15 +303,35 @@ export class Publisher {
269
303
  timescale,
270
304
  stamped: msg.propertiesWanted,
271
305
  unsubscribed,
306
+ streams,
272
307
  })
273
308
  : Promise.resolve();
274
309
  let publishError;
310
+ let ended = false;
275
311
  try {
276
- await Promise.race([Promise.all([serving, filling]), stream.reader.closed]);
312
+ const served = Symbol("served");
313
+ ended =
314
+ (await race([Promise.all([serving, filling]).then(() => served), stream.reader.closed])) === served;
277
315
  }
278
316
  catch (err) {
279
317
  publishError = error(err);
280
318
  }
319
+ // PUBLISH_DONE waits until every stream this subscription will open is closed, as
320
+ // the draft requires, so its count is final. The subscriber leaving cancels the
321
+ // ones still queued instead.
322
+ await race([Promise.all(groups), unsubscribed]);
323
+ // Draft 14 on has no end location in PUBLISH_DONE: an END_OF_TRACK object is what
324
+ // tells the subscriber where the track ended.
325
+ const final = track.final();
326
+ if (ended && !publishError && final !== undefined) {
327
+ await this.#runEndOfTrack({
328
+ requestId: msg.requestId,
329
+ final,
330
+ publisherPriority,
331
+ unsubscribed,
332
+ streams,
333
+ });
334
+ }
281
335
  console.debug(`publish done: broadcast=${name} track=${track.name}`);
282
336
  if (publishError) {
283
337
  console.warn(`publish error: broadcast=${name} track=${track.name} error=${reason(publishError)}`);
@@ -290,7 +344,8 @@ export class Publisher {
290
344
  requestId: version === Version.DRAFT_14 || version === Version.DRAFT_15 || version === Version.DRAFT_16
291
345
  ? msg.requestId
292
346
  : undefined,
293
- statusCode: publishError ? PUBLISH_DONE_STATUS.INTERNAL_ERROR : PUBLISH_DONE_STATUS.TRACK_ENDED,
347
+ statusCode: publishError ? PublishDoneStatus.INTERNAL_ERROR : PublishDoneStatus.TRACK_ENDED,
348
+ streamCount: BigInt(streams.opened),
294
349
  reasonPhrase: publishError ? "internal error" : "track ended",
295
350
  });
296
351
  await done.encode(stream.writer, version);
@@ -320,7 +375,7 @@ export class Publisher {
320
375
  * Runs a group and sends its frames using ObjectStream (Subgroup delivery mode).
321
376
  */
322
377
  async #runGroup(options) {
323
- const { requestId, group, timescale, publisherPriority, stamped, slice, unsubscribed } = options;
378
+ const { requestId, group, timescale, publisherPriority, stamped, slice, unsubscribed, streams } = options;
324
379
  try {
325
380
  // One stream per group is faster than a peer at its limit can retire them, so this
326
381
  // is the one path that doesn't wait for a slot: the transport would serve the opens
@@ -335,6 +390,7 @@ export class Publisher {
335
390
  group.close(new Error("no stream slot"));
336
391
  return;
337
392
  }
393
+ streams.opened += 1;
338
394
  const header = new GroupMessage({
339
395
  trackAlias: requestId,
340
396
  groupId: group.sequence,
@@ -354,7 +410,7 @@ export class Publisher {
354
410
  },
355
411
  });
356
412
  try {
357
- await hooks.guardGroup(group, header.encode(stream, this.#session.version));
413
+ await hooks.guardGroup(group, () => header.encode(stream, this.#session.version));
358
414
  // The first written object goes on the wire as its absolute id, so a trimmed
359
415
  // head shows the true numbering rather than a silently renumbered group.
360
416
  let first = true;
@@ -370,7 +426,7 @@ export class Publisher {
370
426
  break;
371
427
  // Reading from the filter's start drops the objects below it: they are outside
372
428
  // the requested range, so skipping them is not a gap.
373
- const read = await Promise.race([hooks.readGroupFrame(group, slice.skip), stream.closed]);
429
+ const read = await race([hooks.readGroupFrame(group, slice.skip), stream.closed]);
374
430
  if (!read)
375
431
  break;
376
432
  next = read.sequence + 1;
@@ -382,7 +438,7 @@ export class Publisher {
382
438
  const obj = new Frame({ payload: read.frame.payload, timestamp: read.frame.timestamp });
383
439
  const delta = first ? read.sequence : 0;
384
440
  first = false;
385
- await hooks.guardGroup(group, obj.encode(stream, header.flags, timescale, this.#session.version, delta));
441
+ await hooks.guardGroup(group, () => obj.encode(stream, header.flags, timescale, this.#session.version, delta));
386
442
  }
387
443
  finally {
388
444
  read.complete();
@@ -398,6 +454,43 @@ export class Publisher {
398
454
  group.close();
399
455
  }
400
456
  }
457
+ /**
458
+ * Mark the track's end with an END_OF_TRACK object on its own stream, at object 0 of the
459
+ * group that will never exist.
460
+ *
461
+ * The last group's stream has usually finished before the track ends, so the marker cannot
462
+ * ride on it. A failure only costs the subscriber the early boundary.
463
+ */
464
+ async #runEndOfTrack(options) {
465
+ const { requestId, final, publisherPriority, unsubscribed, streams } = options;
466
+ const version = this.#session.version;
467
+ const stream = await Writer.tryOpen(this.#quic, { cancel: unsubscribed, version }).catch(() => undefined);
468
+ if (!stream)
469
+ return;
470
+ streams.opened += 1;
471
+ try {
472
+ const header = new GroupMessage({
473
+ trackAlias: requestId,
474
+ groupId: final,
475
+ subGroupId: 0,
476
+ publisherPriority,
477
+ flags: {
478
+ hasExtensions: false,
479
+ hasSubgroup: false,
480
+ hasSubgroupObject: false,
481
+ hasEnd: false,
482
+ hasPriority: true,
483
+ firstObject: true,
484
+ },
485
+ });
486
+ await header.encode(stream, version);
487
+ await new Frame({ endOfTrack: true }).encode(stream, header.flags, Timescale.MILLI, version);
488
+ stream.close();
489
+ }
490
+ catch (err) {
491
+ stream.reset(error(err));
492
+ }
493
+ }
401
494
  /**
402
495
  * Serve a draft-20 fill on its own fetch stream: the requested range, read from the
403
496
  * group cache, capped at the Largest Object snapshot.
@@ -407,7 +500,7 @@ export class Publisher {
407
500
  * fill-failure signal. Nothing here touches the subscription either way.
408
501
  */
409
502
  async #runFill(options) {
410
- const { requestId, fill, cache, timescale, stamped, unsubscribed } = options;
503
+ const { requestId, fill, cache, timescale, stamped, unsubscribed, streams } = options;
411
504
  const version = this.#session.version;
412
505
  // Everything is inside the try so the cache fork is released on every path out,
413
506
  // including a transport failure while opening the stream.
@@ -420,6 +513,7 @@ export class Publisher {
420
513
  console.debug(`fill stream failed to open: fill=${requestId}`);
421
514
  return;
422
515
  }
516
+ streams.opened += 1;
423
517
  await stream.u53(FetchHeader.type);
424
518
  await new FetchHeader({ requestId }).encode(stream, version);
425
519
  if (fill.kind !== "group") {
@@ -469,11 +563,7 @@ export class Publisher {
469
563
  if (fill.until !== undefined && next >= fill.until)
470
564
  break;
471
565
  // Reading from the fill's start drops everything below it; see the same read in #runGroup.
472
- const frame = await Promise.race([
473
- group.readFrameSequence({ from: Number(fill.skip) }),
474
- stream.closed,
475
- cancelled,
476
- ]);
566
+ const frame = await race([group.readFrameSequence({ from: Number(fill.skip) }), stream.closed, cancelled]);
477
567
  if (left)
478
568
  throw new Error("unsubscribed before the fill finished");
479
569
  if (!frame)
@@ -489,11 +579,12 @@ export class Publisher {
489
579
  /**
490
580
  * Handles an incoming SUBSCRIBE_NAMESPACE on a bidi stream.
491
581
  *
492
- * This carries the advertisements only when the peer asked to be told on request
493
- * (MoQ Solicit); otherwise {@link runPublishNamespaces} has already announced
494
- * everything and repeating it here would leave the peer holding two sources for one
495
- * broadcast. Draft-16+ streams Namespace entries inline; draft-14/15 predate those
496
- * messages, so each advertisement is a PUBLISH_NAMESPACE request of its own.
582
+ * This carries the advertisements when the peer asked to be told on request (MoQ
583
+ * Solicit); otherwise {@link runPublishNamespaces} has already announced everything
584
+ * visible and repeating it here would leave the peer holding two sources for one
585
+ * broadcast, so only the hidden namespaces it may see ride here (MoQ Hidden).
586
+ * Draft-16+ streams Namespace entries inline; draft-14/15 predate those messages, so
587
+ * each advertisement is a PUBLISH_NAMESPACE request of its own.
497
588
  *
498
589
  * @internal
499
590
  */
@@ -517,40 +608,38 @@ export class Publisher {
517
608
  });
518
609
  await ok.encode(stream.writer, version);
519
610
  }
520
- if (!this.#requiresSolicitation) {
521
- // Already announced, unasked. Hold the stream open until the peer is done.
522
- await stream.reader.closed;
523
- stream.close();
524
- return;
525
- }
526
- // Reports whether the peer now holds the namespace: an inline entry always
527
- // lands, but a PUBLISH_NAMESPACE request can be declined.
528
- const advertise = async (suffix, snap) => {
529
- const cluster = clusterFor(this.#advert, snap.route);
530
- if (legacy) {
531
- return await this.#advertise(Path.join(prefix, suffix), requests, refused, cluster);
532
- }
611
+ // Hidden namespaces are left out unless the peer opted in (MoQ Hidden). Unless the
612
+ // peer asked to be told only on request, it has already heard everything visible
613
+ // from the empty prefix unasked, so this stream carries only what that hid.
614
+ const carries = (covered) => (!this.#hidden || msg.hidden || !hiddenBelow(prefix, covered)) &&
615
+ (this.#requiresSolicitation || (this.#hidden && hiddenBelow(Path.empty(), covered)));
616
+ // Inline entries always land, and the receiver treats a repeated NAMESPACE as a
617
+ // replacement, so repricing one is just sending it again, a new original
618
+ // publisher included, as Rust does. Only a legacy PUBLISH_NAMESPACE request can
619
+ // be declined.
620
+ const namespace = async (suffix, snap) => {
533
621
  await stream.writer.u53(SubscribeNamespaceEntry.id);
622
+ const cluster = clusterFor(this.#advert, snap.route);
534
623
  await new SubscribeNamespaceEntry({ suffix, cluster }).encode(stream.writer, version);
535
- return true;
624
+ return "held";
536
625
  };
537
- const withdraw = async (suffix) => {
538
- if (legacy) {
539
- await this.#withdraw(Path.join(prefix, suffix), requests);
626
+ const target = legacy
627
+ ? {
628
+ advertise: (suffix, snap) => this.#advertise(Path.join(prefix, suffix), requests, clusterFor(this.#advert, snap.route)),
629
+ update: (suffix, _snap, reprice) => this.#update(Path.join(prefix, suffix), requests, reprice),
630
+ withdraw: (suffix) => this.#withdraw(Path.join(prefix, suffix), requests),
540
631
  }
541
- else {
542
- await stream.writer.u53(SubscribeNamespaceEntryDone.id);
543
- await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
544
- }
545
- };
546
- // What the peer holds: keyed by suffix, valued by the routing front, so a republish
547
- // diffs as withdraw-then-advertise rather than nothing.
548
- let active = new Map();
632
+ : {
633
+ advertise: namespace,
634
+ update: namespace,
635
+ withdraw: async (suffix) => {
636
+ await stream.writer.u53(SubscribeNamespaceEntryDone.id);
637
+ await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
638
+ },
639
+ };
640
+ // Keyed by suffix, as the entries name them.
641
+ const ns = { active: new Map(), refused: new Map(), offered: new Map() };
549
642
  let retry = 0;
550
- // What the peer refused, and whether coming back is worth anything.
551
- const refused = new Map();
552
- // The identity each refusal was about, so a republish at the same path clears it.
553
- const offered = new Map();
554
643
  for (;;) {
555
644
  // Subscribe BEFORE reconciling, for the same reason as
556
645
  // {@link runPublishNamespaces}: a publish landing while an advertisement
@@ -565,57 +654,12 @@ export class Publisher {
565
654
  dispose();
566
655
  break;
567
656
  }
568
- const updated = new Map();
569
- for (const [covered, snap] of advertised) {
570
- const suffix = Path.stripPrefix(prefix, covered);
571
- if (suffix === null)
572
- continue;
573
- updated.set(suffix, snap);
574
- }
575
- // A namespace that is gone, or that a republish replaced, takes its refusal with
576
- // it: the peer refused a broadcast, not a path forever, so a different one at
577
- // the same path is offered again. The origin swaps the front in one mutation,
578
- // so the path never leaves `updated` and only the front says they differ.
579
- for (const path of [...refused.keys()]) {
580
- const suffix = Path.stripPrefix(prefix, path);
581
- const snap = suffix === null ? undefined : updated.get(suffix);
582
- if (snap === undefined || offered.get(path) !== snap.identity) {
583
- refused.delete(path);
584
- offered.delete(path);
585
- }
586
- }
587
- // Track what the peer holds rather than what we attempted: a declined
588
- // advertisement stays out of `held`, so the next turn retries it instead of
589
- // believing the namespace is already up.
590
- const held = new Map(active);
591
- // Withdraw first so a republish or re-price reads as withdraw-then-advertise
592
- // (a restart). Identity change is a new broadcast; a route change is the
593
- // same one at a new cost or hop chain.
594
- for (const [removed, snap] of active) {
595
- if (sameAdvert(updated.get(removed), snap))
596
- continue;
597
- await withdraw(removed);
598
- held.delete(removed);
599
- }
600
- for (const [added, snap] of updated) {
601
- if (sameAdvert(held.get(added), snap))
602
- continue;
603
- if (!this.#offerable(Path.join(prefix, added), refused))
604
- continue;
605
- offered.set(Path.join(prefix, added), snap.identity);
606
- if (await advertise(added, snap))
607
- held.set(added, snap);
608
- }
609
- active = held;
610
- // Whatever we wanted up and could not get up, as {@link runPublishNamespaces}
611
- // does: only a legacy request can be declined, and nothing about the peer
612
- // starting to answer raises a signal this loop is watching.
613
- const outstanding = [...updated].some(([suffix, snap]) => !sameAdvert(active.get(suffix), snap) && this.#pending(Path.join(prefix, suffix), refused));
657
+ const outstanding = await this.#reconcile(ns, presented(prefix, advertised, carries), target);
614
658
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
615
659
  // Wait for the next change, or for the peer to unsubscribe.
616
660
  const next = await (retry
617
- ? Promise.race([changed, stream.reader.closed, retryAfter(retry).then(() => advertised)])
618
- : Promise.race([changed, stream.reader.closed]));
661
+ ? race([changed, stream.reader.closed, retryAfter(retry).then(() => advertised)])
662
+ : race([changed, stream.reader.closed]));
619
663
  dispose();
620
664
  if (!next)
621
665
  break;
@@ -653,6 +697,11 @@ export class Publisher {
653
697
  }
654
698
  // The open PUBLISH_NAMESPACE request per advertised path.
655
699
  const requests = new Map();
700
+ const target = {
701
+ advertise: (path, snap) => this.#advertise(path, requests, clusterFor(this.#advert, snap.route)),
702
+ update: (path, _snap, reprice) => this.#update(path, requests, reprice),
703
+ withdraw: (path) => this.#withdraw(path, requests),
704
+ };
656
705
  // The origin outlives the session and its signal never ends, so this loop needs the
657
706
  // session's own ending to stop: without it a closed connection leaves the loop parked
658
707
  // on a shared origin forever, waking on someone else's publish to fail on a dead
@@ -661,14 +710,9 @@ export class Publisher {
661
710
  const closed = this.#quic.closed.then(() => undefined, () => undefined);
662
711
  let dispose;
663
712
  try {
664
- // What the peer holds: keyed by path, valued by identity plus route, so a
665
- // republish diffs as withdraw-then-advertise rather than nothing.
666
- let active = new Map();
713
+ // Keyed by path.
714
+ const ns = { active: new Map(), refused: new Map(), offered: new Map() };
667
715
  let retry = 0;
668
- // What the peer refused, and whether coming back is worth anything.
669
- const refused = new Map();
670
- // The identity each refusal was about, so a republish at the same path clears it.
671
- const offered = new Map();
672
716
  for (;;) {
673
717
  // Subscribe BEFORE reconciling. Each advertisement below waits a round trip
674
718
  // for the peer's reply, and a publish that lands in that window notifies
@@ -685,49 +729,18 @@ export class Publisher {
685
729
  break;
686
730
  }
687
731
  const updated = new Map();
688
- for (const [covered, snap] of advertised) {
689
- updated.set(covered, snap);
690
- }
691
- // A namespace that is gone, or that a republish replaced, takes its refusal with
692
- // it: the peer refused a broadcast, not a path forever, so a different one at
693
- // the same path is offered again. Rust gets this by rebuilding the watched entry.
694
- for (const path of [...refused.keys()]) {
695
- const snap = updated.get(path);
696
- if (snap === undefined || offered.get(path) !== snap.identity) {
697
- refused.delete(path);
698
- offered.delete(path);
699
- }
700
- }
701
- // Withdraw first so a republish or re-price reads as withdraw-then-advertise
702
- // (a restart) rather than nothing.
703
- for (const [removed, snap] of active) {
704
- if (sameAdvert(updated.get(removed), snap))
705
- continue;
706
- await this.#withdraw(removed, requests);
707
- }
708
- for (const [added, snap] of updated) {
709
- if (sameAdvert(active.get(added), snap))
732
+ for (const [covered, candidates] of advertised) {
733
+ // Only peers that declared MoQ Hidden filter unsolicited discovery.
734
+ if ((this.#hidden && hiddenBelow(Path.empty(), covered)) || candidates.length === 0)
710
735
  continue;
711
- if (!this.#offerable(added, refused))
712
- continue;
713
- offered.set(added, snap.identity);
714
- await this.#advertise(added, requests, refused, clusterFor(this.#advert, snap.route));
736
+ updated.set(covered, candidates[0]);
715
737
  }
716
- // What the peer holds, not what we attempted: a declined PUBLISH_NAMESPACE
717
- // leaves no request behind, so it stays outstanding below.
718
- active = new Map([...requests.keys()].flatMap((path) => {
719
- const snap = updated.get(path);
720
- return snap ? [[path, snap]] : [];
721
- }));
722
- // Whatever we wanted up and could not get up. Stream credit freeing, a
723
- // transient failure clearing, or the peer starting to answer raises no
724
- // signal of its own, so the only way back is to ask again on a timer.
725
- const outstanding = [...updated].some(([path, snap]) => !sameAdvert(active.get(path), snap) && this.#pending(path, refused));
738
+ const outstanding = await this.#reconcile(ns, updated, target);
726
739
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
727
740
  // Wait for the next change, which has already fired if one landed above.
728
741
  const next = await (retry
729
- ? Promise.race([changed, closed, retryAfter(retry).then(() => advertised)])
730
- : Promise.race([changed, closed]));
742
+ ? race([changed, closed, retryAfter(retry).then(() => advertised)])
743
+ : race([changed, closed]));
731
744
  dispose?.();
732
745
  if (!next)
733
746
  break;
@@ -746,14 +759,79 @@ export class Publisher {
746
759
  }
747
760
  }
748
761
  }
762
+ /**
763
+ * Bring the peer's view in line with `updated`, one namespace at a time, and report
764
+ * whether anything it should hold is still missing and worth coming back for.
765
+ *
766
+ * Nothing the peer cannot see is sent, a reprice updates the namespace in place, and
767
+ * anything else is withdrawn first so a republish reads as withdraw-then-advertise.
768
+ * `ns` records what the peer holds rather than what we attempted: a declined
769
+ * advertisement or update stays out of it, so the next turn offers it fresh instead
770
+ * of believing it is already up.
771
+ */
772
+ async #reconcile(ns, updated, target) {
773
+ // A namespace that is gone, or that a republish replaced, takes its refusal with
774
+ // it: the peer refused a broadcast, not a path forever, so a different one at the
775
+ // same path is offered again. The origin swaps the front in one mutation, so the
776
+ // path never leaves `updated` and only the front says they differ. Rust gets this
777
+ // by rebuilding the watched entry.
778
+ for (const key of [...ns.refused.keys()]) {
779
+ const snap = updated.get(key);
780
+ if (snap === undefined || ns.offered.get(key) !== snap.identity) {
781
+ ns.refused.delete(key);
782
+ ns.offered.delete(key);
783
+ }
784
+ }
785
+ const held = new Map(ns.active);
786
+ for (const [key, snap] of ns.active) {
787
+ if (change(this.#advert, snap, updated.get(key)) !== "restart")
788
+ continue;
789
+ await target.withdraw(key);
790
+ held.delete(key);
791
+ }
792
+ for (const [key, snap] of updated) {
793
+ const prev = held.get(key);
794
+ const diff = change(this.#advert, prev, snap);
795
+ if (diff === "same")
796
+ continue;
797
+ let answer;
798
+ if (prev !== undefined && diff !== "restart") {
799
+ answer = await target.update(key, snap, diff);
800
+ }
801
+ else {
802
+ // A fresh offer waits for what a refusal asked for, whatever brought us back.
803
+ if (!this.#offerable(key, ns.refused))
804
+ continue;
805
+ answer = await target.advertise(key, snap);
806
+ }
807
+ // `offered` pairs with `refused`, so a held or withdrawn path leaves nothing behind.
808
+ if (answer === "held") {
809
+ held.set(key, snap);
810
+ ns.refused.delete(key);
811
+ ns.offered.delete(key);
812
+ }
813
+ else {
814
+ held.delete(key);
815
+ if (answer !== "dropped") {
816
+ ns.refused.set(key, answer);
817
+ ns.offered.set(key, snap.identity);
818
+ }
819
+ }
820
+ }
821
+ ns.active = held;
822
+ // Whatever we wanted up and could not get up. Stream credit freeing, a transient
823
+ // failure clearing, or the peer starting to answer raises no signal of its own, so
824
+ // the only way back is to ask again on a timer.
825
+ return [...updated].some(([key, snap]) => change(this.#advert, held.get(key), snap) !== "same" && this.#pending(key, ns.refused));
826
+ }
749
827
  /**
750
828
  * Whether a namespace may be offered to the peer right now.
751
829
  *
752
830
  * A peer that asked never to be offered it again means it, whatever brought us back;
753
831
  * one that named a minimum wait gets it, even when our own backoff comes round sooner.
754
832
  */
755
- #offerable(path, refused) {
756
- const entry = refused.get(path);
833
+ #offerable(key, refused) {
834
+ const entry = refused.get(key);
757
835
  if (entry === undefined)
758
836
  return true;
759
837
  return entry !== "never" && Date.now() >= entry;
@@ -766,21 +844,31 @@ export class Publisher {
766
844
  * gating the timer on offerable instead would disarm it for exactly the wait it is
767
845
  * supposed to be counting. Only a refusal that forbids retrying ends it.
768
846
  */
769
- #pending(path, refused) {
770
- return refused.get(path) !== "never";
847
+ #pending(key, refused) {
848
+ return refused.get(key) !== "never";
849
+ }
850
+ /**
851
+ * What a REQUEST_ERROR's retry interval, in milliseconds, says about re-offering the
852
+ * namespace.
853
+ *
854
+ * Draft-14/15 carry no such field, so a 0 there says nothing and our own backoff
855
+ * stands; everywhere else 0 means the peer does not want this again.
856
+ */
857
+ #refusal(err) {
858
+ const version = this.#session.version;
859
+ if (version === Version.DRAFT_14 || version === Version.DRAFT_15)
860
+ return "dropped";
861
+ return err.retryInterval === 0n ? "never" : Date.now() + Number(err.retryInterval);
771
862
  }
772
863
  /**
773
864
  * Advertise one namespace on its own PUBLISH_NAMESPACE request. A declined request
774
865
  * is logged and skipped: a peer that wants none of this rejects each one and stays
775
866
  * connected.
776
- *
777
- * `refused` records what a refusal said about coming back, so a peer that asked not to
778
- * be offered a namespace again is not re-offered it by the retry above.
779
867
  */
780
- async #advertise(path, requests, refused, cluster = this.#advert) {
868
+ async #advertise(path, requests, cluster = this.#advert) {
781
869
  const requestId = await this.#session.nextRequestId();
782
870
  if (requestId === undefined)
783
- return false;
871
+ return "dropped";
784
872
  // Opening is inside the try because it fails like any other advertisement does:
785
873
  // a peer out of stream credit rejects here, and letting that escape would unwind
786
874
  // the announce loop and take discovery down for the whole session, rather than
@@ -793,22 +881,18 @@ export class Publisher {
793
881
  // advertisements, so a peer that takes the stream and answers nothing strands
794
882
  // every publish and withdrawal behind it. Timing out costs this namespace a
795
883
  // turn and leaves it outstanding, which the retry above re-offers.
796
- await withTimeout((async () => {
884
+ const answer = await withTimeout((async () => {
797
885
  await stream.writer.u53(PublishNamespace.id);
798
886
  const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster });
799
887
  await msg.encode(stream.writer, this.#session.version);
800
888
  // Read response (RequestOk and PublishNamespaceOk share 0x07)
801
889
  const respTypeId = await stream.reader.u53();
802
890
  if (respTypeId === RequestError.id) {
803
- // The peer named how long to stay away, in milliseconds. Draft-14/15
804
- // carry no such field, so a 0 there says nothing and our own backoff
805
- // stands; everywhere else 0 means it does not want this again.
806
891
  const err = await RequestError.decode(stream.reader, this.#session.version);
807
- const legacy = this.#session.version === Version.DRAFT_14 || this.#session.version === Version.DRAFT_15;
808
- if (!legacy) {
809
- refused.set(path, err.retryInterval === 0n ? "never" : Date.now() + Number(err.retryInterval));
810
- }
811
- throw new Error(`PublishNamespace rejected: ${requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", this.#session.version)}`);
892
+ const why = requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", this.#session.version);
893
+ console.warn(`announce refused: broadcast=${path} error=${why}`);
894
+ stream.abort(new Error(`PublishNamespace rejected: ${why}`));
895
+ return this.#refusal(err);
812
896
  }
813
897
  if (respTypeId !== RequestOk.id) {
814
898
  throw new Error(`PublishNamespace rejected: typeId=0x${respTypeId.toString(16)}`);
@@ -820,18 +904,79 @@ export class Publisher {
820
904
  else {
821
905
  await RequestOk.decode(stream.reader, this.#session.version);
822
906
  }
907
+ return "held";
823
908
  })(), ADVERTISE_TIMEOUT_MS, `advertisement timed out after ${ADVERTISE_TIMEOUT_MS}ms waiting for the peer's answer`);
824
- requests.set(path, { path, requestId, stream: request });
825
- return true;
909
+ if (answer === "held")
910
+ requests.set(path, { path, requestId, stream });
911
+ return answer;
826
912
  }
827
913
  catch (err) {
828
914
  // The peer never answered the advertisement: a control timeout, not late content.
829
915
  const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
830
916
  console.warn(`announce failed: broadcast=${path} error=${reason(e)}`);
831
917
  request?.abort(e);
832
- return false;
918
+ return "dropped";
833
919
  }
834
920
  }
921
+ /**
922
+ * Update a namespace the peer holds: REQUEST_UPDATE on the request that carries it,
923
+ * with only the parameters that changed, then its answer.
924
+ *
925
+ * Waiting for the answer keeps one update outstanding per stream, which satisfies any
926
+ * MAX_REQUEST_UPDATES the peer set without reading it; a change landing meanwhile waits
927
+ * for the next turn. The answer decides whether the peer still holds the namespace: a
928
+ * REQUEST_ERROR closes the peer's side and withdraws the advertisement, so ours is
929
+ * finished too, and an unanswered update is dropped abruptly, since a peer that ignored
930
+ * it cannot be assumed to hold either price. Either way the retry re-offers it fresh.
931
+ *
932
+ * A different original publisher is an update like any other: the receiver drains what
933
+ * it already serves from the old one and never splices the two.
934
+ */
935
+ async #update(path, requests, { from, to }) {
936
+ const request = requests.get(path);
937
+ if (!request)
938
+ return "dropped";
939
+ const update = {
940
+ hops: sameHops(from.hops, to.hops) ? undefined : to.hops,
941
+ cost: from.cost === to.cost ? undefined : to.cost,
942
+ };
943
+ const version = this.#session.version;
944
+ let answer;
945
+ try {
946
+ const requestId = await this.#session.nextRequestId();
947
+ if (requestId === undefined)
948
+ throw new Error("no request ID for the update");
949
+ answer = await withTimeout((async () => {
950
+ const { writer, reader } = request.stream;
951
+ await writer.u53(PublishNamespaceUpdate.id);
952
+ await new PublishNamespaceUpdate({ requestId, update }).encode(writer, version);
953
+ const typeId = await reader.u53();
954
+ if (typeId === RequestError.id) {
955
+ const err = await RequestError.decode(reader, version);
956
+ const why = requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", version);
957
+ console.warn(`publish_namespace update refused: broadcast=${path} error=${why}`);
958
+ return this.#refusal(err);
959
+ }
960
+ if (typeId !== RequestOk.id) {
961
+ throw new Error(`unexpected answer to the update: typeId=0x${typeId.toString(16)}`);
962
+ }
963
+ await RequestOk.decode(reader, version);
964
+ return "held";
965
+ })(), ADVERTISE_TIMEOUT_MS, `update timed out after ${ADVERTISE_TIMEOUT_MS}ms waiting for the peer's answer`);
966
+ }
967
+ catch (err) {
968
+ const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
969
+ console.warn(`publish_namespace update failed: broadcast=${path} error=${reason(e)}`);
970
+ requests.delete(path);
971
+ request.stream.abort(e);
972
+ return "dropped";
973
+ }
974
+ // The peer already closed out a refused request, and its STOP_SENDING can reject the
975
+ // wait on our FIN. That is the withdrawal finishing, not a reason to end the loop.
976
+ if (answer !== "held")
977
+ await this.#withdraw(path, requests).catch(() => undefined);
978
+ return answer;
979
+ }
835
980
  /**
836
981
  * Close out a namespace's PUBLISH_NAMESPACE request with PUBLISH_NAMESPACE_DONE.
837
982
  */
@@ -869,26 +1014,50 @@ export class Publisher {
869
1014
  * @internal
870
1015
  */
871
1016
  async runTrackStatusRequest(msg, stream) {
1017
+ // TRACK_STATUS_ERROR is 0x0f on draft-14.
1018
+ await this.#refuseUnsupported(stream, msg.requestId, "track_status", 0x0f, "TRACK_STATUS is not supported");
1019
+ }
1020
+ /**
1021
+ * Refuses an incoming SUBSCRIBE_TRACKS (draft-18+): we never send the PUBLISH it asks for.
1022
+ * The reply carries no Request ID, so the message body is left unread.
1023
+ *
1024
+ * @internal
1025
+ */
1026
+ async runSubscribeTracks(stream) {
872
1027
  const version = this.#session.version;
1028
+ await stream.writer.u53(RequestError.id);
1029
+ await new RequestError({
1030
+ errorCode: toRequestCode("not_supported", "subscribe_namespace", version),
1031
+ reasonPhrase: "SUBSCRIBE_TRACKS is not supported",
1032
+ }).encode(stream.writer, version);
1033
+ stream.close();
1034
+ }
1035
+ /**
1036
+ * Handles an incoming FETCH on a bidi stream. We serve none.
1037
+ *
1038
+ * @internal
1039
+ */
1040
+ async runFetch(msg, stream) {
1041
+ await this.#refuseUnsupported(stream, msg.requestId, "fetch", FetchError.id, "FETCH is not supported");
1042
+ }
1043
+ /**
1044
+ * Refuse a request NOT_SUPPORTED. Draft-14 gives each request its own error message,
1045
+ * `errorId14`, with the SUBSCRIBE_ERROR body; later drafts use REQUEST_ERROR.
1046
+ */
1047
+ async #refuseUnsupported(stream, requestId, kind, errorId14, reasonPhrase) {
1048
+ const version = this.#session.version;
1049
+ const errorCode = toRequestCode("not_supported", kind, version);
873
1050
  if (version === Version.DRAFT_14) {
874
- // v14: respond with TrackStatus (0x0E = TRACK_STATUS_OK)
875
- await stream.writer.u53(TrackStatus.id);
876
- const status = new TrackStatus({
877
- trackNamespace: msg.trackNamespace,
878
- trackName: msg.trackName,
879
- statusCode: TrackStatus.STATUS_NOT_FOUND,
880
- lastGroupId: 0n,
881
- lastObjectId: 0n,
882
- });
883
- await status.encode(stream.writer, version);
1051
+ await stream.writer.u53(errorId14);
1052
+ await new SubscribeError({ requestId, errorCode, reasonPhrase }).encode(stream.writer, version);
884
1053
  }
885
1054
  else {
886
- // v15+: respond with RequestOk (0x07)
887
- await stream.writer.u53(RequestOk.id);
888
- const ok = new RequestOk({
889
- requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
890
- });
891
- await ok.encode(stream.writer, version);
1055
+ await stream.writer.u53(RequestError.id);
1056
+ await new RequestError({
1057
+ requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? requestId : undefined,
1058
+ errorCode,
1059
+ reasonPhrase,
1060
+ }).encode(stream.writer, version);
892
1061
  }
893
1062
  stream.close();
894
1063
  }