@moq/net 0.3.4 → 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 (215) hide show
  1. package/README.md +2 -2
  2. package/announce.d.ts +7 -0
  3. package/announce.d.ts.map +1 -0
  4. package/announce.js +8 -0
  5. package/announce.js.map +1 -0
  6. package/announced.d.ts +35 -91
  7. package/announced.d.ts.map +1 -1
  8. package/announced.js +21 -156
  9. package/announced.js.map +1 -1
  10. package/bandwidth.d.ts +163 -0
  11. package/bandwidth.d.ts.map +1 -0
  12. package/bandwidth.js +304 -0
  13. package/bandwidth.js.map +1 -0
  14. package/bandwidth_api.d.ts +7 -0
  15. package/bandwidth_api.d.ts.map +1 -0
  16. package/bandwidth_api.js +8 -0
  17. package/bandwidth_api.js.map +1 -0
  18. package/broadcast.d.ts +20 -28
  19. package/broadcast.d.ts.map +1 -1
  20. package/broadcast.js +60 -42
  21. package/broadcast.js.map +1 -1
  22. package/connection/accept.d.ts +16 -1
  23. package/connection/accept.d.ts.map +1 -1
  24. package/connection/accept.js +39 -24
  25. package/connection/accept.js.map +1 -1
  26. package/connection/browser.d.ts.map +1 -1
  27. package/connection/browser.js +9 -7
  28. package/connection/browser.js.map +1 -1
  29. package/connection/connect.d.ts +30 -6
  30. package/connection/connect.d.ts.map +1 -1
  31. package/connection/connect.js +97 -50
  32. package/connection/connect.js.map +1 -1
  33. package/connection/established.d.ts +16 -21
  34. package/connection/established.d.ts.map +1 -1
  35. package/connection/established.js.map +1 -1
  36. package/connection/forward.d.ts +2 -0
  37. package/connection/forward.d.ts.map +1 -0
  38. package/connection/forward.js +159 -0
  39. package/connection/forward.js.map +1 -0
  40. package/connection/handshake.d.ts.map +1 -1
  41. package/connection/handshake.js +2 -2
  42. package/connection/handshake.js.map +1 -1
  43. package/connection/index.d.ts +5 -5
  44. package/connection/index.d.ts.map +1 -1
  45. package/connection/index.js +4 -5
  46. package/connection/index.js.map +1 -1
  47. package/connection/pool.d.ts +188 -0
  48. package/connection/pool.d.ts.map +1 -0
  49. package/connection/pool.js +351 -0
  50. package/connection/pool.js.map +1 -0
  51. package/connection/reload.d.ts +14 -93
  52. package/connection/reload.d.ts.map +1 -1
  53. package/connection/reload.js +216 -80
  54. package/connection/reload.js.map +1 -1
  55. package/connection/stats.d.ts +3 -26
  56. package/connection/stats.d.ts.map +1 -1
  57. package/connection/stats.js.map +1 -1
  58. package/connection/transport.d.ts +0 -7
  59. package/connection/transport.d.ts.map +1 -1
  60. package/consume.d.ts +1 -43
  61. package/consume.d.ts.map +1 -1
  62. package/consume.js +1 -1
  63. package/consume.js.map +1 -1
  64. package/error.d.ts +180 -29
  65. package/error.d.ts.map +1 -1
  66. package/error.js +310 -16
  67. package/error.js.map +1 -1
  68. package/errors.d.ts +7 -0
  69. package/errors.d.ts.map +1 -0
  70. package/errors.js +8 -0
  71. package/errors.js.map +1 -0
  72. package/group.d.ts +9 -43
  73. package/group.d.ts.map +1 -1
  74. package/group.js +283 -69
  75. package/group.js.map +1 -1
  76. package/hop.d.ts +107 -0
  77. package/hop.d.ts.map +1 -0
  78. package/hop.js +103 -0
  79. package/hop.js.map +1 -0
  80. package/ietf/aliases.d.ts +1 -78
  81. package/ietf/aliases.d.ts.map +1 -1
  82. package/ietf/cluster.d.ts +6 -120
  83. package/ietf/cluster.d.ts.map +1 -1
  84. package/ietf/cluster.js +81 -41
  85. package/ietf/cluster.js.map +1 -1
  86. package/ietf/connection.d.ts +6 -72
  87. package/ietf/connection.d.ts.map +1 -1
  88. package/ietf/connection.js +11 -47
  89. package/ietf/connection.js.map +1 -1
  90. package/ietf/error.d.ts +11 -0
  91. package/ietf/error.d.ts.map +1 -0
  92. package/ietf/error.js +168 -0
  93. package/ietf/error.js.map +1 -0
  94. package/ietf/filter.d.ts.map +1 -1
  95. package/ietf/filter.js +6 -1
  96. package/ietf/filter.js.map +1 -1
  97. package/ietf/goaway.d.ts.map +1 -1
  98. package/ietf/goaway.js +22 -5
  99. package/ietf/goaway.js.map +1 -1
  100. package/ietf/parameters.d.ts +2 -2
  101. package/ietf/parameters.d.ts.map +1 -1
  102. package/ietf/parameters.js +15 -17
  103. package/ietf/parameters.js.map +1 -1
  104. package/ietf/publish_namespace.d.ts +25 -0
  105. package/ietf/publish_namespace.d.ts.map +1 -1
  106. package/ietf/publish_namespace.js +63 -0
  107. package/ietf/publish_namespace.js.map +1 -1
  108. package/ietf/publisher.d.ts +1 -82
  109. package/ietf/publisher.d.ts.map +1 -1
  110. package/ietf/publisher.js +219 -125
  111. package/ietf/publisher.js.map +1 -1
  112. package/ietf/solicit.d.ts +1 -40
  113. package/ietf/solicit.d.ts.map +1 -1
  114. package/ietf/subscribe.d.ts +1 -5
  115. package/ietf/subscribe.d.ts.map +1 -1
  116. package/ietf/subscribe.js +8 -9
  117. package/ietf/subscribe.js.map +1 -1
  118. package/ietf/subscriber.d.ts +1 -65
  119. package/ietf/subscriber.d.ts.map +1 -1
  120. package/ietf/subscriber.js +154 -73
  121. package/ietf/subscriber.js.map +1 -1
  122. package/ietf/version.d.ts +12 -1
  123. package/ietf/version.d.ts.map +1 -1
  124. package/ietf/version.js +13 -0
  125. package/ietf/version.js.map +1 -1
  126. package/index.d.ts +11 -6
  127. package/index.d.ts.map +1 -1
  128. package/index.js +10 -5
  129. package/index.js.map +1 -1
  130. package/internal.d.ts +99 -1
  131. package/internal.d.ts.map +1 -1
  132. package/internal.js +65 -0
  133. package/internal.js.map +1 -1
  134. package/lite/announce.d.ts +15 -9
  135. package/lite/announce.d.ts.map +1 -1
  136. package/lite/announce.js +47 -20
  137. package/lite/announce.js.map +1 -1
  138. package/lite/connection.d.ts +9 -59
  139. package/lite/connection.d.ts.map +1 -1
  140. package/lite/connection.js +20 -32
  141. package/lite/connection.js.map +1 -1
  142. package/lite/fetch.d.ts +15 -1
  143. package/lite/fetch.d.ts.map +1 -1
  144. package/lite/fetch.js +39 -7
  145. package/lite/fetch.js.map +1 -1
  146. package/lite/goaway.d.ts.map +1 -1
  147. package/lite/goaway.js +7 -1
  148. package/lite/goaway.js.map +1 -1
  149. package/lite/group.d.ts +18 -4
  150. package/lite/group.d.ts.map +1 -1
  151. package/lite/group.js +31 -10
  152. package/lite/group.js.map +1 -1
  153. package/lite/priority.d.ts +1 -61
  154. package/lite/priority.d.ts.map +1 -1
  155. package/lite/priority.js +4 -5
  156. package/lite/priority.js.map +1 -1
  157. package/lite/publisher.d.ts +1 -69
  158. package/lite/publisher.d.ts.map +1 -1
  159. package/lite/publisher.js +559 -232
  160. package/lite/publisher.js.map +1 -1
  161. package/lite/setup.d.ts +7 -7
  162. package/lite/setup.d.ts.map +1 -1
  163. package/lite/setup.js +13 -13
  164. package/lite/setup.js.map +1 -1
  165. package/lite/subscribe.d.ts +61 -13
  166. package/lite/subscribe.d.ts.map +1 -1
  167. package/lite/subscribe.js +186 -44
  168. package/lite/subscribe.js.map +1 -1
  169. package/lite/subscriber.d.ts +8 -57
  170. package/lite/subscriber.d.ts.map +1 -1
  171. package/lite/subscriber.js +179 -117
  172. package/lite/subscriber.js.map +1 -1
  173. package/lite/track.d.ts +4 -10
  174. package/lite/track.d.ts.map +1 -1
  175. package/lite/track.js +34 -29
  176. package/lite/track.js.map +1 -1
  177. package/lite/version.d.ts +31 -6
  178. package/lite/version.d.ts.map +1 -1
  179. package/lite/version.js +71 -11
  180. package/lite/version.js.map +1 -1
  181. package/origin.d.ts +229 -29
  182. package/origin.d.ts.map +1 -1
  183. package/origin.js +1087 -37
  184. package/origin.js.map +1 -1
  185. package/package.json +3 -2
  186. package/path.d.ts +25 -7
  187. package/path.d.ts.map +1 -1
  188. package/path.js +5 -3
  189. package/path.js.map +1 -1
  190. package/stream.d.ts.map +1 -1
  191. package/stream.js +25 -16
  192. package/stream.js.map +1 -1
  193. package/time.d.ts +15 -2
  194. package/time.d.ts.map +1 -1
  195. package/time.js +28 -9
  196. package/time.js.map +1 -1
  197. package/track.d.ts +171 -82
  198. package/track.d.ts.map +1 -1
  199. package/track.js +633 -184
  200. package/track.js.map +1 -1
  201. package/util/log.d.ts +5 -0
  202. package/util/log.d.ts.map +1 -0
  203. package/util/log.js +17 -0
  204. package/util/log.js.map +1 -0
  205. package/wire.d.ts +67 -0
  206. package/wire.d.ts.map +1 -0
  207. package/wire.js +32 -0
  208. package/wire.js.map +1 -0
  209. package/zod.d.ts +1 -1
  210. package/zod.d.ts.map +1 -1
  211. package/zod.js.map +1 -1
  212. package/mock.d.ts +0 -66
  213. package/mock.d.ts.map +0 -1
  214. package/mock.js +0 -243
  215. 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,10 +543,14 @@ export class Publisher {
488
543
  await new SubscribeNamespaceEntryDone({ suffix }).encode(stream.writer, version);
489
544
  }
