返回源码地图

packages/chord/src/host.ts

v1.3.0 · 71023aec1546 · 22:对象地址、principal、root与关闭

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

1import { ChildReloads, reconcileChild, runClusterReload } from "./cluster.ts";
2import { type AcceptOptions, Connection, type LinkOptions, type RelayRef } from "./connection.ts";
3import {
4 type AnyContract,
5 bind,
6 contractFromDescription,
7 type InputOf,
8 type LocalContract,
9 type LocalDef,
10 placedOn,
11 placementText,
12 type Ref,
13 type RemoteContract,
14 type RemoteDef,
15 resolveHost,
16} from "./contract.ts";
17import { ChordError, invalid, runAll } from "./errors.ts";
18import type { Link } from "./link.ts";
19import {
20 awaitReady,
21 CtxImpl,
22 type Decls,
23 type Factory,
24 type HostCore,
25 hostLifetime,
26 makeService,
27 ObjectImpl,
28 type RefCore,
29 RefImpl,
30 type RefOwner,
31 type ServeOptions,
32 type ServeOptionsFor,
33 type Service,
34} from "./object.ts";
35import { enqueue } from "./publish.ts";
36import type { Registry, RegistryTable, RegistryView } from "./registry.ts";
37import { type ReloadOptions, type ReloadReport, runReload } from "./reload.ts";
38import { RemoteBinding, RemoteRef } from "./remote.ts";
39import { canonicalIdentity, canonicalJson, deepEqual, normalize } from "./schema.ts";
40import type { Ctx, GetOptions } from "./types.ts";
41import type { Frame } from "./wire.ts";
42
43/**
44 * Registers a factory for a type. Overloaded on the contract's definition (not the contract type) so TypeScript
45 * keeps literal `variant`s in factory returns. `P` is the app's principal type (see `createHost`).
46 */
47export interface Serve<P = unknown> {
48 <D extends RemoteDef>(
49 type: RemoteContract<D>,
50 factory: Factory<RemoteContract<D>, P>,
51 options?: ServeOptionsFor<RemoteContract<D>>,
52 ): void;
53 <D extends LocalDef>(
54 type: LocalContract<D>,
55 factory: Factory<LocalContract<D>, P>,
56 options?: ServeOptionsFor<LocalContract<D>>,
57 ): void;
58}
59
60type AnyServe = (type: AnyContract, factory: Factory<AnyContract>, options?: ServeOptions) => void;
61
62/**
63 * What a facet's `setup` gets. `serve` registers types; `root` and `registry` give the facet's code that is not a
64 * Chord method, listener or task (Durable tools and hooks, callbacks of native libraries) access to its own host,
65 * so plugins never need a process-global host. Both may be kept and used after `setup` returns.
66 */
67export interface FacetApi<P = unknown> {
68 readonly serve: Serve<P>;
69 /** The host's name (`server`, `session:S1`, ...). */
70 readonly name: string;
71 /** Starts a root on the facet's host (in its current code version at call time). */
72 root<T>(fn: (ctx: Ctx<P>) => T | Promise<T>, options?: RootOptions<P>): Promise<T>;
73 /** The facet's host's registry view (`get(key, ctx)` reads the table of `ctx.codeVersion`). */
74 registry<V>(registry: Registry<V>): RegistryView<V>;
75 /**
76 * Aborted when this run of the facet is no longer installed: a reload that replaced or removed it committed, the reload
77 * that loaded it aborted, or the host closed. While a reload prepares, the installed and the candidate run are both
78 * live.
79 */
80 readonly signal: AbortSignal;
81}
82
83/** What a facet module exports (default export): the code that serves its types on one host kind. */
84export interface FacetDefinition<P = unknown> {
85 /** Contract tokens this facet consumes; checked against providers at reload. */
86 readonly uses?: readonly AnyContract[];
87 setup(api: FacetApi<P>): void;
88}
89
90/** A named facet. Modules are named by their URL; reloading a facet replaces everything it served. */
91export interface Facet<P = unknown> extends FacetDefinition<P> {
92 readonly name: string;
93}
94
95/** `defineFacet<P>(…)`: an app passes its principal type, so factories and contexts see `P`. */
96export const defineFacet = <P = unknown>(
97 setup: (api: FacetApi<P>) => void,
98 options: { readonly uses?: readonly AnyContract[] } = {},
99): FacetDefinition<P> => ({ setup, uses: options.uses });
100
101/** Imports facet modules (fresh copies on every call) and names them by module URL. */
102export type FacetLoader = (modules: readonly (string | URL)[]) => Promise<Facet[]>;
103
104/** A facet object, or a module (path or URL) whose default export is a FacetDefinition. */
105export type PluginRef<P = unknown> = Facet<P> | string | URL;
106
107const isFacet = (ref: PluginRef): ref is Facet => typeof ref === "object" && !(ref instanceof URL);
108
109/**
110 * `P` is the app's principal type: who a caller is, JSON-serializable. Chord never makes one up: the app supplies the
111 * host's own (`self`), the one its parent's own requests act as (`connect`), the ones links act as (`accept`) and the
112 * ones routed hosts act as (`Route.principal`).
113 */
114export interface HostOptions<P = unknown> {
115 readonly name?: string;
116 /**
117 * The principal of the host's own code: roots it starts, code inside its objects, and its `lifetime: "host"` objects.
118 * Compared by `principalKey`, so an equal principal from elsewhere reaches the same objects. Not used to infer `P`:
119 * pass the app's type as `createHost<P>(…)`.
120 */
121 readonly self: NoInfer<P>;
122 /** Maps a principal to its object key (should include connection provenance and grant revision). */
123 readonly principalKey?: (principal: P) => string;
124 /** Validates every cell write and exposed state value against its schemas. */
125 readonly dev?: boolean;
126 /** Errors from background work (disposal, listeners, tasks). Defaults to console.error. */
127 readonly onError?: (error: unknown) => void;
128 /**
129 * Milliseconds a reload waits for an object's aborted tasks to finish before it starts their replacements anyway
130 * (reported). Default 5000.
131 */
132 readonly taskStopDeadline?: number;
133 /**
134 * Milliseconds an activation (or a reload's prepare) waits for its references to be ready and hydrated, and an
135 * awaited `get` for its reference, before failing with `unavailable/ready_timeout`. Default 60000.
136 */
137 readonly readyTimeout?: number;
138 /**
139 * Consumer-side linger of remote references: when the last reference to a remote object is released, its binding
140 * stays held, and hydrated, for `types[typeName]` milliseconds, so a reference taken again meanwhile costs nothing
141 * on the link. At most `cap` bindings (default 4) linger; beyond, the least recently released go first. Types not
142 * listed do not linger. (The provider's own `serve(…, { linger })` keeps its object after the last reference.)
143 */
144 readonly linger?: { readonly types?: Readonly<Record<string, number>>; readonly cap?: number };
145 /** Needed for `load`/`reload` with modules; `nodeLoader` from loader.ts in Node. */
146 readonly loader?: FacetLoader;
147 /** `client` (browser): never a reload participant, never carries roots or code versions. Default `host`. */
148 readonly kind?: "host" | "client";
149 /** The link to this host's parent (server). Can also be set later with `connect`. */
150 readonly upstream?: { readonly link: Link } & ConnectOptions<P>;
151}
152
153/** `connect` options: the link's, and the principal its parent's own requests act as. */
154export interface ConnectOptions<P = unknown> extends LinkOptions {
155 /** What a request from the parent acts as when the parent does not forward its caller's principal (its own code). */
156 readonly principal: P;
157}
158
159/** Where requests for hosts named `prefix…` go (on the server). */
160export interface Route<P = unknown> {
161 /** Checked before resolving (or spawning) and again after: grants may change meanwhile. */
162 authorize(principal: P, hostName: string): boolean | Promise<boolean>;
163 /** A link to the host, spawned if needed. */
164 resolve(hostName: string): Promise<Link>;
165 /** The principal the resolved host acts as when it calls back. */
166 readonly principal: (hostName: string) => P;
167}
168
169/** Fields a principal must have, equal (`deepEqual`), for an `invalidatePrincipal` pattern. */
170export type PrincipalPattern<P> = P extends object
171 ? { readonly [K in keyof P]?: P[K] }
172 : Readonly<Record<string, unknown>>;
173
174/** `invalidatePrincipal` matches: a predicate (this host only), or a pattern (fields that must be equal; propagates). */
175export type PrincipalMatch<P = unknown> = ((principal: P) => boolean) | PrincipalPattern<P>;
176
177export interface RootOptions<P = unknown> {
178 readonly principal?: P;
179 readonly signal?: AbortSignal;
180 /** Start the root in a retained code version (links carry code versions). Defaults to the current code version. */
181 readonly codeVersion?: number;
182}
183
184export interface LoadOptions {
185 /**
186 * Await the activation of the `lifetime: "host"` objects the facets serve (default true). False starts them but
187 * leaves readiness to `host.ready()` (a child host whose objects need its parent, which admits it only later).
188 */
189 readonly awaitHostObjects?: boolean;
190}
191
192export interface Host<P = unknown> {
193 readonly name: string;
194 readonly codeVersion: number;
195 readonly previousCodeVersion: number | undefined;
196 readonly serve: Serve<P>;
197 /** Installs synchronously, then awaits this facet's host objects unless `awaitHostObjects` is false. */
198 install(facet: Facet<P>, options?: LoadOptions): Promise<void>;
199 /** Installs all facets before awaiting their host objects; referenced objects are created when first referenced. */
200 load(plugins: readonly PluginRef<P>[], options?: LoadOptions): Promise<void>;
201 /** Awaits the host objects present at call time, including those started by `serve` or deferred loads. */
202 ready(): Promise<void>;
203 /**
204 * A reference held until `release()`. Resolves once it is ready: live, with every state member of its variant
205 * (unless `state: false`). Rejects with the activation error, `aborted` (`signal`), or `unavailable/ready_timeout`
206 * after `readyTimeout`; the reference is released then.
207 */
208 get<C extends AnyContract>(
209 type: C,
210 input: InputOf<C>,
211 options?: GetOptions<P> & { readonly signal?: AbortSignal },
212 ): Promise<Ref<C>>;
213 /**
214 * The same reference, synchronously, possibly still `loading`: for UI runtimes that render its status (hooks, a
215 * TUI watch). Its state members throw `not_ready` until it is live.
216 */
217 hold<C extends AnyContract>(type: C, input: InputOf<C>, options?: GetOptions<P>): Ref<C>;
218 root<T>(fn: (ctx: Ctx<P>) => T | Promise<T>, options?: RootOptions<P>): Promise<T>;
219 registry<V>(registry: Registry<V>): RegistryView<V>;
220 /**
221 * Force-disposes every object whose principal matches (never the host's own principal), re-stamps or closes
222 * matching links, and propagates pattern matches to child hosts.
223 */
224 invalidatePrincipal(match: PrincipalMatch<P>): Promise<void>;
225 /** Accepts a child link (a worker or a browser); requests on it act as `options.principal`. */
226 accept(link: Link, options: AcceptOptions<P>): void;
227 /**
228 * Sets (or replaces, after a reconnect) the link to this host's parent; remote references re-hold over it. The
229 * parent's own requests act as `options.principal`; requests it relays act as the principal it forwards.
230 */
231 connect(link: Link, options: ConnectOptions<P>): void;
232 route(prefix: string, route: Route<P>): void;
233 /** Reloads the given facets (modules are re-imported); facets not listed keep running unchanged. */
234 reload(plugins: readonly PluginRef<P>[], options?: ReloadOptions): Promise<ReloadReport>;
235 close(): Promise<void>;
236}
237
238export interface CodeVersionState {
239 readonly id: number;
240 readonly services: Map<string, Service>;
241 tables: ReadonlyMap<string, RegistryTable<unknown>>;
242 /** Running roots with the number of their calls running here. */
243 readonly roots: Map<string, number>;
244 /** Aborts every root of this code version (forced retirement). */
245 readonly abort: AbortController;
246}
247
248const EMPTY_TABLE: RegistryTable<never> = new Map<string, never>();
249
250/** A host whose principals are `P` (the app's type; `unknown` if not given). */
251export function createHost<P = unknown>(options: HostOptions<P>): Host<P> {
252 return new HostImpl(options as HostOptions) as unknown as Host<P>;
253}
254
255export class HostImpl implements Host, HostCore {
256 readonly name: string;
257 readonly dev: boolean;
258 readonly principal: unknown;
259 inFactory = 0;
260 failed: unknown;
261 readonly objects = new Map<string, ObjectImpl>();
262 readonly codeVersions = new Map<number, CodeVersionState>();
263 readonly facets = new Map<string, Facet>();
264 /** The host's own references to its `lifetime: "host"` objects, by type name. */
265 readonly hostObjects = new Map<string, RefCore>();
266 readonly kind: "host" | "client";
267 readonly connections = new Set<Connection>();
268 upstream: Connection | undefined;
269 /** Shared bindings of this host's remote references, by key (re-held after an upstream reconnect). */
270 readonly bindings = new Map<string, RemoteBinding>();
271 /** Bindings without references that linger, least recently released first. */
272 readonly #lingering = new Map<string, RemoteBinding>();
273 readonly #lingerTypes: Readonly<Record<string, number>>;
274 readonly #lingerCap: number;
275 #originSeq = 0;
276 readonly #routes = new Map<string, Route>();
277 readonly #childReloads = new ChildReloads(this);
278 /** Child facet modules by host-name prefix, from every committed cluster reload (for reconciling children). */
279 remoteModules: Record<string, string[]> = {};
280 /** Removal tombstones also reconcile children that connected during a transaction. */
281 remoteRemoved: Record<string, string[]> = {};
282 /** Highest code version the parent has retired. */
283 #retireAllowed = 0;
284 /** Roots that came over a link, by the link they came from. */
285 /** Foreign roots (started on another host), by the links they came over. */
286 readonly #foreign = new Map<string, Set<Connection>>();
287 /** Roots started on this host that have not ended. */
288 readonly #local = new Set<string>();
289 readonly #incarnation = Math.random().toString(36).slice(2, 8);
290 /** Links each root's calls went out on. */
291 readonly #rootLinks = new Map<string, Set<Connection>>();
292 current: CodeVersionState;
293 previous: CodeVersionState | undefined;
294 /** The code version a running reload will commit; new types activated during prepare install their implementation for it. */
295 pending: CodeVersionState | undefined;
296 /** Activations of these types wait (reload gate). */
297 /** Types behind a reload gate: new objects of these types are rejected `upgrade_conflict` until commit/abort. */
298 gating: ReadonlySet<string> | undefined;
299 reloading = false;
300 readonly taskStopDeadline: number;
301 readonly readyTimeout: number;
302 readonly #principalKey: (principal: unknown) => string;
303 /** `principalKey(self)`: an equal principal is the host's own, whatever object carries it. */
304 readonly #selfKey: string;
305 /** Called when a root ends, the parent allows a retirement, or the previous code version retires. */
306 readonly #retirementWatchers = new Set<() => void>();
307 /** Child hosts whose hello arrived while a reload ran: synced or reconciled once it ends. */
308 readonly #deferredHellos = new Map<Connection, number>();
309 /** Resolved when the running reload ends. */
310 readonly #reloadWaiters: (() => void)[] = [];
311 /** Aborted when the installed run of a facet (by name) is replaced, removed, or the host closes. */
312 readonly #facetRuns = new Map<string, AbortController>();
313 readonly #onError: (error: unknown) => void;
314 readonly #loader: FacetLoader | undefined;
315 readonly #dying = new Map<string, ObjectImpl>();
316 readonly #touches = new Map<string, Set<ObjectImpl>>();
317 readonly #order = new Map<string, Map<string, number>>();
318 readonly #subscribers = new Map<string, Set<(table: RegistryTable<unknown>, codeVersion: number) => void>>();
319 #codeVersionSeq = 1;
320 #rootSeq = 0;
321
322 constructor(options: HostOptions) {
323 this.name = options.name ?? "host";
324 this.dev = options.dev ?? false;
325 if (!("self" in options)) throw new TypeError("createHost needs `self`: the principal of the host's own code");
326 this.principal = options.self;
327 this.#principalKey = options.principalKey ?? canonicalJson;
328 this.#selfKey = this.#principalKey(options.self);
329 this.#onError = options.onError ?? ((error) => console.error("chord:", error));
330 this.#loader = options.loader;
331 this.taskStopDeadline = options.taskStopDeadline ?? 5000;
332 this.readyTimeout = options.readyTimeout ?? 60_000;
333 this.#lingerTypes = options.linger?.types ?? {};
334 this.#lingerCap = options.linger?.cap ?? 4;
335 this.current = {
336 id: this.#codeVersionSeq,
337 services: new Map(),
338 tables: new Map(),
339 roots: new Map(),
340 abort: new AbortController(),
341 };
342 this.codeVersions.set(this.current.id, this.current);
343 this.kind = options.kind ?? "host";
344 if (options.upstream !== undefined) this.connect(options.upstream.link, options.upstream);
345 }
346
347 /** Whether `principal` is the host's own: the same key as `self`. */
348 isSelf(principal: unknown): boolean {
349 return principal === this.principal || this.#principalKey(principal) === this.#selfKey;
350 }
351
352 get codeVersion(): number {
353 return this.current.id;
354 }
355
356 get previousCodeVersion(): number | undefined {
357 return this.previous?.id;
358 }
359
360 /** Allocates the next code version id, or adopts one issued by the coordinating server. */
361 nextCodeVersionId(given?: number): number {
362 if (given !== undefined && given <= this.current.id)
363 throw new Error(`code version ${given} is not newer than ${this.current.id}`);
364 this.#codeVersionSeq = given ?? this.#codeVersionSeq + 1;
365 return this.#codeVersionSeq;
366 }
367
368 report(error: unknown): void {
369 this.#onError(error);
370 }
371
372 // ─── serving ───
373
374 readonly serve: Serve = ((type, factory, options = {}) => {
375 if (this.reloading) throw new Error("host.serve during a reload; serve from a facet passed to reload()");
376 this.serveInto(this.current.services, makeService(type, factory, options, ""));
377 if (options.lifetime === "host") this.startHostObject(this.current.services.get(type.name)!);
378 }) satisfies AnyServe as Serve;
379
380 install(facet: Facet, options: LoadOptions = {}): Promise<void> {
381 if (this.reloading) throw new Error("host.install during a reload");
382 if (this.facets.has(facet.name)) throw new Error(`facet ${facet.name} is already installed; use reload()`);
383 const added: Service[] = [];
384 const run = new AbortController();
385 try {
386 facet.setup(
387 this.facetApi(
388 ((type, factory, options = {}) => {
389 const service = makeService(type, factory, options, facet.name);
390 this.serveInto(this.current.services, service);
391 added.push(service);
392 }) satisfies AnyServe as Serve,
393 run.signal,
394 ),
395 );
396 } catch (error) {
397 run.abort(error);
398 throw error;
399 }
400 this.facets.set(facet.name, facet);
401 this.facetRunChanged(facet.name, run);
402 const refs = added.filter(hostLifetime).map((service) => this.startHostObject(service));
403 return options.awaitHostObjects === false ? Promise.resolve() : this.#hostObjectsReady(refs);
404 }
405
406 async load(plugins: readonly PluginRef[], options: LoadOptions = {}): Promise<void> {
407 const facets = await this.resolve(plugins);
408 // No await between installs: a host object's factory may consume a type served by a later facet.
409 await Promise.all(facets.map((facet) => this.install(facet, options)));
410 }
411
412 ready(): Promise<void> {
413 return this.#hostObjectsReady(this.hostObjects.values());
414 }
415
416 #hostObjectsReady(refs: Iterable<RefCore>): Promise<void> {
417 const ready = Promise.all([...refs].map((ref) => ref.ready)).then(() => {});
418 // Ignoring install's return still reports through onError without an unhandled rejection.
419 ready.catch(() => {});
420 return ready;
421 }
422
423 /** Turns plugin references into facets, importing modules through the loader. */
424 async resolve(plugins: readonly PluginRef[]): Promise<Facet[]> {
425 const modules = plugins.filter((ref): ref is string | URL => !isFacet(ref));
426 if (modules.length > 0 && this.#loader === undefined) {
427 throw new Error(
428 "loading modules needs createHost({ loader }), e.g. nodeLoader from @earendil-works/chord/node",
429 );
430 }
431 const loaded = modules.length > 0 && this.#loader !== undefined ? await this.#loader(modules) : [];
432 return plugins.map((ref) => (isFacet(ref) ? ref : loaded.shift()!));
433 }
434
435 facetApi(serve: Serve, signal: AbortSignal): FacetApi {
436 return {
437 serve,
438 name: this.name,
439 root: (fn, options) => this.root(fn, options),
440 registry: (registry) => this.registry(registry),
441 signal,
442 };
443 }
444
445 /** The installed run of facet `name` is now `run` (or none): the run it replaces is aborted. */
446 facetRunChanged(name: string, run: AbortController | undefined): void {
447 const replaced = this.#facetRuns.get(name);
448 if (run === undefined) this.#facetRuns.delete(name);
449 else this.#facetRuns.set(name, run);
450 if (replaced !== run) replaced?.abort(new ChordError("gone", `facet ${name} was replaced or removed`));
451 }
452
453 serveInto(services: Map<string, Service>, service: Service): void {
454 if (services.has(service.contract.name)) throw new Error(`${service.contract.name} is already served`);
455 const placement = service.contract.description.host;
456 if (placement !== undefined && !placedOn(placement, this.name)) {
457 throw new TypeError(
458 `${service.contract.name} is declared for ${placementText(placement)}, but ${this.name} serves it`,
459 );
460 }
461 services.set(service.contract.name, service);
462 }
463
464 startHostObject(service: Service): RefCore {
465 const ref = this.acquire(service.contract, {}, undefined, "host");
466 this.hostObjects.set(service.contract.name, ref);
467 ref.ready.catch((error: unknown) => this.report(error));
468 return ref;
469 }
470
471 // ─── HostCore ───
472
473 currentCodeVersion(): number {
474 return this.current.id;
475 }
476
477 hasCodeVersion(codeVersion: number): boolean {
478 return this.codeVersions.has(codeVersion);
479 }
480
481 *retainedCodeVersions(): Iterable<readonly [number, ReadonlyMap<string, Service>]> {
482 for (const [id, state] of this.codeVersions) yield [id, state.services];
483 if (this.pending !== undefined) yield [this.pending.id, this.pending.services];
484 }
485
486 pendingCodeVersion(): number | undefined {
487 return this.pending?.id;
488 }
489
490 /** The current code for a type; a type a running reload adds is served from the pending code version. */
491 service(typeName: string): Service | undefined {
492 return this.current.services.get(typeName) ?? this.pending?.services.get(typeName);
493 }
494
495 addressOf(type: AnyContract, input: unknown, principal: unknown, candidate = false): string {
496 const elsewhere = this.#elsewhere(type, input);
497 if (elsewhere !== undefined) return this.#remoteKey(type, elsewhere.input, principal);
498 const service = this.#bindingService(type.name, candidate);
499 if (service === undefined) throw unknownType(type.name, this.name);
500 return this.#locate(service, input, principal).address;
501 }
502
503 /**
504 * Where an object of a remote type lives when that is another host: its name and the input normalized with the
505 * caller's contract (the placement is read from it). `undefined`: here (and every local type).
506 */
507 #elsewhere(type: AnyContract, input: unknown): { readonly at: string; readonly input: unknown } | undefined {
508 const placement = type.description.host;
509 if (type.scope !== "remote" || placement === undefined) return undefined;
510 const normalized = normalize(type.input, input, `${type.name} input`);
511 const at = resolveHost(type.name, placement, normalized);
512 return at === this.name ? undefined : { at, input: normalized };
513 }
514
515 /**
516 * The address of `input` for `principal`, normalized. A `lifetime: "host"` type has one object: the empty input, for
517 * the host principal, whoever asks; another input is invalid.
518 */
519 #locate(service: Service, input: unknown, principal: unknown) {
520 const { name, input: schema } = service.contract;
521 const normalized = normalize(schema, input, `${name} input`);
522 const identity = canonicalIdentity(schema, normalized);
523 if (hostLifetime(service)) {
524 if (identity !== canonicalIdentity(schema, normalize(schema, {}, `${name} input`)))
525 throw invalid("input", `${name} has lifetime "host": its one object has the empty input`);
526 principal = this.principal;
527 }
528 return { address: `${name}\u0000${identity}\u0000${this.#principalPart(principal)}`, normalized, principal };
529 }
530
531 #principalPart(principal: unknown): string {
532 return this.isSelf(principal) ? "host" : `p:${this.#principalKey(principal)}`;
533 }
534
535 /**
536 * The key of a remote binding: type, input identity (fields equal to their defaults omitted, as for local objects),
537 * principal key and the consumer's contract fingerprint. No host name: the type and the input decide where it lives.
538 */
539 #remoteKey(type: AnyContract, normalized: unknown, principal: unknown): string {
540 const identity = canonicalIdentity(type.input, normalized);
541 return `@${type.name}\u0000${identity}\u0000${this.#principalPart(principal)}\u0000${type.fingerprint}`;
542 }
543
544 acquire(
545 type: AnyContract,
546 input: unknown,
547 options: GetOptions | undefined,
548 owner: RefOwner,
549 from?: ObjectImpl,
550 candidate = false,
551 ): RefCore {
552 const elsewhere = this.#elsewhere(type, input);
553 if (elsewhere !== undefined) return this.#acquireRemote(type, elsewhere.at, elsewhere.input, options, owner);
554 const service = this.#bindingService(type.name, candidate);
555 if (service === undefined) throw unknownType(type.name, this.name);
556 bind(service.contract, service.options.accepts, type);
557 const { address, normalized, principal } = this.#locate(service, input, options?.principal ?? this.principal);
558 // The provider's own placement decides, never where a request says it is going (a client picks that).
559 const placement = service.contract.description.host;
560 if (placement !== undefined && resolveHost(type.name, placement, normalized) !== this.name) {
561 throw invalid(
562 "placement",
563 `${type.name} with this input lives on ${resolveHost(type.name, placement, normalized)}, not ${this.name}`,
564 );
565 }
566 let object = this.objects.get(address);
567 if (from !== undefined && object !== undefined && (object === from || reaches(object, from))) {
568 throw invalid("cycle", `${from.address} -> ${address} would create a ref cycle`);
569 }
570 if (object === undefined) {
571 if (this.gating?.has(type.name)) {
572 throw new ChordError("upgrade_conflict", `${type.name} is being upgraded; retry`, { reason: "gate" });
573 }
574 const dying = this.#dying.get(address);
575 if (dying?.status === "disposed") this.#dying.delete(address);
576 object = new ObjectImpl(this, {
577 address,
578 typeName: type.name,
579 input: normalized,
580 principal,
581 hostLifetime: hostLifetime(service),
582 });
583 this.objects.set(address, object);
584 // A new object for an address still being disposed waits for that cleanup (exclusive resources).
585 object.start(dying?.status === "disposing" ? dying.dispose(false) : undefined);
586 }
587 const ref = new RefImpl(object, type, owner);
588 object.addRef(ref);
589 return ref;
590 }
591
592 forget(object: ObjectImpl): void {
593 if (this.objects.get(object.address) === object) this.objects.delete(object.address);
594 if (object.status === "disposing") this.#dying.set(object.address, object);
595 }
596
597 disposed(object: ObjectImpl): void {
598 if (this.#dying.get(object.address) === object) this.#dying.delete(object.address);
599 }
600
601 touch(rootId: string, object: ObjectImpl): void {
602 let touched = this.#touches.get(rootId);
603 if (touched === undefined) {
604 touched = new Set();
605 this.#touches.set(rootId, touched);
606 }
607 touched.add(object);
608 }
609
610 // ─── roots ───
611
612 async root<T>(fn: (ctx: Ctx) => T | Promise<T>, options: RootOptions = {}): Promise<T> {
613 // The incarnation keeps root ids unique across restarts of a host with the same name.
614 const rootId = `${this.name}#${this.#incarnation}:${++this.#rootSeq}`;
615 this.#local.add(rootId);
616 return this.joinRoot(rootId, options.codeVersion ?? this.current.id, fn, options);
617 }
618
619 /**
620 * Runs `fn` inside root `rootId` of `codeVersion`. A root counts as running here (for retirement) while any of its
621 * calls runs here. A root that started here ends when its last call here settles, even if it went out and came back
622 * over a link meanwhile. A foreign root (started elsewhere, arriving `from` a link) keeps its leases on objects
623 * until every link it came over announced its end (`root_end`) or closed, so its re-entry stays grandfathered.
624 */
625 async joinRoot<T>(
626 rootId: string,
627 codeVersionId: number,
628 fn: (ctx: Ctx) => T | Promise<T>,
629 options: { readonly principal?: unknown; readonly signal?: AbortSignal; readonly from?: Connection } = {},
630 ): Promise<T> {
631 const codeVersion = this.codeVersions.get(codeVersionId);
632 if (codeVersion === undefined) {
633 this.#local.delete(rootId);
634 throw new ChordError("superseded", `code version ${codeVersionId} is not retained by ${this.name}`);
635 }
636 if (options.from !== undefined && !this.#local.has(rootId)) {
637 let links = this.#foreign.get(rootId);
638 if (links === undefined) {
639 links = new Set();
640 this.#foreign.set(rootId, links);
641 }
642 links.add(options.from);
643 }
644 codeVersion.roots.set(rootId, (codeVersion.roots.get(rootId) ?? 0) + 1);
645 const ctx = new CtxImpl(this, {
646 // Forced retirement aborts what still runs on a code version before closing what only it used.
647 signals:
648 options.signal === undefined ? [codeVersion.abort.signal] : [options.signal, codeVersion.abort.signal],
649 rootId,
650 codeVersion: codeVersion.id,
651 principal: options.principal ?? this.principal,
652 });
653 try {
654 return await fn(ctx);
655 } finally {
656 ctx.close();
657 const count = (codeVersion.roots.get(rootId) ?? 1) - 1;
658 if (count > 0) codeVersion.roots.set(rootId, count);
659 else {
660 codeVersion.roots.delete(rootId);
661 if (!this.#foreign.has(rootId)) this.endRoot(rootId);
662 this.maybeRetire();
663 this.#retirementChanged();
664 }
665 }
666 }
667
668 /** Remembers that calls of `rootId` went out on `connection`, which must hear when the root ends. */
669 rootSent(rootId: string, connection: Connection): void {
670 let links = this.#rootLinks.get(rootId);
671 if (links === undefined) {
672 links = new Set();
673 this.#rootLinks.set(rootId, links);
674 }
675 links.add(connection);
676 }
677
678 /** A root ended (here, or announced by its origin): end its leases and tell the links it went out on. */
679 endRoot(rootId: string): void {
680 this.#local.delete(rootId);
681 this.#foreign.delete(rootId);
682 for (const object of this.#touches.get(rootId) ?? []) object.rootEnded(rootId);
683 this.#touches.delete(rootId);
684 for (const connection of this.#rootLinks.get(rootId) ?? []) connection.send({ t: "root_end", rootId });
685 this.#rootLinks.delete(rootId);
686 }
687
688 /**
689 * `from` announced the end of a foreign root (or closed). Honored only if the root came over `from`: a peer cannot
690 * end leases of roots it never carried. The root ends when no link that brought it remains.
691 */
692 foreignRootEnded(rootId: string, from: Connection): void {
693 const links = this.#foreign.get(rootId);
694 if (links === undefined || !links.delete(from) || links.size > 0) return;
695 const running = [...this.codeVersions.values()].some((codeVersion) => codeVersion.roots.has(rootId));
696 // Still running here (a call in flight): the lease ends when it settles.
697 if (running) this.#foreign.delete(rootId);
698 else this.endRoot(rootId);
699 }
700
701 /**
702 * Retires the previous code version once no local roots of it remain. A child also waits for its parent to retire
703 * it: roots span hosts, and an old root on the server may still call in.
704 */
705 maybeRetire(): void {
706 if (this.retirable()) this.retire();
707 }
708
709 /** The previous code version has no roots left here and, on a child host, the parent has retired it. */
710 retirable(): boolean {
711 const previous = this.previous;
712 if (previous === undefined || previous.roots.size > 0) return false;
713 return this.kind === "client" || this.upstream === undefined || previous.id <= this.#retireAllowed;
714 }
715
716 allowRetire(codeVersion: number): void {
717 this.#retireAllowed = Math.max(this.#retireAllowed, codeVersion);
718 this.maybeRetire();
719 this.#retirementChanged();
720 }
721
722 /** Calls `watcher` whenever a root ends, the parent allows a retirement, or a code version retires. */
723 watchRetirement(watcher: () => void): () => void {
724 this.#retirementWatchers.add(watcher);
725 return () => this.#retirementWatchers.delete(watcher);
726 }
727
728 #retirementChanged(): void {
729 for (const watcher of [...this.#retirementWatchers]) watcher();
730 }
731
732 /**
733 * Tells a child that is now in step which code versions this host retired before: every id below the oldest one it
734 * retains (ids only grow). Without it, a child reconciled after those retirements would never hear a `retire` frame for
735 * its own previous code version and would wait for the retire deadline at every reload.
736 */
737 announceRetired(connection: Connection): void {
738 const retired = (this.previous ?? this.current).id - 1;
739 if (retired > 0) connection.send({ t: "retire", codeVersion: retired });
740 }
741
742 /** Drops the previous code version: its implementations and the declarations only it used. */
743 retire(): void {
744 const previous = this.previous;
745 if (previous === undefined) return;
746 this.previous = undefined;
747 this.codeVersions.delete(previous.id);
748 for (const object of [...this.objects.values()]) this.retireImplementation(object, previous.id);
749 for (const connection of this.connections) {
750 if (connection.role === "downstream" && connection.peer?.kind === "host")
751 connection.send({ t: "retire", codeVersion: previous.id });
752 }
753 this.#retirementChanged();
754 }
755
756 /**
757 * Drops an object's implementation for `codeVersion` and what only that implementation declared, in disposal order:
758 * resources close (reverse open order) before its references are released.
759 */
760 retireImplementation(object: ObjectImpl, codeVersion: number): void {
761 const installed = object.implementations.get(codeVersion);
762 object.implementations.delete(codeVersion);
763 if (installed === undefined || installed.decls === object.decls) return;
764 const kept = object.allDecls();
765 const keep = <T>(pick: (decls: Decls) => Iterable<T>): Set<T> =>
766 new Set([...kept].flatMap((decls) => [...pick(decls)]));
767 const refs = keep((decls) => decls.refs.values());
768 const resources = keep((decls) => decls.resources.values());
769 const derives = keep((decls) => decls.derives.values());
770 for (const derived of installed.decls.derives.values()) if (!derives.has(derived)) derived.detach();
771 const closing = [...installed.decls.resources.values()]
772 .filter((resource) => !resources.has(resource))
773 .sort((a, b) => object.openOrder.indexOf(b) - object.openOrder.indexOf(a));
774 const releasing = [...installed.decls.refs.values()].filter((ref) => !refs.has(ref));
775 object.refreshSchemas();
776 runAll(
777 [
778 ...closing.map((resource) => () => resource.close(object.openOrder)),
779 ...releasing.map((ref) => () => ref.release()),
780 ],
781 `${object.address}: retiring code version ${codeVersion} failed`,
782 ).catch((error: unknown) => this.report(error));
783 }
784
785 // ─── registries ───
786
787 registry<V>(registry: Registry<V>): RegistryView<V> {
788 const table = (ctx?: Ctx): RegistryTable<V> => {
789 const codeVersion = ctx === undefined ? this.current : this.codeVersions.get(ctx.codeVersion);
790 if (codeVersion === undefined)
791 throw new ChordError("superseded", `code version ${ctx?.codeVersion} is retired`);
792 return (codeVersion.tables.get(registry.name) ?? EMPTY_TABLE) as RegistryTable<V>;
793 };
794 return {
795 table,
796 get: (key, ctx) => table(ctx).get(key),
797 subscribe: (listener) => {
798 let set = this.#subscribers.get(registry.name);
799 if (set === undefined) {
800 set = new Set();
801 this.#subscribers.set(registry.name, set);
802 }
803 const wrapped = listener as (table: RegistryTable<unknown>, codeVersion: number) => void;
804 set.add(wrapped);
805 wrapped(table(), this.current.id);
806 return () => set.delete(wrapped);
807 },
808 };
809 }
810
811 /** Builds registry tables from (object, declarations) pairs. Throws registry_conflict. */
812 buildTables(entries: Iterable<readonly [ObjectImpl, Decls]>): Map<string, RegistryTable<unknown>> {
813 const byRegistry = new Map<string, Map<string, { value: unknown; object: ObjectImpl }>>();
814 for (const [object, decls] of entries) {
815 for (const { registry, key, value } of decls.registrations.values()) {
816 let entries = byRegistry.get(registry.name);
817 if (entries === undefined) {
818 entries = new Map();
819 byRegistry.set(registry.name, entries);
820 }
821 const existing = entries.get(key);
822 if (existing !== undefined && existing.object !== object && registry.conflict === "error") {
823 throw invalid(
824 "registry_conflict",
825 `${registry.name}: ${key} registered by ${existing.object.address} and ${object.address}`,
826 );
827 }
828 entries.set(key, { value, object });
829 let order = this.#order.get(registry.name);
830 if (order === undefined) {
831 order = new Map();
832 this.#order.set(registry.name, order);
833 }
834 if (!order.has(key)) order.set(key, order.size);
835 }
836 }
837 const tables = new Map<string, RegistryTable<unknown>>();
838 for (const [name, entries] of byRegistry) {
839 const order = this.#order.get(name)!;
840 const sorted = [...entries].sort(([a], [b]) => order.get(a)! - order.get(b)!);
841 tables.set(name, new Map(sorted.map(([key, entry]) => [key, entry.value])));
842 }
843 return tables;
844 }
845
846 /**
847 * The service a reference binds against: the current one, or for a prepare rerun (`candidate`) the running reload's
848 * pending one, so consumer and provider of a breaking change can reload in one batch.
849 */
850 #bindingService(typeName: string, candidate: boolean): Service | undefined {
851 return (candidate ? this.pending?.services.get(typeName) : undefined) ?? this.service(typeName);
852 }
853
854 /** Live objects with their current declarations; objects waiting for a reload's commit only with `candidates`. */
855 liveDecls(candidates = false): [ObjectImpl, Decls][] {
856 return [...this.objects.values()]
857 .filter((object) => object.status === "live" && (candidates || !object.deferredRuntime))
858 .map((object) => [object, object.decls]);
859 }
860
861 checkRegistrations(object: ObjectImpl, decls: Decls): void {
862 if (decls.registrations.size === 0) return;
863 this.buildTables([...this.liveDecls().filter(([other]) => other !== object), [object, decls]]);
864 }
865
866 registriesChanged(including?: ObjectImpl): void {
867 const entries = this.liveDecls().filter(([object]) => object !== including);
868 if (including !== undefined) entries.push([including, including.decls]);
869 this.installTables(this.current, this.buildTables(entries));
870 }
871
872 /** A commit failed midway: from now on this host admits no work (calls fail `unavailable/host_failed`). */
873 fail(error: unknown): void {
874 this.failed ??= error;
875 this.report(error);
876 }
877
878 /** Installs tables for `codeVersion`; subscribers hear about changed tables of the current code version (all tables when `all`). */
879 installTables(codeVersion: CodeVersionState, tables: Map<string, RegistryTable<unknown>>, all = false): void {
880 const before = codeVersion.tables;
881 codeVersion.tables = tables;
882 if (codeVersion !== this.current) return;
883 for (const [name, listeners] of this.#subscribers) {
884 const next = tables.get(name) ?? EMPTY_TABLE;
885 if (!all && sameTable(before.get(name) ?? EMPTY_TABLE, next)) continue;
886 const current = [...listeners];
887 enqueue(() => {
888 for (const listener of current) {
889 try {
890 listener(next, codeVersion.id);
891 } catch (error) {
892 this.report(error);
893 }
894 }
895 });
896 }
897 }
898
899 // ─── public API ───
900
901 async get<C extends AnyContract>(
902 type: C,
903 input: InputOf<C>,
904 options?: GetOptions & { readonly signal?: AbortSignal },
905 ): Promise<Ref<C>> {
906 const ref = this.acquire(type, input, options, "external");
907 await awaitReady(ref, options?.signal === undefined ? [] : [options.signal], this.readyTimeout);
908 return ref.proxy as Ref<C>;
909 }
910
911 hold<C extends AnyContract>(type: C, input: InputOf<C>, options?: GetOptions): Ref<C> {
912 return this.acquire(type, input, options, "external").proxy as Ref<C>;
913 }
914
915 async invalidatePrincipal(match: PrincipalMatch): Promise<void> {
916 const matches = typeof match === "function" ? match : (principal: unknown) => matchesPattern(match, principal);
917 const reason = new ChordError("gone", "principal invalidated");
918 // Links acting as a matching principal are re-stamped (if the acceptor can) or closed.
919 for (const connection of [...this.connections]) {
920 if (connection.role !== "downstream" || !matches(connection.principal)) continue;
921 // Relays under the old principal close at once, including those still resolving their route.
922 connection.revoke(connection.restamp?.(connection.principal));
923 }
924 // Patterns propagate to child hosts, which dispose their own matching objects (e.g. relayed guests).
925 if (typeof match !== "function") {
926 for (const connection of this.connections) {
927 if (connection.role === "downstream" && connection.peer.kind === "host") {
928 connection.send({ t: "invalidate", pattern: match });
929 }
930 }
931 }
932 const matching = [...this.objects.values()].filter(
933 (object) => !this.isSelf(object.principal) && matches(object.principal),
934 );
935 await disposeHoldersFirst(matching, reason, "invalidatePrincipal: disposal failed");
936 }
937
938 // ─── links ───
939
940 accept(link: Link, options: AcceptOptions): void {
941 const kind = options.kind ?? "client";
942 if (kind === "host" && options.name === undefined) throw new TypeError("accepting a host link needs its name");
943 this.#addConnection(link, {
944 ...options,
945 role: "downstream",
946 principal: options.principal,
947 peer: { kind, name: kind === "host" ? options.name : undefined },
948 // Holds over a client link carry its id as their origin (also when relayed), so hosts can tell clients apart.
949 ...(kind === "client" ? { originId: `${this.#incarnation}:${++this.#originSeq}` } : {}),
950 });
951 }
952
953 connect(link: Link, options: ConnectOptions): void {
954 if (!("principal" in options))
955 throw new TypeError("connect needs `principal`: what the parent's own requests act as");
956 if (this.upstream?.open) this.upstream.link.close("replaced");
957 const connection = this.#addConnection(link, {
958 ...options,
959 role: "upstream",
960 principal: options.principal,
961 peer: { kind: "host", name: undefined },
962 });
963 this.upstream = connection;
964 // Bindings that lost their link re-hold over the new one (`again`: they keep their values meanwhile).
965 for (const binding of this.bindings.values())
966 if (binding.hold === undefined && !binding.ended) connection.hold(binding, binding.applied);
967 }
968
969 #addConnection(link: Link, config: ConstructorParameters<typeof Connection>[2]): Connection {
970 const connection = new Connection(this, link, config);
971 // A link that was already closed closed the connection in its constructor: keeping it would route to it forever.
972 if (connection.open) this.connections.add(connection);
973 return connection;
974 }
975
976 route(prefix: string, route: Route): void {
977 if (typeof route.principal !== "function")
978 throw new TypeError(`route ${prefix} needs \`principal\`: what the routed hosts act as when they call back`);
979 this.#routes.set(prefix, route);
980 }
981
982 /**
983 * A child host announced its code version. In step: usable. Behind: fenced (nothing is routed to it) and reconciled
984 * by a reload of its modules to this host's code version, never by renumbering what it runs. Ahead: impossible,
985 * refused.
986 */
987 peerHello(connection: Connection, codeVersion: number): void {
988 if (codeVersion > this.current.id) {
989 this.report(
990 new ChordError(
991 "invalid",
992 `${connection.name} runs code version ${codeVersion}, ahead of ${this.current.id}`,
993 ),
994 );
995 connection.link.close("code version ahead of parent");
996 return;
997 }
998 if (this.reloading) {
999 // Not a participant of the running reload (participants are fixed when it starts): in step now, it would miss
1000 // the commit. Decided when the reload ends. A child already behind is fenced now, so the calls its roots make
1001 // meanwhile are admitted in this host's code version (never relabeled) instead of being `superseded`.
1002 connection.peerCodeVersion = codeVersion;
1003 if (codeVersion < this.current.id) connection.fencedCodeVersions.add(codeVersion);
1004 this.#deferredHellos.set(connection, codeVersion);
1005 return;
1006 }
1007 if (codeVersion === this.current.id) {
1008 connection.markSynced(codeVersion);
1009 this.announceRetired(connection);
1010 return;
1011 }
1012 connection.peerCodeVersion = codeVersion;
1013 connection.fencedCodeVersions.add(codeVersion);
1014 reconcileChild(this, connection).catch((error: unknown) => {
1015 this.report(error);
1016 connection.link.close("reconciliation failed");
1017 });
1018 }
1019
1020 /** The host's reload slot was freed: children that said hello meanwhile are synced or reconciled now. */
1021 reloadEnded(): void {
1022 this.reloading = false;
1023 const deferred = [...this.#deferredHellos];
1024 this.#deferredHellos.clear();
1025 for (const [connection, codeVersion] of deferred) if (connection.open) this.peerHello(connection, codeVersion);
1026 for (const resolve of this.#reloadWaiters.splice(0)) resolve();
1027 this.maybeRetire();
1028 }
1029
1030 /** Resolves once no reload runs on this host. */
1031 whenReloadEnded(): Promise<void> {
1032 if (!this.reloading) return Promise.resolve();
1033 return new Promise((resolve) => this.#reloadWaiters.push(resolve));
1034 }
1035
1036 connectionClosed(connection: Connection): void {
1037 this.connections.delete(connection);
1038 this.#deferredHellos.delete(connection);
1039 // Foreign roots that came over this link will never announce their end over it.
1040 for (const [rootId, links] of [...this.#foreign])
1041 if (links.has(connection)) this.foreignRootEnded(rootId, connection);
1042 for (const links of this.#rootLinks.values()) links.delete(connection);
1043 if (this.upstream === connection) {
1044 this.upstream = undefined;
1045 this.#childReloads.parentLost();
1046 }
1047 }
1048
1049 /** The last reference to `binding` was released: it lingers if its type does (`HostOptions.linger`), else closes. */
1050 bindingIdle(binding: RemoteBinding): void {
1051 const ms = Object.hasOwn(this.#lingerTypes, binding.contract.name)
1052 ? this.#lingerTypes[binding.contract.name]!
1053 : 0;
1054 // A binding that never had a shape has nothing worth keeping.
1055 if (ms <= 0 || binding.ended || !binding.applied || this.#lingerCap <= 0) {
1056 binding.close();
1057 return;
1058 }
1059 binding.lingerTimer = setTimeout(() => binding.close(), ms);
1060 (binding.lingerTimer as { unref?: () => void }).unref?.();
1061 this.#lingering.set(binding.key, binding);
1062 for (const oldest of this.#lingering.values()) {
1063 if (this.#lingering.size <= this.#lingerCap) break;
1064 oldest.close();
1065 }
1066 }
1067
1068 forgetBinding(binding: RemoteBinding): void {
1069 if (this.bindings.get(binding.key) === binding) this.bindings.delete(binding.key);
1070 if (this.#lingering.get(binding.key) === binding) this.#lingering.delete(binding.key);
1071 }
1072
1073 /** A downstream host connection by its configured name (never by what a peer announced). */
1074 #childNamed(name: string): Connection | undefined {
1075 return [...this.connections].find(
1076 (connection) =>
1077 connection.open &&
1078 connection.role === "downstream" &&
1079 connection.peer.kind === "host" &&
1080 connection.peer.name === name,
1081 );
1082 }
1083
1084 /**
1085 * A reference to an object on host `at`: a view onto the binding for its key, created (and held) if there is none.
1086 * `input` is normalized with `type` (the hold carries it so).
1087 */
1088 #acquireRemote(
1089 type: AnyContract,
1090 at: string,
1091 input: unknown,
1092 options: GetOptions | undefined,
1093 owner: RefOwner,
1094 ): RefCore {
1095 const principal =
1096 options?.principal === undefined || this.isSelf(options.principal) ? undefined : options.principal;
1097 const key = this.#remoteKey(type, input, principal ?? this.principal);
1098 let binding = this.bindings.get(key);
1099 const fresh = binding === undefined || binding.ended;
1100 if (binding === undefined || binding.ended) {
1101 binding = new RemoteBinding(this, { key, contract: type, at, input, principal });
1102 this.bindings.set(key, binding);
1103 }
1104 const ref = new RemoteRef(binding, owner, options?.state !== false);
1105 this.#lingering.delete(key);
1106 binding.addView(ref);
1107 if (fresh) this.#hold(binding);
1108 return ref;
1109 }
1110
1111 /** Holds `binding` over the link to its host: the parent's, a child's, or one a route resolves. */
1112 #hold(binding: RemoteBinding): void {
1113 const bindWhenSynced = (connection: Promise<Connection>): void => {
1114 connection.then(
1115 (target) => {
1116 if (!binding.ended && binding.hold === undefined) target.hold(binding, false);
1117 },
1118 (error: unknown) => binding.gone(error),
1119 );
1120 };
1121 const direct = this.#childNamed(binding.at);
1122 if (this.upstream !== undefined) this.upstream.hold(binding, false);
1123 else if (direct !== undefined) bindWhenSynced(direct.whenSynced().then(() => direct));
1124 else {
1125 const route = this.#routeFor(binding.at);
1126 if (route === undefined) binding.gone(new ChordError("unavailable", `no route to ${binding.at}`));
1127 else bindWhenSynced(this.#resolve(route, binding.at, binding.principal ?? this.principal));
1128 }
1129 }
1130
1131 #routeFor(hostName: string): Route | undefined {
1132 let best: [string, Route] | undefined;
1133 for (const entry of this.#routes) {
1134 if (hostName.startsWith(entry[0]) && (best === undefined || entry[0].length > best[0].length)) best = entry;
1135 }
1136 return best?.[1];
1137 }
1138
1139 /** Authorize, resolve (maybe spawn), authorize again; returns the synced connection to the host. */
1140 async #resolve(
1141 route: Route,
1142 hostName: string,
1143 principal: unknown,
1144 still: () => boolean = () => true,
1145 ): Promise<Connection> {
1146 const refuse = (): ChordError => new ChordError("forbidden", `${hostName} refused for this principal`);
1147 const revoked = (): ChordError => new ChordError("gone", "principal invalidated while resolving");
1148 if (!(await route.authorize(principal, hostName))) throw refuse();
1149 if (!still()) throw revoked();
1150 const link = await route.resolve(hostName);
1151 if (!still()) throw revoked();
1152 if (!(await route.authorize(principal, hostName))) throw refuse();
1153 if (!still()) throw revoked();
1154 let connection = [...this.connections].find((candidate) => candidate.link === link);
1155 connection ??= this.#addConnection(link, {
1156 role: "downstream",
1157 principal: route.principal(hostName),
1158 peer: { kind: "host", name: hostName },
1159 });
1160 await connection.whenSynced();
1161 if (!still()) throw revoked();
1162 return connection;
1163 }
1164
1165 /**
1166 * Relays a reference from `relay.origin` to the host it names. Relaying needs a route: it is where authorization
1167 * lives. The origin's authorization generation is re-checked after every await and right before forwarding, so a
1168 * revocation during resolution wins.
1169 */
1170 async relay(relay: RelayRef): Promise<void> {
1171 const at = relay.frame.at;
1172 // The hold names its target; its contract token says where the type lives. They must agree.
1173 const placement = contractFromDescription(relay.frame.token).description.host;
1174 if (placement === undefined || resolveHost(relay.frame.token.name, placement, relay.frame.input) !== at)
1175 throw invalid("placement", `${relay.frame.token.name} with this input does not live on ${at}`);
1176 const route = this.#routeFor(at);
1177 if (route === undefined) {
1178 throw this.#childNamed(at) === undefined
1179 ? new ChordError("unavailable", `no route to ${at}`)
1180 : new ChordError("forbidden", `no route authorizes ${at}`);
1181 }
1182 const down = await this.#resolve(route, at, relay.principal, () => relay.current);
1183 if (!relay.current) return;
1184 relay.open(down);
1185 }
1186
1187 reload(plugins: readonly PluginRef[], options: ReloadOptions = {}): Promise<ReloadReport> {
1188 // Client-local facet code versions never cross the parent link; only child hosts require cluster coordination.
1189 if (this.kind !== "client" && this.upstream !== undefined) {
1190 return Promise.reject(
1191 new ChordError("unavailable", "reloads are coordinated by the server", { reason: "not_coordinator" }),
1192 );
1193 }
1194 const children = [...this.connections].some(
1195 (connection) => connection.role === "downstream" && connection.peer.kind === "host",
1196 );
1197 return children || options.remote !== undefined || options.remoteRemove !== undefined
1198 ? runClusterReload(this, plugins, options)
1199 : runReload(this, plugins, options);
1200 }
1201
1202 onReloadFrame(connection: Connection, frame: Extract<Frame, { t: "prepare" | "commit" | "abort" }>): void {
1203 this.#childReloads.handle(connection, frame);
1204 }
1205
1206 rememberRemoteModules(
1207 remote: Readonly<Record<string, readonly string[]>> | undefined,
1208 remove: Readonly<Record<string, readonly string[]>> | undefined,
1209 ): void {
1210 for (const prefix of new Set([...Object.keys(remote ?? {}), ...Object.keys(remove ?? {})])) {
1211 const modules = remote?.[prefix] ?? [];
1212 const removed = remove?.[prefix] ?? [];
1213 this.remoteModules[prefix] = [...new Set([...(this.remoteModules[prefix] ?? []), ...modules])].filter(
1214 (module) => !removed.includes(module),
1215 );
1216 this.remoteRemoved[prefix] = [...new Set([...(this.remoteRemoved[prefix] ?? []), ...removed])].filter(
1217 (module) => !modules.includes(module),
1218 );
1219 }
1220 }
1221
1222 /** The code version id the next reload would commit. */
1223 peekNextCodeVersion(): number {
1224 return this.#codeVersionSeq + 1;
1225 }
1226
1227 /**
1228 * Disposes every object, holders before what they reference (a resource's `close` may still use the objects its object
1229 * references, local or remote), then closes the links.
1230 */
1231 async close(): Promise<void> {
1232 for (const binding of [...this.#lingering.values()]) binding.close();
1233 this.hostObjects.clear();
1234 for (const name of [...this.#facetRuns.keys()]) this.facetRunChanged(name, undefined);
1235 const reason = new ChordError("gone", `host ${this.name} closed`);
1236 try {
1237 await disposeHoldersFirst([...this.objects.values()], reason, "host close: disposal failed");
1238 } finally {
1239 for (const connection of [...this.connections]) connection.link.close("host closed");
1240 }
1241 }
1242}
1243
1244/**
1245 * Force-disposes `objects` in waves: an object goes once no object of the set that references it is left, so holders are
1246 * disposed (and their resources closed) while what they reference is still live. In-host references are acyclic. Errors of
1247 * every disposal are collected.
1248 */
1249async function disposeHoldersFirst(objects: readonly ObjectImpl[], reason: unknown, message: string): Promise<void> {
1250 const remaining = new Set(objects);
1251 const held = (object: ObjectImpl): Set<ObjectImpl> => {
1252 const result = new Set<ObjectImpl>();
1253 for (const decls of object.allDecls()) {
1254 for (const ref of decls.refs.values()) if (ref.object !== undefined) result.add(ref.object);
1255 }
1256 return result;
1257 };
1258 const refs = new Map(objects.map((object) => [object, held(object)] as const));
1259 const errors: unknown[] = [];
1260 while (remaining.size > 0) {
1261 const heldByRemaining = new Set<ObjectImpl>();
1262 for (const object of remaining) for (const target of refs.get(object) ?? []) heldByRemaining.add(target);
1263 let wave = [...remaining].filter((object) => !heldByRemaining.has(object));
1264 // A cycle cannot happen in-host; dispose the rest together rather than loop.
1265 if (wave.length === 0) wave = [...remaining];
1266 for (const object of wave) remaining.delete(object);
1267 const results = await Promise.allSettled(wave.map((object) => object.dispose(true, reason)));
1268 for (const result of results) if (result.status === "rejected") errors.push(result.reason);
1269 }
1270 if (errors.length === 1) throw errors[0];
1271 if (errors.length > 1) throw new AggregateError(errors, message);
1272}
1273
1274function sameTable(a: RegistryTable<unknown>, b: RegistryTable<unknown>): boolean {
1275 if (a.size !== b.size) return false;
1276 const keys = [...a.keys()];
1277 return [...b].every(([key, value], index) => keys[index] === key && a.get(key) === value);
1278}
1279
1280const matchesPattern = (pattern: Readonly<Record<string, unknown>>, principal: unknown): boolean =>
1281 principal !== null &&
1282 typeof principal === "object" &&
1283 Object.entries(pattern).every(([key, value]) => deepEqual((principal as Record<string, unknown>)[key], value));
1284
1285const unknownType = (type: string, host: string): ChordError =>
1286 new ChordError("unavailable", `${type} is not served by ${host}`, { reason: "unknown_type" });
1287
1288/** True if `from` references `to`, directly or transitively, through object-owned references on this host. */
1289function reaches(from: ObjectImpl, to: ObjectImpl): boolean {
1290 const seen = new Set<ObjectImpl>();
1291 const stack = [from];
1292 while (stack.length > 0) {
1293 const object = stack.pop()!;
1294 if (object === to) return true;
1295 if (seen.has(object)) continue;
1296 seen.add(object);
1297 // Remote references have no object here: cycles across hosts are avoided by convention.
1298 for (const decls of object.allDecls()) {
1299 for (const ref of decls.refs.values()) if (ref.object !== undefined) stack.push(ref.object);
1300 }
1301 }
1302 return false;
1303}