Skip to content
TypeScript

fix(server): updates no longer keep every old runtime on disk (#22253)

Julius Marminge2b28b46daa10
diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts
index 784472be246..12127541738 100644
--- a/apps/server/src/cli/uninstall.ts
+++ b/apps/server/src/cli/uninstall.ts
@@ -14,10 +14,14 @@ import * as Schema from "effect/Schema";
import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
import * as BootService from "../cloud/bootService.ts";
-import { pinnedRuntimeVersionsDir } from "../cloud/pinnedRuntime.ts";
+import {
+ launcherOwnsVersionsDir,
+ pinnedRuntimeVersionsDir,
+ windowsShimTarget,
+} from "../cloud/pinnedRuntime.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
import * as CliService from "./service.ts";
-import { findWindowsShim, launcherOwnsVersionsDir, resolveLauncherPath } from "./update.ts";
+import { findWindowsShim, resolveLauncherPath } from "./update.ts";
export class CliUninstallError extends Schema.TaggedError<CliUninstallError>()(
"CliUninstallError",
@@ -51,7 +55,7 @@ export const findOwnedLauncher = Effect.fn("cli.uninstall.find_launcher")(functi
const shimPath = yield* findWindowsShim(input.launchedAs);
if (shimPath === undefined) return undefined;
const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
- const target = Option.isSome(contents) ? /^"([^"]+)"/m.exec(contents.value)?.[1] : undefined;
+ const target = Option.isSome(contents) ? windowsShimTarget(contents.value) : undefined;
return target !== undefined && launcherOwnsVersionsDir(path, input.versionsDir, target)
? shimPath
: undefined;
diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts
index 9a35a47424e..f5e5eafa8d2 100644
--- a/apps/server/src/cli/update.ts
+++ b/apps/server/src/cli/update.ts
@@ -22,9 +22,12 @@ import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
import {
ensurePinnedRuntimeInstalled,
+ launcherOwnsVersionsDir,
pinnedRuntimeCommand,
PinnedRuntimeInstallError,
pinnedRuntimePaths,
+ prunePinnedRuntimes,
+ windowsShimTarget,
} from "../cloud/pinnedRuntime.ts";
import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
import * as ProcessRunner from "../processRunner.ts";
@@ -87,15 +90,6 @@ export const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(funct
return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
});
-export function launcherOwnsVersionsDir(
- path: Path.Path,
- versionsDir: string,
- candidate: string,
-): boolean {
- const relative = path.relative(versionsDir, path.resolve(candidate));
- return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
-}
-
/**
* Only a launcher that already points into this home's `runtime/versions` tree is touched; a
* plain copy of the executable, or a launcher for some other install, is left alone.
@@ -116,7 +110,7 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function
const shimPath = yield* findWindowsShim(input.launchedAs);
if (shimPath === undefined) return Option.none<string>();
const current = yield* fs.readFileString(shimPath).pipe(Effect.option);
- const quoted = Option.isSome(current) ? /^"([^"]+)"/m.exec(current.value)?.[1] : undefined;
+ const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined;
if (quoted === undefined || !ownsTarget(quoted)) return Option.none<string>();
yield* fs
.writeFileString(shimPath, `@echo off\r\n"${input.targetEntryPath}" %*`)
@@ -188,7 +182,7 @@ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(functio
const shimPath = path.join(directory, "t3.cmd");
const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
if (Option.isNone(contents)) continue;
- const target = /^"([^"]+)"/m.exec(contents.value)?.[1];
+ const target = windowsShimTarget(contents.value);
if (
target !== undefined &&
path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase()
@@ -521,6 +515,17 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
);
}
+ // A handed-off service install rewrites the unit later, while the old launcher may be stopped.
+ if (servicePlan?.handedOff !== true) {
+ // A stopped service's unit still names the launcher runtime it will start.
+ const unit = yield* fs.readFileString(status.unitPath).pipe(Effect.option);
+ yield* prunePinnedRuntimes({
+ baseDir: input.baseDir,
+ keep: [currentVersion, targetVersion],
+ references: Option.toArray(Option.flatMapNullishOr(unit, BootService.bootServiceProgramOf)),
+ });
+ }
+
progress.success(`Installed T3 Code ${targetVersion}`);
if (Option.isSome(repointed)) {
yield* Console.log(" Run t3 to get started.\n");
diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts
index a838b710c84..47d36292a10 100644
--- a/apps/server/src/cloud/bootService.test.ts
+++ b/apps/server/src/cloud/bootService.test.ts
@@ -64,6 +64,23 @@ it("reads the served T3 home back out of a rendered unit or plist", () => {
expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined();
});
+it.each([
+ ["a unit", '/home/theo/T3 "Data"/100%\\x', BootService.renderBootServiceUnit],
+ [
+ "a plist",
+ "/Users/theo/a&b <c>",
+ (plan: BootService.BootServicePlan) =>
+ BootService.renderBootServicePlist(plan, { homeDir: "/Users/theo", environmentPath: "" }),
+ ],
+] as const)("reads the launcher back out of %s", (_, baseDir, render) => {
+ const program = `${baseDir}/runtime/versions/1.2.3/t3`;
+ expect(
+ BootService.bootServiceProgramOf(
+ render({ program: [program, "__service-launcher"], baseDir, logPath: "/log", unitPath: "" }),
+ ),
+ ).toBe(program);
+});
+
it("survives the kernel OOM-killing a greedy agent child", () => {
const unit = BootService.renderBootServiceUnit(linuxPlan);
diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts
index b821d1951a8..c1be1fc2c5e 100644
--- a/apps/server/src/cloud/bootService.ts
+++ b/apps/server/src/cloud/bootService.ts
@@ -53,21 +53,30 @@ function quoteSystemdValue(value: string): string {
: escaped;
}
+const unquoteSystemdValue = (raw: string) =>
+ (raw.startsWith('"') && raw.endsWith('"')
+ ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
+ : raw
+ ).replaceAll("%%", "%");
+
+const unescapeXmlText = (value: string) =>
+ value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
+
export function bootServiceBaseDirOf(contents: string): string | undefined {
const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
- if (systemd !== undefined) {
- const raw = systemd.trim();
- const unquoted =
- raw.startsWith('"') && raw.endsWith('"')
- ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
- : raw;
- return unquoted.replaceAll("%%", "%");
- }
+ if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
- if (plist !== undefined) {
- return plist.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
- }
- return undefined;
+ return plist === undefined ? undefined : unescapeXmlText(plist);
+}
+
+/** The executable an installed unit or plist starts: the launcher's runtime. */
+export function bootServiceProgramOf(contents: string): string | undefined {
+ const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
+ if (systemd !== undefined) return unquoteSystemdValue(systemd);
+ const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
+ contents,
+ )?.[1];
+ return plist === undefined ? undefined : unescapeXmlText(plist);
}
export interface BootServicePlan {
diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts
index 0556425ef21..b0e15e68863 100644
--- a/apps/server/src/cloud/pinnedRuntime.test.ts
+++ b/apps/server/src/cloud/pinnedRuntime.test.ts
@@ -8,8 +8,11 @@ import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientResponse } from "effect/http";
+import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+
import * as ProcessRunner from "../processRunner.ts";
import {
ensurePinnedRuntimeInstalled,
@@ -17,7 +20,9 @@ import {
pinnedRuntimePaths,
PinnedRuntimeInstallError,
type PinnedRuntimeProgress,
+ prunePinnedRuntimes,
} from "./pinnedRuntime.ts";
+import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
const version = "1.2.3";
const archiveName = `t3-${version}-linux-x64.tar.gz`;
@@ -553,3 +558,205 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
}),
);
});
+
+it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
+ const lsofRunner = (stdout: string) =>
+ ProcessRunner.ProcessRunner.of({
+ run: () =>
+ Effect.succeed({
+ stdout,
+ stderr: "",
+ code: ChildProcessSpawner.ExitCode(0),
+ timedOut: false,
+ stdoutTruncated: false,
+ stderrTruncated: false,
+ stdoutInvalidUtf8: false,
+ stderrInvalidUtf8: false,
+ }),
+ });
+
+ const setup = Effect.fn(function* (versions: ReadonlyArray<string>) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-prune-" });
+ const versionsDir = path.join(baseDir, "runtime", "versions");
+ const now = Duration.toMillis(Duration.days(1));
+ yield* TestClock.setTime(now);
+ const install = Effect.fn(function* (
+ version: string,
+ completed: "long ago" | "just now" | "never" = "long ago",
+ ) {
+ const directory = path.join(versionsDir, version);
+ yield* fs.makeDirectory(directory, { recursive: true });
+ yield* fs.writeFileString(path.join(directory, "t3"), "");
+ if (completed === "never") return;
+ const sentinel = path.join(directory, ".install-complete");
+ yield* fs.writeFileString(sentinel, `${version}\n`);
+ const at = completed === "just now" ? now : 0;
+ yield* fs.utimes(sentinel, at, at);
+ });
+ for (const version of versions) yield* install(version);
+ return { baseDir, versionsDir, install };
+ });
+
+ it.effect("removes only completed runtimes nothing references", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const { baseDir, versionsDir, install } = yield* setup([
+ "1.0.0",
+ "1.1.0",
+ "1.2.0",
+ "1.2.5",
+ "1.3.0",
+ "1.3.5",
+ "1.4.0",
+ "1.5.0",
+ "2.0.0",
+ "2.1.0",
+ ]);
+ // A downgrade another process installed but has not pointed anything at yet.
+ yield* install("0.5.0", "just now");
+ yield* install("1.0.1", "never");
+ yield* install(".staging-abc", "never");
+ yield* install(".pruned-0.8.0");
+ yield* install("other", "never");
+ yield* fs.symlink(path.join(versionsDir, "other"), path.join(versionsDir, "0.9.0"));
+ const binDir = path.join(baseDir, "bin");
+ const customBinDir = path.join(baseDir, "custom-bin");
+ yield* fs.makeDirectory(binDir);
+ yield* fs.makeDirectory(customBinDir);
+ // Chained: the launcher reaches its runtime through a second link.
+ yield* fs.symlink(path.join(versionsDir, "1.2.0", "t3"), path.join(baseDir, "alias-t3"));
+ yield* fs.symlink(path.join(baseDir, "alias-t3"), path.join(binDir, "t3"));
+ yield* fs.symlink(path.join(versionsDir, "1.2.5", "t3"), path.join(customBinDir, "t3"));
+ yield* fs.writeFileString(
+ path.join(baseDir, "runtime", "launchers"),
+ `${path.join(customBinDir, "t3")}\n`,
+ );
+ yield* fs.writeFileString(
+ path.join(baseDir, "runtime", "service-state.json"),
+ JSON.stringify({
+ protocol: SERVICE_LAUNCHER_PROTOCOL,
+ activeVersion: "1.4.0",
+ update: { id: "u", fromVersion: "1.4.0", targetVersion: "1.5.0", status: "rolled-back" },
+ }),
+ );
+
+ const removed = yield* prunePinnedRuntimes({
+ baseDir,
+ keep: ["2.0.0"],
+ references: [`ExecStart=${path.join(versionsDir, "1.3.5", "t3")} __service-launcher`],
+ }).pipe(
+ Effect.provideService(
+ ProcessRunner.ProcessRunner,
+ lsofRunner(`p42\nftxt\nn${path.join(versionsDir, "1.3.0", "t3")}\n`),
+ ),
+ Effect.provideService(HostProcess.Platform, "darwin"),
+ Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: binDir }),
+ );
+
+ // 1.2.0 is the default launcher, 1.2.5 a recorded one, 1.3.0 running, 1.3.5 in the unit,
+ // 1.4.0 active, 1.5.0 the rolled-back target, 2.0.0 the caller's, 0.5.0 just installed.
+ // Being newer than the caller's version does not keep 2.1.0.
+ assert.deepEqual(removed.toSorted(), ["0.8.0", "1.0.0", "1.1.0", "2.1.0"]);
+ // The launcher found on PATH is remembered for a service that cannot see it.
+ assert.equal(
+ yield* fs.readFileString(path.join(baseDir, "runtime", "launchers")),
+ `${path.join(customBinDir, "t3")}\n${path.join(binDir, "t3")}\n`,
+ );
+ assert.deepEqual((yield* fs.readDirectory(versionsDir)).toSorted(), [
+ ".staging-abc",
+ "0.5.0",
+ "0.9.0",
+ "1.0.1",
+ "1.2.0",
+ "1.2.5",
+ "1.3.0",
+ "1.3.5",
+ "1.4.0",
+ "1.5.0",
+ "2.0.0",
+ "other",
+ ]);
+ }),
+ );
+
+ it.effect("matches a Windows shim whatever its casing", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
+ const shim = path.join(baseDir, "t3.cmd");
+ yield* fs.writeFileString(
+ shim,
+ `@echo off\r\n"${path.join(versionsDir, "1.0.0", "t3.exe").toUpperCase()}" %*`,
+ );
+ yield* fs.writeFileString(path.join(baseDir, "runtime", "launchers"), `${shim}\n`);
+
+ const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
+ Effect.provideService(
+ ProcessRunner.ProcessRunner,
+ lsofRunner("C:\\Windows\\explorer.exe\n"),
+ ),
+ Effect.provideService(HostProcess.Platform, "win32"),
+ Effect.provideService(HostProcess.Environment, {}),
+ );
+ assert.deepEqual(removed, ["1.1.0"]);
+ }),
+ );
+
+ it.effect.each([
+ { name: "the process list is unavailable", state: undefined, lsof: "" },
+ { name: "the service state is unparseable", state: "{", lsof: "p1\nftxt\nn/sbin/launchd\n" },
+ {
+ name: "the service state cannot be read",
+ state: null,
+ lsof: "p1\nftxt\nn/sbin/launchd\n",
+ },
+ ])("keeps everything when $name", ({ state, lsof }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const { baseDir, versionsDir } = yield* setup(["1.0.0"]);
+ const statePath = path.join(baseDir, "runtime", "service-state.json");
+ if (state === null) yield* fs.makeDirectory(statePath);
+ else if (state !== undefined) yield* fs.writeFileString(statePath, state);
+
+ const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
+ Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner(lsof)),
+ Effect.provideService(HostProcess.Platform, "darwin"),
+ Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
+ );
+ assert.deepEqual(removed, []);
+ assert.deepEqual(yield* fs.readDirectory(versionsDir), ["1.0.0"]);
+ }),
+ );
+
+ it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
+ "keeps a runtime a process runs through a symlink",
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
+ const entry = path.join(versionsDir, "1.0.0", "t3");
+ yield* fs.copyFile("/bin/sleep", entry);
+ yield* fs.chmod(entry, 0o755);
+ const link = path.join(baseDir, "t3");
+ yield* fs.symlink(entry, link);
+ // Its argv names only the link, as with `t3 serve` run from PATH. Removing the link after
+ // spawning leaves the process's executable as the only reference.
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ yield* spawner.spawn(ChildProcess.make(link, ["30"]));
+ yield* fs.remove(link);
+
+ const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
+ Effect.provideService(HostProcess.Platform, "linux"),
+ Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
+ Effect.provide(ProcessRunner.layer),
+ );
+ assert.deepEqual(removed, ["1.1.0"]);
+ }),
+ );
+});
diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts
index 0b3592a2019..0093e7a6220 100644
--- a/apps/server/src/cloud/pinnedRuntime.ts
+++ b/apps/server/src/cloud/pinnedRuntime.ts
@@ -1,4 +1,5 @@
import * as Cause from "effect/Cause";
+import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
@@ -19,7 +20,10 @@ import {
parseChecksums,
} from "@t3tools/shared/cliRelease";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+
import * as ProcessRunner from "../processRunner.ts";
+import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts";
const PINNED_RUNTIME_DIR = "runtime";
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
@@ -364,3 +368,266 @@ const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(
export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));
+
+const PINNED_RUNTIME_PRUNED_PREFIX = ".pruned-";
+/**
+ * Another process may have just published a runtime it has not yet pointed anything at: an
+ * update, a downgrade, or the install script between unpacking and linking. The install lock only
+ * covers this process, so recently completed runtimes are left for a later prune.
+ */
+const PINNED_RUNTIME_PRUNE_GRACE = Duration.hours(1);
+/**
+ * One `t3` launcher path per line, appended by the install scripts and by any prune that finds a
+ * launcher on PATH. A service does not see the installer's `T3CODE_INSTALL_BIN_DIR` or the
+ * interactive PATH, so this is how it finds a custom one, including installs that predate the file.
+ */
+const PINNED_RUNTIME_LAUNCHERS_FILE = "launchers";
+
+export function launcherOwnsVersionsDir(
+ path: Path.Path,
+ versionsDir: string,
+ candidate: string,
+): boolean {
+ const relative = path.relative(versionsDir, path.resolve(candidate));
+ return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
+}
+
+/** The executable a `t3.cmd` shim written by the install script or `t3 update` runs. */
+export const windowsShimTarget = (contents: string) => /^"([^"]+)"/m.exec(contents)?.[1];
+
+/** Where the `t3` launchers written by the install scripts and `t3 update` point. */
+const shellLauncherTargets = Effect.fn("cloud.pinned_runtime.shell_launcher_targets")(function* (
+ baseDir: string,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const platform = yield* HostProcess.Platform;
+ const environment = yield* HostProcess.Environment;
+ const home = yield* HostProcess.HomeDirectory;
+ const launcherName = platform === "win32" ? "t3.cmd" : "t3";
+ const launchersFile = path.join(baseDir, PINNED_RUNTIME_DIR, PINNED_RUNTIME_LAUNCHERS_FILE);
+ const recorded = (yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => "")))
+ .split(/\r?\n/)
+ .filter((launcher) => launcher.trim().length > 0);
+ const found = [
+ environment["T3CODE_INSTALL_BIN_DIR"] || path.join(home, ".local", "bin"),
+ ...(environment["PATH"] ?? environment["Path"] ?? "").split(platform === "win32" ? ";" : ":"),
+ ]
+ .filter((directory) => path.isAbsolute(directory))
+ .map((directory) => path.join(directory, launcherName));
+ const versionsDir = pinnedRuntimeVersionsDir(path, baseDir);
+ const realVersionsDir = yield* fs
+ .realPath(versionsDir)
+ .pipe(Effect.orElseSucceed(() => versionsDir));
+ const unrecorded: Array<string> = [];
+ const targets: Array<string> = [];
+ for (const launcher of [...recorded, ...found]) {
+ const target =
+ platform === "win32"
+ ? yield* fs.readFileString(launcher).pipe(
+ Effect.map(windowsShimTarget),
+ Effect.orElseSucceed(() => undefined),
+ )
+ : // Fully resolved, through chained links and a symlinked T3 home alike.
+ yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined));
+ if (target === undefined) continue;
+ targets.push(target);
+ if (
+ (launcherOwnsVersionsDir(path, versionsDir, target) ||
+ launcherOwnsVersionsDir(path, realVersionsDir, target)) &&
+ !recorded.includes(launcher) &&
+ !unrecorded.includes(launcher)
+ ) {
+ unrecorded.push(launcher);
+ }
+ }
+ if (unrecorded.length > 0) {
+ yield* fs
+ .writeFileString(launchersFile, unrecorded.map((launcher) => `${launcher}\n`).join(""), {
+ flag: "a",
+ })
+ .pipe(Effect.ignore);
+ }
+ return targets;
+});
+
+/**
+ * Resolved executables rather than command lines: a server started through the `t3` symlink
+ * shows up as `t3 serve`, possibly from another T3 home that runs this home's runtimes. Windows
+ * has no symlink launcher, and its `t3.cmd` shim runs the absolute path, so command lines do there.
+ */
+const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables")(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const runner = yield* ProcessRunner.ProcessRunner;
+ const platform = yield* HostProcess.Platform;
+ if (platform === "linux") {
+ const pids = yield* fs.readDirectory("/proc").pipe(Effect.option);
+ if (Option.isNone(pids)) return Option.none<string>();
+ const executables: Array<string> = [];
+ for (const pid of pids.value) {
+ if (!/^\d+$/.test(pid)) continue;
+ // Unreadable ones belong to other users or are this user's non-dumpable daemons (systemd
+ // --user, ssh-agent). Neither runs a t3 runtime, and bailing on them would never prune.
+ const executable = yield* fs.readLink(`/proc/${pid}/exe`).pipe(Effect.option);
+ if (Option.isSome(executable)) executables.push(executable.value);
+ }
+ return executables.length === 0 ? Option.none<string>() : Option.some(executables.join("\n"));
+ }
+ const result = yield* runner
+ .run({
+ ...(platform === "win32"
+ ? {
+ command: "powershell.exe",
+ args: [
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine",
+ ],
+ }
+ : { command: "lsof", args: ["-nP", "-w", "-d", "txt", "-F", "n"] }),
+ timeout: Duration.seconds(10),
+ maxOutputBytes: 16 * 1024 * 1024,
+ })
+ .pipe(Effect.option);
+ return Option.isSome(result) && result.value.code === 0 && result.value.stdout.length > 0
+ ? Option.some(result.value.stdout)
+ : Option.none<string>();
+});
+
+const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(function* (input: {
+ readonly baseDir: string;
+ readonly keep: ReadonlyArray<string>;
+ readonly references: ReadonlyArray<string>;
+}) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
+ const entries = yield* fs.readDirectory(versionsDir).pipe(Effect.orElseSucceed(() => []));
+ // An interrupted prune has already renamed its runtime out of the way.
+ const pruned = new Set(
+ entries
+ .filter((entry) => entry.startsWith(PINNED_RUNTIME_PRUNED_PREFIX))
+ .map((entry) => path.join(versionsDir, entry)),
+ );
+
+ const settledBefore =
+ (yield* Clock.currentTimeMillis) - Duration.toMillis(PINNED_RUNTIME_PRUNE_GRACE);
+ const completed: Array<string> = [];
+ for (const version of entries) {
+ if (!isExactServiceVersion(version)) continue;
+ const versionDir = path.join(versionsDir, version);
+ const sentinelPath = path.join(versionDir, ".install-complete");
+ const isLink = yield* fs.readLink(versionDir).pipe(Effect.isSuccess);
+ const sentinel = yield* fs.readFileString(sentinelPath).pipe(Effect.option);
+ const completedAt = yield* fs.stat(sentinelPath).pipe(
+ Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
+ Effect.orElseSucceed(() => undefined),
+ );
+ if (
+ !isLink &&
+ Option.isSome(sentinel) &&
+ sentinel.value.trim() === version &&
+ completedAt !== undefined &&
+ completedAt < settledBefore
+ ) {
+ completed.push(version);
+ }
+ }
+ if (completed.length === 0) return pruned;
+
+ const keep = new Set(input.keep);
+ const stateText = yield* fs
+ .readFileString(path.join(input.baseDir, PINNED_RUNTIME_DIR, SERVICE_STATE_FILE))
+ .pipe(
+ Effect.asSome,
+ Effect.catch((error) =>
+ Effect.succeed(error.reason._tag === "NotFound" ? Option.none<string>() : undefined),
+ ),
+ );
+ // State this version cannot read may reference runtimes in ways it does not know.
+ if (stateText === undefined) return pruned;
+ if (Option.isSome(stateText)) {
+ const state = parseServiceState(stateText.value);
+ if (state === undefined) return pruned;
+ keep.add(state.activeVersion);
+ if (state.update !== undefined) {
+ keep.add(state.update.fromVersion);
+ keep.add(state.update.targetVersion);
+ }
+ }
+ const executables = yield* runningExecutables();
+ // Without a process list, a runtime in use would look unused.
+ if (Option.isNone(executables)) return pruned;
+ const platform = yield* HostProcess.Platform;
+ // Windows paths are case-insensitive, and shims and process lists need not agree on case.
+ const foldCase = (value: string) => (platform === "win32" ? value.toLowerCase() : value);
+ const references = [
+ executables.value,
+ ...(yield* shellLauncherTargets(input.baseDir)),
+ ...input.references,
+ ].map(foldCase);
+ // Process executables are resolved, so they name the real path of a symlinked T3 home.
+ const realVersionsDir = yield* fs
+ .realPath(versionsDir)
+ .pipe(Effect.orElseSucceed(() => versionsDir));
+
+ for (const version of completed) {
+ const versionDir = path.join(versionsDir, version);
+ const prefixes = [versionDir, path.join(realVersionsDir, version)].map((dir) =>
+ foldCase(dir + path.sep),
+ );
+ if (
+ keep.has(version) ||
+ references.some((reference) => prefixes.some((prefix) => reference.includes(prefix)))
+ ) {
+ continue;
+ }
+ const target = path.join(versionsDir, `${PINNED_RUNTIME_PRUNED_PREFIX}${version}`);
+ // Renaming first means an interrupted removal never leaves a partial tree that still carries
+ // its sentinel and would pass for a complete install.
+ yield* fs.remove(target, { recursive: true, force: true }).pipe(
+ Effect.andThen(fs.rename(versionDir, target)),
+ Effect.andThen(Effect.sync(() => pruned.add(target))),
+ Effect.catch((cause) =>
+ Effect.logWarning("Could not remove an unused t3 runtime.", { version, cause }),
+ ),
+ );
+ }
+ return pruned;
+});
+
+/**
+ * Every update publishes a new immutable runtime, so without pruning they pile up. Removes
+ * completed runtimes nothing can start again and keeps: the caller's versions, everything the
+ * service state references (active, rollback, pending), and runtimes that a running process
+ * executes, a `t3` launcher points at, or `references` (such as the service unit) name, plus
+ * anything published within the last hour. Staging directories, symlinks, and unexpected entries
+ * are never touched. Returns the versions removed.
+ */
+export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(function* (input: {
+ readonly baseDir: string;
+ readonly keep: ReadonlyArray<string>;
+ readonly references?: ReadonlyArray<string>;
+}) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ // Only selection and the renames race an install; deleting renamed trees can take a while.
+ const pruned = yield* pinnedRuntimeInstallLock.withPermit(
+ selectUnusedRuntimes({ ...input, references: input.references ?? [] }),
+ );
+ const removed: Array<string> = [];
+ for (const target of pruned) {
+ yield* fs.remove(target, { recursive: true, force: true }).pipe(
+ Effect.andThen(
+ Effect.sync(() =>
+ removed.push(path.basename(target).slice(PINNED_RUNTIME_PRUNED_PREFIX.length)),
+ ),
+ ),
+ Effect.catch((cause) =>
+ Effect.logWarning("Could not remove an unused t3 runtime.", { target, cause }),
+ ),
+ );
+ }
+ return removed;
+});
diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.ts
index 4180d7ece6b..10c2a7991e7 100644
--- a/apps/server/src/cloud/selfUpdate.ts
+++ b/apps/server/src/cloud/selfUpdate.ts
@@ -25,6 +25,7 @@ import { HttpClient } from "effect/http";
import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
+import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
import * as ProcessRunner from "../processRunner.ts";
@@ -33,6 +34,7 @@ import {
pinnedRuntimeCommand,
PinnedRuntimeInstallError,
PinnedRuntimePreflightBlockedError,
+ prunePinnedRuntimes,
} from "./pinnedRuntime.ts";
import { decodeServicePreflightResult } from "./servicePreflight.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
@@ -186,6 +188,19 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
);
const inFlight = yield* Ref.make(false);
+ // A managed server starting means its launcher has settled on a version, so runtimes left by
+ // earlier updates can go.
+ if (launcher.managed) {
+ yield* prunePinnedRuntimes({ baseDir: serverConfig.baseDir, keep: [packageJson.version] }).pipe(
+ Effect.tap((removed) =>
+ removed.length === 0
+ ? Effect.void
+ : Effect.logInfo("Removed unused t3 runtimes.", { versions: removed }),
+ ),
+ Effect.forkScoped,
+ );
+ }
+
const capability: ServerSelfUpdateCapability | null =
serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
const failWith = (reason: string, cause?: unknown) =>
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index d0d7140d2f4..58df4a6447a 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -215,6 +215,12 @@ $shim = Join-Path $binDir "t3.cmd"
# UTF-8 without a BOM: cmd.exe reads the shim as-is, and ASCII would corrupt
# non-ASCII characters in the user's home path.
[System.IO.File]::WriteAllText($shim, "@echo off`r`n`"$(Join-Path $targetDir 't3.exe')`" %*", (New-Object System.Text.UTF8Encoding $false))
+# Pruning keeps what this shim points at; a background service cannot see $binDir otherwise.
+$launchers = Join-Path $t3Home "runtime\launchers"
+$shimPath = (Resolve-Path $shim).Path
+if (-not ((Test-Path $launchers) -and ((Get-Content $launchers) -contains $shimPath))) {
+ [System.IO.File]::AppendAllText($launchers, "$shimPath`r`n", (New-Object System.Text.UTF8Encoding $false))
+}
if ($interactive) { [Console]::Error.Write("`r$esc[2K") }
[Console]::Error.WriteLine(" ${green}Installed T3 Code $version$reset`n")
if (($env:PATH -split ";") -notcontains $binDir) {
diff --git a/scripts/install.sh b/scripts/install.sh
index 421d8d021ae..1718aff952e 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -219,6 +219,10 @@ fi
step "Setting up the t3 command..."
mkdir -p "$bin_dir"
ln -sfn "${target_dir}/t3" "${bin_dir}/t3"
+# Pruning keeps what this launcher points at; a background service cannot see bin_dir otherwise.
+launcher="$(CDPATH='' cd -P -- "$bin_dir" && pwd)/t3"
+launchers="${t3_home}/runtime/launchers"
+grep -qxF "$launcher" "$launchers" 2>/dev/null || printf '%s\n' "$launcher" >> "$launchers"
if "$interactive"; then printf '\r\033[2K' >&2; fi
printf ' %sInstalled T3 Code %s%s\n\n' "$green" "$version" "$reset" >&2
case ":${PATH}:" in
diff --git a/scripts/install.test.ts b/scripts/install.test.ts
index 54af8a57772..ba215343505 100644
--- a/scripts/install.test.ts
+++ b/scripts/install.test.ts
@@ -102,6 +102,9 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer term
}).trim(),
).toBe("t3 v1.2.3");
expect(await NodeFSP.readdir(versions)).toEqual([version]);
+ expect(
+ await NodeFSP.readFile(NodePath.join(root, "home/runtime/launchers"), "utf8"),
+ ).toBe(`${NodePath.join(root, "bin/t3")}\n`);
}
} finally {
if (child.exitCode === null) child.kill();