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 Schedule from "effect/Schedule";
11import * as Stream from "effect/Stream";
12import * as Semaphore from "effect/Semaphore";
13import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
14
15import {
16 CLI_RELEASE_CHECKSUMS_FILE,
17 cliArchiveFileName,
18 cliArchivePlatformKey,
19 cliArchiveTarCommand,
20 cliReleaseAssetUrl,
21 type CliArchivePlatformKey,
22 parseChecksums,
23} from "@t3tools/shared/cliRelease";
24
25import * as HostProcess from "@t3tools/shared/HostProcess";
26
27import * as ProcessRunner from "../processRunner.ts";
28import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts";
29
30const PINNED_RUNTIME_DIR = "runtime";
31const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
32const PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT = Duration.minutes(1);
33const PINNED_RUNTIME_ARCHIVE_FILE = "t3-runtime-archive";
34// Separate layers share one install lock across this process.
35const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
36
37export interface PinnedRuntimePaths {
38 readonly versionDir: string;
39 readonly entryPath: string;
40 readonly sentinelPath: string;
41}
42
43export function pinnedRuntimeCommand(paths: PinnedRuntimePaths): {
44 readonly command: string;
45 readonly args: ReadonlyArray<string>;
46} {
47 return { command: paths.entryPath, args: [] };
48}
49
50export function pinnedRuntimeVersionsDir(path: Path.Path, baseDir: string): string {
51 return path.join(baseDir, PINNED_RUNTIME_DIR, "versions");
52}
53
54export function pinnedRuntimePaths(
55 path: Path.Path,
56 baseDir: string,
57 version: string,
58 platform: NodeJS.Platform,
59): PinnedRuntimePaths {
60 const versionDir = path.join(pinnedRuntimeVersionsDir(path, baseDir), version);
61 return {
62 versionDir,
63 entryPath: path.join(versionDir, platform === "win32" ? "t3.exe" : "t3"),
64 sentinelPath: path.join(versionDir, ".install-complete"),
65 };
66}
67
68export class PinnedRuntimeInstallError extends Schema.TaggedError<PinnedRuntimeInstallError>()(
69 "PinnedRuntimeInstallError",
70 {
71 step: Schema.String,
72 exitCode: Schema.optional(Schema.Number),
73 stdoutLength: Schema.optional(Schema.Number),
74 stderrLength: Schema.optional(Schema.Number),
75 httpStatus: Schema.optional(Schema.Number),
76 downloadHost: Schema.optional(Schema.String),
77 cause: Schema.optional(Schema.Defect()),
78 },
79) {
80 override get message(): string {
81 return this.exitCode === undefined
82 ? `Pinned runtime install failed while ${this.step}.`
83 : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
84 }
85}
86
87export class PinnedRuntimePreflightBlockedError extends Schema.TaggedError<PinnedRuntimePreflightBlockedError>()(
88 "PinnedRuntimePreflightBlockedError",
89 {
90 version: Schema.String,
91 reason: Schema.String,
92 },
93) {
94 override get message(): string {
95 return this.reason;
96 }
97}
98
99export type PinnedRuntimeProgress =
100 | { readonly stage: "download"; readonly received: number; readonly total: number | undefined }
101 | { readonly stage: "verify" | "extract" | "validate" | "cached" };
102
103/** Tar writes the executable before native packages; only a validated install gets a sentinel. */
104
105interface PinnedRuntimeInstallInput {
106 readonly baseDir: string;
107 readonly version: string;
108 readonly fs: FileSystem.FileSystem;
109 readonly path: Path.Path;
110 readonly runner: ProcessRunner.ProcessRunner["Service"];
111 readonly validate: (
112 paths: PinnedRuntimePaths,
113 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
114 readonly platform: NodeJS.Platform;
115 readonly arch: string;
116 readonly httpClient: HttpClient.HttpClient;
117 readonly releaseBaseUrl?: string | undefined;
118 /** Reuse a cached runtime only while the release source still lists it, as a policy mirror does. */
119 readonly requirePublishedRelease?: boolean;
120 readonly onProgress?: (progress: PinnedRuntimeProgress) => void;
121}
122
123// GitHub release downloads intermittently answer 5xx during incidents; a retry usually lands.
124const DOWNLOAD_RETRY = { times: 3, schedule: Schedule.exponential("2 seconds") } as const;
125
126const isTransientDownloadFailure = (
127 error: HttpClientError.HttpClientError | Cause.TimeoutError,
128): boolean => {
129 // A slow link stalls past the bound and then recovers; the retry resumes from the bytes held.
130 if (error._tag === "TimeoutError") return true;
131 // Body bytes are read raw, so a DecodeError is a body that failed after the host answered.
132 if (error.reason._tag === "DecodeError") return true;
133 const status = error.response?.status;
134 return status !== undefined && (status >= 500 || status === 429 || status === 408);
135};
136
137const CONTENT_RANGE = /^bytes (\d+)-\d+\/(\d+|\*)$/;
138
139const concatChunks = (chunks: ReadonlyArray<Uint8Array>, length: number): Uint8Array => {
140 const bytes = new Uint8Array(length);
141 let offset = 0;
142 for (const chunk of chunks) {
143 bytes.set(chunk, offset);
144 offset += chunk.byteLength;
145 }
146 return bytes;
147};
148
149const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* (
150 httpClient: HttpClient.HttpClient,
151 url: string,
152 step: string,
153 // Only a digest-checked asset resumes; anything else restarts at byte 0 on each retry.
154 resume: boolean,
155 onProgress?: (progress: PinnedRuntimeProgress) => void,
156) {
157 // Bytes from earlier attempts outlive the retry so a stalled download resumes with Range.
158 let chunks: Array<Uint8Array> = [];
159 let received = 0;
160 // Bound stalls while holding the install lock, but allow transfers that keep
161 // receiving bytes to finish regardless of their total duration.
162 return yield* Effect.suspend(() => {
163 if (!resume) {
164 chunks = [];
165 received = 0;
166 }
167 return httpClient.execute(
168 received > 0
169 ? HttpClientRequest.get(url).pipe(
170 HttpClientRequest.setHeader("range", `bytes=${received}-`),
171 )
172 : HttpClientRequest.get(url),
173 );
174 }).pipe(
175 // A resume answered 416 has nothing after the held bytes to send; the archive
176 // checksum decides whether they are the whole file.
177 Effect.filterOrElse(
178 (response) => received > 0 && response.status === 416,
179 HttpClientResponse.filterStatusOk,
180 ),
181 Effect.timeout(PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT),
182 Effect.flatMap(
183 Effect.fn(function* (response) {
184 if (response.status === 416) return concatChunks(chunks, received);
185 const contentRange =
186 response.status === 206
187 ? CONTENT_RANGE.exec(response.headers["content-range"] ?? "")
188 : null;
189 if (response.status === 206 && Number(contentRange?.[1]) !== received) {
190 chunks = [];
191 received = 0;
192 return yield* new HttpClientError.HttpClientError({
193 reason: new HttpClientError.DecodeError({
194 request: response.request,
195 response,
196 description: "partial content does not resume the bytes already received",
197 }),
198 });
199 }
200 if (contentRange === null) {
201 chunks = [];
202 received = 0;
203 }
204 const length = Number(
205 contentRange === null ? response.headers["content-length"] : contentRange[2],
206 );
207 const total = Number.isFinite(length) && length > 0 ? length : undefined;
208 onProgress?.({ stage: "download", received, total });
209 const attemptStart = received;
210 yield* response.stream.pipe(
211 Stream.timeoutOrElse({
212 duration: PINNED_RUNTIME_DOWNLOAD_STALL_TIMEOUT,
213 orElse: () => Stream.fail(new Cause.TimeoutError()),
214 }),
215 Stream.runForEach((chunk) =>
216 Effect.sync(() => {
217 chunks.push(chunk);
218 received += chunk.byteLength;
219 onProgress?.({ stage: "download", received, total });
220 }),
221 ),
222 );
223 // A server may end a 206 before the declared total; a retry asks for the rest.
224 if (
225 resume &&
226 contentRange !== null &&
227 total !== undefined &&
228 received > attemptStart &&
229 received < total
230 ) {
231 return yield* new HttpClientError.HttpClientError({
232 reason: new HttpClientError.DecodeError({
233 request: response.request,
234 response,
235 description: "partial content ended before the declared total",
236 }),
237 });
238 }
239 if (total === undefined && received > 0) {
240 onProgress?.({ stage: "download", received, total: received });
241 }
242 return concatChunks(chunks, received);
243 }),
244 ),
245 Effect.retry({ ...DOWNLOAD_RETRY, while: isTransientDownloadFailure }),
246 Effect.mapError(
247 (cause) =>
248 new PinnedRuntimeInstallError({
249 step: cause._tag === "TimeoutError" ? `${step} (timed out)` : step,
250 httpStatus:
251 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
252 ? cause.reason.response.status
253 : undefined,
254 downloadHost: URL.parse(
255 HttpClientError.isHttpClientError(cause) ? cause.request.url : url,
256 )?.host,
257 cause,
258 }),
259 ),
260 );
261});
262
263const downloadArchive = Effect.fn("cloud.pinned_runtime.download_archive")(function* (
264 input: PinnedRuntimeInstallInput,
265) {
266 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
267 if (platformKey === undefined) {
268 return yield* new PinnedRuntimeInstallError({
269 step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
270 });
271 }
272 const httpClient = input.httpClient;
273 input.onProgress?.({ stage: "download", received: 0, total: undefined });
274 const { fileName, expected } = yield* publishedArchive(input, platformKey);
275 const archive = yield* fetchReleaseAsset(
276 httpClient,
277 cliReleaseAssetUrl(input.version, fileName, input.releaseBaseUrl),
278 "downloading the t3 release archive",
279 true,
280 input.onProgress,
281 );
282 input.onProgress?.({ stage: "verify" });
283 const digest = yield* Effect.tryPromise({
284 try: () => crypto.subtle.digest("SHA-256", archive),
285 catch: (cause) =>
286 new PinnedRuntimeInstallError({ step: "verifying the t3 release archive", cause }),
287 });
288 if (Hex.encode(new Uint8Array(digest)) !== expected) {
289 return yield* new PinnedRuntimeInstallError({
290 step: "verifying the t3 release archive checksum",
291 });
292 }
293 return archive;
294});
295
296const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(function* (
297 input: PinnedRuntimeInstallInput,
298 stagingDir: string,
299 archive: Uint8Array,
300) {
301 const { fs, path } = input;
302 const archivePath = path.join(stagingDir, PINNED_RUNTIME_ARCHIVE_FILE);
303 yield* fs
304 .writeFile(archivePath, archive)
305 .pipe(
306 Effect.mapError(
307 (cause) => new PinnedRuntimeInstallError({ step: "writing the t3 release archive", cause }),
308 ),
309 );
310 input.onProgress?.({ stage: "extract" });
311 const extractStep = "extracting the t3 release archive";
312 // Strip the archive's stem directory so the executable lands at <versionDir>/t3.
313 yield* input.runner
314 .run({
315 command: cliArchiveTarCommand(input.platform, process.env),
316 args: ["-xf", archivePath, "-C", stagingDir, "--strip-components=1"],
317 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
318 })
319 .pipe(
320 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: extractStep, cause })),
321 Effect.filterOrFail(
322 (result) => result.code === 0,
323 (result) =>
324 new PinnedRuntimeInstallError({
325 step: extractStep,
326 exitCode: Number(result.code),
327 stdoutLength: result.stdout.length,
328 stderrLength: result.stderr.length,
329 }),
330 ),
331 );
332 yield* fs.remove(archivePath, { force: true }).pipe(Effect.ignore);
333});
334
335/** The release's archive for this machine and its checksum; fails when the release lists none. */
336const publishedArchive = Effect.fn("cloud.pinned_runtime.published_archive")(function* (
337 input: PinnedRuntimeInstallInput,
338 platformKey: CliArchivePlatformKey,
339) {
340 const fileName = cliArchiveFileName(input.version, platformKey);
341 const checksums = parseChecksums(
342 new TextDecoder().decode(
343 yield* fetchReleaseAsset(
344 input.httpClient,
345 cliReleaseAssetUrl(input.version, CLI_RELEASE_CHECKSUMS_FILE, input.releaseBaseUrl),
346 "downloading the t3 release checksums",
347 false,
348 ),
349 ),
350 );
351 const expected = checksums.get(fileName);
352 if (expected === undefined) {
353 return yield* new PinnedRuntimeInstallError({
354 step: `finding ${fileName} in the t3 release checksums`,
355 });
356 }
357 return { fileName, expected };
358});
359
360const isPinnedRuntimeInstallError = Schema.is(PinnedRuntimeInstallError);
361
362/** Whether an install failed because the release source does not publish the version for this machine. */
363export const isUnpublishedRelease = (error: unknown): error is PinnedRuntimeInstallError =>
364 isPinnedRuntimeInstallError(error) &&
365 (error.step.startsWith("finding ") ||
366 (error.step.startsWith("downloading the t3 release") &&
367 HttpClientError.isHttpClientError(error.cause) &&
368 error.cause.response?.status === 404));
369
370const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
371 input: PinnedRuntimeInstallInput,
372) {
373 const { fs } = input;
374 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version, input.platform);
375 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
376 fs.exists(paths.versionDir),
377 fs.exists(paths.entryPath),
378 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
379 ]).pipe(
380 Effect.mapError(
381 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
382 ),
383 );
384 const alreadyPinned =
385 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
386 if (alreadyPinned) {
387 if (input.requirePublishedRelease === true) {
388 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
389 if (platformKey === undefined) {
390 return yield* new PinnedRuntimeInstallError({
391 step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
392 });
393 }
394 yield* publishedArchive(input, platformKey);
395 }
396 input.onProgress?.({ stage: "cached" });
397 yield* input.validate(paths);
398 return paths;
399 }
400 if (versionDirExists) {
401 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
402 Effect.mapError(
403 (cause) =>
404 new PinnedRuntimeInstallError({
405 step: "removing an incomplete pinned runtime",
406 cause,
407 }),
408 ),
409 );
410 }
411
412 const versionsDir = input.path.dirname(paths.versionDir);
413 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
414 Effect.mapError(
415 (cause) =>
416 new PinnedRuntimeInstallError({
417 step: "preparing the pinned runtime directory",
418 cause,
419 }),
420 ),
421 );
422 // Downloads are buffered in memory and can take hours; staging only once they finish keeps a
423 // staging directory's age a sign of abandonment for prunes in other processes.
424 const archive = yield* downloadArchive(input);
425 const stagingDir = yield* fs
426 .makeTempDirectory({
427 directory: versionsDir,
428 prefix: PINNED_RUNTIME_STAGING_PREFIX,
429 })
430 .pipe(
431 Effect.mapError(
432 (cause) =>
433 new PinnedRuntimeInstallError({
434 step: "preparing the pinned runtime directory",
435 cause,
436 }),
437 ),
438 );
439 const stagingPaths: PinnedRuntimePaths = {
440 versionDir: stagingDir,
441 entryPath: input.path.join(stagingDir, input.path.relative(paths.versionDir, paths.entryPath)),
442 sentinelPath: input.path.join(stagingDir, ".install-complete"),
443 };
444
445 return yield* Effect.gen(function* () {
446 yield* installFromArchive(input, stagingDir, archive);
447
448 input.onProgress?.({ stage: "validate" });
449 yield* input.validate(stagingPaths);
450 yield* fs
451 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
452 .pipe(
453 Effect.mapError(
454 (cause) =>
455 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
456 ),
457 );
458 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
459 Effect.as(true),
460 Effect.catch((cause) =>
461 Effect.all([
462 fs.exists(paths.entryPath),
463 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
464 ]).pipe(
465 Effect.mapError(
466 (checkCause) =>
467 new PinnedRuntimeInstallError({
468 step: "checking a concurrently published pinned runtime",
469 cause: checkCause,
470 }),
471 ),
472 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
473 publishedEntryExists &&
474 Option.isSome(publishedSentinel) &&
475 publishedSentinel.value.trim() === input.version
476 ? Effect.succeed(false)
477 : Effect.fail(
478 new PinnedRuntimeInstallError({
479 step: "publishing the pinned runtime",
480 cause,
481 }),
482 ),
483 ),
484 ),
485 ),
486 );
487 if (!published) yield* input.validate(paths);
488 return paths;
489 }).pipe(
490 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
491 );
492});
493
494export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
495 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));
496
497const PINNED_RUNTIME_STAGING_PREFIX = ".staging-";
498const PINNED_RUNTIME_PRUNED_PREFIX = ".pruned-";
499/**
500 * Another process may have just published a runtime it has not yet pointed anything at: an
501 * update, a downgrade, or the install script between unpacking and linking. The install lock only
502 * covers this process, so recently completed runtimes are left for a later prune.
503 */
504const PINNED_RUNTIME_PRUNE_GRACE = Duration.hours(1);
505/**
506 * One `t3` launcher path per line, appended by the install scripts and by any prune that finds a
507 * launcher on PATH. A service does not see the installer's `T3CODE_INSTALL_BIN_DIR` or the
508 * interactive PATH, so this is how it finds a custom one, including installs that predate the file.
509 */
510const PINNED_RUNTIME_LAUNCHERS_FILE = "launchers";
511
512/**
513 * Starts on a fresh line whatever the file ends with when the append lands: another process's
514 * append may have been cut short since this one read the file. Readers skip the blank lines.
515 */
516const launcherRecords = (launchers: ReadonlyArray<string>) =>
517 `\n${launchers.map((launcher) => `${launcher}\n`).join("")}`;
518
519export function launcherOwnsVersionsDir(
520 path: Path.Path,
521 versionsDir: string,
522 candidate: string,
523): boolean {
524 const relative = path.relative(versionsDir, path.resolve(candidate));
525 return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
526}
527
528/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */
529export const resolveLauncherPath = Effect.gen(function* () {
530 const path = yield* Path.Path;
531 const fs = yield* FileSystem.FileSystem;
532 const invokedAs = yield* HostProcess.InvokedAs;
533 const cwd = yield* HostProcess.WorkingDirectory;
534 const environment = yield* HostProcess.Environment;
535 const platform = yield* HostProcess.Platform;
536 if (invokedAs.includes("/") || invokedAs.includes("\\")) {
537 return path.resolve(cwd, invokedAs);
538 }
539 const delimiter = platform === "win32" ? ";" : ":";
540 for (const directory of (environment["PATH"] ?? "").split(delimiter)) {
541 if (directory.length === 0) continue;
542 const candidate = path.resolve(cwd, directory, invokedAs);
543 const info = yield* fs.stat(candidate).pipe(Effect.option);
544 // Like the shell, pass over directories and non-executable files named the same.
545 if (
546 Option.isSome(info) &&
547 info.value.type === "File" &&
548 (platform === "win32" || (info.value.mode & 0o111) !== 0)
549 ) {
550 return candidate;
551 }
552 }
553 return undefined;
554});
555
556/**
557 * `t3 update` repoints the launcher it was started through, which may be on neither PATH nor the
558 * default bin dir. Unrecorded, the next prune would remove the runtime it now points at.
559 */
560export const recordPinnedRuntimeLauncher = Effect.fn("cloud.pinned_runtime.record_launcher")(
561 function* (input: { readonly baseDir: string; readonly launcher: string }) {
562 const fs = yield* FileSystem.FileSystem;
563 const path = yield* Path.Path;
564 const launchersFile = path.join(
565 input.baseDir,
566 PINNED_RUNTIME_DIR,
567 PINNED_RUNTIME_LAUNCHERS_FILE,
568 );
569 // Prune may run in another process, such as the service, whose working directory differs.
570 const launcher = path.resolve(input.launcher);
571 const recorded = yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => ""));
572 if (recorded.split(/\r?\n/).includes(launcher)) return;
573 yield* fs.writeFileString(launchersFile, launcherRecords([launcher]), { flag: "a" });
574 },
575);
576
577/** Whether `candidate` is a version's own executable, `<versionsDir>/<version>/t3[.exe]`. */
578export function isVersionExecutable(
579 path: Path.Path,
580 versionsDir: string,
581 candidate: string,
582): boolean {
583 const relative = path.relative(versionsDir, path.resolve(candidate));
584 // On another Windows drive, relative() returns the absolute path, like `D:\t3.exe`.
585 return !path.isAbsolute(relative) && /^(?!\.\.)[^\\/]+[\\/]t3(?:\.exe)?$/i.test(relative);
586}
587
588/** The executable a `t3.cmd` shim written by the install script or `t3 update` runs. */
589export const windowsShimTarget = (contents: string) => /^"([^"]+)"/m.exec(contents)?.[1];
590
591/** Like {@link windowsShimTarget}, but only for a shim exactly as written; never a user's wrapper. */
592export const generatedWindowsShimTarget = (contents: string) =>
593 /^@echo off\r?\n"([^"]+)" %\*\s*$/.exec(contents)?.[1];
594
595/**
596 * The `t3` script the install scripts and `t3 update` write on macOS and Linux. Exec by absolute
597 * path: through a symlink, argv0 is the link, and the Cursor SDK looks for its helpers beside it.
598 */
599export const posixLauncherScript = (executable: string) =>
600 `#!/bin/sh\nexec '${executable.replaceAll("'", "'\\''")}' "$@"\n`;
601
602/** The executable a script exactly as {@link posixLauncherScript} writes it runs; never a user's wrapper. */
603export const readPosixLauncherTarget = Effect.fn("cloud.pinned_runtime.read_posix_launcher")(
604 function* (launcher: string) {
605 const fs = yield* FileSystem.FileSystem;
606 // Stat first so a runtime binary found the same way is never read whole.
607 const info = yield* fs.stat(launcher).pipe(Effect.option);
608 if (Option.isNone(info) || info.value.type !== "File" || info.value.size > 4096n) {
609 return undefined;
610 }
611 const contents = yield* fs.readFileString(launcher).pipe(Effect.option);
612 if (Option.isNone(contents)) return undefined;
613 const quoted = /^#!\/bin\/sh\nexec '((?:[^']|'\\'')*)' "\$@"\n$/.exec(contents.value)?.[1];
614 return quoted?.replaceAll("'\\''", "'");
615 },
616);
617
618/**
619 * The `t3` this executable was started through on macOS or Linux: a legacy symlink into this
620 * home's runtime/versions, or, since a script execs the executable and argv0 names it, an unedited
621 * {@link posixLauncherScript} that runs it.
622 */
623export const findPosixLauncher = Effect.fn("cloud.pinned_runtime.find_posix_launcher")(
624 function* (input: { readonly launchedAs: string; readonly versionsDir: string }) {
625 const fs = yield* FileSystem.FileSystem;
626 const path = yield* Path.Path;
627 const environment = yield* HostProcess.Environment;
628 const linkTarget = yield* fs.readLink(input.launchedAs).pipe(Effect.option);
629 if (Option.isSome(linkTarget)) {
630 const resolved = path.resolve(path.dirname(input.launchedAs), linkTarget.value);
631 return isVersionExecutable(path, input.versionsDir, resolved) ? input.launchedAs : undefined;
632 }
633 const realPath = (file: string) =>
634 fs.realPath(file).pipe(Effect.orElseSucceed(() => undefined));
635 const executable = yield* realPath(input.launchedAs);
636 const realVersionsDir = yield* realPath(input.versionsDir);
637 if (
638 executable === undefined ||
639 realVersionsDir === undefined ||
640 !isVersionExecutable(path, realVersionsDir, executable)
641 ) {
642 return undefined;
643 }
644 const recorded = yield* fs
645 .readFileString(path.join(path.dirname(input.versionsDir), "launchers"))
646 .pipe(Effect.orElseSucceed(() => ""));
647 const cwd = yield* HostProcess.WorkingDirectory;
648 const candidates = [
649 // PATH first, resolved like the shell does: it decides which t3 the user runs.
650 ...(environment["PATH"] ?? "")
651 .split(":")
652 .filter((directory) => directory.length > 0)
653 .map((directory) => path.resolve(cwd, directory, "t3")),
654 path.join(
655 environment["T3CODE_INSTALL_BIN_DIR"] ||
656 path.join(yield* HostProcess.HomeDirectory, ".local", "bin"),
657 "t3",
658 ),
659 ...recorded.split(/\r?\n/),
660 ].filter((candidate) => path.isAbsolute(candidate));
661 for (const candidate of candidates) {
662 // The script itself, so an alias that links to it keeps working.
663 const script = yield* realPath(candidate);
664 if (script === undefined) continue;
665 // Like the shell, pass over a script nobody can execute.
666 const info = yield* fs.stat(script).pipe(Effect.option);
667 if (Option.isNone(info) || (info.value.mode & 0o111) === 0) continue;
668 const target = yield* readPosixLauncherTarget(script);
669 if (target !== undefined && (yield* realPath(target)) === executable) return script;
670 }
671 return undefined;
672 },
673);
674
675/** Writes {@link posixLauncherScript} at `launcher` in one rename, replacing a legacy symlink rather than writing through it. */
676export const writePosixLauncher = Effect.fn("cloud.pinned_runtime.write_posix_launcher")(
677 function* (input: {
678 readonly launcher: string;
679 readonly executable: string;
680 /** Fail instead of replacing a file that is there, even one created after the caller looked. */
681 readonly exclusive: boolean;
682 }) {
683 const fs = yield* FileSystem.FileSystem;
684 const path = yield* Path.Path;
685 const staging = yield* fs.makeTempFileScoped({
686 directory: path.dirname(input.launcher),
687 prefix: ".t3-",
688 });
689 yield* fs.writeFileString(staging, posixLauncherScript(input.executable));
690 yield* fs.chmod(staging, 0o755);
691 yield* input.exclusive ? fs.link(staging, input.launcher) : fs.rename(staging, input.launcher);
692 },
693 Effect.scoped,
694);
695
696/** Where the `t3` launchers written by the install scripts and `t3 update` point. */
697const shellLauncherTargets = Effect.fn("cloud.pinned_runtime.shell_launcher_targets")(function* (
698 baseDir: string,
699) {
700 const fs = yield* FileSystem.FileSystem;
701 const path = yield* Path.Path;
702 const platform = yield* HostProcess.Platform;
703 const environment = yield* HostProcess.Environment;
704 const home = yield* HostProcess.HomeDirectory;
705 const launcherName = platform === "win32" ? "t3.cmd" : "t3";
706 const launchersFile = path.join(baseDir, PINNED_RUNTIME_DIR, PINNED_RUNTIME_LAUNCHERS_FILE);
707 const recorded = (yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => "")))
708 .split(/\r?\n/)
709 .filter((launcher) => launcher.trim().length > 0);
710 const found = [
711 environment["T3CODE_INSTALL_BIN_DIR"] || path.join(home, ".local", "bin"),
712 ...(environment["PATH"] ?? environment["Path"] ?? "").split(platform === "win32" ? ";" : ":"),
713 ]
714 .filter((directory) => path.isAbsolute(directory))
715 .map((directory) => path.join(directory, launcherName));
716 const versionsDir = pinnedRuntimeVersionsDir(path, baseDir);
717 const realVersionsDir = yield* fs
718 .realPath(versionsDir)
719 .pipe(Effect.orElseSucceed(() => versionsDir));
720 const inVersionsDir = (candidate: string) =>
721 launcherOwnsVersionsDir(path, versionsDir, candidate) ||
722 launcherOwnsVersionsDir(path, realVersionsDir, candidate);
723 const unrecorded: Array<string> = [];
724 const targets: Array<string> = [];
725 for (const launcher of [...recorded, ...found]) {
726 const resolved =
727 platform === "win32"
728 ? yield* fs.readFileString(launcher).pipe(
729 Effect.map(windowsShimTarget),
730 Effect.orElseSucceed(() => undefined),
731 )
732 : // Fully resolved, through chained links and a symlinked T3 home alike.
733 yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined));
734 if (resolved === undefined) continue;
735 const scriptTarget =
736 platform === "win32" ? undefined : yield* readPosixLauncherTarget(resolved);
737 const target =
738 scriptTarget === undefined
739 ? resolved
740 : yield* fs.realPath(scriptTarget).pipe(Effect.orElseSucceed(() => scriptTarget));
741 // A runtime's own entry, on the macOS service PATH or recorded by an earlier prune, is no launcher.
742 // It is named as `versions/<version>/t3`, and neither it nor its directory is a link.
743 const entryDir = path.dirname(path.resolve(launcher));
744 const parent = path.dirname(entryDir);
745 if (
746 platform !== "win32" &&
747 scriptTarget === undefined &&
748 (parent === versionsDir || parent === realVersionsDir) &&
749 target === path.join(realVersionsDir, path.basename(entryDir), path.basename(launcher))
750 ) {
751 continue;
752 }
753 targets.push(target);
754 if (inVersionsDir(target) && !recorded.includes(launcher) && !unrecorded.includes(launcher)) {
755 unrecorded.push(launcher);
756 }
757 }
758 if (unrecorded.length > 0) {
759 yield* fs
760 .writeFileString(launchersFile, launcherRecords(unrecorded), { flag: "a" })
761 .pipe(Effect.ignore);
762 }
763 return targets;
764});
765
766/**
767 * Resolved executables rather than command lines: a server started through the `t3` symlink
768 * shows up as `t3 serve`, possibly from another T3 home that runs this home's runtimes. Windows
769 * has no symlink launcher, and its `t3.cmd` shim runs the absolute path, so command lines do there.
770 */
771const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables")(function* () {
772 const fs = yield* FileSystem.FileSystem;
773 const runner = yield* ProcessRunner.ProcessRunner;
774 const platform = yield* HostProcess.Platform;
775 if (platform === "linux") {
776 const pids = yield* fs.readDirectory("/proc").pipe(Effect.option);
777 if (Option.isNone(pids)) return Option.none<string>();
778 const executables: Array<string> = [];
779 for (const pid of pids.value) {
780 if (!/^\d+$/.test(pid)) continue;
781 // Unreadable ones belong to other users or are this user's non-dumpable daemons (systemd
782 // --user, ssh-agent). Neither runs a t3 runtime, and bailing on them would never prune.
783 const executable = yield* fs.readLink(`/proc/${pid}/exe`).pipe(Effect.option);
784 if (Option.isSome(executable)) executables.push(executable.value);
785 }
786 return executables.length === 0 ? Option.none<string>() : Option.some(executables.join("\n"));
787 }
788 const result = yield* runner
789 .run({
790 ...(platform === "win32"
791 ? {
792 command: "powershell.exe",
793 args: [
794 "-NoProfile",
795 "-NonInteractive",
796 "-Command",
797 "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine",
798 ],
799 }
800 : { command: "lsof", args: ["-nP", "-w", "-d", "txt", "-F", "n"] }),
801 timeout: Duration.seconds(10),
802 maxOutputBytes: 16 * 1024 * 1024,
803 })
804 .pipe(Effect.option);
805 return Option.isSome(result) && result.value.code === 0 && result.value.stdout.length > 0
806 ? Option.some(result.value.stdout)
807 : Option.none<string>();
808});
809
810const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(function* (input: {
811 readonly baseDir: string;
812 readonly keep: ReadonlyArray<string>;
813 readonly references: ReadonlyArray<string>;
814}) {
815 const fs = yield* FileSystem.FileSystem;
816 const path = yield* Path.Path;
817 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
818 const entries = yield* fs.readDirectory(versionsDir).pipe(Effect.orElseSucceed(() => []));
819 // An interrupted prune has already renamed its runtime out of the way.
820 const pruned = new Set(
821 entries
822 .filter((entry) => entry.startsWith(PINNED_RUNTIME_PRUNED_PREFIX))
823 .map((entry) => path.join(versionsDir, entry)),
824 );
825
826 const settledBefore =
827 (yield* Clock.currentTimeMillis) - Duration.toMillis(PINNED_RUNTIME_PRUNE_GRACE);
828 const completed: Array<string> = [];
829 for (const version of entries) {
830 if (version.startsWith(PINNED_RUNTIME_STAGING_PREFIX)) {
831 // A crashed or interrupted install leaves its staging directory behind.
832 const stagingDir = path.join(versionsDir, version);
833 const modifiedAt = yield* fs.stat(stagingDir).pipe(
834 Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
835 Effect.orElseSucceed(() => undefined),
836 );
837 if (modifiedAt !== undefined && modifiedAt < settledBefore) pruned.add(stagingDir);
838 continue;
839 }
840 if (!isExactServiceVersion(version)) continue;
841 const versionDir = path.join(versionsDir, version);
842 const sentinelPath = path.join(versionDir, ".install-complete");
843 const isLink = yield* fs.readLink(versionDir).pipe(Effect.isSuccess);
844 const sentinel = yield* fs.readFileString(sentinelPath).pipe(Effect.option);
845 const completedAt = yield* fs.stat(sentinelPath).pipe(
846 Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
847 Effect.orElseSucceed(() => undefined),
848 );
849 if (
850 !isLink &&
851 Option.isSome(sentinel) &&
852 sentinel.value.trim() === version &&
853 completedAt !== undefined &&
854 completedAt < settledBefore
855 ) {
856 completed.push(version);
857 }
858 }
859 if (completed.length === 0) return pruned;
860
861 const keep = new Set(input.keep);
862 const stateText = yield* fs
863 .readFileString(path.join(input.baseDir, PINNED_RUNTIME_DIR, SERVICE_STATE_FILE))
864 .pipe(
865 Effect.asSome,
866 Effect.catch((error) =>
867 Effect.succeed(error.reason._tag === "NotFound" ? Option.none<string>() : undefined),
868 ),
869 );
870 // State this version cannot read may reference runtimes in ways it does not know.
871 if (stateText === undefined) return pruned;
872 if (Option.isSome(stateText)) {
873 const state = parseServiceState(stateText.value);
874 if (state === undefined) return pruned;
875 keep.add(state.activeVersion);
876 if (state.update !== undefined) {
877 // A committed update never returns to the runtime it replaced.
878 if (state.update.status !== "committed") keep.add(state.update.fromVersion);
879 keep.add(state.update.targetVersion);
880 }
881 }
882 const executables = yield* runningExecutables();
883 // Without a process list, a runtime in use would look unused.
884 if (Option.isNone(executables)) return pruned;
885 const platform = yield* HostProcess.Platform;
886 // Windows paths are case-insensitive, and shims and process lists need not agree on case.
887 const foldCase = (value: string) => (platform === "win32" ? value.toLowerCase() : value);
888 const references = [
889 executables.value,
890 ...(yield* shellLauncherTargets(input.baseDir)),
891 ...input.references,
892 ].map(foldCase);
893 // Process executables are resolved, so they name the real path of a symlinked T3 home.
894 const realVersionsDir = yield* fs
895 .realPath(versionsDir)
896 .pipe(Effect.orElseSucceed(() => versionsDir));
897
898 for (const version of completed) {
899 const versionDir = path.join(versionsDir, version);
900 const prefixes = [versionDir, path.join(realVersionsDir, version)].map((dir) =>
901 foldCase(dir + path.sep),
902 );
903 if (
904 keep.has(version) ||
905 references.some((reference) => prefixes.some((prefix) => reference.includes(prefix)))
906 ) {
907 continue;
908 }
909 const target = path.join(versionsDir, `${PINNED_RUNTIME_PRUNED_PREFIX}${version}`);
910 // Renaming first means an interrupted removal never leaves a partial tree that still carries
911 // its sentinel and would pass for a complete install.
912 yield* fs.remove(target, { recursive: true, force: true }).pipe(
913 Effect.andThen(fs.rename(versionDir, target)),
914 Effect.andThen(Effect.sync(() => pruned.add(target))),
915 Effect.catch((cause) =>
916 Effect.logWarning("Could not remove an unused t3 runtime.", { version, cause }),
917 ),
918 );
919 }
920 return pruned;
921});
922
923/**
924 * Keep runtimes named by callers, service state, running processes, launchers, or references,
925 * and anything published within an hour. Only prune completed runtimes and staging directories
926 * untouched for an hour; leave symlinks and unexpected entries untouched.
927 */
928export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(function* (input: {
929 readonly baseDir: string;
930 readonly keep: ReadonlyArray<string>;
931 readonly references?: ReadonlyArray<string>;
932}) {
933 const fs = yield* FileSystem.FileSystem;
934 const path = yield* Path.Path;
935 // Only selection and the renames race an install; deleting renamed trees can take a while.
936 const pruned = yield* pinnedRuntimeInstallLock.withPermit(
937 selectUnusedRuntimes({ ...input, references: input.references ?? [] }),
938 );
939 const removed: Array<string> = [];
940 for (const target of pruned) {
941 const name = path.basename(target);
942 yield* fs.remove(target, { recursive: true, force: true }).pipe(
943 Effect.andThen(
944 Effect.sync(() => {
945 if (name.startsWith(PINNED_RUNTIME_PRUNED_PREFIX)) {
946 removed.push(name.slice(PINNED_RUNTIME_PRUNED_PREFIX.length));
947 }
948 }),
949 ),
950 Effect.catch((cause) =>
951 Effect.logWarning("Could not remove an unused t3 runtime.", { target, cause }),
952 ),
953 );
954 }
955 return removed;
956});