Open History to see the last commit
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;
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
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 }
80}
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 }
89}
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 }
117}
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 }
137}
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));
159}
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));
166}
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;
173}
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 }
201}
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 }
214}
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 };
228}
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 });
241}
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()));
246}
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 }
260}
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, and
321 // launchd signals only the job's main process (this launcher), so the
322 // marker lands before the child sees any signal on both platforms.
323 try {
324 NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
325 } catch {
326 // Err toward keeping the tunnel; the next link or unlink reconciles it.
327 }
328 if (this.#stopRequested || this.#stopping) {
329 await this.#completion.promise.catch(() => undefined);
330 return;
331 }
332 this.#stopRequested = true;
333 this.#clearTimer();
334 this.#enqueue(async () => {
335 // Let an update transition already in progress start its replacement
336 // before this queued stop tears it down. That replacement owns the
337 // pre-activation tunnel cleanup path and observes the marker above.
338 this.#stopping = true;
339 const child = this.#child?.process;
340 this.#child = null;
341 if (child !== undefined) await terminateChild(child, signal);
342 this.#done = true;
343 this.#completion.resolve();
344 });
345 await this.#completion.promise.catch(() => undefined);
346 }
347
348 #clearTimer(): void {
349 clearTimeout(this.#timer);
350 this.#timer = undefined;
351 }
352
353 async #recover(): Promise<void> {
354 // A fresh launcher means servers are running again: any stop marker from
355 // a previous explicit stop is stale and must not make a future update
356 // handoff release its tunnel.
357 await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
358 const update = this.#state.update;
359 if (update?.status !== "pending") {
360 if (update !== undefined) {
361 await discardDatabaseBackup(this.#baseDir, update.id).catch(() => undefined);
362 }
363 await this.#startChild(this.#state.activeVersion, "active", update);
364 return;
365 }
366 if (await databaseRestorePending(this.#baseDir, update)) {
367 await this.#returnToPrevious(update, "failed", "rollback-interrupted");
368 return;
369 }
370 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
371 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
372 return;
373 }
374 await this.#startTrial(update);
375 }
376
377 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
378 // The previous child is dead here, so all three SQLite files are quiescent.
379 try {
380 await backupDatabaseOnce(this.#baseDir, pending);
381 } catch {
382 await this.#returnToPrevious(pending, "failed", "db-backup-failed");
383 return;
384 }
385 try {
386 await this.#startChild(pending.targetVersion, "trial", pending);
387 } catch {
388 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
389 }
390 }
391
392 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
393 if (this.#stopping) return;
394 if (!(await runtimeExists(this.#baseDir, version))) {
395 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
396 }
397 if (this.#stopping) return;
398 const paths = runtimePaths(this.#baseDir, version);
399 const context: ServiceLauncherContext = {
400 protocol: SERVICE_LAUNCHER_PROTOCOL,
401 childVersion: version,
402 ...(update === undefined ? {} : { update }),
403 };
404 const child = NodeChildProcess.spawn(process.execPath, [paths.entryPath, "serve"], {
405 env: { ...process.env, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
406 stdio: ["inherit", "inherit", "inherit", "ipc"],
407 });
408 await new Promise<void>((resolve, reject) => {
409 const onError = (error: Error) => reject(error);
410 child.once("error", onError);
411 child.once("spawn", () => {
412 child.removeListener("error", onError);
413 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
414 resolve();
415 });
416 });
417 if (this.#stopping) {
418 await terminateChild(child);
419 return;
420 }
421
422 const managed: ManagedChild = {
423 version,
424 role,
425 process: child,
426 };
427 this.#child = managed;
428 child.on("message", (value) => {
429 const message = decodeServiceLauncherChildMessage(value);
430 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
431 });
432 child.once("exit", (code, signal) =>
433 this.#enqueue(() => this.#handleExit(managed, code, signal)),
434 );
435
436 if (role === "trial") {
437 this.#timer = setTimeout(
438 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
439 PREPARED_TIMEOUT_MS,
440 );
441 }
442 }
443
444 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
445 if (this.#child !== child || this.#stopping) return;
446 if (message.type === "request-update") {
447 await this.#handleUpdateRequest(child, message);
448 return;
449 }
450 await this.#handlePrepared(child, message.updateId);
451 }
452
453 async #handleUpdateRequest(
454 child: ManagedChild,
455 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
456 ): Promise<void> {
457 const reject = (reason: string) =>
458 sendMessage(child.process, { type: "update-rejected", reason });
459 if (child.role !== "active") {
460 await reject("Only the active server can request an update.");
461 return;
462 }
463 if (child.version !== this.#state.activeVersion) {
464 await reject("The requesting server is not the selected active version.");
465 return;
466 }
467 if (this.#state.update?.status === "pending") {
468 await reject("Another server update is already pending.");
469 return;
470 }
471 if (!isExactServiceVersion(message.targetVersion)) {
472 await reject("The requested target is not an exact version.");
473 return;
474 }
475 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
476 await reject("Remote updates must select a newer server version.");
477 return;
478 }
479 if (!NodePath.isAbsolute(message.dbPath)) {
480 await reject("The requested database path is not absolute.");
481 return;
482 }
483 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
484 await reject("The requested target runtime is missing or incomplete.");
485 return;
486 }
487
488 const pending: PendingServiceUpdate = {
489 id: NodeCrypto.randomUUID(),
490 fromVersion: child.version,
491 targetVersion: message.targetVersion,
492 dbPath: message.dbPath,
493 status: "pending",
494 };
495 const next: ServiceState = { ...this.#state, update: pending };
496 await writeServiceState(this.#statePath, next);
497 this.#state = next;
498 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
499 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
500 }
501
502 async #beginTrial(child: ManagedChild): Promise<void> {
503 const pending = this.#state.update;
504 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
505 return;
506 }
507 this.#timer = undefined;
508 this.#child = null;
509 await terminateChild(child.process);
510 await this.#startTrial(pending);
511 }
512
513 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
514 const pending = this.#state.update;
515 if (
516 child.role !== "trial" ||
517 pending?.status !== "pending" ||
518 pending.id !== updateId ||
519 pending.targetVersion !== child.version
520 ) {
521 if (child.role === "trial" && pending?.status === "pending") {
522 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
523 return;
524 }
525 throw new Error("Trial child reported prepared for an unexpected update.");
526 }
527 this.#clearTimer();
528 const committed = terminalUpdate({ pending, status: "committed" });
529 const next: ServiceState = {
530 ...this.#state,
531 activeVersion: pending.targetVersion,
532 update: committed,
533 };
534 await writeServiceState(this.#statePath, next);
535 this.#state = next;
536 child.role = "active";
537 await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
538 await sendMessage(child.process, { type: "committed", updateId: committed.id });
539 }
540
541 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
542 const pending = this.#state.update;
543 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
544 return;
545 }
546 this.#timer = undefined;
547 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
548 }
549
550 async #handleExit(
551 child: ManagedChild,
552 code: number | null,
553 signal: NodeJS.Signals | null,
554 ): Promise<void> {
555 if (this.#child !== child || this.#stopping) return;
556 this.#child = null;
557 if (child.role === "trial") {
558 this.#clearTimer();
559 const pending = this.#state.update;
560 if (pending?.status !== "pending") {
561 throw new Error("Trial child exited without matching pending state.");
562 }
563 await this.#returnToPrevious(
564 pending,
565 "rolled-back",
566 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
567 );
568 return;
569 }
570
571 this.#clearTimer();
572 const pending = this.#state.update;
573 if (pending?.status === "pending") {
574 await this.#startTrial(pending);
575 return;
576 }
577 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
578 }
579
580 async #returnToPrevious(
581 pending: PendingServiceUpdate,
582 status: "rolled-back" | "failed",
583 reason: string,
584 child?: ManagedChild,
585 ): Promise<void> {
586 if (child !== undefined) {
587 this.#child = null;
588 await terminateChild(child.process);
589 }
590 await restoreDatabaseBackup(this.#baseDir, pending);
591 const outcome = terminalUpdate({ pending, status, reason });
592 const next: ServiceState = {
593 ...this.#state,
594 activeVersion: pending.fromVersion,
595 update: outcome,
596 };
597 await writeServiceState(this.#statePath, next);
598 this.#state = next;
599 await discardDatabaseBackup(this.#baseDir, pending.id).catch(() => undefined);
600 await this.#startChild(next.activeVersion, "active", outcome);
601 }
602}
603
604async function main(): Promise<void> {
605 const baseDir = process.env.T3CODE_HOME?.trim();
606 if (baseDir === undefined || baseDir === "") {
607 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
608 }
609 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
610 const state = await readServiceState(statePath);
611 await new Launcher(baseDir, state).run();
612}
613
614if (import.meta.main) {
615 main().catch((cause: unknown) => {
616 const error = cause instanceof Error ? cause : new Error(String(cause));
617 process.stderr.write(`[service-launcher] ${error.message}\n`);
618 process.exitCode = 1;
619 });
620}