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

serviceLauncher.ts

865 lines31.3 KB

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 { prepareServiceDatabaseBackup } from "./serviceDatabaseBackup.ts";
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_LAUNCHER_CONTEXT_ENV,
28 SERVICE_LAUNCHER_PROTOCOL,
29 SERVICE_STATE_FILE,
30 SERVICE_RESTART_PENDING_FILE,
31 SERVICE_STOP_MARKER_FILE,
32} from "./cloud/serviceProtocol.ts";
33​
34const HANDOFF_DELAY_MS = 2_000;
35/**
36 * Migrations count toward it and can scale with the database: tens of GB on a cold page cache
37 * take minutes. A missed window rolls back the database, so 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;
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 }
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 }
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 }
112​
113function runCp(args: ReadonlyArray<string>): Promise<boolean> {
114 return new Promise((resolve) => {
115 NodeChildProcess.execFile("cp", args, (error) => resolve(error === null));
116 });
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);
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;
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 }
194​
195export interface BackupSpaceProbe {
196 readonly readFreeBytes: (directory: string) => Promise<number>;
197 readonly canClone: (dbPath: string, backupRoot: string) => Promise<boolean>;
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.`;
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 }
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 }
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}.`);
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);
334​
335async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
336 const backupDir = databaseBackupDir(baseDir, updateId);
337 const stagingDir = `${backupDir}.staging`;
338 if (!(await pathExists(backupDir)) && !(await pathExists(stagingDir))) return;
339 await NodeFSP.rm(backupDir, { recursive: true, force: true });
340 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
341 await syncDirectory(NodePath.dirname(backupDir));
343​
344export async function readServiceState(filePath: string): Promise<ServiceState> {
345 const contents = await NodeFSP.readFile(filePath, "utf8");
346 const state = parseServiceState(contents);
347 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
348 return state;
350​
351export async function writeServiceState(filePath: string, state: ServiceState): Promise<void> {
352 const directory = NodePath.dirname(filePath);
353 await NodeFSP.mkdir(directory, { recursive: true, mode: 0o700 });
354 const tempPath = NodePath.join(
355 directory,
356 `.${NodePath.basename(filePath)}.${process.pid}.${NodeCrypto.randomUUID()}`,
357 );
358 let handle: NodeFSP.FileHandle | undefined;
359 try {
360 handle = await NodeFSP.open(tempPath, "wx", 0o600);
361 await handle.writeFile(`${JSON.stringify(state, null, 2)}\n`, "utf8");
362 await handle.sync();
363 await handle.close();
364 handle = undefined;
365 await NodeFSP.rename(tempPath, filePath);
366 await syncDirectory(directory);
367 } finally {
368 await handle?.close().catch(() => undefined);
369 await NodeFSP.rm(tempPath, { force: true }).catch(() => undefined);
370 }
372​
373async function runtimeExists(baseDir: string, version: string): Promise<boolean> {
374 const paths = runtimePaths(baseDir, version);
375 try {
376 const [entry, sentinel] = await Promise.all([
377 NodeFSP.stat(paths.entryPath),
378 NodeFSP.readFile(paths.sentinelPath, "utf8"),
379 ]);
380 return entry.isFile() && sentinel.trim() === version;
381 } catch {
382 return false;
383 }
385​
386function terminalUpdate<S extends TerminalStatus>(input: {
387 readonly pending: PendingServiceUpdate;
388 readonly status: S;
389 readonly reason?: string;
390}): Exclude<ServiceUpdateRecord, PendingServiceUpdate> & { readonly status: S } {
391 return {
392 id: input.pending.id,
393 fromVersion: input.pending.fromVersion,
394 targetVersion: input.pending.targetVersion,
395 status: input.status,
396 ...(input.reason === undefined ? {} : { reason: input.reason }),
397 };
399​
400function sendMessage(
401 child: NodeChildProcess.ChildProcess,
402 message: ServiceLauncherParentMessage,
403): Promise<void> {
404 return new Promise((resolve, reject) => {
405 if (!child.connected || child.send === undefined) {
406 reject(new Error("service child IPC is disconnected."));
407 return;
408 }
409 child.send(message, (error) => (error === null ? resolve() : reject(error)));
410 });
412​
413function waitForExit(child: NodeChildProcess.ChildProcess): Promise<void> {
414 if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
415 return new Promise((resolve) => child.once("exit", () => resolve()));
417​
418async function terminateChild(
419 child: NodeChildProcess.ChildProcess,
420 signal: NodeJS.Signals = "SIGTERM",
421): Promise<void> {
422 if (child.exitCode !== null || child.signalCode !== null) return;
423 child.kill(signal);
424 const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS);
425 try {
426 await waitForExit(child);
427 } finally {
428 clearTimeout(force);
429 }
431​
432const stopMarkerPath = (baseDir: string) =>
433 NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
434const restartPendingPath = (baseDir: string) =>
435 NodePath.join(baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
436​
437export class Launcher {
438 readonly #baseDir: string;
439 readonly #statePath: string;
440 #state: ServiceState;
441 #child: ManagedChild | null = null;
442 #timer: NodeJS.Timeout | undefined;
443 #transitions: Promise<void> = Promise.resolve();
444 #stopRequested = false;
445 #stopping = false;
446 #done = false;
447 readonly #completion = Promise.withResolvers<void>();
448 readonly #backupSpaceProbe: Partial<BackupSpaceProbe> | undefined;
449​
450 constructor(
451 baseDir: string,
452 state: ServiceState,
453 options: { readonly backupSpaceProbe?: Partial<BackupSpaceProbe> } = {},
454 ) {
455 this.#baseDir = baseDir;
456 this.#backupSpaceProbe = options.backupSpaceProbe;
457 this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
458 this.#state = state;
459 }
460​
461 async run(): Promise<void> {
462 const onSigterm = () => void this.stop("SIGTERM");
463 const onSigint = () => void this.stop("SIGINT");
464 process.once("SIGTERM", onSigterm);
465 process.once("SIGINT", onSigint);
466 try {
467 this.#enqueue(() => this.#recover());
468 await this.#completion.promise;
469 } finally {
470 process.off("SIGTERM", onSigterm);
471 process.off("SIGINT", onSigint);
472 }
473 }
474​
475 #enqueue(transition: () => Promise<void>): void {
476 this.#transitions = this.#transitions
477 .then(transition, transition)
478 .catch((cause: unknown) =>
479 this.#fatal(cause instanceof Error ? cause : new Error(String(cause))),
480 );
481 }
482​
483 async #fatal(error: Error): Promise<void> {
484 if (this.#done) return;
485 this.#done = true;
486 this.#stopping = true;
487 this.#clearTimer();
488 const child = this.#child?.process;
489 this.#child = null;
490 if (child !== undefined) await terminateChild(child);
491 this.#completion.reject(error);
492 }
493​
494 async stop(signal: NodeJS.Signals): Promise<void> {
495 // This must happen synchronously at signal receipt. A queued update
496 // transition may already be terminating the active child, and that child
497 // needs to see the marker in its shutdown finalizer.
498 try {
499 NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
500 } catch {}
501 if (this.#stopRequested || this.#stopping) {
502 await this.#completion.promise.catch(() => undefined);
503 return;
504 }
505 this.#stopRequested = true;
506 this.#clearTimer();
507 this.#enqueue(async () => {
508 // Let an update transition already in progress start its replacement
509 // before this queued stop tears it down. That replacement owns the
510 // pre-activation tunnel cleanup path and observes the marker above.
511 this.#stopping = true;
512 const child = this.#child?.process;
513 this.#child = null;
514 if (child !== undefined) await terminateChild(child, signal);
515 this.#done = true;
516 this.#completion.resolve();
517 });
518 await this.#completion.promise.catch(() => undefined);
519 }
520​
521 #clearTimer(): void {
522 clearTimeout(this.#timer);
523 this.#timer = undefined;
524 }
525​
526 async #recover(): Promise<void> {
527 // A fresh launcher means servers are running again: any stop marker from
528 // a previous explicit stop is stale and must not make a future update
529 // handoff release its tunnel. A restart deferred by `t3 update` is done
530 // no matter who restarted the service, but only once this launcher is
531 // the version the marker waits for: a launcher that came up between the
532 // CLI writing the marker and writing the new state still runs the old
533 // version, and the marker has to outlive it.
534 await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
535 const restartPending = restartPendingPath(this.#baseDir);
536 const awaitedVersion = await NodeFSP.readFile(restartPending, "utf8").catch(() => undefined);
537 if (awaitedVersion?.trim() === this.#state.activeVersion) {
538 await NodeFSP.rm(restartPending, { force: true }).catch(() => undefined);
539 }
540 const update = this.#state.update;
541 if (update?.status !== "pending") {
542 if (update !== undefined) {
543 await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
544 }
545 await this.#startChild(this.#state.activeVersion, "active", update);
546 return;
547 }
548 if (await databaseRestorePending(this.#baseDir, update)) {
549 await this.#returnToPrevious(update, "failed", "rollback-interrupted");
550 return;
551 }
552 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
553 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
554 return;
555 }
556 await this.#startTrial(update);
557 }
558​
559 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
560 try {
561 await backupDatabaseOnce(this.#baseDir, pending);
562 } catch {
563 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
564 return;
565 }
566 try {
567 await this.#startChild(pending.targetVersion, "trial", pending);
568 } catch {
569 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
570 }
571 }
572​
573 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
574 if (this.#stopping) return;
575 if (!(await runtimeExists(this.#baseDir, version))) {
576 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
577 }
578 if (this.#stopping) return;
579 const paths = runtimePaths(this.#baseDir, version);
580 const context: ServiceLauncherContext = {
581 protocol: SERVICE_LAUNCHER_PROTOCOL,
582 childVersion: version,
583 ...(update === undefined ? {} : { update }),
584 };
585 const spawnArguments = runtimeSpawnArguments(paths);
586 const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
587 env: { ...process.env, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
588 stdio: ["inherit", "inherit", "inherit", "ipc"],
589 });
590 await new Promise<void>((resolve, reject) => {
591 const onError = (error: Error) => reject(error);
592 child.once("error", onError);
593 child.once("spawn", () => {
594 child.removeListener("error", onError);
595 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
596 resolve();
597 });
598 });
599 if (this.#stopping) {
600 await terminateChild(child);
601 return;
602 }
603​
604 const managed: ManagedChild = {
605 version,
606 role,
607 process: child,
608 };
609 this.#child = managed;
610 child.on("message", (value) => {
611 const message = decodeServiceLauncherChildMessage(value);
612 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
613 });
614 child.once("exit", (code, signal) =>
615 this.#enqueue(() => this.#handleExit(managed, code, signal)),
616 );
617​
618 if (role === "trial") {
619 this.#timer = setTimeout(
620 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
621 PREPARED_TIMEOUT_MS,
622 );
623 }
624 }
625​
626 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
627 if (this.#child !== child || this.#stopping) return;
628 if (message.type === "request-update") {
629 await this.#handleUpdateRequest(child, message);
630 return;
631 }
632 await this.#handlePrepared(child, message.updateId);
633 }
634​
635 async #handleUpdateRequest(
636 child: ManagedChild,
637 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
638 ): Promise<void> {
639 const reject = (reason: string) =>
640 sendMessage(child.process, { type: "update-rejected", reason });
641 if (child.role !== "active") {
642 await reject("Only the active server can request an update.");
643 return;
644 }
645 if (child.version !== this.#state.activeVersion) {
646 await reject("The requesting server is not the selected active version.");
647 return;
648 }
649 if (this.#state.update?.status === "pending") {
650 await reject("Another server update is already pending.");
651 return;
652 }
653 if (!isExactServiceVersion(message.targetVersion)) {
654 await reject("The requested target is not an exact version.");
655 return;
656 }
657 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
658 await reject("Remote updates must select a newer server version.");
659 return;
660 }
661 if (!NodePath.isAbsolute(message.dbPath)) {
662 await reject("The requested database path is not absolute.");
663 return;
664 }
665 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
666 await reject("The requested target runtime is missing or incomplete.");
667 return;
668 }
669 // A check that cannot run refuses the update too: the alternative is
670 // stopping the server without knowing whether the backup fits.
671 const backupBlocker = await databaseBackupBlocker(
672 this.#baseDir,
673 message.dbPath,
674 this.#backupSpaceProbe,
675 ).catch(
676 (error: unknown) =>
677 `Could not check that the database backup fits before updating: ${error instanceof Error ? error.message : String(error)}. The server was not stopped.`,
678 );
679 if (!child.process.connected) return;
680 if (backupBlocker !== undefined) {
681 await reject(backupBlocker);
682 return;
683 }
684​
685 const pending: PendingServiceUpdate = {
686 id: NodeCrypto.randomUUID(),
687 fromVersion: child.version,
688 targetVersion: message.targetVersion,
689 dbPath: message.dbPath,
690 status: "pending",
691 };
692 const next: ServiceState = { ...this.#state, update: pending };
693 await writeServiceState(this.#statePath, next);
694 this.#state = next;
695 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
696 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
697 }
698​
699 async #beginTrial(child: ManagedChild): Promise<void> {
700 const pending = this.#state.update;
701 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
702 return;
703 }
704 this.#timer = undefined;
705 // Back up every update: even a trial without migrations can write incompatible payloads.
706 const backupDir = databaseBackupDir(this.#baseDir, pending.id);
707 const stagingDir = `${backupDir}.staging`;
708 let prepared: Awaited<ReturnType<typeof prepareServiceDatabaseBackup>> | undefined;
709 try {
710 if (!(await pathExists(backupDir))) {
711 prepared = await prepareServiceDatabaseBackup(pending.dbPath, stagingDir);
712 }
713 } catch {
714 // The accepted update must proceed; #startTrial falls back to a stopped copy.
715 prepared = undefined;
716 }
717 this.#child = null;
718 try {
719 await terminateChild(child.process);
720 if (prepared !== undefined) {
721 await prepared.finish();
722 await syncDirectory(stagingDir);
723 await NodeFSP.rename(stagingDir, backupDir);
724 await syncDirectory(NodePath.dirname(backupDir));
725 }
726 } catch {
727 prepared?.close();
728 prepared = undefined;
729 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
730 return;
731 } finally {
732 prepared?.close();
733 }
734 await this.#startTrial(pending);
735 }
736​
737 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
738 const pending = this.#state.update;
739 if (
740 child.role !== "trial" ||
741 pending?.status !== "pending" ||
742 pending.id !== updateId ||
743 pending.targetVersion !== child.version
744 ) {
745 if (child.role === "trial" && pending?.status === "pending") {
746 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
747 return;
748 }
749 throw new Error("Trial child reported prepared for an unexpected update.");
750 }
751 this.#clearTimer();
752 const committed = terminalUpdate({ pending, status: "committed" });
753 const next: ServiceState = {
754 ...this.#state,
755 activeVersion: pending.targetVersion,
756 update: committed,
757 };
758 await writeServiceState(this.#statePath, next);
759 this.#state = next;
760 child.role = "active";
761 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
762 await sendMessage(child.process, { type: "committed", updateId: committed.id });
763 }
764​
765 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
766 const pending = this.#state.update;
767 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
768 return;
769 }
770 this.#timer = undefined;
771 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
772 }
773​
774 async #handleExit(
775 child: ManagedChild,
776 code: number | null,
777 signal: NodeJS.Signals | null,
778 ): Promise<void> {
779 if (this.#child !== child || this.#stopping) return;
780 this.#child = null;
781 if (code === STATE_DIR_OWNED_EXIT_CODE) {
782 await this.#idleWhileStateDirOwned();
783 return;
784 }
785 if (child.role === "trial") {
786 this.#clearTimer();
787 const pending = this.#state.update;
788 if (pending?.status !== "pending") {
789 throw new Error("Trial child exited without matching pending state.");
790 }
791 await this.#returnToPrevious(
792 pending,
793 "rolled-back",
794 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
795 );
796 return;
797 }
798​
799 this.#clearTimer();
800 const pending = this.#state.update;
801 if (pending?.status === "pending") {
802 await this.#startTrial(pending);
803 return;
804 }
805 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
806 }
807​
808 /**
809 * Exiting would make systemd or launchd start another refused server, so stay
810 * idle until stopped or restarted. A pending update fails without restoring
811 * its backup: the other owner may have written to the database since.
812 */
813 async #idleWhileStateDirOwned(): Promise<void> {
814 this.#clearTimer();
815 const pending = this.#state.update;
816 if (pending?.status === "pending") {
817 const next: ServiceState = {
818 ...this.#state,
819 activeVersion: pending.fromVersion,
820 update: terminalUpdate({ pending, status: "failed", reason: "state-dir-owned" }),
821 };
822 await writeServiceState(this.#statePath, next);
823 this.#state = next;
824 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
825 }
826 // Signal listeners alone do not keep Node alive.
827 this.#timer = setInterval(() => {}, 2_147_483_647);
828 process.stderr.write(
829 "[service-launcher] Another T3 Code server owns this T3 home. Stop it, then restart this service.\n",
830 );
831 }
832​
833 async #returnToPrevious(
834 pending: PendingServiceUpdate,
835 status: "rolled-back" | "failed",
836 reason: string,
837 child?: ManagedChild,
838 ): Promise<void> {
839 if (child !== undefined) {
840 this.#child = null;
841 await terminateChild(child.process);
842 }
843 await restoreDatabaseBackup(this.#baseDir, pending);
844 const outcome = terminalUpdate({ pending, status, reason });
845 const next: ServiceState = {
846 ...this.#state,
847 activeVersion: pending.fromVersion,
848 update: outcome,
849 };
850 await writeServiceState(this.#statePath, next);
851 this.#state = next;
852 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
853 await this.#startChild(next.activeVersion, "active", outcome);
854 }
856​
857export async function main(): Promise<void> {
858 const baseDir = process.env.T3CODE_HOME?.trim();
859 if (baseDir === undefined || baseDir === "") {
860 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
861 }
862 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
863 const state = await readServiceState(statePath);
864 await new Launcher(baseDir, state).run();