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

serviceLauncher.ts

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