返回源码地图

packages/chord/src/connection.ts

v1.3.0 · 71023aec1546 · 22:远程身份、调用、状态背压与hydrate

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { contractFromDescription, LOCAL_VARIANT, resolveHost } from "./contract.ts";
2import { type Encoder, encoder } from "./delta/index.ts";
3import { ChordError, invalid } from "./errors.ts";
4import type { HostImpl } from "./host.ts";
5import { type Link, Packed, unpack } from "./link.ts";
6import { type CtxImpl, RefImpl, variantOf } from "./object.ts";
7import type { RemoteBinding, RemoteChannel } from "./remote.ts";
8import { assertValid } from "./schema.ts";
9import type { Ctx, Readable, Shape, StateEvent } from "./types.ts";
10import { type Frame, fromWireError, isFrame, PROTOCOL_VERSION, type RootRef, toWireError } from "./wire.ts";
11
12export interface LinkOptions {
13 /** Milliseconds between pings (default 15000). */
14 readonly pingInterval?: number;
15 /** Close the link when nothing arrived for this long (default 45000). Everything held through it is released. */
16 readonly pingTimeout?: number;
17 /**
18 * Unacknowledged frame bytes (JSON text length) beyond which state frames wait for the peer (default 256 KiB). Only
19 * applies when both ends acknowledge frames and the link reports sizes; `Infinity` never holds state back.
20 */
21 readonly window?: number;
22 /**
23 * Bytes of state ops that may wait for the peer on this link (default 4 windows). Beyond, the oldest waiting streams
24 * are replaced by their current value (a reset), so memory stays bounded however long the peer stalls.
25 */
26 readonly pendingCap?: number;
27 /**
28 * The peer speaks another link protocol version (`peer`: undefined if it did not say): the link closes, and should
29 * not be reconnected with the same code. A browser reloads its page, for instance.
30 */
31 readonly onProtocolMismatch?: (versions: { readonly local: number; readonly peer: number | undefined }) => void;
32}
33
34const DEFAULT_WINDOW = 256 * 1024;
35/** The default cap of waiting state ops per link, in windows. */
36const PENDING_WINDOWS = 4;
37
38type StateFrame = Extract<Frame, { t: "state" }>;
39
40/**
41 * How a waiting stream recovers when its ops must be dropped: the provider resends the current value as a reset at
42 * flush; a relay (which has no value) asks downstream for one.
43 */
44type Overflow = { readonly resend: () => void } | { readonly resync: () => void };
45
46/**
47 * What waits on a link. A unit slot is lazy: the shape and snapshots are built from the current values when it is sent.
48 * A state slot keeps a snapshot, reset or error (`base`) and encoded ops to apply after it, in order (as they arrived;
49 * the receiving decoder validates them), or, once `lazy`, only the promise of a reset built at flush.
50 */
51type Slot =
52 | { readonly kind: "unit"; readonly hold: number; readonly flush: () => void }
53 | {
54 readonly kind: "state";
55 readonly hold: number;
56 readonly m: string;
57 base: StateFrame | undefined;
58 ops: (readonly unknown[])[];
59 size: number;
60 lazy: boolean;
61 readonly overflow: Overflow;
62 };
63
64export interface AcceptOptions<P = unknown> extends LinkOptions {
65 /** The principal of whatever connects, from the app's authenticator. Every request on the link acts as it. */
66 readonly principal: P;
67 /**
68 * What the peer is, decided here and never by its `hello`: `client` (default; a browser: no roots, no code versions,
69 * not a reload participant, not addressable) or `host` (a child host; needs `name`).
70 */
71 readonly kind?: "host" | "client";
72 /** A child host's name: its hello must match, and it is reachable `at` this name. */
73 readonly name?: string;
74 /** On `invalidatePrincipal`: a new principal keeps the link, `undefined` closes it (default: close). */
75 restamp?(principal: P): P | undefined;
76 /**
77 * Calls the peer may have in progress on this link (default: no limit). Further ones never run: they are answered
78 * at once with `unavailable` (reason `too_many_calls`), and the link stays open.
79 */
80 readonly maxCalls?: number;
81}
82
83export interface Peer {
84 readonly kind: "host" | "client";
85 /** Configured (downstream hosts) or announced by the trusted parent (upstream). */
86 readonly name: string | undefined;
87}
88
89/** A state member's stream to the consumer: its subscription and delta encoder. */
90interface Feed {
91 unsubscribe: () => void;
92 encoder: Encoder;
93 /** Events that arrived while a unit or reset was being built (replayed after it is sent). */
94 buffer: StateEvent<unknown>[] | undefined;
95}
96
97/** A hold the peer made on this host and serves locally. */
98interface ServedLocal {
99 readonly kind: "local";
100 readonly id: number;
101 readonly ref: RefImpl;
102 readonly principal: unknown;
103 /** The client connection it comes from (see `Frame` hold `origin`); undefined for a host's own holds. */
104 readonly origin: string | undefined;
105 /** The consumer wants state (hold without `state: false`, or `sub`). */
106 wantsState: boolean;
107 /** The consumer had values before (re-hold): its first unit waits for the window like any other. */
108 readonly again: boolean;
109 /** A unit was sent. */
110 unitSent: boolean;
111 /** The members whose snapshot the consumer has, with their streams. */
112 readonly feeds: Map<string, Feed>;
113}
114
115/** A hold the peer made on this host: served locally or relayed to another link. */
116type Served = ServedLocal | { readonly kind: "relay"; readonly relay: RelayRef };
117
118type Pending = { readonly resolve: (value: unknown) => void; readonly reject: (error: unknown) => void };
119
120const unavailable = (message: string): ChordError => new ChordError("unavailable", message);
121
122// ─── relay ───────────────────────────────────────────────────────────────────
123
124/**
125 * A hold relayed from an origin link to a downstream link. It owns everything done through it: state and calls queued
126 * while the route resolves, and the downstream twins once forwarded. `close` undoes all of it exactly once (cancels
127 * calls downstream, drops what waits for the origin, releases the downstream hold, rejects waiters).
128 */
129export class RelayRef {
130 readonly origin: Connection;
131 readonly frame: Extract<Frame, { t: "hold" }>;
132 readonly principal: unknown;
133 /** The client connection the hold comes from (forwarded downstream); undefined for a host's own holds. */
134 readonly originTag: string | undefined;
135 /** The origin's authorization generation when the hold arrived; a revocation bumps it. */
136 readonly generation: number;
137 down: Connection | undefined;
138 downId = 0;
139 closed = false;
140 /** The origin wants state (forwarded as `state: false`, `sub`, `unsub`). */
141 stateWanted: boolean;
142 /** The members of the first unit, still to forward past the origin's window. */
143 urgent: Set<string> | undefined;
144 #shaped = false;
145 /** Members whose ops this relay dropped: downstream ops are ignored until their reset arrives. */
146 readonly awaiting = new Set<string>();
147 readonly calls = new Map<number, RelayCall>();
148 readonly #waiters = new Set<Pending>();
149
150 constructor(
151 origin: Connection,
152 frame: Extract<Frame, { t: "hold" }>,
153 principal: unknown,
154 originTag: string | undefined,
155 ) {
156 this.origin = origin;
157 this.frame = frame;
158 this.principal = principal;
159 this.originTag = originTag;
160 this.stateWanted = frame.state !== false;
161 this.generation = origin.generation;
162 }
163
164 get originId(): number {
165 return this.frame.id;
166 }
167
168 get client(): boolean {
169 return this.originTag !== undefined;
170 }
171
172 /** Still authorized as it was when it arrived. */
173 get current(): boolean {
174 return !this.closed && this.origin.open && this.origin.generation === this.generation;
175 }
176
177 /** The downstream connection once the route resolved; rejects if the relay closes first. */
178 ready(): Promise<Connection> {
179 if (this.closed) return Promise.reject(new ChordError("gone", "relayed hold closed"));
180 if (this.down !== undefined) return Promise.resolve(this.down);
181 return new Promise<Connection>((resolve, reject) => {
182 this.#waiters.add({ resolve: resolve as (value: unknown) => void, reject });
183 });
184 }
185
186 /** Forwards the hold to `down`. */
187 open(down: Connection): void {
188 if (this.closed) return;
189 this.down = down;
190 this.downId = down.nextId();
191 down.relayedRefs.set(this.downId, this);
192 const { at, token, input } = this.frame;
193 down.send({
194 t: "hold",
195 id: this.downId,
196 at,
197 token,
198 input,
199 principal: this.principal,
200 ...(this.originTag === undefined ? {} : { origin: this.originTag }),
201 ...(this.stateWanted ? {} : { state: false as const }),
202 ...(this.frame.again === true ? { again: true as const } : {}),
203 });
204 for (const waiter of this.#waiters) waiter.resolve(down);
205 this.#waiters.clear();
206 }
207
208 /** The origin starts or stops the hold's state. */
209 wantState(wanted: boolean): void {
210 if (this.closed || wanted === this.stateWanted) return;
211 this.stateWanted = wanted;
212 if (!wanted) {
213 this.origin.dropHoldState(this.originId);
214 this.awaiting.clear();
215 }
216 this.down?.send({ t: wanted ? "sub" : "unsub", hold: this.downId });
217 }
218
219 /**
220 * The origin could not keep up and dropped what waited for member `m` (or asked for it again): ask downstream for a
221 * reset, and ignore its ops until the reset arrives.
222 */
223 resync(m: string): void {
224 if (this.closed) return;
225 this.awaiting.add(m);
226 this.down?.send({ t: "resync", hold: this.downId, m });
227 }
228
229 /** A shape from downstream: forwarded at once; the members of the first unit then skip the origin's window. */
230 shape(frame: Extract<Frame, { t: "shape" }>): void {
231 if (this.closed) return;
232 if (!this.#shaped) {
233 this.#shaped = true;
234 if (this.frame.again !== true) this.urgent = new Set(frame.state);
235 }
236 this.origin.send({ ...frame, id: this.originId });
237 }
238
239 /** A state frame from downstream. */
240 state(frame: StateFrame): void {
241 if (this.closed) return;
242 const m = frame.m;
243 if (this.awaiting.has(m)) {
244 if (frame.as === "ops") return;
245 this.awaiting.delete(m);
246 }
247 const out: StateFrame = { ...frame, hold: this.originId };
248 if (this.urgent?.delete(m) === true) {
249 this.origin.send(out);
250 return;
251 }
252 this.origin.sendState(out, { resync: () => this.resync(m) });
253 }
254
255 /**
256 * Closes the relay. `releaseDown`: the downstream hold is still there (origin released, disconnected, or was
257 * revoked): cancel its calls and release it. `notify`: tell the origin the hold is gone.
258 */
259 close(error: unknown, options: { readonly releaseDown: boolean; readonly notify: boolean }): void {
260 if (this.closed) return;
261 this.closed = true;
262 for (const call of [...this.calls.values()]) call.cancel(error, options.releaseDown);
263 this.origin.dropHoldState(this.originId);
264 if (this.origin.served.get(this.originId)?.kind === "relay") this.origin.served.delete(this.originId);
265 if (this.down !== undefined) {
266 this.down.relayedRefs.delete(this.downId);
267 if (options.releaseDown) this.down.send({ t: "release", id: this.downId });
268 }
269 for (const waiter of this.#waiters) waiter.reject(error);
270 this.#waiters.clear();
271 if (options.notify) this.origin.send({ t: "gone", id: this.originId, error: toWireError(error) });
272 }
273}
274
275/** One relayed call: settles once, by result, cancellation or the relay closing; removes both mappings. */
276export class RelayCall {
277 readonly relay: RelayRef;
278 readonly originId: number;
279 readonly downId: number;
280 readonly #pending: Pending;
281 #settled = false;
282
283 constructor(relay: RelayRef, originId: number, downId: number, pending: Pending) {
284 this.relay = relay;
285 this.originId = originId;
286 this.downId = downId;
287 this.#pending = pending;
288 relay.calls.set(originId, this);
289 relay.down?.relayedCalls.set(downId, this);
290 }
291
292 finish(error: unknown, value?: unknown): void {
293 if (this.#settled) return;
294 this.#settled = true;
295 this.relay.calls.delete(this.originId);
296 this.relay.down?.relayedCalls.delete(this.downId);
297 if (error === undefined) this.#pending.resolve(value);
298 else this.#pending.reject(error);
299 }
300
301 /** Cancels downstream (when the downstream hold still exists) and settles with `error`. */
302 cancel(error: unknown, forward: boolean): void {
303 if (this.#settled) return;
304 if (forward) this.relay.down?.send({ t: "cancel", id: this.downId });
305 this.finish(error);
306 }
307}
308
309// ─── connection ──────────────────────────────────────────────────────────────
310
311/**
312 * One end of a link on a host: consumer of remote references, provider for the peer's holds, and relay.
313 *
314 * State
315 * -----
316 *
317 * A hold implies the state of its variant (unless it says `state: false`). The provider answers with a unit: the shape,
318 * then a snapshot of each state member the consumer does not have yet (`shape.state` lists them), then the members'
319 * ops and resets. A reload or a variant change sends another unit with the members that are new; members that left the
320 * variant stop. The consumer applies a shape once its snapshots are here (`RemoteBinding`).
321 *
322 * Flow control
323 * ------------
324 *
325 * Problem: state is pushed as fast as it changes, but a peer may read slowly (a phone behind a relay), and a relay may
326 * hide that: Cloudflare forwards to browsers without backpressure. Everything sent then queues in front of the next
327 * call result. Example: a browser opens three long transcripts (500 KiB of snapshots each) over a 5 Mbit/s path; a
328 * result sent next waits 2.4 s, and the snapshot of a transcript the user already left is still sent in full.
329 *
330 * Solution: the peer acknowledges what it processed (`ack`, a cumulative frame count), and the sender counts the sizes
331 * of the frames not yet acknowledged. While they exceed the window, state waits here in slots, flushed in creation
332 * order as acknowledgements come:
333 * - a member's stream has one slot: ops are appended (encoded batches of one stream may be concatenated, see
334 * `encoder`), a snapshot, reset or error replaces it;
335 * - a hold's unit has one slot, built lazily from the current values when it is sent, so a newer unit merges into it;
336 * while it waits, the members it introduces have no stream yet.
337 *
338 * The first unit of a hold that is not a re-hold (`again`) is sent at once, past the window: a `get` waits for it, and
339 * must not wait behind other holds' state. Results, shapes, gone, reload control and pings are sent at once too: they
340 * are bounded by the requests the peer makes. Hence the one ordering exception of a link: while state waits, a result
341 * can arrive before state changes made before it. Frames of one stream stay in order.
342 *
343 * Waiting ops are capped per link (`pendingCap`): beyond, the oldest streams are replaced by their current value (a
344 * reset built at flush), or, on a relay, by a reset asked of the provider (`resync`), so memory stays bounded however
345 * long the peer stalls. The window bounds what is unacknowledged when a frame is sent, so one frame (a large snapshot)
346 * may exceed it. Both hellos must announce `acks`; with an older peer nothing is acknowledged and nothing waits. Links
347 * that do not report sizes (IPC) never fill the window.
348 */
349export class Connection implements RemoteChannel {
350 readonly host: HostImpl;
351 readonly link: Link;
352 /** `upstream`: the link to this host's parent. `downstream`: a link this host accepted. */
353 readonly role: "upstream" | "downstream";
354 readonly peer: Peer;
355 /** A client connection's opaque id: holds that come over it (directly or relayed) carry it as their `origin`. */
356 readonly originId: string | undefined;
357 principal: unknown;
358 readonly restamp: ((principal: unknown) => unknown | undefined) | undefined;
359 /** Bumped when the stamped principal is revoked or re-stamped: relays from before are refused. */
360 generation = 0;
361 /** The code version a downstream host peer runs (from its hello, then from commits). */
362 peerCodeVersion: number | undefined;
363 /** A downstream host peer is usable once it runs this host's current code version (see `HostImpl.peerHello`). */
364 synced: boolean;
365 /** Code versions this child announced while behind this host (fenced): this host never ran them. */
366 readonly fencedCodeVersions = new Set<number>();
367 /** Roots of fenced code versions, by the code version of this host they were admitted in. */
368 readonly #admitted = new Map<string, number>();
369 #parentName: string | undefined;
370 readonly #syncWaiters = new Set<Pending>();
371 #nextId = 1;
372 #lastSeen = Date.now();
373 #pinger: ReturnType<typeof setInterval> | undefined;
374 readonly #maxCalls: number;
375 // flow control (see the class comment)
376 readonly #window: number;
377 readonly #pendingCap: number;
378 /** Whether the peer acknowledges frames; until its hello is here, frames are counted in case it does. */
379 #peerAcks: boolean | undefined;
380 #sent = 0;
381 #acked = 0;
382 /** Sizes of the frames sent after the last acknowledged one. */
383 #unacked: number[] = [];
384 #unackedBytes = 0;
385 readonly #pending = new Map<string, Slot>();
386 /** Bytes of ops waiting in `#pending`. */
387 #pendingBytes = 0;
388 #received = 0;
389 #ackTimer: ReturnType<typeof setTimeout> | undefined;
390 readonly #onProtocolMismatch: LinkOptions["onProtocolMismatch"];
391 /** The peer speaks another protocol version: nothing it sends is processed any more. */
392 #mismatched = false;
393 // consumer side: what this host asked of the peer
394 readonly remotes = new Map<number, RemoteBinding>();
395 readonly calls = new Map<number, Pending>();
396 // provider side: what the peer asked of this host
397 readonly served = new Map<number, Served>();
398 readonly incoming = new Map<number, AbortController>();
399 // downstream side of relays: ids this host used on this link
400 readonly relayedRefs = new Map<number, RelayRef>();
401 readonly relayedCalls = new Map<number, RelayCall>();
402 /** Reload votes awaited from this (child) peer. */
403 readonly votes = new Map<number, Pending>();
404
405 constructor(
406 host: HostImpl,
407 link: Link,
408 config: {
409 readonly role: "upstream" | "downstream";
410 readonly principal: unknown;
411 readonly peer: Peer;
412 readonly originId?: string;
413 readonly restamp?: (principal: unknown) => unknown | undefined;
414 readonly maxCalls?: number;
415 } & LinkOptions,
416 ) {
417 this.host = host;
418 this.link = link;
419 this.role = config.role;
420 this.peer = config.peer;
421 this.originId = config.originId;
422 this.principal = config.principal;
423 this.restamp = config.restamp;
424 this.synced = !(this.role === "downstream" && this.peer.kind === "host");
425 this.#window = config.window ?? DEFAULT_WINDOW;
426 this.#pendingCap = config.pendingCap ?? this.#window * PENDING_WINDOWS;
427 this.#maxCalls = config.maxCalls ?? Number.POSITIVE_INFINITY;
428 this.#onProtocolMismatch = config.onProtocolMismatch;
429 link.onClose((reason) => this.#closed(reason));
430 link.receive((frame) => this.#receive(frame));
431 this.send({
432 t: "hello",
433 protocol: PROTOCOL_VERSION,
434 name: host.name,
435 kind: host.kind,
436 codeVersion: host.current.id,
437 acks: true,
438 });
439 const interval = config.pingInterval ?? 15_000;
440 const timeout = config.pingTimeout ?? 45_000;
441 // A link that was already closed closed this connection above; it needs no keepalive.
442 if (link.closed) return;
443 let n = 0;
444 this.#pinger = setInterval(() => {
445 if (Date.now() - this.#lastSeen > timeout) link.close("ping timeout");
446 else this.send({ t: "ping", n: ++n });
447 }, interval);
448 this.#pinger.unref?.();
449 }
450
451 get open(): boolean {
452 return !this.link.closed;
453 }
454
455 /** The peer's name: configured for downstream hosts, announced by the parent upstream. */
456 get name(): string | undefined {
457 return this.role === "upstream" ? this.#parentName : this.peer.name;
458 }
459
460 send(frame: Frame): void {
461 const size = this.link.send(frame) ?? 0;
462 if (this.#peerAcks === false) return;
463 this.#sent++;
464 this.#unacked.push(size);
465 this.#unackedBytes += size;
466 }
467
468 /** Sends a state frame, or keeps it waiting (see the class comment). */
469 sendState(frame: StateFrame, overflow: Overflow): void {
470 const key = stateKey(frame.hold, frame.m);
471 let slot = this.#pending.get(key);
472 if (slot === undefined && !this.#full) {
473 this.send(frame);
474 return;
475 }
476 if (slot?.kind === "unit") return;
477 if (slot === undefined) {
478 slot = {
479 kind: "state",
480 hold: frame.hold,
481 m: frame.m,
482 base: undefined,
483 ops: [],
484 size: 0,
485 lazy: false,
486 overflow,
487 };
488 this.#pending.set(key, slot);
489 }
490 if (frame.as !== "ops") {
491 this.#pendingBytes -= slot.size;
492 slot.base = frame;
493 slot.ops = [];
494 slot.size = 0;
495 slot.lazy = false;
496 return;
497 }
498 // A reset built at flush already covers these ops.
499 if (slot.lazy) return;
500 const size = JSON.stringify(frame.ops).length;
501 if (this.#pendingBytes + size > this.#pendingCap) this.#makeRoom(size, slot);
502 if (slot.lazy || this.#pending.get(key) !== slot) return;
503 for (const op of frame.ops ?? []) slot.ops.push(op);
504 slot.size += size;
505 this.#pendingBytes += size;
506 }
507
508 /** Replaces the oldest waiting streams by resets until `size` more bytes fit; `current` last, if needed. */
509 #makeRoom(size: number, current: Extract<Slot, { kind: "state" }>): void {
510 for (const slot of [...this.#pending.values()]) {
511 if (this.#pendingBytes + size <= this.#pendingCap) return;
512 if (slot.kind === "state" && slot !== current && slot.size > 0) this.#drop(slot);
513 }
514 if (this.#pendingBytes + size > this.#pendingCap) this.#drop(current);
515 }
516
517 /** Drops what waits for a stream: a lazy reset replaces it (provider), or the relay asks downstream for one. */
518 #drop(slot: Extract<Slot, { kind: "state" }>): void {
519 this.#pendingBytes -= slot.size;
520 slot.base = undefined;
521 slot.ops = [];
522 slot.size = 0;
523 if ("resend" in slot.overflow) {
524 slot.lazy = true;
525 return;
526 }
527 this.#pending.delete(stateKey(slot.hold, slot.m));
528 slot.overflow.resync();
529 }
530
531 /** Sends member `m` of a served hold again as a reset, through the window (`resync`). */
532 #resetLater(hold: number, m: string, resend: () => void): void {
533 const key = stateKey(hold, m);
534 let slot = this.#pending.get(key);
535 if (slot?.kind === "unit") return;
536 if (slot === undefined) {
537 slot = { kind: "state", hold, m, base: undefined, ops: [], size: 0, lazy: true, overflow: { resend } };
538 this.#pending.set(key, slot);
539 } else {
540 this.#pendingBytes -= slot.size;
541 slot.base = undefined;
542 slot.ops = [];
543 slot.size = 0;
544 slot.lazy = true;
545 }
546 this.#flush();
547 }
548
549 /** Queues a hold's lazy unit (a waiting one already covers this one), and sends what the window allows. */
550 #queueUnit(hold: number, flush: () => void): void {
551 const key = unitKey(hold);
552 if (!this.#pending.has(key)) this.#pending.set(key, { kind: "unit", hold, flush });
553 this.#flush();
554 }
555
556 /** Forgets what waits for a stream that ended. */
557 dropState(hold: number, m: string): void {
558 const slot = this.#pending.get(stateKey(hold, m));
559 if (slot?.kind !== "state") return;
560 this.#pendingBytes -= slot.size;
561 this.#pending.delete(stateKey(hold, m));
562 }
563
564 /** Forgets everything that waits for a hold (released, closed, or its state stopped). */
565 dropHoldState(hold: number): void {
566 for (const [key, slot] of this.#pending) {
567 if (slot.hold !== hold) continue;
568 if (slot.kind === "state") this.#pendingBytes -= slot.size;
569 this.#pending.delete(key);
570 }
571 }
572
573 /** What waits for the peer: slots and bytes of ops (for tests and diagnostics). */
574 get waiting(): { readonly slots: number; readonly bytes: number } {
575 return { slots: this.#pending.size, bytes: this.#pendingBytes };
576 }
577
578 get #full(): boolean {
579 return this.#peerAcks === true && this.#unackedBytes >= this.#window;
580 }
581
582 #onAck(n: number): void {
583 if (this.#peerAcks !== true || n < this.#acked || n > this.#sent) {
584 this.#violation(`ack ${n} outside ${this.#acked}..${this.#sent}`);
585 return;
586 }
587 for (const size of this.#unacked.splice(0, n - this.#acked)) this.#unackedBytes -= size;
588 this.#acked = n;
589 this.#flush();
590 }
591
592 /** Sends waiting slots in creation order while the window allows. */
593 #flush(): void {
594 for (const [key, slot] of this.#pending) {
595 if (this.#full) return;
596 this.#pending.delete(key);
597 if (slot.kind === "unit") {
598 slot.flush();
599 continue;
600 }
601 this.#pendingBytes -= slot.size;
602 if (slot.lazy) {
603 if ("resend" in slot.overflow) slot.overflow.resend();
604 continue;
605 }
606 if (slot.base !== undefined) this.send(slot.base);
607 if (slot.ops.length > 0) this.send({ t: "state", hold: slot.hold, m: slot.m, as: "ops", ops: slot.ops });
608 }
609 }
610
611 /** Acknowledges once the frames that arrived together are processed: one ack per burst, not per frame. */
612 #scheduleAck(): void {
613 if (this.#peerAcks !== true || this.#ackTimer !== undefined || !this.open) return;
614 this.#ackTimer = setTimeout(() => {
615 this.#ackTimer = undefined;
616 this.link.send({ t: "ack", n: this.#received });
617 }, 0);
618 this.#ackTimer.unref?.();
619 }
620
621 nextId(): number {
622 return this.#nextId++;
623 }
624
625 /** Resolves once the peer is usable (a host peer runs this host's code version); rejects if the link closes first. */
626 whenSynced(): Promise<void> {
627 if (!this.open) return Promise.reject(unavailable(`link to ${this.name ?? "peer"} closed`));
628 if (this.synced) return Promise.resolve();
629 return new Promise<void>((resolve, reject) => this.#syncWaiters.add({ resolve: resolve as () => void, reject }));
630 }
631
632 markSynced(codeVersion: number): void {
633 this.peerCodeVersion = codeVersion;
634 this.synced = true;
635 for (const waiter of this.#syncWaiters) waiter.resolve(undefined);
636 this.#syncWaiters.clear();
637 }
638
639 /** Revokes the stamped principal: relays made under it close at once (also those still resolving a route). */
640 revoke(next: unknown | undefined): void {
641 this.generation++;
642 const error = new ChordError("gone", "principal invalidated");
643 for (const served of [...this.served.values()]) {
644 if (served.kind === "relay") served.relay.close(error, { releaseDown: true, notify: true });
645 }
646 if (next === undefined) this.link.close("principal invalidated");
647 else this.principal = next;
648 }
649
650 /**
651 * Stops talking to a peer of another protocol version: reports it and closes the link. The close reason tells the
652 * peer this side's version (`protocol-version <n>`); a peer that noticed first told us the same way (`#closed`).
653 */
654 #protocolMismatch(peer: number | undefined, close = true): void {
655 if (this.#mismatched) return;
656 this.#mismatched = true;
657 try {
658 this.#onProtocolMismatch?.({ local: PROTOCOL_VERSION, peer });
659 } catch (error) {
660 this.host.report(error);
661 }
662 if (close) this.link.close(`protocol-version ${PROTOCOL_VERSION}`);
663 }
664
665 /** A protocol violation: the peer cannot be trusted with anything on this link any more. */
666 #violation(reason: string): void {
667 this.host.report(new ChordError("invalid", `link to ${this.name ?? "peer"}: ${reason}`, { reason: "protocol" }));
668 this.link.close(`protocol error: ${reason}`);
669 }
670
671 // ─── consumer side (RemoteChannel) ───
672
673 hold(binding: RemoteBinding, again: boolean): number {
674 const id = this.nextId();
675 this.remotes.set(id, binding);
676 binding.bound(this, id);
677 const principal = binding.principal;
678 this.send({
679 t: "hold",
680 id,
681 at: binding.at,
682 token: binding.contract.description,
683 input: binding.input,
684 ...(principal === undefined ? {} : { principal }),
685 ...(binding.stateOn ? {} : { state: false as const }),
686 ...(again ? { again: true as const } : {}),
687 });
688 return id;
689 }
690
691 release(id: number): void {
692 this.remotes.delete(id);
693 this.send({ t: "release", id });
694 }
695
696 wantState(hold: number, wanted: boolean): void {
697 if (this.remotes.has(hold)) this.send({ t: wanted ? "sub" : "unsub", hold });
698 }
699
700 call(hold: number, member: string, args: unknown, root: RootRef | undefined, signal: AbortSignal): Promise<unknown> {
701 const id = this.nextId();
702 return new Promise<unknown>((resolve, reject) => {
703 if (signal.aborted) {
704 reject(new ChordError("aborted", "call aborted"));
705 return;
706 }
707 const onAbort = (): void => {
708 this.calls.delete(id);
709 this.send({ t: "cancel", id });
710 reject(new ChordError("aborted", "call aborted", { cause: signal.reason }));
711 };
712 signal.addEventListener("abort", onAbort, { once: true });
713 const done = (): void => signal.removeEventListener("abort", onAbort);
714 this.calls.set(id, {
715 resolve: (value) => {
716 done();
717 resolve(value);
718 },
719 reject: (error) => {
720 done();
721 reject(error);
722 },
723 });
724 // Clients never carry roots or code versions: the server starts roots for them.
725 const carried = root !== undefined && this.host.kind === "host";
726 if (carried) this.host.rootSent(root.rootId, this);
727 this.send({ t: "call", id, hold, member, args, ...(carried ? { root } : {}) });
728 });
729 }
730
731 // ─── receiving ───
732
733 #receive(frame: unknown): void {
734 if (this.#mismatched) return;
735 this.#lastSeen = Date.now();
736 if (!isFrame(frame)) {
737 this.#violation("malformed frame");
738 return;
739 }
740 if (frame.t === "ack") {
741 this.#onAck(frame.n);
742 return;
743 }
744 this.#received++;
745 try {
746 this.#dispatch(frame);
747 } catch (error) {
748 this.host.report(error);
749 }
750 this.#scheduleAck();
751 }
752
753 #dispatch(frame: Frame): void {
754 switch (frame.t) {
755 case "hello":
756 this.#onHello(frame);
757 return;
758 case "ping":
759 this.send({ t: "pong", n: frame.n });
760 return;
761 case "pong":
762 case "bye":
763 case "ack":
764 return;
765 case "hold":
766 this.#onHold(frame);
767 return;
768 case "release":
769 this.#dropServed(frame.id, true);
770 return;
771 case "call":
772 this.#onCall(frame);
773 return;
774 case "cancel":
775 this.incoming.get(frame.id)?.abort(new ChordError("aborted", "cancelled by caller"));
776 return;
777 case "sub":
778 case "unsub":
779 this.#onWantState(frame.hold, frame.t === "sub");
780 return;
781 case "resync":
782 this.#onResync(frame.hold, frame.m);
783 return;
784 case "shape":
785 case "gone":
786 this.#onHoldReply(frame);
787 return;
788 case "result":
789 this.#onResult(frame);
790 return;
791 case "state":
792 this.#onState(frame);
793 return;
794 case "root_end":
795 // Honored only from the link the root came over (see HostImpl.foreignRootEnded).
796 this.#admitted.delete(frame.rootId);
797 this.host.foreignRootEnded(frame.rootId, this);
798 return;
799 case "invalidate":
800 case "prepare":
801 case "commit":
802 case "abort":
803 case "retire":
804 // Control frames only from the parent.
805 if (this.role !== "upstream") {
806 this.#violation(`${frame.t} from a child`);
807 return;
808 }
809 if (frame.t === "invalidate") {
810 this.host.invalidatePrincipal(frame.pattern).catch((error: unknown) => this.host.report(error));
811 } else if (frame.t === "retire") this.host.allowRetire(frame.codeVersion);
812 else this.host.onReloadFrame(this, frame);
813 return;
814 case "vote": {
815 if (this.role !== "downstream" || this.peer.kind !== "host") {
816 this.#violation("vote from a non-participant");
817 return;
818 }
819 const vote = this.votes.get(frame.reload);
820 this.votes.delete(frame.reload);
821 if (frame.error === undefined) vote?.resolve(frame.report);
822 else vote?.reject(fromWireError(frame.error));
823 return;
824 }
825 }
826 }
827
828 /**
829 * The peer's hello must agree with what this side decided about it. A downstream host announces its code version:
830 * the host either finds it in step or fences and reconciles it (never renumbers).
831 */
832 #onHello(frame: Extract<Frame, { t: "hello" }>): void {
833 if ((frame.protocol ?? 1) !== PROTOCOL_VERSION) {
834 this.#protocolMismatch(frame.protocol ?? 1);
835 return;
836 }
837 if (this.#peerAcks === undefined) {
838 this.#peerAcks = frame.acks === true;
839 if (!this.#peerAcks) {
840 this.#unacked = [];
841 this.#unackedBytes = 0;
842 }
843 }
844 if (this.role === "upstream") {
845 if (frame.kind !== "host") {
846 this.#violation("parent is not a host");
847 return;
848 }
849 this.#parentName ??= frame.name;
850 return;
851 }
852 if (frame.kind !== this.peer.kind || (this.peer.name !== undefined && frame.name !== this.peer.name)) {
853 this.#violation(
854 `hello ${frame.kind} ${frame.name} does not match the accepted ${this.peer.kind} ${this.peer.name ?? ""}`,
855 );
856 return;
857 }
858 if (this.peer.kind === "host") this.host.peerHello(this, frame.codeVersion);
859 }
860
861 /**
862 * Principal stamping: a downstream link acts as the principal it was accepted with, whatever the frame says. Only
863 * the parent may forward a principal (relayed requests); its own requests act as the principal given to `connect`.
864 */
865 #principalOf(frame: { readonly principal?: unknown }): unknown {
866 if (this.role === "downstream") return this.principal;
867 return frame.principal ?? this.principal;
868 }
869
870 /**
871 * The client connection a hold comes from: this link's own id for a client link (whatever the frame says), the id
872 * the parent forwarded for a relayed hold, none for a host's own holds.
873 */
874 #originOf(frame: { readonly origin?: string }): string | undefined {
875 return this.role === "downstream" ? this.originId : frame.origin;
876 }
877
878 #onHold(frame: Extract<Frame, { t: "hold" }>): void {
879 if (this.served.has(frame.id)) {
880 this.#violation(`duplicate hold id ${frame.id}`);
881 return;
882 }
883 const principal = this.#principalOf(frame);
884 const origin = this.#originOf(frame);
885 const client = origin !== undefined;
886 if (frame.at !== this.host.name) {
887 if (this.role === "upstream") {
888 this.send({ t: "gone", id: frame.id, error: toWireError(unavailable(`${this.host.name} does not relay`)) });
889 return;
890 }
891 const relay = new RelayRef(this, frame, principal, origin);
892 this.served.set(frame.id, { kind: "relay", relay });
893 this.host.relay(relay).catch((error: unknown) => relay.close(error, { releaseDown: true, notify: true }));
894 return;
895 }
896 let ref: RefImpl;
897 try {
898 const token = contractFromDescription(frame.token);
899 if (token.scope !== "remote") throw invalid("token", `${token.name} is local; only remote types cross links`);
900 // Addressed here, so the input must place it here (also by this host's contract, checked when acquiring).
901 if (resolveHost(token.name, token.description.host!, frame.input) !== this.host.name)
902 throw invalid("placement", `${token.name} with this input does not live on ${this.host.name}`);
903 const acquired = this.host.acquire(token, frame.input, { principal }, client ? "client" : "connection");
904 if (!(acquired instanceof RefImpl)) throw unavailable("not a local reference");
905 ref = acquired;
906 } catch (error) {
907 this.send({ t: "gone", id: frame.id, error: toWireError(client ? clientError(error) : error) });
908 return;
909 }
910 const served: ServedLocal = {
911 kind: "local",
912 id: frame.id,
913 ref,
914 principal,
915 origin,
916 wantsState: frame.state !== false,
917 again: frame.again === true,
918 unitSent: false,
919 feeds: new Map(),
920 };
921 this.served.set(frame.id, served);
922 ref.onShape(() => this.#unit(served));
923 ref.goneListeners.add((error) => {
924 if (this.served.get(frame.id) !== served) return;
925 this.#dropServed(frame.id, false);
926 this.send({ t: "gone", id: frame.id, error: toWireError(error) });
927 });
928 if (ref.status === "live") this.#unit(served);
929 }
930
931 /** The state members of `shape` the consumer's contract knows. */
932 #stateMembers(ref: RefImpl, shape: Shape): string[] {
933 return shape.members.filter((name) => ref.describe(shape.variant, name)?.kind === "state");
934 }
935
936 /**
937 * The shape changed (live, reload, variant) or state was asked for: members that left lose their stream, and a unit
938 * goes out with the shape and the members the consumer lacks. The first unit of a hold (not a re-hold) is urgent.
939 */
940 #unit(served: ServedLocal): void {
941 if (this.served.get(served.id) !== served) return;
942 const shape = served.ref.shape;
943 if (shape === undefined) return;
944 const members = new Set(served.wantsState ? this.#stateMembers(served.ref, shape) : []);
945 for (const [name, feed] of served.feeds) {
946 if (members.has(name)) continue;
947 feed.unsubscribe();
948 served.feeds.delete(name);
949 this.dropState(served.id, name);
950 }
951 const urgent = served.feeds.size === 0 && !(served.again && !served.unitSent);
952 if (urgent) this.#sendUnit(served);
953 else this.#queueUnit(served.id, () => this.#sendUnit(served));
954 }
955
956 /** Builds and sends a unit from the current shape and values. */
957 #sendUnit(served: ServedLocal): void {
958 this.#pending.delete(unitKey(served.id));
959 if (this.served.get(served.id) !== served) return;
960 const shape = served.ref.shape;
961 if (shape === undefined) return;
962 served.unitSent = true;
963 const members = served.wantsState ? this.#stateMembers(served.ref, shape) : [];
964 const listed = members.filter((name) => !served.feeds.has(name));
965 const snaps: StateFrame[] = [];
966 const attached: (readonly [string, Feed])[] = [];
967 for (const name of listed) {
968 const attachment = this.#attach(served, name);
969 if (attachment === undefined) continue;
970 snaps.push(attachment.frame);
971 attached.push([name, attachment.feed]);
972 }
973 this.send({
974 t: "shape",
975 id: served.id,
976 ...(shape.variant === undefined ? {} : { variant: shape.variant }),
977 members: shape.members,
978 contract: shape.contract,
979 state: snaps.map((frame) => frame.m),
980 });
981 for (const frame of snaps) this.send(frame);
982 for (const [name, feed] of attached) this.#replay(served, name, feed);
983 }
984
985 /**
986 * Subscribes member `name` for the consumer: its snapshot (as a frame of type `as`), and a feed whose later events
987 * wait in its buffer until the snapshot is sent (`#replay`). Undefined if the member is not readable state.
988 */
989 #attach(
990 served: ServedLocal,
991 name: string,
992 as: "snap" | "reset" = "snap",
993 ): { readonly frame: StateFrame; readonly feed: Feed } | undefined {
994 const readable = served.ref.member(name) as Readable<unknown> | undefined;
995 if (readable === undefined || typeof readable.events !== "function") return undefined;
996 const feed: Feed = { unsubscribe: () => {}, encoder: encoder(), buffer: [] };
997 let first: StateEvent<unknown> | undefined;
998 feed.unsubscribe = readable.events((event) => {
999 if (first === undefined) first = event;
1000 else if (feed.buffer !== undefined) feed.buffer.push(event);
1001 else this.#feedEvent(served, name, feed, event);
1002 });
1003 served.feeds.set(name, feed);
1004 return { frame: this.#snapshot(served, name, as, first?.value), feed };
1005 }
1006
1007 /** Sends the events that arrived while the snapshot was built, now that it is sent. */
1008 #replay(served: ServedLocal, name: string, feed: Feed): void {
1009 const buffered = feed.buffer ?? [];
1010 feed.buffer = undefined;
1011 for (const event of buffered) this.#feedEvent(served, name, feed, event);
1012 }
1013
1014 /** A member's state frame for a snapshot or reset: validated against the schema the consumer is promised. */
1015 #snapshot(served: ServedLocal, name: string, as: "snap" | "reset", value: unknown): StateFrame {
1016 try {
1017 validateSnapshot(served.ref, name, value);
1018 } catch (error) {
1019 return { t: "state", hold: served.id, m: name, as: "error", error: toWireError(error) };
1020 }
1021 return { t: "state", hold: served.id, m: name, as, ...(value === undefined ? {} : { value }) };
1022 }
1023
1024 /** A later event of a member's stream: ops are encoded, a reset starts a new stream. */
1025 #feedEvent(served: ServedLocal, name: string, feed: Feed, event: StateEvent<unknown>): void {
1026 if (served.feeds.get(name) !== feed) return;
1027 const overflow = { resend: () => this.#resend(served, name) };
1028 if (event.type === "ops") {
1029 this.sendState(
1030 { t: "state", hold: served.id, m: name, as: "ops", ops: feed.encoder.encode(event.ops) },
1031 overflow,
1032 );
1033 return;
1034 }
1035 feed.encoder = encoder();
1036 this.sendState(this.#snapshot(served, name, "reset", event.value), overflow);
1037 }
1038
1039 /** Sends member `name` again, now, as a reset from its current value (a lazy slot is flushed, or `resync`). */
1040 #resend(served: ServedLocal, name: string): void {
1041 const feed = served.feeds.get(name);
1042 if (feed === undefined || this.served.get(served.id) !== served) return;
1043 feed.unsubscribe();
1044 served.feeds.delete(name);
1045 const attachment = this.#attach(served, name, "reset");
1046 if (attachment === undefined) return;
1047 this.send(attachment.frame);
1048 this.#replay(served, name, attachment.feed);
1049 }
1050
1051 /** The consumer starts (`sub`) or stops (`unsub`) the state of a hold. */
1052 #onWantState(hold: number, wanted: boolean): void {
1053 const served = this.served.get(hold);
1054 if (served === undefined) return;
1055 if (served.kind === "relay") {
1056 served.relay.wantState(wanted);
1057 return;
1058 }
1059 if (served.wantsState === wanted) return;
1060 served.wantsState = wanted;
1061 if (wanted) {
1062 this.#unit(served);
1063 return;
1064 }
1065 for (const feed of served.feeds.values()) feed.unsubscribe();
1066 served.feeds.clear();
1067 this.dropHoldState(hold);
1068 }
1069
1070 /** The consumer (a relay that dropped ops) asks for member `m` again as a reset. */
1071 #onResync(hold: number, m: string): void {
1072 const served = this.served.get(hold);
1073 if (served === undefined) return;
1074 if (served.kind === "relay") {
1075 served.relay.resync(m);
1076 return;
1077 }
1078 if (!served.feeds.has(m)) return;
1079 this.#resetLater(hold, m, () => this.#resend(served, m));
1080 }
1081
1082 /** Forgets a served hold: unsubscribes its feeds and releases it (locally or downstream). */
1083 #dropServed(id: number, release: boolean): void {
1084 const served = this.served.get(id);
1085 if (served === undefined) return;
1086 this.served.delete(id);
1087 if (served.kind === "relay") {
1088 served.relay.close(new ChordError("released", "relayed hold released"), {
1089 releaseDown: release,
1090 notify: false,
1091 });
1092 return;
1093 }
1094 for (const feed of served.feeds.values()) feed.unsubscribe();
1095 served.feeds.clear();
1096 this.dropHoldState(id);
1097 if (release) served.ref.release();
1098 }
1099
1100 #onCall(frame: Extract<Frame, { t: "call" }>): void {
1101 if (this.incoming.has(frame.id)) {
1102 this.#violation(`duplicate call id ${frame.id}`);
1103 return;
1104 }
1105 if (this.incoming.size >= this.#maxCalls) {
1106 const error = new ChordError(
1107 "unavailable",
1108 `Too many calls in progress on this connection (${this.#maxCalls}); wait for earlier ones to finish`,
1109 { reason: "too_many_calls" },
1110 );
1111 this.send({ t: "result", id: frame.id, error: toWireError(error) });
1112 return;
1113 }
1114 const served = this.served.get(frame.hold);
1115 if (served === undefined) {
1116 this.send({ t: "result", id: frame.id, error: toWireError(new ChordError("gone", "unknown hold")) });
1117 return;
1118 }
1119 const controller = new AbortController();
1120 this.incoming.set(frame.id, controller);
1121 // Roots are honored from hosts only; a request without one (or from a client) starts one here.
1122 const root = this.peer.kind === "host" ? this.#admitRoot(frame.root) : undefined;
1123 const principal = served.kind === "local" ? served.principal : served.relay.principal;
1124 const options = { principal, signal: controller.signal };
1125 const run =
1126 served.kind === "local"
1127 ? (ctx: Ctx) => served.ref.object.call(served.ref, frame.member, unpack(frame.args), ctx as CtxImpl)
1128 : (ctx: Ctx) =>
1129 relayCall(
1130 served.relay,
1131 frame,
1132 { rootId: ctx.rootId, codeVersion: ctx.codeVersion },
1133 // The root's signal: a cancel from the origin and the root's code version retiring both reach it.
1134 ctx.signal,
1135 this.host,
1136 );
1137 const result =
1138 root === undefined
1139 ? this.host.root(run, options)
1140 : this.host.joinRoot(root.rootId, root.codeVersion, run, { ...options, from: this });
1141 result
1142 .then(
1143 (value) => this.send({ t: "result", id: frame.id, value }),
1144 (error: unknown) => this.send({ t: "result", id: frame.id, error: toWireError(error) }),
1145 )
1146 .finally(() => this.incoming.delete(frame.id));
1147 }
1148
1149 /**
1150 * A child that connected behind this host runs roots of a code version this host never had (it was fenced and is
1151 * being, or was, reconciled). Such a root is admitted in this host's current code version at its first call here,
1152 * and keeps that code version for its later calls (`superseded` once this host retired it). Other unknown code
1153 * versions stay `superseded`.
1154 */
1155 #admitRoot(root: RootRef | undefined): RootRef | undefined {
1156 if (root === undefined || this.role !== "downstream" || !this.fencedCodeVersions.has(root.codeVersion))
1157 return root;
1158 if (this.host.hasCodeVersion(root.codeVersion)) return root;
1159 let codeVersion = this.#admitted.get(root.rootId);
1160 if (codeVersion === undefined) {
1161 codeVersion = this.host.current.id;
1162 this.#admitted.set(root.rootId, codeVersion);
1163 }
1164 return { rootId: root.rootId, codeVersion };
1165 }
1166
1167 #onHoldReply(frame: Extract<Frame, { t: "shape" | "gone" }>): void {
1168 const relay = this.relayedRefs.get(frame.id);
1169 if (relay !== undefined) {
1170 if (frame.t === "gone") relay.close(fromWireError(frame.error), { releaseDown: false, notify: true });
1171 else relay.shape(frame);
1172 return;
1173 }
1174 const binding = this.remotes.get(frame.id);
1175 if (binding === undefined) return;
1176 if (frame.t === "gone") {
1177 this.remotes.delete(frame.id);
1178 binding.gone(fromWireError(frame.error));
1179 return;
1180 }
1181 binding.shaped({ variant: frame.variant, members: frame.members, contract: frame.contract }, frame.state);
1182 }
1183
1184 #onResult(frame: Extract<Frame, { t: "result" }>): void {
1185 const relayed = this.relayedCalls.get(frame.id);
1186 if (relayed !== undefined) {
1187 relayed.finish(frame.error === undefined ? undefined : fromWireError(frame.error), frame.value);
1188 return;
1189 }
1190 const pending = this.calls.get(frame.id);
1191 this.calls.delete(frame.id);
1192 if (frame.error !== undefined) {
1193 pending?.reject(fromWireError(frame.error));
1194 return;
1195 }
1196 let value: unknown;
1197 try {
1198 value = unpack(frame.value);
1199 } catch (error) {
1200 pending?.reject(error);
1201 return;
1202 }
1203 pending?.resolve(value);
1204 }
1205
1206 #onState(frame: StateFrame): void {
1207 const relay = this.relayedRefs.get(frame.hold);
1208 if (relay !== undefined) {
1209 relay.state(frame);
1210 return;
1211 }
1212 const binding = this.remotes.get(frame.hold);
1213 if (binding === undefined) return;
1214 if (!(frame.value instanceof Packed)) {
1215 binding.state(frame.m, frame);
1216 return;
1217 }
1218 let value: unknown;
1219 try {
1220 value = unpack(frame.value);
1221 } catch (error) {
1222 binding.state(frame.m, { as: "error", error: toWireError(error) });
1223 return;
1224 }
1225 binding.state(frame.m, { ...frame, value });
1226 }
1227
1228 // ─── lifetime ───
1229
1230 #closed(reason: string): void {
1231 const told = /^protocol-version (\d+)$/.exec(reason);
1232 if (told !== null && Number(told[1]) !== PROTOCOL_VERSION) this.#protocolMismatch(Number(told[1]), false);
1233 if (this.#pinger !== undefined) clearInterval(this.#pinger);
1234 if (this.#ackTimer !== undefined) clearTimeout(this.#ackTimer);
1235 this.#pending.clear();
1236 this.#pendingBytes = 0;
1237 const error = unavailable(`link to ${this.name ?? "peer"} closed: ${reason}`);
1238 // As origin: everything the peer held here, relayed or not, is released (downstream calls cancelled).
1239 for (const id of [...this.served.keys()]) this.#dropServed(id, true);
1240 for (const controller of this.incoming.values()) controller.abort(error);
1241 this.incoming.clear();
1242 for (const pending of this.calls.values()) pending.reject(error);
1243 this.calls.clear();
1244 for (const vote of this.votes.values()) vote.reject(error);
1245 this.votes.clear();
1246 for (const waiter of this.#syncWaiters) waiter.reject(error);
1247 this.#syncWaiters.clear();
1248 // As downstream of relays: their origins lose the hold.
1249 for (const relay of [...this.relayedRefs.values()]) relay.close(error, { releaseDown: false, notify: true });
1250 this.relayedRefs.clear();
1251 this.relayedCalls.clear();
1252 const bindings = [...this.remotes.values()];
1253 this.remotes.clear();
1254 for (const binding of bindings) {
1255 // An upstream link may be replaced (reconnect); a downstream host that went away is gone.
1256 if (this.role === "upstream") binding.detached();
1257 else binding.gone(error);
1258 }
1259 this.host.connectionClosed(this);
1260 }
1261}
1262
1263const stateKey = (hold: number, m: string): string => `s${hold}\u0000${m}`;
1264const unitKey = (hold: number): string => `u${hold}`;
1265
1266/**
1267 * A call through a relay: waits for the route, then forwards with the root it runs in. It settles exactly once; a
1268 * cancel (or the origin going away) is forwarded downstream and removes both mappings.
1269 */
1270async function relayCall(
1271 relay: RelayRef,
1272 frame: Extract<Frame, { t: "call" }>,
1273 root: RootRef,
1274 signal: AbortSignal,
1275 host: HostImpl,
1276): Promise<unknown> {
1277 const abortError = (): ChordError => new ChordError("aborted", "call cancelled", { cause: signal.reason });
1278 if (signal.aborted) throw abortError();
1279 let onAbort = (): void => {};
1280 let onCancel = (): void => {};
1281 const aborted = new Promise<never>((_, reject) => {
1282 onAbort = () => reject(abortError());
1283 signal.addEventListener("abort", onAbort, { once: true });
1284 });
1285 aborted.catch(() => {});
1286 try {
1287 const down = await Promise.race([relay.ready(), aborted]);
1288 if (relay.closed) throw new ChordError("gone", "relayed hold closed");
1289 return await new Promise<unknown>((resolve, reject) => {
1290 const call = new RelayCall(relay, frame.id, down.nextId(), { resolve, reject });
1291 onCancel = () => call.cancel(abortError(), true);
1292 signal.addEventListener("abort", onCancel, { once: true });
1293 host.rootSent(root.rootId, down);
1294 down.send({ t: "call", id: call.downId, hold: relay.downId, member: frame.member, args: frame.args, root });
1295 });
1296 } finally {
1297 signal.removeEventListener("abort", onAbort);
1298 signal.removeEventListener("abort", onCancel);
1299 }
1300}
1301
1302/**
1303 * Validates a snapshot against the schema the consumer is promised: the provider's own schema for a direct binding,
1304 * the consumer's contract for one through an `accepts` adapter (the adapter's view is what the consumer gets).
1305 */
1306function validateSnapshot(ref: RefImpl, member: string, value: unknown): void {
1307 if (value === undefined) return;
1308 const installed = ref.object.currentInstalled();
1309 if (installed === undefined) return;
1310 const view = ref.currentView();
1311 const variant = view === undefined ? variantOf(installed.implementation) : variantOf(view);
1312 const description =
1313 view !== undefined && view !== installed.implementation
1314 ? ref.contract.description.variants[variant ?? LOCAL_VARIANT]?.[member]
1315 : installed.service.contract.description.variants[variantOf(installed.implementation) ?? LOCAL_VARIANT]?.[
1316 member
1317 ];
1318 if (description?.kind === "state") assertValid("state", `${ref.address}.${member}`, description.schema, value);
1319}
1320
1321/** Clients (browsers) holding an outdated contract are told to reload their code. */
1322function clientError(error: unknown): unknown {
1323 if (error instanceof ChordError && error.code === "contract_mismatch") {
1324 return new ChordError("upgrade_required", error.message, { cause: error });
1325 }
1326 return error;
1327}