Skip to content
TypeScript

fix(server): startup no longer hangs on a shell stuck in the kernel (#27938)

AdEx-Partners-DEda3f97299f25
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
index 79344567fcd..fbf4bf9713f 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
@@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Deferred from "effect/Deferred";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -14,6 +15,7 @@ import * as Schema from "effect/Schema";
import * as Option from "effect/Option";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+import * as TestClock from "effect/testing/TestClock";
import * as NodeOS from "node:os";
import { vi } from "vite-plus/test";
@@ -60,6 +62,22 @@ function makeProcess(output: string, exitCode = 0): ChildProcessSpawner.ChildPro
});
}
+function makeHungProcess(): ChildProcessSpawner.ChildProcessHandle {
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(124),
+ stdout: Stream.never,
+ stderr: Stream.never,
+ all: Stream.never,
+ exitCode: Effect.never,
+ isRunning: Effect.succeed(true),
+ kill: () => Effect.never,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ });
+}
+
function withProcessEnv<A, E, R>(
env: NodeJS.ProcessEnv,
effect: Effect.Effect<A, E, R>,
@@ -673,6 +691,25 @@ describe("DesktopShellEnvironment", () => {
}),
);
+ it.effect("gives up on a Windows shell that survives the kill", () =>
+ Effect.gen(function* () {
+ const commands: Array<string> = [];
+ const fiber = yield* runShellEnvironment({
+ env: { PATH: "C:\\Windows", APPDATA: "C:\\Roaming" },
+ platform: "win32",
+ handler: () => "",
+ processSpawner: ChildProcessSpawner.make((command) => {
+ commands.push(command._tag === "StandardCommand" ? command.command : "");
+ return Effect.acquireRelease(Effect.succeed(makeHungProcess()), () => Effect.never);
+ }),
+ }).pipe(Effect.forkChild({ startImmediately: true }));
+
+ for (let probe = 0; probe < 4; probe++) yield* TestClock.adjust("5 seconds");
+ yield* Fiber.join(fiber);
+ assert.deepEqual([...new Set(commands)], ["pwsh.exe", "powershell.exe"]);
+ }),
+ );
+
it.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = { Path: "C:\\Windows\\System32" };
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts
index 556f7090b42..37826f8ee5a 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts
@@ -8,6 +8,7 @@ import {
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Deferred from "effect/Deferred";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
@@ -259,7 +260,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
readonly shell?: boolean;
}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const output = yield* Effect.scoped(
+ const fiber = yield* Effect.scoped(
Effect.gen(function* () {
const child = yield* spawner.spawn(
ChildProcess.make(input.command, input.args, {
@@ -302,7 +303,12 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(
DesktopShellEnvironmentCommandError: (error) =>
logShellEnvironmentCommandError(error).pipe(Effect.as("")),
}),
+ Effect.forkDetach,
+ );
+ const output = yield* Fiber.join(fiber).pipe(
Effect.timeoutOption(input.timeout),
+ // Interrupting awaits the child's exit, which a shell stuck in the kernel never reaches.
+ Effect.ensuring(Fiber.interrupt(fiber).pipe(Effect.forkDetach)),
);
if (Option.isSome(output)) {
return output.value;
diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts
index 6ae7401a488..e3af0855ebf 100644
--- a/packages/shared/src/shell.test.ts
+++ b/packages/shared/src/shell.test.ts
@@ -9,6 +9,7 @@ import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Option from "effect/Option";
+import * as TestClock from "effect/testing/TestClock";
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
@@ -42,10 +43,12 @@ const decodeDesktopHostMessage = Schema.decodeUnknownSync(DesktopHostTelemetryMe
const nativeProbe = vi.hoisted(() => ({
execFile: vi.fn<typeof import("node:child_process").execFile>(),
+ original: undefined as unknown as typeof import("node:child_process").execFile,
}));
vi.mock("node:child_process", async (importOriginal) => {
const original = await importOriginal<typeof import("node:child_process")>();
+ nativeProbe.original = original.execFile;
return { ...original, execFile: nativeProbe.execFile.mockImplementation(original.execFile) };
});
@@ -275,7 +278,7 @@ describe("readEnvironmentFromWindowsShell", () => {
Effect.gen(function* () {
const started = Promise.withResolvers<void>();
const kill = vi.fn(() => true);
- const child = { kill } as unknown as ReturnType<
+ const child = { kill, unref: vi.fn() } as unknown as ReturnType<
typeof import("node:child_process").execFile
>;
const execFile = nativeProbe.execFile;
@@ -297,6 +300,32 @@ describe("readEnvironmentFromWindowsShell", () => {
}),
);
+ effectIt.effect("gives up on a shell that survives the kill and holds stdout open", () =>
+ Effect.gen(function* () {
+ const stdout = { destroy: vi.fn() };
+ const unref = vi.fn();
+ const child = { kill: vi.fn(() => true), stdout, unref } as unknown as ReturnType<
+ typeof import("node:child_process").execFile
+ >;
+ const execFile = nativeProbe.execFile;
+ execFile.mockClear();
+ execFile.mockImplementation(() => child);
+ try {
+ const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
+ yield* Effect.yieldNow;
+ yield* TestClock.adjust("6 seconds");
+ expect(execFile.mock.calls.map(([file]) => file)).toEqual(["pwsh.exe", "powershell.exe"]);
+ yield* TestClock.adjust("6 seconds");
+ expect(yield* Fiber.join(fiber)).toEqual({});
+ expect(stdout.destroy).toHaveBeenCalledTimes(2);
+ expect(unref).toHaveBeenCalledTimes(2);
+ } finally {
+ execFile.mockReset();
+ execFile.mockImplementation(nativeProbe.original);
+ }
+ }),
+ );
+
effectIt.effect("extracts environment variables from a PowerShell command", () =>
Effect.gen(function* () {
const execFile = vi.fn<
diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts
index f3aaa4a11c4..28b666ce055 100644
--- a/packages/shared/src/shell.ts
+++ b/packages/shared/src/shell.ts
@@ -5,6 +5,7 @@ import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as Cache from "effect/Cache";
import * as Clock from "effect/Clock";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -17,6 +18,9 @@ const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
const WINDOWS_PATH_DELIMITER = ";";
const POSIX_PATH_DELIMITER = ":";
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
+const WINDOWS_SHELL_PROBE_TIMEOUT_MS = 5000;
+// A shell stuck in the kernel survives the kill and holds stdout, so execFile's callback never fires.
+const WINDOWS_SHELL_PROBE_DEADLINE = Duration.millis(WINDOWS_SHELL_PROBE_TIMEOUT_MS + 1000);
type ExecFileSyncLike = (
file: string,
@@ -360,6 +364,9 @@ const execWindowsEnvironmentProbe = (
}
return Effect.sync(() => {
child.kill();
+ child.stdout?.destroy();
+ child.stderr?.destroy();
+ child.unref();
});
});
@@ -380,7 +387,10 @@ export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentF
command,
];
for (const shell of WINDOWS_SHELL_CANDIDATES) {
- const output = yield* execFile(shell, args, { encoding: "utf8", timeout: 5000 });
+ const output = yield* execFile(shell, args, {
+ encoding: "utf8",
+ timeout: WINDOWS_SHELL_PROBE_TIMEOUT_MS,
+ }).pipe(Effect.timeoutOption(WINDOWS_SHELL_PROBE_DEADLINE), Effect.map(Option.flatten));
if (Option.isNone(output)) continue;
const environment: Partial<Record<string, string>> = {};