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