Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NonBlockingSpawner.test.ts

242 lines10.8 KB

1// @effect-diagnostics nodeBuiltinImport:off - the spawner's checks are node:fs/promises calls, which the test spies on.
2import * as NodeFSP from "node:fs/promises";
3​
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { describe, expect, it } from "@effect/vitest";
6import { vi } from "vite-plus/test";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Redacted from "effect/Redacted";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17​
18import * as NonBlockingSpawner from "./NonBlockingSpawner.ts";
19​
20vi.mock("node:fs/promises", { spy: true });
21​
22const hostPath = process.env.PATH;
23​
24const wrapped = NonBlockingSpawner.layer.pipe(Layer.provideMerge(NodeServices.layer));
25​
26/** What a caller sees of a command: its output, or the error of a spawn that failed. */
27const outcome = (command: ChildProcess.Command) =>
28 ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.string(command)).pipe(
29 Effect.match({
30 onSuccess: (output) => ({ output }),
31 onFailure: (error) => ({ reason: error.reason._tag, message: error.message }),
32 }),
33 Effect.catchDefect((defect) =>
34 Effect.succeed({
35 defect: defect instanceof Error ? { ...defect, message: defect.message } : defect,
36 }),
37 ),
38 );
39​
40describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("NonBlockingSpawner", () => {
41 it.live("gives callers what the native spawner gives them", () =>
42 Effect.gen(function* () {
43 const fileSystem = yield* FileSystem.FileSystem;
44 const root = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped());
45 for (const [file, mode] of [
46 ["stale/tool", 0o644],
47 ["fresh/tool", 0o755],
48 ["target/bin/tool", 0o755],
49 // GNU env reads a lone `-` as -i and `NAME=value` as an assignment, even after `--`.
50 ["fresh/-", 0o755],
51 ["fresh/launch=stable", 0o755],
52 ] as const) {
53 yield* fileSystem.makeDirectory(`${root}/${file.slice(0, file.lastIndexOf("/"))}`, {
54 recursive: true,
55 });
56 yield* fileSystem.writeFileString(`${root}/${file}`, `#!/bin/sh\necho ${file} "$@"\n`);
57 yield* fileSystem.chmod(`${root}/${file}`, mode);
58 }
59 yield* fileSystem.makeDirectory(`${root}/target/subdir`);
60 yield* fileSystem.makeDirectory(`${root}/dironly/tool`, { recursive: true });
61 yield* fileSystem.makeDirectory(`${root}/no-exec`);
62 yield* fileSystem.chmod(`${root}/no-exec`, 0o600);
63 yield* fileSystem.symlink(`${root}/target/subdir`, `${root}/link`);
64 const PATH = `${root}/stale:${root}/fresh`;
65 const directory = ChildProcess.make(`${root}/dironly/tool`, []);
66 // Kernels refuse to exec a directory with EACCES, which the spawner mirrors, or with
67 // EISDIR, which no access check can predict.
68 const directoryOutcome = yield* outcome(directory).pipe(Effect.provide(NodeServices.layer));
69 const directoryCases =
70 "reason" in directoryOutcome && directoryOutcome.reason === "PermissionDenied"
71 ? {
72 "a directory in PATH": ChildProcess.make("tool", [], {
73 env: { PATH: `${root}/dironly` },
74 }),
75 "a directory before an executable in PATH": ChildProcess.make("tool", [], {
76 env: { PATH: `${root}/dironly:${root}/fresh` },
77 }),
78 "an explicit path to a directory": directory,
79 }
80 : {};
81​
82 const commands = {
83 "enters the cwd": ChildProcess.make("pwd", ["-P"], { cwd: root }),
84 "keeps argv": ChildProcess.make(
85 "printf",
86 ["%s\\n", "-n", "--", "a b", `it's "quoted"`, "$HOME", "; exit 3", "", "A=b"],
87 { cwd: root },
88 ),
89 // dash would drop the exported function and add PWD and OLDPWD.
90 "keeps the environment": ChildProcess.make("env", [], {
91 cwd: root,
92 env: { PATH: hostPath, A: "1", "BASH_FUNC_x%%": "() { echo exported\n}" },
93 }),
94 "skips a non-executable PATH entry": ChildProcess.make("tool", [], { env: { PATH } }),
95 "resolves `..` in PATH after a symlink": ChildProcess.make("tool", [], {
96 env: { PATH: `${root}/link/../bin` },
97 }),
98 "searches PATH relative to the cwd": ChildProcess.make("tool", [], {
99 cwd: root,
100 env: { PATH: "fresh" },
101 }),
102 "a command named -": ChildProcess.make("-", [], { cwd: root, env: { PATH } }),
103 "a command containing =": ChildProcess.make("launch=stable", [], { env: { PATH } }),
104 "shell mode": ChildProcess.make('pwd -P; echo "$0" "a b"', [], { cwd: root, shell: true }),
105 "a pipeline": ChildProcess.make("printf", ["a\\nb\\n"], { cwd: root }).pipe(
106 ChildProcess.pipeTo(ChildProcess.make("tail", ["-n", "1"])),
107 ),
108 "a missing command": ChildProcess.make("t3code-missing-command", ["--version"]),
109 "a missing command with a regular file in PATH": ChildProcess.make("tool", [], {
110 env: { PATH: `${root}/fresh/tool:${root}/target` },
111 }),
112 "a missing command with a regular file last in PATH": ChildProcess.make("tool", [], {
113 env: { PATH: `${root}/target:${root}/fresh/tool` },
114 }),
115 "an explicit path through a regular file": ChildProcess.make(`${root}/fresh/tool/x`, []),
116 "a NUL argument takes precedence over ENOTDIR": ChildProcess.make(`${root}/fresh/tool/x`, [
117 "invalid\0argument",
118 ]),
119 "a redacted NUL argument takes precedence over ENOTDIR": ChildProcess.make(
120 `${root}/fresh/tool/x`,
121 [Redacted.make("invalid\0argument")],
122 ),
123 "a missing command in a cwd": ChildProcess.make("t3code-missing-command", [], {
124 cwd: root,
125 }),
126 "a non-executable command": ChildProcess.make("tool", [], {
127 env: { PATH: `${root}/stale` },
128 }),
129 "a missing explicit path": ChildProcess.make("./missing", [], { cwd: root }),
130 "a non-executable explicit path": ChildProcess.make(`${root}/stale/tool`, []),
131 "a missing cwd": ChildProcess.make("true", [], { cwd: `${root}/missing` }),
132 // The native check sees `missing`, although the path resolves to an existing directory.
133 "a cwd through a missing directory": ChildProcess.make("true", [], {
134 cwd: `${root}/missing/..`,
135 }),
136 "a regular file cwd": ChildProcess.make("true", [], { cwd: `${root}/fresh/tool` }),
137 "an unsearchable cwd": ChildProcess.make("true", [], { cwd: `${root}/no-exec` }),
138 ...directoryCases,
139 };
140 for (const [name, command] of Object.entries(commands)) {
141 const native = yield* outcome(command).pipe(Effect.provide(NodeServices.layer));
142 expect(yield* outcome(command).pipe(Effect.provide(wrapped)), name).toEqual(native);
143 }
144 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
145 );
146​
147 it.live("hands the native spawner only `env`, never a cwd or a command to look up", () =>
148 Effect.gen(function* () {
149 const fileSystem = yield* FileSystem.FileSystem;
150 const directory = yield* fileSystem.makeTempDirectoryScoped();
151 const received: Array<ChildProcess.StandardCommand> = [];
152 const record = (command: ChildProcess.Command): void => {
153 if (command._tag === "StandardCommand") received.push(command);
154 else [command.left, command.right].forEach(record);
155 };
156 const recording = Layer.effect(
157 ChildProcessSpawner.ChildProcessSpawner,
158 Effect.map(ChildProcessSpawner.ChildProcessSpawner, (native) =>
159 ChildProcessSpawner.make((command) => {
160 record(command);
161 return native.spawn(command);
162 }),
163 ),
164 ).pipe(Layer.provideMerge(NodeServices.layer));
165 const commands = [
166 ChildProcess.make("true", [], { cwd: directory }),
167 ChildProcess.make("true", []),
168 ChildProcess.make("/bin/true", []),
169 ChildProcess.make("t3code-missing-command", []),
170 ChildProcess.make("true", [], { cwd: directory, shell: true }),
171 ChildProcess.make("printf", ["a"], { cwd: directory }).pipe(
172 ChildProcess.pipeTo(ChildProcess.make("cat", [], { cwd: directory })),
173 ),
174 ];
175 yield* Effect.forEach(commands, (command) =>
176 ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.exitCode(command)).pipe(
177 Effect.exit,
178 ),
179 ).pipe(Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provide(recording))));
180​
181 expect(received.map((command) => [command.command, command.options.cwd])).toEqual(
182 Array.from({ length: 6 }, () => ["/usr/bin/env", undefined]),
183 );
184 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
185 );
186​
187 it.live("checks at most two paths at once, however many directories hang", () =>
188 Effect.gen(function* () {
189 const allArrived = yield* Deferred.make<void>();
190 let arrivals = 0;
191 // Each spawn resolves its cwd, then starts its check within microtasks.
192 const arrivalPath = Layer.effect(
193 Path.Path,
194 Effect.map(Path.Path, (path) => ({
195 ...path,
196 resolve: (...segments: ReadonlyArray<string>) => {
197 if (++arrivals === 3) setImmediate(() => Deferred.doneUnsafe(allArrived, Effect.void));
198 return path.resolve(...segments);
199 },
200 })),
201 );
202 const hung: Array<() => void> = [];
203 let releasing = false;
204 let running = 0;
205 let mostRunning = 0;
206 using _access = vi.spyOn(NodeFSP, "access").mockImplementation(
207 () =>
208 new Promise<void>((_resolve, reject) => {
209 mostRunning = Math.max(mostRunning, ++running);
210 const fail = () => {
211 running--;
212 reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
213 };
214 if (releasing) fail();
215 else hung.push(fail);
216 }),
217 );
218 const spawns = yield* Effect.forEach(
219 ["a", "b", "c"],
220 (name) =>
221 ChildProcessSpawner.ChildProcessSpawner.use((spawner) =>
222 spawner.exitCode(ChildProcess.make("true", [], { cwd: `/t3code-hung/${name}` })),
223 ).pipe(Effect.flip),
224 { concurrency: "unbounded" },
225 ).pipe(
226 Effect.provide(
227 NonBlockingSpawner.layer.pipe(
228 Layer.provide(arrivalPath),
229 Layer.provide(NodeServices.layer),
230 ),
231 ),
232 Effect.forkChild,
233 );
234 yield* Deferred.await(allArrived);
235 expect(mostRunning).toBe(2);
236 releasing = true;
237 for (const fail of hung.splice(0)) fail();
238 yield* Fiber.join(spawns);
239 expect(mostRunning).toBe(2);
240 }),
241 );
242});