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