Skip to content

Commit 95e8dea

Browse files
fix(server): leave freshly installed runtimes alone and fold Windows path case
- A downgrade installed by another process could be pruned before it repointed anything, since only versions newer than the caller were protected and the install lock is per process. Skip any runtime completed within the last hour instead; that covers upgrades, downgrades, and the install script alike, and stops keeping newer runtimes forever after a deliberate downgrade. - Match references case-insensitively on Windows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4f84442 commit 95e8dea

2 files changed

Lines changed: 75 additions & 27 deletions

File tree

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

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -580,13 +580,20 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
580580
const path = yield* Path.Path;
581581
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-prune-" });
582582
const versionsDir = path.join(baseDir, "runtime", "versions");
583-
const install = Effect.fn(function* (version: string, complete = true) {
583+
const now = Duration.toMillis(Duration.days(1));
584+
yield* TestClock.setTime(now);
585+
const install = Effect.fn(function* (
586+
version: string,
587+
completed: "long ago" | "just now" | "never" = "long ago",
588+
) {
584589
const directory = path.join(versionsDir, version);
585590
yield* fs.makeDirectory(directory, { recursive: true });
586591
yield* fs.writeFileString(path.join(directory, "t3"), "");
587-
if (complete) {
588-
yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
589-
}
592+
if (completed === "never") return;
593+
const sentinel = path.join(directory, ".install-complete");
594+
yield* fs.writeFileString(sentinel, `${version}\n`);
595+
const at = completed === "just now" ? now : 0;
596+
yield* fs.utimes(sentinel, at, at);
590597
});
591598
for (const version of versions) yield* install(version);
592599
return { baseDir, versionsDir, install };
@@ -608,10 +615,12 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
608615
"2.0.0",
609616
"2.1.0",
610617
]);
611-
yield* install("1.0.1", false);
612-
yield* install(".staging-abc", false);
618+
// A downgrade another process installed but has not pointed anything at yet.
619+
yield* install("0.5.0", "just now");
620+
yield* install("1.0.1", "never");
621+
yield* install(".staging-abc", "never");
613622
yield* install(".pruned-0.8.0");
614-
yield* install("other", false);
623+
yield* install("other", "never");
615624
yield* fs.symlink(path.join(versionsDir, "other"), path.join(versionsDir, "0.9.0"));
616625
const binDir = path.join(baseDir, "bin");
617626
const customBinDir = path.join(baseDir, "custom-bin");
@@ -648,15 +657,17 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
648657
);
649658

650659
// 1.2.0 is the default launcher, 1.2.5 a recorded one, 1.3.0 running, 1.3.5 in the unit,
651-
// 1.4.0 active, 1.5.0 the rolled-back target, 2.0.0 the caller's and 2.1.0 newer.
652-
assert.deepEqual(removed.toSorted(), ["0.8.0", "1.0.0", "1.1.0"]);
660+
// 1.4.0 active, 1.5.0 the rolled-back target, 2.0.0 the caller's, 0.5.0 just installed.
661+
// Being newer than the caller's version does not keep 2.1.0.
662+
assert.deepEqual(removed.toSorted(), ["0.8.0", "1.0.0", "1.1.0", "2.1.0"]);
653663
// The launcher found on PATH is remembered for a service that cannot see it.
654664
assert.equal(
655665
yield* fs.readFileString(path.join(baseDir, "runtime", "launchers")),
656666
`${path.join(customBinDir, "t3")}\n${path.join(binDir, "t3")}\n`,
657667
);
658668
assert.deepEqual((yield* fs.readDirectory(versionsDir)).toSorted(), [
659669
".staging-abc",
670+
"0.5.0",
660671
"0.9.0",
661672
"1.0.1",
662673
"1.2.0",
@@ -666,12 +677,35 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
666677
"1.4.0",
667678
"1.5.0",
668679
"2.0.0",
669-
"2.1.0",
670680
"other",
671681
]);
672682
}),
673683
);
674684

