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

pinnedRuntime.ts

650 lines24.1 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​
380/**
381 * Starts on a fresh line whatever the file ends with when the append lands: another process's
382 * append may have been cut short since this one read the file. Readers skip the blank lines.
383 */
384const launcherRecords = (launchers: ReadonlyArray<string>) =>
385 `\n${launchers.map((launcher) => `${launcher}\n`).join("")}`;
386​
387export function launcherOwnsVersionsDir(
388 path: Path.Path,
389 versionsDir: string,
390 candidate: string,
391): boolean {
392 const relative = path.relative(versionsDir, path.resolve(candidate));
393 return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
395​
396/**
397 * `t3 update` repoints the launcher it was started through, which may be on neither PATH nor the
398 * default bin dir. Unrecorded, the next prune would remove the runtime it now points at.
399 */
400export const recordPinnedRuntimeLauncher = Effect.fn("cloud.pinned_runtime.record_launcher")(
401 function* (input: { readonly baseDir: string; readonly launcher: string }) {
402 const fs = yield* FileSystem.FileSystem;
403 const path = yield* Path.Path;
404 const launchersFile = path.join(
405 input.baseDir,
406 PINNED_RUNTIME_DIR,
407 PINNED_RUNTIME_LAUNCHERS_FILE,
408 );
409 // Prune may run in another process, such as the service, whose working directory differs.
410 const launcher = path.resolve(input.launcher);
411 const recorded = yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => ""));
412 if (recorded.split(/\r?\n/).includes(launcher)) return;
413 yield* fs.writeFileString(launchersFile, launcherRecords([launcher]), { flag: "a" });
414 },
415);
416​
417/** The executable a `t3.cmd` shim written by the install script or `t3 update` runs. */
418export const windowsShimTarget = (contents: string) => /^"([^"]+)"/m.exec(contents)?.[1];
419​
420/** Where the `t3` launchers written by the install scripts and `t3 update` point. */
421const shellLauncherTargets = Effect.fn("cloud.pinned_runtime.shell_launcher_targets")(function* (
422 baseDir: string,
423) {
424 const fs = yield* FileSystem.FileSystem;
425 const path = yield* Path.Path;
426 const platform = yield* HostProcess.Platform;
427 const environment = yield* HostProcess.Environment;
428 const home = yield* HostProcess.HomeDirectory;
429 const launcherName = platform === "win32" ? "t3.cmd" : "t3";
430 const launchersFile = path.join(baseDir, PINNED_RUNTIME_DIR, PINNED_RUNTIME_LAUNCHERS_FILE);
431 const recorded = (yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => "")))
432 .split(/\r?\n/)
433 .filter((launcher) => launcher.trim().length > 0);
434 const found = [
435 environment["T3CODE_INSTALL_BIN_DIR"] || path.join(home, ".local", "bin"),
436 ...(environment["PATH"] ?? environment["Path"] ?? "").split(platform === "win32" ? ";" : ":"),
437 ]
438 .filter((directory) => path.isAbsolute(directory))
439 .map((directory) => path.join(directory, launcherName));
440 const versionsDir = pinnedRuntimeVersionsDir(path, baseDir);
441 const realVersionsDir = yield* fs
442 .realPath(versionsDir)
443 .pipe(Effect.orElseSucceed(() => versionsDir));
444 const unrecorded: Array<string> = [];
445 const targets: Array<string> = [];
446 for (const launcher of [...recorded, ...found]) {
447 const target =
448 platform === "win32"
449 ? yield* fs.readFileString(launcher).pipe(
450 Effect.map(windowsShimTarget),
451 Effect.orElseSucceed(() => undefined),
452 )
453 : // Fully resolved, through chained links and a symlinked T3 home alike.
454 yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined));
455 if (target === undefined) continue;
456 targets.push(target);
457 if (
458 (launcherOwnsVersionsDir(path, versionsDir, target) ||
459 launcherOwnsVersionsDir(path, realVersionsDir, target)) &&
460 !recorded.includes(launcher) &&
461 !unrecorded.includes(launcher)
462 ) {
463 unrecorded.push(launcher);
464 }
465 }
466 if (unrecorded.length > 0) {
467 yield* fs
468 .writeFileString(launchersFile, launcherRecords(unrecorded), { flag: "a" })
469 .pipe(Effect.ignore);
470 }
471 return targets;
472});
473​
474/**
475 * Resolved executables rather than command lines: a server started through the `t3` symlink
476 * shows up as `t3 serve`, possibly from another T3 home that runs this home's runtimes. Windows
477 * has no symlink launcher, and its `t3.cmd` shim runs the absolute path, so command lines do there.
478 */
479const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables")(function* () {
480 const fs = yield* FileSystem.FileSystem;
481 const runner = yield* ProcessRunner.ProcessRunner;
482 const platform = yield* HostProcess.Platform;
483 if (platform === "linux") {
484 const pids = yield* fs.readDirectory("/proc").pipe(Effect.option);
485 if (Option.isNone(pids)) return Option.none<string>();
486 const executables: Array<string> = [];
487 for (const pid of pids.value) {
488 if (!/^\d+$/.test(pid)) continue;
489 // Unreadable ones belong to other users or are this user's non-dumpable daemons (systemd
490 // --user, ssh-agent). Neither runs a t3 runtime, and bailing on them would never prune.
491 const executable = yield* fs.readLink(`/proc/${pid}/exe`).pipe(Effect.option);
492 if (Option.isSome(executable)) executables.push(executable.value);
493 }
494 return executables.length === 0 ? Option.none<string>() : Option.some(executables.join("\n"));
495 }
496 const result = yield* runner
497 .run({
498 ...(platform === "win32"
499 ? {
500 command: "powershell.exe",
501 args: [
502 "-NoProfile",
503 "-NonInteractive",
504 "-Command",
505 "Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine",
506 ],
507 }
508 : { command: "lsof", args: ["-nP", "-w", "-d", "txt", "-F", "n"] }),
509 timeout: Duration.seconds(10),
510 maxOutputBytes: 16 * 1024 * 1024,
511 })
512 .pipe(Effect.option);
513 return Option.isSome(result) && result.value.code === 0 && result.value.stdout.length > 0
514 ? Option.some(result.value.stdout)
515 : Option.none<string>();
516});
517​
518const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(function* (input: {
519 readonly baseDir: string;
520 readonly keep: ReadonlyArray<string>;
521 readonly references: ReadonlyArray<string>;
522}) {
523 const fs = yield* FileSystem.FileSystem;
524 const path = yield* Path.Path;
525 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
526 const entries = yield* fs.readDirectory(versionsDir).pipe(Effect.orElseSucceed(() => []));
527 // An interrupted prune has already renamed its runtime out of the way.
528 const pruned = new Set(
529 entries
530 .filter((entry) => entry.startsWith(PINNED_RUNTIME_PRUNED_PREFIX))
531 .map((entry) => path.join(versionsDir, entry)),
532 );
533​
534 const settledBefore =
535 (yield* Clock.currentTimeMillis) - Duration.toMillis(PINNED_RUNTIME_PRUNE_GRACE);
536 const completed: Array<string> = [];
537 for (const version of entries) {
538 if (!isExactServiceVersion(version)) continue;
539 const versionDir = path.join(versionsDir, version);
540 const sentinelPath = path.join(versionDir, ".install-complete");
541 const isLink = yield* fs.readLink(versionDir).pipe(Effect.isSuccess);
542 const sentinel = yield* fs.readFileString(sentinelPath).pipe(Effect.option);
543 const completedAt = yield* fs.stat(sentinelPath).pipe(
544 Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
545 Effect.orElseSucceed(() => undefined),
546 );
547 if (
548 !isLink &&
549 Option.isSome(sentinel) &&
550 sentinel.value.trim() === version &&
551 completedAt !== undefined &&
552 completedAt < settledBefore
553 ) {
554 completed.push(version);
555 }
556 }
557 if (completed.length === 0) return pruned;
558​
559 const keep = new Set(input.keep);
560 const stateText = yield* fs
561 .readFileString(path.join(input.baseDir, PINNED_RUNTIME_DIR, SERVICE_STATE_FILE))
562 .pipe(
563 Effect.asSome,
564 Effect.catch((error) =>
565 Effect.succeed(error.reason._tag === "NotFound" ? Option.none<string>() : undefined),
566 ),
567 );
568 // State this version cannot read may reference runtimes in ways it does not know.
569 if (stateText === undefined) return pruned;
570 if (Option.isSome(stateText)) {
571 const state = parseServiceState(stateText.value);
572 if (state === undefined) return pruned;
573 keep.add(state.activeVersion);
574 if (state.update !== undefined) {
575 keep.add(state.update.fromVersion);
576 keep.add(state.update.targetVersion);
577 }
578 }
579 const executables = yield* runningExecutables();
580 // Without a process list, a runtime in use would look unused.
581 if (Option.isNone(executables)) return pruned;
582 const platform = yield* HostProcess.Platform;
583 // Windows paths are case-insensitive, and shims and process lists need not agree on case.
584 const foldCase = (value: string) => (platform === "win32" ? value.toLowerCase() : value);
585 const references = [
586 executables.value,
587 ...(yield* shellLauncherTargets(input.baseDir)),
588 ...input.references,
589 ].map(foldCase);
590 // Process executables are resolved, so they name the real path of a symlinked T3 home.
591 const realVersionsDir = yield* fs
592 .realPath(versionsDir)
593 .pipe(Effect.orElseSucceed(() => versionsDir));
594​
595 for (const version of completed) {
596 const versionDir = path.join(versionsDir, version);
597 const prefixes = [versionDir, path.join(realVersionsDir, version)].map((dir) =>
598 foldCase(dir + path.sep),
599 );
600 if (
601 keep.has(version) ||
602 references.some((reference) => prefixes.some((prefix) => reference.includes(prefix)))
603 ) {
604 continue;
605 }
606 const target = path.join(versionsDir, `${PINNED_RUNTIME_PRUNED_PREFIX}${version}`);
607 // Renaming first means an interrupted removal never leaves a partial tree that still carries
608 // its sentinel and would pass for a complete install.
609 yield* fs.remove(target, { recursive: true, force: true }).pipe(
610 Effect.andThen(fs.rename(versionDir, target)),
611 Effect.andThen(Effect.sync(() => pruned.add(target))),
612 Effect.catch((cause) =>
613 Effect.logWarning("Could not remove an unused t3 runtime.", { version, cause }),
614 ),
615 );
616 }
617 return pruned;
618});
619​
620/**
621 * Keep runtimes named by callers, service state, running processes, launchers, or references,
622 * and anything published within an hour. Only prune completed runtimes; leave staging
623 * directories, symlinks, and unexpected entries untouched.
624 */
625export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(function* (input: {
626 readonly baseDir: string;
627 readonly keep: ReadonlyArray<string>;
628 readonly references?: ReadonlyArray<string>;
629}) {
630 const fs = yield* FileSystem.FileSystem;
631 const path = yield* Path.Path;
632 // Only selection and the renames race an install; deleting renamed trees can take a while.
633 const pruned = yield* pinnedRuntimeInstallLock.withPermit(
634 selectUnusedRuntimes({ ...input, references: input.references ?? [] }),
635 );
636 const removed: Array<string> = [];
637 for (const target of pruned) {
638 yield* fs.remove(target, { recursive: true, force: true }).pipe(
639 Effect.andThen(
640 Effect.sync(() =>
641 removed.push(path.basename(target).slice(PINNED_RUNTIME_PRUNED_PREFIX.length)),
642 ),
643 ),
644 Effect.catch((cause) =>
645 Effect.logWarning("Could not remove an unused t3 runtime.", { target, cause }),
646 ),
647 );
648 }
649 return removed;
650});