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

pinnedRuntime.ts

222 lines7.5 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 Schema from "effect/Schema";
6import * as Option from "effect/Option";
7import * as Semaphore from "effect/Semaphore";
8​
9import * as ProcessRunner from "../processRunner.ts";
10​
11/**
12 * A pinned runtime is an exact `t3@<version>` npm-installed into
13 * <baseDir>/runtime/versions/<version>. The boot service points its unit or
14 * launch agent here, and server self-update installs the target version here before
15 * switching over, never `npx t3`, whose cache is ephemeral and whose
16 * registry fetch at boot would make startup depend on the network.
17 */
18​
19const PINNED_RUNTIME_DIR = "runtime";
20const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
21// Boot-service setup and remote update can construct separate layers. Serialize
22// the complete install transaction across every caller in this process.
23const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
24​
25export interface PinnedRuntimePaths {
26 readonly versionDir: string;
27 readonly entryPath: string;
28 readonly sentinelPath: string;
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 };
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 }
60​
61export class PinnedRuntimePreflightBlockedError extends Schema.TaggedErrorClass<PinnedRuntimePreflightBlockedError>()(
62 "PinnedRuntimePreflightBlockedError",
63 {
64 version: Schema.String,
65 reason: Schema.String,
66 },
67) {
68 override get message(): string {
69 return this.reason;
70 }
72​
73/**
74 * Installs `t3@<version>` into the pinned runtime directory unless a complete
75 * install is already there, and returns its paths. The sentinel is written
76 * only after npm exits 0; checking the entry file alone is not enough. npm
77 * extracts files before running native builds (node-pty), so a killed
78 * install leaves a plausible-looking but broken tree behind.
79 */
80interface PinnedRuntimeInstallInput {
81 readonly baseDir: string;
82 readonly version: string;
83 readonly fs: FileSystem.FileSystem;
84 readonly path: Path.Path;
85 readonly runner: ProcessRunner.ProcessRunner["Service"];
86 readonly validate: (
87 paths: PinnedRuntimePaths,
88 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
90​
91const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
92 input: PinnedRuntimeInstallInput,
93) {
94 const { fs, runner } = input;
95 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);
96 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
97 fs.exists(paths.versionDir),
98 fs.exists(paths.entryPath),
99 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
100 ]).pipe(
101 Effect.mapError(
102 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
103 ),
104 );
105 const alreadyPinned =
106 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
107 if (alreadyPinned) {
108 yield* input.validate(paths);
109 return paths;
110 }
111 if (versionDirExists) {
112 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
113 Effect.mapError(
114 (cause) =>
115 new PinnedRuntimeInstallError({
116 step: "removing an incomplete pinned runtime",
117 cause,
118 }),
119 ),
120 );
121 }
122​
123 const versionsDir = input.path.dirname(paths.versionDir);
124 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
125 Effect.mapError(
126 (cause) =>
127 new PinnedRuntimeInstallError({
128 step: "preparing the pinned runtime directory",
129 cause,
130 }),
131 ),
132 );
133 const stagingDir = yield* fs
134 .makeTempDirectory({
135 directory: versionsDir,
136 prefix: ".staging-",
137 })
138 .pipe(
139 Effect.mapError(
140 (cause) =>
141 new PinnedRuntimeInstallError({
142 step: "preparing the pinned runtime directory",
143 cause,
144 }),
145 ),
146 );
147 const stagingPaths: PinnedRuntimePaths = {
148 versionDir: stagingDir,
149 entryPath: input.path.join(stagingDir, "node_modules", "t3", "dist", "bin.mjs"),
150 sentinelPath: input.path.join(stagingDir, ".install-complete"),
151 };
152​
153 return yield* Effect.gen(function* () {
154 const installStep = "installing the pinned t3 runtime (this can take a few minutes)";
155 yield* runner
156 .run({
157 command: "npm",
158 args: ["install", "--prefix", stagingDir, "--no-fund", "--no-audit", `t3@${input.version}`],
159 // Native dependencies may compile from source on slower machines.
160 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
161 })
162 .pipe(
163 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),
164 Effect.filterOrFail(
165 (result) => result.code === 0,
166 (result) =>
167 new PinnedRuntimeInstallError({
168 step: installStep,
169 exitCode: Number(result.code),
170 stdoutLength: result.stdout.length,
171 stderrLength: result.stderr.length,
172 }),
173 ),
174 );
175​
176 yield* input.validate(stagingPaths);
177 yield* fs
178 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
179 .pipe(
180 Effect.mapError(
181 (cause) =>
182 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
183 ),
184 );
185 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
186 Effect.as(true),
187 Effect.catch((cause) =>
188 Effect.all([
189 fs.exists(paths.entryPath),
190 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
191 ]).pipe(
192 Effect.mapError(
193 (checkCause) =>
194 new PinnedRuntimeInstallError({
195 step: "checking a concurrently published pinned runtime",
196 cause: checkCause,
197 }),
198 ),
199 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
200 publishedEntryExists &&
201 Option.isSome(publishedSentinel) &&
202 publishedSentinel.value.trim() === input.version
203 ? Effect.succeed(false)
204 : Effect.fail(
205 new PinnedRuntimeInstallError({
206 step: "publishing the pinned runtime",
207 cause,
208 }),
209 ),
210 ),
211 ),
212 ),
213 );
214 if (!published) yield* input.validate(paths);
215 return paths;
216 }).pipe(
217 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
218 );
219});
220​
221export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
222 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));