Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceLauncher.ts

595 lines19.8 KB

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