1
import type { Cell } from "./cell.ts";2
import { type AnyContract, bind, coverage } from "./contract.ts";3
import { asChordError, ChordError, invalid, isChordError } from "./errors.ts";4
import type { CodeVersionState, Facet, HostImpl, PluginRef, Serve } from "./host.ts";5
import {6
type Factory,7
hostLifetime,8
makeService,9
memberSchemas,10
type ObjectImpl,11
RefImpl,12
type ResourceImpl,13
type Run,14
type ServeOptions,15
type Service,16
type StagedListeners,17
} from "./object.ts";18
import { holdPublications } from "./publish.ts";19
import type { RegistryTable } from "./registry.ts";20
import { assertValid, deepEqual } from "./schema.ts";21
import type { Readable } from "./types.ts";23
export interface ReloadOptions {24
/** Facet names to remove. */25
readonly remove?: readonly string[];26
/** Milliseconds the gate waits for grandfathered roots (default 5000). Missed: the reload aborts. */27
readonly gateDeadline?: number;28
/** Milliseconds to wait for the previous code version to retire first (default 5000). Missed: it is retired anyway. */29
readonly retireDeadline?: number;30
/** Server: facet modules for child hosts by host-name prefix (longest wins). Every connected host participates. */31
readonly remote?: Readonly<Record<string, readonly string[]>>;32
/** Server: facet names to remove on child hosts, by the same host-name prefix rules. */33
readonly remoteRemove?: Readonly<Record<string, readonly string[]>>;34
/** Server: milliseconds to wait for every child's vote (default: gate + retire deadlines + 5000). */35
readonly voteDeadline?: number;36
}38
export interface ReloadReport {39
readonly codeVersion: number;40
readonly previous: number;41
readonly changed: readonly string[];42
readonly removed: readonly string[];43
/** Addresses of objects whose new factory was installed. */44
readonly prepared: readonly string[];45
/** Addresses of objects that went through the gate. */46
readonly gated: readonly string[];47
/**48
* Cluster reloads: what each participating child host prepared, by host name (its vote; the child commits it after49
* the server). Absent for local reloads.50
*/51
readonly children?: Readonly<Record<string, ReloadReport>>;52
}54
interface Candidate {55
readonly object: ObjectImpl;56
readonly service: Service;57
readonly run: Run;58
/** Why the object needs the gate (empty: compatible). */59
readonly reasons: string[];60
/** New exclusive resources and their new dependents, opened at the gate. */61
readonly atGate: ResourceImpl[];62
/** Old exclusive resources closed at the gate. */63
readonly replaced: ResourceImpl[];64
readonly migrated: Map<Cell<unknown>, unknown>;65
/** Values of the run's derivations over the candidate (migrated) values, validated. */66
derived: Map<unknown, unknown>;67
/** Listener subscriptions made at the end of prepare, activated by the commit. */68
staged: StagedListeners | undefined;69
}71
/**72
* Computes the new derivation functions over the candidate values and validates every prospective value (migrated73
* cells and derivations) against every schema that will apply after the commit: the cell's new schema and the new74
* implementation's remote state-member schemas. A failure fails prepare; the commit then installs without re-checking.75
*/76
function dryRun(candidate: Candidate): void {77
const { run, migrated, service, object } = candidate;78
const exposed = memberSchemas(service, run.implementation);79
for (const [cell, value] of migrated) {80
for (const schema of exposed.get(cell) ?? [])81
assertValid("state", `${object.address}: migrated state ${cell.key}`, schema, value);82
}83
const values = new Map<unknown, unknown>(migrated);84
const derives = [...run.decls.derives].sort(([, a], [, b]) => a.seq - b.seq);85
for (const [name, derived] of derives) {86
const value = derived.compute((source) => (values.has(source) ? values.get(source) : candidateValue(source)));87
for (const schema of exposed.get(derived) ?? [])88
assertValid("state", `${object.address}: derivation ${name}`, schema, value);89
values.set(derived, value);90
}91
candidate.derived = values;92
}94
/**95
* A source's value for a dry run. A reference to a provider this reload upgrades too reads nothing before the commit96
* (its new contract does not bind the old code): the dry run computes without it, the commit with the real value.97
*/98
function candidateValue(source: Readable<unknown>): unknown {99
try {100
return source.value;101
} catch (error) {102
if (isChordError(error, "not_ready") || isChordError(error, "not_in_variant")) return undefined;103
throw error;104
}105
}107
/** A reload error keeps the underlying code (`contract_mismatch`, `invalid`, ...) and says it aborted the reload. */108
export function reloadError(error: unknown): ChordError {109
const cause = asChordError(error, "reload");110
if (/^reload aborted/.test(cause.message.replace(/^[^:]*: /, ""))) return cause;111
return new ChordError(cause.code, `reload aborted: ${cause.message}`, {112
cause,113
reason: cause.reason,114
details: cause.details,115
});116
}118
/** Serialized: a second reload while one runs is rejected. */119
export async function runReload(120
host: HostImpl,121
plugins: readonly PluginRef[],122
options: ReloadOptions,123
): Promise<ReloadReport> {124
const reload = await beginReload(host, plugins, options);125
try {126
await reload.prepare();127
return reload.commit();128
} finally {129
endReload(host);130
}131
}133
/** Takes the host's reload slot and loads the plugin modules. Pair with `endReload`. */134
export async function beginReload(135
host: HostImpl,136
plugins: readonly PluginRef[],137
options: ReloadOptions,138
codeVersion?: number,139
): Promise<Reload> {140
if (host.reloading) {141
throw new ChordError("unavailable", "a reload is already running", { reason: "reload_running" });142
}143
host.reloading = true;144
try {145
return new Reload(host, await host.resolve(plugins), options, codeVersion);146
} catch (error) {147
host.reloadEnded();148
throw reloadError(error);149
}150
}152
export function endReload(host: HostImpl): void {153
host.reloadEnded();154
}156
/** Most milliseconds a forced retirement waits for aborted roots to settle before it closes what they used. */157
const ABORTED_ROOTS_GRACE = 1000;159
/** Resolves true once `ready()` holds (checked whenever retirement-relevant state changes), false after `ms`. */160
function until(host: HostImpl, ready: () => boolean, ms: number): Promise<boolean> {161
if (ready()) return Promise.resolve(true);162
return new Promise<boolean>((resolve) => {163
const timer = setTimeout(() => {164
stop();165
resolve(false);166
}, ms);167
const stop = host.watchRetirement(() => {168
if (!ready()) return;169
clearTimeout(timer);170
stop();171
resolve(true);172
});173
});174
}176
/** One reload on one host: `prepare` (load, prepare, gate), then `commit` or `rollback`. */177
export class Reload {178
readonly host: HostImpl;179
readonly facets: readonly Facet[];180
readonly options: ReloadOptions;181
/** Code version id to commit (issued by the coordinating server); a local reload allocates one. */182
readonly codeVersion: number | undefined;183
readonly candidates = new Map<ObjectImpl, Candidate>();184
readonly abort = new AbortController();185
readonly closed: [ObjectImpl, ResourceImpl][] = [];186
services = new Map<string, Service>();187
changed = new Set<string>();188
removed = new Set<string>();189
tables = new Map<string, RegistryTable<unknown>>();190
gated: Candidate[] = [];191
rolledBack = false;192
/** Objects of types this reload adds, with their staged listeners: their runtime starts at commit. */193
readonly deferred = new Map<ObjectImpl, StagedListeners>();194
/** This reload's run of each facet it loads (`FacetApi.signal`): installed at commit, aborted at rollback. */195
readonly facetRuns = new Map<string, AbortController>();197
constructor(host: HostImpl, facets: readonly Facet[], options: ReloadOptions, codeVersion?: number) {198
this.host = host;199
this.facets = facets;200
this.options = options;201
this.codeVersion = codeVersion;202
}204
/** Everything up to the commit. On failure the host is rolled back and the underlying error is thrown. */205
async prepare(): Promise<void> {206
try {207
await this.waitForRetirement();208
this.load();209
this.checkProviders();210
await this.prepareAll();211
// From here new objects of changed types are rejected (upgrade_conflict, retryable) until commit or abort,212
// so the candidate set is final once the activations already in flight have been prepared.213
this.host.gating = this.changed;214
await this.withDeadline(this.prepareAll(), "activations in flight did not finish");215
this.checkRefs();216
this.tables = this.host.buildTables(this.entries());217
await this.gate();218
this.#alive();219
this.#stage();220
} catch (error) {221
await this.rollback();222
throw reloadError(error);223
}224
}226
/** What a successful prepare will commit (a child sends it with its vote). */227
summary(): ReloadReport {228
const live = [...this.candidates.values()].filter(({ object }) => object.status === "live");229
return {230
codeVersion: this.host.pending?.id ?? this.host.current.id,231
previous: this.host.current.id,232
changed: [...this.changed],233
removed: [...this.removed],234
prepared: live.map(({ object }) => object.address),235
gated: this.gated.map(({ object }) => object.address),236
};237
}239
/** After every await of prepare: a rollback meanwhile (abort from the coordinator) ends it. */240
#alive(): void {241
if (this.rolledBack) throw new ChordError("aborted", "reload aborted while preparing", { reason: "aborted" });242
}244
/**245
* Subscribes every new listener now, buffering its events, so a failing source fails prepare instead of leaving a246
* half-installed code version. Objects running only the new code (types this reload adds) are staged too.247
*/248
#stage(): void {249
for (const candidate of this.candidates.values()) {250
if (candidate.object.status === "live")251
candidate.staged = candidate.object.stageListeners(candidate.run.decls);252
}253
for (const object of this.host.objects.values()) {254
if (object.status === "live" && object.deferredRuntime)255
this.deferred.set(object, object.stageListeners(object.decls));256
}257
}259
/**260
* Retires the previous code version before loading the next one (a host keeps two). Waits until its roots ended and,261
* on a child host, its parent retired it too (`retire` frame), at most `retireDeadline`. Past the deadline it is262
* retired anyway: its remaining roots are aborted first and get a short grace to stop, so they see cancellation263
* before the resources only that code version used are closed; their next call is `superseded`.264
*/265
async waitForRetirement(): Promise<void> {266
const host = this.host;267
const previous = host.previous;268
if (previous === undefined) return;269
const deadline = this.options.retireDeadline ?? 5000;270
const gone = (): boolean => host.previous !== previous;271
if (!(await until(host, () => gone() || host.retirable(), deadline)) && !gone()) {272
previous.abort.abort(new ChordError("superseded", `code version ${previous.id} was retired`));273
await until(host, () => gone() || previous.roots.size === 0, Math.min(deadline, ABORTED_ROOTS_GRACE));274
}275
if (!gone()) host.retire();276
}278
/** Builds the candidate service table: unchanged services plus everything the given facets serve. */279
load(): void {280
const replaced = new Set([...this.facets.map((facet) => facet.name), ...(this.options.remove ?? [])]);281
const current = this.host.current.services;282
this.services = new Map([...current].filter(([, service]) => !replaced.has(service.facet)));283
for (const facet of this.facets) {284
const run = new AbortController();285
this.facetRuns.set(facet.name, run);286
facet.setup(287
this.host.facetApi(288
((type: AnyContract, factory: Factory<AnyContract>, options: ServeOptions = {}) =>289
this.host.serveInto(this.services, makeService(type, factory, options, facet.name))) as Serve,290
run.signal,291
),292
);293
}294
for (const [name, service] of this.services) if (current.get(name) !== service) this.changed.add(name);295
for (const name of current.keys()) if (!this.services.has(name)) this.removed.add(name);296
this.host.pending = {297
id: this.host.nextCodeVersionId(this.codeVersion),298
services: this.services,299
tables: new Map(),300
roots: new Map(),301
abort: new AbortController(),302
};303
}305
async withDeadline<T>(promise: Promise<T>, what: string): Promise<T> {306
const deadline = this.options.gateDeadline ?? 5000;307
let timer: ReturnType<typeof setTimeout> | undefined;308
const timeout = new Promise<never>((_, reject) => {309
timer = setTimeout(310
() => reject(new ChordError("aborted", `${what} within ${deadline} ms`, { reason: "deadline" })),311
deadline,312
);313
});314
try {315
return await Promise.race([promise, timeout]);316
} finally {317
clearTimeout(timer);318
}319
}321
/** Same contract version must cover the old description (forgotten bump); facets' `uses` must bind. */322
checkProviders(): void {323
for (const name of this.changed) {324
const next = this.services.get(name)!.contract;325
const old = this.host.current.services.get(name)?.contract;326
if (old === undefined || old.version !== next.version) continue;327
const reason = coverage(next.description, old.description);328
if (reason !== undefined) {329
throw new ChordError(330
"contract_mismatch",331
`${name}@${next.version} changed incompatibly without a version bump (${reason})`,332
);333
}334
}335
const facets = new Map(this.host.facets);336
for (const facet of this.facets) facets.set(facet.name, facet);337
for (const name of this.options.remove ?? []) facets.delete(name);338
for (const facet of facets.values()) {339
for (const token of facet.uses ?? []) {340
const service = this.services.get(token.name);341
if (service !== undefined && this.changed.has(token.name))342
bind(service.contract, service.options.accepts, token);343
}344
}345
}347
/**348
* Prepares every live object of a changed type, including objects that activate meanwhile, to a fixpoint. Objects349
* already running the new code (types this reload adds) are skipped.350
*/351
async prepareAll(): Promise<void> {352
for (;;) {353
const todo = [...this.host.objects.values()].filter(354
(object) =>355
this.changed.has(object.typeName) &&356
!this.candidates.has(object) &&357
object.service !== this.services.get(object.typeName) &&358
(object.status === "live" || object.status === "activating"),359
);360
if (todo.length === 0) return;361
await Promise.allSettled(todo.map((object) => object.ready));362
this.#alive();363
for (const object of todo) {364
if (object.status === "live" && object.service !== this.services.get(object.typeName)) {365
await this.prepareObject(object);366
this.#alive();367
}368
}369
}370
}372
/** Runs the new factory in recording mode and opens what can be opened without the gate. */373
async prepareObject(object: ObjectImpl): Promise<void> {374
const service = this.services.get(object.typeName)!;375
const run = object.run(service, object.decls);376
const candidate: Candidate = {377
object,378
service,379
run,380
reasons: [],381
atGate: [],382
replaced: [],383
migrated: new Map(),384
derived: new Map(),385
staged: undefined,386
};387
this.candidates.set(object, candidate);388
// Each cell carries its own version: a raised one gates and migrates, a schema change without one is refused.389
for (const [name, cell] of run.decls.cells) {390
if (object.decls.cells.get(name) !== cell) continue;391
const from = object.decls.cellVersions.get(name) ?? 1;392
const to = run.decls.cellVersions.get(name) ?? 1;393
if (to < from)394
throw invalid("state", `${object.address}: version of state ${name} lowered from ${from} to ${to}`);395
if (to > from) candidate.reasons.push(`state ${name} version ${from} -> ${to}`);396
else if (!deepEqual(cell.schema, run.decls.cellSchemas.get(name)))397
throw invalid("state", `${object.address}: schema of state ${name} changed without a version bump`);398
}399
const deferred = new Set<ResourceImpl>();400
for (const resource of run.created.resources) {401
if (resource.exclusive || resource.deps.some((dep) => deferred.has(dep as ResourceImpl)))402
deferred.add(resource);403
}404
for (const resource of deferred) {405
candidate.atGate.push(resource);406
const old = object.decls.resources.get(resource.key);407
if (resource.exclusive && old?.exclusive && old.state === "open") candidate.replaced.push(old);408
}409
if (deferred.size > 0) candidate.reasons.push("exclusive resource replaced");410
await object.open(411
run.created.resources.filter((resource) => !deferred.has(resource)),412
run.created.refs,413
this.abort.signal,414
);415
await object.waitHydrated(run);416
// Cells this reload adds read their first value once the new resources are open (gated objects: at the gate);417
// the derivations over them are checked after.418
if (candidate.reasons.length === 0) {419
await object.initCells(run, this.abort.signal);420
dryRun(candidate);421
}422
}424
/**425
* Every reference that survives into the new code version must bind to the new provider. Browser references don't block a426
* reload: after the commit they get `upgrade_required` instead.427
*/428
checkRefs(): void {429
const dropped = new Set<unknown>();430
for (const { object, run } of this.candidates.values()) {431
for (const ref of object.decls.refs.values())432
if (![...run.decls.refs.values()].includes(ref)) dropped.add(ref);433
}434
for (const object of this.host.objects.values()) {435
const service = this.services.get(object.typeName);436
if (service === undefined || !this.changed.has(object.typeName)) continue;437
for (const ref of object.refs) {438
// The host's bootstrap reference follows this provider at commit; it is not an old-code consumer.439
if (ref === this.host.hostObjects.get(object.typeName)) continue;440
if (!dropped.has(ref) && ref.owner !== "client")441
bind(service.contract, service.options.accepts, ref.contract);442
}443
}444
}446
entries(): [ObjectImpl, Run["decls"]][] {447
return this.host448
.liveDecls(true)449
.filter(([object]) => !this.removed.has(object.typeName))450
.map(([object, decls]) => [object, this.candidates.get(object)?.run.decls ?? decls]);451
}453
/**454
* Admission cut, wait for grandfathered roots (deadline), replace exclusive resources, migrate into private455
* copies. Old tasks of gated objects are stopped at the cut; listener events are queued until commit or abort.456
*/457
async gate(): Promise<void> {458
this.gated = [...this.candidates.values()].filter(459
(candidate) => candidate.reasons.length > 0 && candidate.object.status === "live",460
);461
const drained = this.gated.map(({ object }) => {462
const grandfathered = new Set(object.leases.keys());463
return new Promise<void>((resolve) => {464
object.gate = { grandfathered, queue: [], drained: resolve };465
object.stopTasks();466
if (grandfathered.size === 0) resolve();467
});468
});469
const deadline = this.options.gateDeadline ?? 5000;470
let timer: ReturnType<typeof setTimeout> | undefined;471
const timedOut = await Promise.race([472
Promise.all(drained).then(() => false),473
new Promise<boolean>((resolve) => {474
timer = setTimeout(() => resolve(true), deadline);475
}),476
]);477
clearTimeout(timer);478
if (timedOut) {479
const blocking = this.gated.flatMap(({ object }) => [...(object.gate?.grandfathered ?? [])]);480
throw new ChordError(481
"aborted",482
`gate deadline (${deadline} ms) missed; blocking roots: ${blocking.join(", ")}`,483
{484
reason: "gate_deadline",485
details: { blocking },486
},487
);488
}489
this.#alive();490
for (const candidate of this.gated) {491
const { object } = candidate;492
for (const old of candidate.replaced) {493
// Owned by the rollback before closing: a failing close must still be restored.494
this.closed.push([object, old]);495
await old.close(object.openOrder);496
}497
await object.open(candidate.atGate, [], this.abort.signal);498
this.#alive();499
await object.initCells(candidate.run, this.abort.signal);500
this.#alive();501
}502
for (const candidate of this.gated) this.migrate(candidate);503
}505
migrate(candidate: Candidate): void {506
const { object, run } = candidate;507
for (const [name, cell] of run.decls.cells) {508
if (object.decls.cells.get(name) !== cell) continue;509
const schema = run.decls.cellSchemas.get(name)!;510
const from = object.decls.cellVersions.get(name) ?? 1;511
const fn = run.decls.cellMigrations.get(name);512
let value: unknown;513
if ((run.decls.cellVersions.get(name) ?? 1) > from && fn !== undefined)514
value = fn(structuredClone(cell.value), from);515
else if (!deepEqual(cell.schema, schema)) value = cell.value;516
else continue;517
assertValid("state", `${object.address}: migrated state ${name}`, schema, value);518
candidate.migrated.set(cell, value);519
}520
dryRun(candidate);521
}523
async rollback(): Promise<void> {524
if (this.rolledBack) return;525
this.rolledBack = true;526
this.abort.abort(new ChordError("aborted", "reload aborted"));527
for (const run of this.facetRuns.values()) run.abort(new ChordError("aborted", "reload aborted"));528
const report = (error: unknown): void => this.host.report(error);529
for (const candidate of this.candidates.values()) candidate.staged?.discard();530
for (const staged of this.deferred.values()) staged.discard();531
for (const { object, run } of this.candidates.values()) {532
object.pending.delete(run.decls);533
await object.unwind(run).catch(report);534
}535
// Replaced exclusive resources are restored; one that cannot be is marked unavailable, never silently closed.536
for (const [object, resource] of this.closed) {537
if (resource.state !== "closed") continue;538
await resource.open(new AbortController().signal, object.openOrder).catch((error: unknown) => {539
resource.markUnavailable();540
report(541
new ChordError("unavailable", `${object.address}: resource ${resource.key} could not be restored`, {542
cause: error,543
}),544
);545
});546
}547
for (const { object } of this.gated) {548
if (object.gate === undefined) continue;549
object.openGate();550
object.startTasks();551
}552
// Objects of types this reload would have added lose their code.553
const reason = new ChordError("gone", "reload aborted; type not served");554
for (const object of [...this.host.objects.values()]) {555
if (!this.host.current.services.has(object.typeName)) await object.dispose(true, reason).catch(report);556
}557
this.host.pending = undefined;558
this.host.gating = undefined;559
}561
/**562
* Publishes the new code version in one synchronous step. Everything fallible ran in prepare (factories, opens,563
* migration and derivation checks against the prospective schemas, listener subscriptions), so this only installs.564
* Observers (state, shapes, registries, listener roots) are notified after the whole step. If an install still565
* throws, the code version is half-published: the host fails terminally and admits no more work.566
*/567
commit(beforeStart?: () => void): ReloadReport {568
try {569
return holdPublications(() => {570
const report = this.#publish();571
// Installed, not yet started: the coordinator queues its commit frames here, so nothing this code version572
// starts (tasks, host object activations, then the held listener/registry/state notifications) can reach a child573
// first.574
beforeStart?.();575
for (const start of this.#starts.splice(0)) start();576
return report;577
});578
} catch (error) {579
this.host.fail(error);580
throw reloadError(error);581
}582
}584
/** Work that may start new-code-version roots, run after installation (and after the coordinator's commit frames). */585
readonly #starts: (() => void)[] = [];587
#publish(): ReloadReport {588
const host = this.host;589
const previous = host.current;590
const next: CodeVersionState = host.pending!;591
host.pending = undefined;592
host.codeVersions.set(next.id, next);593
host.previous = previous;594
host.current = next;595
const prepared: string[] = [];596
for (const object of [...host.objects.values()]) {597
if (this.removed.has(object.typeName)) continue;598
const candidate = this.candidates.get(object);599
if (candidate === undefined) {600
const installed = object.implementations.get(previous.id);601
if (installed !== undefined) object.implementations.set(next.id, { ...installed, codeVersion: next.id });602
continue;603
}604
if (object.status !== "live") continue;605
this.install(candidate, next.id);606
prepared.push(object.address);607
}608
for (const { object, run, staged } of this.candidates.values()) {609
if (object.status === "live") continue;610
staged?.discard();611
object.pending.delete(run.decls);612
object.unwind(run).catch((error: unknown) => host.report(error));613
}614
// Objects of types this reload adds start their runtime now.615
for (const [object, staged] of this.deferred) {616
if (object.status !== "live") {617
staged.discard();618
continue;619
}620
object.deferredRuntime = false;621
staged.activate();622
this.#starts.push(() => object.startTasks());623
}624
host.installTables(next, this.tables, true);625
const reason = new ChordError("gone", "type no longer served");626
for (const object of [...host.objects.values()]) {627
if (this.removed.has(object.typeName))628
object.dispose(true, reason).catch((error: unknown) => host.report(error));629
}630
for (const name of this.removed) host.hostObjects.delete(name);631
for (const facet of this.facets) host.facets.set(facet.name, facet);632
for (const name of this.options.remove ?? []) host.facets.delete(name);633
// The replaced and removed runs' signals abort after the install, like other observers.634
for (const [name, run] of this.facetRuns) this.#starts.push(() => host.facetRunChanged(name, run));635
for (const name of this.options.remove ?? []) this.#starts.push(() => host.facetRunChanged(name, undefined));636
host.gating = undefined;637
for (const [name, service] of this.services) {638
if (hostLifetime(service) && this.changed.has(name) && host.hostObjects.get(name)?.object?.status !== "live") {639
this.#starts.push(() => host.startHostObject(service));640
}641
// A type whose lifetime became "referenced" lives on only while someone else references its object.642
const pinned = host.hostObjects.get(name);643
if (!hostLifetime(service) && pinned !== undefined) {644
host.hostObjects.delete(name);645
this.#starts.push(() => pinned.release());646
}647
}648
return {649
codeVersion: next.id,650
previous: previous.id,651
changed: [...this.changed],652
removed: [...this.removed],653
prepared,654
gated: this.gated.map(({ object }) => object.address),655
};656
}658
install(candidate: Candidate, codeVersion: number): void {659
const { object, run, service } = candidate;660
const gated = candidate.reasons.length > 0;661
object.pending.delete(run.decls);662
object.stopTasks();663
if (gated) {664
// Old derivations would compute over migrated values; the old implementation can no longer run anyway.665
const kept = new Set(run.decls.derives.values());666
for (const derived of object.decls.derives.values()) if (!kept.has(derived)) derived.detach();667
}668
object.decls = run.decls;669
object.service = service;670
// Kept resources close with the new code's `close`; replaced ones keep their own (closed at retirement).671
for (const [resource, declaration] of run.decls.adopted) resource.adopt(declaration);672
object.implementations.set(codeVersion, {673
codeVersion,674
service,675
implementation: run.implementation,676
decls: run.decls,677
});678
if (gated) {679
// Old code can never run over migrated state: drop the previous implementation now, not at retirement.680
object.minCodeVersion = codeVersion;681
for (const old of [...object.implementations.keys()])682
if (old !== codeVersion) this.host.retireImplementation(object, old);683
}684
// Schemas first, then the values validated against them in prepare.685
object.refreshSchemas();686
for (const [name, cell] of run.decls.cells) {687
const schema = run.decls.cellSchemas.get(name)!;688
if (candidate.migrated.has(cell)) cell.reset(candidate.migrated.get(cell), schema);689
else cell.schema = schema;690
}691
const created = new Set(run.created.derives);692
for (const derived of run.created.derives) derived.attach(candidate.derived);693
for (const derived of run.decls.derives.values()) if (!created.has(derived)) derived.refresh();694
candidate.staged?.activate();695
this.#starts.push(() => object.startTasks());696
object.openGate();697
const pinned = this.host.hostObjects.get(object.typeName);698
if (pinned?.object === object && pinned.contract.fingerprint !== service.contract.fingerprint) {699
const replacement = new RefImpl(object, service.contract, "host");700
// Acquire first: releasing the only reference must not dispose/reopen the surviving host object.701
object.addRef(replacement);702
this.host.hostObjects.set(object.typeName, replacement);703
pinned.release();704
}705
for (const ref of [...object.refs]) {706
// Browser references whose contract no longer binds are told to reload their code (they never block a reload).707
if (ref.owner === "client") {708
try {709
bind(service.contract, service.options.accepts, ref.contract);710
} catch (error) {711
ref.gone(712
new ChordError("upgrade_required", `${object.typeName} changed; reload the web facets`, {713
cause: error,714
}),715
);716
object.release(ref);717
continue;718
}719
}720
ref.shapeChanged();721
}722
}723
}