@moq/net 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/announce.d.ts +7 -0
  2. package/announce.d.ts.map +1 -0
  3. package/announce.js +8 -0
  4. package/announce.js.map +1 -0
  5. package/announced.d.ts +35 -91
  6. package/announced.d.ts.map +1 -1
  7. package/announced.js +21 -156
  8. package/announced.js.map +1 -1
  9. package/bandwidth.d.ts +163 -0
  10. package/bandwidth.d.ts.map +1 -0
  11. package/bandwidth.js +304 -0
  12. package/bandwidth.js.map +1 -0
  13. package/bandwidth_api.d.ts +7 -0
  14. package/bandwidth_api.d.ts.map +1 -0
  15. package/bandwidth_api.js +8 -0
  16. package/bandwidth_api.js.map +1 -0
  17. package/broadcast.d.ts +20 -28
  18. package/broadcast.d.ts.map +1 -1
  19. package/broadcast.js +55 -38
  20. package/broadcast.js.map +1 -1
  21. package/connection/accept.d.ts +16 -1
  22. package/connection/accept.d.ts.map +1 -1
  23. package/connection/accept.js +39 -24
  24. package/connection/accept.js.map +1 -1
  25. package/connection/browser.d.ts.map +1 -1
  26. package/connection/browser.js +9 -7
  27. package/connection/browser.js.map +1 -1
  28. package/connection/connect.d.ts +30 -6
  29. package/connection/connect.d.ts.map +1 -1
  30. package/connection/connect.js +85 -45
  31. package/connection/connect.js.map +1 -1
  32. package/connection/established.d.ts +16 -21
  33. package/connection/established.d.ts.map +1 -1
  34. package/connection/established.js.map +1 -1
  35. package/connection/forward.d.ts +2 -0
  36. package/connection/forward.d.ts.map +1 -0
  37. package/connection/forward.js +159 -0
  38. package/connection/forward.js.map +1 -0
  39. package/connection/handshake.d.ts.map +1 -1
  40. package/connection/handshake.js +2 -2
  41. package/connection/handshake.js.map +1 -1
  42. package/connection/index.d.ts +5 -5
  43. package/connection/index.d.ts.map +1 -1
  44. package/connection/index.js +4 -5
  45. package/connection/index.js.map +1 -1
  46. package/connection/pool.d.ts +188 -0
  47. package/connection/pool.d.ts.map +1 -0
  48. package/connection/pool.js +351 -0
  49. package/connection/pool.js.map +1 -0
  50. package/connection/reload.d.ts +14 -93
  51. package/connection/reload.d.ts.map +1 -1
  52. package/connection/reload.js +216 -80
  53. package/connection/reload.js.map +1 -1
  54. package/connection/stats.d.ts +3 -26
  55. package/connection/stats.d.ts.map +1 -1
  56. package/connection/stats.js.map +1 -1
  57. package/connection/transport.d.ts +0 -7
  58. package/connection/transport.d.ts.map +1 -1
  59. package/consume.d.ts +1 -43
  60. package/consume.d.ts.map +1 -1
  61. package/consume.js +1 -1
  62. package/consume.js.map +1 -1
  63. package/error.d.ts +180 -29
  64. package/error.d.ts.map +1 -1
  65. package/error.js +310 -16
  66. package/error.js.map +1 -1
  67. package/errors.d.ts +7 -0
  68. package/errors.d.ts.map +1 -0
  69. package/errors.js +8 -0
  70. package/errors.js.map +1 -0
  71. package/group.d.ts +9 -43
  72. package/group.d.ts.map +1 -1
  73. package/group.js +283 -69
  74. package/group.js.map +1 -1
  75. package/hop.d.ts +107 -0
  76. package/hop.d.ts.map +1 -0
  77. package/hop.js +103 -0
  78. package/hop.js.map +1 -0
  79. package/ietf/aliases.d.ts +1 -78
  80. package/ietf/aliases.d.ts.map +1 -1
  81. package/ietf/cluster.d.ts +6 -120
  82. package/ietf/cluster.d.ts.map +1 -1
  83. package/ietf/cluster.js +81 -41
  84. package/ietf/cluster.js.map +1 -1
  85. package/ietf/connection.d.ts +6 -72
  86. package/ietf/connection.d.ts.map +1 -1
  87. package/ietf/connection.js +11 -47
  88. package/ietf/connection.js.map +1 -1
  89. package/ietf/error.d.ts +11 -0
  90. package/ietf/error.d.ts.map +1 -0
  91. package/ietf/error.js +168 -0
  92. package/ietf/error.js.map +1 -0
  93. package/ietf/filter.d.ts.map +1 -1
  94. package/ietf/filter.js +6 -1
  95. package/ietf/filter.js.map +1 -1
  96. package/ietf/goaway.d.ts.map +1 -1
  97. package/ietf/goaway.js +22 -5
  98. package/ietf/goaway.js.map +1 -1
  99. package/ietf/parameters.d.ts +2 -2
  100. package/ietf/parameters.d.ts.map +1 -1
  101. package/ietf/parameters.js +15 -17
  102. package/ietf/parameters.js.map +1 -1
  103. package/ietf/publish_namespace.d.ts +25 -0
  104. package/ietf/publish_namespace.d.ts.map +1 -1
  105. package/ietf/publish_namespace.js +63 -0
  106. package/ietf/publish_namespace.js.map +1 -1
  107. package/ietf/publisher.d.ts +1 -82
  108. package/ietf/publisher.d.ts.map +1 -1
  109. package/ietf/publisher.js +203 -136
  110. package/ietf/publisher.js.map +1 -1
  111. package/ietf/solicit.d.ts +1 -40
  112. package/ietf/solicit.d.ts.map +1 -1
  113. package/ietf/subscribe.d.ts +1 -5
  114. package/ietf/subscribe.d.ts.map +1 -1
  115. package/ietf/subscribe.js +8 -9
  116. package/ietf/subscribe.js.map +1 -1
  117. package/ietf/subscriber.d.ts +1 -65
  118. package/ietf/subscriber.d.ts.map +1 -1
  119. package/ietf/subscriber.js +154 -73
  120. package/ietf/subscriber.js.map +1 -1
  121. package/ietf/version.d.ts +12 -1
  122. package/ietf/version.d.ts.map +1 -1
  123. package/ietf/version.js +13 -0
  124. package/ietf/version.js.map +1 -1
  125. package/index.d.ts +11 -6
  126. package/index.d.ts.map +1 -1
  127. package/index.js +10 -5
  128. package/index.js.map +1 -1
  129. package/internal.d.ts +97 -1
  130. package/internal.d.ts.map +1 -1
  131. package/internal.js +65 -0
  132. package/internal.js.map +1 -1
  133. package/lite/announce.d.ts +15 -9
  134. package/lite/announce.d.ts.map +1 -1
  135. package/lite/announce.js +47 -20
  136. package/lite/announce.js.map +1 -1
  137. package/lite/connection.d.ts +9 -59
  138. package/lite/connection.d.ts.map +1 -1
  139. package/lite/connection.js +20 -32
  140. package/lite/connection.js.map +1 -1
  141. package/lite/fetch.d.ts +15 -1
  142. package/lite/fetch.d.ts.map +1 -1
  143. package/lite/fetch.js +39 -7
  144. package/lite/fetch.js.map +1 -1
  145. package/lite/goaway.d.ts.map +1 -1
  146. package/lite/goaway.js +7 -1
  147. package/lite/goaway.js.map +1 -1
  148. package/lite/group.d.ts +18 -4
  149. package/lite/group.d.ts.map +1 -1
  150. package/lite/group.js +31 -10
  151. package/lite/group.js.map +1 -1
  152. package/lite/priority.d.ts +1 -61
  153. package/lite/priority.d.ts.map +1 -1
  154. package/lite/priority.js +4 -5
  155. package/lite/priority.js.map +1 -1
  156. package/lite/publisher.d.ts +1 -69
  157. package/lite/publisher.d.ts.map +1 -1
  158. package/lite/publisher.js +507 -200
  159. package/lite/publisher.js.map +1 -1
  160. package/lite/setup.d.ts +7 -7
  161. package/lite/setup.d.ts.map +1 -1
  162. package/lite/setup.js +13 -13
  163. package/lite/setup.js.map +1 -1
  164. package/lite/subscribe.d.ts +61 -13
  165. package/lite/subscribe.d.ts.map +1 -1
  166. package/lite/subscribe.js +186 -44
  167. package/lite/subscribe.js.map +1 -1
  168. package/lite/subscriber.d.ts +8 -57
  169. package/lite/subscriber.d.ts.map +1 -1
  170. package/lite/subscriber.js +179 -117
  171. package/lite/subscriber.js.map +1 -1
  172. package/lite/track.d.ts +4 -10
  173. package/lite/track.d.ts.map +1 -1
  174. package/lite/track.js +34 -29
  175. package/lite/track.js.map +1 -1
  176. package/lite/version.d.ts +31 -6
  177. package/lite/version.d.ts.map +1 -1
  178. package/lite/version.js +71 -11
  179. package/lite/version.js.map +1 -1
  180. package/origin.d.ts +229 -29
  181. package/origin.d.ts.map +1 -1
  182. package/origin.js +1087 -37
  183. package/origin.js.map +1 -1
  184. package/package.json +3 -2
  185. package/path.d.ts +25 -7
  186. package/path.d.ts.map +1 -1
  187. package/path.js +5 -3
  188. package/path.js.map +1 -1
  189. package/stream.d.ts.map +1 -1
  190. package/stream.js +23 -14
  191. package/stream.js.map +1 -1
  192. package/time.d.ts +15 -2
  193. package/time.d.ts.map +1 -1
  194. package/time.js +28 -9
  195. package/time.js.map +1 -1
  196. package/track.d.ts +166 -83
  197. package/track.d.ts.map +1 -1
  198. package/track.js +617 -187
  199. package/track.js.map +1 -1
  200. package/wire.d.ts +67 -0
  201. package/wire.d.ts.map +1 -0
  202. package/wire.js +32 -0
  203. package/wire.js.map +1 -0
  204. package/zod.d.ts +1 -1
  205. package/zod.d.ts.map +1 -1
  206. package/zod.js.map +1 -1
  207. package/mock.d.ts +0 -66
  208. package/mock.d.ts.map +0 -1
  209. package/mock.js +0 -243
  210. package/mock.js.map +0 -1
