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

serviceLauncher.ts

625 lines21.2 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 NodeFS from "node:fs";
9import * as NodeFSP from "node:fs/promises";
10import * as NodePath from "node:path";
11​
12import type {
13 PendingServiceUpdate,
14 ServiceLauncherChildMessage,
15 ServiceLauncherContext,
16 ServiceLauncherParentMessage,
17 ServiceState,
18 ServiceUpdateRecord,
19} from "./cloud/serviceProtocol.ts";
20import {
21 compareExactServiceVersions,
22 decodeServiceLauncherChildMessage,
23 isExactServiceVersion,
24 parseServiceState,
25 SERVICE_LAUNCHER_CONTEXT_ENV,
26 SERVICE_LAUNCHER_PROTOCOL,
27 SERVICE_STATE_FILE,
28 SERVICE_STOP_MARKER_FILE,
29} from "./cloud/serviceProtocol.ts";
30import { isEntrypoint } from "./entrypoint.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;
44​
45const runtimePaths = (baseDir: string, version: string) => {
46 const versionDir = NodePath.join(baseDir, "runtime", "versions", version);
47 return {
48 versionDir,
49 entryPath: NodePath.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
50 sentinelPath: NodePath.join(versionDir, ".install-complete"),
51 };
52};
53​
54/** SQLite persists across the main file plus its WAL and shared-memory sidecars. */
55const DB_FILE_SUFFIXES = ["", "-wal", "-shm"] as const;
56const RESTORE_MARKER = ".restore-pending";
57​
58const databaseBackupDir = (baseDir: string, updateId: string) =>
59 NodePath.join(baseDir, "runtime", "db-backup", updateId);
60​
61const databaseBackupFile = (backupDir: string, suffix: (typeof DB_FILE_SUFFIXES)[number]) =>
62 NodePath.join(backupDir, suffix === "" ? "database" : `database${suffix}`);
63​
64async function pathExists(target: string): Promise<boolean> {
65 try {
66 await NodeFSP.access(target);
67 return true;
68 } catch (cause) {
69 if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return false;
70 throw cause;
71 }
73​
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 }
82​
83async function syncDirectory(directory: string): Promise<void> {
84 const handle = await NodeFSP.open(directory, "r");
85 try {
86 await handle.sync();
87 } finally {
88 await handle.close();
89 }
91​
92/**
93 * Snapshots the database once per update before the first trial. A completed
94 * backup is never overwritten because a restarted launcher may be looking at
95 * database writes from an earlier attempt by the same trial.
96 */
97async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise<void> {
98 const backupDir = databaseBackupDir(baseDir, pending.id);
99 if (await pathExists(backupDir)) return;
100​
101 const stagingDir = `${backupDir}.staging`;
102 await NodeFSP.rm(stagingDir, { recursive: true, force: true });
103 await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 });
104 try {
105 for (const suffix of DB_FILE_SUFFIXES) {
106 const source = `${pending.dbPath}${suffix}`;
107 if (suffix !== "" && !(await pathExists(source))) continue;
108 const destination = databaseBackupFile(stagingDir, suffix);
109 await NodeFSP.copyFile(source, destination);
110 await syncFile(destination);
111 }
112 await NodeFSP.rename(stagingDir, backupDir);
113 await syncDirectory(NodePath.dirname(backupDir));
114 } catch (cause) {
115 await NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);
116 throw cause;
117 }
119​
120const restoreMarkerPath = (baseDir: string, updateId: string) =>
121 NodePath.join(databaseBackupDir(baseDir, updateId), RESTORE_MARKER);
122​
123const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) =>
124 pathExists(restoreMarkerPath(baseDir, pending.id));
125​
126/** Mark rollback before changing live files so launcher recovery cannot boot a partial restore. */
127async function markDatabaseRestorePending(backupDir: string): Promise<void> {
128 const markerPath = NodePath.join(backupDir, RESTORE_MARKER);
129 if (!(await pathExists(markerPath))) {
130 const handle = await NodeFSP.open(markerPath, "wx", 0o600);
131 try {
132 await handle.sync();
133 } finally {
134 await handle.close();
135 }
136 await syncDirectory(backupDir);
137 }
139​
140/** Restore is retryable after any process crash while the backup directory remains. */
141async function restoreDatabaseBackup(
142 baseDir: string,
143 pending: PendingServiceUpdate,
144): Promise<void> {
145 const backupDir = databaseBackupDir(baseDir, pending.id);
146 if (!(await pathExists(backupDir))) return;
147​
148 await markDatabaseRestorePending(backupDir);
149 for (const suffix of DB_FILE_SUFFIXES) {
150 const target = `${pending.dbPath}${suffix}`;
151 const source = databaseBackupFile(backupDir, suffix);
152 if (await pathExists(source)) {
153 await NodeFSP.copyFile(source, target);
154 await syncFile(target);
155 } else {
156 await NodeFSP.rm(target, { force: true });
157 }
158 }
159 await syncDirectory(NodePath.dirname(pending.dbPath));
161​
162async function discardDatabaseBackup(baseDir: string, updateId: string): Promise<void> {
163 const backupDir = databaseBackupDir(baseDir, updateId);
164 if (!(await pathExists(backupDir))) return;
165 await NodeFSP.rm(backupDir, { recursive: true, force: true });
166 await syncDirectory(NodePath.dirname(backupDir));
168​
169export async function readServiceState(filePath: string): Promise<ServiceState> {
170 const contents = await NodeFSP.readFile(filePath, "utf8");
171 const state = parseServiceState(contents);
172 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
173 return state;
175​
176/** Durable same-directory replacement used for every runtime state transition. */
177export async function writeServiceState(filePath: string, state: ServiceState): Promise<void> {
178 const directory = NodePath.dirname(filePath);
179 await NodeFSP.mkdir(directory, { recursive: true, mode: 0o700 });
180 const tempPath = NodePath.join(
181 directory,
182 `.${NodePath.basename(filePath)}.${process.pid}.${NodeCrypto.randomUUID()}`,
183 );
184 let handle: NodeFSP.FileHandle | undefined;
185 try {
186 handle = await NodeFSP.open(tempPath, "wx", 0o600);
187 await handle.writeFile(`${JSON.stringify(state, null, 2)}\n`, "utf8");
188 await handle.sync();
189 await handle.close();
190 handle = undefined;
191 await NodeFSP.rename(tempPath, filePath);
192 const directoryHandle = await NodeFSP.open(directory, "r");
193 try {
194 await directoryHandle.sync();
195 } finally {
196 await directoryHandle.close();
197 }
198 } finally {
199 await handle?.close().catch(() => undefined);
200 await NodeFSP.rm(tempPath, { force: true }).catch(() => undefined);
201 }
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 }
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 };
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 });
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()));
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 }
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.
322 try {
323 NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
324 } catch {
325 // Err toward keeping the tunnel; the next link or unlink reconciles it.
326 }
327 if (this.#stopRequested || this.#stopping) {
328 await this.#completion.promise.catch(() => undefined);
329 return;
330 }
331 this.#stopRequested = true;
332 this.#clearTimer();
333 this.#enqueue(async () => {
334 // Let an update transition already in progress start its replacement
335 // before this queued stop tears it down. That replacement owns the
336 // pre-activation tunnel cleanup path and observes the marker above.
337 this.#stopping = true;
338 const child = this.#child?.process;
339 this.#child = null;
340 if (child !== undefined) await terminateChild(child, signal);
341 this.#done = true;
342 this.#completion.resolve();
343 });
344 await this.#completion.promise.catch(() => undefined);
345 }
346​
347 #clearTimer(): void {
348 clearTimeout(this.#timer);
349 this.#timer = undefined;
350 }
351​
352 async #recover(): Promise<void> {
353 // A fresh launcher means servers are running again: any stop marker from
354 // a previous explicit stop is stale and must not make a future update
355 // handoff release its tunnel.
356 await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
357 const update = this.#state.update;
358 if (update?.status !== "pending") {
359 if (update !== undefined) {
360 await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
361 }
362 await this.#startChild(this.#state.activeVersion, "active", update);
363 return;
364 }
365 if (await databaseRestorePending(this.#baseDir, update)) {
366 await this.#returnToPrevious(update, "failed", "rollback-interrupted");
367 return;
368 }
369 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
370 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
371 return;
372 }
373 await this.#startTrial(update);
374 }
375​
376 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
377 // The previous child is dead here, so all three SQLite files are quiescent.
378 try {
379 await backupDatabaseOnce(this.#baseDir, pending);
380 } catch {
381 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
382 return;
383 }
384 try {
385 await this.#startChild(pending.targetVersion, "trial", pending);
386 } catch {
387 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
388 }
389 }
390​
391 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
392 if (this.#stopping) return;
393 if (!(await runtimeExists(this.#baseDir, version))) {
394 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
395 }
396 if (this.#stopping) return;
397 const paths = runtimePaths(this.#baseDir, version);
398 const context: ServiceLauncherContext = {
399 protocol: SERVICE_LAUNCHER_PROTOCOL,
400 childVersion: version,
401 ...(update === undefined ? {} : { update }),
402 };
403 const child = NodeChildProcess.spawn(process.execPath, [paths.entryPath, "serve"], {
404 env: { ...process.env, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
405 stdio: ["inherit", "inherit", "inherit", "ipc"],
406 });
407 await new Promise<void>((resolve, reject) => {
408 const onError = (error: Error) => reject(error);
409 child.once("error", onError);
410 child.once("spawn", () => {
411 child.removeListener("error", onError);
412 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
413 resolve();
414 });
415 });
416 if (this.#stopping) {
417 await terminateChild(child);
418 return;
419 }
420​
421 const managed: ManagedChild = {
422 version,
423 role,
424 process: child,
425 };
426 this.#child = managed;
427 child.on("message", (value) => {
428 const message = decodeServiceLauncherChildMessage(value);
429 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
430 });
431 child.once("exit", (code, signal) =>
432 this.#enqueue(() => this.#handleExit(managed, code, signal)),
433 );
434​
435 if (role === "trial") {
436 this.#timer = setTimeout(
437 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
438 PREPARED_TIMEOUT_MS,
439 );
440 }
441 }
442​
443 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
444 if (this.#child !== child || this.#stopping) return;
445 if (message.type === "request-update") {
446 await this.#handleUpdateRequest(child, message);
447 return;
448 }
449 await this.#handlePrepared(child, message.updateId);
450 }
451​
452 async #handleUpdateRequest(
453 child: ManagedChild,
454 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
455 ): Promise<void> {
456 const reject = (reason: string) =>
457 sendMessage(child.process, { type: "update-rejected", reason });
458 if (child.role !== "active") {
459 await reject("Only the active server can request an update.");
460 return;
461 }
462 if (child.version !== this.#state.activeVersion) {
463 await reject("The requesting server is not the selected active version.");
464 return;
465 }
466 if (this.#state.update?.status === "pending") {
467 await reject("Another server update is already pending.");
468 return;
469 }
470 if (!isExactServiceVersion(message.targetVersion)) {
471 await reject("The requested target is not an exact version.");
472 return;
473 }
474 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
475 await reject("Remote updates must select a newer server version.");
476 return;
477 }
478 if (!NodePath.isAbsolute(message.dbPath)) {
479 await reject("The requested database path is not absolute.");
480 return;
481 }
482 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
483 await reject("The requested target runtime is missing or incomplete.");
484 return;
485 }
486​
487 const pending: PendingServiceUpdate = {
488 id: NodeCrypto.randomUUID(),
489 fromVersion: child.version,
490 targetVersion: message.targetVersion,
491 dbPath: message.dbPath,
492 status: "pending",
493 };
494 const next: ServiceState = { ...this.#state, update: pending };
495 await writeServiceState(this.#statePath, next);
496 this.#state = next;
497 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
498 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
499 }
500​
501 async #beginTrial(child: ManagedChild): Promise<void> {
502 const pending = this.#state.update;
503 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
504 return;
505 }
506 this.#timer = undefined;
507 this.#child = null;
508 await terminateChild(child.process);
509 await this.#startTrial(pending);
510 }
511​
512 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
513 const pending = this.#state.update;
514 if (
515 child.role !== "trial" ||
516 pending?.status !== "pending" ||
517 pending.id !== updateId ||
518 pending.targetVersion !== child.version
519 ) {
520 if (child.role === "trial" && pending?.status === "pending") {
521 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
522 return;
523 }
524 throw new Error("Trial child reported prepared for an unexpected update.");
525 }
526 this.#clearTimer();
527 const committed = terminalUpdate({ pending, status: "committed" });
528 const next: ServiceState = {
529 ...this.#state,
530 activeVersion: pending.targetVersion,
531 update: committed,
532 };
533 await writeServiceState(this.#statePath, next);
534 this.#state = next;
535 child.role = "active";
536 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
537 await sendMessage(child.process, { type: "committed", updateId: committed.id });
538 }
539​
540 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
541 const pending = this.#state.update;
542 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
543 return;
544 }
545 this.#timer = undefined;
546 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
547 }
548​
549 async #handleExit(
550 child: ManagedChild,
551 code: number | null,
552 signal: NodeJS.Signals | null,
553 ): Promise<void> {
554 if (this.#child !== child || this.#stopping) return;
555 this.#child = null;
556 if (child.role === "trial") {
557 this.#clearTimer();
558 const pending = this.#state.update;
559 if (pending?.status !== "pending") {
560 throw new Error("Trial child exited without matching pending state.");
561 }
562 await this.#returnToPrevious(
563 pending,
564 "rolled-back",
565 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
566 );
567 return;
568 }
569​
570 this.#clearTimer();
571 const pending = this.#state.update;
572 if (pending?.status === "pending") {
573 await this.#startTrial(pending);
574 return;
575 }
576 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
577 }
578​
579 async #returnToPrevious(
580 pending: PendingServiceUpdate,
581 status: "rolled-back" | "failed",
582 reason: string,
583 child?: ManagedChild,
584 ): Promise<void> {
585 if (child !== undefined) {
586 this.#child = null;
587 await terminateChild(child.process);
588 }
589 await restoreDatabaseBackup(this.#baseDir, pending);
590 const outcome = terminalUpdate({ pending, status, reason });
591 const next: ServiceState = {
592 ...this.#state,
593 activeVersion: pending.fromVersion,
594 update: outcome,
595 };
596 await writeServiceState(this.#statePath, next);
597 this.#state = next;
598 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
599 await this.#startChild(next.activeVersion, "active", outcome);
600 }
602​
603async function main(): Promise<void> {
604 const baseDir = process.env.T3CODE_HOME?.trim();
605 if (baseDir === undefined || baseDir === "") {
606 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
607 }
608 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
609 const state = await readServiceState(statePath);
610 await new Launcher(baseDir, state).run();
612​
613if (
614 isEntrypoint({
615 moduleUrl: import.meta.url,
616 entryPath: process.argv[1],
617 runtimeMain: import.meta.main,
618 })
619) {
620 main().catch((cause: unknown) => {
621 const error = cause instanceof Error ? cause : new Error(String(cause));
622 process.stderr.write(`[service-launcher] ${error.message}\n`);
623 process.exitCode = 1;
624 });