Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 72 additions & 5 deletions apps/server/src/cli/update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ import * as BootService from "../cloud/bootService.ts";
import { prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as ProcessRunner from "../processRunner.ts";
import { repointLauncher, resolveLauncherPath, resolveNewestVersion, runUpdate } from "./update.ts";
import {
repointLauncher,
resolveLauncherPath,
resolveMirrorVersion,
resolveNewestVersion,
runUpdate,
} from "./update.ts";

// lsof listing one process, so prune sees a process list in which no runtime is running.
const unrelatedLsof = ProcessRunner.ProcessRunner.of({
Expand Down Expand Up @@ -60,10 +66,56 @@ it.effect("authenticates each release page until the requested channel is found"
}),
);

it.effect("reads the newest version from the update feed file a mirror publishes", () =>
Effect.gen(function* () {
const requested: string[] = [];
const mirror = { organization: "Example Corp", feedUrl: "https://updates.example.com/t3code/" };
const resolve = (
channel: "stable" | "nightly" | "preview",
platform: NodeJS.Platform,
arch: string,
feed: string,
) =>
resolveMirrorVersion(mirror, channel).pipe(
Effect.map((version): string => version),
Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
Effect.provideService(HostProcess.Platform, platform),
Effect.provideService(HostProcess.Architecture, arch),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make((request) => {
requested.push(request.url);
return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
}),
),
);

assert.equal(
yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
"1.4.0",
);
assert.equal(
yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
"1.5.0-nightly.20261101.2",
);
assert.deepStrictEqual(requested, [
"https://updates.example.com/t3code/latest-mac.yml",
"https://updates.example.com/t3code/nightly-linux-arm64.yml",
]);
// A feed for the wrong track is not trusted to mean the requested one.
assert.include(
yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
"Could not read https://updates.example.com/t3code/latest.yml",
);
assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
}),
);

it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
const runWithPolicy = (
updates: ManagedUpdatesPolicy,
input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
) =>
runUpdate({
baseDir: "/unused",
Expand All @@ -85,10 +137,7 @@ it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
// Refusals happen before the update touches the network, the service, or a process.
Layer.mock(BootService.BootService, {}),
Layer.mock(ProcessRunner.ProcessRunner, {}),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected release lookup")),
),
Layer.succeed(HttpClient.HttpClient, httpClient),
),
),
);
Expand Down Expand Up @@ -118,6 +167,24 @@ it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
}
}),
);

it.effect("looks for updates on the policy's mirror, never the public releases", () =>
Effect.gen(function* () {
const requested: string[] = [];
const error = yield* runWithPolicy(
{ mode: "auto", feedUrl: "https://updates.example.com/t3code" },
{ channel: "stable" },
HttpClient.make((request) => {
requested.push(new URL(request.url).origin);
return Effect.succeed(
HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
);
}),
);
assert.include(error.message, "from Example Corp's update mirror");
assert.deepStrictEqual(requested, ["https://updates.example.com"]);
}),
);
});

it.layer(NodeServices.layer)("t3 update launcher", (it) => {
Expand Down
59 changes: 53 additions & 6 deletions apps/server/src/cli/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
cliReleaseIndexPageUrl,
cliReleaseChannelOf,
newestCliReleaseVersion,
updateFeedFileName,
type CliReleaseChannel,
} from "@t3tools/shared/cliRelease";
import * as Console from "effect/Console";
Expand Down Expand Up @@ -33,7 +34,7 @@ import {
} from "../cloud/pinnedRuntime.ts";
import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { managedUpdateRefusal } from "../policy/managedUpdates.ts";
import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
import * as ProcessRunner from "../processRunner.ts";
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
Expand Down Expand Up @@ -94,6 +95,45 @@ export const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(funct
return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
});

