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

pinnedRuntime.ts

292 lines9.8 KB

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 PlatformError from "effect/PlatformError";
6import * as Schema from "effect/Schema";
7import * as Option from "effect/Option";
8import * as Semaphore from "effect/Semaphore";
9​
10import * as ProcessRunner from "../processRunner.ts";
11​
12/**
13 * A pinned runtime is an exact `t3@<version>` npm-installed into
14 * <baseDir>/runtime/versions/<version>. The boot service points its unit or
15 * launch agent here, and server self-update installs the target version here before
16 * switching over, never `npx t3`, whose cache is ephemeral and whose
17 * registry fetch at boot would make startup depend on the network.
18 */
19​
20const PINNED_RUNTIME_DIR = "runtime";
21const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
22// Boot-service setup and remote update can construct separate layers. Serialize
23// the complete install transaction across every caller in this process.
24const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
25​
26export interface PinnedRuntimePaths {
27 readonly versionDir: string;
28 readonly entryPath: string;
29 readonly sentinelPath: string;
31​
32export function pinnedRuntimePaths(
33 path: Path.Path,
34 baseDir: string,
35 version: string,
36): PinnedRuntimePaths {
37 const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, "versions", version);
38 return {
39 versionDir,
40 entryPath: path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
41 sentinelPath: path.join(versionDir, ".install-complete"),
42 };
44​
45export class PinnedRuntimeInstallError extends Schema.TaggedError<PinnedRuntimeInstallError>()(
46 "PinnedRuntimeInstallError",
47 {
48 step: Schema.String,
49 exitCode: Schema.optional(Schema.Number),
50 stdoutLength: Schema.optional(Schema.Number),
51 stderrLength: Schema.optional(Schema.Number),
52 cause: Schema.optional(Schema.Defect()),
53 },
54) {
55 override get message(): string {
56 return this.exitCode === undefined
57 ? `Pinned runtime install failed while ${this.step}.`
58 : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
59 }
61​
62export class PinnedRuntimePreflightBlockedError extends Schema.TaggedError<PinnedRuntimePreflightBlockedError>()(
63 "PinnedRuntimePreflightBlockedError",
64 {
65 version: Schema.String,
66 reason: Schema.String,
67 },
68) {
69 override get message(): string {
70 return this.reason;
71 }
73​
74/**
75 * Installs `t3@<version>` into the pinned runtime directory unless a complete
76 * install is already there, and returns its paths. The sentinel is written
77 * only after npm succeeds and validation passes. npm can skip native builds
78 * (node-pty) or be killed after extracting files, leaving a plausible-looking
79 * but broken tree behind.
80 */
81interface PinnedRuntimeInstallInput {
82 readonly baseDir: string;
83 readonly version: string;
84 readonly execPath: string;
85 readonly fs: FileSystem.FileSystem;
86 readonly path: Path.Path;
87 readonly runner: ProcessRunner.ProcessRunner["Service"];
88 readonly validate: (
89 paths: PinnedRuntimePaths,
90 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
92​
93const validatePinnedRuntime = Effect.fn("cloud.pinned_runtime.validate")(function* (
94 input: PinnedRuntimeInstallInput,
95 paths: PinnedRuntimePaths,
96) {
97 // Resolve from the candidate, using the Node executable that will run it.
98 // npm can exit successfully even when it skips node-pty's native build.
99 const step = "loading node-pty in the pinned t3 runtime";
100 yield* input.runner
101 .run({
102 command: input.execPath,
103 args: [
104 "--input-type=commonjs",
105 "--eval",
106 "require('node:module').createRequire(process.argv[1])('node-pty');",
107 paths.entryPath,
108 ],
109 timeout: Duration.seconds(30),
110 })
111 .pipe(
112 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step, cause })),
113 Effect.filterOrFail(
114 (result) => result.code === 0,
115 (result) =>
116 new PinnedRuntimeInstallError({
117 step,
118 exitCode: Number(result.code),
119 stdoutLength: result.stdout.length,
120 stderrLength: result.stderr.length,
121 }),
122 ),
123 );
124 yield* input.validate(paths);
125});
126​
127const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
128 input: PinnedRuntimeInstallInput,
129) {
130 const { fs, runner } = input;
131 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
132 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
133 fs.exists(paths.versionDir),
134 fs.exists(paths.entryPath),
135 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
136 ]).pipe(
137 Effect.mapError(
138 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
139 ),
140 );
141 const alreadyPinned =
142 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
143 if (alreadyPinned) {
144 yield* validatePinnedRuntime(input, paths);
145 return paths;
146 }
147 if (versionDirExists) {
148 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
149 Effect.mapError(
150 (cause) =>
151 new PinnedRuntimeInstallError({
152 step: "removing an incomplete pinned runtime",
153 cause,
154 }),
155 ),
156 );
157 }
158​
159 const versionsDir = input.path.dirname(paths.versionDir);
160 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
161 Effect.mapError(
162 (cause) =>
163 new PinnedRuntimeInstallError({
164 step: "preparing the pinned runtime directory",
165 cause,
166 }),
167 ),
168 );
169 const stagingDir = yield* fs
170 .makeTempDirectory({
171 directory: versionsDir,
172 prefix: ".staging-",
173 })
174 .pipe(
175 Effect.mapError(
176 (cause) =>
177 new PinnedRuntimeInstallError({
178 step: "preparing the pinned runtime directory",
179 cause,
180 }),
181 ),
182 );
183 const stagingPaths: PinnedRuntimePaths = {
184 versionDir: stagingDir,
185 entryPath: input.path.join(stagingDir, "node_modules", "t3", "dist", "bin.mjs"),
186 sentinelPath: input.path.join(stagingDir, ".install-complete"),
187 };
188​
189 return yield* Effect.gen(function* () {
190 // npm 12 requires project-scoped build approvals in the root manifest.
191 // Its CLI allow-scripts flag only applies to global installs and npm exec.
192 yield* fs
193 .writeFileString(
194 input.path.join(stagingDir, "package.json"),
195 '{"private":true,"allowScripts":{"node-pty":true,"msgpackr-extract":true}}\n',
196 )
197 .pipe(
198 Effect.mapError(
199 (cause) =>
200 new PinnedRuntimeInstallError({ step: "preparing native build approvals", cause }),
201 ),
202 );
203 const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
204 const installArgs = [
205 "install",
206 "--prefix",
207 stagingDir,
208 "--no-fund",
209 "--no-audit",
210 `t3@${input.version}`,
211 ];
212 yield* runner
213 .run({
214 command: "npm",
215 args: installArgs,
216 // Native dependencies may compile from source on slower machines.
217 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
218 })
219 .pipe(
220 Effect.catchTags({
221 ProcessSpawnError: (error) =>
222 error.cause instanceof PlatformError.PlatformError &&
223 error.cause.reason._tag === "NotFound"
224 ? // pnpm-managed Node installations do not include npm. Keep npm
225 // installation semantics for the pinned runtime and native builds.
226 runner.run({
227 command: "pnpm",
228 args: ["--package=npm@11", "dlx", "npm", ...installArgs],
229 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
230 })
231 : Effect.fail(error),
232 }),
233 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
234 Effect.filterOrFail(
235 (result) => result.code === 0,
236 (result) =>
237 new PinnedRuntimeInstallError({
238 step: installStep,
239 exitCode: Number(result.code),
240 stdoutLength: result.stdout.length,
241 stderrLength: result.stderr.length,
242 }),
243 ),
244 );
245​
246 yield* validatePinnedRuntime(input, stagingPaths);
247 yield* fs
248 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
249 .pipe(
250 Effect.mapError(
251 (cause) =>
252 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
253 ),
254 );
255 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
256 Effect.as(true),
257 Effect.catch((cause) =>
258 Effect.all([
259 fs.exists(paths.entryPath),
260 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
261 ]).pipe(
262 Effect.mapError(
263 (checkCause) =>
264 new PinnedRuntimeInstallError({
265 step: "checking a concurrently published pinned runtime",
266 cause: checkCause,
267 }),
268 ),
269 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
270 publishedEntryExists &&
271 Option.isSome(publishedSentinel) &&
272 publishedSentinel.value.trim() === input.version
273 ? Effect.succeed(false)
274 : Effect.fail(
275 new PinnedRuntimeInstallError({
276 step: "publishing the pinned runtime",
277 cause,
278 }),
279 ),
280 ),
281 ),
282 ),
283 );
284 if (!published) yield* validatePinnedRuntime(input, paths);
285 return paths;
286 }).pipe(
287 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
288 );
289});
290​
291export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
292 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));