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

pinnedRuntime.ts

339 lines11.8 KB

1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as Encoding from "effect/Encoding";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7import * as Option from "effect/Option";
8import * as Semaphore from "effect/Semaphore";
9import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
10​
11import {
12 CLI_RELEASE_CHECKSUMS_FILE,
13 cliArchiveFileName,
14 cliArchivePlatformKey,
15 cliArchiveTarCommand,
16 cliReleaseDownloadBaseUrl,
17 parseChecksums,
18} from "@t3tools/shared/cliRelease";
19​
20import * as ProcessRunner from "../processRunner.ts";
21​
22/**
23 * A pinned runtime is an exact t3 release archive unpacked into
24 * <baseDir>/runtime/versions/<version>: the self-contained executable, the
25 * web client, and the native packages beside it. The boot service points its
26 * unit or launch agent at the executable, and server self-update installs the
27 * target version here before switching over. The runtime never depends on a
28 * Node or npm on the machine; the only npm involvement in T3 Code is the `t3`
29 * package for people who prefer `npx t3` or `npm install -g t3`, and even a
30 * CLI installed that way pins an archive when it sets up the service.
31 */
32const PINNED_RUNTIME_DIR = "runtime";
33const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
34const PINNED_RUNTIME_ARCHIVE_FILE = "t3-runtime-archive";
35// Boot-service setup and remote update can construct separate layers. Serialize
36// the complete install transaction across every caller in this process.
37const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
38​
39export interface PinnedRuntimePaths {
40 readonly versionDir: string;
41 /** The executable. Its existence is what marks a runtime as present. */
42 readonly entryPath: string;
43 readonly sentinelPath: string;
45​
46/** The exact command that runs a pinned runtime. */
47export function pinnedRuntimeCommand(paths: PinnedRuntimePaths): {
48 readonly command: string;
49 readonly args: ReadonlyArray<string>;
50} {
51 return { command: paths.entryPath, args: [] };
53​
54export function pinnedRuntimeVersionsDir(path: Path.Path, baseDir: string): string {
55 return path.join(baseDir, PINNED_RUNTIME_DIR, "versions");
57​
58export function pinnedRuntimePaths(
59 path: Path.Path,
60 baseDir: string,
61 version: string,
62 platform: NodeJS.Platform,
63): PinnedRuntimePaths {
64 const versionDir = path.join(pinnedRuntimeVersionsDir(path, baseDir), version);
65 return {
66 versionDir,
67 entryPath: path.join(versionDir, platform === "win32" ? "t3.exe" : "t3"),
68 sentinelPath: path.join(versionDir, ".install-complete"),
69 };
71​
72export class PinnedRuntimeInstallError extends Schema.TaggedError<PinnedRuntimeInstallError>()(
73 "PinnedRuntimeInstallError",
74 {
75 step: Schema.String,
76 exitCode: Schema.optional(Schema.Number),
77 stdoutLength: Schema.optional(Schema.Number),
78 stderrLength: Schema.optional(Schema.Number),
79 cause: Schema.optional(Schema.Defect()),
80 },
81) {
82 override get message(): string {
83 return this.exitCode === undefined
84 ? `Pinned runtime install failed while ${this.step}.`
85 : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
86 }
88​
89export class PinnedRuntimePreflightBlockedError extends Schema.TaggedError<PinnedRuntimePreflightBlockedError>()(
90 "PinnedRuntimePreflightBlockedError",
91 {
92 version: Schema.String,
93 reason: Schema.String,
94 },
95) {
96 override get message(): string {
97 return this.reason;
98 }
100​
101/**
102 * Installs the t3 release archive for `version` into the pinned runtime
103 * directory unless a complete install is already there, and returns its
104 * paths. The sentinel is written only after extraction and validation
105 * succeed; checking the entry file alone is not enough, since tar writes the
106 * executable before the last native package and a killed install leaves a
107 * plausible-looking but broken tree behind.
108 */
109interface PinnedRuntimeInstallInput {
110 readonly baseDir: string;
111 readonly version: string;
112 readonly fs: FileSystem.FileSystem;
113 readonly path: Path.Path;
114 readonly runner: ProcessRunner.ProcessRunner["Service"];
115 readonly validate: (
116 paths: PinnedRuntimePaths,
117 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
118 readonly platform: NodeJS.Platform;
119 readonly arch: string;
120 readonly httpClient: HttpClient.HttpClient;
121 readonly releaseBaseUrl?: string | undefined;
123​
124const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* (
125 httpClient: HttpClient.HttpClient,
126 url: string,
127 step: string,
128) {
129 // The install lock is held for the whole transaction, so a stalled download
130 // must fail rather than block every other caller.
131 return yield* httpClient.execute(HttpClientRequest.get(url)).pipe(
132 Effect.flatMap(HttpClientResponse.filterStatusOk),
133 Effect.flatMap((response) => response.arrayBuffer),
134 Effect.map((buffer) => new Uint8Array(buffer)),
135 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step, cause })),
136 Effect.timeoutOrElse({
137 duration: PINNED_RUNTIME_INSTALL_TIMEOUT,
138 orElse: () => Effect.fail(new PinnedRuntimeInstallError({ step: `${step} (timed out)` })),
139 }),
140 );
141});
142​
143/**
144 * Downloads the release archive for this platform, verifies it against the
145 * release's checksum file, and unpacks it so the executable sits directly in
146 * the staging directory. Only `tar` is required on the host; every supported
147 * OS ships one that reads gzip and zip.
148 */
149const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(function* (
150 input: PinnedRuntimeInstallInput,
151 stagingDir: string,
152) {
153 const { fs, path } = input;
154 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
155 if (platformKey === undefined) {
156 return yield* new PinnedRuntimeInstallError({
157 step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
158 });
159 }
160 const httpClient = input.httpClient;
161 const baseUrl = cliReleaseDownloadBaseUrl(input.version, input.releaseBaseUrl);
162 const fileName = cliArchiveFileName(input.version, platformKey);
163​
164 const checksums = parseChecksums(
165 new TextDecoder().decode(
166 yield* fetchReleaseAsset(
167 httpClient,
168 `${baseUrl}/${CLI_RELEASE_CHECKSUMS_FILE}`,
169 "downloading the t3 release checksums",
170 ),
171 ),
172 );
173 const expected = checksums.get(fileName);
174 if (expected === undefined) {
175 return yield* new PinnedRuntimeInstallError({
176 step: `finding ${fileName} in the t3 release checksums`,
177 });
178 }
179 const archive = yield* fetchReleaseAsset(
180 httpClient,
181 `${baseUrl}/${fileName}`,
182 "downloading the t3 release archive",
183 );
184 const digest = yield* Effect.tryPromise({
185 try: () => crypto.subtle.digest("SHA-256", archive),
186 catch: (cause) =>
187 new PinnedRuntimeInstallError({ step: "verifying the t3 release archive", cause }),
188 });
189 if (Encoding.encodeHex(new Uint8Array(digest)) !== expected) {
190 return yield* new PinnedRuntimeInstallError({
191 step: "verifying the t3 release archive checksum",
192 });
193 }
194​
195 const archivePath = path.join(stagingDir, PINNED_RUNTIME_ARCHIVE_FILE);
196 yield* fs
197 .writeFile(archivePath, archive)
198 .pipe(
199 Effect.mapError(
200 (cause) => new PinnedRuntimeInstallError({ step: "writing the t3 release archive", cause }),
201 ),
202 );
203 const extractStep = "extracting the t3 release archive";
204 // The archive wraps everything in one directory named after its stem;
205 // strip it so the executable lands at <versionDir>/t3.
206 yield* input.runner
207 .run({
208 command: cliArchiveTarCommand(input.platform, process.env),
209 args: ["-xf", archivePath, "-C", stagingDir, "--strip-components=1"],
210 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
211 })
212 .pipe(
213 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: extractStep, cause })),
214 Effect.filterOrFail(
215 (result) => result.code === 0,
216 (result) =>
217 new PinnedRuntimeInstallError({
218 step: extractStep,
219 exitCode: Number(result.code),
220 stdoutLength: result.stdout.length,
221 stderrLength: result.stderr.length,
222 }),
223 ),
224 );
225 yield* fs.remove(archivePath, { force: true }).pipe(Effect.ignore);
226});
227​
228const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
229 input: PinnedRuntimeInstallInput,
230) {
231 const { fs } = input;
232 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version, input.platform);
233 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
234 fs.exists(paths.versionDir),
235 fs.exists(paths.entryPath),
236 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
237 ]).pipe(
238 Effect.mapError(
239 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
240 ),
241 );
242 const alreadyPinned =
243 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
244 if (alreadyPinned) {
245 yield* input.validate(paths);
246 return paths;
247 }
248 if (versionDirExists) {
249 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
250 Effect.mapError(
251 (cause) =>
252 new PinnedRuntimeInstallError({
253 step: "removing an incomplete pinned runtime",
254 cause,
255 }),
256 ),
257 );
258 }
259​
260 const versionsDir = input.path.dirname(paths.versionDir);
261 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
262 Effect.mapError(
263 (cause) =>
264 new PinnedRuntimeInstallError({
265 step: "preparing the pinned runtime directory",
266 cause,
267 }),
268 ),
269 );
270 const stagingDir = yield* fs
271 .makeTempDirectory({
272 directory: versionsDir,
273 prefix: ".staging-",
274 })
275 .pipe(
276 Effect.mapError(
277 (cause) =>
278 new PinnedRuntimeInstallError({
279 step: "preparing the pinned runtime directory",
280 cause,
281 }),
282 ),
283 );
284 const stagingPaths: PinnedRuntimePaths = {
285 versionDir: stagingDir,
286 entryPath: input.path.join(stagingDir, input.path.relative(paths.versionDir, paths.entryPath)),
287 sentinelPath: input.path.join(stagingDir, ".install-complete"),
288 };
289​
290 return yield* Effect.gen(function* () {
291 yield* installFromArchive(input, stagingDir);
292​
293 yield* input.validate(stagingPaths);
294 yield* fs
295 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
296 .pipe(
297 Effect.mapError(
298 (cause) =>
299 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
300 ),
301 );
302 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
303 Effect.as(true),
304 Effect.catch((cause) =>
305 Effect.all([
306 fs.exists(paths.entryPath),
307 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
308 ]).pipe(
309 Effect.mapError(
310 (checkCause) =>
311 new PinnedRuntimeInstallError({
312 step: "checking a concurrently published pinned runtime",
313 cause: checkCause,
314 }),
315 ),
316 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
317 publishedEntryExists &&
318 Option.isSome(publishedSentinel) &&
319 publishedSentinel.value.trim() === input.version
320 ? Effect.succeed(false)
321 : Effect.fail(
322 new PinnedRuntimeInstallError({
323 step: "publishing the pinned runtime",
324 cause,
325 }),
326 ),
327 ),
328 ),
329 ),
330 );
331 if (!published) yield* input.validate(paths);
332 return paths;
333 }).pipe(
334 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
335 );
336});
337​
338export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
339 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));