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

pinnedRuntime.ts

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