Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2// @effect-diagnostics globalTimers:off
3// The launcher must survive unloadable server versions; use Node built-ins without Effect.
4import * as NodeChildProcess from "node:child_process";
5import * as NodeCrypto from "node:crypto";
6import * as NodeFS from "node:fs";
7import * as NodeFSP from "node:fs/promises";
8import * as NodePath from "node:path";
9import * as NodeUtil from "node:util";
10
11import type {
12 PendingServiceUpdate,
13 ServiceLauncherChildMessage,
14 ServiceLauncherContext,
15 ServiceLauncherParentMessage,
16 ServiceState,
17 ServiceUpdateRecord,
18} from "./cloud/serviceProtocol.ts";
19import {
20 compareExactServiceVersions,
21 decodeServiceLauncherChildMessage,
22 isExactServiceVersion,
23 parseServiceState,
24 SERVICE_ENV_FILE,
25 SERVICE_LAUNCHER_CONTEXT_ENV,
26 SERVICE_LAUNCHER_PROTOCOL,
27 SERVICE_STATE_FILE,
28 SERVICE_RESTART_PENDING_FILE,
29 SERVICE_STOP_MARKER_FILE,
30} from "./cloud/serviceProtocol.ts";
31
32const HANDOFF_DELAY_MS = 2_000;
33/**
34 * Migrations count toward it and can scale with the database: tens of GB on a cold page cache
35 * take minutes. A missed window rolls back the database, so the next attempt pays the same cost.
36 */
37const PREPARED_TIMEOUT_MS = 30 * 60_000;
38const TERMINATE_GRACE_MS = 5_000;
39// Match contracts' SERVER_EXIT_CODE_STATE_DIR_OWNED without depending on Effect.
40const STATE_DIR_OWNED_EXIT_CODE = 78;
41
42type TerminalStatus = "committed" | "rolled-back" | "failed";
43type ChildRole = "active" | "trial";
44
45interface ManagedChild {
46 readonly version: string;
47 role: ChildRole;
48 readonly process: NodeChildProcess.ChildProcess;
49}
50
51const runtimePaths = (baseDir: string, version: string) => {
52 const versionDir = NodePath.join(baseDir, "runtime", "versions", version);
53 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
54 const executableName = process.platform === "win32" ? "t3.exe" : "t3";
55 return {
56 versionDir,
57 entryPath: NodePath.join(versionDir, executableName),
58 sentinelPath: NodePath.join(versionDir, ".install-complete"),
59 };
60};
61
62const runtimeSpawnArguments = (paths: ReturnType<typeof runtimePaths>) => ({
63 command: paths.entryPath,
64 args: ["serve"],
65});
66
67const DB_FILE_SUFFIXES = ["", "-wal", "-shm"] as const;
68const RESTORE_MARKER = ".restore-pending";
69
70const databaseBackupDir = (baseDir: string, updateId: string) =>
71 NodePath.join(baseDir, "runtime", "db-backup", updateId);
72
73const databaseBackupFile = (backupDir: string, suffix: (typeof DB_FILE_SUFFIXES)[number]) =>
74 NodePath.join(backupDir, suffix === "" ? "database" : `database${suffix}`);
75
76async function pathExists(target: string): Promise<boolean> {
77 try {
78 await NodeFSP.access(target);
79 return true;
80 } catch (cause) {
81 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return false;
82 throw cause;
83 }
84}
85
86const MANAGED_SERVICE_ENV_NAMES = new Set([
87 "PATH",
88 "T3CODE_HOME",
89 "T3_BOOT_SERVICE_UNIT",
90 SERVICE_LAUNCHER_CONTEXT_ENV,
91]);
92
93export async function readServiceEnvironment(
94 baseDir: string,
95 inherited: NodeJS.ProcessEnv = process.env,
96): Promise<NodeJS.ProcessEnv> {
97 const environment = { ...inherited };
98 let contents: string;
99 try {
100 contents = await NodeFSP.readFile(NodePath.join(baseDir, SERVICE_ENV_FILE), "utf8");
101 } catch (cause) {
102 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return environment;
103 throw cause;
104 }
105 for (const [name, value] of Object.entries(NodeUtil.parseEnv(contents))) {
106 if (
107 /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) &&
108 !MANAGED_SERVICE_ENV_NAMES.has(name.toUpperCase())
109 ) {
110 environment[name] = value;
111 }
112 }
113 return environment;
114}
115
116// Opened read-write: Windows refuses to flush a handle without write access.
117async function syncFile(filePath: string): Promise<void> {
118 const handle = await NodeFSP.open(filePath, "r+");
119 try {
120 await handle.sync();
121 } finally {
122 await handle.close();
123 }
124}
125
126// Fsync makes renames durable; Windows returns EPERM and NTFS journals them itself.
127async function syncDirectory(directory: string): Promise<void> {
128 const handle = await NodeFSP.open(directory, "r");
129 try {
130 await handle.sync();
131 } catch (error) {
132 if ((error as NodeJS.ErrnoException).code !== "EPERM") throw error;
133 } finally {
134 await handle.close();
135 }
136}
137
138function runCp(args: ReadonlyArray<string>): Promise<boolean> {
139 return new Promise((resolve) => {
140 NodeChildProcess.execFile("cp", args, (error) => resolve(error === null));
141 });
142}
143
144// macOS fs.copyFile clone flags fall back to full copies.
145async function copyDatabaseFile(source: string, destination: string): Promise<void> {
146 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
147 const platform = process.platform;
148 // cp -c replaces files and breaks hard links; copy into hard-linked destinations instead.
149 const hardLinked =
150 platform === "darwin" &&
151 ((await NodeFSP.stat(destination).catch(() => undefined))?.nlink ?? 1) > 1;
152 const args =
153 platform === "darwin" && !hardLinked
154 ? ["-c", source, destination]
155 : platform === "linux"
156 ? ["--reflink=auto", source, destination]
157 : undefined;
158 if (args === undefined || !(await runCp(args))) await NodeFSP.copyFile(source, destination);
159}
160
161const GIB = 1024 ** 3;
162// Cloned backups still need headroom for trial writes and migrations to diverge.
163const CLONED_BACKUP_MIN_HEADROOM_BYTES = GIB;
164const CLONED_BACKUP_HEADROOM_FRACTION = 0.1;
165
166async function statDatabaseFiles(dbPath: string): Promise<ReadonlyArray<NodeFS.Stats>> {
167 const stats: Array<NodeFS.Stats> = [];
168 for (const suffix of DB_FILE_SUFFIXES) {
169 const stat = await NodeFSP.stat(`${dbPath}${suffix}`).catch((cause: unknown) => {
170 if (suffix !== "" && (cause as NodeJS.ErrnoException).code === "ENOENT") return undefined;
171 throw cause;
172 });
173 if (stat !== undefined) stats.push(stat);
174 }
175 return stats;
176}
177
178// cp -c silently copies across volumes; require one device matching the APFS system volume's filesystem type.
179async function backupCanClone(dbPath: string, backupRoot: string): Promise<boolean> {
180 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
181 const platform = process.platform;
182 if (platform === "darwin") {
183 const [backupDirectory, backupFs, systemFs] = await Promise.all([
184 NodeFSP.stat(backupRoot),
185 NodeFSP.statfs(backupRoot),
186 NodeFSP.statfs("/"),
187 ]);
188 if (backupFs.type !== systemFs.type) return false;
189 return (await statDatabaseFiles(dbPath)).every(
190 (source) => source.dev === backupDirectory.dev && source.nlink === 1,
191 );
192 }
193 if (platform !== "linux") return false;
194 const probe = NodePath.join(backupRoot, `.clone-probe-${NodeCrypto.randomUUID()}`);
195 try {
196 for (const suffix of DB_FILE_SUFFIXES) {
197 const source = `${dbPath}${suffix}`;
198 if (suffix !== "" && !(await pathExists(source))) continue;
199 if (!(await runCp(["--reflink=always", source, `${probe}${suffix}`]))) return false;
200 }
201 return true;
202 } finally {
203 for (const suffix of DB_FILE_SUFFIXES) {
204 await NodeFSP.rm(`${probe}${suffix}`, { force: true }).catch(() => undefined);
205 }
206 }
207}
208
209export interface BackupSpaceProbe {
210 readonly readFreeBytes: (directory: string) => Promise<number>;
211 readonly canClone: (dbPath: string, backupRoot: string) => Promise<boolean>;
212}
213
214const filesystemBackupSpaceProbe: BackupSpaceProbe = {
215 readFreeBytes: async (directory) => {
216 const stats = await NodeFSP.statfs(directory);
217 return stats.bavail * stats.bsize;
218 },
219 canClone: backupCanClone,
220};
221
222/** Check before stopping the server so full disks refuse updates without an outage. */
223export async function databaseBackupBlocker(
224 baseDir: string,
225 dbPath: string,
226 probe: Partial<BackupSpaceProbe> = {},
227): Promise<string | undefined> {
228 const { readFreeBytes, canClone } = { ...filesystemBackupSpaceProbe, ...probe };
229 const backupRoot = NodePath.join(baseDir, "runtime", "db-backup");
230 await NodeFSP.mkdir(backupRoot, { recursive: true, mode: 0o700 });
231 const [files, free] = await Promise.all([statDatabaseFiles(dbPath), readFreeBytes(backupRoot)]);
232 const size = files.reduce((total, file) => total + file.size, 0);
233 const fullCopyBytes = size * 1.05;
234 if (free >= fullCopyBytes) return undefined;
235 const clonedBytes = Math.max(
236 CLONED_BACKUP_MIN_HEADROOM_BYTES,
237 size * CLONED_BACKUP_HEADROOM_FRACTION,
238 );
239 const needed = (await canClone(dbPath, backupRoot)) ? clonedBytes : fullCopyBytes;
240 if (free >= needed) return undefined;
241 const gb = (bytes: number) => (bytes / GIB).toFixed(1);
242 return `Not enough free disk space to back up the database before updating: ${gb(needed)} GB needed, ${gb(free)} GB free. Free up disk space and try again. The server was not stopped.`;
243}
244
245// Preserve completed backups; restarted trials may already have changed the live database.
246async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise<void> {
247 const backupDir = databaseBackupDir(baseDir, pending.id);
248 if (await pathExists(backupDir)) return;
249
250 const stagingDir = `${backupDir}.staging`;
251 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
252 await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
253 try {
254 for (const suffix of DB_FILE_SUFFIXES) {
255 const source = `${pending.dbPath}${suffix}`;
256 if (suffix !== "" && !(await pathExists(source))) continue;
257 const destination = databaseBackupFile(stagingDir, suffix);
258 await copyDatabaseFile(source, destination);
259 await syncFile(destination);
260 }
261 await NodeFSP.rename(stagingDir, backupDir);
262 await syncDirectory(NodePath.dirname(backupDir));
263 } catch (cause) {
264 await NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
265 throw cause;
266 }
267}
268
269const restoreMarkerPath = (baseDir: string, updateId: string) =>
270 NodePath.join(databaseBackupDir(baseDir, updateId), RESTORE_MARKER);
271
272const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) =>
273 pathExists(restoreMarkerPath(baseDir, pending.id));
274
275// Mark before live writes so recovery cannot boot a partial restore.
276async function markDatabaseRestorePending(backupDir: string): Promise<void> {
277 const markerPath = NodePath.join(backupDir, RESTORE_MARKER);
278 if (!(await pathExists(markerPath))) {
279 const handle = await NodeFSP.open(markerPath, "wx", 0o600);
280 try {
281 await handle.sync();
282 } finally {
283 await handle.close();
284 }
285 await syncDirectory(backupDir);
286 }
287}
288
289// Resolve symlink targets even if a crashed cp -c left the final target missing.
290async function restoreTarget(path: string): Promise<string> {
291 let current = path;
292 for (let hops = 0; hops < 40; hops++) {
293 try {
294 return await NodeFSP.realpath(current);
295 } catch (cause) {
296 if ((cause as NodeJS.ErrnoException).code !== "ENOENT") throw cause;
297 }
298 const link = await NodeFSP.readlink(current).catch((cause: unknown) => {
299 const code = (cause as NodeJS.ErrnoException).code;
300 if (code === "ENOENT" || code === "EINVAL") return undefined;
301 throw cause;
302 });
303 if (link === undefined) return current;
304 // Do not normalize .. before following directory symlinks; match filesystem resolution.
305 current = NodePath.isAbsolute(link)
306 ? link
307 : `${await NodeFSP.realpath(NodePath.dirname(current))}${NodePath.sep}${link}`;
308 }
309 throw new Error(`Too many symbolic links resolving ${path}.`);
310}
311
312async function restoreDatabaseBackup(
313 baseDir: string,
314 pending: PendingServiceUpdate,
315): Promise<void> {
316 const backupDir = databaseBackupDir(baseDir, pending.id);
317 if (!(await pathExists(backupDir))) return;
318
319 await markDatabaseRestorePending(backupDir);
320 const directories = new Set([NodePath.dirname(pending.dbPath)]);
321 for (const suffix of DB_FILE_SUFFIXES) {
322 const livePath = `${pending.dbPath}${suffix}`;
323 const source = databaseBackupFile(backupDir, suffix);
324 if (await pathExists(source)) {
325 // Restore into the symlink target; cloning would replace the link.
326 const target = await restoreTarget(livePath);
327 await copyDatabaseFile(source, target);
328 await syncFile(target);
329 directories.add(NodePath.dirname(target));
330 } else {
331 await NodeFSP.rm(livePath, { force: true });
332 }
333 }
334 for (const directory of directories) await syncDirectory(directory);
335}
336
337async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
338 const backupDir = databaseBackupDir(baseDir, updateId);
339 if (!(await pathExists(backupDir))) return;
340 await NodeFSP.rm(backupDir, { recursive: true, force: true });
341 await syncDirectory(NodePath.dirname(backupDir));
342}
343
344export async function readServiceState(filePath: string): Promise<ServiceState> {
345 const contents = await NodeFSP.readFile(filePath, "utf8");
346 const state = parseServiceState(contents);
347 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
348 return state;
349}
350
351export async function writeServiceState(filePath: string, state: ServiceState): Promise<void> {
352 const directory = NodePath.dirname(filePath);
353 await NodeFSP.mkdir(directory, { recursive: true, mode: 0o700 });
354 const tempPath = NodePath.join(
355 directory,
356 `.${NodePath.basename(filePath)}.${process.pid}.${NodeCrypto.randomUUID()}`,
357 );
358 let handle: NodeFSP.FileHandle | undefined;
359 try {
360 handle = await NodeFSP.open(tempPath, "wx", 0o600);
361 await handle.writeFile(`${JSON.stringify(state, null, 2)}\n`, "utf8");
362 await handle.sync();
363 await handle.close();
364 handle = undefined;
365 await NodeFSP.rename(tempPath, filePath);
366 await syncDirectory(directory);
367 } finally {
368 await handle?.close().catch(() => undefined);
369 await NodeFSP.rm(tempPath, { force: true }).catch(() => undefined);
370 }
371}
372
373async function runtimeExists(baseDir: string, version: string): Promise<boolean> {
374 const paths = runtimePaths(baseDir, version);
375 try {
376 const [entry, sentinel] = await Promise.all([
377 NodeFSP.stat(paths.entryPath),
378 NodeFSP.readFile(paths.sentinelPath, "utf8"),
379 ]);
380 return entry.isFile() && sentinel.trim() === version;
381 } catch {
382 return false;
383 }
384}
385
386function terminalUpdate<S extends TerminalStatus>(input: {
387 readonly pending: PendingServiceUpdate;
388 readonly status: S;
389 readonly reason?: string;
390}): Exclude<ServiceUpdateRecord, PendingServiceUpdate> & { readonly status: S } {
391 return {
392 id: input.pending.id,
393 fromVersion: input.pending.fromVersion,
394 targetVersion: input.pending.targetVersion,
395 status: input.status,
396 ...(input.reason === undefined ? {} : { reason: input.reason }),
397 };
398}
399
400function sendMessage(
401 child: NodeChildProcess.ChildProcess,
402 message: ServiceLauncherParentMessage,
403): Promise<void> {
404 return new Promise((resolve, reject) => {
405 if (!child.connected || child.send === undefined) {
406 reject(new Error("service child IPC is disconnected."));
407 return;
408 }
409 child.send(message, (error) => (error === null ? resolve() : reject(error)));
410 });
411}
412
413function waitForExit(child: NodeChildProcess.ChildProcess): Promise<void> {
414 if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
415 return new Promise((resolve) => child.once("exit", () => resolve()));
416}
417
418async function terminateChild(
419 child: NodeChildProcess.ChildProcess,
420 signal: NodeJS.Signals = "SIGTERM",
421): Promise<void> {
422 if (child.exitCode !== null || child.signalCode !== null) return;
423 child.kill(signal);
424 const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS);
425 try {
426 await waitForExit(child);
427 } finally {
428 clearTimeout(force);
429 }
430}
431
432const stopMarkerPath = (baseDir: string) =>
433 NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
434const restartPendingPath = (baseDir: string) =>
435 NodePath.join(baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
436
437export class Launcher {
438 readonly #baseDir: string;
439 readonly #statePath: string;
440 #state: ServiceState;
441 #child: ManagedChild | null = null;
442 #timer: NodeJS.Timeout | undefined;
443 #transitions: Promise<void> = Promise.resolve();
444 #stopRequested = false;
445 #stopping = false;
446 #done = false;
447 readonly #completion = Promise.withResolvers<void>();
448 readonly #backupSpaceProbe: Partial<BackupSpaceProbe> | undefined;
449 readonly #environment: Readonly<NodeJS.ProcessEnv>;
450
451 constructor(
452 baseDir: string,
453 state: ServiceState,
454 options: {
455 readonly backupSpaceProbe?: Partial<BackupSpaceProbe>;
456 readonly environment?: Readonly<NodeJS.ProcessEnv>;
457 } = {},
458 ) {
459 this.#baseDir = baseDir;
460 this.#backupSpaceProbe = options.backupSpaceProbe;
461 this.#environment = { ...(options.environment ?? process.env) };
462 this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
463 this.#state = state;
464 }
465
466 async run(): Promise<void> {
467 const onSigterm = () => void this.stop("SIGTERM");
468 const onSigint = () => void this.stop("SIGINT");
469 process.once("SIGTERM", onSigterm);
470 process.once("SIGINT", onSigint);
471 try {
472 this.#enqueue(() => this.#recover());
473 await this.#completion.promise;
474 } finally {
475 process.off("SIGTERM", onSigterm);
476 process.off("SIGINT", onSigint);
477 }
478 }
479
480 #enqueue(transition: () => Promise<void>): void {
481 this.#transitions = this.#transitions
482 .then(transition, transition)
483 .catch((cause: unknown) =>
484 this.#fatal(cause instanceof Error ? cause : new Error(String(cause))),
485 );
486 }
487
488 async #fatal(error: Error): Promise<void> {
489 if (this.#done) return;
490 this.#done = true;
491 this.#stopping = true;
492 this.#clearTimer();
493 const child = this.#child?.process;
494 this.#child = null;
495 if (child !== undefined) await terminateChild(child);
496 this.#completion.reject(error);
497 }
498
499 async stop(signal: NodeJS.Signals): Promise<void> {
500 // Write synchronously on signal receipt; a terminating child needs the marker in its finalizer.
501 try {
502 NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
503 } catch {}
504 if (this.#stopRequested || this.#stopping) {
505 await this.#completion.promise.catch(() => undefined);
506 return;
507 }
508 this.#stopRequested = true;
509 this.#clearTimer();
510 this.#enqueue(async () => {
511 // Let in-progress updates start replacements first; replacements observe the marker and own pre-activation tunnel cleanup.
512 this.#stopping = true;
513 const child = this.#child?.process;
514 this.#child = null;
515 if (child !== undefined) await terminateChild(child, signal);
516 this.#done = true;
517 this.#completion.resolve();
518 });
519 await this.#completion.promise.catch(() => undefined);
520 }
521
522 #clearTimer(): void {
523 clearTimeout(this.#timer);
524 this.#timer = undefined;
525 }
526
527 async #recover(): Promise<void> {
528 // Clear old stop markers to preserve future tunnels; clear restart-pending only for the awaited version to avoid CLI races.
529 await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
530 const restartPending = restartPendingPath(this.#baseDir);
531 const awaitedVersion = await NodeFSP.readFile(restartPending, "utf8").catch(() => undefined);
532 if (awaitedVersion?.trim() === this.#state.activeVersion) {
533 await NodeFSP.rm(restartPending, { force: true }).catch(() => undefined);
534 }
535 const update = this.#state.update;
536 if (update?.status !== "pending") {
537 if (update !== undefined) {
538 await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
539 }
540 await this.#startChild(this.#state.activeVersion, "active", update);
541 return;
542 }
543 if (await databaseRestorePending(this.#baseDir, update)) {
544 await this.#returnToPrevious(update, "failed", "rollback-interrupted");
545 return;
546 }
547 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
548 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
549 return;
550 }
551 await this.#startTrial(update);
552 }
553
554 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
555 try {
556 await backupDatabaseOnce(this.#baseDir, pending);
557 } catch {
558 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
559 return;
560 }
561 try {
562 await this.#startChild(pending.targetVersion, "trial", pending);
563 } catch {
564 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
565 }
566 }
567
568 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
569 if (this.#stopping) return;
570 if (!(await runtimeExists(this.#baseDir, version))) {
571 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
572 }
573 if (this.#stopping) return;
574 const paths = runtimePaths(this.#baseDir, version);
575 const context: ServiceLauncherContext = {
576 protocol: SERVICE_LAUNCHER_PROTOCOL,
577 childVersion: version,
578 ...(update === undefined ? {} : { update }),
579 };
580 const spawnArguments = runtimeSpawnArguments(paths);
581 const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
582 env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
583 stdio: ["inherit", "inherit", "inherit", "ipc"],
584 });
585 await new Promise<void>((resolve, reject) => {
586 const onError = (error: Error) => reject(error);
587 child.once("error", onError);
588 child.once("spawn", () => {
589 child.removeListener("error", onError);
590 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
591 resolve();
592 });
593 });
594 if (this.#stopping) {
595 await terminateChild(child);
596 return;
597 }
598
599 const managed: ManagedChild = {
600 version,
601 role,
602 process: child,
603 };
604 this.#child = managed;
605 child.on("message", (value) => {
606 const message = decodeServiceLauncherChildMessage(value);
607 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
608 });
609 child.once("exit", (code, signal) =>
610 this.#enqueue(() => this.#handleExit(managed, code, signal)),
611 );
612
613 if (role === "trial") {
614 this.#timer = setTimeout(
615 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
616 PREPARED_TIMEOUT_MS,
617 );
618 }
619 }
620
621 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
622 if (this.#child !== child || this.#stopping) return;
623 if (message.type === "request-update") {
624 await this.#handleUpdateRequest(child, message);
625 return;
626 }
627 await this.#handlePrepared(child, message.updateId);
628 }
629
630 async #handleUpdateRequest(
631 child: ManagedChild,
632 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
633 ): Promise<void> {
634 const reject = (reason: string) =>
635 sendMessage(child.process, { type: "update-rejected", reason });
636 if (child.role !== "active") {
637 await reject("Only the active server can request an update.");
638 return;
639 }
640 if (child.version !== this.#state.activeVersion) {
641 await reject("The requesting server is not the selected active version.");
642 return;
643 }
644 if (this.#state.update?.status === "pending") {
645 await reject("Another server update is already pending.");
646 return;
647 }
648 if (!isExactServiceVersion(message.targetVersion)) {
649 await reject("The requested target is not an exact version.");
650 return;
651 }
652 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
653 await reject("Remote updates must select a newer server version.");
654 return;
655 }
656 if (!NodePath.isAbsolute(message.dbPath)) {
657 await reject("The requested database path is not absolute.");
658 return;
659 }
660 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
661 await reject("The requested target runtime is missing or incomplete.");
662 return;
663 }
664 // Failed checks must refuse updates rather than stop the server with unknown backup capacity.
665 const backupBlocker = await databaseBackupBlocker(
666 this.#baseDir,
667 message.dbPath,
668 this.#backupSpaceProbe,
669 ).catch(
670 (error: unknown) =>
671 `Could not check that the database backup fits before updating: ${error instanceof Error ? error.message : String(error)}. The server was not stopped.`,
672 );
673 if (!child.process.connected) return;
674 if (backupBlocker !== undefined) {
675 await reject(backupBlocker);
676 return;
677 }
678
679 const pending: PendingServiceUpdate = {
680 id: NodeCrypto.randomUUID(),
681 fromVersion: child.version,
682 targetVersion: message.targetVersion,
683 dbPath: message.dbPath,
684 status: "pending",
685 };
686 const next: ServiceState = { ...this.#state, update: pending };
687 await writeServiceState(this.#statePath, next);
688 this.#state = next;
689 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
690 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
691 }
692
693 async #beginTrial(child: ManagedChild): Promise<void> {
694 const pending = this.#state.update;
695 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
696 return;
697 }
698 this.#timer = undefined;
699 this.#child = null;
700 await terminateChild(child.process);
701 await this.#startTrial(pending);
702 }
703
704 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
705 const pending = this.#state.update;
706 if (
707 child.role !== "trial" ||
708 pending?.status !== "pending" ||
709 pending.id !== updateId ||
710 pending.targetVersion !== child.version
711 ) {
712 if (child.role === "trial" && pending?.status === "pending") {
713 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
714 return;
715 }
716 throw new Error("Trial child reported prepared for an unexpected update.");
717 }
718 this.#clearTimer();
719 const committed = terminalUpdate({ pending, status: "committed" });
720 const next: ServiceState = {
721 ...this.#state,
722 activeVersion: pending.targetVersion,
723 update: committed,
724 };
725 await writeServiceState(this.#statePath, next);
726 this.#state = next;
727 child.role = "active";
728 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
729 await sendMessage(child.process, { type: "committed", updateId: committed.id });
730 }
731
732 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
733 const pending = this.#state.update;
734 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
735 return;
736 }
737 this.#timer = undefined;
738 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
739 }
740
741 async #handleExit(
742 child: ManagedChild,
743 code: number | null,
744 signal: NodeJS.Signals | null,
745 ): Promise<void> {
746 if (this.#child !== child || this.#stopping) return;
747 this.#child = null;
748 if (code === STATE_DIR_OWNED_EXIT_CODE) {
749 await this.#idleWhileStateDirOwned();
750 return;
751 }
752 if (child.role === "trial") {
753 this.#clearTimer();
754 const pending = this.#state.update;
755 if (pending?.status !== "pending") {
756 throw new Error("Trial child exited without matching pending state.");
757 }
758 await this.#returnToPrevious(
759 pending,
760 "rolled-back",
761 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
762 );
763 return;
764 }
765
766 this.#clearTimer();
767 const pending = this.#state.update;
768 if (pending?.status === "pending") {
769 await this.#startTrial(pending);
770 return;
771 }
772 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
773 }
774
775 // Stay idle to avoid supervisor restart loops; never restore backups over another owner's possible writes.
776 async #idleWhileStateDirOwned(): Promise<void> {
777 this.#clearTimer();
778 const pending = this.#state.update;
779 if (pending?.status === "pending") {
780 const next: ServiceState = {
781 ...this.#state,
782 activeVersion: pending.fromVersion,
783 update: terminalUpdate({ pending, status: "failed", reason: "state-dir-owned" }),
784 };
785 await writeServiceState(this.#statePath, next);
786 this.#state = next;
787 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
788 }
789 // Signal listeners alone do not keep Node alive.
790 this.#timer = setInterval(() => {}, 2_147_483_647);
791 process.stderr.write(
792 "[service-launcher] Another T3 Code server owns this T3 home. Stop it, then restart this service.\n",
793 );
794 }
795
796 async #returnToPrevious(
797 pending: PendingServiceUpdate,
798 status: "rolled-back" | "failed",
799 reason: string,
800 child?: ManagedChild,
801 ): Promise<void> {
802 if (child !== undefined) {
803 this.#child = null;
804 await terminateChild(child.process);
805 }
806 await restoreDatabaseBackup(this.#baseDir, pending);
807 const outcome = terminalUpdate({ pending, status, reason });
808 const next: ServiceState = {
809 ...this.#state,
810 activeVersion: pending.fromVersion,
811 update: outcome,
812 };
813 await writeServiceState(this.#statePath, next);
814 this.#state = next;
815 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
816 await this.#startChild(next.activeVersion, "active", outcome);
817 }
818}
819
820export async function main(): Promise<void> {
821 const baseDir = process.env.T3CODE_HOME?.trim();
822 if (baseDir === undefined || baseDir === "") {
823 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
824 }
825 const environment = await readServiceEnvironment(baseDir);
826 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
827 const state = await readServiceState(statePath);
828 await new Launcher(baseDir, state, { environment }).run();
829}