Skip to content

Commit f460ddb

Browse files
fix(server): probe the Windows startup environment asynchronously (pingdotgg#21720)
1 parent b9aaff4 commit f460ddb

3 files changed

Lines changed: 268 additions & 108 deletions

File tree

‎apps/server/src/os-jank.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second
143143
yield* fixPath().pipe(
144144
Effect.provideService(HostProcess.Platform, "win32"),
145145
Effect.provideService(HostProcess.Environment, env),
146-
Effect.provideService(WindowsShellEnvironment, () => ({ PATH: "C:\\Tools" })),
146+
Effect.provideService(WindowsShellEnvironment, () => Effect.succeed({ PATH: "C:\\Tools" })),
147147
Effect.provideService(CommandAvailability, () => Effect.succeed(true)),
148148
Effect.provide(NodeServices.layer),
149149
);

‎packages/shared/src/shell.test.ts‎

Lines changed: 214 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
33
import { it as effectIt } from "@effect/vitest";
44
import * as HostProcess from "@t3tools/shared/HostProcess";
55
import * as Effect from "effect/Effect";
6+
import * as Fiber from "effect/Fiber";
67
import * as FileSystem from "effect/FileSystem";
78
import * as Path from "effect/Path";
9+
import * as Option from "effect/Option";
810
import * as NodeChildProcess from "node:child_process";
911
import * as NodeFS from "node:fs";
1012
import * as NodeOS from "node:os";
@@ -33,13 +35,26 @@ import {
3335
XcodeGitLocation,
3436
} from "./shell.ts";
3537

38+
const nativeProbe = vi.hoisted(() => ({
39+
execFile: vi.fn<typeof import("node:child_process").execFile>(),
40+
}));
41+
42+
vi.mock("node:child_process", async (importOriginal) => {
43+
const original = await importOriginal<typeof import("node:child_process")>();
44+
return { ...original, execFile: nativeProbe.execFile.mockImplementation(original.execFile) };
45+
});
46+
3647
const withWindowsEnvironmentMocks = <A, E, R>(
3748
effect: Effect.Effect<A, E, R>,
38-
readEnvironment: WindowsShellEnvironmentReader,
49+
readEnvironment: (
50+
...args: Parameters<WindowsShellEnvironmentReader>
51+
) => Partial<Record<string, string>>,
3952
commandAvailable: CommandAvailabilityChecker,
4053
) =>
4154
effect.pipe(
42-
Effect.provideService(WindowsShellEnvironment, readEnvironment),
55+
Effect.provideService(WindowsShellEnvironment, (...args) =>
56+
Effect.sync(() => readEnvironment(...args)),
57+
),
4358
Effect.provideService(CommandAvailability, commandAvailable),
4459
);
4560

@@ -178,49 +193,207 @@ describe("mergePathEntries", () => {
178193
});
179194

180195
describe("readEnvironmentFromWindowsShell", () => {
181-
it("strips CRLF delimiters from captured PowerShell values", () => {
182-
const execFile = vi.fn<
183-
(
184-
file: string,
185-
args: ReadonlyArray<string>,
186-
options: { encoding: "utf8"; timeout: number },
187-
) => string
188-
>(
189-
() =>
190-
"__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
191-
);
196+
effectIt.effect("yields while the native shell probe is pending", () =>
197+
Effect.gen(function* () {
198+
let completed = false;
199+
const [environment, completedBeforeProbeReturned] = yield* Effect.all(
200+
[
201+
readEnvironmentFromWindowsShell(["PATH"]).pipe(
202+
Effect.tap(() =>
203+
Effect.sync(() => {
204+
completed = true;
205+
}),
206+
),
207+
),
208+
Effect.sync(() => completed),
209+
],
210+
{ concurrency: 2 },
211+
);
212+
expect(completedBeforeProbeReturned).toBe(false);
213+
expect(environment).toBeTypeOf("object");
214+
}),
215+
);
192216

193-
expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
194-
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
195-
});
217+
effectIt.layer(NodeServices.layer)("synchronous spawn failures", (it) => {
218+
it.effect("tries both shells and preserves baseline PATH repair", () =>
219+
Effect.gen(function* () {
220+
const execFile = nativeProbe.execFile;
221+
execFile.mockImplementationOnce(() => {
222+
throw new Error("spawn EPERM");
223+
});
224+
execFile.mockImplementationOnce(() => {
225+
throw new Error("spawn EINVAL");
226+
});
227+
try {
228+
const patch = yield* resolveWindowsEnvironment({
229+
PATH: "C:\\Windows",
230+
APPDATA: "C:\\Roaming",
231+
}).pipe(Effect.provideService(CommandAvailability, () => Effect.succeed(true)));
232+
expect(patch).toEqual({ PATH: "C:\\Windows;C:\\Roaming\\npm" });
233+
expect(execFile.mock.calls.slice(-2).map(([file]) => file)).toEqual([
234+
"pwsh.exe",
235+
"powershell.exe",
236+
]);
237+
} finally {
238+
execFile.mockClear();
239+
}
240+
}),
241+
);
196242
});
197243

198-
it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
199-
const execFile = vi.fn<
200-
(
201-
file: string,
202-
args: ReadonlyArray<string>,
203-
options: { encoding: "utf8"; timeout: number },
204-
) => string
205-
>((file) => {
206-
if (file === "pwsh.exe") {
207-
throw new Error("spawn pwsh.exe ENOENT");
208-
}
209-
return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
210-
});
244+
effectIt.effect("returns an empty environment after both shell candidates fail", () =>
245+
Effect.gen(function* () {
246+
const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
247+
expect(yield* readEnvironmentFromWindowsShell(["PATH"], {}, execFile)).toEqual({});
248+
expect(execFile).toHaveBeenCalledTimes(2);
249+
}),
250+
);
211251

212-
expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
213-
PATH: "C:\\Tools",
214-
});
215-
expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
216-
encoding: "utf8",
217-
timeout: 5000,
218-
});
219-
expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
220-
encoding: "utf8",
221-
timeout: 5000,
222-
});
223-
});
252+
effectIt.effect("does not launch a shell when no variables are requested", () =>
253+
Effect.gen(function* () {
254+
const execFile = vi.fn(() => Effect.succeed(Option.none<string>()));
255+
expect(yield* readEnvironmentFromWindowsShell([], {}, execFile)).toEqual({});
256+
expect(execFile).not.toHaveBeenCalled();
257+
}),
258+
);
259+
260+
effectIt.effect(
261+
"kills the native probe child on interruption without trying the next shell",
262+
() =>
263+
Effect.gen(function* () {
264+
const started = Promise.withResolvers<void>();
265+
const kill = vi.fn(() => true);
266+
const child = { kill } as unknown as ReturnType<
267+
typeof import("node:child_process").execFile
268+
>;
269+
const execFile = nativeProbe.execFile;
270+
execFile.mockClear();
271+
execFile.mockImplementationOnce(() => {
272+
started.resolve();
273+
return child;
274+
});
275+
try {
276+
const fiber = yield* readEnvironmentFromWindowsShell(["PATH"]).pipe(Effect.forkChild);
277+
yield* Effect.promise(() => started.promise);
278+
yield* Fiber.interrupt(fiber);
279+
expect(kill).toHaveBeenCalledTimes(1);
280+
expect(execFile).toHaveBeenCalledTimes(1);
281+
expect(execFile.mock.calls[0]?.[0]).toBe("pwsh.exe");
282+
} finally {
283+
execFile.mockClear();
284+
}
285+
}),
286+
);
287+
288+
effectIt.effect("extracts environment variables from a PowerShell command", () =>
289+
Effect.gen(function* () {
290+
const execFile = vi.fn<
291+
(
292+
file: string,
293+
args: ReadonlyArray<string>,
294+
options: { encoding: "utf8"; timeout: number },
295+
) => string
296+
>(
297+
() =>
298+
"__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
299+
);
300+
301+
expect(
302+
yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
303+
Effect.try(() => execFile(...args)).pipe(Effect.option),
304+
),
305+
).toEqual({
306+
PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
307+
});
308+
expect(execFile).toHaveBeenCalledWith(
309+
"pwsh.exe",
310+
expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
311+
{ encoding: "utf8", timeout: 5000 },
312+
);
313+
}),
314+
);
315+
316+
effectIt.effect("strips CRLF delimiters from captured PowerShell values", () =>
317+
Effect.gen(function* () {
318+
const execFile = vi.fn<
319+
(
320+
file: string,
321+
args: ReadonlyArray<string>,
322+
options: { encoding: "utf8"; timeout: number },
323+
) => string
324+
>(
325+
() =>
326+
"__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
327+
);
328+
329+
expect(
330+
yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
331+
Effect.try(() => execFile(...args)).pipe(Effect.option),
332+
),
333+
).toEqual({
334+
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
335+
});
336+
}),
337+
);
338+
339+
effectIt.effect("omits -NoProfile when loadProfile is enabled", () =>
340+
Effect.gen(function* () {
341+
const execFile = vi.fn<
342+
(
343+
file: string,
344+
args: ReadonlyArray<string>,
345+
options: { encoding: "utf8"; timeout: number },
346+
) => string
347+
>(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
348+
349+
expect(
350+
yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
351+
Effect.try(() => execFile(...args)).pipe(Effect.option),
352+
),
353+
).toEqual({
354+
PATH: "C:\\Tools",
355+
});
356+
expect(execFile).toHaveBeenCalledWith(
357+
"pwsh.exe",
358+
expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
359+
{ encoding: "utf8", timeout: 5000 },
360+
);
361+
expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
362+
}),
363+
);
364+
365+
effectIt.effect("falls back to Windows PowerShell when pwsh.exe is unavailable", () =>
366+
Effect.gen(function* () {
367+
const execFile = vi.fn<
368+
(
369+
file: string,
370+
args: ReadonlyArray<string>,
371+
options: { encoding: "utf8"; timeout: number },
372+
) => string
373+
>((file) => {
374+
if (file === "pwsh.exe") {
375+
throw new Error("spawn pwsh.exe ENOENT");
376+
}
377+
return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
378+
});
379+
380+
expect(
381+
yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
382+
Effect.try(() => execFile(...args)).pipe(Effect.option),
383+
),
384+
).toEqual({
385+
PATH: "C:\\Tools",
386+
});
387+
expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
388+
encoding: "utf8",
389+
timeout: 5000,
390+
});
391+
expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
392+
encoding: "utf8",
393+
timeout: 5000,
394+
});
395+
}),
396+
);
224397
});
225398

226399
describe("mergePathValues", () => {

0 commit comments

Comments
 (0)