@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/origin.js CHANGED
@@ -1,59 +1,1109 @@
1
1
  /* @ts-self-types="./origin.d.ts" */
2
2
  /**
3
- * Endpoint identity within a hop chain, shared by both wire protocols.
3
+ * A broadcast routing table, independent of any connection.
4
4
  *
5
- * moq-lite carries these natively on every announcement; moq-transport carries them
6
- * via the MoQ Cluster extension (see `ietf/cluster.ts`). Mirrors `Origin` in
5
+ * Publish broadcasts into an origin and hand the origin to one or more connections to
6
+ * serve them; the broadcasts outlive any single session. Hand the same (or another)
7
+ * origin to a connection's `consume` option and the peer's announced routes appear
8
+ * in the table too: each route covers a path prefix, and a request for a path under
9
+ * it resolves through the session that announced it. Mirrors the `origin` module in
7
10
  * `rs/moq-net`.
8
11
  *
9
12
  * @module
10
13
  */
11
- import * as z from "@zod/mini";
14
+ import { Derived, getter, Once, Signal } from "@moq/signals";
15
+ import * as announce from "./announced.js";
16
+ import * as broadcast from "./broadcast.js";
17
+ import { StreamCode, StreamError } from "./error.js";
18
+ import { Route, routesEqual } from "./hop.js";
19
+ import { hooks, scopeCaptures, scopeOverlaps } from "./internal.js";
20
+ import * as Path from "./path.js";
21
+ import { registerWire, wireOf } from "./wire.js";
22
+ export { isAnonymous } from "./hop.js";
23
+ function noCapacity() {
24
+ return new StreamError(StreamCode.NoCapacity, { message: "no capacity" });
25
+ }
26
+ /** A served route from {@link Producer.dynamic}: the queue a handler drains. */
27
+ class ServeState {
28
+ queue = new Signal([]);
29
+ pending = new Map();
30
+ served = new Map();
31
+ rejected = new Map();
32
+ // demand() is the only reader of `rejected`. A Consumer.request refusal never
33
+ // re-enqueues, so storing the error without a waiter would pin every unique
34
+ // path until the route dies.
35
+ demanding = new Map();
36
+ closed = new Once();
37
+ settled = new Signal(0);
38
+ onChange = () => { };
39
+ onReject = () => { };
40
+ enqueue(path) {
41
+ if (this.closed.peek() !== undefined)
42
+ return;
43
+ this.rejected.delete(path);
44
+ if (this.pending.has(path))
45
+ return;
46
+ const live = this.served.get(path);
47
+ if (live && live.closed.peek() === undefined)
48
+ return;
49
+ const request = makeRequest(path, this);
50
+ this.pending.set(path, request);
51
+ this.queue.mutate((queue) => {
52
+ queue.push(request);
53
+ });
54
+ }
55
+ accept(request, front) {
56
+ if (this.closed.peek() !== undefined || this.pending.get(request.path) !== request) {
57
+ front.close();
58
+ return;
59
+ }
60
+ this.pending.delete(request.path);
61
+ const existing = this.served.get(request.path);
62
+ if (existing && existing.closed.peek() === undefined) {
63
+ front.close();
64
+ this.onChange(request.path);
65
+ this.settled.update((n) => n + 1);
66
+ return;
67
+ }
68
+ this.served.set(request.path, front);
69
+ void front.closed.then(() => {
70
+ if (this.served.get(request.path) !== front)
71
+ return;
72
+ this.served.delete(request.path);
73
+ this.onChange(request.path);
74
+ });
75
+ this.onChange(request.path);
76
+ this.settled.update((n) => n + 1);
77
+ }
78
+ reject(request, err) {
79
+ if (this.pending.get(request.path) !== request)
80
+ return;
81
+ this.pending.delete(request.path);
82
+ if (this.demanding.has(request.path))
83
+ this.rejected.set(request.path, err);
84
+ this.onReject(request.path);
85
+ this.settled.update((n) => n + 1);
86
+ }
87
+ close(abort) {
88
+ if (this.closed.peek() !== undefined)
89
+ return;
90
+ const err = abort ?? noCapacity();
91
+ this.closed.set(err);
92
+ const queued = [...this.pending.values()];
93
+ this.pending.clear();
94
+ this.queue.mutate((queue) => {
95
+ queue.length = 0;
96
+ });
97
+ for (const request of queued) {
98
+ finishRequest(request, err);
99
+ }
100
+ for (const [path, front] of this.served) {
101
+ front.close(abort);
102
+ this.onChange(path);
103
+ }
104
+ this.served.clear();
105
+ this.rejected.clear();
106
+ this.demanding.clear();
107
+ this.settled.update((n) => n + 1);
108
+ }
109
+ }
110
+ /** Reactive backing state shared by origin producers and consumers. */
111
+ class OriginState {
112
+ // Both tables decouple the application producing into the origin from the
113
+ // connections serving or feeding it. Undefined once the origin closes, so late
114
+ // writes fail loudly.
115
+ //
116
+ // Local is what this endpoint creates, keyed by exact path: reachable for
117
+ // subscribes whether or not it is advertised. Routes is the advertisement table:
118
+ // prefixes a dynamic handle or a received session covers, newest first. They stay
119
+ // separate so a session can never announce a received entry back to a peer, which
120
+ // is what makes an origin shared by both directions echo-free.
121
+ local = new Signal(new Map());
122
+ advertisedLocal = new Signal(new Map());
123
+ routes = new Signal(new Map());
124
+ // Originated advertisements sessions should forward: exact-path announces plus
125
+ // originated dynamics. Identity is the local front or the route entry, so a
126
+ // republish diffs as retract-then-announce and a re-price as another active.
127
+ originated = new Signal(new Map());
128
+ // Broadcasts materialized from a served route, keyed by exact path. Shared by every
129
+ // request for the path so repeats reuse one accept; dropped (and closed) when the
130
+ // providing route goes away or the last request releases it.
131
+ materialized = new Map();
132
+ // Paths consumers asked for without waiting for an announcement; attached sessions
133
+ // answer them with blind subscriptions. Never announced: an answered request is assumed
134
+ // present, not known live, so it must not read as an availability claim.
135
+ requests = new Signal(new Map());
136
+ // How many sessions are attached, and how many of those support broadcast discovery.
137
+ // What backs the public `discovery` getter.
138
+ sessions = new Signal({ total: 0, discovery: 0 });
139
+ // How many things are prepared to answer a request: attached sessions, plus reconnecting
140
+ // connections that have no session right now but will. Zero means an unrouted path is
141
+ // unroutable rather than merely unanswered, which is the whole difference between "wait,
142
+ // this is coming" and "nothing here can ever serve you".
143
+ answerers = new Signal(0);
144
+ closed = new Once();
145
+ /**
146
+ * Recompute what `path` resolves to, waking only the requests watching that path.
147
+ *
148
+ * A no-op for a path nobody requested, so the common case (publishing into a table
149
+ * nobody is asking about) costs a map lookup. Call after any write that could change
150
+ * the answer for a single path.
151
+ */
152
+ refresh(path) {
153
+ const slot = this.requests.peek()?.get(path);
154
+ if (!slot)
155
+ return;
156
+ slot.route.set(this.route(path, slot));
157
+ }
158
+ /** Record that `entry` refused `path` and re-route the requests watching it. */
159
+ refuse(path, entry) {
160
+ const slot = this.requests.peek()?.get(path);
161
+ if (!slot)
162
+ return;
163
+ slot.refused.add(entry);
164
+ slot.route.set(this.route(path, slot));
165
+ }
166
+ /**
167
+ * Recompute every open request covered by `prefix`, after a route was inserted or
168
+ * removed there: a route covers many paths, so a single-path refresh is not enough.
169
+ * Materialized broadcasts whose provider changed are released here too, so a
170
+ * retracted route's session subscription closes even when nothing reads it again.
171
+ */
172
+ refreshPrefix(prefix) {
173
+ const requests = this.requests.peek();
174
+ for (const [path, cached] of [...this.materialized]) {
175
+ if (!Path.hasPrefix(prefix, path))
176
+ continue;
177
+ if (cached.entry !== this.bestEntry(path, requests?.get(path)?.refused)) {
178
+ this.materialized.delete(path);
179
+ cached.front.close();
180
+ }
181
+ }
182
+ for (const [path, slot] of requests ?? []) {
183
+ if (Path.hasPrefix(prefix, path))
184
+ slot.route.set(this.route(path, slot));
185
+ }
186
+ }
187
+ /** Rebuild the publisher-facing originated table after an advertisement write. */
188
+ rebuildOriginated() {
189
+ const local = this.local.peek();
190
+ const advertised = this.advertisedLocal.peek();
191
+ const routes = this.routes.peek();
192
+ if (!local && !advertised && !routes) {
193
+ this.originated.set(undefined);
194
+ return;
195
+ }
196
+ const next = new Map();
197
+ for (const [path, route] of advertised ?? []) {
198
+ const front = local?.get(path);
199
+ if (front)
200
+ next.set(path, { identity: front, route });
201
+ }
202
+ for (const [prefix, entries] of routes ?? []) {
203
+ const mine = entries.find((entry) => entry.originated);
204
+ if (mine)
205
+ next.set(prefix, { identity: mine.identity, route: mine.route.peek() });
206
+ }
207
+ this.originated.set(next);
208
+ }
209
+ /**
210
+ * Release the materialized broadcast for `path`, once its last request is gone: the
211
+ * cache exists to share one session subscription between requests, not to outlive
212
+ * them.
213
+ */
214
+ releaseMaterialized(path) {
215
+ const cached = this.materialized.get(path);
216
+ if (!cached)
217
+ return;
218
+ this.materialized.delete(path);
219
+ cached.front.close();
220
+ }
221
+ /** The newest entry on the most specific route covering `path`, skipping `refused`, if any. */
222
+ bestEntry(path, refused) {
223
+ let bestPrefix;
224
+ let best;
225
+ for (const [prefix, entries] of this.routes.peek() ?? []) {
226
+ const entry = entries.find((candidate) => !refused?.has(candidate));
227
+ if (!entry)
228
+ continue;
229
+ if (!Path.hasPrefix(prefix, path))
230
+ continue;
231
+ if (bestPrefix === undefined || prefix.length > bestPrefix.length) {
232
+ bestPrefix = prefix;
233
+ best = entry;
234
+ }
235
+ }
236
+ return best;
237
+ }
238
+ /**
239
+ * What `path` resolves to: a local publish, a broadcast materialized from the best
240
+ * covering route, or the blind answer.
241
+ *
242
+ * Materialization is lazy and cached per path: the first request under a route opens
243
+ * the providing session's subscription, repeats share it, and a provider change (the
244
+ * route retracting, a better session taking over) swaps it out.
245
+ */
246
+ route(path, slot) {
247
+ const local = this.local.peek()?.get(path);
248
+ if (local)
249
+ return local;
250
+ const entry = this.bestEntry(path, slot.refused);
251
+ const cached = this.materialized.get(path);
252
+ if (cached && cached.entry === entry) {
253
+ if (cached.front.closed.peek() === undefined)
254
+ return cached.front;
255
+ this.materialized.delete(path);
256
+ }
257
+ else if (cached) {
258
+ this.materialized.delete(path);
259
+ cached.front.close();
260
+ }
261
+ if (!entry?.server)
262
+ return slot.answer;
263
+ const served = entry.server.served.get(path);
264
+ if (served && served.closed.peek() === undefined) {
265
+ this.materialized.set(path, { entry, front: served });
266
+ return served;
267
+ }
268
+ entry.server.enqueue(path);
269
+ return undefined;
270
+ }
271
+ }
272
+ /**
273
+ * The write side of an origin: create broadcasts by path and advertise them.
274
+ *
275
+ * Independent of any connection. A connection given this origin (via its `publish` option)
276
+ * announces and serves the table's originated advertisements for as long as the session
277
+ * lasts; the broadcasts themselves live until their producer closes or {@link close} tears
278
+ * the origin down. A reconnecting session re-announces the table on each attach, so
279
+ * advertisements made while offline surface on the next connection.
280
+ *
281
+ * Create, attach {@link dynamic} for tracks served on demand, populate, then
282
+ * {@link broadcast.Producer.announce}: an exact-path subscribe before the tracks exist is
283
+ * refused, and announcing advertises the path to peers.
284
+ *
285
+ * @public
286
+ */
287
+ export class Producer {
288
+ #state = new OriginState();
289
+ // The reader backing the passthroughs, so holding a Producer never requires the
290
+ // consume().x() stutter for everyday reads. One instance, so `discovery` keeps its
291
+ // identity across reads.
292
+ #reader = makeConsumer(this.#state);
293
+ constructor() {
294
+ const thisProducer = this;
295
+ registerWire(this, {
296
+ receive: (prefix, route) => this.#receive(prefix, route),
297
+ attach: (discovery) => this.#attach(discovery),
298
+ expect: () => this.#expect(),
299
+ get requests() {
300
+ return thisProducer.#state.requests;
301
+ },
302
+ changed: () => this.#changed(),
303
+ answer: (path, front) => this.#answer(path, front),
304
+ routes: (path) => wireOf(this.#reader).routes(path),
305
+ });
306
+ }
307
+ /**
308
+ * Settles once the origin closes: `null` on a clean close, or the abort {@link Error}.
309
+ * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.
310
+ */
311
+ get closed() {
312
+ return this.#state.closed;
313
+ }
314
+ /**
315
+ * Create a broadcast at `path`, returning its producer.
316
+ *
317
+ * The broadcast appears on this origin's local announce streams immediately.
318
+ * Call {@link broadcast.Producer.announce} to advertise it to peers once its
319
+ * tracks exist. Local consumers can discover and request it without that call.
320
+ *
321
+ * Close the producer to drop it. Creating a path again supersedes the previous
322
+ * broadcast: the origin drops its handle on the old one, which closes it unless the
323
+ * application still holds a consumer clone. A local broadcast also shadows any
324
+ * remote broadcast at the same path.
325
+ */
326
+ createBroadcast(path) {
327
+ const producer = new broadcast.Producer();
328
+ const front = producer.consume();
329
+ hooks.attachAnnouncer(producer, {
330
+ announce: (route) => this.#advertiseExact(path, front, route),
331
+ unannounce: () => this.#retractExact(path, front),
332
+ });
333
+ this.#state.local.mutate((broadcasts) => {
334
+ if (!broadcasts)
335
+ throw new Error("origin is closed");
336
+ broadcasts.get(path)?.close();
337
+ broadcasts.set(path, front);
338
+ });
339
+ this.#state.advertisedLocal.mutate((advertised) => {
340
+ advertised?.delete(path);
341
+ });
342
+ this.#state.rebuildOriginated();
343
+ this.#state.refresh(path);
344
+ // Drop it when the broadcast closes, unless a recreate already replaced it: a
345
+ // stale broadcast closing must not unpublish the live one.
346
+ void front.closed.then(() => {
347
+ this.#retractExact(path, front);
348
+ this.#state.local.mutate((broadcasts) => {
349
+ if (broadcasts?.get(path) === front)
350
+ broadcasts.delete(path);
351
+ });
352
+ this.#state.refresh(path);
353
+ });
354
+ return producer;
355
+ }
356
+ #advertiseExact(path, front, route) {
357
+ this.#state.advertisedLocal.mutate((advertised) => {
358
+ if (!advertised)
359
+ throw new Error("origin is closed");
360
+ if (this.#state.local.peek()?.get(path) !== front)
361
+ throw new Error("broadcast is closed");
362
+ advertised.set(path, route);
363
+ });
364
+ this.#state.rebuildOriginated();
365
+ this.#state.refresh(path);
366
+ }
367
+ #retractExact(path, front) {
368
+ this.#state.advertisedLocal.mutate((advertised) => {
369
+ if (this.#state.local.peek()?.get(path) !== front)
370
+ return;
371
+ advertised?.delete(path);
372
+ });
373
+ this.#state.rebuildOriginated();
374
+ this.#state.refresh(path);
375
+ }
376
+ /**
377
+ * Advertise `prefix` and serve the requests beneath it.
378
+ *
379
+ * A route is always a prefix: it claims `prefix` and every path beneath it (the
380
+ * empty prefix claims every path). A service that only serves some of them
381
+ * advertises the covering prefix and rejects the rest as they are requested;
382
+ * consumers narrow with a {@link Path.Pattern} locally. The advertisement is
383
+ * visible to {@link Consumer.announced} and forwarded by sessions for as long as
384
+ * the returned {@link Dynamic} lives. A consumer resolving a path under it that
385
+ * no local broadcast covers is handed to the handle as a {@link Request}.
386
+ */
387
+ dynamic(prefix, route = Route.default) {
388
+ return this.#insertRoute(prefix, Route.normalize(route), true);
389
+ }
390
+ /**
391
+ * Land a route a peer announced, served through the returned handle. Same as
392
+ * {@link dynamic} but not originated, so a session never announces it back.
393
+ *
394
+ * @internal
395
+ */
396
+ #receive(prefix, route = Route.default) {
397
+ return this.#insertRoute(prefix, Route.normalize(route), false);
398
+ }
399
+ #insertRoute(prefix, route, originated) {
400
+ const server = new ServeState();
401
+ server.onChange = (path) => this.#state.refresh(path);
402
+ const entry = {
403
+ identity: {},
404
+ route: new Signal(route),
405
+ originated,
406
+ server,
407
+ };
408
+ server.onReject = (path) => this.#state.refuse(path, entry);
409
+ let closed = false;
410
+ this.#state.routes.mutate((routes) => {
411
+ if (!routes) {
412
+ closed = true;
413
+ return;
414
+ }
415
+ const entries = routes.get(prefix);
416
+ if (entries)
417
+ entries.unshift(entry);
418
+ else
419
+ routes.set(prefix, [entry]);
420
+ });
421
+ if (closed) {
422
+ server.close();
423
+ return makeDynamic(prefix, entry, this.#state, () => { });
424
+ }
425
+ this.#state.rebuildOriginated();
426
+ this.#state.refreshPrefix(prefix);
427
+ const retract = () => {
428
+ this.#state.routes.mutate((routes) => {
429
+ const entries = routes?.get(prefix);
430
+ if (!entries)
431
+ return;
432
+ const index = entries.indexOf(entry);
433
+ if (index < 0)
434
+ return;
435
+ entries.splice(index, 1);
436
+ if (entries.length === 0)
437
+ routes?.delete(prefix);
438
+ });
439
+ // A retracted entry can never be picked again, so the refusals pinned to it are dead weight.
440
+ for (const slot of this.#state.requests.peek()?.values() ?? [])
441
+ slot.refused.delete(entry);
442
+ server.close();
443
+ this.#state.rebuildOriginated();
444
+ this.#state.refreshPrefix(prefix);
445
+ };
446
+ return makeDynamic(prefix, entry, this.#state, retract);
447
+ }
448
+ /**
449
+ * Register an attached session, counting it toward the `discovery` state. Returns the
450
+ * detach; call it exactly once when the session dies.
451
+ *
452
+ * @internal
453
+ */
454
+ #attach(discovery) {
455
+ this.#sessions(1, discovery);
456
+ const release = this.#expect();
457
+ let detached = false;
458
+ return () => {
459
+ if (detached)
460
+ return;
461
+ detached = true;
462
+ this.#sessions(-1, discovery);
463
+ release();
464
+ };
465
+ }
466
+ #sessions(delta, discovery) {
467
+ this.#state.sessions.update(({ total, discovery: d }) => ({
468
+ total: total + delta,
469
+ discovery: d + (discovery ? delta : 0),
470
+ }));
471
+ }
472
+ /**
473
+ * Declare that something will answer requests on this origin, even with no session
474
+ * attached right now.
475
+ *
476
+ * A reconnecting connection holds one for its whole life, so a request made during a
477
+ * reconnect (or before the first session establishes) stays pending instead of reading as
478
+ * unroutable. Without it, {@link Request.unroutable} would fire on every page load, in the
479
+ * window between wiring the origin up and the handshake completing. Call the returned
480
+ * dispose when the connection is done for good.
481
+ *
482
+ * @internal
483
+ */
484
+ #expect() {
485
+ this.#state.answerers.update((count) => count + 1);
486
+ let released = false;
487
+ return () => {
488
+ if (released)
489
+ return;
490
+ released = true;
491
+ // Clamped because closing the origin zeroes the count, and the sessions attached at
492
+ // the time still release afterwards.
493
+ this.#state.answerers.update((count) => Math.max(0, count - 1));
494
+ };
495
+ }
496
+ /**
497
+ * Resolves once anything a serving session scans changes: the open requests, or either
498
+ * side of the routing table.
499
+ *
500
+ * @internal
501
+ */
502
+ #changed() {
503
+ return Signal.race(this.#state.requests, this.#state.local, this.#state.routes, this.#state.advertisedLocal);
504
+ }
505
+ /**
506
+ * Provide `front` as the answer for the open request on `path`, taking ownership of it.
507
+ *
508
+ * Returns undefined (releasing the front) when the request is gone or already answered;
509
+ * first session in wins, and a loser must stay eligible to answer later. The returned
510
+ * withdraw releases the front and, if it was the standing answer, vacates the slot and
511
+ * wakes the other serving loops so a standby session answers immediately; call it when
512
+ * the session dies.
513
+ *
514
+ * @internal
515
+ */
516
+ #answer(path, front) {
517
+ const slot = this.#state.requests.peek()?.get(path);
518
+ if (!slot || slot.answer !== undefined) {
519
+ front.close();
520
+ return undefined;
521
+ }
522
+ slot.answer = front;
523
+ this.#state.refresh(path);
524
+ return () => {
525
+ if (slot.answer === front) {
526
+ slot.answer = undefined;
527
+ this.#state.refresh(path);
528
+ // The route signal only reaches this path's requesters; poke the map so every
529
+ // serving loop re-scans and one of them re-answers.
530
+ this.#state.requests.mutate(() => { });
531
+ }
532
+ front.close();
533
+ };
534
+ }
535
+ /** A read handle for this origin, the side a connection's `publish` option borrows. */
536
+ consume() {
537
+ return makeConsumer(this.#state);
538
+ }
539
+ /** Whether every attached session announces into the table; see {@link Consumer.discovery}. */
540
+ get discovery() {
541
+ return this.#reader.discovery;
542
+ }
543
+ /** Resolve `path`, optionally waiting for an announcement; see {@link Consumer.request}. */
544
+ request(path, options) {
545
+ return this.#reader.request(path, options);
546
+ }
547
+ /** The available broadcasts under `scope`, as a live stream; see {@link Consumer.announced}. */
548
+ announced(scope) {
549
+ return this.#reader.announced(scope);
550
+ }
551
+ /** Close the origin, every broadcast it still routes, and its announcement streams. Idempotent. */
552
+ close(abort) {
553
+ if (this.#state.closed.peek() !== undefined)
554
+ return;
555
+ this.#state.closed.set(abort ?? null);
556
+ this.#state.local.update((broadcasts) => {
557
+ for (const front of broadcasts?.values() ?? []) {
558
+ front.close(abort);
559
+ }
560
+ return undefined;
561
+ });
562
+ this.#state.advertisedLocal.update(() => undefined);
563
+ this.#state.routes.update((routes) => {
564
+ for (const entries of routes?.values() ?? []) {
565
+ for (const entry of entries)
566
+ entry.server?.close(abort);
567
+ }
568
+ return undefined;
569
+ });
570
+ this.#state.originated.update(() => undefined);
571
+ // Materialized broadcasts are handles we opened; release them.
572
+ for (const cached of this.#state.materialized.values()) {
573
+ cached.front.close();
574
+ }
575
+ this.#state.materialized.clear();
576
+ // Nothing will answer a request on a closed origin, whatever is still attached, so
577
+ // existing requests report unroutable rather than waiting on a corpse.
578
+ this.#state.answerers.set(0);
579
+ this.#state.requests.update((requests) => {
580
+ for (const slot of requests?.values() ?? []) {
581
+ slot.answer?.close();
582
+ slot.answer = undefined;
583
+ slot.route.set(undefined);
584
+ }
585
+ return undefined;
586
+ });
587
+ }
588
+ }
589
+ // Constructs a Consumer from within this module without exposing a public constructor
590
+ // that would leak the unexported OriginState. Assigned in the class's static block.
591
+ let makeConsumer;
592
+ // Same for Requesting: a public constructor would let a caller forge a handle that no origin
593
+ // ever registered, whose lifecycle guarantees are then false. `@internal` alone would not
594
+ // stop it, since the declaration emit keeps the constructor.
595
+ let makeRequesting;
596
+ let makeDynamic;
597
+ let makeRequest;
598
+ let finishRequest;
12
599
  /**
13
- * A relay origin id, encoded as a 62-bit varint on the wire.
600
+ * An open request for a path nothing announced; see {@link Consumer.request}.
14
601
  *
15
- * The {@link OriginSchema} validates any incoming value and brands it so the
16
- * type system enforces "only validated origins flow into hop lists." Internal
17
- * code that synthesizes an id (e.g. {@link randomOrigin}) uses
18
- * `OriginSchema.parse(...)` to produce a branded value from the raw bigint.
602
+ * @public
19
603
  */
