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

pinnedRuntime.ts

244 lines8.2 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 exits 0; checking the entry file alone is not enough. npm
78 * extracts files before running native builds (node-pty), so a killed
79 * install leaves a plausible-looking but broken tree behind.
80 */
81interface PinnedRuntimeInstallInput {
82 readonly baseDir: string;
83 readonly version: string;
84 readonly fs: FileSystem.FileSystem;
85 readonly path: Path.Path;
86 readonly runner: ProcessRunner.ProcessRunner["Service"];
87 readonly validate: (
88 paths: PinnedRuntimePaths,
89 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
91​
92const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
93 input: PinnedRuntimeInstallInput,
94) {
95 const { fs, runner } = input;
96 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
97 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
98 fs.exists(paths.versionDir),
99 fs.exists(paths.entryPath),
100 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
101 ]).pipe(
102 Effect.mapError(
103 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
104 ),
105 );
106 const alreadyPinned =
107 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
108 if (alreadyPinned) {
109 yield* input.validate(paths);
110 return paths;
111 }
112 if (versionDirExists) {
113 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
114 Effect.mapError(
115 (cause) =>
116 new PinnedRuntimeInstallError({
117 step: "removing an incomplete pinned runtime",
118 cause,
119 }),
120 ),
121 );
122 }
123​
124 const versionsDir = input.path.dirname(paths.versionDir);
125 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
126 Effect.mapError(
127 (cause) =>
128 new PinnedRuntimeInstallError({
129 step: "preparing the pinned runtime directory",
130 cause,
131 }),
132 ),
133 );
134 const stagingDir = yield* fs
135 .makeTempDirectory({
136 directory: versionsDir,
137 prefix: ".staging-",
138 })
139 .pipe(
140 Effect.mapError(
141 (cause) =>
142 new PinnedRuntimeInstallError({
143 step: "preparing the pinned runtime directory",
144 cause,
145 }),
146 ),
147 );
148 const stagingPaths: PinnedRuntimePaths = {
149 versionDir: stagingDir,
150 entryPath: input.path.join(stagingDir, "node_modules", "t3", "dist", "bin.mjs"),
151 sentinelPath: input.path.join(stagingDir, ".install-complete"),
152 };
153​
154 return yield* Effect.gen(function* () {
155 const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
156 const installArgs = [
157 "install",
158 "--prefix",
159 stagingDir,
160 "--no-fund",
161 "--no-audit",
162 `t3@${input.version}`,
163 ];
164 yield* runner
165 .run({
166 command: "npm",
167 args: installArgs,
168 // Native dependencies may compile from source on slower machines.
169 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
170 })
171 .pipe(
172 Effect.catchTags({
173 ProcessSpawnError: (error) =>
174 error.cause instanceof PlatformError.PlatformError &&
175 error.cause.reason._tag === "NotFound"
176 ? // pnpm-managed Node installations do not include npm. Keep npm
177 // installation semantics for the pinned runtime and native builds.
178 runner.run({
179 command: "pnpm",
180 args: ["--package=npm@11", "dlx", "npm", ...installArgs],
181 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
182 })
183 : Effect.fail(error),
184 }),
185 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
186 Effect.filterOrFail(
187 (result) => result.code === 0,
188 (result) =>
189 new PinnedRuntimeInstallError({
190 step: installStep,
191 exitCode: Number(result.code),
192 stdoutLength: result.stdout.length,
193 stderrLength: result.stderr.length,
194 }),
195 ),
196 );
197​
198 yield* input.validate(stagingPaths);
199 yield* fs
200 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
201 .pipe(
202 Effect.mapError(
203 (cause) =>
204 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
205 ),
206 );
207 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
208 Effect.as(true),
209 Effect.catch((cause) =>
210 Effect.all([
211 fs.exists(paths.entryPath),
212 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
213 ]).pipe(
214 Effect.mapError(
215 (checkCause) =>
216 new PinnedRuntimeInstallError({
217 step: "checking a concurrently published pinned runtime",
218 cause: checkCause,
219 }),
220 ),
221 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
222 publishedEntryExists &&
223 Option.isSome(publishedSentinel) &&
224 publishedSentinel.value.trim() === input.version
225 ? Effect.succeed(false)
226 : Effect.fail(
227 new PinnedRuntimeInstallError({
228 step: "publishing the pinned runtime",
229 cause,
230 }),
231 ),
232 ),
233 ),
234 ),
235 );
236 if (!published) yield* input.validate(paths);
237 return paths;
238 }).pipe(
239 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
240 );
241});
242​
243export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
244 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));