Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 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
45 changes: 30 additions & 15 deletions apps/server/src/cli/invocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,22 +42,24 @@ const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(I
* `T3CODE_NPM_LAUNCHER_PATH` is inherited by child shells, so accept it only for this package
* version to avoid claiming another `t3` invocation is the npm install.
*/
export const resolveEntryPath = Effect.gen(function* () {
export const resolveNpmLauncherPath = Effect.gen(function* () {
const npmLauncher = (yield* HostProcess.Environment).T3CODE_NPM_LAUNCHER_PATH?.trim();
if (npmLauncher) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const manifest = yield* fs
.readFileString(path.join(path.dirname(npmLauncher), "../package.json"))
.pipe(Effect.flatMap(decodeInstallManifest), Effect.option);
if (
Option.isSome(manifest) &&
manifest.value.name === "t3" &&
manifest.value.version === packageJson.version
) {
return npmLauncher;
}
}
if (!npmLauncher) return Option.none<string>();
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const manifest = yield* fs
.readFileString(path.join(path.dirname(npmLauncher), "../package.json"))
.pipe(Effect.flatMap(decodeInstallManifest), Effect.option);
return Option.isSome(manifest) &&
manifest.value.name === "t3" &&
manifest.value.version === packageJson.version
? Option.some(npmLauncher)
: Option.none<string>();
});

export const resolveEntryPath = Effect.gen(function* () {
const npmLauncher = yield* resolveNpmLauncherPath;
if (Option.isSome(npmLauncher)) return npmLauncher.value;
if (yield* HostProcess.IsExecutable) return yield* HostProcess.ExecutablePath;
return (yield* HostProcess.Arguments)[1] ?? "";
});
Expand Down Expand Up @@ -120,6 +122,19 @@ export const resolveCliCommand = (subcommand: string) =>
const shellWord = (value: string) =>
/^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;

/** The npm launcher starts the runtime named by its package version, so only the package manager moves it. */
export function packageUpdateCommand(installation: ServerInstallation, version: string): string {
const spec = `t3@${version}`;
switch (installation.kind) {
case "npm-global":
return `npm install --global --prefix ${shellWord(installation.prefix)} ${spec}`;
case "pnpm-dlx":
return `pnpm dlx ${spec}`;
default:
return `${installation.kind} ${spec}`;
}
}

/** PowerShell also treats typographic quotes as delimiters; escape them and suppress expansion. */
const powershellWord = (value: string) =>
`"${value
Expand Down
132 changes: 131 additions & 1 deletion apps/server/src/cli/update.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/cli";
import { HttpClient, HttpClientResponse } from "effect/http";
import { afterEach, vi } from "vite-plus/test";

import { repointLauncher, resolveLauncherPath, resolveNewestVersion } from "./update.ts";
import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
import {
repointLauncher,
resolveLauncherPath,
resolveNewestVersion,
updateCommand,
} from "./update.ts";

afterEach(() => vi.restoreAllMocks());

Expand Down Expand Up @@ -128,3 +140,121 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
}).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
);
});

it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 update closing hint", (it) => {
it.effect("tells npm users how to move the t3 their package still pins", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
const baseDir = path.join(root, "home");
const prefix = path.join(root, "node");
const npmGlobal = path.join(prefix, "lib/node_modules/t3/bin/t3.mjs");
const npx = path.join(root, ".npm/_npx/abc/node_modules/t3/bin/t3.mjs");
const projectLocal = path.join(root, "project/node_modules/t3/bin/t3.mjs");
for (const launcher of [npmGlobal, npx, projectLocal]) {
yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
yield* fs.writeFileString(launcher, "");
yield* fs.writeFileString(
path.join(path.dirname(launcher), "../package.json"),
`{"name":"t3","version":"${packageJson.version}","bin":{"t3":"./bin/t3.mjs"}}`,
);
}
yield* fs.makeDirectory(path.join(prefix, "bin"));
yield* fs.symlink(npmGlobal, path.join(prefix, "bin/t3"));
const realPrefix = yield* fs.realPath(prefix);
// Already-downloaded runtimes skip the release download; update still runs them for --version.
const entryFor = (version: string) => path.join(baseDir, "runtime/versions", version, "t3");
for (const version of ["9.9.9", packageJson.version]) {
yield* fs.makeDirectory(path.dirname(entryFor(version)), { recursive: true });
yield* fs.writeFileString(entryFor(version), `#!/bin/sh\necho "t3 v${version}"\n`);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
yield* fs.chmod(entryFor(version), 0o755);
yield* fs.writeFileString(
path.join(path.dirname(entryFor(version)), ".install-complete"),
version,
);
}

const update = (
version: string,
launcher: string | undefined,
status: BootService.BootServiceStatus,
) => {
vi.spyOn(BootService, "layer").mockReturnValue(
Layer.succeed(
BootService.BootService,
BootService.BootService.of({
status: Effect.succeed(status),
withStopped: (operation) => operation,
restart: Effect.succeed("restarted"),
install: () =>
Effect.succeed({
program: [entryFor(version), "__service-launcher"],
baseDir,
unitPath: status.unitPath,
logPath: status.logPath,
}),
uninstall: Effect.succeed(false),
}),
),
);
return Command.runWith(updateCommand, { version: packageJson.version })([
version,
"--base-dir",
baseDir,
"--yes",
]).pipe(
Effect.andThen(TestConsole.logLines),
Effect.map((lines) => lines.join("\n")),
Effect.provideService(
HostProcess.Environment,
launcher === undefined ? {} : { T3CODE_NPM_LAUNCHER_PATH: launcher },
),
Effect.provideService(HostProcess.IsExecutable, false),
Effect.provideService(HostProcess.Arguments, ["node", path.join(root, "missing.mjs")]),
Effect.provideService(HostProcess.HomeDirectory, root),
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
Layer.fresh(TestConsole.layer),
),
),
);
};
const noService = {
supported: true,
installed: false,
current: false,
unitPath: path.join(root, "t3code.service"),
logPath: path.join(root, "boot-service.log"),
} as const;
const stillRuns = `The t3 npm package still runs ${packageJson.version}.`;