package/ietf/publisher.js CHANGED
@@ -1,14 +1,20 @@
1
1
  /* @ts-self-types="./publisher.d.ts" */
2
2
  import { Signal } from "@moq/signals";
3
- import { error, reason } from "../error.js";
3
+ import { controlTimeout, error, reason, StreamCode, StreamError } from "../error.js";
4
+ import { routesEqual } from "../hop.js";
5
+ import { hooks } from "../internal.js";
4
6
  import * as Path from "../path.js";
5
7
  import { Writer } from "../stream.js";
6
- import { withTimeout } from "../util/timeout.js";
8
+ import { Milli } from "../time.js";
9
+ import { TimeoutError, withTimeout } from "../util/timeout.js";
10
+ import * as Varint from "../varint.js";
11
+ import { wireOf } from "../wire.js";
7
12
  import * as Cluster from "./cluster.js";
13
+ import { requestReason, toRequestCode } from "./error.js";
8
14
  import { FetchHeader } from "./fetch.js";
9
15
  import * as Filter from "./filter.js";
10
16
  import { FetchFrame, Frame, Group as GroupMessage } from "./object.js";
11
- import { fromWire } from "./priority.js";
17
+ import { fromWire, toWire } from "./priority.js";
12
18
  import * as Properties from "./properties.js";
