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