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

pinnedRuntime.ts

624 lines22.9 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 Stream from "effect/Stream";
11import * as Semaphore from "effect/Semaphore";
12import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
13​
14import {
15 CLI_RELEASE_CHECKSUMS_FILE,
16 cliArchiveFileName,
17 cliArchivePlatformKey,
18 cliArchiveTarCommand,
19 cliReleaseDownloadBaseUrl,
20 parseChecksums,
21} from "@t3tools/shared/cliRelease";
22​
23import * as HostProcess from "@t3tools/shared/HostProcess";
24​
25import * as ProcessRunner from "../processRunner.ts";
26import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts";
27​
28const PINNED_RUNTIME_DIR = "runtime";
29const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
30const PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT = Duration.minutes(1);
31const PINNED_RUNTIME_ARCHIVE_FILE = "t3-runtime-archive";
32// Separate layers share one install lock across this process.
33const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
34​
35export interface PinnedRuntimePaths {
36 readonly versionDir: string;
37 readonly entryPath: string;
38 readonly sentinelPath: string;
40​
41export function pinnedRuntimeCommand(paths: PinnedRuntimePaths): {
42 readonly command: string;
43 readonly args: ReadonlyArray<string>;
44} {
45 return { command: paths.entryPath, args: [] };
47​
48export function pinnedRuntimeVersionsDir(path: Path.Path, baseDir: string): string {
49 return path.join(baseDir, PINNED_RUNTIME_DIR, "versions");
51​
52export function pinnedRuntimePaths(
53 path: Path.Path,
54 baseDir: string,
55 version: string,
56 platform: NodeJS.Platform,
57): PinnedRuntimePaths {
58 const versionDir = path.join(pinnedRuntimeVersionsDir(path, baseDir), version);
59 return {
60 versionDir,
61 entryPath: path.join(versionDir, platform === "win32" ? "t3.exe" : "t3"),
62 sentinelPath: path.join(versionDir, ".install-complete"),
63 };
65​
66export class PinnedRuntimeInstallError extends Schema.TaggedError<PinnedRuntimeInstallError>()(
67 "PinnedRuntimeInstallError",
68 {
69 step: Schema.String,
70 exitCode: Schema.optional(Schema.Number),
71 stdoutLength: Schema.optional(Schema.Number),
72 stderrLength: Schema.optional(Schema.Number),
73 cause: Schema.optional(Schema.Defect()),
74 },
75) {
76 override get message(): string {
77 return this.exitCode === undefined
78 ? `Pinned runtime install failed while ${this.step}.`
79 : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
80 }
82​
83export class PinnedRuntimePreflightBlockedError extends Schema.TaggedError<PinnedRuntimePreflightBlockedError>()(
84 "PinnedRuntimePreflightBlockedError",
85 {
86 version: Schema.String,
87 reason: Schema.String,
88 },
89) {
90 override get message(): string {
91 return this.reason;
92 }
94​
95export type PinnedRuntimeProgress =
96 | { readonly stage: "download"; readonly received: number; readonly total: number | undefined }
97 | { readonly stage: "verify" | "extract" | "validate" | "cached" };
98​
99/** Tar writes the executable before native packages; only a validated install gets a sentinel. */
100​
101interface PinnedRuntimeInstallInput {
102 readonly baseDir: string;
103 readonly version: string;
104 readonly fs: FileSystem.FileSystem;
105 readonly path: Path.Path;
106 readonly runner: ProcessRunner.ProcessRunner["Service"];
107 readonly validate: (
108 paths: PinnedRuntimePaths,
109 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
110 readonly platform: NodeJS.Platform;
111 readonly arch: string;
112 readonly httpClient: HttpClient.HttpClient;
113 readonly releaseBaseUrl?: string | undefined;
114 readonly onProgress?: (progress: PinnedRuntimeProgress) => void;
116​
117const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* (
118 httpClient: HttpClient.HttpClient,
119 url: string,
120 step: string,
121 onProgress?: (progress: PinnedRuntimeProgress) => void,
122) {
123 // Bound stalls while holding the install lock, but allow transfers that keep
124 // receiving bytes to finish regardless of their total duration.
125 return yield* httpClient.execute(HttpClientRequest.get(url)).pipe(
126 Effect.flatMap(HttpClientResponse.filterStatusOk),
127 Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT),
128 Effect.flatMap(
129 Effect.fn(function* (response) {
130 const length = Number(response.headers["content-length"]);
131 const total = Number.isFinite(length) && length > 0 ? length : undefined;
132 let received = 0;
133 onProgress?.({ stage: "download", received, total });
134 const chunks = yield* response.stream.pipe(
135 Stream.timeoutOrElse({
136 duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT,
137 orElse: () => Stream.fail(new Cause.TimeoutError()),
138 }),
139 Stream.tap((chunk) =>
140 Effect.sync(() => {
141 received += chunk.byteLength;
142 onProgress?.({ stage: "download", received, total });
143 }),
144 ),
145 Stream.runCollect,
146 );
147 if (total === undefined && received > 0) {
148 onProgress?.({ stage: "download", received, total: received });
149 }
150 const bytes = new Uint8Array(received);
151 let offset = 0;
152 for (const chunk of chunks) {
153 bytes.set(chunk, offset);
154 offset += chunk.byteLength;
155 }
156 return bytes;
157 }),
158 ),
159 Effect.mapError(
160 (cause) =>
161 new PinnedRuntimeInstallError({
162 step: cause._tag === "TimeoutError" ? `${step} (timed out)` : step,
163 cause,
164 }),
165 ),
166 );
167});
168​
169const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(function* (
170 input: PinnedRuntimeInstallInput,
171 stagingDir: string,
172) {
173 const { fs, path } = input;
174 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
175 if (platformKey === undefined) {
176 return yield* new PinnedRuntimeInstallError({
177 step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
178 });
179 }
180 const httpClient = input.httpClient;
181 const baseUrl = cliReleaseDownloadBaseUrl(input.version, input.releaseBaseUrl);
182 const fileName = cliArchiveFileName(input.version, platformKey);
183​
184 input.onProgress?.({ stage: "download", received: 0, total: undefined });
185 const checksums = parseChecksums(
186 new TextDecoder().decode(
187 yield* fetchReleaseAsset(
188 httpClient,
189 `${baseUrl}/${CLI_RELEASE_CHECKSUMS_FILE}`,
190 "downloading the t3 release checksums",
191 ),
192 ),
193 );
194 const expected = checksums.get(fileName);
195 if (expected === undefined) {
196 return yield* new PinnedRuntimeInstallError({
197 step: `finding ${fileName} in the t3 release checksums`,
198 });
199 }
200 const archive = yield* fetchReleaseAsset(
201 httpClient,
202 `${baseUrl}/${fileName}`,
203 "downloading the t3 release archive",
204 input.onProgress,
205 );
206 input.onProgress?.({ stage: "verify" });
207 const digest = yield* Effect.tryPromise({
208 try: () => crypto.subtle.digest("SHA-256", archive),
209 catch: (cause) =>
210 new PinnedRuntimeInstallError({ step: "verifying the t3 release archive", cause }),
211 });
212 if (Hex.encode(new Uint8Array(digest)) !== expected) {
213 return yield* new PinnedRuntimeInstallError({
214 step: "verifying the t3 release archive checksum",
215 });
216 }
217​
218 const archivePath = path.join(stagingDir, PINNED_RUNTIME_ARCHIVE_FILE);
219 yield* fs
220 .writeFile(archivePath, archive)
221 .pipe(
222 Effect.mapError(
223 (cause) => new PinnedRuntimeInstallError({ step: "writing the t3 release archive", cause }),
224 ),
225 );
226 input.onProgress?.({ stage: "extract" });
227 const extractStep = "extracting the t3 release archive";
228 // Strip the archive's stem directory so the executable lands at <versionDir>/t3.
229 yield* input.runner
230 .run({
231 command: cliArchiveTarCommand(input.platform, process.env),
232 args: ["-xf", archivePath, "-C", stagingDir, "--strip-components=1"],
233 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
234 })
235 .pipe(
236 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: extractStep, cause })),
237 Effect.filterOrFail(
238 (result) => result.code === 0,
239 (result) =>
240 new PinnedRuntimeInstallError({
241 step: extractStep,
242 exitCode: Number(result.code),
243 stdoutLength: result.stdout.length,
244 stderrLength: result.stderr.length,
245 }),
246 ),
247 );
248 yield* fs.remove(archivePath, { force: true }).pipe(Effect.ignore);
249});
250​
251const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
252 input: PinnedRuntimeInstallInput,
253) {
254 const { fs } = input;
255 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version, input.platform);
256 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
257 fs.exists(paths.versionDir),
258 fs.exists(paths.entryPath),
259 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
260 ]).pipe(
261 Effect.mapError(
262 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
263 ),
264 );
265 const alreadyPinned =
266 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
267 if (alreadyPinned) {
268 input.onProgress?.({ stage: "cached" });
269 yield* input.validate(paths);
270 return paths;
271 }
272 if (versionDirExists) {
273 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
274 Effect.mapError(
275 (cause) =>
276 new PinnedRuntimeInstallError({
277 step: "removing an incomplete pinned runtime",
278 cause,
279 }),
280 ),
281 );
282 }
283​
284 const versionsDir = input.path.dirname(paths.versionDir);
285 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
286 Effect.mapError(
287 (cause) =>
288 new PinnedRuntimeInstallError({
289 step: "preparing the pinned runtime directory",
290 cause,
291 }),
292 ),
293 );
294 const stagingDir = yield* fs
295 .makeTempDirectory({
296 directory: versionsDir,
297 prefix: ".staging-",
298 })
299 .pipe(
300 Effect.mapError(
301 (cause) =>
302 new PinnedRuntimeInstallError({
303 step: "preparing the pinned runtime directory",
304 cause,
305 }),
306 ),
307 );
308 const stagingPaths: PinnedRuntimePaths = {
309 versionDir: stagingDir,
310 entryPath: input.path.join(stagingDir, input.path.relative(paths.versionDir, paths.entryPath)),
311 sentinelPath: input.path.join(stagingDir, ".install-complete"),
312 };
313​
314 return yield* Effect.gen(function* () {
315 yield* installFromArchive(input, stagingDir);
316​
317 input.onProgress?.({ stage: "validate" });
318 yield* input.validate(stagingPaths);
319 yield* fs
320 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
321 .pipe(
322 Effect.mapError(
323 (cause) =>
324 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
325 ),
326 );
327 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
328 Effect.as(true),
329 Effect.catch((cause) =>
330 Effect.all([
331 fs.exists(paths.entryPath),
332 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
333 ]).pipe(
334 Effect.mapError(
335 (checkCause) =>
336 new PinnedRuntimeInstallError({
337 step: "checking a concurrently published pinned runtime",
338 cause: checkCause,
339 }),
340 ),
341 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
342 publishedEntryExists &&
343 Option.isSome(publishedSentinel) &&
344 publishedSentinel.value.trim() === input.version
345 ? Effect.succeed(false)
346 : Effect.fail(
347 new PinnedRuntimeInstallError({
348 step: "publishing the pinned runtime",
349 cause,
350 }),
351 ),
352 ),
353 ),
354 ),
355 );
356 if (!published) yield* input.validate(paths);
357 return paths;
358 }).pipe(
359 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
360 );
361});
362​
363export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
364 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));
365​
366const PINNED_RUNTIME_PRUNED_PREFIX = ".pruned-";
367/**
368 * Another process may have just published a runtime it has not yet pointed anything at: an
369 * update, a downgrade, or the install script between unpacking and linking. The install lock only
370 * covers this process, so recently completed runtimes are left for a later prune.
371 */
372const PINNED_RUNTIME_PRUNE_GRACE = Duration.hours(1);
373/**
374 * One `t3` launcher path per line, appended by the install scripts and by any prune that finds a
375 * launcher on PATH. A service does not see the installer's `T3CODE_INSTALL_BIN_DIR` or the
376 * interactive PATH, so this is how it finds a custom one, including installs that predate the file.
377 */
378const PINNED_RUNTIME_LAUNCHERS_FILE = "launchers";
379​
380export function launcherOwnsVersionsDir(
381 path: Path.Path,
382 versionsDir: string,
383 candidate: string,
384): boolean {
385 const relative = path.relative(versionsDir, path.resolve(candidate));
386 return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
388​
389/** The executable a `t3.cmd` shim written by the install script or `t3 update` runs. */
390export const windowsShimTarget = (contents: string) => /^"([^"]+)"/m.exec(contents)?.[1];
391​
392/** Where the `t3` launchers written by the install scripts and `t3 update` point. */
393const shellLauncherTargets = Effect.fn("cloud.pinned_runtime.shell_launcher_targets")(function* (
394 baseDir: string,
395) {
396 const fs = yield* FileSystem.FileSystem;
397 const path = yield* Path.Path;
398 const platform = yield* HostProcess.Platform;
399 const environment = yield* HostProcess.Environment;
400 const home = yield* HostProcess.HomeDirectory;
401 const launcherName = platform === "win32" ? "t3.cmd" : "t3";
402 const launchersFile = path.join(baseDir, PINNED_RUNTIME_DIR, PINNED_RUNTIME_LAUNCHERS_FILE);
403 const recorded = (yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => "")))
404 .split(/\r?\n/)
405 .filter((launcher) => launcher.trim().length > 0);
406 const found = [
407 environment["T3CODE_INSTALL_BIN_DIR"] || path.join(home, ".local", "bin"),
408 ...(environment["PATH"] ?? environment["Path"] ?? "").split(platform === "win32" ? ";" : ":"),
409 ]
410 .filter((directory) => path.isAbsolute(directory))
411 .map((directory) => path.join(directory, launcherName));
412 const versionsDir = pinnedRuntimeVersionsDir(path, baseDir);
413 const realVersionsDir = yield* fs
414 .realPath(versionsDir)
415 .pipe(Effect.orElseSucceed(() => versionsDir));
416 const unrecorded: Array<string> = [];
417 const targets: Array<string> = [];
418 for (const launcher of [...recorded, ...found]) {
419 const target =
420 platform === "win32"
421 ? yield* fs.readFileString(launcher).pipe(
422 Effect.map(windowsShimTarget),
423 Effect.orElseSucceed(() => undefined),
424 )
425 : // Fully resolved, through chained links and a symlinked T3 home alike.
426 yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined));
427 if (target === undefined) continue;
428 targets.push(target);
429 if (
430 (launcherOwnsVersionsDir(path, versionsDir, target) ||
431 launcherOwnsVersionsDir(path, realVersionsDir, target)) &&
432 !recorded.includes(launcher) &&
433 !unrecorded.includes(launcher)
434 ) {
435 unrecorded.push(launcher);
436 }
437 }
438 if (unrecorded.length > 0) {
439 yield* fs
440 .writeFileString(launchersFile, unrecorded.map((launcher) => `${launcher}\n`).join(""), {
441 flag: "a",
442 })
443 .pipe(Effect.ignore);
444 }
445 return targets;
446});
447​
448/**
449 * Resolved executables rather than command lines: a server started through the `t3` symlink
450 * shows up as `t3 serve`, possibly from another T3 home that runs this home's runtimes. Windows
451 * has no symlink launcher, and its `t3.cmd` shim runs the absolute path, so command lines do there.
452 */
453const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables")(function* () {
454 const fs = yield* FileSystem.FileSystem;
455 const runner = yield* ProcessRunner.ProcessRunner;
456 const platform = yield* HostProcess.Platform;
457 if (platform === "linux") {
458 const pids = yield* fs.readDirectory("/proc").pipe(Effect.option);
459 if (Option.isNone(pids)) return Option.none<string>();
460 const executables: Array<string> = [];
461 for (const pid of pids.value) {
462 if (!/^\d+$/.test(pid)) continue;
463 // Unreadable ones belong to other users or are this user's non-dumpable daemons (systemd
464 // --user, ssh-agent). Neither runs a t3 runtime, and bailing on them would never prune.
465 const executable = yield* fs.readLink(`/proc/${pid}/exe`).pipe(Effect.option);
466 if (Option.isSome(executable)) executables.push(executable.value);
467 }
468 return executables.length === 0 ? Option.none<string>() : Option.some(executables.join("\n"));
469 }
470 const result = yield* runner
471 .run({
472 ...(platform === "win32"
473 ? {
474 command: "powershell.exe",
475 args: [
476 "-NoProfile",
477 "-NonInteractive",
478 "-Command",
479 "Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine",
480 ],
481 }
482 : { command: "lsof", args: ["-nP", "-w", "-d", "txt", "-F", "n"] }),
483 timeout: Duration.seconds(10),
484 maxOutputBytes: 16 * 1024 * 1024,
485 })
486 .pipe(Effect.option);
487 return Option.isSome(result) && result.value.code === 0 && result.value.stdout.length > 0
488 ? Option.some(result.value.stdout)
489 : Option.none<string>();
490});
491​
492const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(function* (input: {
493 readonly baseDir: string;
494 readonly keep: ReadonlyArray<string>;
495 readonly references: ReadonlyArray<string>;
496}) {
497 const fs = yield* FileSystem.FileSystem;
498 const path = yield* Path.Path;
499 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
500 const entries = yield* fs.readDirectory(versionsDir).pipe(Effect.orElseSucceed(() => []));
501 // An interrupted prune has already renamed its runtime out of the way.
502 const pruned = new Set(
503 entries
504 .filter((entry) => entry.startsWith(PINNED_RUNTIME_PRUNED_PREFIX))
505 .map((entry) => path.join(versionsDir, entry)),
506 );
507​
508 const settledBefore =
509 (yield* Clock.currentTimeMillis) - Duration.toMillis(PINNED_RUNTIME_PRUNE_GRACE);
510 const completed: Array<string> = [];
511 for (const version of entries) {
512 if (!isExactServiceVersion(version)) continue;
513 const versionDir = path.join(versionsDir, version);
514 const sentinelPath = path.join(versionDir, ".install-complete");
515 const isLink = yield* fs.readLink(versionDir).pipe(Effect.isSuccess);
516 const sentinel = yield* fs.readFileString(sentinelPath).pipe(Effect.option);
517 const completedAt = yield* fs.stat(sentinelPath).pipe(
518 Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
519 Effect.orElseSucceed(() => undefined),
520 );
521 if (
522 !isLink &&
523 Option.isSome(sentinel) &&
524 sentinel.value.trim() === version &&
525 completedAt !== undefined &&
526 completedAt < settledBefore
527 ) {
528 completed.push(version);
529 }
530 }
531 if (completed.length === 0) return pruned;
532​
533 const keep = new Set(input.keep);
534 const stateText = yield* fs
535 .readFileString(path.join(input.baseDir, PINNED_RUNTIME_DIR, SERVICE_STATE_FILE))
536 .pipe(
537 Effect.asSome,
538 Effect.catch((error) =>
539 Effect.succeed(error.reason._tag === "NotFound" ? Option.none<string>() : undefined),
540 ),
541 );
542 // State this version cannot read may reference runtimes in ways it does not know.
543 if (stateText === undefined) return pruned;
544 if (Option.isSome(stateText)) {
545 const state = parseServiceState(stateText.value);
546 if (state === undefined) return pruned;
547 keep.add(state.activeVersion);
548 if (state.update !== undefined) {
549 keep.add(state.update.fromVersion);
550 keep.add(state.update.targetVersion);
551 }
552 }
553 const executables = yield* runningExecutables();
554 // Without a process list, a runtime in use would look unused.
555 if (Option.isNone(executables)) return pruned;
556 const platform = yield* HostProcess.Platform;
557 // Windows paths are case-insensitive, and shims and process lists need not agree on case.
558 const foldCase = (value: string) => (platform === "win32" ? value.toLowerCase() : value);
559 const references = [
560 executables.value,
561 ...(yield* shellLauncherTargets(input.baseDir)),
562 ...input.references,
563 ].map(foldCase);
564 // Process executables are resolved, so they name the real path of a symlinked T3 home.
565 const realVersionsDir = yield* fs
566 .realPath(versionsDir)
567 .pipe(Effect.orElseSucceed(() => versionsDir));
568​
569 for (const version of completed) {
570 const versionDir = path.join(versionsDir, version);
571 const prefixes = [versionDir, path.join(realVersionsDir, version)].map((dir) =>
572 foldCase(dir + path.sep),
573 );
574 if (
575 keep.has(version) ||
576 references.some((reference) => prefixes.some((prefix) => reference.includes(prefix)))
577 ) {
578 continue;
579 }
580 const target = path.join(versionsDir, `${PINNED_RUNTIME_PRUNED_PREFIX}${version}`);
581 // Renaming first means an interrupted removal never leaves a partial tree that still carries
582 // its sentinel and would pass for a complete install.
583 yield* fs.remove(target, { recursive: true, force: true }).pipe(
584 Effect.andThen(fs.rename(versionDir, target)),
585 Effect.andThen(Effect.sync(() => pruned.add(target))),
586 Effect.catch((cause) =>
587 Effect.logWarning("Could not remove an unused t3 runtime.", { version, cause }),
588 ),
589 );
590 }
591 return pruned;
592});
593​
594/**
595 * Keep runtimes named by callers, service state, running processes, launchers, or references,
596 * and anything published within an hour. Only prune completed runtimes; leave staging
597 * directories, symlinks, and unexpected entries untouched.
598 */
599export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(function* (input: {
600 readonly baseDir: string;
601 readonly keep: ReadonlyArray<string>;
602 readonly references?: ReadonlyArray<string>;
603}) {
604 const fs = yield* FileSystem.FileSystem;
605 const path = yield* Path.Path;
606 // Only selection and the renames race an install; deleting renamed trees can take a while.
607 const pruned = yield* pinnedRuntimeInstallLock.withPermit(
608 selectUnusedRuntimes({ ...input, references: input.references ?? [] }),
609 );
610 const removed: Array<string> = [];
611 for (const target of pruned) {
612 yield* fs.remove(target, { recursive: true, force: true }).pipe(
613 Effect.andThen(
614 Effect.sync(() =>
615 removed.push(path.basename(target).slice(PINNED_RUNTIME_PRUNED_PREFIX.length)),
616 ),
617 ),
618 Effect.catch((cause) =>
619 Effect.logWarning("Could not remove an unused t3 runtime.", { target, cause }),
620 ),
621 );
622 }
623 return removed;
624});