20
- export const OriginSchema = z
21
- .bigint()
22
- .check(z.refine((value) => value >= 0n && value < 1n << 62n, "Origin must be a non-negative 62-bit integer"))
23
- .brand("Origin");
604
+ export class Requesting {
605
+ /** The requested path. */
606
+ path;
607
+ /**
608
+ * The resolved broadcast, or undefined while nothing provides the path.
609
+ *
610
+ * The table's route when it has one: a local publish (no round trip) or an announced
611
+ * broadcast, swapping when a republish takes the path. Otherwise a session's blind
612
+ * answer, which is assumed present rather than known live: a missing broadcast
613
+ * surfaces as a reset on the first track subscription, not here. Drops back to
614
+ * undefined when the providing route dies and resolves again when another appears.
615
+ *
616
+ * Yours for as long as the request is open: it is a handle of this request's own, so
617
+ * closing it ends your view of the path rather than the route everyone else reads.
618
+ * {@link close} releases whatever is current.
619
+ */
620
+ active;
621
+ /**
622
+ * Whether nothing can serve this path, as opposed to not having served it yet.
623
+ *
624
+ * True when the origin routes nothing here and nothing is prepared to answer: no session
625
+ * attached and no connection reconnecting toward one. False whenever {@link active} is
626
+ * set, and false while a connection is still coming up, so the ordinary page-load window
627
+ * before the first handshake reads as pending rather than as a missing broadcast. Waiting
628
+ * on this is futile by definition; wait for an announcement instead, via the origin's
629
+ * `announced`.
630
+ */
631
+ unroutable;
632
+ #dispose;
633
+ #closed = false;
634
+ constructor(path, active, unroutable, dispose) {
635
+ this.path = path;
636
+ this.active = active;
637
+ this.unroutable = unroutable;
638
+ this.#dispose = dispose;
639
+ }
640
+ static {
641
+ makeRequesting = (path, active, unroutable, dispose) => new Requesting(path, active, unroutable, dispose);
642
+ }
643
+ /** Withdraw the request. The path stays routed for any other open request. Idempotent. */
644
+ close() {
645
+ if (this.#closed)
646
+ return;
647
+ this.#closed = true;
648
+ this.#dispose();
649
+ }
650
+ }
24
651
  /**
25
- * The reserved id 0, meaning "no identity".
652
+ * The read side of an origin: resolve broadcasts by path and watch what is available.
653
+ *
654
+ * Obtain one from {@link Producer.consume}. Pass it to a connection's `publish` option to
655
+ * serve the origin's local broadcasts to that peer; read it directly to consume anything
656
+ * the origin routes, locally published or discovered by a session.
26
657
  *
27
- * It stands in for an endpoint that never declared one, and any number of endpoints can
28
- * be 0, so it identifies nothing: it is never a loop, never a publisher two chains have
29
- * in common, and never excluded from an advertisement.
658
+ * @public
30
659
  */
31
- export const UNKNOWN_ORIGIN = OriginSchema.parse(0n);
660
+ export class Consumer {
661
+ #state;
662
+ constructor(state) {
663
+ this.#state = state;
664
+ // True only when every attached session announces. One session that cannot means the
665
+ // table is an incomplete picture, so a consumer gated on it has to keep its blind
666
+ // fallback: the paths only that session carries never reach the table at all.
667
+ this.#discovery = new Derived([state.sessions], ({ total, discovery }) => total === 0 ? undefined : discovery === total);
668
+ registerWire(this, {
669
+ routes: (path) => this.#routes(path),
670
+ get broadcasts() {
671
+ return state.local;
672
+ },
673
+ get advertised() {
674
+ return state.originated;
675
+ },
676
+ demand: (path) => this.#demand(path),
677
+ });
678
+ }
679
+ static {
680
+ makeConsumer = (state) => new Consumer(state);
681
+ }
682
+ /** Settles once the origin closes; see {@link Producer.closed}. */
683
+ get closed() {
684
+ return this.#state.closed;
685
+ }
686
+ /**
687
+ * Whether the announcement table sees everything the attached sessions can serve.
688
+ *
689
+ * Undefined while no session is attached (nothing is known yet), true when every attached
690
+ * session announces into the table, and false as soon as one does not, where
691
+ * {@link announced} cannot be complete and consumers should {@link request} paths instead
692
+ * of waiting. One blind session among several is still false: the paths only it carries
693
+ * never reach the table, so a consumer that trusted the gate would never see them.
694
+ */
695
+ get discovery() {
696
+ return this.#discovery;
697
+ }
698
+ // Derived per access rather than cached: a lightweight mapped view over the session
699
+ // counts, avoiding a Computed's lifecycle.
700
+ #discovery;
701
+ /**
702
+ * Whether the table routes `path`, by a local publish or an announced route
703
+ * covering it.
704
+ *
705
+ * Availability, not a handle: {@link request} is the only way to consume by path. A
706
+ * request on a routed path resolves to that route and never to a blind answer, which is
707
+ * why a serving session leaves it alone.
708
+ *
709
+ * @internal
710
+ */
711
+ #routes(path) {
712
+ if (this.#state.local.peek()?.has(path))
713
+ return true;
714
+ return this.#state.bestEntry(path) !== undefined;
715
+ }
716
+ /**
717
+ * Resolve `path`, optionally waiting for an announcement.
718
+ *
719
+ * The one way to consume by path. {@link Requesting.active} follows whatever the table
720
+ * routes (a local publish, or any feeding session's announcement, swapping on a
721
+ * republish); when nothing does, the request stands and whichever attached session
722
+ * answers first provides a blind subscription instead, re-answered across reconnects.
723
+ * With `announced: true`, an unrouted request waits while discovery is supported and
724
+ * falls back to that blind behavior only when discovery is unavailable. Close the request
725
+ * when done. On a closed origin it never resolves.
726
+ *
727
+ * With several sessions on one origin the first to answer wins, and it may be one that
728
+ * does not carry the path. Nothing corrects that: a missing broadcast surfaces as a reset
729
+ * on the first track and deliberately leaves the handle open, since the wire cannot tell
730
+ * "not here" from "not yet" and a blind handle is expected to survive until a publisher
731
+ * arrives. It matters only on an origin mixing sessions that announce with sessions that
732
+ * cannot, where a path only the silent session carries may sit behind another session's
733
+ * answer. Prefer {@link unroutable} and announcements over blind requests when the origin
734
+ * feeds from more than one connection.
735
+ */
736
+ request(path, options = {}) {
737
+ const requests = this.#state.requests.peek();
738
+ if (!requests) {
739
+ // Closed origin: a request that can never resolve, and says so.
740
+ return makeRequesting(path, new Signal(undefined), getter(true), () => { });
741
+ }
742
+ let slot = requests.get(path);
743
+ if (!slot) {
744
+ // Seeded through the constructor, so a path the table already routes resolves on the
745
+ // first read. It must not go through a silent set: that still captures the pre-seed
746
+ // value as the baseline the next change is compared against, and never flushes to
747
+ // clear it, so a seeded route retracting to undefined would look like no change and
748
+ // notify nobody.
749
+ const refused = new Set();
750
+ const created = {
751
+ count: 0,
752
+ blind: 0,
753
+ refused,
754
+ route: new Signal(this.#state.route(path, { refused })),
755
+ };
756
+ slot = created;
757
+ this.#state.requests.mutate((map) => {
758
+ map?.set(path, created);
759
+ });
760
+ }
761
+ slot.count += 1;
762
+ let blind = !options.announced || this.#discovery.peek() === false;
763
+ if (blind)
764
+ slot.blind += 1;
765
+ this.#state.requests.mutate(() => { });
766
+ // An announcement-gated request falls back to a blind subscription only while at
767
+ // least one attached session cannot announce. It returns to the gate if discovery
768
+ // becomes complete again, and remains gated with no session attached.
769
+ const unsubscribeDiscovery = options.announced
770
+ ? this.#discovery.subscribe((discovery) => {
771
+ const next = discovery === false;
772
+ if (next === blind)
773
+ return;
774
+ blind = next;
775
+ slot.blind += next ? 1 : -1;
776
+ this.#state.requests.mutate(() => { });
777
+ })
778
+ : () => { };
779
+ // Hand out a handle of the request's own rather than the table's. Closing a consumer
780
+ // closes the broadcast once it was the last one, and the table often holds the only
781
+ // other handle, so lending its front out means an ordinary close() by one requester
782
+ // can unpublish the path for everybody else.
783
+ const taken = slot;
784
+ // Memoized on the route's identity: the same front resolving again returns the handle
785
+ // we already made, and only a real swap clones a new one (cloning before closing the
786
+ // old, so a broadcast that both routes share never briefly loses its last handle).
787
+ let released = false;
788
+ let source;
789
+ let handle;
790
+ const own = (front) => {
791
+ if (released)
792
+ return undefined;
793
+ if (front !== source) {
794
+ const previous = handle;
795
+ source = front;
796
+ handle = front?.clone();
797
+ previous?.close();
798
+ }
799
+ return handle;
800
+ };
801
+ const route = taken.route;
802
+ const active = new Derived([route], own);
803
+ // Swapping on the read is what keeps a routed path resolving synchronously, but a
804
+ // holder that only ever peeked would then pin a route that has already been retracted
805
+ // until it happened to read again. Following the route as well retires it promptly,
806
+ // and the memo makes the two paths agree: whichever runs first does the swap.
807
+ const unsubscribe = route.subscribe(own);
808
+ // Only meaningful while nothing is routed, so it reads the route rather than `active`:
809
+ // the two cannot disagree, since a routed path always has an answerer-independent
810
+ // answer.
811
+ const unroutable = new Derived([route, this.#state.answerers], (front, answerers) => !front && answerers === 0);
812
+ return makeRequesting(path, active, unroutable, () => {
813
+ // Releases this request's handle; the route itself belongs to the table.
814
+ released = true;
815
+ unsubscribeDiscovery();
816
+ unsubscribe();
817
+ handle?.close();
818
+ handle = undefined;
819
+ source = undefined;
820
+ taken.count -= 1;
821
+ if (blind)
822
+ taken.blind -= 1;
823
+ this.#state.requests.mutate(() => { });
824
+ if (taken.count > 0)
825
+ return;
826
+ // Defer the teardown a microtask: an effect whose rerun was triggered by the
827
+ // answer resolving closes its old request and takes a new one in the same tick,
828
+ // and tearing down in between would drop the answer it is about to read.
829
+ queueMicrotask(() => {
830
+ if (taken.count > 0)
831
+ return;
832
+ this.#state.requests.mutate((map) => {
833
+ if (map?.get(path) === taken)
834
+ map.delete(path);
835
+ });
836
+ taken.answer?.close();
837
+ taken.answer = undefined;
838
+ taken.route.set(undefined);
839
+ this.#state.releaseMaterialized(path);
840
+ });
841
+ });
842
+ }
843
+ /**
844
+ * The announced routes matching `scope`, as a live stream: every currently advertised
845
+ * route arrives first as active, then additions and retractions as they happen.
846
+ * Any pattern is accepted. A local broadcast appears when it is created;
847
+ * {@link broadcast.Producer.announce} only forwards it to peers. A dynamic or
848
+ * received route announces the prefix it covers when its subtree overlaps the scope. The
849
+ * stream ends when the origin closes or the consumer is closed.
850
+ */
851
+ announced(scope = Path.Pattern.all()) {
852
+ const producer = new announce.Producer();
853
+ void this.#runAnnounced(producer, scope);
854
+ return producer.consume();
855
+ }
856
+ async #runAnnounced(producer, scope) {
857
+ // Keyed by the presented path (from the origin, not the scope), valued by identity
858
+ // plus route. Diffing identity rather than mere presence means a republish emits a
859
+ // retraction then a fresh announcement; a re-price of the same identity emits an
860
+ // update.
861
+ let active = new Map();
862
+ try {
863
+ for (;;) {
864
+ const local = this.#state.local.peek();
865
+ const advertisedLocal = this.#state.advertisedLocal.peek();
866
+ const routes = this.#state.routes.peek();
867
+ if (local === undefined && advertisedLocal === undefined && routes === undefined)
868
+ break;
869
+ const next = new Map();
870
+ // Routes first, so an advertised local at the same path overwrites it: the
871
+ // announcement points at whatever request() would resolve. A route remains
872
+ // the prefix it advertised; the pattern is a local filter, not a new claim.
873
+ for (const [covered, entries] of routes ?? []) {
874
+ const entry = entries[0];
875
+ if (!entry)
876
+ continue;
877
+ if (!scopeOverlaps(scope, covered))
878
+ continue;
879
+ const snap = {
880
+ identity: entry.identity,
881
+ route: entry.route.peek(),
882
+ captures: scopeCaptures(scope, covered),
883
+ };
884
+ next.set(covered, snap);
885
+ }
886
+ for (const [path, front] of local ?? []) {
887
+ const route = advertisedLocal?.get(path) ?? Route.default;
888
+ if (scope.matches(path))
889
+ next.set(path, { identity: front, route, captures: scopeCaptures(scope, path) });
890
+ }
891
+ for (const [path, snap] of active) {
892
+ const cur = next.get(path);
893
+ if (!cur || cur.identity !== snap.identity)
894
+ producer.append({
895
+ prefix: path,
896
+ captures: snap.captures,
897
+ kind: "retracted",
898
+ route: snap.route,
899
+ });
900
+ }
901
+ for (const [path, snap] of next) {
902
+ const prev = active.get(path);
903
+ if (!prev || prev.identity !== snap.identity) {
904
+ producer.append({
905
+ prefix: path,
906
+ captures: snap.captures,
907
+ kind: "announced",
908
+ route: snap.route,
909
+ });
910
+ }
911
+ else if (!routesEqual(prev.route, snap.route)) {
912
+ producer.append({ prefix: path, captures: snap.captures, kind: "updated", route: snap.route });
913
+ }
914
+ }
915
+ active = next;
916
+ await Signal.race(this.#state.local, this.#state.advertisedLocal, this.#state.routes, producer.closed);
917
+ if (producer.closed.peek() !== undefined)
918
+ return;
919
+ }
920
+ }
921
+ catch {
922
+ // The reader closed between the check and an append; nothing left to do.
923
+ }
924
+ producer.close();
925
+ }
926
+ /**
927
+ * The local table, borrowed by the wire publishers to answer subscribes.
928
+ *
929
+ * Deliberately excludes received routes: a session never re-announces what a peer
930
+ * told it, so an origin wired to both directions of a connection cannot echo.
931
+ * Borrowed, not owned: do not close the fronts. Undefined once the origin closes.
932
+ *
933
+ * @internal
934
+ */
935
+ /**
936
+ * Originated advertisements a session should forward: exact-path announces plus
937
+ * originated dynamics. Undefined once the origin closes.
938
+ *
939
+ * @internal
940
+ */
941
+ /**
942
+ * Resolve `path` for serving: a local broadcast, or wait for an originated dynamic
943
+ * to accept it. Undefined when nothing here can serve the path.
944
+ *
945
+ * @internal
946
+ */
947
+ async #demand(path) {
948
+ const local = this.#state.local.peek()?.get(path);
949
+ if (local)
950
+ return local;
951
+ const entry = this.#state.bestEntry(path);
952
+ if (!entry?.originated || !entry.server)
953
+ return undefined;
954
+ const server = entry.server;
955
+ const live = server.served.get(path);
956
+ if (live && live.closed.peek() === undefined)
957
+ return live;
958
+ server.enqueue(path);
959
+ server.demanding.set(path, (server.demanding.get(path) ?? 0) + 1);
960
+ try {
961
+ for (;;) {
962
+ const served = server.served.get(path);
963
+ if (served && served.closed.peek() === undefined)
964
+ return served;
965
+ const rejected = server.rejected.get(path);
966
+ if (rejected) {
967
+ server.rejected.delete(path);
968
+ throw rejected;
969
+ }
970
+ const closed = server.closed.peek();
971
+ if (closed !== undefined) {
972
+ if (closed)
973
+ throw closed;
974
+ return undefined;
975
+ }
976
+ if (!server.pending.has(path))
977
+ return undefined;
978
+ await Signal.race(server.settled, server.closed);
979
+ }
980
+ }
981
+ finally {
982
+ const n = (server.demanding.get(path) ?? 1) - 1;
983
+ if (n <= 0)
984
+ server.demanding.delete(path);
985
+ else
986
+ server.demanding.set(path, n);
987
+ }
988
+ }
989
+ }
32
990
  /**
33
- * Maximum length of a hop chain. Must match `MAX_HOPS` in Rust's `model/origin.rs`.
991
+ * A served route from {@link Producer.dynamic}: advertises a prefix and answers the
992
+ * requests beneath it.
993
+ *
994
+ * Drop it (or {@link close}) to retract the route and reject anything still waiting
995
+ * with {@link StreamCode.NoCapacity}. {@link update} re-prices it in place.
34
996
  *
35
- * Broadcasts with longer chains are rejected, which bounds loop detection and rejects
36
- * pathological announcements across clusters with unbounded forwarding.
997
+ * @public
37
998
  */
