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