Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
145 changes: 85 additions & 60 deletions apps/server/src/cli/uninstall.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
Expand All @@ -28,64 +27,80 @@

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

it.live("reports failure when the Windows cleanup shell cannot start", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" });
const runtimeDir = path.join(baseDir, "runtime");
yield* fs.makeDirectory(runtimeDir);
vi.spyOn(BootService, "layer").mockReturnValue(
Layer.succeed(
BootService.BootService,
BootService.BootService.of({
status: Effect.succeed({
supported: false,
installed: false,
current: false,
unitPath: "",
logPath: "",
it.live(
"runs the Windows cleanup from System32 and reports failure when its shell cannot start",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" });
const runtimeDir = path.join(baseDir, "runtime");
yield* fs.makeDirectory(runtimeDir);
vi.spyOn(BootService, "layer").mockReturnValue(
Layer.succeed(
BootService.BootService,
BootService.BootService.of({
status: Effect.succeed({
supported: false,
installed: false,
current: false,
unitPath: "",
logPath: "",
}),
withStopped: (operation) => operation,
restart: Effect.die("unexpected restart"),
install: () => Effect.die("unexpected install"),
uninstall: Effect.die("unexpected uninstall"),
}),
withStopped: (operation) => operation,
restart: Effect.die("unexpected restart"),
install: () => Effect.die("unexpected install"),
uninstall: Effect.die("unexpected uninstall"),
}),
),
);
const actual = yield* Effect.promise(() =>
vi.importActual<typeof import("node:child_process")>("node:child_process"),
);
const spawn = actual.spawn;
const failedSpawn = new Promise<Error>((resolve) => {
vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => {
const child = spawn(...args);
// Observe the real spawn error without letting it terminate the test runner.
child.once("error", resolve);
return child;
),
);
const actual = yield* Effect.promise(() =>
vi.importActual<typeof import("node:child_process")>("node:child_process"),
);
const spawn = actual.spawn;
const spawned: Array<Parameters<typeof spawn>> = [];
const failedSpawn = new Promise<Error>((resolve) => {
vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => {
spawned.push(args);
const child = spawn(...args);
// Observe the real spawn error without letting it terminate the test runner.
child.once("error", resolve);
return child;
});
});
});
const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([
"--base-dir",
baseDir,
"--yes",
]).pipe(
Effect.result,
Effect.provideService(HostProcess.Environment, {
ComSpec: path.join(baseDir, "missing-cmd.exe"),
}),
Effect.provideService(HostProcess.Platform, "win32"),
Effect.provideService(HostProcess.IsExecutable, false),
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
Layer.fresh(TestConsole.layer),
const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([
"--base-dir",
baseDir,
"--yes",
]).pipe(
Effect.result,
Effect.provideService(HostProcess.Environment, {
ComSpec: path.join(baseDir, "missing-cmd.exe"),
SystemRoot: String.raw`C:\Windows`,
}),
Effect.provideService(HostProcess.Platform, "win32"),
Effect.provideService(HostProcess.IsExecutable, false),
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
Layer.fresh(TestConsole.layer),
),
),
),
);
yield* Effect.promise(() => failedSpawn);
expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure");
}).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))),
);
yield* Effect.promise(() => failedSpawn);
expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure");
const [, args, options] = spawned[0]!;
expect(args.at(-1)).toBe(
'""%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""',
);
expect(options).toMatchObject({
cwd: String.raw`C:\Windows\System32`,
env: {
T3_UNINSTALL_PING: String.raw`C:\Windows\System32\ping.exe`,
T3_UNINSTALL_RUNTIME: runtimeDir,
},
});
}).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))),
);

it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => {
Expand Down Expand Up @@ -187,7 +202,7 @@
const script = path.join(scriptDir, "t3");
yield* fs.makeDirectory(scriptDir);
yield* fs.writeFileString(script, posixLauncherScript(exe), { mode: 0o755 });
assert.equal(

Check failure on line 205 in apps/server/src/cli/uninstall.test.ts

View workflow job for this annotation

GitHub Actions / Test (apps/server)

src/cli/uninstall.test.ts > t3 uninstall launcher > claims only a launcher that points into this home's runtime tree

AssertionError: expected undefined to equal 'C:\Users\runneradmin\AppData\Local\Te…' - Expected: "C:\\Users\\runneradmin\\AppData\\Local\\Temp\\t3-uninstall-paifM6\\script-bin\\t3" + Received: undefined ❯ src/cli/uninstall.test.ts:205:14 ❯ ~effect/Effect/successCont ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a_aba80c29b49819a04948202da07c645e/node_modules/effect/src/internal/effect.ts:1498:28 ❯ ~effect/Effect/evaluate ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a_aba80c29b49819a04948202da07c645e/node_modules/effect/src/internal/core.ts:586:30 ❯ FiberImpl.runLoop ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a_aba80c29b49819a04948202da07c645e/node_modules/effect/src/internal/effect.ts:711:43 ❯ FiberImpl.evaluate ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a_aba80c29b49819a04948202da07c645e/node_modules/effect/src/internal/effect.ts:637:23 ❯ FiberImpl.evaluate ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a_aba80c29b49819a04948202da07c645e/node_modules/effect/src/internal/effect.ts:626:29 ❯ ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a_aba80c29b49819a04948202da07c645e/node_modules/effect/src/internal/effect.ts:1226:17 ❯ ../../node_modules/.pnpm/effect@4.1.5_patch_hash=14a_aba80c29b49819a04948202da07c645e/node_modules/effect/src/Effect.ts:27941:13
yield* findOwnedLauncher({ launchedAs: exe, versionsDir }).pipe(
Effect.provideService(HostProcess.Environment, { PATH: scriptDir }),
),
Expand Down Expand Up @@ -277,7 +292,7 @@
});