38
- export const MAX_HOPS = 32;
999
+ export class Dynamic {
1000
+ /** The prefix this handle advertises. */
1001
+ prefix;
1002
+ #entry;
1003
+ #state;
1004
+ #retract;
1005
+ #closed = false;
1006
+ constructor(prefix, entry, state, retract) {
1007
+ this.prefix = prefix;
1008
+ this.#entry = entry;
1009
+ this.#state = state;
1010
+ this.#retract = retract;
1011
+ }
1012
+ static {
1013
+ makeDynamic = (prefix, entry, state, retract) => new Dynamic(prefix, entry, state, retract);
1014
+ }
1015
+ /** Re-price the route in place. The prefix is fixed at announce time. */
1016
+ update(route) {
1017
+ if (this.#closed)
1018
+ throw new Error("dynamic is closed");
1019
+ this.#entry.route.set(Route.normalize(route));
1020
+ this.#state.rebuildOriginated();
1021
+ this.#state.refreshPrefix(this.prefix);
1022
+ this.#state.routes.mutate(() => { });
1023
+ }
1024
+ /** Retract the route and reject anything still waiting. Idempotent. */
1025
+ close() {
1026
+ if (this.#closed)
1027
+ return;
1028
+ this.#closed = true;
1029
+ this.#retract();
1030
+ }
1031
+ /** Requests under this prefix, as they arrive, each to {@link Request.accept} or reject. */
1032
+ async *requested() {
1033
+ const server = this.#entry.server;
1034
+ if (!server)
1035
+ return;
1036
+ let current;
1037
+ const drop = () => {
1038
+ current?.reject(noCapacity());
1039
+ current = undefined;
1040
+ };
1041
+ try {
1042
+ for (;;) {
1043
+ const next = server.queue.peek()[0];
1044
+ if (next) {
1045
+ drop();
1046
+ server.queue.mutate((queue) => {
1047
+ queue.shift();
1048
+ });
1049
+ current = next;
1050
+ yield next;
1051
+ continue;
1052
+ }
1053
+ if (server.closed.peek() !== undefined)
1054
+ return;
1055
+ await Signal.race(server.queue, server.closed);
1056
+ }
1057
+ }
1058
+ finally {
1059
+ drop();
1060
+ }
1061
+ }
1062
+ }
39
1063
  /**
40
- * Generate a fresh origin with a random non-zero id.
1064
+ * A pending request for a broadcast to be served on demand.
41
1065
  *
42
- * `crypto.getRandomValues` is overkill for best-effort loop detection, but
43
- * used for slightly better distribution than `Math.random` at negligible cost.
1066
+ * Yielded by {@link Dynamic.requested}. {@link accept} resolves it with a live
1067
+ * broadcast; {@link reject} resolves it with an error. Advancing the iterator or
1068
+ * closing it without either rejects the request.
44
1069
  *
45
- * TEMPORARY: the wire format allows 62 bits, but older `@moq/lite` JS clients
46
- * decode `AnnounceInterest.exclude_hop` as a u53 (number) and throw on anything
47
- * > 2^53-1. To keep those clients alive against fresh peers, we cap the random
48
- * id at 53 bits. Restore to 62 bits once the u62 fix has propagated to deployed
49
- * bundles. Mirrors `Origin::random` in rs/moq-net.
1070
+ * @public
50
1071
  */
51
- export function randomOrigin() {
52
- const buf = new BigUint64Array(1);
53
- crypto.getRandomValues(buf);
54
- // Mask to 53 bits.
55
- const raw = buf[0] & 0x1fffffffffffffn;
56
- // Guard against the (astronomically unlikely) zero draw.
57
- return OriginSchema.parse(raw === 0n ? 1n : raw);
1072
+ export class Request {
1073
+ /** The path that was requested. */
1074
+ path;
1075
+ #server;
1076
+ #done = false;
1077
+ constructor(path, server) {
1078
+ this.path = path;
1079
+ this.#server = server;
1080
+ }
1081
+ static {
1082
+ makeRequest = (path, server) => new Request(path, server);
1083
+ finishRequest = (request, err) => {
1084
+ request.#done = true;
1085
+ void err;
1086
+ };
1087
+ }
1088
+ /**
1089
+ * Accept the request, resolving every awaiting requester with `broadcast`.
1090
+ *
1091
+ * The caller keeps producing into `broadcast`; repeat requests for the path share
1092
+ * it for as long as it stays live.
1093
+ */
1094
+ accept(source) {
1095
+ if (this.#done)
1096
+ return;
1097
+ this.#done = true;
1098
+ const front = source instanceof broadcast.Producer ? source.consume() : source;
1099
+ this.#server.accept(this, front);
1100
+ }
1101
+ /** Reject the request, resolving every awaiting requester with `err`. */
1102
+ reject(err) {
1103
+ if (this.#done)
1104
+ return;
1105
+ this.#done = true;
1106
+ this.#server.reject(this, err);
1107
+ }
58
1108
  }
59
1109
  //# sourceMappingURL=origin.js.map