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