@moq/net 0.3.5 → 0.4.1

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