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

serviceLauncher.ts

1,330 lines50.0 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 parseLegacyServiceState,
25 disabledServiceTask,
26 parseServiceState,
27 serviceTaskIsDisabled,
28 serviceUnitBaseDirOf,
29 SERVICE_ENV_FILE,
30 SERVICE_LAUNCHER_LOCK_FILE,
31 SERVICE_LAUNCHER_CONTEXT_ENV,
32 SERVICE_LAUNCHER_PROTOCOL,
33 SERVICE_STATE_FILE,
34 SERVICE_RESTART_PENDING_FILE,
35 SERVICE_STOP_MARKER_FILE,
36 SERVICE_UNIT_ENV,
37} from "./cloud/serviceProtocol.ts";
38​
39const HANDOFF_DELAY_MS = 2_000;
40/**
41 * Migrations count toward it and can scale with the database: tens of GB on a cold page cache
42 * take minutes. A missed window rolls back the database, so the next attempt pays the same cost.
43 */
44const PREPARED_TIMEOUT_MS = 30 * 60_000;
45const TERMINATE_GRACE_MS = 5_000;
46// A replacement started by a handoff waits up to two minutes for the stopping launcher.
47const LOCK_RETRY_MS = 500;
48const LOCK_ATTEMPTS = 240;
49// Match contracts' SERVER_EXIT_CODE_STATE_DIR_OWNED without depending on Effect.
50const STATE_DIR_OWNED_EXIT_CODE = 78;
51​
52type TerminalStatus = "committed" | "rolled-back" | "failed";
53type ChildRole = "active" | "trial";
54​
55interface ManagedChild {
56 readonly version: string;
57 role: ChildRole;
58 readonly process: NodeChildProcess.ChildProcess;
60​
61const runtimePaths = (baseDir: string, version: string) => {
62 const versionDir = NodePath.join(baseDir, "runtime", "versions", version);
63 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
64 const executableName = process.platform === "win32" ? "t3.exe" : "t3";
65 return {
66 versionDir,
67 entryPath: NodePath.join(versionDir, executableName),
68 sentinelPath: NodePath.join(versionDir, ".install-complete"),
69 };
70};
71​
72const runtimeSpawnArguments = (paths: ReturnType<typeof runtimePaths>) => ({
73 command: paths.entryPath,
74 args: ["serve"],
75});
76​
77/**
78 * The unit or launch agent that `t3 service install` wrote. Its program names
79 * the runtime that ran the install, and a remote update never replaces it, so
80 * after a commit the launcher points it at the committed runtime. Otherwise the
81 * next start lands on a runtime that nothing in the service state records.
82 */
83export interface ServiceUnit {
84 readonly path: string;
85 /** systemd and Task Scheduler keep a loaded copy; launchd re-reads the plist at bootstrap. */
86 readonly reload: () => Promise<void>;
88​
89const runSchtasks = (...args: ReadonlyArray<string>) =>
90 NodeUtil.promisify(NodeChildProcess.execFile)("schtasks", args, {
91 windowsHide: true,
92 timeout: 30_000,
93 });
94​
95/**
96 * Registering replaces the task, so one the CLI disabled to keep the service stopped is
97 * registered disabled. The caller holds the unit lease, as the CLI does to disable it.
98 */
99export async function registerServiceTask(
100 unitPath: string,
101 taskName: string,
102 schtasks: (...args: ReadonlyArray<string>) => Promise<{ readonly stdout: string }> = runSchtasks,
103): Promise<void> {
104 const register = (xmlPath: string) => schtasks("/Create", "/XML", xmlPath, "/TN", taskName, "/F");
105 const registered = await schtasks("/Query", "/TN", taskName, "/XML");
106 if (!serviceTaskIsDisabled(registered.stdout)) {
107 await register(unitPath);
108 return;
109 }
110 const disabledPath = `${unitPath}.${process.pid}.disabled`;
111 try {
112 const unit = await NodeFSP.readFile(unitPath, "utf8");
113 await NodeFSP.writeFile(disabledPath, disabledServiceTask(unit));
114 await register(disabledPath);
115 } finally {
116 await NodeFSP.rm(disabledPath, { force: true });
117 }
119​
120function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): ServiceUnit | undefined {
121 const unitName = env[SERVICE_UNIT_ENV]?.trim();
122 if (!unitName) return undefined;
123 if (unitName.endsWith(".xml")) {
124 const localAppData = env.LOCALAPPDATA?.trim();
125 if (!localAppData) return undefined;
126 const path = NodePath.win32.join(localAppData, "t3code", unitName);
127 const taskName = serviceTaskName(env.USERDOMAIN ?? "", env.USERNAME ?? "");
128 return { path, reload: () => registerServiceTask(path, taskName) };
129 }
130 const home = env.HOME?.trim();
131 if (!home) return undefined;
132 if (unitName.endsWith(".plist")) {
133 return {
134 path: NodePath.join(home, "Library", "LaunchAgents", unitName),
135 reload: () => Promise.resolve(),
136 };
137 }
138 // The manager's own environment, which decides where it reads user units.
139 const xdgConfigHome = env.XDG_CONFIG_HOME?.trim();
140 const configHome =
141 xdgConfigHome && NodePath.isAbsolute(xdgConfigHome)
142 ? xdgConfigHome
143 : NodePath.join(home, ".config");
144 return {
145 path: NodePath.join(configHome, "systemd", "user", unitName),
146 reload: () =>
147 new Promise((resolve, reject) => {
148 NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], {
149 stdio: "ignore",
150 timeout: 30_000,
151 })
152 .once("error", reject)
153 .once("exit", (code, signal) =>
154 code === 0
155 ? resolve()
156 : reject(new Error(`systemctl --user daemon-reload exited with ${code ?? signal}`)),
157 );
158 }),
159 };
161​
162// systemd's ExecStart value, or the plist string or task argument before __service-launcher.
163// Only the version segment changes, so quoted or escaped paths stay as rendered.
164// The launch agent's PATH names a versions directory without the executable; leave it.
165const SERVICE_UNIT_PROGRAMS = [
166 /^(ExecStart=.*?[\\/]runtime[\\/]versions[\\/])([^\\/\s"]+)([\\/]t3)(?=["\s])/m,
167 /(<string>[^<]*?[\\/]runtime[\\/]versions[\\/])([^\\/<]+)([\\/]t3<\/string>\s*<string>__service-launcher<\/string>)/,
168 /(<Arguments>--headless "[^"<]*?[\\/]runtime[\\/]versions[\\/])([^\\/"<]+)([\\/]t3\.exe" "__service-launcher")/,
169] as const;
170​
171/**
172 * The unit contents with their program pointed at `version`'s runtime. A unit
173 * already at that version or a newer one is returned unchanged: `t3 update`
174 * may have repointed it to a later version while this commit was in flight.
175 */
176function repointServiceUnit(contents: string, version: string): string {
177 for (const program of SERVICE_UNIT_PROGRAMS) {
178 const match = program.exec(contents);
179 if (match === null) continue;
180 const [, prefix = "", current = "", suffix = ""] = match;
181 if (isExactServiceVersion(current) && compareExactServiceVersions(current, version) >= 0) {
182 return contents;
183 }
184 return contents.replace(program, () => `${prefix}${version}${suffix}`);
185 }
186 return contents;
188​
189const DB_FILE_SUFFIXES = ["", "-wal", "-shm"] as const;
190const RESTORE_MARKER = ".restore-pending";
191​
192const databaseBackupDir = (baseDir: string, updateId: string) =>
193 NodePath.join(baseDir, "runtime", "db-backup", updateId);
194​
195const databaseBackupFile = (backupDir: string, suffix: (typeof DB_FILE_SUFFIXES)[number]) =>
196 NodePath.join(backupDir, suffix === "" ? "database" : `database${suffix}`);
197​
198async function pathExists(target: string): Promise<boolean> {
199 try {
200 await NodeFSP.access(target);
201 return true;
202 } catch (cause) {
203 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return false;
204 throw cause;
205 }
207​
208const MANAGED_SERVICE_ENV_NAMES = new Set([
209 "PATH",
210 "T3CODE_HOME",
211 "T3_BOOT_SERVICE_UNIT",
212 SERVICE_LAUNCHER_CONTEXT_ENV,
213]);
214​
215export async function readServiceEnvironment(
216 baseDir: string,
217 inherited: NodeJS.ProcessEnv = process.env,
218): Promise<NodeJS.ProcessEnv> {
219 const environment = { ...inherited };
220 let contents: string;
221 try {
222 contents = await NodeFSP.readFile(NodePath.join(baseDir, SERVICE_ENV_FILE), "utf8");
223 } catch (cause) {
224 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return environment;
225 throw cause;
226 }
227 for (const [name, value] of Object.entries(NodeUtil.parseEnv(contents))) {
228 if (
229 /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) &&
230 !MANAGED_SERVICE_ENV_NAMES.has(name.toUpperCase())
231 ) {
232 environment[name] = value;
233 }
234 }
235 return environment;
237​
238// Opened read-write: Windows refuses to flush a handle without write access.
239async function syncFile(filePath: string): Promise<void> {
240 const handle = await NodeFSP.open(filePath, "r+");
241 try {
242 await handle.sync();
243 } finally {
244 await handle.close();
245 }
247​
248// Fsync makes renames durable; Windows returns EPERM and NTFS journals them itself.
249async function syncDirectory(directory: string): Promise<void> {
250 const handle = await NodeFSP.open(directory, "r");
251 try {
252 await handle.sync();
253 } catch (error) {
254 if ((error as NodeJS.ErrnoException).code !== "EPERM") throw error;
255 } finally {
256 await handle.close();
257 }
259​
260function runCp(args: ReadonlyArray<string>): Promise<boolean> {
261 return new Promise((resolve) => {
262 NodeChildProcess.execFile("cp", args, (error) => resolve(error === null));
263 });
265​
266// macOS fs.copyFile clone flags fall back to full copies.
267async function copyDatabaseFile(source: string, destination: string): Promise<void> {
268 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
269 const platform = process.platform;
270 // cp -c replaces files and breaks hard links; copy into hard-linked destinations instead.
271 const hardLinked =
272 platform === "darwin" &&
273 ((await NodeFSP.stat(destination).catch(() => undefined))?.nlink ?? 1) > 1;
274 const args =
275 platform === "darwin" && !hardLinked
276 ? ["-c", source, destination]
277 : platform === "linux"
278 ? ["--reflink=auto", source, destination]
279 : undefined;
280 if (args === undefined || !(await runCp(args))) await NodeFSP.copyFile(source, destination);
282​
283const GIB = 1024 ** 3;
284// Cloned backups still need headroom for trial writes and migrations to diverge.
285const CLONED_BACKUP_MIN_HEADROOM_BYTES = GIB;
286const CLONED_BACKUP_HEADROOM_FRACTION = 0.1;
287// While the online backup holds its snapshot, the live WAL and its copy can each reach the server's 128 MiB gate.
288const ONLINE_BACKUP_WAL_HEADROOM_BYTES = 2 * 128 * 1024 ** 2;
289​
290async function statDatabaseFiles(dbPath: string): Promise<ReadonlyArray<NodeFS.Stats>> {
291 const stats: Array<NodeFS.Stats> = [];
292 for (const suffix of DB_FILE_SUFFIXES) {
293 const stat = await NodeFSP.stat(`${dbPath}${suffix}`).catch((cause: unknown) => {
294 if (suffix !== "" && (cause as NodeJS.ErrnoException).code === "ENOENT") return undefined;
295 throw cause;
296 });
297 if (stat !== undefined) stats.push(stat);
298 }
299 return stats;
301​
302// cp -c silently copies across volumes; require one device matching the APFS system volume's filesystem type.
303async function backupCanClone(dbPath: string, backupRoot: string): Promise<boolean> {
304 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
305 const platform = process.platform;
306 if (platform === "darwin") {
307 const [backupDirectory, backupFs, systemFs] = await Promise.all([
308 NodeFSP.stat(backupRoot),
309 NodeFSP.statfs(backupRoot),
310 NodeFSP.statfs("/"),
311 ]);
312 if (backupFs.type !== systemFs.type) return false;
313 return (await statDatabaseFiles(dbPath)).every(
314 (source) => source.dev === backupDirectory.dev && source.nlink === 1,
315 );
316 }
317 if (platform !== "linux") return false;
318 const probe = NodePath.join(backupRoot, `.clone-probe-${NodeCrypto.randomUUID()}`);
319 try {
320 for (const suffix of DB_FILE_SUFFIXES) {
321 const source = `${dbPath}${suffix}`;
322 if (suffix !== "" && !(await pathExists(source))) continue;
323 if (!(await runCp(["--reflink=always", source, `${probe}${suffix}`]))) return false;
324 }
325 return true;
326 } finally {
327 for (const suffix of DB_FILE_SUFFIXES) {
328 await NodeFSP.rm(`${probe}${suffix}`, { force: true }).catch(() => undefined);
329 }
330 }
332​
333export interface BackupSpaceProbe {
334 readonly readFreeBytes: (directory: string) => Promise<number>;
335 readonly canClone: (dbPath: string, backupRoot: string) => Promise<boolean>;
337​
338const filesystemBackupSpaceProbe: BackupSpaceProbe = {
339 readFreeBytes: async (directory) => {
340 const stats = await NodeFSP.statfs(directory);
341 return stats.bavail * stats.bsize;
342 },
343 canClone: backupCanClone,
344};
345​
346// A killed launcher skips the backup's cleanup, and retries only clear their own update's copy.
347// Update requests are refused while one is pending, so no staging directory is still in use here.
348async function removeAbandonedBackupCopies(backupRoot: string): Promise<void> {
349 for (const entry of await NodeFSP.readdir(backupRoot)) {
350 if (!entry.endsWith(".staging")) continue;
351 await NodeFSP.rm(NodePath.join(backupRoot, entry), { recursive: true, force: true }).catch(
352 () => undefined,
353 );
354 }
356​
357/** Check before stopping the server so full disks refuse updates without an outage. */
358export async function databaseBackupBlocker(
359 baseDir: string,
360 dbPath: string,
361 probe: Partial<BackupSpaceProbe> = {},
362): Promise<string | undefined> {
363 const { readFreeBytes, canClone } = { ...filesystemBackupSpaceProbe, ...probe };
364 const backupRoot = NodePath.join(baseDir, "runtime", "db-backup");
365 await NodeFSP.mkdir(backupRoot, { recursive: true, mode: 0o700 });
366 await removeAbandonedBackupCopies(backupRoot);
367 const [files, free] = await Promise.all([statDatabaseFiles(dbPath), readFreeBytes(backupRoot)]);
368 const size = files.reduce((total, file) => total + file.size, 0);
369 const fullCopyBytes = size * 1.05 + ONLINE_BACKUP_WAL_HEADROOM_BYTES;
370 if (free >= fullCopyBytes) return undefined;
371 const clonedBytes = Math.max(
372 CLONED_BACKUP_MIN_HEADROOM_BYTES,
373 size * CLONED_BACKUP_HEADROOM_FRACTION,
374 );
375 const needed = (await canClone(dbPath, backupRoot)) ? clonedBytes : fullCopyBytes;
376 if (free >= needed) return undefined;
377 const gb = (bytes: number) => (bytes / GIB).toFixed(1);
378 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.`;
380​
381// A child-process copy: closing any descriptor this process opens on the database drops the snapshot's POSIX locks.
382async function copyWithoutOpening(source: string, destination: string): Promise<void> {
383 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
384 if (process.platform === "win32") return NodeFSP.copyFile(source, destination);
385 if (!(await runCp([source, destination]))) throw new Error(`cp ${source} failed.`);
387​
388// Copies the main file while the server runs; an open read transaction stops SQLite resetting the WAL,
389// which `finish` copies after the stop and which overrides any page the copy caught mid-checkpoint.
390// `-shm` is left out: its backfill count would make SQLite trust those pages. Past the WAL size gate,
391// a write-heavy server's new writes wait, uncommitted, until the server stops.
392async function startOnlineDatabaseBackup(
393 baseDir: string,
394 pending: PendingServiceUpdate,
395 probe: Partial<BackupSpaceProbe> = {},
396): Promise<(() => Promise<void>) | undefined> {
397 const backupDir = databaseBackupDir(baseDir, pending.id);
398 if (await pathExists(backupDir)) return undefined;
399 const { canClone } = { ...filesystemBackupSpaceProbe, ...probe };
400 if (await canClone(pending.dbPath, NodePath.dirname(backupDir)).catch(() => true))
401 return undefined;
402 const NodeSqlite = await import("node:sqlite").catch(() => undefined);
403 if (NodeSqlite === undefined) return undefined;
404​
405 const stagingDir = `${backupDir}.staging`;
406 const discardStaging = () =>
407 NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
408 const fallBack = async (cause: unknown) => {
409 await discardStaging();
410 process.stderr.write(
411 `[service-launcher] Copying the database while the server runs failed; backing it up offline: ${cause instanceof Error ? cause.message : String(cause)}\n`,
412 );
413 return undefined;
414 };
415 let snapshot: InstanceType<typeof NodeSqlite.DatabaseSync> | undefined;
416 // SQLite keeps -wal beside the resolved file, not beside a symlink to it.
417 let dbPath = pending.dbPath;
418 const release = () => {
419 try {
420 snapshot?.close();
421 } catch {}
422 snapshot = undefined;
423 };
424 try {
425 await discardStaging();
426 await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
427 dbPath = await NodeFSP.realpath(pending.dbPath);
428 snapshot = new NodeSqlite.DatabaseSync(dbPath, { readOnly: true });
429 const mode = String(snapshot.prepare("PRAGMA journal_mode").get()?.journal_mode);
430 if (mode.toLowerCase() !== "wal") throw new Error(`journal_mode is ${mode}, not wal.`);
431 snapshot.exec("BEGIN");
432 snapshot.prepare("SELECT count(*) FROM sqlite_schema").get();
433 const mainCopy = databaseBackupFile(stagingDir, "");
434 await copyWithoutOpening(dbPath, mainCopy);
435 await syncFile(mainCopy);
436 } catch (cause) {
437 release();
438 return fallBack(cause);
439 }
440 return async () => {
441 try {
442 const wal = `${dbPath}-wal`;
443 if (!(await pathExists(wal)))
444 throw new Error("the WAL disappeared while the snapshot was open.");
445 const walCopy = databaseBackupFile(stagingDir, "-wal");
446 await copyWithoutOpening(wal, walCopy);
447 await syncFile(walCopy);
448 release();
449 await NodeFSP.rename(stagingDir, backupDir);
450 await syncDirectory(NodePath.dirname(backupDir));
451 } catch (cause) {
452 release();
453 await fallBack(cause);
454 }
455 };
457​
458// Preserve completed backups; restarted trials may already have changed the live database.
459async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise<void> {
460 const backupDir = databaseBackupDir(baseDir, pending.id);
461 if (await pathExists(backupDir)) return;
462​
463 const stagingDir = `${backupDir}.staging`;
464 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
465 await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
466 try {
467 for (const suffix of DB_FILE_SUFFIXES) {
468 const source = `${pending.dbPath}${suffix}`;
469 if (suffix !== "" && !(await pathExists(source))) continue;
470 const destination = databaseBackupFile(stagingDir, suffix);
471 await copyDatabaseFile(source, destination);
472 await syncFile(destination);
473 }
474 await NodeFSP.rename(stagingDir, backupDir);
475 await syncDirectory(NodePath.dirname(backupDir));
476 } catch (cause) {
477 await NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
478 throw cause;
479 }
481​
482const restoreMarkerPath = (baseDir: string, updateId: string) =>
483 NodePath.join(databaseBackupDir(baseDir, updateId), RESTORE_MARKER);
484​
485const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) =>
486 pathExists(restoreMarkerPath(baseDir, pending.id));
487​
488// Mark before live writes so recovery cannot boot a partial restore.
489async function markDatabaseRestorePending(backupDir: string): Promise<void> {
490 const markerPath = NodePath.join(backupDir, RESTORE_MARKER);
491 if (!(await pathExists(markerPath))) {
492 const handle = await NodeFSP.open(markerPath, "wx", 0o600);
493 try {
494 await handle.sync();
495 } finally {
496 await handle.close();
497 }
498 await syncDirectory(backupDir);
499 }
501​
502// Resolve symlink targets even if a crashed cp -c left the final target missing.
503async function restoreTarget(path: string): Promise<string> {
504 let current = path;
505 for (let hops = 0; hops < 40; hops++) {
506 try {
507 return await NodeFSP.realpath(current);
508 } catch (cause) {
509 if ((cause as NodeJS.ErrnoException).code !== "ENOENT") throw cause;
510 }
511 const link = await NodeFSP.readlink(current).catch((cause: unknown) => {
512 const code = (cause as NodeJS.ErrnoException).code;
513 if (code === "ENOENT" || code === "EINVAL") return undefined;
514 throw cause;
515 });
516 if (link === undefined) return current;
517 // Do not normalize .. before following directory symlinks; match filesystem resolution.
518 current = NodePath.isAbsolute(link)
519 ? link
520 : `${await NodeFSP.realpath(NodePath.dirname(current))}${NodePath.sep}${link}`;
521 }
522 throw new Error(`Too many symbolic links resolving ${path}.`);
524​
525async function restoreDatabaseBackup(
526 baseDir: string,
527 pending: PendingServiceUpdate,
528): Promise<void> {
529 const backupDir = databaseBackupDir(baseDir, pending.id);
530 if (!(await pathExists(backupDir))) return;
531​
532 await markDatabaseRestorePending(backupDir);
533 const directories = new Set([NodePath.dirname(pending.dbPath)]);
534 // SQLite keeps -wal and -shm beside the resolved database file, not beside a symlink to it.
535 const mainTarget = await restoreTarget(pending.dbPath);
536 for (const suffix of DB_FILE_SUFFIXES) {
537 const livePath = suffix === "" ? pending.dbPath : `${mainTarget}${suffix}`;
538 if (livePath !== `${pending.dbPath}${suffix}`) {
539 await NodeFSP.rm(`${pending.dbPath}${suffix}`, { force: true });
540 }
541 const source = databaseBackupFile(backupDir, suffix);
542 if (await pathExists(source)) {
543 // Restore into the symlink target; cloning would replace the link.
544 const target = await restoreTarget(livePath);
545 await copyDatabaseFile(source, target);
546 await syncFile(target);
547 directories.add(NodePath.dirname(target));
548 } else {
549 await NodeFSP.rm(livePath, { force: true });
550 }
551 }
552 for (const directory of directories) await syncDirectory(directory);
554​
555async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
556 const backupDir = databaseBackupDir(baseDir, updateId);
557 if (!(await pathExists(backupDir))) return;
558 await NodeFSP.rm(backupDir, { recursive: true, force: true });
559 await syncDirectory(NodePath.dirname(backupDir));
561​
562export async function readServiceState(filePath: string): Promise<ServiceState> {
563 const contents = await NodeFSP.readFile(filePath, "utf8");
564 const state = parseServiceState(contents) ?? adoptLegacyServiceState(contents);
565 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
566 return state;
568​
569// An older coordinator can write protocol 2 beside a newer runtime. Adopt
570// only its install record, in memory: rewriting it outside the selection lock
571// could replace state a concurrent install wrote after this read.
572function adoptLegacyServiceState(contents: string): ServiceState | undefined {
573 const legacy = parseLegacyServiceState(contents);
574 return legacy && { protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: legacy.activeVersion };
576​
577export async function writeServiceState(filePath: string, state: ServiceState): Promise<void> {
578 await NodeFSP.mkdir(NodePath.dirname(filePath), { recursive: true, mode: 0o700 });
579 await replaceFileDurably(filePath, `${JSON.stringify(state, null, 2)}\n`);
581​
582async function replaceFileDurably(filePath: string, contents: string): Promise<void> {
583 const directory = NodePath.dirname(filePath);
584 const tempPath = NodePath.join(
585 directory,
586 `.${NodePath.basename(filePath)}.${process.pid}.${NodeCrypto.randomUUID()}`,
587 );
588 let handle: NodeFSP.FileHandle | undefined;
589 try {
590 handle = await NodeFSP.open(tempPath, "wx", 0o600);
591 await handle.writeFile(contents, "utf8");
592 await handle.sync();
593 await handle.close();
594 handle = undefined;
595 await NodeFSP.rename(tempPath, filePath);
596 await syncDirectory(directory);
597 } finally {
598 await handle?.close().catch(() => undefined);
599 await NodeFSP.rm(tempPath, { force: true }).catch(() => undefined);
600 }
602​
603async function runtimeExists(baseDir: string, version: string): Promise<boolean> {
604 const paths = runtimePaths(baseDir, version);
605 try {
606 const [entry, sentinel] = await Promise.all([
607 NodeFSP.stat(paths.entryPath),
608 NodeFSP.readFile(paths.sentinelPath, "utf8"),
609 ]);
610 return entry.isFile() && sentinel.trim() === version;
611 } catch {
612 return false;
613 }
615​
616function terminalUpdate<S extends TerminalStatus>(input: {
617 readonly pending: PendingServiceUpdate;
618 readonly status: S;
619 readonly reason?: string;
620}): Exclude<ServiceUpdateRecord, PendingServiceUpdate> & { readonly status: S } {
621 return {
622 id: input.pending.id,
623 fromVersion: input.pending.fromVersion,
624 targetVersion: input.pending.targetVersion,
625 status: input.status,
626 ...(input.reason === undefined ? {} : { reason: input.reason }),
627 };
629​
630function sendMessage(
631 child: NodeChildProcess.ChildProcess,
632 message: ServiceLauncherParentMessage,
633): Promise<void> {
634 return new Promise((resolve, reject) => {
635 if (!child.connected || child.send === undefined) {
636 reject(new Error("service child IPC is disconnected."));
637 return;
638 }
639 child.send(message, (error) => (error === null ? resolve() : reject(error)));
640 });
642​
643function waitForExit(child: NodeChildProcess.ChildProcess): Promise<void> {
644 if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
645 return new Promise((resolve) => child.once("exit", () => resolve()));
647​
648async function terminateChild(
649 child: NodeChildProcess.ChildProcess,
650 signal: NodeJS.Signals,
651 overIpc: boolean,
652): Promise<void> {
653 if (child.exitCode !== null || child.signalCode !== null) return;
654 if (overIpc) {
655 await sendMessage(child, { type: "stop" }).catch(() => child.kill(signal));
656 } else {
657 child.kill(signal);
658 }
659 const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS);
660 try {
661 await waitForExit(child);
662 } finally {
663 clearTimeout(force);
664 }
666​
667/** Task Scheduler names are machine-wide, so each Windows account runs its own task. */
668export const serviceTaskName = (domain: string, userName: string) => `t3code-${domain}-${userName}`;
669​
670export const serviceLauncherLockPath = (baseDir: string) =>
671 NodePath.join(baseDir, "runtime", SERVICE_LAUNCHER_LOCK_FILE);
672​
673// An exclusive SQLite transaction, like the server's owner lock: the OS drops it when the holder dies.
674async function tryAcquireLauncherLock(
675 lockPath: string,
676): Promise<{ readonly close: () => void } | undefined> {
677 const { DatabaseSync } = await import("node:sqlite");
678 const db = new DatabaseSync(lockPath);
679 try {
680 db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
681 return db;
682 } catch (cause) {
683 db.close();
684 if (cause instanceof Error && "errcode" in cause && cause.errcode === 5) return undefined;
685 throw cause;
686 }
688​
689export async function serviceLauncherIsRunning(lockPath: string): Promise<boolean> {
690 if (!NodeFS.existsSync(lockPath)) return false;
691 const lock = await tryAcquireLauncherLock(lockPath);
692 lock?.close();
693 return lock === undefined;
695​
696/** Resolves once no launcher holds the lock; the caller bounds the wait through `signal`. */
697export async function waitForServiceLauncherExit(
698 lockPath: string,
699 signal: AbortSignal,
700): Promise<void> {
701 while (await serviceLauncherIsRunning(lockPath)) {
702 signal.throwIfAborted();
703 await new Promise((resolve) => setTimeout(resolve, 100));
704 }
706​
707const stopMarkerPath = (baseDir: string) =>
708 NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
709const restartPendingPath = (baseDir: string) =>
710 NodePath.join(baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
711​
712export class Launcher {
713 readonly #baseDir: string;
714 readonly #statePath: string;
715 #state: ServiceState;
716 #child: ManagedChild | null = null;
717 #timer: NodeJS.Timeout | undefined;
718 #transitions: Promise<void> = Promise.resolve();
719 #stopRequested = false;
720 #stopping = false;
721 #done = false;
722 readonly #completion = Promise.withResolvers<void>();
723 readonly #backupSpaceProbe: Partial<BackupSpaceProbe> | undefined;
724 readonly #serviceUnit: ServiceUnit | undefined;
725 readonly #environment: Readonly<NodeJS.ProcessEnv>;
726 readonly #output: number | undefined;
727 readonly #lockPath: string | undefined;
728 readonly #stopChildOverIpc: boolean;
729​
730 constructor(
731 baseDir: string,
732 state: ServiceState,
733 options: {
734 readonly backupSpaceProbe?: Partial<BackupSpaceProbe>;
735 readonly serviceUnit?: ServiceUnit;
736 readonly environment?: Readonly<NodeJS.ProcessEnv>;
737 /** Launcher and server output, for managers that cannot redirect it. */
738 readonly output?: number;
739 /** Makes this the only launcher for its home; a replacement waits for the one stopping. */
740 readonly lockPath?: string;
741 /** Windows `kill()` is TerminateProcess, which skips the server's shutdown finalizers. */
742 readonly stopChildOverIpc?: boolean;
743 } = {},
744 ) {
745 this.#baseDir = baseDir;
746 this.#backupSpaceProbe = options.backupSpaceProbe;
747 this.#serviceUnit = options.serviceUnit;
748 this.#environment = { ...(options.environment ?? process.env) };
749 this.#output = options.output;
750 this.#lockPath = options.lockPath;
751 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
752 this.#stopChildOverIpc = options.stopChildOverIpc ?? process.platform === "win32";
753 this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
754 this.#state = state;
755 }
756​
757 async run(): Promise<void> {
758 const onSigterm = () => void this.stop("SIGTERM");
759 const onSigint = () => void this.stop("SIGINT");
760 process.once("SIGTERM", onSigterm);
761 process.once("SIGINT", onSigint);
762 try {
763 const lock =
764 this.#lockPath === undefined ? undefined : await this.#acquireLock(this.#lockPath);
765 try {
766 // The launcher that held the lock may have moved the state since main read it.
767 if (lock !== undefined) this.#state = await readServiceState(this.#statePath);
768 // A stop that arrived before this point leaves nothing to start or recover.
769 if (!this.#stopRequested) this.#enqueue(() => this.#recover());
770 await this.#completion.promise;
771 } finally {
772 if (lock !== undefined) {
773 // Releasing the lock says this launcher is done with the home.
774 await this.#transitions.catch(() => undefined);
775 lock.close();
776 }
777 }
778 } finally {
779 process.off("SIGTERM", onSigterm);
780 process.off("SIGINT", onSigint);
781 }
782 }
783​
784 async #acquireLock(lockPath: string): Promise<{ readonly close: () => void } | undefined> {
785 for (let attempt = 1; !this.#stopRequested; attempt++) {
786 const lock = await tryAcquireLauncherLock(lockPath);
787 if (lock !== undefined) return lock;
788 if (attempt >= LOCK_ATTEMPTS) {
789 throw new Error("Another T3 Code service launcher still runs for this T3 home.");
790 }
791 await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
792 }
793 return undefined;
794 }
795​
796 #terminate(child: NodeChildProcess.ChildProcess, signal: NodeJS.Signals = "SIGTERM") {
797 return terminateChild(child, signal, this.#stopChildOverIpc);
798 }
799​
800 #log(line: string): void {
801 if (this.#output === undefined) process.stderr.write(line);
802 else NodeFS.writeSync(this.#output, line);
803 }
804​
805 #enqueue(transition: () => Promise<void>): void {
806 this.#transitions = this.#transitions
807 .then(transition, transition)
808 .catch((cause: unknown) =>
809 this.#fatal(cause instanceof Error ? cause : new Error(String(cause))),
810 );
811 }
812​
813 async #fatal(error: Error): Promise<void> {
814 if (this.#done) return;
815 this.#done = true;
816 this.#stopping = true;
817 this.#clearTimer();
818 const child = this.#child?.process;
819 this.#child = null;
820 if (child !== undefined) await this.#terminate(child);
821 this.#completion.reject(error);
822 }
823​
824 async stop(signal: NodeJS.Signals): Promise<void> {
825 // Write synchronously on signal receipt; a terminating child needs the marker in its finalizer.
826 try {
827 NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
828 } catch {}
829 if (this.#stopRequested || this.#stopping) {
830 await this.#completion.promise.catch(() => undefined);
831 return;
832 }
833 this.#stopRequested = true;
834 this.#clearTimer();
835 this.#enqueue(async () => {
836 // Let in-progress updates start replacements first; replacements observe the marker and own pre-activation tunnel cleanup.
837 this.#stopping = true;
838 const child = this.#child?.process;
839 this.#child = null;
840 if (child !== undefined) await this.#terminate(child, signal);
841 this.#done = true;
842 this.#completion.resolve();
843 });
844 await this.#completion.promise.catch(() => undefined);
845 }
846​
847 #clearTimer(): void {
848 clearTimeout(this.#timer);
849 this.#timer = undefined;
850 }
851​
852 async #selectState(next: ServiceState): Promise<void> {
853 const release = await acquireServiceSelectionLock(this.#statePath);
854 try {
855 const selected = await readServiceState(this.#statePath);
856 // Local installs replace the selection and clear its update record. An old
857 // launcher must not restore its own selection when asked to update again.
858 if (
859 selected.activeVersion !== this.#state.activeVersion ||
860 selected.update?.id !== this.#state.update?.id ||
861 selected.update?.status !== this.#state.update?.status
862 ) {
863 throw new Error("Service selection changed. Restart the service before updating.");
864 }
865 await writeServiceState(this.#statePath, next);
866 this.#state = next;
867 } finally {
868 release();
869 }
870 }
871​
872 async #recover(): Promise<void> {
873 // Clear old stop markers to preserve future tunnels; clear restart-pending only for the awaited version to avoid CLI races.
874 await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
875 const restartPending = restartPendingPath(this.#baseDir);
876 try {
877 const release = await acquireServiceSelectionLock(this.#statePath);
878 try {
879 const selected = await readServiceState(this.#statePath);
880 const awaitedVersion = await NodeFSP.readFile(restartPending, "utf8").catch(
881 () => undefined,
882 );
883 const awaited = awaitedVersion?.trim();
884 if (
885 selected.activeVersion === this.#state.activeVersion &&
886 selected.update?.id === this.#state.update?.id &&
887 selected.update?.status === this.#state.update?.status &&
888 awaited !== undefined &&
889 isExactServiceVersion(awaited) &&
890 compareExactServiceVersions(awaited, this.#state.activeVersion) <= 0
891 ) {
892 await NodeFSP.rm(restartPending, { force: true });
893 }
894 } finally {
895 release();
896 }
897 } catch (error) {
898 process.stderr.write(
899 `[service-launcher] Could not clear ${restartPending}: ${error instanceof Error ? error.message : String(error)}\n`,
900 );
901 }
902 const update = this.#state.update;
903 if (update?.status !== "pending") {
904 if (update !== undefined) {
905 await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
906 }
907 try {
908 await this.#startChild(this.#state.activeVersion, "active", update);
909 } finally {
910 if (update !== undefined) await this.#repointServiceUnit(this.#state.activeVersion);
911 }
912 return;
913 }
914 if (await databaseRestorePending(this.#baseDir, update)) {
915 await this.#returnToPrevious(update, "failed", "rollback-interrupted");
916 return;
917 }
918 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
919 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
920 return;
921 }
922 await this.#startTrial(update);
923 }
924​
925 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
926 try {
927 await backupDatabaseOnce(this.#baseDir, pending);
928 } catch {
929 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
930 return;
931 }
932 try {
933 await this.#startChild(pending.targetVersion, "trial", pending);
934 } catch {
935 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
936 }
937 }
938​
939 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
940 if (this.#stopping) return;
941 if (!(await runtimeExists(this.#baseDir, version))) {
942 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
943 }
944 if (this.#stopping) return;
945 const paths = runtimePaths(this.#baseDir, version);
946 const context: ServiceLauncherContext = {
947 protocol: SERVICE_LAUNCHER_PROTOCOL,
948 childVersion: version,
949 ...(update === undefined ? {} : { update }),
950 };
951 const spawnArguments = runtimeSpawnArguments(paths);
952 const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
953 env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
954 stdio:
955 this.#output === undefined
956 ? ["inherit", "inherit", "inherit", "ipc"]
957 : ["ignore", this.#output, this.#output, "ipc"],
958 });
959 await new Promise<void>((resolve, reject) => {
960 const onError = (error: Error) => reject(error);
961 child.once("error", onError);
962 child.once("spawn", () => {
963 child.removeListener("error", onError);
964 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
965 resolve();
966 });
967 });
968 if (this.#stopping) {
969 await this.#terminate(child);
970 return;
971 }
972​
973 const managed: ManagedChild = {
974 version,
975 role,
976 process: child,
977 };
978 this.#child = managed;
979 child.on("message", (value) => {
980 const message = decodeServiceLauncherChildMessage(value);
981 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
982 });
983 child.once("exit", (code, signal) =>
984 this.#enqueue(() => this.#handleExit(managed, code, signal)),
985 );
986​
987 if (role === "trial") {
988 this.#timer = setTimeout(
989 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
990 PREPARED_TIMEOUT_MS,
991 );
992 }
993 }
994​
995 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
996 if (this.#child !== child || this.#stopping) return;
997 if (message.type === "request-update") {
998 await this.#handleUpdateRequest(child, message);
999 return;
1001 await this.#handlePrepared(child, message.updateId);
1003​
1004 async #handleUpdateRequest(
1005 child: ManagedChild,
1006 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
1007 ): Promise<void> {
1008 const reject = (reason: string) =>
1009 sendMessage(child.process, { type: "update-rejected", reason });
1010 if (child.role !== "active") {
1011 await reject("Only the active server can request an update.");
1012 return;
1014 if (child.version !== this.#state.activeVersion) {
1015 await reject("The requesting server is not the selected active version.");
1016 return;
1018 if (this.#state.update?.status === "pending") {
1019 await reject("Another server update is already pending.");
1020 return;
1022 if (!isExactServiceVersion(message.targetVersion)) {
1023 await reject("The requested target is not an exact version.");
1024 return;
1026 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
1027 await reject("Remote updates must select a newer server version.");
1028 return;
1030 if (!NodePath.isAbsolute(message.dbPath)) {
1031 await reject("The requested database path is not absolute.");
1032 return;
1034 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
1035 await reject("The requested target runtime is missing or incomplete.");
1036 return;
1038 // Failed checks must refuse updates rather than stop the server with unknown backup capacity.
1039 const backupBlocker = await databaseBackupBlocker(
1040 this.#baseDir,
1041 message.dbPath,
1042 this.#backupSpaceProbe,
1043 ).catch(
1044 (error: unknown) =>
1045 `Could not check that the database backup fits before updating: ${error instanceof Error ? error.message : String(error)}. The server was not stopped.`,
1046 );
1047 if (!child.process.connected) return;
1048 if (backupBlocker !== undefined) {
1049 await reject(backupBlocker);
1050 return;
1052​
1053 const pending: PendingServiceUpdate = {
1054 id: NodeCrypto.randomUUID(),
1055 fromVersion: child.version,
1056 targetVersion: message.targetVersion,
1057 dbPath: message.dbPath,
1058 status: "pending",
1059 };
1060 const next: ServiceState = { ...this.#state, update: pending };
1061 try {
1062 await this.#selectState(next);
1063 } catch (error) {
1064 await reject(error instanceof Error ? error.message : String(error));
1065 return;
1067 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
1068 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
1070​
1071 async #beginTrial(child: ManagedChild): Promise<void> {
1072 const pending = this.#state.update;
1073 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
1074 return;
1076 this.#timer = undefined;
1077 // Anything thrown outside its own fallback still leaves the offline backup to run.
1078 const finishOnlineBackup = await startOnlineDatabaseBackup(
1079 this.#baseDir,
1080 pending,
1081 this.#backupSpaceProbe,
1082 ).catch(() => undefined);
1083 this.#child = null;
1084 await this.#terminate(child.process);
1085 await finishOnlineBackup?.();
1086 // A stop during a minutes-long copy should not start a trial; restart resumes the pending update.
1087 if (this.#stopRequested) return;
1088 await this.#startTrial(pending);
1090​
1091 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
1092 const pending = this.#state.update;
1093 if (
1094 child.role !== "trial" ||
1095 pending?.status !== "pending" ||
1096 pending.id !== updateId ||
1097 pending.targetVersion !== child.version
1098 ) {
1099 if (child.role === "trial" && pending?.status === "pending") {
1100 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
1101 return;
1103 throw new Error("Trial child reported prepared for an unexpected update.");
1105 this.#clearTimer();
1106 const committed = terminalUpdate({ pending, status: "committed" });
1107 const next: ServiceState = {
1108 ...this.#state,
1109 activeVersion: pending.targetVersion,
1110 update: committed,
1111 };
1112 await this.#selectState(next);
1113 child.role = "active";
1114 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
1115 try {
1116 await sendMessage(child.process, { type: "committed", updateId: committed.id });
1117 } finally {
1118 await this.#repointServiceUnit(committed.targetVersion);
1121​
1122 // Selection is durable before this best-effort unit reconciliation.
1123 async #repointServiceUnit(version: string): Promise<void> {
1124 const unit = this.#serviceUnit;
1125 if (unit === undefined) return;
1126 try {
1127 const release = await acquireServiceSelectionLock(unit.path);
1128 try {
1129 // The installer writes state before the unit under this lease. Do not
1130 // acquire its state lease here: the installer takes that lease first.
1131 const selected = await readServiceState(this.#statePath);
1132 if (
1133 selected.activeVersion !== this.#state.activeVersion ||
1134 selected.update?.id !== this.#state.update?.id ||
1135 selected.update?.status !== this.#state.update?.status
1136 ) {
1137 return;
1139 const contents = await NodeFSP.readFile(unit.path, "utf8");
1140 const installedBaseDir = serviceUnitBaseDirOf(contents);
1141 if (
1142 installedBaseDir === undefined ||
1143 NodePath.resolve(installedBaseDir) !== NodePath.resolve(this.#baseDir)
1144 ) {
1145 return;
1147 const repointed = repointServiceUnit(contents, version);
1148 if (repointed !== contents) await replaceFileDurably(unit.path, repointed);
1149 // A previous rename may have succeeded before reload failed.
1150 await unit.reload();
1151 } finally {
1152 release();
1154 } catch (error) {
1155 process.stderr.write(
1156 `[service-launcher] Could not point ${unit.path} at t3@${version}: ${error instanceof Error ? error.message : String(error)}\n`,
1157 );
1160​
1161 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
1162 const pending = this.#state.update;
1163 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
1164 return;
1166 this.#timer = undefined;
1167 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
1169​
1170 async #handleExit(
1171 child: ManagedChild,
1172 code: number | null,
1173 signal: NodeJS.Signals | null,
1174 ): Promise<void> {
1175 if (this.#child !== child || this.#stopping) return;
1176 this.#child = null;
1177 if (code === STATE_DIR_OWNED_EXIT_CODE) {
1178 await this.#idleWhileStateDirOwned();
1179 return;
1181 if (child.role === "trial") {
1182 this.#clearTimer();
1183 const pending = this.#state.update;
1184 if (pending?.status !== "pending") {
1185 throw new Error("Trial child exited without matching pending state.");
1187 await this.#returnToPrevious(
1188 pending,
1189 "rolled-back",
1190 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
1191 );
1192 return;
1194​
1195 this.#clearTimer();
1196 const pending = this.#state.update;
1197 if (pending?.status === "pending") {
1198 await this.#startTrial(pending);
1199 return;
1201 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
1203​
1204 // Stay idle to avoid supervisor restart loops; never restore backups over another owner's possible writes.
1205 async #idleWhileStateDirOwned(): Promise<void> {
1206 this.#clearTimer();
1207 const pending = this.#state.update;
1208 if (pending?.status === "pending") {
1209 const next: ServiceState = {
1210 ...this.#state,
1211 activeVersion: pending.fromVersion,
1212 update: terminalUpdate({ pending, status: "failed", reason: "state-dir-owned" }),
1213 };
1214 await this.#selectState(next);
1215 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
1216 await this.#repointServiceUnit(next.activeVersion);
1218 // Signal listeners alone do not keep Node alive.
1219 this.#timer = setInterval(() => {}, 2_147_483_647);
1220 this.#log(
1221 "[service-launcher] Another T3 Code server owns this T3 home. Stop it, then restart this service.\n",
1222 );
1224​
1225 async #returnToPrevious(
1226 pending: PendingServiceUpdate,
1227 status: "rolled-back" | "failed",
1228 reason: string,
1229 child?: ManagedChild,
1230 ): Promise<void> {
1231 if (child !== undefined) {
1232 this.#child = null;
1233 await this.#terminate(child.process);
1235 await restoreDatabaseBackup(this.#baseDir, pending);
1236 const outcome = terminalUpdate({ pending, status, reason });
1237 const next: ServiceState = {
1238 ...this.#state,
1239 activeVersion: pending.fromVersion,
1240 update: outcome,
1241 };
1242 await this.#selectState(next);
1243 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
1244 try {
1245 await this.#startChild(next.activeVersion, "active", outcome);
1246 } finally {
1247 await this.#repointServiceUnit(next.activeVersion);
1251​
1252/** Task Scheduler cannot set variables or redirect output, so a Windows task passes them as flags. */
1253export interface LauncherOptions {
1254 readonly baseDir?: string | undefined;
1255 readonly logFile?: string | undefined;
1256 readonly serviceUnit?: string | undefined;
1258​
1259export async function main(options: LauncherOptions = {}): Promise<void> {
1260 const baseDir = (options.baseDir ?? process.env.T3CODE_HOME)?.trim();
1261 if (baseDir === undefined || baseDir === "") {
1262 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
1264 const output =
1265 options.logFile === undefined ? undefined : NodeFS.openSync(options.logFile, "a", 0o600);
1266 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
1267 const windows = process.platform === "win32";
1268 try {
1269 // What the service manager started the launcher with. It locates the unit; service.env
1270 // changes only what the server gets.
1271 const managerEnvironment = {
1272 ...process.env,
1273 T3CODE_HOME: baseDir,
1274 ...(options.serviceUnit === undefined ? {} : { [SERVICE_UNIT_ENV]: options.serviceUnit }),
1275 };
1276 const environment = await readServiceEnvironment(baseDir, managerEnvironment);
1277 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
1278 const contents = await NodeFSP.readFile(statePath, "utf8");
1279 let state = parseServiceState(contents);
1280 if (state === undefined) {
1281 state = adoptLegacyServiceState(contents);
1282 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
1283 if (!(await runtimeExists(baseDir, state.activeVersion))) {
1284 throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`);
1287 const serviceUnit = serviceUnitFromEnvironment(managerEnvironment);
1288 const launcher = new Launcher(baseDir, state, {
1289 environment,
1290 ...(serviceUnit === undefined ? {} : { serviceUnit }),
1291 ...(output === undefined ? {} : { output }),
1292 ...(windows ? { lockPath: serviceLauncherLockPath(baseDir) } : {}),
1293 });
1294 // Ending a scheduled task kills its console host without a signal; the console read fails instead.
1295 const watchConsole = windows && process.stdin.isTTY === true;
1296 const onConsoleLost = () => void launcher.stop("SIGTERM");
1297 if (watchConsole) {
1298 process.stdin.on("error", () => undefined);
1299 process.stdin.once("close", onConsoleLost);
1300 process.stdin.resume();
1302 try {
1303 await launcher.run();
1304 } finally {
1305 if (watchConsole) {
1306 process.stdin.off("close", onConsoleLost);
1307 process.stdin.destroy();
1310 } catch (cause) {
1311 if (output !== undefined) {
1312 NodeFS.writeSync(
1313 output,
1314 `[service-launcher] ${cause instanceof Error ? cause.message : String(cause)}\n`,
1315 );
1317 // Agents the server left behind keep the console host, and so the task, running; ending it
1318 // lets the next repeating trigger start the service again.
1319 if (windows && options.serviceUnit !== undefined) {
1320 const taskName = serviceTaskName(process.env.USERDOMAIN ?? "", process.env.USERNAME ?? "");
1321 NodeChildProcess.spawnSync("schtasks", ["/End", "/TN", taskName], {
1322 stdio: "ignore",
1323 windowsHide: true,
1324 });
1326 throw cause;
1327 } finally {
1328 if (output !== undefined) NodeFS.closeSync(output);