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

pinnedRuntime.ts

1,100 lines42.7 KB

1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Hex from "effect/encoding/Hex";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as Option from "effect/Option";
10import * as Schedule from "effect/Schedule";
11import * as Stream from "effect/Stream";
12import * as Semaphore from "effect/Semaphore";
13import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
14​
15import {
16 CLI_RELEASE_CHECKSUMS_FILE,
17 cliArchiveFileName,
18 cliArchivePlatformKey,
19 cliArchiveTarCommand,
20 cliReleaseAssetUrl,
21 cliReleaseChannelOf,
22 cliReleaseIndexPageUrl,
23 type CliArchivePlatformKey,
24 parseChecksums,
25} from "@t3tools/shared/cliRelease";
26​
27import * as HostProcess from "@t3tools/shared/HostProcess";
28​
29import * as ProcessRunner from "../processRunner.ts";
30import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem";
31import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts";
32​
33const PINNED_RUNTIME_DIR = "runtime";
34const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
35const PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT = Duration.minutes(1);
36const PINNED_RUNTIME_ARCHIVE_FILE = "t3-runtime-archive";
37// Separate layers share one install lock across this process.
38const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
39​
40export interface PinnedRuntimePaths {
41 readonly versionDir: string;
42 readonly entryPath: string;
43 readonly sentinelPath: string;
45​
46export function pinnedRuntimeCommand(paths: PinnedRuntimePaths): {
47 readonly command: string;
48 readonly args: ReadonlyArray<string>;
49} {
50 return { command: paths.entryPath, args: [] };
52​
53export function pinnedRuntimeVersionsDir(path: Path.Path, baseDir: string): string {
54 return path.join(baseDir, PINNED_RUNTIME_DIR, "versions");
56​
57export function pinnedRuntimePaths(
58 path: Path.Path,
59 baseDir: string,
60 version: string,
61 platform: NodeJS.Platform,
62): PinnedRuntimePaths {
63 const versionDir = path.join(pinnedRuntimeVersionsDir(path, baseDir), version);
64 return {
65 versionDir,
66 entryPath: path.join(versionDir, platform === "win32" ? "t3.exe" : "t3"),
67 sentinelPath: path.join(versionDir, ".install-complete"),
68 };
70​
71export class PinnedRuntimeInstallError extends Schema.TaggedError<PinnedRuntimeInstallError>()(
72 "PinnedRuntimeInstallError",
73 {
74 step: Schema.String,
75 exitCode: Schema.optional(Schema.Number),
76 stdoutLength: Schema.optional(Schema.Number),
77 stderrLength: Schema.optional(Schema.Number),
78 httpStatus: Schema.optional(Schema.Number),
79 downloadHost: Schema.optional(Schema.String),
80 cause: Schema.optional(Schema.Defect()),
81 },
82) {
83 override get message(): string {
84 return this.exitCode === undefined
85 ? `Pinned runtime install failed while ${this.step}.`
86 : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
87 }
89​
90export class PinnedRuntimePreflightBlockedError extends Schema.TaggedError<PinnedRuntimePreflightBlockedError>()(
91 "PinnedRuntimePreflightBlockedError",
92 {
93 version: Schema.String,
94 reason: Schema.String,
95 },
96) {
97 override get message(): string {
98 return this.reason;
99 }
101​
102export type PinnedRuntimeProgress =
103 | { readonly stage: "download"; readonly received: number; readonly total: number | undefined }
104 | { readonly stage: "verify" | "extract" | "validate" | "cached" };
105​
106/** Tar writes the executable before native packages; only a validated install gets a sentinel. */
107​
108interface PinnedRuntimeInstallInput {
109 readonly baseDir: string;
110 readonly version: string;
111 readonly fs: FileSystem.FileSystem;
112 readonly path: Path.Path;
113 readonly runner: ProcessRunner.ProcessRunner["Service"];
114 readonly validate: (
115 paths: PinnedRuntimePaths,
116 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
117 readonly platform: NodeJS.Platform;
118 readonly arch: string;
119 readonly httpClient: HttpClient.HttpClient;
120 readonly releaseBaseUrl?: string | undefined;
121 readonly githubToken?: string | undefined;
122 /** Reuse a cached runtime only while the release source still lists it, as a policy mirror does. */
123 readonly requirePublishedRelease?: boolean;
124 readonly onProgress?: (progress: PinnedRuntimeProgress) => void;
126​
127// GitHub release downloads intermittently answer 5xx during incidents; a retry usually lands.
128const DOWNLOAD_RETRY = { times: 3, schedule: Schedule.exponential("2 seconds") } as const;
129​
130const isTransientDownloadFailure = (
131 error: HttpClientError.HttpClientError | Cause.TimeoutError,
132): boolean => {
133 // A slow link stalls past the bound and then recovers; the retry resumes from the bytes held.
134 if (error._tag === "TimeoutError") return true;
135 // Body bytes are read raw, so a DecodeError is a body that failed after the host answered.
136 if (error.reason._tag === "DecodeError") return true;
137 const status = error.response?.status;
138 return status !== undefined && (status >= 500 || status === 429 || status === 408);
139};
140​
141const CONTENT_RANGE = /^bytes (\d+)-\d+\/(\d+|\*)$/;
142​
143const concatChunks = (chunks: ReadonlyArray<Uint8Array>, length: number): Uint8Array => {
144 const bytes = new Uint8Array(length);
145 let offset = 0;
146 for (const chunk of chunks) {
147 bytes.set(chunk, offset);
148 offset += chunk.byteLength;
149 }
150 return bytes;
151};
152​
153const GITHUB_API_ORIGIN = "https://api.github.com";
154const GITHUB_RELEASE_INDEX_MAX_PAGES = 10;
155​
156const GithubReleaseIndex = Schema.Array(
157 Schema.Struct({
158 tag_name: Schema.String,
159 assets: Schema.optional(
160 Schema.Array(
161 Schema.Struct({
162 name: Schema.String,
163 url: Schema.String,
164 }),
165 ),
166 ),
167 }),
168);
169const decodeGithubReleaseIndex = Schema.decodeUnknownEffect(
170 Schema.fromJsonString(GithubReleaseIndex),
171);
172​
173const resolveGithubReleaseAssets = Effect.fn("cloud.pinned_runtime.resolve_github_release_assets")(
174 function* (httpClient: HttpClient.HttpClient, version: string, githubToken: string) {
175 const tag = `v${version}`;
176 for (let page = 1; page <= GITHUB_RELEASE_INDEX_MAX_PAGES; page += 1) {
177 const url = cliReleaseIndexPageUrl(page);
178 const request = HttpClientRequest.get(url).pipe(
179 HttpClientRequest.setHeader("Accept", "application/vnd.github+json"),
180 HttpClientRequest.setHeader("Authorization", `Bearer ${githubToken}`),
181 );
182 const body = yield* httpClient.execute(request).pipe(
183 Effect.flatMap(HttpClientResponse.filterStatusOk),
184 Effect.flatMap((response) => response.text),
185 Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT),
186 Effect.retry({ ...DOWNLOAD_RETRY, while: isTransientDownloadFailure }),
187 Effect.mapError(
188 (cause) =>
189 new PinnedRuntimeInstallError({
190 step:
191 cause._tag === "TimeoutError"
192 ? "listing t3 releases (timed out)"
193 : "listing t3 releases",
194 httpStatus:
195 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
196 ? cause.reason.response.status
197 : undefined,
198 downloadHost: URL.parse(
199 HttpClientError.isHttpClientError(cause) ? cause.request.url : url,
200 )?.host,
201 cause,
202 }),
203 ),
204 );
205 const releases = yield* decodeGithubReleaseIndex(body).pipe(
206 Effect.mapError(
207 (cause) =>
208 new PinnedRuntimeInstallError({
209 step: "decoding the t3 release index",
210 cause,
211 }),
212 ),
213 );
214 const release = releases.find((candidate) => candidate.tag_name === tag);
215 if (release !== undefined) {
216 return new Map((release.assets ?? []).map((asset) => [asset.name, asset.url] as const));
217 }
218 if (releases.length === 0) break;
219 }
220 return yield* new PinnedRuntimeInstallError({
221 step: `finding t3@${version} in GitHub releases`,
222 });
223 },
224);
225​
226const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* (
227 httpClient: HttpClient.HttpClient,
228 url: string,
229 step: string,
230 // Only a digest-checked asset resumes; anything else restarts at byte 0 on each retry.
231 resume: boolean,
232 onProgress?: (progress: PinnedRuntimeProgress) => void,
233 headers?: Readonly<Record<string, string>>,
234) {
235 // Bytes from earlier attempts outlive the retry so a stalled download resumes with Range.
236 let chunks: Array<Uint8Array> = [];
237 let received = 0;
238 // Bound stalls while holding the install lock, but allow transfers that keep
239 // receiving bytes to finish regardless of their total duration.
240 return yield* Effect.suspend(() => {
241 if (!resume) {
242 chunks = [];
243 received = 0;
244 }
245 let request = HttpClientRequest.get(url);
246 if (headers !== undefined) {
247 request = HttpClientRequest.setHeaders(request, headers);
248 }
249 if (received > 0) {
250 request = HttpClientRequest.setHeader(request, "range", `bytes=${received}-`);
251 }
252 return httpClient.execute(request);
253 }).pipe(
254 // A resume answered 416 has nothing after the held bytes to send; the archive
255 // checksum decides whether they are the whole file.
256 Effect.filterOrElse(
257 (response) => received > 0 && response.status === 416,
258 HttpClientResponse.filterStatusOk,
259 ),
260 Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT),
261 Effect.flatMap(
262 Effect.fn(function* (response) {
263 if (response.status === 416) return concatChunks(chunks, received);
264 const contentRange =
265 response.status === 206
266 ? CONTENT_RANGE.exec(response.headers["content-range"] ?? "")
267 : null;
268 if (response.status === 206 && Number(contentRange?.[1]) !== received) {
269 chunks = [];
270 received = 0;
271 return yield* new HttpClientError.HttpClientError({
272 reason: new HttpClientError.DecodeError({
273 request: response.request,
274 response,
275 description: "partial content does not resume the bytes already received",
276 }),
277 });
278 }
279 if (contentRange === null) {
280 chunks = [];
281 received = 0;
282 }
283 const length = Number(
284 contentRange === null ? response.headers["content-length"] : contentRange[2],
285 );
286 const total = Number.isFinite(length) && length > 0 ? length : undefined;
287 onProgress?.({ stage: "download", received, total });
288 const attemptStart = received;
289 yield* response.stream.pipe(
290 Stream.timeoutOrElse({
291 duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT,
292 orElse: () => Stream.fail(new Cause.TimeoutError()),
293 }),
294 Stream.runForEach((chunk) =>
295 Effect.sync(() => {
296 chunks.push(chunk);
297 received += chunk.byteLength;
298 onProgress?.({ stage: "download", received, total });
299 }),
300 ),
301 );
302 // A server may end a 206 before the declared total; a retry asks for the rest.
303 if (
304 resume &&
305 contentRange !== null &&
306 total !== undefined &&
307 received > attemptStart &&
308 received < total
309 ) {
310 return yield* new HttpClientError.HttpClientError({
311 reason: new HttpClientError.DecodeError({
312 request: response.request,
313 response,
314 description: "partial content ended before the declared total",
315 }),
316 });
317 }
318 if (total === undefined && received > 0) {
319 onProgress?.({ stage: "download", received, total: received });
320 }
321 return concatChunks(chunks, received);
322 }),
323 ),
324 Effect.retry({ ...DOWNLOAD_RETRY, while: isTransientDownloadFailure }),
325 Effect.mapError(
326 (cause) =>
327 new PinnedRuntimeInstallError({
328 step: cause._tag === "TimeoutError" ? `${step} (timed out)` : step,
329 httpStatus:
330 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
331 ? cause.reason.response.status
332 : undefined,
333 downloadHost: URL.parse(
334 HttpClientError.isHttpClientError(cause) ? cause.request.url : url,
335 )?.host,
336 cause,
337 }),
338 ),
339 );
340});
341​
342const fetchNamedReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_named_release_asset")(
343 function* (
344 input: PinnedRuntimeInstallInput,
345 fileName: string,
346 step: string,
347 resume: boolean,
348 releaseAssets: ReadonlyMap<string, string> | undefined,
349 onProgress?: (progress: PinnedRuntimeProgress) => void,
350 ) {
351 if (releaseAssets !== undefined) {
352 const assetUrl = releaseAssets.get(fileName);
353 if (assetUrl === undefined) {
354 return yield* new PinnedRuntimeInstallError({
355 step: `finding ${fileName} in the t3 release assets`,
356 });
357 }
358 const headers: Record<string, string> = { Accept: "application/octet-stream" };
359 if (input.githubToken !== undefined && URL.parse(assetUrl)?.origin === GITHUB_API_ORIGIN) {
360 headers["Authorization"] = `Bearer ${input.githubToken}`;
361 }
362 return yield* fetchReleaseAsset(
363 input.httpClient,
364 assetUrl,
365 step,
366 resume,
367 onProgress,
368 headers,
369 );
370 }
371 return yield* fetchReleaseAsset(
372 input.httpClient,
373 cliReleaseAssetUrl(input.version, fileName, input.releaseBaseUrl),
374 step,
375 resume,
376 onProgress,
377 );
378 },
379);
380​
381const downloadArchive = Effect.fn("cloud.pinned_runtime.download_archive")(function* (
382 input: PinnedRuntimeInstallInput,
383) {
384 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
385 if (platformKey === undefined) {
386 return yield* new PinnedRuntimeInstallError({
387 step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
388 });
389 }
390 input.onProgress?.({ stage: "download", received: 0, total: undefined });
391 const { fileName, expected, releaseAssets } = yield* publishedArchive(input, platformKey);
392 const archive = yield* fetchNamedReleaseAsset(
393 input,
394 fileName,
395 "downloading the t3 release archive",
396 true,
397 releaseAssets,
398 input.onProgress,
399 );
400 input.onProgress?.({ stage: "verify" });
401 const digest = yield* Effect.tryPromise({
402 try: () => crypto.subtle.digest("SHA-256", archive),
403 catch: (cause) =>
404 new PinnedRuntimeInstallError({ step: "verifying the t3 release archive", cause }),
405 });
406 if (Hex.encode(new Uint8Array(digest)) !== expected) {
407 return yield* new PinnedRuntimeInstallError({
408 step: "verifying the t3 release archive checksum",
409 });
410 }
411 return archive;
412});
413​
414const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(function* (
415 input: PinnedRuntimeInstallInput,
416 stagingDir: string,
417 archive: Uint8Array,
418) {
419 const { fs, path } = input;
420 const archivePath = path.join(stagingDir, PINNED_RUNTIME_ARCHIVE_FILE);
421 yield* fs
422 .writeFile(archivePath, archive)
423 .pipe(
424 Effect.mapError(
425 (cause) => new PinnedRuntimeInstallError({ step: "writing the t3 release archive", cause }),
426 ),
427 );
428 input.onProgress?.({ stage: "extract" });
429 const extractStep = "extracting the t3 release archive";
430 // Strip the archive's stem directory so the executable lands at <versionDir>/t3.
431 yield* input.runner
432 .run({
433 command: cliArchiveTarCommand(input.platform, process.env),
434 args: ["-xf", archivePath, "-C", stagingDir, "--strip-components=1"],
435 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
436 })
437 .pipe(
438 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: extractStep, cause })),
439 Effect.filterOrFail(
440 (result) => result.code === 0,
441 (result) =>
442 new PinnedRuntimeInstallError({
443 step: extractStep,
444 exitCode: Number(result.code),
445 stdoutLength: result.stdout.length,
446 stderrLength: result.stderr.length,
447 }),
448 ),
449 );
450 yield* fs.remove(archivePath, { force: true }).pipe(Effect.ignore);
451});
452​
453/** The release's archive for this machine and its checksum; fails when the release lists none. */
454const publishedArchive = Effect.fn("cloud.pinned_runtime.published_archive")(function* (
455 input: PinnedRuntimeInstallInput,
456 platformKey: CliArchivePlatformKey,
457) {
458 const fileName = cliArchiveFileName(input.version, platformKey);
459 const canUseGithubApi = input.releaseBaseUrl === undefined && input.githubToken !== undefined;
460 let releaseAssets: ReadonlyMap<string, string> | undefined;
461 const fetchChecksumsFromApi = Effect.gen(function* () {
462 releaseAssets = yield* resolveGithubReleaseAssets(
463 input.httpClient,
464 input.version,
465 input.githubToken!,
466 );
467 return yield* fetchNamedReleaseAsset(
468 input,
469 CLI_RELEASE_CHECKSUMS_FILE,
470 "downloading the t3 release checksums",
471 false,
472 releaseAssets,
473 );
474 });
475 // Preview releases stay GitHub drafts, so their public download URLs always 404.
476 const checksumsBytes =
477 canUseGithubApi && cliReleaseChannelOf(input.version) === "preview"
478 ? yield* fetchChecksumsFromApi
479 : yield* fetchNamedReleaseAsset(
480 input,
481 CLI_RELEASE_CHECKSUMS_FILE,
482 "downloading the t3 release checksums",
483 false,
484 undefined,
485 ).pipe(
486 Effect.catchIf(
487 (error) => canUseGithubApi && isUnpublishedRelease(error),
488 () => fetchChecksumsFromApi,
489 ),
490 );
491 const checksums = parseChecksums(new TextDecoder().decode(checksumsBytes));
492 const expected = checksums.get(fileName);
493 if (expected === undefined) {
494 return yield* new PinnedRuntimeInstallError({
495 step: `finding ${fileName} in the t3 release checksums`,
496 });
497 }
498 return { fileName, expected, releaseAssets };
499});
500​
501const isPinnedRuntimeInstallError = Schema.is(PinnedRuntimeInstallError);
502​
503/** Whether an install failed because the release source does not publish the version for this machine. */
504export const isUnpublishedRelease = (error: unknown): error is PinnedRuntimeInstallError =>
505 isPinnedRuntimeInstallError(error) &&
506 (error.step.startsWith("finding ") ||
507 (error.step.startsWith("downloading the t3 release") &&
508 HttpClientError.isHttpClientError(error.cause) &&
509 error.cause.response?.status === 404));
510​
511const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
512 input: PinnedRuntimeInstallInput,
513) {
514 const { fs } = input;
515 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version, input.platform);
516 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
517 fs.exists(paths.versionDir),
518 fs.exists(paths.entryPath),
519 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
520 ]).pipe(
521 Effect.mapError(
522 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
523 ),
524 );
525 const alreadyPinned =
526 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
527 if (alreadyPinned) {
528 if (input.requirePublishedRelease === true) {
529 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
530 if (platformKey === undefined) {
531 return yield* new PinnedRuntimeInstallError({
532 step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
533 });
534 }
535 yield* publishedArchive(input, platformKey);
536 }
537 input.onProgress?.({ stage: "cached" });
538 yield* input.validate(paths);
539 return paths;
540 }
541 if (versionDirExists) {
542 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
543 Effect.mapError(
544 (cause) =>
545 new PinnedRuntimeInstallError({
546 step: "removing an incomplete pinned runtime",
547 cause,
548 }),
549 ),
550 );
551 }
552​
553 const versionsDir = input.path.dirname(paths.versionDir);
554 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
555 Effect.mapError(
556 (cause) =>
557 new PinnedRuntimeInstallError({
558 step: "preparing the pinned runtime directory",
559 cause,
560 }),
561 ),
562 );
563 // Downloads are buffered in memory and can take hours; staging only once they finish keeps a
564 // staging directory's age a sign of abandonment for prunes in other processes.
565 const archive = yield* downloadArchive(input);
566 const stagingDir = yield* fs
567 .makeTempDirectory({
568 directory: versionsDir,
569 prefix: PINNED_RUNTIME_STAGING_PREFIX,
570 })
571 .pipe(
572 Effect.mapError(
573 (cause) =>
574 new PinnedRuntimeInstallError({
575 step: "preparing the pinned runtime directory",
576 cause,
577 }),
578 ),
579 );
580 const stagingPaths: PinnedRuntimePaths = {
581 versionDir: stagingDir,
582 entryPath: input.path.join(stagingDir, input.path.relative(paths.versionDir, paths.entryPath)),
583 sentinelPath: input.path.join(stagingDir, ".install-complete"),
584 };
585​
586 return yield* Effect.gen(function* () {
587 yield* installFromArchive(input, stagingDir, archive);
588​
589 input.onProgress?.({ stage: "validate" });
590 yield* input.validate(stagingPaths);
591 yield* fs
592 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
593 .pipe(
594 Effect.mapError(
595 (cause) =>
596 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
597 ),
598 );
599 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
600 Effect.as(true),
601 Effect.catch((cause) =>
602 Effect.all([
603 fs.exists(paths.entryPath),
604 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
605 ]).pipe(
606 Effect.mapError(
607 (checkCause) =>
608 new PinnedRuntimeInstallError({
609 step: "checking a concurrently published pinned runtime",
610 cause: checkCause,
611 }),
612 ),
613 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
614 publishedEntryExists &&
615 Option.isSome(publishedSentinel) &&
616 publishedSentinel.value.trim() === input.version
617 ? Effect.succeed(false)
618 : Effect.fail(
619 new PinnedRuntimeInstallError({
620 step: "publishing the pinned runtime",
621 cause,
622 }),
623 ),
624 ),
625 ),
626 ),
627 );
628 if (!published) yield* input.validate(paths);
629 return paths;
630 }).pipe(
631 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
632 );
633});
634​
635export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
636 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));
637​
638const PINNED_RUNTIME_STAGING_PREFIX = ".staging-";
639const PINNED_RUNTIME_PRUNED_PREFIX = ".pruned-";
640/**
641 * Another process may have just published a runtime it has not yet pointed anything at: an
642 * update, a downgrade, or the install script between unpacking and linking. The install lock only
643 * covers this process, so recently completed runtimes are left for a later prune.
644 */
645const PINNED_RUNTIME_PRUNE_GRACE = Duration.hours(1);
646/**
647 * One `t3` launcher path per line, appended by the install scripts and by any prune that finds a
648 * launcher on PATH. A service does not see the installer's `T3CODE_INSTALL_BIN_DIR` or the
649 * interactive PATH, so this is how it finds a custom one, including installs that predate the file.
650 */
651const PINNED_RUNTIME_LAUNCHERS_FILE = "launchers";
652​
653/**
654 * Starts on a fresh line whatever the file ends with when the append lands: another process's
655 * append may have been cut short since this one read the file. Readers skip the blank lines.
656 */
657const launcherRecords = (launchers: ReadonlyArray<string>) =>
658 `\n${launchers.map((launcher) => `${launcher}\n`).join("")}`;
659​
660export function launcherOwnsVersionsDir(
661 path: Path.Path,
662 versionsDir: string,
663 candidate: string,
664): boolean {
665 const relative = path.relative(versionsDir, path.resolve(candidate));
666 return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
668​
669/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */
670export const resolveLauncherPath = Effect.gen(function* () {
671 const path = yield* Path.Path;
672 const fs = yield* FileSystem.FileSystem;
673 const invokedAs = yield* HostProcess.InvokedAs;
674 const cwd = yield* HostProcess.WorkingDirectory;
675 const environment = yield* HostProcess.Environment;
676 const platform = yield* HostProcess.Platform;
677 if (invokedAs.includes("/") || invokedAs.includes("\\")) {
678 return path.resolve(cwd, invokedAs);
679 }
680 const delimiter = platform === "win32" ? ";" : ":";
681 const searchPath = environment["PATH"] ?? "";
682 for (const directory of searchPath.split(delimiter)) {
683 // POSIX shells search the working directory for an empty entry of a nonempty PATH.
684 if (directory.length === 0 && (platform === "win32" || searchPath.length === 0)) continue;
685 const candidate = path.resolve(cwd, directory || ".", invokedAs);
686 const info = yield* fs.stat(candidate).pipe(Effect.option);
687 // Like the shell, pass over directories and non-executable files named the same.
688 if (
689 Option.isSome(info) &&
690 info.value.type === "File" &&
691 (platform === "win32" || (info.value.mode & 0o111) !== 0)
692 ) {
693 return candidate;
694 }
695 }
696 return undefined;
697});
698​
699/**
700 * `t3 update` repoints the launcher it was started through, which may be on neither PATH nor the
701 * default bin dir. Unrecorded, the next prune would remove the runtime it now points at.
702 */
703export const recordPinnedRuntimeLauncher = Effect.fn("cloud.pinned_runtime.record_launcher")(
704 function* (input: { readonly baseDir: string; readonly launcher: string }) {
705 const fs = yield* FileSystem.FileSystem;
706 const path = yield* Path.Path;
707 const launchersFile = path.join(
708 input.baseDir,
709 PINNED_RUNTIME_DIR,
710 PINNED_RUNTIME_LAUNCHERS_FILE,
711 );
712 // Prune may run in another process, such as the service, whose working directory differs.
713 const launcher = path.resolve(input.launcher);
714 const recorded = yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => ""));
715 if (recorded.split(/\r?\n/).includes(launcher)) return;
716 yield* fs.writeFileString(launchersFile, launcherRecords([launcher]), { flag: "a" });
717 },
718);
719​
720/** Whether `candidate` is a version's own executable, `<versionsDir>/<version>/t3[.exe]`. */
721export function isVersionExecutable(
722 path: Path.Path,
723 versionsDir: string,
724 candidate: string,
725): boolean {
726 const relative = path.relative(versionsDir, path.resolve(candidate));
727 // On another Windows drive, relative() returns the absolute path, like `D:\t3.exe`.
728 return !path.isAbsolute(relative) && /^(?!\.\.)[^\\/]+[\\/]t3(?:\.exe)?$/i.test(relative);
730​
731/** The executable a `t3.cmd` shim written by the install script or `t3 update` runs. */
732export const windowsShimTarget = (contents: string) => /^"([^"]+)"/m.exec(contents)?.[1];
733​
734/** Like {@link windowsShimTarget}, but only for a shim exactly as written; never a user's wrapper. */
735export const generatedWindowsShimTarget = (contents: string) =>
736 /^@echo off\r?\n"([^"]+)" %\*\s*$/.exec(contents)?.[1];
737​
738/**
739 * The `t3` script the install scripts and `t3 update` write on macOS and Linux. Exec by absolute
740 * path: through a symlink, argv0 is the link, and the Cursor SDK looks for its helpers beside it.
741 */
742export const posixLauncherScript = (executable: string) =>
743 `#!/bin/sh\nexec '${executable.replaceAll("'", "'\\''")}' "$@"\n`;
744​
745/** The executable a script exactly as {@link posixLauncherScript} writes it runs; never a user's wrapper. */
746export const readPosixLauncherTarget = Effect.fn("cloud.pinned_runtime.read_posix_launcher")(
747 function* (launcher: string) {
748 const fs = yield* FileSystem.FileSystem;
749 // Stat first so a runtime binary found the same way is never read whole.
750 const info = yield* fs.stat(launcher).pipe(Effect.option);
751 if (Option.isNone(info) || info.value.type !== "File" || info.value.size > 4096n) {
752 return undefined;
753 }
754 const contents = yield* fs.readFileString(launcher).pipe(Effect.option);
755 if (Option.isNone(contents)) return undefined;
756 const quoted = /^#!\/bin\/sh\nexec '((?:[^']|'\\'')*)' "\$@"\n$/.exec(contents.value)?.[1];
757 return quoted?.replaceAll("'\\''", "'");
758 },
759);
760​
761/**
762 * The `t3` this executable was started through on macOS or Linux: a legacy symlink into this
763 * home's runtime/versions, or, since a script execs the executable and argv0 names it, an unedited
764 * {@link posixLauncherScript} that runs it.
765 */
766export const findPosixLauncher = Effect.fn("cloud.pinned_runtime.find_posix_launcher")(
767 function* (input: { readonly launchedAs: string; readonly versionsDir: string }) {
768 const fs = yield* FileSystem.FileSystem;
769 const path = yield* Path.Path;
770 const environment = yield* HostProcess.Environment;
771 const linkTarget = yield* fs.readLink(input.launchedAs).pipe(Effect.option);
772 if (Option.isSome(linkTarget)) {
773 const resolved = path.resolve(path.dirname(input.launchedAs), linkTarget.value);
774 return isVersionExecutable(path, input.versionsDir, resolved) ? input.launchedAs : undefined;
775 }
776 const realPath = (file: string) =>
777 fs.realPath(file).pipe(Effect.orElseSucceed(() => undefined));
778 const executable = yield* realPath(input.launchedAs);
779 const realVersionsDir = yield* realPath(input.versionsDir);
780 if (
781 executable === undefined ||
782 realVersionsDir === undefined ||
783 !isVersionExecutable(path, realVersionsDir, executable)
784 ) {
785 return undefined;
786 }
787 const recorded = yield* fs
788 .readFileString(path.join(path.dirname(input.versionsDir), "launchers"))
789 .pipe(Effect.orElseSucceed(() => ""));
790 const cwd = yield* HostProcess.WorkingDirectory;
791 const searchPath = environment["PATH"] ?? "";
792 const candidates = [
793 // PATH first, resolved like the shell does: it decides which t3 the user runs. An empty
794 // entry of a nonempty PATH is the working directory; an empty PATH searches nothing.
795 ...(searchPath.length === 0 ? [] : searchPath.split(":")).map((directory) =>
796 path.resolve(cwd, directory || ".", "t3"),
797 ),
798 path.join(
799 environment["T3CODE_INSTALL_BIN_DIR"] ||
800 path.join(yield* HostProcess.HomeDirectory, ".local", "bin"),
801 "t3",
802 ),
803 ...recorded.split(/\r?\n/),
804 ].filter((candidate) => path.isAbsolute(candidate));
805 for (const candidate of candidates) {
806 // The script itself, so an alias that links to it keeps working.
807 const script = yield* realPath(candidate);
808 if (script === undefined) continue;
809 // Like the shell, pass over a script nobody can execute.
810 const info = yield* fs.stat(script).pipe(Effect.option);
811 if (Option.isNone(info) || (info.value.mode & 0o111) === 0) continue;
812 const target = yield* readPosixLauncherTarget(script);
813 if (target !== undefined && (yield* realPath(target)) === executable) return script;
814 }
815 return undefined;
816 },
817);
818​
819/** Writes {@link posixLauncherScript} at `launcher` in one rename, replacing a legacy symlink rather than writing through it. */
820export const writePosixLauncher = Effect.fn("cloud.pinned_runtime.write_posix_launcher")(
821 function* (input: {
822 readonly launcher: string;
823 readonly executable: string;
824 /** Fail instead of replacing a file that is there, even one created after the caller looked. */
825 readonly exclusive: boolean;
826 }) {
827 const fs = yield* FileSystem.FileSystem;
828 const path = yield* Path.Path;
829 const staging = yield* fs.makeTempFileScoped({
830 directory: path.dirname(input.launcher),
831 prefix: ".t3-",
832 });
833 yield* fs.writeFileString(staging, posixLauncherScript(input.executable));
834 yield* fs.chmod(staging, 0o755);
835 yield* input.exclusive ? fs.link(staging, input.launcher) : fs.rename(staging, input.launcher);
836 },
837 Effect.scoped,
838);
839​
840/** Where the `t3` launchers written by the install scripts and `t3 update` point. */
841const shellLauncherTargets = Effect.fn("cloud.pinned_runtime.shell_launcher_targets")(function* (
842 baseDir: string,
843) {
844 const fs = yield* FileSystem.FileSystem;
845 const path = yield* Path.Path;
846 const platform = yield* HostProcess.Platform;
847 const environment = yield* HostProcess.Environment;
848 const home = yield* HostProcess.HomeDirectory;
849 const launcherName = platform === "win32" ? "t3.cmd" : "t3";
850 const launchersFile = path.join(baseDir, PINNED_RUNTIME_DIR, PINNED_RUNTIME_LAUNCHERS_FILE);
851 const recorded = (yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => "")))
852 .split(/\r?\n/)
853 .filter((launcher) => launcher.trim().length > 0);
854 const found = [
855 environment["T3CODE_INSTALL_BIN_DIR"] || path.join(home, ".local", "bin"),
856 ...(environment["PATH"] ?? environment["Path"] ?? "").split(platform === "win32" ? ";" : ":"),
857 ]
858 .filter((directory) => path.isAbsolute(directory))
859 .map((directory) => path.join(directory, launcherName));
860 const versionsDir = pinnedRuntimeVersionsDir(path, baseDir);
861 const realVersionsDir = yield* fs
862 .realPath(versionsDir)
863 .pipe(Effect.orElseSucceed(() => versionsDir));
864 const inVersionsDir = (candidate: string) =>
865 launcherOwnsVersionsDir(path, versionsDir, candidate) ||
866 launcherOwnsVersionsDir(path, realVersionsDir, candidate);
867 const unrecorded: Array<string> = [];
868 const targets: Array<string> = [];
869 for (const launcher of [...recorded, ...found]) {
870 const resolved =
871 platform === "win32"
872 ? yield* fs.readFileString(launcher).pipe(
873 Effect.map(windowsShimTarget),
874 Effect.orElseSucceed(() => undefined),
875 )
876 : // Fully resolved, through chained links and a symlinked T3 home alike.
877 yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined));
878 if (resolved === undefined) continue;
879 const scriptTarget =
880 platform === "win32" ? undefined : yield* readPosixLauncherTarget(resolved);
881 const target =
882 scriptTarget === undefined
883 ? resolved
884 : yield* fs.realPath(scriptTarget).pipe(Effect.orElseSucceed(() => scriptTarget));
885 // A runtime's own entry, on the macOS service PATH or recorded by an earlier prune, is no launcher.
886 // It is named as `versions/<version>/t3`, and neither it nor its directory is a link.
887 const entryDir = path.dirname(path.resolve(launcher));
888 const parent = path.dirname(entryDir);
889 if (
890 platform !== "win32" &&
891 scriptTarget === undefined &&
892 (parent === versionsDir || parent === realVersionsDir) &&
893 target === path.join(realVersionsDir, path.basename(entryDir), path.basename(launcher))
894 ) {
895 continue;
896 }
897 targets.push(target);
898 if (inVersionsDir(target) && !recorded.includes(launcher) && !unrecorded.includes(launcher)) {
899 unrecorded.push(launcher);
900 }
901 }
902 if (unrecorded.length > 0) {
903 yield* fs
904 .writeFileString(launchersFile, launcherRecords(unrecorded), { flag: "a" })
905 .pipe(Effect.ignore);
906 }
907 return targets;
908});
909​
910/**
911 * Resolved executables rather than command lines: a server started through the `t3` symlink
912 * shows up as `t3 serve`, possibly from another T3 home that runs this home's runtimes. Windows
913 * has no symlink launcher, and its `t3.cmd` shim runs the absolute path, so command lines do there.
914 */
915const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables")(function* () {
916 const fs = yield* FileSystem.FileSystem;
917 const runner = yield* ProcessRunner.ProcessRunner;
918 const platform = yield* HostProcess.Platform;
919 if (platform === "linux") {
920 const pids = yield* fs.readDirectory("/proc").pipe(Effect.option);
921 if (Option.isNone(pids)) return Option.none<string>();
922 const executables: Array<string> = [];
923 for (const pid of pids.value) {
924 if (!/^\d+$/.test(pid)) continue;
925 // Unreadable ones belong to other users or are this user's non-dumpable daemons (systemd
926 // --user, ssh-agent). Neither runs a t3 runtime, and bailing on them would never prune.
927 const executable = yield* fs.readLink(`/proc/${pid}/exe`).pipe(Effect.option);
928 if (Option.isSome(executable)) executables.push(executable.value);
929 }
930 return executables.length === 0 ? Option.none<string>() : Option.some(executables.join("\n"));
931 }
932 const result = yield* runner
933 .run({
934 ...(platform === "win32"
935 ? {
936 command: windowsPowerShellPath(yield* HostProcess.Environment),
937 args: [
938 "-NoProfile",
939 "-NonInteractive",
940 "-Command",
941 "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine",
942 ],
943 }
944 : { command: "lsof", args: ["-nP", "-w", "-d", "txt", "-F", "n"] }),
945 timeout: Duration.seconds(10),
946 maxOutputBytes: 16 * 1024 * 1024,
947 })
948 .pipe(Effect.option);
949 return Option.isSome(result) && result.value.code === 0 && result.value.stdout.length > 0
950 ? Option.some(result.value.stdout)
951 : Option.none<string>();
952});
953​
954const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(function* (input: {
955 readonly baseDir: string;
956 readonly keep: ReadonlyArray<string>;
957 readonly references: ReadonlyArray<string>;
958}) {
959 const fs = yield* FileSystem.FileSystem;
960 const path = yield* Path.Path;
961 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
962 const entries = yield* fs.readDirectory(versionsDir).pipe(Effect.orElseSucceed(() => []));
963 // An interrupted prune has already renamed its runtime out of the way.
964 const pruned = new Set(
965 entries
966 .filter((entry) => entry.startsWith(PINNED_RUNTIME_PRUNED_PREFIX))
967 .map((entry) => path.join(versionsDir, entry)),
968 );
969​
970 const settledBefore =
971 (yield* Clock.currentTimeMillis) - Duration.toMillis(PINNED_RUNTIME_PRUNE_GRACE);
972 const completed: Array<string> = [];
973 for (const version of entries) {
974 if (version.startsWith(PINNED_RUNTIME_STAGING_PREFIX)) {
975 // A crashed or interrupted install leaves its staging directory behind.
976 const stagingDir = path.join(versionsDir, version);
977 const modifiedAt = yield* fs.stat(stagingDir).pipe(
978 Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
979 Effect.orElseSucceed(() => undefined),
980 );
981 if (modifiedAt !== undefined && modifiedAt < settledBefore) pruned.add(stagingDir);
982 continue;
983 }
984 if (!isExactServiceVersion(version)) continue;
985 const versionDir = path.join(versionsDir, version);
986 const sentinelPath = path.join(versionDir, ".install-complete");
987 const isLink = yield* fs.readLink(versionDir).pipe(Effect.isSuccess);
988 const sentinel = yield* fs.readFileString(sentinelPath).pipe(Effect.option);
989 const completedAt = yield* fs.stat(sentinelPath).pipe(
990 Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
991 Effect.orElseSucceed(() => undefined),
992 );
993 if (
994 !isLink &&
995 Option.isSome(sentinel) &&
996 sentinel.value.trim() === version &&
997 completedAt !== undefined &&
998 completedAt < settledBefore
999 ) {
1000 completed.push(version);
1003 if (completed.length === 0) return pruned;
1004​
1005 const keep = new Set(input.keep);
1006 const stateText = yield* fs
1007 .readFileString(path.join(input.baseDir, PINNED_RUNTIME_DIR, SERVICE_STATE_FILE))
1008 .pipe(
1009 Effect.asSome,
1010 Effect.catch((error) =>
1011 Effect.succeed(error.reason._tag === "NotFound" ? Option.none<string>() : undefined),
1012 ),
1013 );
1014 // State this version cannot read may reference runtimes in ways it does not know.
1015 if (stateText === undefined) return pruned;
1016 if (Option.isSome(stateText)) {
1017 const state = parseServiceState(stateText.value);
1018 if (state === undefined) return pruned;
1019 keep.add(state.activeVersion);
1020 if (state.update !== undefined) {
1021 // A committed update never returns to the runtime it replaced.
1022 if (state.update.status !== "committed") keep.add(state.update.fromVersion);
1023 keep.add(state.update.targetVersion);
1026 const executables = yield* runningExecutables();
1027 // Without a process list, a runtime in use would look unused.
1028 if (Option.isNone(executables)) return pruned;
1029 const platform = yield* HostProcess.Platform;
1030 // Windows paths are case-insensitive, and shims and process lists need not agree on case.
1031 const foldCase = (value: string) => (platform === "win32" ? value.toLowerCase() : value);
1032 const references = [
1033 executables.value,
1034 ...(yield* shellLauncherTargets(input.baseDir)),
1035 ...input.references,
1036 ].map(foldCase);
1037 // Process executables are resolved, so they name the real path of a symlinked T3 home.
1038 const realVersionsDir = yield* fs
1039 .realPath(versionsDir)
1040 .pipe(Effect.orElseSucceed(() => versionsDir));
1041​
1042 for (const version of completed) {
1043 const versionDir = path.join(versionsDir, version);
1044 const prefixes = [versionDir, path.join(realVersionsDir, version)].map((dir) =>
1045 foldCase(dir + path.sep),
1046 );
1047 if (
1048 keep.has(version) ||
1049 references.some((reference) => prefixes.some((prefix) => reference.includes(prefix)))
1050 ) {
1051 continue;
1053 const target = path.join(versionsDir, `${PINNED_RUNTIME_PRUNED_PREFIX}${version}`);
1054 // Renaming first means an interrupted removal never leaves a partial tree that still carries
1055 // its sentinel and would pass for a complete install.
1056 yield* fs.remove(target, { recursive: true, force: true }).pipe(
1057 Effect.andThen(fs.rename(versionDir, target)),
1058 Effect.andThen(Effect.sync(() => pruned.add(target))),
1059 Effect.catch((cause) =>
1060 Effect.logWarning("Could not remove an unused t3 runtime.", { version, cause }),
1061 ),
1062 );
1064 return pruned;
1065});
1066​
1067/**
1068 * Keep runtimes named by callers, service state, running processes, launchers, or references,
1069 * and anything published within an hour. Only prune completed runtimes and staging directories
1070 * untouched for an hour; leave symlinks and unexpected entries untouched.
1071 */
1072export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(function* (input: {
1073 readonly baseDir: string;
1074 readonly keep: ReadonlyArray<string>;
1075 readonly references?: ReadonlyArray<string>;
1076}) {
1077 const fs = yield* FileSystem.FileSystem;
1078 const path = yield* Path.Path;
1079 // Only selection and the renames race an install; deleting renamed trees can take a while.
1080 const pruned = yield* pinnedRuntimeInstallLock.withPermit(
1081 selectUnusedRuntimes({ ...input, references: input.references ?? [] }),
1082 );
1083 const removed: Array<string> = [];
1084 for (const target of pruned) {
1085 const name = path.basename(target);
1086 yield* fs.remove(target, { recursive: true, force: true }).pipe(
1087 Effect.andThen(
1088 Effect.sync(() => {
1089 if (name.startsWith(PINNED_RUNTIME_PRUNED_PREFIX)) {
1090 removed.push(name.slice(PINNED_RUNTIME_PRUNED_PREFIX.length));
1092 }),
1093 ),
1094 Effect.catch((cause) =>
1095 Effect.logWarning("Could not remove an unused t3 runtime.", { target, cause }),
1096 ),
1097 );
1099 return removed;
1100});