/** The version an update mirror's feed file for this platform offers on `channel`. */
export const resolveMirrorVersion = Effect.fn("cli.update.resolve_mirror")(function* (
mirror: { readonly organization: string; readonly feedUrl: string },
channel: CliReleaseChannel,
) {
if (channel === "preview") {
return yield* new CliUpdateError({
reason: `${mirror.organization}'s update mirror has no preview builds.`,
});
}
const httpClient = yield* HttpClient.HttpClient;
const url = `${mirror.feedUrl.replace(/\/+$/, "")}/${updateFeedFileName(
channel === "nightly" ? "nightly" : "latest",
yield* HostProcess.Platform,
yield* HostProcess.Architecture,
)}`;
const unreadable = new CliUpdateError({
reason: `Could not read ${url} from ${mirror.organization}'s update mirror.`,
});
const body = yield* httpClient.get(url).pipe(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap((response) => response.text),
Effect.mapError(() => unreadable),
Effect.timeoutOrElse({
duration: RELEASE_INDEX_TIMEOUT,
orElse: () => Effect.fail(unreadable),
}),
);
const version = /^version:\s*["']?([^"'\s]+)/m.exec(body)?.[1];
if (
version === undefined ||
!isExactServiceVersion(version) ||
cliReleaseChannelOf(version) !== channel
) {
return yield* unreadable;
}
return version;
});

/**
* 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. It is
Expand Down Expand Up @@ -320,6 +360,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
const httpClient = yield* HttpClient.HttpClient;
const service = yield* BootService.BootService;
const policy = yield* ManagedPolicy.ManagedPolicy;
const mirror = managedUpdateMirror(policy.document);

const currentVersion = packageJson.version;
const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
Expand All @@ -338,9 +379,11 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
const progress = createUpdateProgress();
progress.status("Checking for updates...");
const targetVersion = yield* (
input.requestedVersion === undefined
? resolveNewestVersion(channel)
: Effect.succeed(input.requestedVersion)
input.requestedVersion !== undefined
? Effect.succeed(input.requestedVersion)
: mirror === undefined
? resolveNewestVersion(channel)
: resolveMirrorVersion(mirror, channel)
).pipe(Effect.ensuring(Effect.sync(progress.finish)));
const targetChannel = cliReleaseChannelOf(targetVersion);

Expand Down Expand Up @@ -455,7 +498,8 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
httpClient,
platform,
arch,
releaseBaseUrl: environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined,
releaseBaseUrl: mirror?.feedUrl ?? (environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined),
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
requirePublishedRelease: mirror !== undefined,
Comment thread
juliusmarminge marked this conversation as resolved.
Resolved
validate: (paths) =>
runner
.run({
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -489,7 +533,10 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
() =>
Effect.fail(
new CliUpdateError({
reason: `No release archive was published for t3@${targetVersion}.`,
reason:
mirror === undefined
? `No release archive was published for t3@${targetVersion}.`
: `${mirror.organization}'s update mirror has no t3@${targetVersion} for this machine.`,
}),
),
),
Comment thread
juliusmarminge marked this conversation as resolved.
Resolved
Expand Down
33 changes: 33 additions & 0 deletions apps/server/src/cloud/pinnedRuntime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,39 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
}),
);

it.effect("reuses a cached runtime under a mirror only while the mirror lists it", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-mirror-" });
const cached = pinnedRuntimePaths(path, baseDir, version, "linux");
yield* fs.makeDirectory(path.dirname(cached.entryPath), { recursive: true });
yield* fs.writeFileString(cached.entryPath, "#!/bin/sh\n");
yield* fs.writeFileString(cached.sentinelPath, `${version}\n`);
const install = (checksums: string, requests: string[]) =>
ensurePinnedRuntimeInstalled({
baseDir,
version,
fs,
path,
platform: "linux",
arch: "x64",
httpClient: releaseHttpClient(checksums, requests),
releaseBaseUrl: "https://updates.example.com/t3code",
requirePublishedRelease: true,
runner: extractingRunner(fs, path),
validate: () => Effect.void,
});

const withdrawn = yield* install("", []).pipe(Effect.flip);
assert.include(withdrawn.message, `finding ${archiveName} in the t3 release checksums`);
const requests: string[] = [];
assert.equal((yield* install(yield* validChecksums, requests)).entryPath, cached.entryPath);
// Listed, so the cached runtime is used without downloading it again.
assert.deepEqual(requests, [`https://updates.example.com/t3code/v${version}/SHA256SUMS`]);
}),
);

it.effect("preserves a completed runtime when validation fails", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand Down
56 changes: 38 additions & 18 deletions apps/server/src/cloud/pinnedRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
cliArchivePlatformKey,
cliArchiveTarCommand,
cliReleaseDownloadBaseUrl,
type CliArchivePlatformKey,
parseChecksums,
} from "@t3tools/shared/cliRelease";

Expand Down Expand Up @@ -111,6 +112,8 @@ interface PinnedRuntimeInstallInput {
readonly arch: string;
readonly httpClient: HttpClient.HttpClient;
readonly releaseBaseUrl?: string | undefined;
/** Reuse a cached runtime only while the release source still lists it, as a policy mirror does. */
readonly requirePublishedRelease?: boolean;
readonly onProgress?: (progress: PinnedRuntimeProgress) => void;
}