for (const [launcher, expected] of [
[
npmGlobal,
`${stillRuns} Run \`npm install --global --prefix ${realPrefix} t3@9.9.9\` to move to 9.9.9.`,
],
[npx, `${stillRuns} Run \`npx t3@9.9.9\` to move to 9.9.9.`],
[
projectLocal,
`${stillRuns} Update it to t3@9.9.9 with the package manager that installed it.`,
],
[undefined, `Run ${entryFor("9.9.9")}\n`],
] as const) {
const output = yield* update("9.9.9", launcher, noService);
assert.include(output, ` ${expected}`, launcher ?? "standalone");
}

// Updating only the service to the package's own version needs no package update.
const output = yield* update(packageJson.version, npmGlobal, {
...noService,
installed: true,
installedVersion: "0.0.1",
installedBaseDir: baseDir,
});
assert.include(output, ` Run ${entryFor(packageJson.version)}\n`);
assert.notInclude(output, stillRuns);
}).pipe(Effect.scoped),
);
});
36 changes: 31 additions & 5 deletions apps/server/src/cli/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/ser
import * as ProcessRunner from "../processRunner.ts";
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
import {
packageUpdateCommand,
resolveNpmLauncherPath,
resolveServerInstallation,
} from "./invocation.ts";
import { createUpdateProgress } from "./updateProgress.ts";
import * as CliService from "./service.ts";

Expand Down Expand Up @@ -185,6 +190,26 @@ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(functio
return undefined;
});

/** npm's `t3` keeps starting the runtime its package version names, not the one just downloaded. */
const resolveNextStep = Effect.fn("cli.update.resolve_next_step")(function* (input: {
readonly repointed: boolean;
readonly entryPath: string;
readonly targetVersion: string;
}) {
if (input.repointed) return "Run t3 to get started.";
if (input.targetVersion === packageJson.version) return `Run ${input.entryPath}`;
const stillRuns = `The t3 npm package still runs ${packageJson.version}.`;
const installation = yield* resolveServerInstallation;
if (installation !== null) {
const command = packageUpdateCommand(installation, input.targetVersion);
return `${stillRuns} Run \`${command}\` to move to ${input.targetVersion}.`;
}
if (Option.isSome(yield* resolveNpmLauncherPath)) {
return `${stillRuns} Update it to t3@${input.targetVersion} with the package manager that installed it.`;
}
return `Run ${input.entryPath}`;
});

const updateFlags = {
...projectLocationFlags,
channel: Flag.Literals("channel", CLI_RELEASE_CHANNELS).pipe(
Expand Down Expand Up @@ -517,11 +542,12 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
}

progress.success(`Installed T3 Code ${targetVersion}`);
if (Option.isSome(repointed)) {
yield* Console.log(" Run t3 to get started.\n");
} else {
yield* Console.log(` Run ${runtime.entryPath}\n`);
}
const nextStep = yield* resolveNextStep({
repointed: Option.isSome(repointed),
entryPath: runtime.entryPath,
targetVersion,
});
yield* Console.log(` ${nextStep}\n`);
if (servicePlan?.handedOff === true) {
yield* Console.log(
` Background service switching to ${targetVersion} from a separate systemd unit, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,
Expand Down
Loading