13
19
  import { PublishDone } from "./publish.js";
14
20
  import { PublishNamespace, PublishNamespaceDone, PublishNamespaceOk } from "./publish_namespace.js";
@@ -21,6 +27,19 @@ import { Version } from "./version.js";
21
27
  const RETRY_BASE = 100;
22
28
  /** Ceiling on that wait. The loop retries for the life of the session, so it must not spin. */
23
29
  const RETRY_MAX = 5000;
30
+ /** Cluster parameters for one snapshot: the advertised hops, then our own id last. */
31
+ function clusterFor(base, route) {
32
+ if (!base)
33
+ return undefined;
34
+ const self = base.hops.at(-1);
35
+ if (self === undefined)
36
+ return undefined;
37
+ const hops = route.hops.at(-1) === self ? [...route.hops] : [...route.hops, self];
38
+ return { hops, cost: route.cost.warm };
39
+ }
40
+ function sameAdvert(a, b) {
41
+ return a !== undefined && b !== undefined && a.identity === b.identity && routesEqual(a.route, b.route);
42
+ }
24
43
  /** PUBLISH_DONE statuses this implementation emits. Stable across drafts 14 through 19. */
25
44
  const PUBLISH_DONE_STATUS = {
26
45
  INTERNAL_ERROR: 0x0,
@@ -46,44 +65,33 @@ export class Publisher {
46
65
  #quic;
47
66
  #session;
48
67
  #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;
74
+ #advertised;
75
+ #publish;
49
76
  // What every advertisement carries on a session that negotiated the MoQ Cluster
50
77
  // extension: a hop path holding our own id, so the peer can tell that what it hears
51
78
  // back came from us. `undefined` when nothing negotiated it.
52
79
  #advert;
53
- // Our published broadcasts.
54
- // It's a signal so we can live update any subscribe_namespace streams.
55
- #broadcasts = new Signal(new Map());
56
80
  /**
57
81
  * Creates a new Publisher instance.
58
82
  *
59
83
  * @internal
60
84
  */
61
- constructor({ quic, session, requiresSolicitation, cluster, }) {
85
+ constructor({ quic, session, publish, requiresSolicitation, cluster, }) {
62
86
  this.#quic = quic;
63
87
  this.#session = session;
88
+ const origin = publish && wireOf(publish);
89
+ this.#broadcasts = origin?.broadcasts ?? new Signal(new Map());
90
+ this.#advertised = origin?.advertised ?? new Signal(new Map());
91
+ this.#publish = publish;
64
92
  this.#requiresSolicitation = requiresSolicitation;
65
93
  this.#advert = Cluster.advertise(cluster);
66
94
  }
67
- /**
68
- * Publishes a broadcast with any associated tracks.
69
- * The namespace is advertised with an unsolicited PUBLISH_NAMESPACE, or on request
70
- * if the peer asked for that (see {@link runPublishNamespaces}).
71
- */
72
- publish(path, broadcast) {
73
- this.#broadcasts.mutate((broadcasts) => {
74
- if (!broadcasts)
75
- throw new Error("closed");
76
- broadcasts.set(path, broadcast);
77
- });
78
- // Remove the broadcast from the lookup when it's closed, unless the path was republished.
79
- void broadcast.closed.then(() => {
80
- this.#broadcasts.mutate((broadcasts) => {
81
- if (broadcasts?.get(path) === broadcast) {
82
- broadcasts.delete(path);
83
- }
84
- });
85
- });
86
- }
87
95
  /**
88
96
  * Handles an incoming SUBSCRIBE request on a bidi stream.
89
97
  * Owns the full lifecycle: sends response, serves track data, waits for close.
@@ -93,15 +101,30 @@ export class Publisher {
93
101
  async runSubscribe(msg, stream) {
94
102
  const version = this.#session.version;
95
103
  const name = msg.trackNamespace;
96
- const broadcast = this.#broadcasts.peek()?.get(name);
97
- if (!broadcast) {
98
- // Write error response
104
+ let broadcast;
105
+ 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
+ }
115
+ }
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) };
120
+ }
121
+ if (refusal) {
99
122
  if (version === Version.DRAFT_14) {
100
123
  await stream.writer.u53(SubscribeError.id);
101
124
  const err = new SubscribeError({
102
125
  requestId: msg.requestId,
103
- errorCode: 404,
104
- reasonPhrase: "Broadcast not found",
126
+ errorCode: refusal.errorCode,
127
+ reasonPhrase: refusal.reasonPhrase,
105
128
  });
106
129
  await err.encode(stream.writer, version);
107
130
  }
@@ -109,21 +132,36 @@ export class Publisher {
109
132
  await stream.writer.u53(RequestError.id);
110
133
  const err = new RequestError({
111
134
  requestId: version === Version.DRAFT_15 || version === Version.DRAFT_16 ? msg.requestId : undefined,
112
- errorCode: 404,
113
- reasonPhrase: "Broadcast not found",
135
+ errorCode: refusal.errorCode,
136
+ reasonPhrase: refusal.reasonPhrase,
114
137
  });
115
138
  await err.encode(stream.writer, version);
116
139
  }
117
140
  stream.close();
118
141
  return;
119
142
  }
143
+ if (!broadcast)
144
+ return;
120
145
  const priority = fromWire(msg.subscriberPriority);
121
- const track = broadcast.subscribe(msg.trackName, { priority });
122
- // Hoisted so the cleanup below reaches it: the fork happens before SUBSCRIBE_OK is
123
- // written, and a write that throws must not strand the sink it attached.
146
+ const track = wireOf(broadcast).subscribe(msg.trackName, {
147
+ priority,
148
+ // moq-transport has no subscriber latency parameter. Keep everything the
149
+ // producer retained and let the receiving subscriber enforce its own budget.
150
+ // Keep the sentinel encodable if this demand crosses a Lite hop before the
151
+ // producer's retention bound is known.
152
+ maxAge: Milli(Varint.MAX_U53),
153
+ });
124
154
  let cache;
125
155
  try {
126
- const timescale = (await track.info()).timescale;
156
+ // Declaring the timescale is what opts the track into timestamps; every object
157
+ // Timestamp below is in these units.
158
+ const info = await track.info();
159
+ const timescale = info.timescale;
160
+ // The model ranks higher-first, the IETF wire lower-first. Every group this
161
+ // subscription serves carries the same publisher priority, which is what lets a
162
+ // relay prefer catalog and audio over video when it has no subscriber preference
163
+ // to go on.
164
+ const publisherPriority = toWire(info.priority);
127
165
  // The filter and any fill are relative to the live edge, so snapshot it once: the
128
166
  // fill ends exactly where a Next Object subscription begins, which is what lets
129
167
  // the draft's current-group join (Next Object plus a StartGroup=1 fill) cover the
@@ -133,21 +171,25 @@ export class Publisher {
133
171
  // The wire request tells an upstream what we need; the cursor is what actually
134
172
  // trims this subscriber, since the producer fans every cached group out to every
135
173
  // sink regardless. An absent start joins at the latest group, which is what
136
- // moq-lite means by joining a live track.
174
+ // moq-lite means by joining a live track. The range's end is the inclusive last
175
+ // group; the model's `endGroup` is exclusive.
137
176
  track.update({
138
177
  priority,
139
- startGroup: range.start && Number(range.start.group),
140
- endGroup: range.end && Number(range.end.group),
178
+ maxAge: Milli(Varint.MAX_U53),
179
+ groups: {
180
+ start: range.start ? { included: Number(range.start.group) } : undefined,
181
+ end: range.end ? { included: Number(range.end.group) } : undefined,
182
+ },
141
183
  });
142
184
  const startGroup = range.start ? Number(range.start.group) : track.latest();
143
185
  if (startGroup !== undefined)
144
- track.startAt(startGroup);
186
+ track.setGroups({ start: { included: startGroup } });
145
187
  // A fill reads the group cache through its own consumer, independent of the
146
188
  // subscription's cursor. Forked from this subscriber rather than resolved through
147
189
  // the broadcast again: a dynamic serve is one request per peer subscription, so
148
190
  // asking the broadcast would mint a second producer nobody has accepted.
149
191
  const fill = msg.fill && Filter.isDraft20(version) ? fillRange(msg.fill, msg.filter, edge.largest) : undefined;
150
- cache = fill && fill.kind !== "empty" ? track.fork({ priority }) : undefined;
192
+ cache = fill && fill.kind !== "empty" ? track.fork({ priority, maxAge: Milli(Varint.MAX_U53) }) : undefined;
151
193
  // Send SUBSCRIBE_OK
152
194
  await stream.writer.u53(SubscribeOk.id);
153
195
  const ok = new SubscribeOk({
@@ -156,8 +198,15 @@ export class Publisher {
156
198
  : undefined,
157
199
  trackAlias: msg.requestId,
158
200
  // Required once the track has content; a fill-requesting subscriber sizes its
159
- // backfill against this.
160
- largest: edge.largest && { groupId: edge.largest.group, objectId: edge.largest.object },
201
+ // backfill against this. Below draft-20 round it down to the start of its
202
+ // group, matching what the subscription serves there: a draft-20 subscriber
203
+ // recovers a group's head with a FILL, which we serve, while older drafts
204
+ // recover it with a joining FETCH, which we do not, so naming a mid-group
205
+ // start would strand them.
206
+ largest: edge.largest &&
207
+ (Filter.isDraft20(version)
208
+ ? { groupId: edge.largest.group, objectId: edge.largest.object }
209
+ : { groupId: edge.largest.group, objectId: 0n }),
161
210
  properties: msg.propertiesWanted
162
211
  ? // Declaring the timescale is what opts the track into timestamps; every
163
212
  // object Timestamp below is in these units. We serve the newest group
@@ -189,7 +238,7 @@ export class Publisher {
189
238
  const group = await track.recvGroup();
190
239
  if (!group)
191
240
  return;
192
- // Past the filter's end. Dropped here rather than through `endAt`, which
241
+ // Past the filter's end. Dropped here rather than through `setGroups`, which
193
242
  // parks a capped group instead: this range is fixed for the life of the
194
243
  // subscription, so a group above it is never coming back in, and holding
195
244
  // one keeps the loop from ever ending. A producer that publishes beyond
@@ -202,6 +251,7 @@ export class Publisher {
202
251
  requestId: msg.requestId,
203
252
  group,
204
253
  timescale,
254
+ publisherPriority,
205
255
  stamped: msg.propertiesWanted,
206
256
  slice: groupSlice(range, group.sequence),
207
257
  unsubscribed,
@@ -270,7 +320,7 @@ export class Publisher {
270
320
  * Runs a group and sends its frames using ObjectStream (Subgroup delivery mode).
271
321
  */