490
545
  };
491
- let active = new Set();
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();
492
549
  let retry = 0;
493
550
  // What the peer refused, and whether coming back is worth anything.
494
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();
495
554
  for (;;) {
496
555
  // Subscribe BEFORE reconciling, for the same reason as
497
556
  // {@link runPublishNamespaces}: a publish landing while an advertisement
@@ -499,50 +558,63 @@ export class Publisher {
499
558
  // TODO Make a better helper within Signals.
500
559
  let dispose;
501
560
  const changed = new Promise((resolve) => {
502
- dispose = this.#broadcasts.changed(resolve);
561
+ dispose = this.#advertised.changed(resolve);
503
562
  });
504
- const broadcasts = this.#broadcasts.peek();
505
- if (!broadcasts) {
563
+ const advertised = this.#advertised.peek();
564
+ if (!advertised) {
506
565
  dispose();
507
566
  break;
508
567
  }
509
- const updated = new Set();
510
- for (const name of broadcasts.keys()) {
511
- const suffix = Path.stripPrefix(prefix, name);
568
+ const updated = new Map();
569
+ for (const [covered, snap] of advertised) {
570
+ const suffix = Path.stripPrefix(prefix, covered);
512
571
  if (suffix === null)
513
572
  continue;
514
- updated.add(suffix);
573
+ updated.set(suffix, snap);
515
574
  }
516
- // A namespace that is gone takes its refusal with it, so re-announcing the
517
- // path offers it again.
518
- const live = new Set([...updated].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.
519
579
  for (const path of [...refused.keys()]) {
520
- 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) {
521
583
  refused.delete(path);
584
+ offered.delete(path);
585
+ }
522
586
  }
523
587
  // Track what the peer holds rather than what we attempted: a declined
524
588
  // advertisement stays out of `held`, so the next turn retries it instead of
525
589
  // believing the namespace is already up.
526
- const held = new Set(active);
527
- for (const added of updated.difference(active)) {
528
- if (this.#offerable(Path.join(prefix, added), refused)) {
529
- if (await advertise(added))
530
- held.add(added);
531
- }
532
- }
533
- for (const removed of active.difference(updated)) {
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;
534
597
  await withdraw(removed);
535
598
  held.delete(removed);
536
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
+ }
537
609
  active = held;
538
610
  // Whatever we wanted up and could not get up, as {@link runPublishNamespaces}
539
611
  // does: only a legacy request can be declined, and nothing about the peer
540
612
  // starting to answer raises a signal this loop is watching.
541
- const outstanding = [...updated.difference(active)].some((suffix) => 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));
542
614
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
543
615
  // Wait for the next change, or for the peer to unsubscribe.
544
616
  const next = await (retry
545
- ? Promise.race([changed, stream.reader.closed, retryAfter(retry).then(() => broadcasts)])
617
+ ? Promise.race([changed, stream.reader.closed, retryAfter(retry).then(() => advertised)])
546
618
  : Promise.race([changed, stream.reader.closed]));
547
619
  dispose();
548
620
  if (!next)
@@ -581,11 +653,22 @@ export class Publisher {
581
653
  }
582
654
  // The open PUBLISH_NAMESPACE request per advertised path.
583
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);
662
+ let dispose;
584
663
  try {
585
- let active = new Set();
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();
586
667
  let retry = 0;
587
668
  // What the peer refused, and whether coming back is worth anything.
588
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();
589
672
  for (;;) {
590
673
  // Subscribe BEFORE reconciling. Each advertisement below waits a round trip
591
674
  // for the peer's reply, and a publish that lands in that window notifies
@@ -593,43 +676,59 @@ export class Publisher {
593
676
  // through it and leave the namespace unadvertised until something unrelated
594
677
  // changed.
595
678
  // TODO Make a better helper within Signals.
596
- let dispose;
597
679
  const changed = new Promise((resolve) => {
598
- dispose = this.#broadcasts.changed(resolve);
680
+ dispose = this.#advertised.changed(resolve);
599
681
  });
600
- const broadcasts = this.#broadcasts.peek();
601
- if (!broadcasts) {
602
- dispose();
682
+ const advertised = this.#advertised.peek();
683
+ if (!advertised) {
684
+ dispose?.();
603
685
  break;
604
686
  }
605
- const updated = new Set(broadcasts.keys());
606
- // A namespace that is gone takes its refusal with it, so re-announcing the
607
- // 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.
608
694
  for (const path of [...refused.keys()]) {
609
- if (!updated.has(path))
695
+ const snap = updated.get(path);
696
+ if (snap === undefined || offered.get(path) !== snap.identity) {
610
697
  refused.delete(path);
611
- }
612
- for (const added of updated.difference(active)) {
613
- if (this.#offerable(added, refused)) {
614
- await this.#advertise(added, requests, refused);
698
+ offered.delete(path);
615
699
  }
616
700
  }
617
- for (const removed of active.difference(updated)) {
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;
618
706
  await this.#withdraw(removed, requests);
619
707
  }
708
+ for (const [added, snap] of updated) {
709
+ if (sameAdvert(active.get(added), snap))
710
+ 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));
715
+ }
620
716
  // What the peer holds, not what we attempted: a declined PUBLISH_NAMESPACE
621
717
  // leaves no request behind, so it stays outstanding below.
622
- active = new Set(requests.keys());
718
+ active = new Map([...requests.keys()].flatMap((path) => {
719
+ const snap = updated.get(path);
720
+ return snap ? [[path, snap]] : [];
721
+ }));
623
722
  // Whatever we wanted up and could not get up. Stream credit freeing, a
624
723
  // transient failure clearing, or the peer starting to answer raises no
625
724
  // signal of its own, so the only way back is to ask again on a timer.
626
- const outstanding = [...updated.difference(active)].some((path) => this.#pending(path, refused));
725
+ const outstanding = [...updated].some(([path, snap]) => !sameAdvert(active.get(path), snap) && this.#pending(path, refused));
627
726
  retry = outstanding ? Math.min(retry ? retry * 2 : RETRY_BASE, RETRY_MAX) : 0;
628
727
  // Wait for the next change, which has already fired if one landed above.
629
728
  const next = await (retry
630
- ? Promise.race([changed, retryAfter(retry).then(() => broadcasts)])
631
- : changed);
632
- dispose();
729
+ ? Promise.race([changed, closed, retryAfter(retry).then(() => advertised)])
730
+ : Promise.race([changed, closed]));
731
+ dispose?.();
633
732
  if (!next)
634
733
  break;
635
734
  }
@@ -640,6 +739,7 @@ export class Publisher {
640
739
  console.warn(`publish_namespace loop failed: ${reason(error(err))}`);
641
740
  }
642
741
  finally {
742
+ dispose?.();
643
743
  // Close out every open PUBLISH_NAMESPACE request.
644
744
  for (const path of [...requests.keys()]) {
645
745
  await this.#withdraw(path, requests);
@@ -677,7 +777,7 @@ export class Publisher {
677
777
  * `refused` records what a refusal said about coming back, so a peer that asked not to
678
778
  * be offered a namespace again is not re-offered it by the retry above.
679
779
  */
680
- async #advertise(path, requests, refused) {
780
+ async #advertise(path, requests, refused, cluster = this.#advert) {
681
781
  const requestId = await this.#session.nextRequestId();
682
782
  if (requestId === undefined)
683
783
  return false;
@@ -695,7 +795,7 @@ export class Publisher {
695
795
  // turn and leaves it outstanding, which the retry above re-offers.
696
796
  await withTimeout((async () => {
697
797
  await stream.writer.u53(PublishNamespace.id);
698
- const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster: this.#advert });
798
+ const msg = new PublishNamespace({ requestId, trackNamespace: path, cluster });
699
799
  await msg.encode(stream.writer, this.#session.version);
700
800
  // Read response (RequestOk and PublishNamespaceOk share 0x07)
701
801
  const respTypeId = await stream.reader.u53();
@@ -708,7 +808,7 @@ export class Publisher {
708
808
  if (!legacy) {
709
809
  refused.set(path, err.retryInterval === 0n ? "never" : Date.now() + Number(err.retryInterval));
710
810
  }
711
- 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)}`);
712
812
  }
713
813
  if (respTypeId !== RequestOk.id) {
714
814
  throw new Error(`PublishNamespace rejected: typeId=0x${respTypeId.toString(16)}`);
@@ -725,7 +825,8 @@ export class Publisher {
725
825
  return true;
726
826
  }
727
827
  catch (err) {
728
- 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);
729
830
  console.warn(`announce failed: broadcast=${path} error=${reason(e)}`);
730
831
  request?.abort(e);
731
832
  return false;
@@ -753,8 +854,14 @@ export class Publisher {
753
854
  catch {
754
855
  // Stream might already be closed
755
856
  }
857
+ request.stream.close();
858
+ return;
756
859
  }
757
860
  request.stream.close();
861
+ // Wait for transport acknowledgment before opening a replacement request.
862
+ // This assumes the peer processes the withdrawal by then; FIN acknowledgment
863
+ // does not itself acknowledge application processing across streams.
864
+ await request.stream.writer.closed;
758
865
  }
759
866
  /**
760
867
  * Handles an incoming TRACK_STATUS_REQUEST on a bidi stream.
@@ -785,19 +892,6 @@ export class Publisher {
785
892
  }
786
893
  stream.close();
787
894
  }
788
- /**
789
- * Closes every published broadcast and stops accepting new ones.
790
- *
791
- * @internal
792
- */
793
- close() {
794
- this.#broadcasts.update((broadcasts) => {
795
- for (const broadcast of broadcasts?.values() ?? []) {
796
- broadcast.close();
797
- }
798
- return undefined;
799
- });
800
- }
801
895
  }
802
896
  /**
803
897
  * Take one group out of a cache view, without waiting.