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

NonBlockingSpawner.test.ts

237 lines10.4 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.symlink(`${root}/target/subdir`, `${root}/link`);
62 const PATH = `${root}/stale:${root}/fresh`;
63 const directory = ChildProcess.make(`${root}/dironly/tool`, []);
64 // Kernels refuse to exec a directory with EACCES, which the spawner mirrors, or with
65 // EISDIR, which no access check can predict.
66 const directoryCases =
67 "reason" in (yield* outcome(directory).pipe(Effect.provide(NodeServices.layer)))
68 ? {
69 "a directory in PATH": ChildProcess.make("tool", [], {
70 env: { PATH: `${root}/dironly` },
71 }),
72 "a directory before an executable in PATH": ChildProcess.make("tool", [], {
73 env: { PATH: `${root}/dironly:${root}/fresh` },
74 }),
75 "an explicit path to a directory": directory,
76 }
77 : {};
78​
79 const commands = {
80 "enters the cwd": ChildProcess.make("pwd", ["-P"], { cwd: root }),
81 "keeps argv": ChildProcess.make(
82 "printf",
83 ["%s\\n", "-n", "--", "a b", `it's "quoted"`, "$HOME", "; exit 3", "", "A=b"],
84 { cwd: root },
85 ),
86 // dash would drop the exported function and add PWD and OLDPWD.
87 "keeps the environment": ChildProcess.make("env", [], {
88 cwd: root,
89 env: { PATH: hostPath, A: "1", "BASH_FUNC_x%%": "() { echo exported\n}" },
90 }),
91 "skips a non-executable PATH entry": ChildProcess.make("tool", [], { env: { PATH } }),
92 "resolves `..` in PATH after a symlink": ChildProcess.make("tool", [], {
93 env: { PATH: `${root}/link/../bin` },
94 }),
95 "searches PATH relative to the cwd": ChildProcess.make("tool", [], {
96 cwd: root,
97 env: { PATH: "fresh" },
98 }),
99 "a command named -": ChildProcess.make("-", [], { cwd: root, env: { PATH } }),
100 "a command containing =": ChildProcess.make("launch=stable", [], { env: { PATH } }),
101 "shell mode": ChildProcess.make('pwd -P; echo "$0" "a b"', [], { cwd: root, shell: true }),
102 "a pipeline": ChildProcess.make("printf", ["a\\nb\\n"], { cwd: root }).pipe(
103 ChildProcess.pipeTo(ChildProcess.make("tail", ["-n", "1"])),
104 ),
105 "a missing command": ChildProcess.make("t3code-missing-command", ["--version"]),
106 "a missing command with a regular file in PATH": ChildProcess.make("tool", [], {
107 env: { PATH: `${root}/fresh/tool:${root}/target` },
108 }),
109 "a missing command with a regular file last in PATH": ChildProcess.make("tool", [], {
110 env: { PATH: `${root}/target:${root}/fresh/tool` },
111 }),
112 "an explicit path through a regular file": ChildProcess.make(`${root}/fresh/tool/x`, []),
113 "a NUL argument takes precedence over ENOTDIR": ChildProcess.make(`${root}/fresh/tool/x`, [
114 "invalid\0argument",
115 ]),
116 "a redacted NUL argument takes precedence over ENOTDIR": ChildProcess.make(
117 `${root}/fresh/tool/x`,
118 [Redacted.make("invalid\0argument")],
119 ),
120 "a missing command in a cwd": ChildProcess.make("t3code-missing-command", [], {
121 cwd: root,
122 }),
123 "a non-executable command": ChildProcess.make("tool", [], {
124 env: { PATH: `${root}/stale` },
125 }),
126 "a missing explicit path": ChildProcess.make("./missing", [], { cwd: root }),
127 "a non-executable explicit path": ChildProcess.make(`${root}/stale/tool`, []),
128 "a missing cwd": ChildProcess.make("true", [], { cwd: `${root}/missing` }),
129 // The native check sees `missing`, although the path resolves to an existing directory.
130 "a cwd through a missing directory": ChildProcess.make("true", [], {
131 cwd: `${root}/missing/..`,
132 }),
133 ...directoryCases,
134 };
135 for (const [name, command] of Object.entries(commands)) {
136 const native = yield* outcome(command).pipe(Effect.provide(NodeServices.layer));
137 expect(yield* outcome(command).pipe(Effect.provide(wrapped)), name).toEqual(native);
138 }
139 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
140 );
141​
142 it.live("hands the native spawner only `env`, never a cwd or a command to look up", () =>
143 Effect.gen(function* () {
144 const fileSystem = yield* FileSystem.FileSystem;
145 const directory = yield* fileSystem.makeTempDirectoryScoped();
146 const received: Array<ChildProcess.StandardCommand> = [];
147 const record = (command: ChildProcess.Command): void => {
148 if (command._tag === "StandardCommand") received.push(command);
149 else [command.left, command.right].forEach(record);
150 };
151 const recording = Layer.effect(
152 ChildProcessSpawner.ChildProcessSpawner,
153 Effect.map(ChildProcessSpawner.ChildProcessSpawner, (native) =>
154 ChildProcessSpawner.make((command) => {
155 record(command);
156 return native.spawn(command);
157 }),
158 ),
159 ).pipe(Layer.provideMerge(NodeServices.layer));
160 const commands = [
161 ChildProcess.make("true", [], { cwd: directory }),
162 ChildProcess.make("true", []),
163 ChildProcess.make("/bin/true", []),
164 ChildProcess.make("t3code-missing-command", []),
165 ChildProcess.make("true", [], { cwd: directory, shell: true }),
166 ChildProcess.make("printf", ["a"], { cwd: directory }).pipe(
167 ChildProcess.pipeTo(ChildProcess.make("cat", [], { cwd: directory })),
168 ),
169 ];
170 yield* Effect.forEach(commands, (command) =>
171 ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.exitCode(command)).pipe(
172 Effect.exit,
173 ),
174 ).pipe(Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provide(recording))));
175​
176 expect(received.map((command) => [command.command, command.options.cwd])).toEqual(
177 Array.from({ length: 6 }, () => ["/usr/bin/env", undefined]),
178 );
179 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
180 );
181​
182 it.live("checks at most two paths at once, however many directories hang", () =>
183 Effect.gen(function* () {
184 const allArrived = yield* Deferred.make<void>();
185 let arrivals = 0;
186 // Each spawn resolves its cwd, then starts its check within microtasks.
187 const arrivalPath = Layer.effect(
188 Path.Path,
189 Effect.map(Path.Path, (path) => ({
190 ...path,
191 resolve: (...segments: ReadonlyArray<string>) => {
192 if (++arrivals === 3) setImmediate(() => Deferred.doneUnsafe(allArrived, Effect.void));
193 return path.resolve(...segments);
194 },
195 })),
196 );
197 const hung: Array<() => void> = [];
198 let releasing = false;
199 let running = 0;
200 let mostRunning = 0;
201 using _access = vi.spyOn(NodeFSP, "access").mockImplementation(
202 () =>
203 new Promise<void>((_resolve, reject) => {
204 mostRunning = Math.max(mostRunning, ++running);
205 const fail = () => {
206 running--;
207 reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" }));
208 };
209 if (releasing) fail();
210 else hung.push(fail);
211 }),
212 );
213 const spawns = yield* Effect.forEach(
214 ["a", "b", "c"],
215 (name) =>
216 ChildProcessSpawner.ChildProcessSpawner.use((spawner) =>
217 spawner.exitCode(ChildProcess.make("true", [], { cwd: `/t3code-hung/${name}` })),
218 ).pipe(Effect.flip),
219 { concurrency: "unbounded" },
220 ).pipe(
221 Effect.provide(
222 NonBlockingSpawner.layer.pipe(
223 Layer.provide(arrivalPath),
224 Layer.provide(NodeServices.layer),
225 ),
226 ),
227 Effect.forkChild,
228 );
229 yield* Deferred.await(allArrived);
230 expect(mostRunning).toBe(2);
231 releasing = true;
232 for (const fail of hung.splice(0)) fail();
233 yield* Fiber.join(spawns);
234 expect(mostRunning).toBe(2);
235 }),
236 );
237});