Expand Down Expand Up @@ -178,25 +181,8 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun
});
}
const httpClient = input.httpClient;
const baseUrl = cliReleaseDownloadBaseUrl(input.version, input.releaseBaseUrl);
const fileName = cliArchiveFileName(input.version, platformKey);

input.onProgress?.({ stage: "download", received: 0, total: undefined });
const checksums = parseChecksums(
new TextDecoder().decode(
yield* fetchReleaseAsset(
httpClient,
`${baseUrl}/${CLI_RELEASE_CHECKSUMS_FILE}`,
"downloading the t3 release checksums",
),
),
);
const expected = checksums.get(fileName);
if (expected === undefined) {
return yield* new PinnedRuntimeInstallError({
step: `finding ${fileName} in the t3 release checksums`,
});
}
const { baseUrl, fileName, expected } = yield* publishedArchive(input, platformKey);
const archive = yield* fetchReleaseAsset(
httpClient,
`${baseUrl}/${fileName}`,
Expand Down Expand Up @@ -248,6 +234,31 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun
yield* fs.remove(archivePath, { force: true }).pipe(Effect.ignore);
});

/** The release's archive for this machine and its checksum; fails when the release lists none. */
const publishedArchive = Effect.fn("cloud.pinned_runtime.published_archive")(function* (
input: PinnedRuntimeInstallInput,
platformKey: CliArchivePlatformKey,
) {
const baseUrl = cliReleaseDownloadBaseUrl(input.version, input.releaseBaseUrl);
const fileName = cliArchiveFileName(input.version, platformKey);
const checksums = parseChecksums(
new TextDecoder().decode(
yield* fetchReleaseAsset(
input.httpClient,
`${baseUrl}/${CLI_RELEASE_CHECKSUMS_FILE}`,
"downloading the t3 release checksums",
),
),
);
const expected = checksums.get(fileName);
if (expected === undefined) {
return yield* new PinnedRuntimeInstallError({
step: `finding ${fileName} in the t3 release checksums`,
});
}
return { baseUrl, fileName, expected };
});

const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
input: PinnedRuntimeInstallInput,
) {
Expand All @@ -265,6 +276,15 @@ const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(
const alreadyPinned =
entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
if (alreadyPinned) {
if (input.requirePublishedRelease === true) {
const platformKey = cliArchivePlatformKey(input.platform, input.arch);
if (platformKey === undefined) {
return yield* new PinnedRuntimeInstallError({
step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
});
}
yield* publishedArchive(input, platformKey);
}
input.onProgress?.({ stage: "cached" });
yield* input.validate(paths);
return paths;
Expand Down
Loading
Loading