@synapse-sdk/client 0.1.0 → 0.3.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.
@@ -0,0 +1,745 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // One MoQ session to the broker (WP §2, §8.2, §10): the link that comes and goes. A `Session` is
10
+ // one admitted connection (hello received) and everything learned on it — the hello, the role the
11
+ // runtime's notices grant, the catalogs, the project state, the offsets table, the clock estimate —
12
+ // its `req` track and the calls pending on it, and its own tasks (the `res` demux, four snapshot
13
+ // watchers, the clock probe), which write only into it. A task that loses its track records why and
14
+ // closes the connection, nothing else: the node's loop (`node.ts`) sees the close and does the rest.
15
+ import * as Moq from "@moq/net";
16
+ import { ADMISSION_REFUSED_CLOSE_CODE, ClockSync, FLAGS, STREAM_GROUP_SPAN_MS, STREAM_SUBSCRIBE_MAX_AGE_MS, SynapseError, TYPES, decode as decodeBody, decodeHeader, frame, headerLength, helloPath, identityQuery, isClientType, isRole, moqPriority, normalizeProjectSnapshot, normalizeServicesSnapshot, normalizeTimeOffsets, normalizeTopicsSnapshot, nowUs, parseSessionPath, rpcPath, toHex, } from "@synapse-sdk/core";
17
+ import { moqLogScope } from "./moq_log.js";
18
+ import { Cell, deferred, withTimeout, TIMEOUT } from "./util.js";
19
+ // ------------------------------------------------------------------------------ moq plumbing
20
+ /** Default datagram budget (WP §6.2): Chrome reports `maxDatagramSize` 1024; native quinn hops allow about 1150. */
21
+ export function defaultMaxDatagram() { return isNodeLike() ? 1150 : 1024; }
22
+ export function isNodeLike() { return typeof globalThis.process?.versions?.node === "string"; }
23
+ /** A `stream` reader never abandons a finished group: an effectively infinite moq latency budget (`u32::MAX` ms, as the Rust client). */
24
+ export const STREAM_READER_MAX_AGE_MS = 0xffff_ffff;
25
+ export const streamSubscription = (priority) => ({ priority, maxAge: Moq.Time.Milli(STREAM_READER_MAX_AGE_MS) });
26
+ /** The latest-value subscription (snapshot tracks, `desc`, `card`): newest group only. */
27
+ export const latestSubscription = (priority, maxAgeMs = 0) => ({ priority, maxAge: Moq.Time.Milli(maxAgeMs) });
28
+ /**
29
+ * The age budget of a call track's group (Rust `CALL_GROUP_MAX_AGE`, 60 s): the retention every call
30
+ * track we write (`req`, `out`) declares, the budget its readers (`res`, `calls`) subscribe with, and how
31
+ * long a reader waits for the group due while a later group is held.
32
+ */
33
+ export const CALL_GROUP_MAX_AGE_MS = 60_000;
34
+ export const callTrackInfo = (priority) => ({ priority, maxAge: Moq.Time.Milli(CALL_GROUP_MAX_AGE_MS) });
35
+ /** A call track reader's subscription (`res`, `calls`): the call track budget. */
36
+ export const callTrackSubscription = (priority) => ({ priority, maxAge: Moq.Time.Milli(CALL_GROUP_MAX_AGE_MS) });
37
+ /**
38
+ * Retention of a one-frame track (`card`, `desc`): the frame lives as long as the track. The Rust moq
39
+ * keeps a track's latest group for the track's life; the JS one prunes it after its default 5 s, so a
40
+ * subscriber joining later would get nothing.
41
+ */
42
+ export const RETAINED_FRAME_MAX_AGE_MS = 0xffff_ffff;
43
+ /** A call track starts a new group after this many frames (moq's cap on a group). */
44
+ export const CALL_GROUP_FRAMES = 8192;
45
+ /** A `stream` topic subscriber's age budget (`STREAM_SUBSCRIBE_MAX_AGE`, 3 × the group span): a reader further behind skips whole groups. */
46
+ export const streamTopicSubscription = (priority) => ({ priority, maxAge: Moq.Time.Milli(STREAM_SUBSCRIBE_MAX_AGE_MS) });
47
+ /** moq's caps on one group. */
48
+ const MAX_GROUP_FRAMES = 8192;
49
+ const MAX_GROUP_BYTES = 32 * 1024 * 1024;
50
+ /**
51
+ * A `stream` topic's writer (WP §6, the Rust `TrackWriter`): frames go into one MoQ group at a time, in
52
+ * order; the writer finishes the open group and starts the next when the open one is older than
53
+ * `STREAM_GROUP_SPAN_MS`, or when the next frame would pass moq's caps. A late joiner reads from the
54
+ * start of the group the relay holds, so it is at most one span behind.
55
+ */
56
+ export class StreamWriter {
57
+ track;
58
+ #group;
59
+ #openedMs = 0;
60
+ #frames = 0;
61
+ #bytes = 0;
62
+ constructor(track) {
63
+ this.track = track;
64
+ }
65
+ write(header, body) {
66
+ const payload = frame(header, body);
67
+ const now = performance.now();
68
+ if (!this.#group || now - this.#openedMs >= STREAM_GROUP_SPAN_MS || this.#frames + 1 > MAX_GROUP_FRAMES || this.#bytes + payload.length > MAX_GROUP_BYTES) {
69
+ this.#group?.close();
70
+ this.#group = this.track.appendGroup();
71
+ this.#openedMs = now;
72
+ this.#frames = 0;
73
+ this.#bytes = 0;
74
+ }
75
+ this.#group.writeFrame({ timestamp: moqTimestamp(header.tUs), payload });
76
+ this.#frames++;
77
+ this.#bytes += payload.length;
78
+ }
79
+ close() { try {
80
+ this.#group?.close();
81
+ }
82
+ catch { /* closed */ } try {
83
+ this.track.close();
84
+ }
85
+ catch { /* closed */ } }
86
+ }
87
+ export function moqTimestamp(tUs) {
88
+ const n = typeof tUs === "bigint" ? Number(tUs) : tUs;
89
+ return Moq.Time.Timestamp.fromMicros(n > 0 ? n : 0);
90
+ }
91
+ /** The error for a frame refused because it is over moq's 32 MiB limit (Rust `frame_too_large`): `invalid_input`, naming the limit. */
92
+ export function frameTooLarge(what, len) {
93
+ return new SynapseError("invalid_input", { message: `${what}: ${len} bytes exceeds the frame limit`, source: "sdk" });
94
+ }
95
+ /**
96
+ * A call track writer (`req`, `out`): frames into one group after another. The open group is finished
97
+ * and the next one started when the next frame would pass `CALL_GROUP_FRAMES` frames or moq's 32 MiB of
98
+ * bytes in the group. A frame over 32 MiB on its own is refused (`frameTooLarge`) before anything is written.
99
+ */
100
+ export class CallWriter {
101
+ track;
102
+ #group;
103
+ #inGroup = 0;
104
+ /** Bytes in the open group (moq's own count: frame payloads). */
105
+ #bytes = 0;
106
+ constructor(track) {
107
+ this.track = track;
108
+ this.#group = track.appendGroup();
109
+ }
110
+ static create(bc, name) { return new CallWriter(bc.createTrack(name, callTrackInfo(moqPriority(0)))); }
111
+ write(header, body) {
112
+ // The frame's size (header + body), as moq counts it; `seq` is a fixed-width field, so it does not change it.
113
+ const size = headerLength(header) + body.length;
114
+ if (size > MAX_GROUP_BYTES)
115
+ throw frameTooLarge("frame", body.length);
116
+ if (this.#inGroup + 1 > CALL_GROUP_FRAMES || this.#bytes + size > MAX_GROUP_BYTES) {
117
+ const next = this.track.appendGroup();
118
+ const done = this.#group;
119
+ this.#group = next;
120
+ done.close();
121
+ this.#inGroup = 0;
122
+ this.#bytes = 0;
123
+ }
124
+ // The frame's `seq` is its index within its group (Rust `CallWriter::write`).
125
+ const payload = frame({ ...header, seq: this.#inGroup }, body);
126
+ this.#group.writeFrame({ timestamp: moqTimestamp(header.tUs), payload });
127
+ this.#inGroup++;
128
+ this.#bytes += payload.length;
129
+ }
130
+ close() { try {
131
+ this.#group.close();
132
+ }
133
+ catch { /* closed */ } try {
134
+ this.track.close();
135
+ }
136
+ catch { /* closed */ } }
137
+ }
138
+ /** One latest-value frame (`desc`, `card`, a snapshot): its own group, one frame, closed; the relay caches the newest. */
139
+ export function writeLatest(track, header, body) {
140
+ const g = track.appendGroup();
141
+ g.writeFrame({ timestamp: moqTimestamp(header.tUs), payload: frame(header, body) });
142
+ g.close();
143
+ }
144
+ /** Waits for a requested broadcast to become routable. */
145
+ export async function waitActive(req, timeoutMs, signal) {
146
+ const t0 = performance.now();
147
+ for (;;) {
148
+ const a = req.active.peek();
149
+ if (a)
150
+ return a;
151
+ if (signal?.aborted)
152
+ throw signal.reason instanceof Error ? signal.reason : new SynapseError("canceled", "aborted");
153
+ const left = timeoutMs - (performance.now() - t0);
154
+ if (left <= 0)
155
+ throw new SynapseError("connection_lost", `broadcast ${req.path} never appeared`);
156
+ const r = await withTimeout(Promise.race([req.active.changed(), signal ? new Promise(res => signal.addEventListener("abort", () => res(undefined), { once: true })) : new Promise(() => { })]), Math.min(left, 250));
157
+ if (r === TIMEOUT)
158
+ continue;
159
+ }
160
+ }
161
+ /**
162
+ * Reads a call track (`res`, `calls`, a FEC `report`) frame by frame, as the Rust `read_call_track`:
163
+ * groups are taken strictly in sequence from group 0, group k read to its end before group k+1. A
164
+ * group that arrives before its turn is held (a track's groups travel on streams of their own, so
165
+ * group 1 can arrive before group 0). The read ends with an error when a group older than the one due
166
+ * arrives, when a group's read fails (reset or expired), when the subscription fails, or when the
167
+ * group due has not arrived within `CALL_GROUP_MAX_AGE_MS` while a later group is held (that wait
168
+ * is armed only then; with nothing later held the reader waits for the next group with no timer).
169
+ * Returns `null` when the track ended cleanly or `signal` aborted, otherwise the error.
170
+ */
171
+ export async function readTrack(sub, onFrame, signal) {
172
+ const abort = () => sub.close();
173
+ signal?.addEventListener("abort", abort, { once: true });
174
+ const held = new Map();
175
+ let next = 0;
176
+ // When the group due must have arrived: set while a later group is held, cleared when it comes.
177
+ let deadline;
178
+ try {
179
+ for (;;) {
180
+ let g = held.get(next);
181
+ if (g)
182
+ held.delete(next);
183
+ else {
184
+ let got;
185
+ if (held.size === 0)
186
+ got = await sub.recvGroup();
187
+ else {
188
+ deadline ??= performance.now() + CALL_GROUP_MAX_AGE_MS;
189
+ const r = await withTimeout(sub.recvGroup(), Math.max(0, deadline - performance.now()));
190
+ if (r === TIMEOUT)
191
+ return new Error(`group ${next} did not arrive within the age budget while later groups did`);
192
+ got = r;
193
+ }
194
+ if (!got)
195
+ return null;
196
+ if (got.sequence > next) {
197
+ held.set(got.sequence, got);
198
+ continue;
199
+ }
200
+ if (got.sequence < next)
201
+ return new Error(`group ${got.sequence} arrived where group ${next} was due`);
202
+ g = got;
203
+ }
204
+ deadline = undefined;
205
+ for (;;) {
206
+ if (signal?.aborted)
207
+ return null;
208
+ const f = await g.readFrame();
209
+ if (!f)
210
+ break;
211
+ const r = onFrame(f.payload);
212
+ if (r)
213
+ await r;
214
+ }
215
+ next++;
216
+ }
217
+ }
218
+ catch (e) {
219
+ return e;
220
+ }
221
+ finally {
222
+ signal?.removeEventListener("abort", abort);
223
+ for (const g of held.values()) {
224
+ try {
225
+ g.close();
226
+ }
227
+ catch { /* closed */ }
228
+ }
229
+ }
230
+ }
231
+ /**
232
+ * Reads a latest-value track (a snapshot) as the Rust `watch_snapshots`: each group as it arrives,
233
+ * its first frame handed to `apply`. Returns `null` when `signal` aborted, otherwise why the track
234
+ * was lost (the subscription failed or ended).
235
+ */
236
+ async function readLatest(sub, apply, signal) {
237
+ const abort = () => sub.close();
238
+ signal.addEventListener("abort", abort, { once: true });
239
+ try {
240
+ for (;;) {
241
+ const g = await sub.recvGroup();
242
+ if (signal.aborted)
243
+ return null;
244
+ if (!g)
245
+ return new Error("track ended");
246
+ let f;
247
+ try {
248
+ f = await g.readFrame();
249
+ }
250
+ catch {
251
+ f = undefined;
252
+ }
253
+ if (f)
254
+ apply(f.payload);
255
+ }
256
+ }
257
+ catch (e) {
258
+ return e;
259
+ }
260
+ finally {
261
+ signal.removeEventListener("abort", abort);
262
+ }
263
+ }
264
+ export async function readDatagrams(sub, onDatagram, signal) {
265
+ const abort = () => sub.close();
266
+ signal?.addEventListener("abort", abort, { once: true });
267
+ try {
268
+ for (;;) {
269
+ const d = await sub.recvDatagram();
270
+ if (!d)
271
+ return null;
272
+ const r = onDatagram(d.payload);
273
+ if (r)
274
+ await r;
275
+ }
276
+ }
277
+ catch (e) {
278
+ return e;
279
+ }
280
+ finally {
281
+ signal?.removeEventListener("abort", abort);
282
+ }
283
+ }
284
+ let polyfillInstalled;
285
+ /** Installs `@moq/web-transport` in Bun/Node when the runtime has no WebTransport. Browsers skip this. */
286
+ export function ensureWebTransport() {
287
+ if (typeof globalThis.WebTransport !== "undefined")
288
+ return Promise.resolve();
289
+ if (!isNodeLike())
290
+ return Promise.resolve();
291
+ polyfillInstalled ??= (async () => {
292
+ const spec = "@moq/web-transport";
293
+ try {
294
+ const m = (await import(__rewriteRelativeImportExtension(/* @vite-ignore */ spec)));
295
+ m.install();
296
+ }
297
+ catch (e) {
298
+ throw new SynapseError("not_supported", { message: `WebTransport is unavailable and @moq/web-transport could not be loaded: ${e instanceof Error ? e.message : String(e)}`, cause: e });
299
+ }
300
+ })();
301
+ return polyfillInstalled;
302
+ }
303
+ /** A connect failure's text (`@moq/net` races WebTransport against WebSocket and rejects with an `AggregateError`). */
304
+ export function describeError(e) {
305
+ if (e instanceof AggregateError) {
306
+ const parts = e.errors.map(describeError).filter(Boolean);
307
+ return parts.length ? parts.join("; ") : e.message || e.name;
308
+ }
309
+ return e instanceof Error ? e.message || e.name : String(e);
310
+ }
311
+ /** The MoQ session-close code the broker's refusal arrives as: application codes sit at 64 + code on the wire. */
312
+ const ADMISSION_REFUSED_SESSION_CODE = 64 + ADMISSION_REFUSED_CLOSE_CODE;
313
+ const ADMISSION_REFUSED_REASON = new RegExp(`app code=${ADMISSION_REFUSED_CLOSE_CODE}(?!\\d)`);
314
+ /**
315
+ * The error of a session's close (`classify_close`): `admission_refused` travels as the application
316
+ * close code (retryable: a live session may hold this name, the project may be settling), another
317
+ * application code is a broker-side failure, `unauthorized` is the relay's own refusal, everything
318
+ * else is the transport (`connection_lost`); a clean close is a drop too (in one-shot mode a broker
319
+ * GOAWAY looks like one).
320
+ */
321
+ export function closeError(err) {
322
+ if (!err)
323
+ return new SynapseError("connection_lost", { message: "session closed by the broker", source: "transport" });
324
+ const text = `${err.message} ${err.reason ?? ""}`;
325
+ if ((err instanceof Moq.Error.Session && err.code === ADMISSION_REFUSED_SESSION_CODE) || ADMISSION_REFUSED_REASON.test(text)) {
326
+ return new SynapseError("admission_refused", { message: "the runtime refused this connection, retryable: a live session may hold this name, the project may be settling, or the runtime is overloaded; retry with backoff", source: "broker", cause: err });
327
+ }
328
+ if (err instanceof Moq.Error.Session && err.code === Moq.SessionCode.Unauthorized)
329
+ return new SynapseError("unauthorized", { message: text.trim(), source: "broker", cause: err });
330
+ const t = text.toLowerCase();
331
+ if (t.includes("unauthorized"))
332
+ return new SynapseError("unauthorized", { message: text.trim(), source: "broker", cause: err });
333
+ return new SynapseError("connection_lost", { message: text.trim() || err.name, source: "transport", cause: err });
334
+ }
335
+ /** `https://host:port/<root>` → `http://host:port/certificate.sha256`, the broker's plain-HTTP helper. */
336
+ export function brokerCertHelperUrl(brokerUrl) { const u = new URL(brokerUrl); return `http://${u.host}/certificate.sha256`; }
337
+ const SHA256_HEX = /^[0-9a-f]{64}$/i;
338
+ /** The certificate pin when the caller gave none (SDK §13): `SYNAPSE_BROKER_CERT_SHA256` (Bun/Node), then the helper, then `undefined` = unpinned. Per attempt. */
339
+ export async function discoverBrokerCertSha256(brokerUrl, opts = {}) {
340
+ const env = globalThis.process?.env?.SYNAPSE_BROKER_CERT_SHA256?.trim();
341
+ if (env)
342
+ return env;
343
+ const signal = opts.signal ? AbortSignal.any([opts.signal, AbortSignal.timeout(opts.timeoutMs ?? 2000)]) : AbortSignal.timeout(opts.timeoutMs ?? 2000);
344
+ try {
345
+ const res = await fetch(brokerCertHelperUrl(brokerUrl), { signal });
346
+ if (!res.ok)
347
+ return undefined;
348
+ const text = (await res.text()).trim();
349
+ return SHA256_HEX.test(text) ? text : undefined;
350
+ }
351
+ catch {
352
+ return undefined;
353
+ }
354
+ }
355
+ /** The key of a call in the session's pending map. */
356
+ export const callKey = (id) => toHex(id);
357
+ export class Session {
358
+ url;
359
+ conn;
360
+ pub;
361
+ sub;
362
+ hello;
363
+ maxDatagram;
364
+ log;
365
+ /** Counts *established* sessions of the node (SDK §2); set by the node when attached. */
366
+ epoch = 0;
367
+ startedMs = performance.now();
368
+ transport;
369
+ /** Datagrams travel only over WebTransport; the WebSocket fallback is stream-only. */
370
+ datagrams;
371
+ #role;
372
+ #admitting = true;
373
+ #req;
374
+ #calls = new Map();
375
+ #closing;
376
+ /** The views this session reads (latest values). */
377
+ topics = new Cell({ topics: {} });
378
+ services = new Cell({ services: {} });
379
+ timeOffsets = new Cell({});
380
+ project = new Cell(undefined);
381
+ clock;
382
+ /** Where notices go: the node's loop sets this at attach. */
383
+ onNotice;
384
+ #tasks = new AbortController();
385
+ #taskDone = [];
386
+ /** Settles with the close's error once the connection closed. */
387
+ closed;
388
+ constructor(url, conn, pub, sub, hello, maxDatagram, log, reqBc, res, resSub, dom) {
389
+ this.url = url;
390
+ this.conn = conn;
391
+ this.pub = pub;
392
+ this.sub = sub;
393
+ this.hello = hello;
394
+ this.maxDatagram = maxDatagram;
395
+ this.log = log;
396
+ this.#reqBc = reqBc;
397
+ this.#role = hello.role;
398
+ this.transport = conn.transport;
399
+ this.datagrams = conn.transport === "webtransport";
400
+ this.#req = CallWriter.create(reqBc, "req");
401
+ this.clock = new Cell(new ClockSync(dom, hello.dom, 0).info());
402
+ this.closed = conn.closed.then(err => { log.release(); return err; });
403
+ this.#resSub = resSub;
404
+ this.#res = res;
405
+ }
406
+ #reqBc;
407
+ #resSub;
408
+ #res;
409
+ get prefix() { return this.hello.prefix; }
410
+ get role() { return this.#role; }
411
+ nowUs() { return nowUs(); }
412
+ /** Whether the session still takes requests (not torn down). */
413
+ get isLive() { return this.#admitting; }
414
+ /** The broker's reason, when it closed this session with a closing notice (or a watcher lost its track). */
415
+ get closingReason() { return this.#closing; }
416
+ /** Appends a frame to our `req` track (WP §8.6). `connection_lost` once the session has ended. */
417
+ writeReq(header, body) {
418
+ if (!this.#admitting)
419
+ throw new SynapseError("connection_lost", { message: "the session has ended", source: "sdk" });
420
+ try {
421
+ this.#req.write(header, body);
422
+ }
423
+ catch (e) {
424
+ throw reqWriteError(e, "req frame", body.length);
425
+ }
426
+ }
427
+ /** Writes call `id`'s request and registers where its frames go, both while the session takes requests. */
428
+ /** `deliver(null)` = the session ended with the call pending. */
429
+ writeCall(header, body, id, deliver) {
430
+ if (!this.#admitting)
431
+ throw new SynapseError("connection_lost", { message: "the session has ended", source: "sdk" });
432
+ const k = callKey(id);
433
+ this.#calls.set(k, deliver);
434
+ try {
435
+ this.#req.write(header, body);
436
+ }
437
+ catch (e) {
438
+ this.#calls.delete(k);
439
+ throw reqWriteError(e, "call request", body.length);
440
+ }
441
+ }
442
+ forgetCall(id) { this.#calls.delete(callKey(id)); }
443
+ /** A frame for call `id`; its terminal frame forgets the call. */
444
+ #deliver(id, f) {
445
+ const k = callKey(id);
446
+ const d = this.#calls.get(k);
447
+ if (f.header.flags & FLAGS.END)
448
+ this.#calls.delete(k);
449
+ d?.(f);
450
+ }
451
+ /** Stops taking requests and fails every call pending here (`deliver(null)`: `connection_lost`). The first step of a teardown; idempotent. */
452
+ endCalls() {
453
+ this.#admitting = false;
454
+ const calls = [...this.#calls.values()];
455
+ this.#calls.clear();
456
+ for (const d of calls)
457
+ d(null);
458
+ }
459
+ /** A task of this session lost what it reads, or the broker announced the close: record `reason` (the first stands) and close the connection. The loop does the rest. */
460
+ lost(reason) {
461
+ this.#closing ??= reason;
462
+ try {
463
+ this.conn.close();
464
+ }
465
+ catch { /* closed */ }
466
+ }
467
+ /** Starts the session's tasks: the `res` demux, the four snapshot watchers, the clock probe (unless the broker shares our domain). Each writes only into this session. */
468
+ start(sync, startCall) {
469
+ const signal = this.#tasks.signal;
470
+ this.#taskDone.push(this.#readRes(signal));
471
+ this.#taskDone.push(this.#watch("runtime/topics", "catalog", signal, b => this.topics.set(normalizeTopicsSnapshot(decodeBody(b)))));
472
+ this.#taskDone.push(this.#watch("runtime/services", "catalog", signal, b => this.services.set(normalizeServicesSnapshot(decodeBody(b)))));
473
+ this.#taskDone.push(this.#watch("runtime/time", "offsets", signal, b => this.timeOffsets.set(normalizeTimeOffsets(decodeBody(b)))));
474
+ this.#taskDone.push(this.#watch("runtime/project", "state", signal, b => this.project.set(normalizeProjectSnapshot(decodeBody(b)))));
475
+ if (!sync.sameDom)
476
+ this.#taskDone.push(this.#clockTask(sync, startCall, signal));
477
+ }
478
+ /** The `res` track (WP §8.6): a call's frame to its call; a notice to the loop; a closing notice closes the session; a broken track closes it too. */
479
+ async #readRes(signal) {
480
+ const onFrame = (payload) => {
481
+ let header, hlen;
482
+ try {
483
+ ({ header, hlen } = decodeHeader(payload));
484
+ }
485
+ catch {
486
+ return;
487
+ }
488
+ const body = payload.subarray(hlen);
489
+ let decoded;
490
+ try {
491
+ decoded = decodeBody(body);
492
+ }
493
+ catch {
494
+ return;
495
+ }
496
+ const call = decoded?.call;
497
+ if (call instanceof Uint8Array && call.length === 16) {
498
+ this.#deliver(call, { header, body });
499
+ return;
500
+ }
501
+ if (header.flags & FLAGS.ERR) {
502
+ const b = decoded;
503
+ if (b && typeof b.code === "string")
504
+ this.onNotice?.({ kind: "error", body: b });
505
+ return;
506
+ }
507
+ const n = decoded;
508
+ if (!n || typeof n !== "object" || !("notice" in n))
509
+ return;
510
+ if (n.notice === "closing") {
511
+ this.lost(typeof n.reason === "string" ? n.reason : "closing");
512
+ return;
513
+ }
514
+ if ((n.notice === "promoted" || n.notice === "demoted") && isRole(n.role)) {
515
+ this.#role = n.role;
516
+ this.onNotice?.({ kind: "project", notice: { kind: n.notice, role: n.role, project: typeof n.project === "string" ? n.project : null } });
517
+ }
518
+ };
519
+ const err = await readTrack(this.#resSub, onFrame, signal);
520
+ if (signal.aborted || !this.#admitting)
521
+ return;
522
+ this.lost(`res track: ${err instanceof Error ? err.message : "ended"}`);
523
+ }
524
+ /** One snapshot watcher: follows `path`/`track` for the life of the session; a lost track closes the session (a view that froze would lie). */
525
+ async #watch(path, track, signal, apply) {
526
+ let why;
527
+ try {
528
+ const req = this.sub.request(Moq.Path.from(path));
529
+ const bc = await waitActive(req, 10_000, signal);
530
+ const sub = bc.track(track).subscribe(latestSubscription(moqPriority(1)));
531
+ const err = await readLatest(sub, payload => { try {
532
+ const { hlen } = decodeHeader(payload);
533
+ apply(payload.subarray(hlen));
534
+ }
535
+ catch { /* undecodable snapshot dropped */ } }, signal);
536
+ why = err instanceof Error ? err.message : "track ended";
537
+ }
538
+ catch (e) {
539
+ why = e instanceof Error ? e.message : String(e);
540
+ }
541
+ if (signal.aborted || !this.#admitting)
542
+ return;
543
+ this.lost(`${path} ${track} watcher: ${why}`);
544
+ }
545
+ /** The clock probe (WP §8.7): `synapse/time` calls on this session feeding the estimate, for the session's life. */
546
+ async #clockTask(sync, startCall, signal) {
547
+ while (!signal.aborted) {
548
+ const at = sync.nextProbeAt();
549
+ if (at === undefined)
550
+ return;
551
+ const wait = at - nowUs();
552
+ if (wait > 0) {
553
+ await new Promise(r => { const t = setTimeout(r, wait / 1000); signal.addEventListener("abort", () => { clearTimeout(t); r(); }, { once: true }); });
554
+ if (signal.aborted)
555
+ return;
556
+ }
557
+ const req = sync.request(nowUs());
558
+ let resp;
559
+ try {
560
+ resp = (await withTimeout(startCall("synapse/time", req), 2000));
561
+ if (resp === TIMEOUT) {
562
+ sync.probeLost();
563
+ continue;
564
+ }
565
+ }
566
+ catch (e) {
567
+ sync.probeLost();
568
+ if (e instanceof SynapseError && (e.code === "not_connected" || e.code === "connection_lost"))
569
+ return;
570
+ continue;
571
+ }
572
+ sync.response(resp, nowUs());
573
+ this.clock.set(sync.info());
574
+ }
575
+ }
576
+ /** Stops and awaits the tasks (bounded), then closes the session: track finished, MoQ close sent. */
577
+ async teardown(graceMs = 1000) {
578
+ this.endCalls();
579
+ this.#tasks.abort();
580
+ await withTimeout(Promise.allSettled(this.#taskDone), graceMs);
581
+ this.close();
582
+ await withTimeout(this.closed, graceMs);
583
+ }
584
+ /** The synchronous end: fail its calls, finish our track, close the connection. Idempotent. */
585
+ close() {
586
+ this.#admitting = false;
587
+ this.#tasks.abort();
588
+ this.log.closing();
589
+ try {
590
+ this.#req.close();
591
+ }
592
+ catch { /* closed */ }
593
+ try {
594
+ this.#reqBc.close();
595
+ }
596
+ catch { /* closed */ }
597
+ try {
598
+ this.#resSub.close();
599
+ }
600
+ catch { /* closed */ }
601
+ try {
602
+ this.#res.close();
603
+ }
604
+ catch { /* closed */ }
605
+ try {
606
+ this.conn.close();
607
+ }
608
+ catch { /* closed */ }
609
+ try {
610
+ this.pub.close();
611
+ }
612
+ catch { /* closed */ }
613
+ try {
614
+ this.sub.close();
615
+ }
616
+ catch { /* closed */ }
617
+ }
618
+ createBroadcast(path) { this.log.announced(path); return this.pub.createBroadcast(Moq.Path.from(path)); }
619
+ request(path) { this.log.requested(path); return this.sub.request(Moq.Path.from(path)); }
620
+ }
621
+ function certOption(hash) {
622
+ return hash ? { serverCertificateHashes: [{ algorithm: "sha-256", value: hash.trim() }] } : undefined;
623
+ }
624
+ /**
625
+ * Opens one session to `dial`: connect with our identity as query parameters (WP §3.1), wait for
626
+ * the hello on `client/<name>/hello` (readiness + grant proof + our prefix), find our `res` track at
627
+ * `runtime/rpc/<sid>`, announce our `req` track under the prefix. A refused admission shows up as
628
+ * the session closing before the hello: the close decides the error. `signal` abandons the dial: every
629
+ * wait stops at once and the half-open connection is closed (`canceled`), as the connect timeout does
630
+ * (`connection_lost`).
631
+ */
632
+ export async function openSession(knobs, dial, dom, signal) {
633
+ const name = dial.identity.name;
634
+ if (!name)
635
+ throw new SynapseError("internal", "identity without a name");
636
+ if (knobs.transport !== "websocket")
637
+ await ensureWebTransport();
638
+ const abandoned = () => new SynapseError("canceled", { message: "the dial was abandoned", source: "sdk" });
639
+ if (signal?.aborted)
640
+ throw abandoned();
641
+ const pub = new Moq.Origin.Producer();
642
+ const sub = new Moq.Origin.Producer();
643
+ const sep = dial.url.includes("?") ? "&" : "?";
644
+ const url = new URL(`${dial.url}${sep}${identityQuery(dial.identity)}${knobs.project ? `&project=${knobs.project}` : ""}`);
645
+ // One controller for both ends of a dial: the connect timeout and the caller's `signal`.
646
+ const ac = new AbortController();
647
+ const timer = setTimeout(() => ac.abort(new SynapseError("connection_lost", "connect timed out")), knobs.connectTimeoutMs);
648
+ const onAbandon = () => ac.abort(abandoned());
649
+ signal?.addEventListener("abort", onAbandon, { once: true });
650
+ // Settles (rejects) with the reason once the dial is stopped.
651
+ const stopped = new Promise((_, reject) => ac.signal.addEventListener("abort", () => reject(ac.signal.reason), { once: true }));
652
+ stopped.catch(() => { });
653
+ const log = moqLogScope();
654
+ const abandon = () => { signal?.removeEventListener("abort", onAbandon); log.closing(); log.release(); };
655
+ let conn;
656
+ try {
657
+ const props = { url, publish: pub.consume(), consume: sub, signal: ac.signal };
658
+ const wt = certOption(dial.cert);
659
+ if (wt)
660
+ props.webtransport = wt;
661
+ if (knobs.transport === "webtransport")
662
+ props.websocket = { enabled: false };
663
+ else if (knobs.transport === "websocket")
664
+ props.websocket = { enabled: true, delay: Moq.Time.Milli(0) };
665
+ conn = await Moq.Connection.connect(props);
666
+ }
667
+ catch (e) {
668
+ clearTimeout(timer);
669
+ pub.close();
670
+ sub.close();
671
+ abandon();
672
+ // Stopped (timeout or `signal`): that reason, whatever error the connect rejected with.
673
+ if (ac.signal.aborted && ac.signal.reason instanceof SynapseError)
674
+ throw ac.signal.reason;
675
+ if (e instanceof SynapseError)
676
+ throw e;
677
+ throw closeError(e instanceof Error ? e : new Error(describeError(e)));
678
+ }
679
+ try {
680
+ // The close is the single source of truth for why a pre-hello session ended, unless the dial was stopped first.
681
+ const closedEarly = Promise.race([conn.closed.then(err => { throw closeError(err); }), stopped]);
682
+ closedEarly.catch(() => { });
683
+ const helloReq = sub.request(Moq.Path.from(helloPath(name)));
684
+ log.requested(helloPath(name));
685
+ const helloBc = await Promise.race([waitActive(helloReq, knobs.connectTimeoutMs, ac.signal), closedEarly]);
686
+ const helloSub = helloBc.track("hello").subscribe(latestSubscription(moqPriority(0)));
687
+ const g = await Promise.race([withTimeout(helloSub.recvGroup(), knobs.connectTimeoutMs), closedEarly]);
688
+ if (g === TIMEOUT || !g)
689
+ throw new SynapseError("connection_lost", "no hello from the broker");
690
+ const first = await Promise.race([withTimeout(g.readFrame(), knobs.connectTimeoutMs), closedEarly]);
691
+ if (first === TIMEOUT || !first)
692
+ throw new SynapseError("connection_lost", "empty hello");
693
+ helloSub.close();
694
+ helloReq.close();
695
+ const { header, hlen } = decodeHeader(first.payload);
696
+ if (header.type !== TYPES.RPC_RESP || header.flags & FLAGS.ERR)
697
+ throw new SynapseError("invalid_input", "hello frame is not a hello");
698
+ const hello = decodeBody(first.payload.subarray(hlen));
699
+ if (!hello || hello.hello !== true || typeof hello.prefix !== "string" || !isRole(hello.role) || !isClientType(hello.type) || typeof hello.dom !== "string")
700
+ throw new SynapseError("invalid_input", "malformed hello");
701
+ const sp = parseSessionPath(rpcPath(hello.prefix));
702
+ if (!sp || sp.name !== name)
703
+ throw new SynapseError("invalid_input", `hello prefix ${hello.prefix} is not client/${name}/<sid>`);
704
+ // The broker's response track for this session.
705
+ const resPath = `runtime/rpc/${sp.sid}`;
706
+ log.requested(resPath);
707
+ const resReq = sub.request(Moq.Path.from(resPath));
708
+ const res = await Promise.race([waitActive(resReq, knobs.connectTimeoutMs, ac.signal), closedEarly]);
709
+ const resSub = res.track("res").subscribe(callTrackSubscription(moqPriority(0)));
710
+ // Our request track (WP §8.2), under the prefix the hello names: the only place we may publish.
711
+ const reqBc = pub.createBroadcast(Moq.Path.from(rpcPath(hello.prefix)));
712
+ log.announced(rpcPath(hello.prefix));
713
+ const session = new Session(dial.url, conn, pub, sub, hello, knobs.maxDatagram, log, reqBc, res, resSub, dom);
714
+ reqBc.announce();
715
+ clearTimeout(timer);
716
+ signal?.removeEventListener("abort", onAbandon);
717
+ return session;
718
+ }
719
+ catch (e) {
720
+ clearTimeout(timer);
721
+ abandon();
722
+ try {
723
+ conn.close();
724
+ }
725
+ catch { /* ignore */ }
726
+ pub.close();
727
+ sub.close();
728
+ throw e instanceof SynapseError ? e : closeError(e instanceof Error ? e : new Error(describeError(e)));
729
+ }
730
+ }
731
+ /** The error a call pending on a session that ended reports (WP §8.4: the request was written, so it may have run). */
732
+ /** `data` is `{ outcome: "unknown" }`, with `reason` when the session's close had one (Rust `outcome_unknown_data`). */
733
+ export function outcomeUnknown(closing) {
734
+ const data = { outcome: "unknown" };
735
+ if (closing !== undefined)
736
+ data.reason = closing;
737
+ return new SynapseError("connection_lost", { message: closing ? `${closing}: the session ended with the call pending; its outcome is unknown` : "the session ended with the call pending; its outcome is unknown", source: "transport", data });
738
+ }
739
+ /** A failed write on our `req` track (Rust `write_req`): an oversized frame is `invalid_input` naming `what`; anything else `connection_lost`. */
740
+ function reqWriteError(e, what, len) {
741
+ if (e instanceof SynapseError && e.code === "invalid_input")
742
+ return frameTooLarge(what, len);
743
+ return new SynapseError("connection_lost", { message: describeError(e), source: "transport", cause: e });
744
+ }
745
+ export { deferred };