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

pinnedRuntime.ts

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