Skip to content

Commit cc6c0d2

Browse files
fix(server): runtime prune no longer keeps a version whose directory is on the service PATH (pingdotgg#25870)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent cdd1c6a commit cc6c0d2

5 files changed

Lines changed: 193 additions & 18 deletions

File tree

‎apps/server/src/cloud/bootService.ts‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,16 @@ export interface BootServiceManager {
194194
readonly finalize: ReadonlyArray<BootServiceStep>;
195195
}
196196

197+
const defaultSystemdUnitDir = (path: Path.Path, homeDir: string, xdgConfigHome: string) =>
198+
path.join(
199+
path.isAbsolute(xdgConfigHome) ? xdgConfigHome : path.join(homeDir, ".config"),
200+
"systemd",
201+
"user",
202+
);
203+
204+
const launchdPlistPath = (path: Path.Path, homeDir: string) =>
205+
path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE);
206+
197207
function systemdManager(input: {
198208
readonly path: Path.Path;
199209
readonly unitDir: string;
@@ -270,12 +280,7 @@ function launchdManager(input: {
270280
readonly uid: number;
271281
readonly environmentPath: string;
272282
}): BootServiceManager {
273-
const unitPath = input.path.join(
274-
input.homeDir,
275-
"Library",
276-
"LaunchAgents",
277-
BOOT_SERVICE_PLIST_FILE,
278-
);
283+
const unitPath = launchdPlistPath(input.path, input.homeDir);
279284
const domainTarget = `gui/${input.uid}`;
280285
const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
281286
// Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them.
@@ -349,13 +354,7 @@ function selectBootServiceManager(input: {
349354
path: input.path,
350355
unitDir:
351356
input.systemdUnitDir ??
352-
input.path.join(
353-
input.path.isAbsolute(input.xdgConfigHome)
354-
? input.xdgConfigHome
355-
: input.path.join(input.homeDir, ".config"),
356-
"systemd",
357-
"user",
358-
),
357+
defaultSystemdUnitDir(input.path, input.homeDir, input.xdgConfigHome),
359358
});
360359
}
361360
if (input.platform === "darwin" && input.uid !== undefined) {
@@ -403,6 +402,20 @@ const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit
403402
Effect.orElseSucceed(() => undefined),
404403
);
405404

405+
/** Where this platform's service manager keeps the unit, whether or not one is installed. */
406+
export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(function* () {
407+
const path = yield* Path.Path;
408+
const platform = yield* HostProcess.Platform;
409+
const homeDir = yield* HostProcess.HomeDirectory;
410+
if (homeDir === "") return undefined;
411+
if (platform === "darwin") return launchdPlistPath(path, homeDir);
412+
if (platform !== "linux") return undefined;
413+
const unitDir =
414+
(yield* readSystemdUnitDirectory()) ??
415+
defaultSystemdUnitDir(path, homeDir, (yield* HostProcess.Environment).XDG_CONFIG_HOME ?? "");
416+
return path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
417+
});
418+
406419
export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
407420
"BootServiceUnsupportedError",
408421
{ platform: Schema.String },

‎apps/server/src/cloud/pinnedRuntime.test.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,97 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
511511
}),
512512
);
513513