685+
it.effect("matches a Windows shim whatever its casing", () =>
686+
Effect.gen(function* () {
687+
const fs = yield* FileSystem.FileSystem;
688+
const path = yield* Path.Path;
689+
const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
690+
const shim = path.join(baseDir, "t3.cmd");
691+
yield* fs.writeFileString(
692+
shim,
693+
`@echo off\r\n"${path.join(versionsDir, "1.0.0", "t3.exe").toUpperCase()}" %*`,
694+
);
695+
yield* fs.writeFileString(path.join(baseDir, "runtime", "launchers"), `${shim}\n`);
696+
697+
const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
698+
Effect.provideService(
699+
ProcessRunner.ProcessRunner,
700+
lsofRunner("C:\\Windows\\explorer.exe\n"),
701+
),
702+
Effect.provideService(HostProcess.Platform, "win32"),
703+
Effect.provideService(HostProcess.Environment, {}),
704+
);
705+
assert.deepEqual(removed, ["1.1.0"]);
706+
}),
707+
);
708+
675709
it.effect.each([
676710
{ name: "the process list is unavailable", state: undefined, lsof: "" },
677711
{ name: "the service state is unparseable", state: "{", lsof: "p1\nftxt\nn/sbin/launchd\n" },

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

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as Cause from "effect/Cause";
2+
import * as Clock from "effect/Clock";
23
import * as Duration from "effect/Duration";
34
import * as Effect from "effect/Effect";
45
import * as Hex from "effect/encoding/Hex";
@@ -22,12 +23,7 @@ import {
2223
import * as HostProcess from "@t3tools/shared/HostProcess";
2324

2425
import * as ProcessRunner from "../processRunner.ts";
25-
import {
26-
compareExactServiceVersions,
27-
isExactServiceVersion,
28-
parseServiceState,
29-
SERVICE_STATE_FILE,
30-
} from "./serviceProtocol.ts";
26+
import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts";
3127

3228
const PINNED_RUNTIME_DIR = "runtime";
3329
const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
@@ -374,6 +370,12 @@ export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =
374370
pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));
375371

376372
const PINNED_RUNTIME_PRUNED_PREFIX = ".pruned-";
373+
/**
374+
* Another process may have just published a runtime it has not yet pointed anything at: an
375+
* update, a downgrade, or the install script between unpacking and linking. The install lock only
376+
* covers this process, so recently completed runtimes are left for a later prune.
377+
*/
378+
const PINNED_RUNTIME_PRUNE_GRACE = Duration.hours(1);
377379
/**
378380
* One `t3` launcher path per line, appended by the install scripts and by any prune that finds a
379381
* launcher on PATH. A service does not see the installer's `T3CODE_INSTALL_BIN_DIR` or the
@@ -509,15 +511,26 @@ const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(fun
509511
.map((entry) => path.join(versionsDir, entry)),
510512
);
511513

514+
const settledBefore =
515+
(yield* Clock.currentTimeMillis) - Duration.toMillis(PINNED_RUNTIME_PRUNE_GRACE);
512516
const completed: Array<string> = [];
513517
for (const version of entries) {
514518
if (!isExactServiceVersion(version)) continue;
515519
const versionDir = path.join(versionsDir, version);
520+
const sentinelPath = path.join(versionDir, ".install-complete");
516521
const isLink = yield* fs.readLink(versionDir).pipe(Effect.isSuccess);
517-
const sentinel = yield* fs
518-
.readFileString(path.join(versionDir, ".install-complete"))
519-
.pipe(Effect.option);
520-
if (!isLink && Option.isSome(sentinel) && sentinel.value.trim() === version) {
522+
const sentinel = yield* fs.readFileString(sentinelPath).pipe(Effect.option);
523+
const completedAt = yield* fs.stat(sentinelPath).pipe(
524+
Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime()),
525+
Effect.orElseSucceed(() => undefined),
526+
);
527+
if (
528+
!isLink &&
529+
Option.isSome(sentinel) &&
530+
sentinel.value.trim() === version &&
531+
completedAt !== undefined &&
532+
completedAt < settledBefore
533+
) {
521534
completed.push(version);
522535
}
523536
}
@@ -546,25 +559,26 @@ const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(fun
546559
const executables = yield* runningExecutables();
547560
// Without a process list, a runtime in use would look unused.
548561
if (Option.isNone(executables)) return pruned;
562+
const platform = yield* HostProcess.Platform;
563+
// Windows paths are case-insensitive, and shims and process lists need not agree on case.
564+
const foldCase = (value: string) => (platform === "win32" ? value.toLowerCase() : value);
549565
const references = [
550566
executables.value,
551567
...(yield* shellLauncherTargets(input.baseDir)),
552568
...input.references,
553-
];
569+
].map(foldCase);
554570
// Process executables are resolved, so they name the real path of a symlinked T3 home.
555571
const realVersionsDir = yield* fs
556572
.realPath(versionsDir)
557573
.pipe(Effect.orElseSucceed(() => versionsDir));
558-
const exactKeep = input.keep.filter(isExactServiceVersion);
559574

560575
for (const version of completed) {
561576
const versionDir = path.join(versionsDir, version);
562-
const prefixes = [versionDir, path.join(realVersionsDir, version)].map((dir) => dir + path.sep);
577+
const prefixes = [versionDir, path.join(realVersionsDir, version)].map((dir) =>
578+
foldCase(dir + path.sep),
579+
);
563580
if (
564581
keep.has(version) ||
565-
// Another process may be installing a newer runtime, so only versions older than every
566-
// kept one go.
567-
!exactKeep.every((kept) => compareExactServiceVersions(version, kept) < 0) ||
568582
references.some((reference) => prefixes.some((prefix) => reference.includes(prefix)))
569583
) {
570584
continue;
@@ -588,7 +602,7 @@ const selectUnusedRuntimes = Effect.fn("cloud.pinned_runtime.select_unused")(fun
588602
* completed runtimes nothing can start again and keeps: the caller's versions, everything the
589603
* service state references (active, rollback, pending), and runtimes that a running process
590604
* executes, a `t3` launcher points at, or `references` (such as the service unit) name, plus
591-
* anything newer than the caller's versions. Staging directories, symlinks, and unexpected entries
605+
* anything published within the last hour. Staging directories, symlinks, and unexpected entries
592606
* are never touched. Returns the versions removed.
593607
*/
594608
export const prunePinnedRuntimes = Effect.fn("cloud.pinned_runtime.prune")(function* (input: {

0 commit comments

Comments
 (0)