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

serviceLauncher.ts

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