514+
it.effect.each([
515+
{ name: "its directory is on PATH", onPath: true, recorded: false, linkedHome: false },
516+
{
517+
name: "an earlier prune recorded its entry as a launcher",
518+
onPath: false,
519+
recorded: true,
520+
linkedHome: false,
521+
},
522+
{
523+
name: "its real directory in a symlinked home is on PATH",
524+
onPath: true,
525+
recorded: false,
526+
linkedHome: true,
527+
},
528+
])("removes a runtime only its own entry names when $name", ({ onPath, recorded, linkedHome }) =>
529+
Effect.gen(function* () {
530+
const fs = yield* FileSystem.FileSystem;
531+
const path = yield* Path.Path;
532+
const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
533+
const binDir = path.join(baseDir, "bin");
534+
yield* fs.makeDirectory(binDir);
535+
yield* fs.symlink(path.join(versionsDir, "1.1.0", "t3"), path.join(binDir, "t3"));
536+
const ownDir = path.join(versionsDir, "1.0.0");
537+
if (recorded) {
538+
yield* fs.writeFileString(
539+
path.join(baseDir, "runtime", "launchers"),
540+
`${path.join(ownDir, "t3")}\n`,
541+
);
542+
}
543+
544+
const home = linkedHome
545+
? path.join(yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-link-" }), "home")
546+
: baseDir;
547+
if (linkedHome) yield* fs.symlink(baseDir, home);
548+
549+
// The launch agent puts the running runtime's own directory on PATH.
550+
const removed = yield* prunePinnedRuntimes({ baseDir: home, keep: ["2.0.0"] }).pipe(
551+
Effect.provideService(
552+
ProcessRunner.ProcessRunner,
553+
lsofRunner("p1\nftxt\nn/sbin/launchd\n"),
554+
),
555+
Effect.provideService(HostProcess.Platform, "darwin"),
556+
Effect.provideService(HostProcess.Environment, {
557+
T3CODE_INSTALL_BIN_DIR: binDir,
558+
PATH: onPath ? `${ownDir}:/usr/bin:/bin` : "/usr/bin:/bin",
559+
}),
560+
);
561+
assert.deepEqual(removed, ["1.0.0"]);
562+
}),
563+
);
564+
565+
it.effect.each([
566+
{ name: "a launcher inside the versions directory", via: "bin" as const },
567+
{ name: "a PATH directory linked to its version directory", via: "linked dir" as const },
568+
{
569+
name: "a PATH directory in the versions directory linked to its version directory",
570+
via: "linked versions dir" as const,
571+
},
572+
])("keeps a runtime $name names", ({ via }) =>
573+
Effect.gen(function* () {
574+
const fs = yield* FileSystem.FileSystem;
575+
const path = yield* Path.Path;
576+
const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
577+
let pathDirs = "/usr/bin:/bin";
578+
if (via === "bin") {
579+
// The installer accepts any bin directory, including one under the versions directory.
580+
const binDir = path.join(versionsDir, "bin");
581+
yield* fs.makeDirectory(binDir);
582+
yield* fs.symlink(path.join(versionsDir, "1.0.0", "t3"), path.join(binDir, "t3"));
583+
yield* fs.writeFileString(
584+
path.join(baseDir, "runtime", "launchers"),
585+
`${path.join(binDir, "t3")}\n`,
586+
);
587+
} else {
588+
const linkedDir = path.join(via === "linked dir" ? baseDir : versionsDir, "current");
589+
yield* fs.symlink(path.join(versionsDir, "1.0.0"), linkedDir);
590+
pathDirs = `${linkedDir}:${pathDirs}`;
591+
}
592+
593+
const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
594+
Effect.provideService(
595+
ProcessRunner.ProcessRunner,
596+
lsofRunner("p1\nftxt\nn/sbin/launchd\n"),
597+
),
598+
Effect.provideService(HostProcess.Platform, "darwin"),
599+
Effect.provideService(HostProcess.Environment, { PATH: pathDirs }),
600+
);
601+
assert.deepEqual(removed, ["1.1.0"]);
602+
}),
603+
);
604+
514605
it.effect.each([
515606
// An interrupted append cut this record short.
516607
{ name: "an unterminated launcher record", recorded: "/opt/t", cut: "" },

‎apps/server/src/cloud/pinnedRuntime.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,9 @@ const shellLauncherTargets = Effect.fn("cloud.pinned_runtime.shell_launcher_targ
494494
const realVersionsDir = yield* fs
495495
.realPath(versionsDir)
496496
.pipe(Effect.orElseSucceed(() => versionsDir));
497+
const inVersionsDir = (candidate: string) =>
498+
launcherOwnsVersionsDir(path, versionsDir, candidate) ||
499+
launcherOwnsVersionsDir(path, realVersionsDir, candidate);
497500
const unrecorded: Array<string> = [];
498501
const targets: Array<string> = [];
499502
for (const launcher of [...recorded, ...found]) {
@@ -506,13 +509,19 @@ const shellLauncherTargets = Effect.fn("cloud.pinned_runtime.shell_launcher_targ
506509
: // Fully resolved, through chained links and a symlinked T3 home alike.
507510
yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined));
508511
if (target === undefined) continue;
509-
targets.push(target);
512+
// A runtime's own entry, on the macOS service PATH or recorded by an earlier prune, is no launcher.
513+
// It is named as `versions/<version>/t3`, and neither it nor its directory is a link.
514+
const entryDir = path.dirname(path.resolve(launcher));
515+
const parent = path.dirname(entryDir);
510516
if (
511-
(launcherOwnsVersionsDir(path, versionsDir, target) ||
512-
launcherOwnsVersionsDir(path, realVersionsDir, target)) &&
513-
!recorded.includes(launcher) &&
514-
!unrecorded.includes(launcher)
517+
platform !== "win32" &&
518+
(parent === versionsDir || parent === realVersionsDir) &&
519+
target === path.join(realVersionsDir, path.basename(entryDir), path.basename(launcher))
515520
) {
521+
continue;
522+
}
523+
targets.push(target);
524+
if (inVersionsDir(target) && !recorded.includes(launcher) && !unrecorded.includes(launcher)) {
516525
unrecorded.push(launcher);
517526
}
518527
}

‎apps/server/src/cloud/selfUpdate.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,19 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
6868
const runner = ProcessRunner.ProcessRunner.of({
6969
run: (input) =>
7070
Effect.gen(function* () {
71+
if (input.command === "busctl") {
72+
// No user bus: the unit directory falls back to XDG_CONFIG_HOME or ~/.config.
73+
return {
74+
stdout: "",
75+
stderr: "",
76+
code: ChildProcessSpawner.ExitCode(1),
77+
timedOut: false,
78+
stdoutTruncated: false,
79+
stderrTruncated: false,
80+
stdoutInvalidUtf8: false,
81+
stderrInvalidUtf8: false,
82+
};
83+
}
7184
if (input.command === "tar") {
7285
order.push("extract");
7386
const stagingDir = input.args[input.args.indexOf("-C") + 1];
@@ -395,6 +408,8 @@ it.layer(NodeServices.layer)("pruning runtimes on start", (it) => {
395408
readonly executable: "own runtime" | "elsewhere";
396409
readonly managed?: boolean;
397410
readonly symlinkedHome?: boolean;
411+
readonly servicePlistStarts?: string;
412+
readonly servicePlistThroughLink?: boolean;
398413
}) {
399414
const fs = yield* FileSystem.FileSystem;
400415
const path = yield* Path.Path;
@@ -412,6 +427,20 @@ it.layer(NodeServices.layer)("pruning runtimes on start", (it) => {
412427
yield* fs.utimes(sentinel, 0, 0);
413428
}
414429
if (input.symlinkedHome) yield* fs.symlink(realHome, baseDir);
430+
const userHome = path.join(tempDir, "user");
431+
if (input.servicePlistStarts !== undefined) {
432+
const agentsDir = path.join(userHome, "Library", "LaunchAgents");
433+
yield* fs.makeDirectory(agentsDir, { recursive: true });
434+
const programHome = input.servicePlistThroughLink
435+
? path.join(tempDir, "alias-home")
436+
: baseDir;
437+
if (input.servicePlistThroughLink) yield* fs.symlink(realHome, programHome);
438+
const program = path.join(programHome, "runtime", "versions", input.servicePlistStarts, "t3");
439+
yield* fs.writeFileString(
440+
path.join(agentsDir, "com.t3tools.t3code.service.plist"),
441+
`<plist><dict>\n<key>ProgramArguments</key>\n<array>\n<string>${program}</string>\n<string>__service-launcher</string>\n</array>\n</dict></plist>\n`,
442+
);
443+
}
415444
// Like `process.execPath`, the running runtime is reported by its real path.
416445
const executablePath =
417446
input.executable === "own runtime"
@@ -424,6 +453,7 @@ it.layer(NodeServices.layer)("pruning runtimes on start", (it) => {
424453
Effect.provideService(HostProcess.ExecutablePath, executablePath),
425454
Effect.provideService(HostProcess.Platform, "darwin"),
426455
Effect.provideService(HostProcess.Environment, {}),
456+
Effect.provideService(HostProcess.HomeDirectory, userHome),
427457
Effect.provideService(ProcessRunner.ProcessRunner, otherProcesses),
428458
);
429459
return { removed, remaining: (yield* fs.readDirectory(versionsDir)).toSorted() };
@@ -452,6 +482,22 @@ it.layer(NodeServices.layer)("pruning runtimes on start", (it) => {
452482
}),
453483
);
454484

485+
// In-place updates move the active version but leave the launch agent on the launcher's runtime.
486+
it.effect.each([
487+
{ name: "", throughLink: false },
488+
{ name: " through a symlinked T3 home", throughLink: true },
489+
])("keeps the runtime a stopped service's launch agent starts$name", ({ throughLink }) =>
490+
Effect.gen(function* () {
491+
const { removed, remaining } = yield* pruneOnStart({
492+
executable: "own runtime",
493+
servicePlistStarts: staleVersion,
494+
servicePlistThroughLink: throughLink,
495+
});
496+
expect(removed).toEqual([]);
497+
expect(remaining).toEqual([staleVersion, packageJson.version].toSorted());
498+
}),
499+
);
500+
455501
it.effect("leaves runtimes alone for an unmanaged server started elsewhere", () =>
456502
Effect.gen(function* () {
457503
const { removed, remaining } = yield* pruneOnStart({ executable: "elsewhere" });

‎apps/server/src/cloud/selfUpdate.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
PinnedRuntimePreflightBlockedError,
4343
prunePinnedRuntimes,
4444
} from "./pinnedRuntime.ts";
45+
import { bootServiceProgramOf, bootServiceUnitPath } from "./bootService.ts";
4546
import { decodeServicePreflightResult } from "./servicePreflight.ts";
4647
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
4748
import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
@@ -91,9 +92,24 @@ export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on
9192
if (!input.managed && executablePath !== entryPath && executablePath !== realEntryPath) {
9293
return [];
9394
}
95+
const unitPath = yield* bootServiceUnitPath();
96+
// A stopped service's unit still names the launcher runtime it will start.
97+
const unit =
98+
unitPath === undefined
99+
? Option.none<string>()
100+
: yield* fs.readFileString(unitPath).pipe(Effect.option);
101+
const program = Option.flatMapNullishOr(unit, bootServiceProgramOf);
102+
// The unit may name it through another spelling of a symlinked T3 home.
103+
const references = Option.isNone(program)
104+
? []
105+
: [
106+
program.value,
107+
yield* fs.realPath(program.value).pipe(Effect.orElseSucceed(() => program.value)),
108+
];
94109
const removed = yield* prunePinnedRuntimes({
95110
baseDir: input.baseDir,
96111
keep: [packageJson.version],
112+
references,
97113
});
98114
if (removed.length > 0) {
99115
yield* Effect.logInfo("Removed unused t3 runtimes.", { versions: removed });

0 commit comments

Comments
 (0)