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