Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2// @effect-diagnostics globalTimers:off
3// The launcher supervises the server child for the boot service and must keep
4// working across server versions, so it stays on Node built-ins with no Effect
5// runtime: it is the one part of the executable that cannot depend on the
6// rest of it being loadable.
7import * as NodeChildProcess from "node:child_process";
8import * as NodeCrypto from "node:crypto";
9import * as NodeFS from "node:fs";
10import * as NodeFSP from "node:fs/promises";
11import * as NodePath from "node:path";
12import * as NodeUtil from "node:util";
13
14import type {
15 PendingServiceUpdate,
16 ServiceLauncherChildMessage,
17 ServiceLauncherContext,
18 ServiceLauncherParentMessage,
19 ServiceState,
20 ServiceUpdateRecord,
21} from "./cloud/serviceProtocol.ts";
22import {
23 compareExactServiceVersions,
24 decodeServiceLauncherChildMessage,
25 isExactServiceVersion,
26 parseServiceState,
27 SERVICE_ENV_FILE,
28 SERVICE_LAUNCHER_CONTEXT_ENV,
29 SERVICE_LAUNCHER_PROTOCOL,
30 SERVICE_STATE_FILE,
31 SERVICE_RESTART_PENDING_FILE,
32 SERVICE_STOP_MARKER_FILE,
33} from "./cloud/serviceProtocol.ts";
34
35const HANDOFF_DELAY_MS = 2_000;
36const PREPARED_TIMEOUT_MS = 120_000;
37const TERMINATE_GRACE_MS = 5_000;
38
39const SERVICE_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
40const MANAGED_SERVICE_ENV_NAMES = new Set(
41 ["PATH", "T3CODE_HOME", "T3_BOOT_SERVICE_UNIT", SERVICE_LAUNCHER_CONTEXT_ENV].map((name) =>
42 name.toUpperCase(),
43 ),
44);
45
46type TerminalStatus = "committed" | "rolled-back" | "failed";
47type ChildRole = "active" | "trial";
48
49interface ManagedChild {
50 readonly version: string;
51 role: ChildRole;
52 readonly process: NodeChildProcess.ChildProcess;
53}
54
55// Mirrors pinnedRuntimePaths: a runtime is an unpacked release archive whose
56// executable runs on its own. Kept inline so this file stays on Node
57// built-ins only.
58const runtimePaths = (baseDir: string, version: string) => {
59 const versionDir = NodePath.join(baseDir, "runtime", "versions", version);
60 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
61 const executableName = process.platform === "win32" ? "t3.exe" : "t3";
62 return {
63 versionDir,
64 entryPath: NodePath.join(versionDir, executableName),
65 sentinelPath: NodePath.join(versionDir, ".install-complete"),
66 };
67};
68
69const runtimeSpawnArguments = (paths: ReturnType<typeof runtimePaths>) => ({
70 command: paths.entryPath,
71 args: ["serve"],
72});
73
74/** SQLite persists across the main file plus its WAL and shared-memory sidecars. */
75const DB_FILE_SUFFIXES = ["", "-wal", "-shm"] as const;
76const RESTORE_MARKER = ".restore-pending";
77
78const databaseBackupDir = (baseDir: string, updateId: string) =>
79 NodePath.join(baseDir, "runtime", "db-backup", updateId);
80
81const databaseBackupFile = (backupDir: string, suffix: (typeof DB_FILE_SUFFIXES)[number]) =>
82 NodePath.join(backupDir, suffix === "" ? "database" : `database${suffix}`);
83
84async function pathExists(target: string): Promise<boolean> {
85 try {
86 await NodeFSP.access(target);
87 return true;
88 } catch (cause) {
89 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return false;
90 throw cause;
91 }
92}
93
94/**
95 * Reads KEY=VALUE assignments from the documented T3 home env file. Managed
96 * names the unit already owns are ignored, regardless of key case, so a
97 * user cannot redirect the service by writing PATH or T3CODE_HOME here.
98 */
99export function parseServiceEnvFile(contents: string): Record<string, string> {
100 const parsed = NodeUtil.parseEnv(contents);
101 const env: Record<string, string> = {};
102 for (const [key, value] of Object.entries(parsed)) {
103 if (
104 value === undefined ||
105 !SERVICE_ENV_NAME.test(key) ||
106 MANAGED_SERVICE_ENV_NAMES.has(key.toUpperCase())
107 ) {
108 continue;
109 }
110 env[key] = value;
111 }
112 return env;
113}
114
115export async function readServiceEnvFile(baseDir: string): Promise<Record<string, string>> {
116 try {
117 return parseServiceEnvFile(
118 await NodeFSP.readFile(NodePath.join(baseDir, SERVICE_ENV_FILE), "utf8"),
119 );
120 } catch (cause) {
121 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
122 throw cause;
123 }
124}
125
126/** Merge `service.env` into a process environment. Missing file is a no-op. */
127export async function applyServiceEnvFile(
128 baseDir: string,
129 env: NodeJS.ProcessEnv = process.env,
130): Promise<Record<string, string>> {
131 const serviceEnv = await readServiceEnvFile(baseDir);
132 Object.assign(env, serviceEnv);
133 return serviceEnv;
134}
135
136// Opened read-write: Windows refuses to flush a handle without write access.
137async function syncFile(filePath: string): Promise<void> {
138 const handle = await NodeFSP.open(filePath, "r+");
139 try {
140 await handle.sync();
141 } finally {
142 await handle.close();
143 }
144}
145
146// Flushes a directory entry so a rename into it survives power loss. Windows
147// has no directory fsync: the handle opens but sync fails with EPERM, and
148// NTFS journals the rename on its own.
149async function syncDirectory(directory: string): Promise<void> {
150 const handle = await NodeFSP.open(directory, "r");
151 try {
152 await handle.sync();
153 } catch (error) {
154 if ((error as NodeJS.ErrnoException).code !== "EPERM") throw error;
155 } finally {
156 await handle.close();
157 }
158}
159
160/**
161 * Snapshots the database once per update before the first trial. A completed
162 * backup is never overwritten because a restarted launcher may be looking at
163 * database writes from an earlier attempt by the same trial.
164 */
165async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise<void> {
166 const backupDir = databaseBackupDir(baseDir, pending.id);
167 if (await pathExists(backupDir)) return;
168
169 const stagingDir = `${backupDir}.staging`;
170 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
171 await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
172 try {
173 for (const suffix of DB_FILE_SUFFIXES) {
174 const source = `${pending.dbPath}${suffix}`;
175 if (suffix !== "" && !(await pathExists(source))) continue;
176 const destination = databaseBackupFile(stagingDir, suffix);
177 await NodeFSP.copyFile(source, destination);
178 await syncFile(destination);
179 }
180 await NodeFSP.rename(stagingDir, backupDir);
181 await syncDirectory(NodePath.dirname(backupDir));
182 } catch (cause) {
183 await NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
184 throw cause;
185 }
186}
187
188const restoreMarkerPath = (baseDir: string, updateId: string) =>
189 NodePath.join(databaseBackupDir(baseDir, updateId), RESTORE_MARKER);
190
191const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) =>
192 pathExists(restoreMarkerPath(baseDir, pending.id));
193
194/** Mark rollback before changing live files so launcher recovery cannot boot a partial restore. */
195async function markDatabaseRestorePending(backupDir: string): Promise<void> {
196 const markerPath = NodePath.join(backupDir, RESTORE_MARKER);
197 if (!(await pathExists(markerPath))) {
198 const handle = await NodeFSP.open(markerPath, "wx", 0o600);
199 try {
200 await handle.sync();
201 } finally {
202 await handle.close();
203 }
204 await syncDirectory(backupDir);
205 }
206}
207
208/** Restore is retryable after any process crash while the backup directory remains. */
209async function restoreDatabaseBackup(
210 baseDir: string,
211 pending: PendingServiceUpdate,
212): Promise<void> {
213 const backupDir = databaseBackupDir(baseDir, pending.id);
214 if (!(await pathExists(backupDir))) return;
215
216 await markDatabaseRestorePending(backupDir);
217 for (const suffix of DB_FILE_SUFFIXES) {
218 const target = `${pending.dbPath}${suffix}`;
219 const source = databaseBackupFile(backupDir, suffix);
220 if (await pathExists(source)) {
221 await NodeFSP.copyFile(source, target);
222 await syncFile(target);
223 } else {
224 await NodeFSP.rm(target, { force: true });
225 }
226 }
227 await syncDirectory(NodePath.dirname(pending.dbPath));
228}
229
230async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
231 const backupDir = databaseBackupDir(baseDir, updateId);
232 if (!(await pathExists(backupDir))) return;
233 await NodeFSP.rm(backupDir, { recursive: true, force: true });
234 await syncDirectory(NodePath.dirname(backupDir));
235}
236
237export async function readServiceState(filePath: string): Promise<ServiceState> {
238 const contents = await NodeFSP.readFile(filePath, "utf8");
239 const state = parseServiceState(contents);
240 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
241 return state;
242}
243
244/** Durable same-directory replacement used for every runtime state transition. */
245export async function writeServiceState(filePath: string, state: ServiceState): Promise<void> {
246 const directory = NodePath.dirname(filePath);
247 await NodeFSP.mkdir(directory, { recursive: true, mode: 0o700 });
248 const tempPath = NodePath.join(
249 directory,
250 `.${NodePath.basename(filePath)}.${process.pid}.${NodeCrypto.randomUUID()}`,
251 );
252 let handle: NodeFSP.FileHandle | undefined;
253 try {
254 handle = await NodeFSP.open(tempPath, "wx", 0o600);
255 await handle.writeFile(`${JSON.stringify(state, null, 2)}\n`, "utf8");
256 await handle.sync();
257 await handle.close();
258 handle = undefined;
259 await NodeFSP.rename(tempPath, filePath);
260 await syncDirectory(directory);
261 } finally {
262 await handle?.close().catch(() => undefined);
263 await NodeFSP.rm(tempPath, { force: true }).catch(() => undefined);
264 }
265}
266
267async function runtimeExists(baseDir: string, version: string): Promise<boolean> {
268 const paths = runtimePaths(baseDir, version);
269 try {
270 const [entry, sentinel] = await Promise.all([
271 NodeFSP.stat(paths.entryPath),
272 NodeFSP.readFile(paths.sentinelPath, "utf8"),
273 ]);
274 return entry.isFile() && sentinel.trim() === version;
275 } catch {
276 return false;
277 }
278}
279
280function terminalUpdate<S extends TerminalStatus>(input: {
281 readonly pending: PendingServiceUpdate;
282 readonly status: S;
283 readonly reason?: string;
284}): Exclude<ServiceUpdateRecord, PendingServiceUpdate> & { readonly status: S } {
285 return {
286 id: input.pending.id,
287 fromVersion: input.pending.fromVersion,
288 targetVersion: input.pending.targetVersion,
289 status: input.status,
290 ...(input.reason === undefined ? {} : { reason: input.reason }),
291 };
292}
293
294function sendMessage(
295 child: NodeChildProcess.ChildProcess,
296 message: ServiceLauncherParentMessage,
297): Promise<void> {
298 return new Promise((resolve, reject) => {
299 if (!child.connected || child.send === undefined) {
300 reject(new Error("service child IPC is disconnected."));
301 return;
302 }
303 child.send(message, (error) => (error === null ? resolve() : reject(error)));
304 });
305}
306
307function waitForExit(child: NodeChildProcess.ChildProcess): Promise<void> {
308 if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
309 return new Promise((resolve) => child.once("exit", () => resolve()));
310}
311
312async function terminateChild(
313 child: NodeChildProcess.ChildProcess,
314 signal: NodeJS.Signals = "SIGTERM",
315): Promise<void> {
316 if (child.exitCode !== null || child.signalCode !== null) return;
317 child.kill(signal);
318 const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS);
319 try {
320 await waitForExit(child);
321 } finally {
322 clearTimeout(force);
323 }
324}
325
326const stopMarkerPath = (baseDir: string) =>
327 NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
328const restartPendingPath = (baseDir: string) =>
329 NodePath.join(baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
330
331export class Launcher {
332 readonly #baseDir: string;
333 readonly #statePath: string;
334 // Startup snapshot from service.env. Later file edits wait for a service restart.
335 readonly #serviceEnv: Record<string, string>;
336 #state: ServiceState;
337 #child: ManagedChild | null = null;
338 #timer: NodeJS.Timeout | undefined;
339 #transitions: Promise<void> = Promise.resolve();
340 #stopRequested = false;
341 #stopping = false;
342 #done = false;
343 readonly #completion = Promise.withResolvers<void>();
344
345 constructor(baseDir: string, state: ServiceState, serviceEnv: Record<string, string> = {}) {
346 this.#baseDir = baseDir;
347 this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
348 this.#state = state;
349 this.#serviceEnv = serviceEnv;
350 }
351
352 async run(): Promise<void> {
353 const onSigterm = () => void this.stop("SIGTERM");
354 const onSigint = () => void this.stop("SIGINT");
355 process.once("SIGTERM", onSigterm);
356 process.once("SIGINT", onSigint);
357 try {
358 this.#enqueue(() => this.#recover());
359 await this.#completion.promise;
360 } finally {
361 process.off("SIGTERM", onSigterm);
362 process.off("SIGINT", onSigint);
363 }
364 }
365
366 #enqueue(transition: () => Promise<void>): void {
367 this.#transitions = this.#transitions
368 .then(transition, transition)
369 .catch((cause: unknown) =>
370 this.#fatal(cause instanceof Error ? cause : new Error(String(cause))),
371 );
372 }
373
374 async #fatal(error: Error): Promise<void> {
375 if (this.#done) return;
376 this.#done = true;
377 this.#stopping = true;
378 this.#clearTimer();
379 const child = this.#child?.process;
380 this.#child = null;
381 if (child !== undefined) await terminateChild(child);
382 this.#completion.reject(error);
383 }
384
385 async stop(signal: NodeJS.Signals): Promise<void> {
386 // This must happen synchronously at signal receipt. A queued update
387 // transition may already be terminating the active child, and that child
388 // needs to see the marker in its shutdown finalizer. KillMode=mixed also
389 // ensures systemd signals the launcher before the rest of the cgroup, and
390 // launchd signals only the job's main process (this launcher), so the
391 // marker lands before the child sees any signal on both platforms.
392 try {
393 NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
394 } catch {
395 // Err toward keeping the tunnel; the next link or unlink reconciles it.
396 }
397 if (this.#stopRequested || this.#stopping) {
398 await this.#completion.promise.catch(() => undefined);
399 return;
400 }
401 this.#stopRequested = true;
402 this.#clearTimer();
403 this.#enqueue(async () => {
404 // Let an update transition already in progress start its replacement
405 // before this queued stop tears it down. That replacement owns the
406 // pre-activation tunnel cleanup path and observes the marker above.
407 this.#stopping = true;
408 const child = this.#child?.process;
409 this.#child = null;
410 if (child !== undefined) await terminateChild(child, signal);
411 this.#done = true;
412 this.#completion.resolve();
413 });
414 await this.#completion.promise.catch(() => undefined);
415 }
416
417 #clearTimer(): void {
418 clearTimeout(this.#timer);
419 this.#timer = undefined;
420 }
421
422 async #recover(): Promise<void> {
423 // A fresh launcher means servers are running again: any stop marker from
424 // a previous explicit stop is stale and must not make a future update
425 // handoff release its tunnel. A restart deferred by `t3 update` is done
426 // no matter who restarted the service, but only once this launcher is
427 // the version the marker waits for: a launcher that came up between the
428 // CLI writing the marker and writing the new state still runs the old
429 // version, and the marker has to outlive it.
430 await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
431 const restartPending = restartPendingPath(this.#baseDir);
432 const awaitedVersion = await NodeFSP.readFile(restartPending, "utf8").catch(() => undefined);
433 if (awaitedVersion?.trim() === this.#state.activeVersion) {
434 await NodeFSP.rm(restartPending, { force: true }).catch(() => undefined);
435 }
436 const update = this.#state.update;
437 if (update?.status !== "pending") {
438 if (update !== undefined) {
439 await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
440 }
441 await this.#startChild(this.#state.activeVersion, "active", update);
442 return;
443 }
444 if (await databaseRestorePending(this.#baseDir, update)) {
445 await this.#returnToPrevious(update, "failed", "rollback-interrupted");
446 return;
447 }
448 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
449 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
450 return;
451 }
452 await this.#startTrial(update);
453 }
454
455 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
456 // The previous child is dead here, so all three SQLite files are quiescent.
457 try {
458 await backupDatabaseOnce(this.#baseDir, pending);
459 } catch {
460 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
461 return;
462 }
463 try {
464 await this.#startChild(pending.targetVersion, "trial", pending);
465 } catch {
466 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
467 }
468 }
469
470 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
471 if (this.#stopping) return;
472 if (!(await runtimeExists(this.#baseDir, version))) {
473 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
474 }
475 if (this.#stopping) return;
476 const paths = runtimePaths(this.#baseDir, version);
477 const context: ServiceLauncherContext = {
478 protocol: SERVICE_LAUNCHER_PROTOCOL,
479 childVersion: version,
480 ...(update === undefined ? {} : { update }),
481 };
482 const spawnArguments = runtimeSpawnArguments(paths);
483 const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
484 env: {
485 ...process.env,
486 ...this.#serviceEnv,
487 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context),
488 },
489 stdio: ["inherit", "inherit", "inherit", "ipc"],
490 });
491 await new Promise<void>((resolve, reject) => {
492 const onError = (error: Error) => reject(error);
493 child.once("error", onError);
494 child.once("spawn", () => {
495 child.removeListener("error", onError);
496 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
497 resolve();
498 });
499 });
500 if (this.#stopping) {
501 await terminateChild(child);
502 return;
503 }
504
505 const managed: ManagedChild = {
506 version,
507 role,
508 process: child,
509 };
510 this.#child = managed;
511 child.on("message", (value) => {
512 const message = decodeServiceLauncherChildMessage(value);
513 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
514 });
515 child.once("exit", (code, signal) =>
516 this.#enqueue(() => this.#handleExit(managed, code, signal)),
517 );
518
519 if (role === "trial") {
520 this.#timer = setTimeout(
521 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
522 PREPARED_TIMEOUT_MS,
523 );
524 }
525 }
526
527 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
528 if (this.#child !== child || this.#stopping) return;
529 if (message.type === "request-update") {
530 await this.#handleUpdateRequest(child, message);
531 return;
532 }
533 await this.#handlePrepared(child, message.updateId);
534 }
535
536 async #handleUpdateRequest(
537 child: ManagedChild,
538 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
539 ): Promise<void> {
540 const reject = (reason: string) =>
541 sendMessage(child.process, { type: "update-rejected", reason });
542 if (child.role !== "active") {
543 await reject("Only the active server can request an update.");
544 return;
545 }
546 if (child.version !== this.#state.activeVersion) {
547 await reject("The requesting server is not the selected active version.");
548 return;
549 }
550 if (this.#state.update?.status === "pending") {
551 await reject("Another server update is already pending.");
552 return;
553 }
554 if (!isExactServiceVersion(message.targetVersion)) {
555 await reject("The requested target is not an exact version.");
556 return;
557 }
558 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
559 await reject("Remote updates must select a newer server version.");
560 return;
561 }
562 if (!NodePath.isAbsolute(message.dbPath)) {
563 await reject("The requested database path is not absolute.");
564 return;
565 }
566 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
567 await reject("The requested target runtime is missing or incomplete.");
568 return;
569 }
570
571 const pending: PendingServiceUpdate = {
572 id: NodeCrypto.randomUUID(),
573 fromVersion: child.version,
574 targetVersion: message.targetVersion,
575 dbPath: message.dbPath,
576 status: "pending",
577 };
578 const next: ServiceState = { ...this.#state, update: pending };
579 await writeServiceState(this.#statePath, next);
580 this.#state = next;
581 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
582 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
583 }
584
585 async #beginTrial(child: ManagedChild): Promise<void> {
586 const pending = this.#state.update;
587 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
588 return;
589 }
590 this.#timer = undefined;
591 this.#child = null;
592 await terminateChild(child.process);
593 await this.#startTrial(pending);
594 }
595
596 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
597 const pending = this.#state.update;
598 if (
599 child.role !== "trial" ||
600 pending?.status !== "pending" ||
601 pending.id !== updateId ||
602 pending.targetVersion !== child.version
603 ) {
604 if (child.role === "trial" && pending?.status === "pending") {
605 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
606 return;
607 }
608 throw new Error("Trial child reported prepared for an unexpected update.");
609 }
610 this.#clearTimer();
611 const committed = terminalUpdate({ pending, status: "committed" });
612 const next: ServiceState = {
613 ...this.#state,
614 activeVersion: pending.targetVersion,
615 update: committed,
616 };
617 await writeServiceState(this.#statePath, next);
618 this.#state = next;
619 child.role = "active";
620 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
621 await sendMessage(child.process, { type: "committed", updateId: committed.id });
622 }
623
624 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
625 const pending = this.#state.update;
626 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
627 return;
628 }
629 this.#timer = undefined;
630 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
631 }
632
633 async #handleExit(
634 child: ManagedChild,
635 code: number | null,
636 signal: NodeJS.Signals | null,
637 ): Promise<void> {
638 if (this.#child !== child || this.#stopping) return;
639 this.#child = null;
640 if (child.role === "trial") {
641 this.#clearTimer();
642 const pending = this.#state.update;
643 if (pending?.status !== "pending") {
644 throw new Error("Trial child exited without matching pending state.");
645 }
646 await this.#returnToPrevious(
647 pending,
648 "rolled-back",
649 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
650 );
651 return;
652 }
653
654 this.#clearTimer();
655 const pending = this.#state.update;
656 if (pending?.status === "pending") {
657 await this.#startTrial(pending);
658 return;
659 }
660 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
661 }
662
663 async #returnToPrevious(
664 pending: PendingServiceUpdate,
665 status: "rolled-back" | "failed",
666 reason: string,
667 child?: ManagedChild,
668 ): Promise<void> {
669 if (child !== undefined) {
670 this.#child = null;
671 await terminateChild(child.process);
672 }
673 await restoreDatabaseBackup(this.#baseDir, pending);
674 const outcome = terminalUpdate({ pending, status, reason });
675 const next: ServiceState = {
676 ...this.#state,
677 activeVersion: pending.fromVersion,
678 update: outcome,
679 };
680 await writeServiceState(this.#statePath, next);
681 this.#state = next;
682 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
683 await this.#startChild(next.activeVersion, "active", outcome);
684 }
685}
686
687export async function main(): Promise<void> {
688 const baseDir = process.env.T3CODE_HOME?.trim();
689 if (baseDir === undefined || baseDir === "") {
690 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
691 }
692 const serviceEnv = await applyServiceEnvFile(baseDir);
693 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
694 const state = await readServiceState(statePath);
695 await new Launcher(baseDir, state, serviceEnv).run();
696}