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