it.live.runIf(HostProcess.Platform.defaultValue() === "win32")(
"t3 uninstall has cmd.exe remove the runtime directory, preserving spaces and literal environment-variable syntax",
"t3 uninstall has cmd.exe remove the runtime directory with System32 tools, preserving spaces and literal environment-variable syntax",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand All @@ -287,10 +302,19 @@
yield* fs.makeDirectory(path.join(runtimeDir, "versions", "1.0.0"), { recursive: true });
yield* fs.writeFileString(path.join(runtimeDir, "versions", "1.0.0", "t3.exe"), "");

const child = spawnWindowsRemoval(
yield* Config.String("ComSpec").pipe(Config.withDefault("cmd.exe")),
runtimeDir,
// The directory `t3 uninstall` is run from holds its own `ping`, which must stay unused.
const marker = path.join(root, "ping-ran.txt");
yield* fs.writeFileString(path.join(root, "ping.cmd"), '@echo ran>"%~dp0ping-ran.txt"\r\n');
yield* Effect.acquireRelease(
Effect.sync(() => {
const previous = process.cwd();
process.chdir(root);
return previous;
}),
(previous) => Effect.sync(() => process.chdir(previous)),
);

const child = spawnWindowsRemoval(yield* HostProcess.Environment, runtimeDir);
yield* Effect.callback<void, Error>((resume) => {
child.once("error", (error) => resume(Effect.fail(error)));
child.once("exit", (code) =>
Expand All @@ -299,5 +323,6 @@
});

assert.isFalse(yield* fs.exists(runtimeDir));
assert.isFalse(yield* fs.exists(marker));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
20 changes: 10 additions & 10 deletions apps/server/src/cli/uninstall.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
// Windows cleanup must outlive this executable to delete its directory; scoped ChildProcess kills children on exit.
import * as NodeChildProcess from "node:child_process";
import * as NodePath from "node:path";

import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Console from "effect/Console";
Expand Down Expand Up @@ -126,19 +127,22 @@ export const findRecordedLaunchers = Effect.fn("cli.uninstall.find_recorded_laun
return owned;
});

// cmd.exe needs verbatim quoting and a literal path, with delayed expansion disabled.
export function spawnWindowsRemoval(comspec: string, dir: string) {
// cmd.exe needs verbatim quoting and literal paths, with delayed expansion disabled. The shell
// starts in System32 and runs ping from there, whatever directory `t3 uninstall` was run in.
export function spawnWindowsRemoval(environment: NodeJS.ProcessEnv, dir: string) {
const ping = windowsSystem32Path(environment, "ping.exe");
return NodeChildProcess.spawn(
comspec,
environment["ComSpec"] ?? environment["COMSPEC"] ?? windowsSystem32Path(environment, "cmd.exe"),
[
"/d",
"/v:off",
"/s",
"/c",
'"ping -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""',
'""%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""',
],
{
env: { ...process.env, T3_UNINSTALL_RUNTIME: dir },
cwd: NodePath.win32.dirname(ping),
env: { ...process.env, T3_UNINSTALL_PING: ping, T3_UNINSTALL_RUNTIME: dir },
windowsVerbatimArguments: true,
detached: true,
stdio: "ignore",
Expand Down Expand Up @@ -282,15 +286,11 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: {
// Windows refuses to unlink this running executable; a detached shell removes it after exit.
if (platform === "win32") {
const runtimeDir = plan.runtimeDir;
const comspec =
environment["ComSpec"] ??
environment["COMSPEC"] ??
windowsSystem32Path(environment, "cmd.exe");
const notScheduled = () =>
new CliUninstallError({
reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`,
});
yield* awaitDetachedSpawn(() => spawnWindowsRemoval(comspec, runtimeDir)).pipe(
yield* awaitDetachedSpawn(() => spawnWindowsRemoval(environment, runtimeDir)).pipe(
Effect.mapError(notScheduled),
);
yield* Console.log(`${runtimeDir} will be removed once t3 exits.`);
Expand Down
Loading