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