Open History to see the last commit
1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6import * as Semaphore from "effect/Semaphore";
7
8import * as ProcessRunner from "../processRunner.ts";
9
10/**
11 * A pinned runtime is an exact `t3@<version>` npm-installed into
12 * <baseDir>/runtime/versions/<version>. The boot service points its systemd
13 * unit here, and server self-update installs the target version here before
14 * switching over — never `npx t3`, whose cache is ephemeral and whose
15 * registry fetch at boot would make startup depend on the network.
16 */
17
18const PINNED_RUNTIME_DIR = "runtime";
19const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
20// Boot-service setup and remote self-update share this module but can be
21// constructed in separate layers. Serialize the complete check/install/
22// sentinel transaction across all callers in this process.
23const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
24
25export interface PinnedRuntimePaths {
26 readonly versionDir: string;
27 readonly entryPath: string;
28 readonly sentinelPath: string;
29}
30
31export function pinnedRuntimePaths(
32 path: Path.Path,
33 baseDir: string,
34 version: string,
35): PinnedRuntimePaths {
36 const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, "versions", version);
37 return {
38 versionDir,
39 entryPath: path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
40 sentinelPath: path.join(versionDir, ".install-complete"),
41 };
42}
43
44export class PinnedRuntimeInstallError extends Schema.TaggedErrorClass<PinnedRuntimeInstallError>()(
45 "PinnedRuntimeInstallError",
46 {
47 step: Schema.String,
48 exitCode: Schema.optional(Schema.Number),
49 stdoutLength: Schema.optional(Schema.Number),
50 stderrLength: Schema.optional(Schema.Number),
51 cause: Schema.optional(Schema.Defect()),
52 },
53) {
54 override get message(): string {
55 return this.exitCode === undefined
56 ? `Pinned runtime install failed while ${this.step}.`
57 : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
58 }
59}
60
61/**
62 * Installs `t3@<version>` into the pinned runtime directory unless a complete
63 * install is already there, and returns its paths. The sentinel is written
64 * only after npm exits 0; checking the entry file alone is not enough — npm
65 * extracts files before running native builds (node-pty), so a killed
66 * install leaves a plausible-looking but broken tree behind.
67 */
68export const ensurePinnedRuntimeInstalled = Effect.fn("cloud.pinned_runtime.ensure_installed")(
69 function* (input: {
70 readonly baseDir: string;
71 readonly version: string;
72 readonly fs: FileSystem.FileSystem;
73 readonly path: Path.Path;
74 readonly runner: ProcessRunner.ProcessRunner["Service"];
75 }) {
76 const { fs, runner } = input;
77 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
78
79 return yield* pinnedRuntimeInstallLock.withPermit(
80 Effect.gen(function* () {
81 const alreadyPinned = yield* Effect.all([
82 fs.exists(paths.sentinelPath),
83 fs.exists(paths.entryPath),
84 ]).pipe(
85 Effect.map(([sentinelExists, entryExists]) => sentinelExists && entryExists),
86 Effect.mapError(
87 (cause) =>
88 new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
89 ),
90 );
91 if (alreadyPinned) {
92 return paths;
93 }
94
95 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
96 Effect.andThen(fs.makeDirectory(paths.versionDir, { recursive: true })),
97 Effect.mapError(
98 (cause) =>
99 new PinnedRuntimeInstallError({
100 step: "preparing the pinned runtime directory",
101 cause,
102 }),
103 ),
104 );
105
106 const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
107 yield* runner
108 .run({
109 command: "npm",
110 args: [
111 "install",
112 "--prefix",
113 paths.versionDir,
114 "--no-fund",
115 "--no-audit",
116 `t3@${input.version}`,
117 ],
118 // Native deps (node-pty) can compile from source on slow boxes; the
119 // ProcessRunner default of 60s would kill a healthy install.
120 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
121 })
122 .pipe(
123 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
124 Effect.filterOrFail(
125 (result) => result.code === 0,
126 (result) =>
127 new PinnedRuntimeInstallError({
128 step: installStep,
129 exitCode: Number(result.code),
130 stdoutLength: result.stdout.length,
131 stderrLength: result.stderr.length,
132 }),
133 ),
134 Effect.tapError(() =>
135 fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(Effect.ignore),
136 ),
137 );
138
139 yield* fs
140 .writeFileString(paths.sentinelPath, `${input.version}\n`)
141 .pipe(
142 Effect.mapError(
143 (cause) =>
144 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
145 ),
146 );
147
148 return paths;
149 }),
150 );
151 },
152);
153
154/** Removes one pinned runtime while holding the same process-wide lock used
155 * by install/check/sentinel work, so cleanup cannot race another caller that
156 * is materializing or reusing the runtime tree. */
157export const removePinnedRuntimeInstallation = Effect.fn("cloud.pinned_runtime.remove")(
158 function* (input: {
159 readonly baseDir: string;
160 readonly version: string;
161 readonly fs: FileSystem.FileSystem;
162 readonly path: Path.Path;
163 }) {
164 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
165 yield* pinnedRuntimeInstallLock.withPermit(
166 input.fs
167 .remove(paths.versionDir, { recursive: true, force: true })
168 .pipe(
169 Effect.mapError(
170 (cause) =>
171 new PinnedRuntimeInstallError({ step: "removing the pinned runtime", cause }),
172 ),
173 ),
174 );
175 },
176);