272
322
  async #runGroup(options) {
273
- const { requestId, group, timescale, stamped, slice, unsubscribed } = options;
323
+ const { requestId, group, timescale, publisherPriority, stamped, slice, unsubscribed } = options;
274
324
  try {
275
325
  // One stream per group is faster than a peer at its limit can retire them, so this
276
326
  // is the one path that doesn't wait for a slot: the transport would serve the opens
@@ -289,7 +339,7 @@ export class Publisher {
289
339
  trackAlias: requestId,
290
340
  groupId: group.sequence,
291
341
  subGroupId: 0,
292
- publisherPriority: 0,
342
+ publisherPriority,
293
343
  flags: {
294
344
  // The object properties carry the timestamp, so there is nothing to write
295
345
  // when the track declared no units to read one in.
@@ -303,8 +353,8 @@ export class Publisher {
303
353
  firstObject: slice.skip === 0,
304
354
  },
305
355
  });
306
- await header.encode(stream, this.#session.version);
307
356
  try {
357
+ await hooks.guardGroup(group, header.encode(stream, this.#session.version));
308
358
  // The first written object goes on the wire as its absolute id, so a trimmed
309
359
  // head shows the true numbering rather than a silently renumbered group.
310
360
  let first = true;
@@ -318,20 +368,25 @@ export class Publisher {
318
368
  // outside the requested range, so stop without waiting for the group's end.
319
369
  if (slice.until !== undefined && next >= slice.until)
320
370
  break;
321
- // Reading from the filter's start drops the objects below it, including any the
322
- // group's cache evicted: they are outside the requested range, so losing them is
323
- // not the gap that would otherwise reset this stream and forfeit the rest of the
324
- // group. An eviction at or above the start is a real gap and still throws.
325
- const frame = await Promise.race([group.readFrameSequence({ from: slice.skip }), stream.closed]);
326
- if (!frame)
371
+ // Reading from the filter's start drops the objects below it: they are outside
372
+ // the requested range, so skipping them is not a gap.
373
+ const read = await Promise.race([hooks.readGroupFrame(group, slice.skip), stream.closed]);
374
+ if (!read)
327
375
  break;
328
- next = frame.sequence + 1;
329
- if (slice.until !== undefined && frame.sequence >= slice.until)
376
+ next = read.sequence + 1;
377
+ if (slice.until !== undefined && read.sequence >= slice.until) {
378
+ read.complete();
330
379
  break;
331
- const obj = new Frame({ payload: frame.payload, timestamp: frame.timestamp });
332
- const delta = first ? frame.sequence : 0;
333
- first = false;
334
- await obj.encode(stream, header.flags, timescale, this.#session.version, delta);
380
+ }
381
+ try {
382
+ const obj = new Frame({ payload: read.frame.payload, timestamp: read.frame.timestamp });
383
+ const delta = first ? read.sequence : 0;
384
+ first = false;
385
+ await hooks.guardGroup(group, obj.encode(stream, header.flags, timescale, this.#session.version, delta));
386
+ }
387
+ finally {
388
+ read.complete();
389
+ }
335
390
  }
336
391
  stream.close();
337
392
  }
@@ -413,8 +468,7 @@ export class Publisher {
413
468
  // subscription, so stop without waiting for the group's end.
414
469
  if (fill.until !== undefined && next >= fill.until)
415
470
  break;
416
- // Reading from the fill's start drops everything below it, evicted objects included;
417
- // see the same read in #runGroup.
471
+ // Reading from the fill's start drops everything below it; see the same read in #runGroup.
418
472
  const frame = await Promise.race([
419
473
  group.readFrameSequence({ from: Number(fill.skip) }),
420
474
  stream.closed,
@@ -471,12 +525,13 @@ export class Publisher {
471
525
  }
472
526
  // Reports whether the peer now holds the namespace: an inline entry always
473
527
  // lands, but a PUBLISH_NAMESPACE request can be declined.
474
- const advertise = async (suffix) => {
528
+ const advertise = async (suffix, snap) => {
529
+ const cluster = clusterFor(this.#advert, snap.route);
475
530
  if (legacy) {
476
- return await this.#advertise(Path.join(prefix, suffix), requests, refused);
531
+ return await this.#advertise(Path.join(prefix, suffix), requests, refused, cluster);
477
532
  }
478
533
  await stream.writer.u53(SubscribeNamespaceEntry.id);
479
- await new SubscribeNamespaceEntry({ suffix, cluster: this.#advert }).encode(stream.writer, version);
534
+ await new SubscribeNamespaceEntry({ suffix, cluster }).encode(stream.writer, version);
480
535
  return true;
481
536
  };
482
537
  const withdraw = async (suffix) => {
@@ -488,13 +543,14 @@ export class Publisher {
488
543
  await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
489
544
  }
490
545
  };
491
- // Which producer holds each advertised suffix. Keyed on the producer rather than
492
- // the path alone, so a path handed to a new producer is withdrawn and re-offered
493
- // instead of diffing away to nothing and leaving the peer on the dead generation.
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.
494
548
  let active = new Map();
495
549
  let retry = 0;
496
550
  // What the peer refused, and whether coming back is worth anything.
497
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();
498
554
  for (;;) {
499
555
  // Subscribe BEFORE reconciling, for the same reason as
500
556
  // {@link runPublishNamespaces}: a publish landing while an advertisement
@@ -502,55 +558,63 @@ export class Publisher {
502
558
  // TODO Make a better helper within Signals.
503
559
  let dispose;
504
560
  const changed = new Promise((resolve) => {
505
- dispose = this.#broadcasts.changed(resolve);
561
+ dispose = this.#advertised.changed(resolve);
506
562
  });
507
- const broadcasts = this.#broadcasts.peek();
508
- if (!broadcasts) {
563
+ const advertised = this.#advertised.peek();
564
+ if (!advertised) {
509
565
  dispose();
510
566
  break;
511
567
  }
512
568
  const updated = new Map();
513
- for (const [name, producer] of broadcasts) {
514
- const suffix = Path.stripPrefix(prefix, name);
569
+ for (const [covered, snap] of advertised) {
570
+ const suffix = Path.stripPrefix(prefix, covered);
515
571
  if (suffix === null)
516
572
  continue;
517
- updated.set(suffix, producer);
573
+ updated.set(suffix, snap);
518
574
  }
519
- // A namespace that is gone takes its refusal with it, so re-announcing the
520
- // path offers it again.
521
- const live = new Set([...updated.keys()].map((suffix) => Path.join(prefix, suffix)));
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.
522
579
  for (const path of [...refused.keys()]) {
523
- if (!live.has(path))
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) {
524
583
  refused.delete(path);
584
+ offered.delete(path);
585
+ }
525
586
  }
526
587
  // Track what the peer holds rather than what we attempted: a declined
527
588
  // advertisement stays out of `held`, so the next turn retries it instead of
528
589
  // believing the namespace is already up.
529
590
  const held = new Map(active);
530
- // Withdraw first, so a replacement reads as an end followed by a start.
531
- for (const [suffix, producer] of active) {
532
- if (updated.get(suffix) === producer)
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))
533
596
  continue;
534
- await withdraw(suffix);
535
- held.delete(suffix);
597
+ await withdraw(removed);
598
+ held.delete(removed);
536
599
  }
537
- for (const [suffix, producer] of updated) {
538
- if (active.get(suffix) === producer)
600
+ for (const [added, snap] of updated) {
601
+ if (sameAdvert(held.get(added), snap))
539
602
  continue;
540
- if (this.#offerable(Path.join(prefix, suffix), refused)) {
541
- if (await advertise(suffix))
542
- held.set(suffix, producer);
543
- }
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);
544
608
  }
545
609
  active = held;
546
610
  // Whatever we wanted up and could not get up, as {@link runPublishNamespaces}
547
611
  // does: only a legacy request can be declined, and nothing about the peer
548
612
  // starting to answer raises a signal this loop is watching.
549
- const outstanding = [...updated].some(([suffix, producer]) => active.get(suffix) !== producer && this.#pending(Path.join(prefix, suffix), refused));
613
+ const outstanding = [...updated].some(([suffix, snap]) => !sameAdvert(active.get(suffix), snap) && this.#pending(Path.join(prefix, suffix), refused));
550
614
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
551
615
  // Wait for the next change, or for the peer to unsubscribe.
552
616
  const next = await (retry
553
- ? Promise.race([changed, stream.reader.closed, retryAfter(retry).then(() => broadcasts)])
617
+ ? Promise.race([changed, stream.reader.closed, retryAfter(retry).then(() => advertised)])
554
618
  : Promise.race([changed, stream.reader.closed]));
555
619
  dispose();
556
620
  if (!next)
@@ -589,13 +653,22 @@ export class Publisher {
589
653
  }
590
654
  // The open PUBLISH_NAMESPACE request per advertised path.
591
655
  const requests = new Map();
656
+ // The origin outlives the session and its signal never ends, so this loop needs the
657
+ // session's own ending to stop: without it a closed connection leaves the loop parked
658
+ // on a shared origin forever, waking on someone else's publish to fail on a dead
659
+ // transport. `runSubscribeNamespace` gets this from the stream the peer asked on; an
660
+ // unsolicited loop has no stream of its own, so the session is what it watches.
661
+ const closed = this.#quic.closed.then(() => undefined, () => undefined);
592
662
  let dispose;
593
663
  try {
594
- // Which producer holds each advertised path; see {@link runSubscribeNamespace}.
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.
595
666
  let active = new Map();
596
667
  let retry = 0;
597
668
  // What the peer refused, and whether coming back is worth anything.
598
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();
599
672
  for (;;) {
600
673
  // Subscribe BEFORE reconciling. Each advertisement below waits a round trip
601
674
  // for the peer's reply, and a publish that lands in that window notifies
@@ -604,51 +677,57 @@ export class Publisher {
604
677
  // changed.
605
678
  // TODO Make a better helper within Signals.
606
679
  const changed = new Promise((resolve) => {
607
- dispose = this.#broadcasts.changed(resolve);
680
+ dispose = this.#advertised.changed(resolve);
608
681
  });
609
- const broadcasts = this.#broadcasts.peek();
610
- if (!broadcasts) {
682
+ const advertised = this.#advertised.peek();
683
+ if (!advertised) {
611
684
  dispose?.();
612
685
  break;
613
686
  }
614
- const updated = new Map(broadcasts);
615
- // A namespace that is gone takes its refusal with it, so re-announcing the
616
- // path offers it again. Rust gets this by rebuilding the watched entry.
687
+ 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.
617
694
  for (const path of [...refused.keys()]) {
618
- if (!updated.has(path))
695
+ const snap = updated.get(path);
696
+ if (snap === undefined || offered.get(path) !== snap.identity) {
619
697
  refused.delete(path);
698
+ offered.delete(path);
699
+ }
620
700
  }
621
- // Withdraw first, so a replacement reads as an end followed by a start.
622
- for (const [path, producer] of active) {
623
- if (updated.get(path) === producer)
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))
624
705
  continue;
625
- await this.#withdraw(path, requests);
706
+ await this.#withdraw(removed, requests);
626
707
  }
627
- for (const [path, producer] of updated) {
628
- if (active.get(path) === producer)
708
+ for (const [added, snap] of updated) {
709
+ if (sameAdvert(active.get(added), snap))
629
710
  continue;
630
- if (this.#offerable(path, refused)) {
631
- await this.#advertise(path, requests, refused);
632
- }
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));
633
715
  }
634
716
  // What the peer holds, not what we attempted: a declined PUBLISH_NAMESPACE
635
717
  // leaves no request behind, so it stays outstanding below.
636
- const held = new Map();
637
- for (const path of requests.keys()) {
638
- const producer = updated.get(path);
639
- if (producer)
640
- held.set(path, producer);
641
- }
642
- active = held;
718
+ active = new Map([...requests.keys()].flatMap((path) => {
719
+ const snap = updated.get(path);
720
+ return snap ? [[path, snap]] : [];
721
+ }));
643
722
  // Whatever we wanted up and could not get up. Stream credit freeing, a
644
723
  // transient failure clearing, or the peer starting to answer raises no
645
724
  // signal of its own, so the only way back is to ask again on a timer.
646
- const outstanding = [...updated].some(([path, producer]) => active.get(path) !== producer && this.#pending(path, refused));
725
+ const outstanding = [...updated].some(([path, snap]) => !sameAdvert(active.get(path), snap) && this.#pending(path, refused));
647
726
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
648
727
  // Wait for the next change, which has already fired if one landed above.
649
728
  const next = await (retry
650
- ? Promise.race([changed, retryAfter(retry).then(() => broadcasts)])
651
- : changed);
729
+ ? Promise.race([changed, closed, retryAfter(retry).then(() => advertised)])
730
+ : Promise.race([changed, closed]));
652
731
  dispose?.();
653
732
  if (!next)
654
733
  break;
@@ -698,7 +777,7 @@ export class Publisher {
698
777
  * `refused` records what a refusal said about coming back, so a peer that asked not to
699
778
  * be offered a namespace again is not re-offered it by the retry above.
700
779
  */
701
- async #advertise(path, requests, refused) {
780
+ async #advertise(path, requests, refused, cluster = this.#advert) {
702
781
  const requestId = await this.#session.nextRequestId();
703
782
  if (requestId === undefined)
704
783
  return false;
@@ -716,7 +795,7 @@ export class Publisher {
716
795
  // turn and leaves it outstanding, which the retry above re-offers.
717
796
  await withTimeout((async () => {
718
797
  await stream.writer.u53(PublishNamespace.id);
719
- const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster: this.#advert });
798
+ const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster });
720
799
  await msg.encode(stream.writer, this.#session.version);
721
800
  // Read response (RequestOk and PublishNamespaceOk share 0x07)
722
801
  const respTypeId = await stream.reader.u53();
@@ -729,7 +808,7 @@ export class Publisher {
729
808
  if (!legacy) {
730
809
  refused.set(path, err.retryInterval === 0n ? "never" : Date.now() + Number(err.retryInterval));
731
810
  }
732
- throw new Error(`PublishNamespace rejected: ${err.errorCode} ${err.reasonPhrase}`);
811
+ throw new Error(`PublishNamespace rejected: ${requestReason(err.errorCode, err.reasonPhrase, "publish_namespace", this.#session.version)}`);
733
812
  }
734
813
  if (respTypeId !== RequestOk.id) {
735
814
  throw new Error(`PublishNamespace rejected: typeId=0x${respTypeId.toString(16)}`);
@@ -746,7 +825,8 @@ export class Publisher {
746
825
  return true;
747
826
  }
748
827
  catch (err) {
749
- const e = error(err);
828
+ // The peer never answered the advertisement: a control timeout, not late content.
829
+ const e = err instanceof TimeoutError ? controlTimeout(err) : error(err);
750
830
  console.warn(`announce failed: broadcast=${path} error=${reason(e)}`);
751
831
  request?.abort(e);
752
832
  return false;
@@ -812,19 +892,6 @@ export class Publisher {
812
892
  }
813
893
  stream.close();
814
894
  }
815
- /**
816
- * Closes every published broadcast and stops accepting new ones.
817
- *
818
- * @internal
819
- */
820
- close() {
821
- this.#broadcasts.update((broadcasts) => {
822
- for (const broadcast of broadcasts?.values() ?? []) {
823
- broadcast.close();
824
- }
825
- return undefined;
826
- });
827
- }
828
895
  }
829
896
  /**
830
897
  * Take one group out of a cache view, without waiting.