Open History to see the last commit
1import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe";
2import { describe, expect, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as PlatformError from "effect/PlatformError";
7import * as Sink from "effect/Sink";
8import * as Stream from "effect/Stream";
9import { ChildProcessSpawner } from "effect/process";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { SpawnExecutableResolution } from "@t3tools/shared/shell";
12
13import * as ProcessRunner from "./processRunner.ts";
14import { probeProcessCreation } from "./process/processCreationProbe.ts";
15
16type ChildProcessCommand = {
17 readonly command: string;
18 readonly args: ReadonlyArray<string>;
19 readonly options: {
20 readonly shell?: boolean | string;
21 };
22};
23
24function asChildProcessCommand(command: unknown): ChildProcessCommand {
25 return command as ChildProcessCommand;
26}
27
28function makeHandle(input: {
29 readonly stdout?: string | Stream.Stream<Uint8Array>;
30 readonly stderr?: string | Stream.Stream<Uint8Array>;
31 readonly code?: number;
32 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
33 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
34}) {
35 return ChildProcessSpawner.makeHandle({
36 pid: ChildProcessSpawner.ProcessId(1),
37 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
38 isRunning: Effect.succeed(false),
39 kill: () => Effect.void,
40 unref: Effect.succeed(Effect.void),
41 stdin: input.stdin ?? Sink.drain,
42 stdout:
43 typeof input.stdout === "string"
44 ? Stream.encodeText(Stream.make(input.stdout))
45 : (input.stdout ?? Stream.empty),
46 stderr:
47 typeof input.stderr === "string"
48 ? Stream.encodeText(Stream.make(input.stderr))
49 : (input.stderr ?? Stream.empty),
50 all: Stream.empty,
51 getInputFd: () => Sink.drain,
52 getOutputFd: () => Stream.empty,
53 });
54}
55
56function makeSpawner(
57 f: (
58 command: ChildProcessCommand,
59 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
60) {
61 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
62}
63
64const runWith =
65 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
66 (input: ProcessRunner.ProcessRunInput) =>
67 Effect.service(ProcessRunner.ProcessRunner).pipe(
68 Effect.flatMap((runner) =>
69 runner.run({
70 ...input,
71 }),
72 ),
73 Effect.provide(
74 Layer.effect(ProcessRunner.ProcessRunner, ProcessRunner.make()).pipe(
75 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
76 ),
77 ),
78 );
79
80describe("runProcess", () => {
81 for (const failure of [
82 undefined,
83 { at: "disposing", mode: "error" },
84 { at: "disposing", mode: "exit" },
85 { at: "child-exited", mode: "error" },
86 { at: "child-exited", mode: "exit" },
87 ] as const) {
88 // quarantine: #25245 this regression exercises Windows child ownership during native creation.
89 it.live.skipIf(HostProcess.Platform.defaultValue() !== "win32")(
90 `cleans up a child cancelled during Windows native creation (${JSON.stringify(failure)})`,
91 () =>
92 Effect.promise(async () => {
93 const probe = probeProcessCreation(false, true, failure);
94 if (failure) {
95 await expect(probe).rejects.toThrow(
96 failure.mode === "error"
97 ? `Fixture worker failed at ${failure.at}`
98 : "Fixture worker exited unexpectedly (17)",
99 );
100 return;
101 }
102 const result = await probe;
103 expect(result).toEqual({
104 serverThread: false,
105 gateClosed: true,
106 stdout: "cancelled",
107 code: null,
108 });
109 }),
110 );
111 }
112 // quarantine: #25245 this regression exercises the Windows process-creation boundary.
113 it.live.skipIf(HostProcess.Platform.defaultValue() !== "win32")(
114 "answers requests while Windows native process creation is blocked",
115 () =>
116 Effect.promise(() => probeProcessCreation()).pipe(
117 Effect.map((result) => {
118 expect(result).toEqual({
119 serverThread: false,
120 gateClosed: true,
121 stdout: "finished",
122 code: 0,
123 });
124 }),
125 ),
126 );
127
128 it.effect("resolves and escapes Windows command shims before spawning", () => {
129 const spawner = makeSpawner((command) =>
130 Effect.sync(() => {
131 expect(command.command).toBe(
132 [
133 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
134 '^"repos^"',
135 '^"pr^"',
136 '^"list^"',
137 '^"--source-branch^"',
138 '^"feature^ ^&^ release^"',
139 ].join(" "),
140 );
141 expect(command.args).toEqual([]);
142 expect(command.options.shell).toBe(true);
143 return makeHandle({ stdout: "[]" });
144 }),
145 );
146
147 return runWith(spawner)({
148 command: "az",
149 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
150 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
151 }).pipe(
152 Effect.provideService(HostProcess.Platform, "win32"),
153 Effect.provideService(HostProcess.Environment, {
154 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
155 PATHEXT: ".COM;.EXE;.BAT;.CMD",
156 }),
157 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
158 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
159 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
160 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
161 : undefined,
162 ),
163 Effect.map((result) => {
164 expect(result.stdout).toBe("[]");
165 }),
166 );
167 });
168
169 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
170 Effect.gen(function* () {
171 // File-valued PATH entries make spawn throw ENOTDIR synchronously, arriving through Effect.callback as a defect.
172 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
173 const spawner = makeSpawner(() =>
174 Effect.callback<never, never>(() => {
175 throw defect;
176 }),
177 );
178
179 const error = yield* runWith(spawner)({
180 command: "jj",
181 args: ["--version"],
182 cwd: "/repo",
183 }).pipe(Effect.flip);
184
185 expect(error._tag).toBe("ProcessSpawnError");
186 if (error._tag !== "ProcessSpawnError") {
187 return expect.fail("Expected ProcessSpawnError");
188 }
189 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
190 expect(error.cause).toBe(defect);
191 }),
192 );
193
194 it.effect("fails when output exceeds max buffer in default mode", () =>
195 Effect.gen(function* () {
196 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
197
198 const error = yield* runWith(spawner)({
199 command: "fake",
200 args: ["stdout-bytes", "2048"],
201 maxOutputBytes: 128,
202 }).pipe(Effect.flip);
203
204 expect(error._tag).toBe("ProcessOutputLimitError");
205 if (error._tag !== "ProcessOutputLimitError") {
206 return expect.fail("Expected ProcessOutputLimitError");
207 }
208 expect(error).toMatchObject({
209 stream: "stdout",
210 maxBytes: 128,
211 observedBytes: 2048,
212 });
213 expect(error.message).toBe(
214 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
215 );
216 }),
217 );
218
219 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
220 Effect.gen(function* () {
221 const output = new TextEncoder().encode("exactly");
222 const spawner = makeSpawner(() =>
223 Effect.succeed(
224 makeHandle({
225 stdout: Stream.make(output, new Uint8Array()),
226 }),
227 ),
228 );
229
230 const result = yield* runWith(spawner)({
231 command: "fake",
232 args: ["exact-limit"],
233 maxOutputBytes: output.byteLength,
234 });
235
236 expect(result.stdout).toBe("exactly");
237 }),
238 );
239
240 it.effect("fails fast on output limit before timeout for long-running output", () =>
241 Effect.gen(function* () {
242 const textChunk = "x".repeat(64);
243 const spawner = makeSpawner(() =>
244 Effect.succeed(
245 makeHandle({
246 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
247 Stream.encodeText,
248 ),
249 exitCode: Effect.never,
250 }),
251 ),
252 );
253
254 const error = yield* runWith(spawner)({
255 command: "fake",
256 args: ["spam-stdout"],
257 maxOutputBytes: 128,
258 timeout: "2 seconds",
259 }).pipe(Effect.flip);
260
261 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
262 }),
263 );
264
265 it.effect("truncates output when outputMode is truncate", () =>
266 Effect.gen(function* () {
267 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
268
269 const result = yield* runWith(spawner)({
270 command: "fake",
271 args: ["stdout-bytes", "2048"],
272 maxOutputBytes: 128,
273 outputMode: "truncate",
274 });
275
276 expect(result.code).toBe(0);
277 expect(result.stdout.length).toBeLessThanOrEqual(128);
278 expect(result.stdoutTruncated).toBe(true);
279 expect(result.stderrTruncated).toBe(false);
280 }),
281 );
282
283 it.effect("writes stdin before waiting for exit", () =>
284 Effect.gen(function* () {
285 const stdinWritten = yield* Deferred.make<void>();
286 const decoder = new TextDecoder();
287 const spawner = makeSpawner(() =>
288 Effect.succeed(
289 makeHandle({
290 stdout: "stdin payload",
291 stdin: Sink.forEach((chunk: Uint8Array) => {
292 const text = decoder.decode(chunk, { stream: true });
293 return text.includes("stdin payload")
294 ? Deferred.succeed(stdinWritten, undefined)
295 : Effect.void;
296 }),
297 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
298 }),
299 ),
300 );
301
302 const result = yield* runWith(spawner)({
303 command: "fake",
304 args: ["stdin-echo"],
305 stdin: "stdin payload",
306 });
307
308 expect(result.stdout).toBe("stdin payload");
309 expect(result.code).toBe(0);
310 }),
311 );
312});
313
314describe("isWindowsCommandNotFound", () => {
315 it.effect("matches the localized German cmd.exe error text", () =>
316 Effect.gen(function* () {
317 const isCommandNotFound = yield* isWindowsCommandNotFound(
318 1,
319 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
320 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
321 expect(isCommandNotFound).toBe(true);
322 }),
323 );
324});