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

serviceLauncher.ts

934 lines34.4 KB

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