Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceLauncher.ts

841 lines30.1 KB

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;
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 }
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;
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 }
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 }
137​
138function runCp(args: ReadonlyArray<string>): Promise<boolean> {
139 return new Promise((resolve) => {
140 NodeChildProcess.execFile("cp", args, (error) => resolve(error === null));
141 });
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);
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;
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 }
208​
209export interface BackupSpaceProbe {
210 readonly readFreeBytes: (directory: string) => Promise<number>;
211 readonly canClone: (dbPath: string, backupRoot: string) => Promise<boolean>;
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// A killed launcher skips the backup's cleanup, and retries only clear their own update's copy.
223// Update requests are refused while one is pending, so no staging directory is still in use here.
224async function removeAbandonedBackupCopies(backupRoot: string): Promise<void> {
225 for (const entry of await NodeFSP.readdir(backupRoot)) {
226 if (!entry.endsWith(".staging")) continue;
227 await NodeFSP.rm(NodePath.join(backupRoot, entry), { recursive: true, force: true }).catch(
228 () => undefined,
229 );
230 }
232​
233/** Check before stopping the server so full disks refuse updates without an outage. */
234export async function databaseBackupBlocker(
235 baseDir: string,
236 dbPath: string,
237 probe: Partial<BackupSpaceProbe> = {},
238): Promise<string | undefined> {
239 const { readFreeBytes, canClone } = { ...filesystemBackupSpaceProbe, ...probe };
240 const backupRoot = NodePath.join(baseDir, "runtime", "db-backup");
241 await NodeFSP.mkdir(backupRoot, { recursive: true, mode: 0o700 });
242 await removeAbandonedBackupCopies(backupRoot);
243 const [files, free] = await Promise.all([statDatabaseFiles(dbPath), readFreeBytes(backupRoot)]);
244 const size = files.reduce((total, file) => total + file.size, 0);
245 const fullCopyBytes = size * 1.05;
246 if (free >= fullCopyBytes) return undefined;
247 const clonedBytes = Math.max(
248 CLONED_BACKUP_MIN_HEADROOM_BYTES,
249 size * CLONED_BACKUP_HEADROOM_FRACTION,
250 );
251 const needed = (await canClone(dbPath, backupRoot)) ? clonedBytes : fullCopyBytes;
252 if (free >= needed) return undefined;
253 const gb = (bytes: number) => (bytes / GIB).toFixed(1);
254 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.`;
256​
257// Preserve completed backups; restarted trials may already have changed the live database.
258async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise<void> {
259 const backupDir = databaseBackupDir(baseDir, pending.id);
260 if (await pathExists(backupDir)) return;
261​
262 const stagingDir = `${backupDir}.staging`;
263 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
264 await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
265 try {
266 for (const suffix of DB_FILE_SUFFIXES) {
267 const source = `${pending.dbPath}${suffix}`;
268 if (suffix !== "" && !(await pathExists(source))) continue;
269 const destination = databaseBackupFile(stagingDir, suffix);
270 await copyDatabaseFile(source, destination);
271 await syncFile(destination);
272 }
273 await NodeFSP.rename(stagingDir, backupDir);
274 await syncDirectory(NodePath.dirname(backupDir));
275 } catch (cause) {
276 await NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
277 throw cause;
278 }
280​
281const restoreMarkerPath = (baseDir: string, updateId: string) =>
282 NodePath.join(databaseBackupDir(baseDir, updateId), RESTORE_MARKER);
283​
284const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) =>
285 pathExists(restoreMarkerPath(baseDir, pending.id));
286​
287// Mark before live writes so recovery cannot boot a partial restore.
288async function markDatabaseRestorePending(backupDir: string): Promise<void> {
289 const markerPath = NodePath.join(backupDir, RESTORE_MARKER);
290 if (!(await pathExists(markerPath))) {
291 const handle = await NodeFSP.open(markerPath, "wx", 0o600);
292 try {
293 await handle.sync();
294 } finally {
295 await handle.close();
296 }
297 await syncDirectory(backupDir);
298 }
300​
301// Resolve symlink targets even if a crashed cp -c left the final target missing.
302async function restoreTarget(path: string): Promise<string> {
303 let current = path;
304 for (let hops = 0; hops < 40; hops++) {
305 try {
306 return await NodeFSP.realpath(current);
307 } catch (cause) {
308 if ((cause as NodeJS.ErrnoException).code !== "ENOENT") throw cause;
309 }
310 const link = await NodeFSP.readlink(current).catch((cause: unknown) => {
311 const code = (cause as NodeJS.ErrnoException).code;
312 if (code === "ENOENT" || code === "EINVAL") return undefined;
313 throw cause;
314 });
315 if (link === undefined) return current;
316 // Do not normalize .. before following directory symlinks; match filesystem resolution.
317 current = NodePath.isAbsolute(link)
318 ? link
319 : `${await NodeFSP.realpath(NodePath.dirname(current))}${NodePath.sep}${link}`;
320 }
321 throw new Error(`Too many symbolic links resolving ${path}.`);
323​
324async function restoreDatabaseBackup(
325 baseDir: string,
326 pending: PendingServiceUpdate,
327): Promise<void> {
328 const backupDir = databaseBackupDir(baseDir, pending.id);
329 if (!(await pathExists(backupDir))) return;
330​
331 await markDatabaseRestorePending(backupDir);
332 const directories = new Set([NodePath.dirname(pending.dbPath)]);
333 for (const suffix of DB_FILE_SUFFIXES) {
334 const livePath = `${pending.dbPath}${suffix}`;
335 const source = databaseBackupFile(backupDir, suffix);
336 if (await pathExists(source)) {
337 // Restore into the symlink target; cloning would replace the link.
338 const target = await restoreTarget(livePath);
339 await copyDatabaseFile(source, target);
340 await syncFile(target);
341 directories.add(NodePath.dirname(target));
342 } else {
343 await NodeFSP.rm(livePath, { force: true });
344 }
345 }
346 for (const directory of directories) await syncDirectory(directory);
348​
349async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
350 const backupDir = databaseBackupDir(baseDir, updateId);
351 if (!(await pathExists(backupDir))) return;
352 await NodeFSP.rm(backupDir, { recursive: true, force: true });
353 await syncDirectory(NodePath.dirname(backupDir));
355​
356export async function readServiceState(filePath: string): Promise<ServiceState> {
357 const contents = await NodeFSP.readFile(filePath, "utf8");
358 const state = parseServiceState(contents);
359 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
360 return state;
362​
363export async function writeServiceState(filePath: string, state: ServiceState): Promise<void> {
364 const directory = NodePath.dirname(filePath);
365 await NodeFSP.mkdir(directory, { recursive: true, mode: 0o700 });
366 const tempPath = NodePath.join(
367 directory,
368 `.${NodePath.basename(filePath)}.${process.pid}.${NodeCrypto.randomUUID()}`,
369 );
370 let handle: NodeFSP.FileHandle | undefined;
371 try {
372 handle = await NodeFSP.open(tempPath, "wx", 0o600);
373 await handle.writeFile(`${JSON.stringify(state, null, 2)}\n`, "utf8");
374 await handle.sync();
375 await handle.close();
376 handle = undefined;
377 await NodeFSP.rename(tempPath, filePath);
378 await syncDirectory(directory);
379 } finally {
380 await handle?.close().catch(() => undefined);
381 await NodeFSP.rm(tempPath, { force: true }).catch(() => undefined);
382 }
384​
385async function runtimeExists(baseDir: string, version: string): Promise<boolean> {
386 const paths = runtimePaths(baseDir, version);
387 try {
388 const [entry, sentinel] = await Promise.all([
389 NodeFSP.stat(paths.entryPath),
390 NodeFSP.readFile(paths.sentinelPath, "utf8"),
391 ]);
392 return entry.isFile() && sentinel.trim() === version;
393 } catch {
394 return false;
395 }
397​
398function terminalUpdate<S extends TerminalStatus>(input: {
399 readonly pending: PendingServiceUpdate;
400 readonly status: S;
401 readonly reason?: string;
402}): Exclude<ServiceUpdateRecord, PendingServiceUpdate> & { readonly status: S } {
403 return {
404 id: input.pending.id,
405 fromVersion: input.pending.fromVersion,
406 targetVersion: input.pending.targetVersion,
407 status: input.status,
408 ...(input.reason === undefined ? {} : { reason: input.reason }),
409 };
411​
412function sendMessage(
413 child: NodeChildProcess.ChildProcess,
414 message: ServiceLauncherParentMessage,
415): Promise<void> {
416 return new Promise((resolve, reject) => {
417 if (!child.connected || child.send === undefined) {
418 reject(new Error("service child IPC is disconnected."));
419 return;
420 }
421 child.send(message, (error) => (error === null ? resolve() : reject(error)));
422 });
424​
425function waitForExit(child: NodeChildProcess.ChildProcess): Promise<void> {
426 if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
427 return new Promise((resolve) => child.once("exit", () => resolve()));
429​
430async function terminateChild(
431 child: NodeChildProcess.ChildProcess,
432 signal: NodeJS.Signals = "SIGTERM",
433): Promise<void> {
434 if (child.exitCode !== null || child.signalCode !== null) return;
435 child.kill(signal);
436 const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS);
437 try {
438 await waitForExit(child);
439 } finally {
440 clearTimeout(force);
441 }
443​
444const stopMarkerPath = (baseDir: string) =>
445 NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
446const restartPendingPath = (baseDir: string) =>
447 NodePath.join(baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
448​
449export class Launcher {
450 readonly #baseDir: string;
451 readonly #statePath: string;
452 #state: ServiceState;
453 #child: ManagedChild | null = null;
454 #timer: NodeJS.Timeout | undefined;
455 #transitions: Promise<void> = Promise.resolve();
456 #stopRequested = false;
457 #stopping = false;
458 #done = false;
459 readonly #completion = Promise.withResolvers<void>();
460 readonly #backupSpaceProbe: Partial<BackupSpaceProbe> | undefined;
461 readonly #environment: Readonly<NodeJS.ProcessEnv>;
462​
463 constructor(
464 baseDir: string,
465 state: ServiceState,
466 options: {
467 readonly backupSpaceProbe?: Partial<BackupSpaceProbe>;
468 readonly environment?: Readonly<NodeJS.ProcessEnv>;
469 } = {},
470 ) {
471 this.#baseDir = baseDir;
472 this.#backupSpaceProbe = options.backupSpaceProbe;
473 this.#environment = { ...(options.environment ?? process.env) };
474 this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
475 this.#state = state;
476 }
477​
478 async run(): Promise<void> {
479 const onSigterm = () => void this.stop("SIGTERM");
480 const onSigint = () => void this.stop("SIGINT");
481 process.once("SIGTERM", onSigterm);
482 process.once("SIGINT", onSigint);
483 try {
484 this.#enqueue(() => this.#recover());
485 await this.#completion.promise;
486 } finally {
487 process.off("SIGTERM", onSigterm);
488 process.off("SIGINT", onSigint);
489 }
490 }
491​
492 #enqueue(transition: () => Promise<void>): void {
493 this.#transitions = this.#transitions
494 .then(transition, transition)
495 .catch((cause: unknown) =>
496 this.#fatal(cause instanceof Error ? cause : new Error(String(cause))),
497 );
498 }
499​
500 async #fatal(error: Error): Promise<void> {
501 if (this.#done) return;
502 this.#done = true;
503 this.#stopping = true;
504 this.#clearTimer();
505 const child = this.#child?.process;
506 this.#child = null;
507 if (child !== undefined) await terminateChild(child);
508 this.#completion.reject(error);
509 }
510​
511 async stop(signal: NodeJS.Signals): Promise<void> {
512 // Write synchronously on signal receipt; a terminating child needs the marker in its finalizer.
513 try {
514 NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
515 } catch {}
516 if (this.#stopRequested || this.#stopping) {
517 await this.#completion.promise.catch(() => undefined);
518 return;
519 }
520 this.#stopRequested = true;
521 this.#clearTimer();
522 this.#enqueue(async () => {
523 // Let in-progress updates start replacements first; replacements observe the marker and own pre-activation tunnel cleanup.
524 this.#stopping = true;
525 const child = this.#child?.process;
526 this.#child = null;
527 if (child !== undefined) await terminateChild(child, signal);
528 this.#done = true;
529 this.#completion.resolve();
530 });
531 await this.#completion.promise.catch(() => undefined);
532 }
533​
534 #clearTimer(): void {
535 clearTimeout(this.#timer);
536 this.#timer = undefined;
537 }
538​
539 async #recover(): Promise<void> {
540 // Clear old stop markers to preserve future tunnels; clear restart-pending only for the awaited version to avoid CLI races.
541 await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
542 const restartPending = restartPendingPath(this.#baseDir);
543 const awaitedVersion = await NodeFSP.readFile(restartPending, "utf8").catch(() => undefined);
544 if (awaitedVersion?.trim() === this.#state.activeVersion) {
545 await NodeFSP.rm(restartPending, { force: true }).catch(() => undefined);
546 }
547 const update = this.#state.update;
548 if (update?.status !== "pending") {
549 if (update !== undefined) {
550 await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
551 }
552 await this.#startChild(this.#state.activeVersion, "active", update);
553 return;
554 }
555 if (await databaseRestorePending(this.#baseDir, update)) {
556 await this.#returnToPrevious(update, "failed", "rollback-interrupted");
557 return;
558 }
559 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
560 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
561 return;
562 }
563 await this.#startTrial(update);
564 }
565​
566 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
567 try {
568 await backupDatabaseOnce(this.#baseDir, pending);
569 } catch {
570 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
571 return;
572 }
573 try {
574 await this.#startChild(pending.targetVersion, "trial", pending);
575 } catch {
576 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
577 }
578 }
579​
580 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
581 if (this.#stopping) return;
582 if (!(await runtimeExists(this.#baseDir, version))) {
583 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
584 }
585 if (this.#stopping) return;
586 const paths = runtimePaths(this.#baseDir, version);
587 const context: ServiceLauncherContext = {
588 protocol: SERVICE_LAUNCHER_PROTOCOL,
589 childVersion: version,
590 ...(update === undefined ? {} : { update }),
591 };
592 const spawnArguments = runtimeSpawnArguments(paths);
593 const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
594 env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
595 stdio: ["inherit", "inherit", "inherit", "ipc"],
596 });
597 await new Promise<void>((resolve, reject) => {
598 const onError = (error: Error) => reject(error);
599 child.once("error", onError);
600 child.once("spawn", () => {
601 child.removeListener("error", onError);
602 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
603 resolve();
604 });
605 });
606 if (this.#stopping) {
607 await terminateChild(child);
608 return;
609 }
610​
611 const managed: ManagedChild = {
612 version,
613 role,
614 process: child,
615 };
616 this.#child = managed;
617 child.on("message", (value) => {
618 const message = decodeServiceLauncherChildMessage(value);
619 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
620 });
621 child.once("exit", (code, signal) =>
622 this.#enqueue(() => this.#handleExit(managed, code, signal)),
623 );
624​
625 if (role === "trial") {
626 this.#timer = setTimeout(
627 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
628 PREPARED_TIMEOUT_MS,
629 );
630 }
631 }
632​
633 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
634 if (this.#child !== child || this.#stopping) return;
635 if (message.type === "request-update") {
636 await this.#handleUpdateRequest(child, message);
637 return;
638 }
639 await this.#handlePrepared(child, message.updateId);
640 }
641​
642 async #handleUpdateRequest(
643 child: ManagedChild,
644 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
645 ): Promise<void> {
646 const reject = (reason: string) =>
647 sendMessage(child.process, { type: "update-rejected", reason });
648 if (child.role !== "active") {
649 await reject("Only the active server can request an update.");
650 return;
651 }
652 if (child.version !== this.#state.activeVersion) {
653 await reject("The requesting server is not the selected active version.");
654 return;
655 }
656 if (this.#state.update?.status === "pending") {
657 await reject("Another server update is already pending.");
658 return;
659 }
660 if (!isExactServiceVersion(message.targetVersion)) {
661 await reject("The requested target is not an exact version.");
662 return;
663 }
664 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
665 await reject("Remote updates must select a newer server version.");
666 return;
667 }
668 if (!NodePath.isAbsolute(message.dbPath)) {
669 await reject("The requested database path is not absolute.");
670 return;
671 }
672 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
673 await reject("The requested target runtime is missing or incomplete.");
674 return;
675 }
676 // Failed checks must refuse updates rather than stop the server with unknown backup capacity.
677 const backupBlocker = await databaseBackupBlocker(
678 this.#baseDir,
679 message.dbPath,
680 this.#backupSpaceProbe,
681 ).catch(
682 (error: unknown) =>
683 `Could not check that the database backup fits before updating: ${error instanceof Error ? error.message : String(error)}. The server was not stopped.`,
684 );
685 if (!child.process.connected) return;
686 if (backupBlocker !== undefined) {
687 await reject(backupBlocker);
688 return;
689 }
690​
691 const pending: PendingServiceUpdate = {
692 id: NodeCrypto.randomUUID(),
693 fromVersion: child.version,
694 targetVersion: message.targetVersion,
695 dbPath: message.dbPath,
696 status: "pending",
697 };
698 const next: ServiceState = { ...this.#state, update: pending };
699 await writeServiceState(this.#statePath, next);
700 this.#state = next;
701 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
702 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
703 }
704​
705 async #beginTrial(child: ManagedChild): Promise<void> {
706 const pending = this.#state.update;
707 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
708 return;
709 }
710 this.#timer = undefined;
711 this.#child = null;
712 await terminateChild(child.process);
713 await this.#startTrial(pending);
714 }
715​
716 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
717 const pending = this.#state.update;
718 if (
719 child.role !== "trial" ||
720 pending?.status !== "pending" ||
721 pending.id !== updateId ||
722 pending.targetVersion !== child.version
723 ) {
724 if (child.role === "trial" && pending?.status === "pending") {
725 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
726 return;
727 }
728 throw new Error("Trial child reported prepared for an unexpected update.");
729 }
730 this.#clearTimer();
731 const committed = terminalUpdate({ pending, status: "committed" });
732 const next: ServiceState = {
733 ...this.#state,
734 activeVersion: pending.targetVersion,
735 update: committed,
736 };
737 await writeServiceState(this.#statePath, next);
738 this.#state = next;
739 child.role = "active";
740 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
741 await sendMessage(child.process, { type: "committed", updateId: committed.id });
742 }
743​
744 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
745 const pending = this.#state.update;
746 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
747 return;
748 }
749 this.#timer = undefined;
750 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
751 }
752​
753 async #handleExit(
754 child: ManagedChild,
755 code: number | null,
756 signal: NodeJS.Signals | null,
757 ): Promise<void> {
758 if (this.#child !== child || this.#stopping) return;
759 this.#child = null;
760 if (code === STATE_DIR_OWNED_EXIT_CODE) {
761 await this.#idleWhileStateDirOwned();
762 return;
763 }
764 if (child.role === "trial") {
765 this.#clearTimer();
766 const pending = this.#state.update;
767 if (pending?.status !== "pending") {
768 throw new Error("Trial child exited without matching pending state.");
769 }
770 await this.#returnToPrevious(
771 pending,
772 "rolled-back",
773 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
774 );
775 return;
776 }
777​
778 this.#clearTimer();
779 const pending = this.#state.update;
780 if (pending?.status === "pending") {
781 await this.#startTrial(pending);
782 return;
783 }
784 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
785 }
786​
787 // Stay idle to avoid supervisor restart loops; never restore backups over another owner's possible writes.
788 async #idleWhileStateDirOwned(): Promise<void> {
789 this.#clearTimer();
790 const pending = this.#state.update;
791 if (pending?.status === "pending") {
792 const next: ServiceState = {
793 ...this.#state,
794 activeVersion: pending.fromVersion,
795 update: terminalUpdate({ pending, status: "failed", reason: "state-dir-owned" }),
796 };
797 await writeServiceState(this.#statePath, next);
798 this.#state = next;
799 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
800 }
801 // Signal listeners alone do not keep Node alive.
802 this.#timer = setInterval(() => {}, 2_147_483_647);
803 process.stderr.write(
804 "[service-launcher] Another T3 Code server owns this T3 home. Stop it, then restart this service.\n",
805 );
806 }
807​
808 async #returnToPrevious(
809 pending: PendingServiceUpdate,
810 status: "rolled-back" | "failed",
811 reason: string,
812 child?: ManagedChild,
813 ): Promise<void> {
814 if (child !== undefined) {
815 this.#child = null;
816 await terminateChild(child.process);
817 }
818 await restoreDatabaseBackup(this.#baseDir, pending);
819 const outcome = terminalUpdate({ pending, status, reason });
820 const next: ServiceState = {
821 ...this.#state,
822 activeVersion: pending.fromVersion,
823 update: outcome,
824 };
825 await writeServiceState(this.#statePath, next);
826 this.#state = next;
827 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
828 await this.#startChild(next.activeVersion, "active", outcome);
829 }
831​
832export async function main(): Promise<void> {
833 const baseDir = process.env.T3CODE_HOME?.trim();
834 if (baseDir === undefined || baseDir === "") {
835 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
836 }
837 const environment = await readServiceEnvironment(baseDir);
838 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
839 const state = await readServiceState(statePath);
840 await new Launcher(baseDir, state, { environment }).run();