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