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