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