Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - execvp's X_OK test has no Effect FileSystem equivalent.
2import * as NodeFS from "node:fs";
3import * as NodeFSP from "node:fs/promises";
4
5import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as Redacted from "effect/Redacted";
12import * as ChildProcess from "effect/process/ChildProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14import * as CommandLine from "effect/process/CommandLine";
15
16// libuv's _PATH_DEFPATH, searched when the child environment has no PATH.
17const DEFAULT_PATH = "/usr/bin:/bin";
18
19// A check on a hung mount holds a libuv threadpool thread until the mount answers, and the
20// pool's four threads also compress every WebSocket frame. Checks therefore run one at a time
21// per directory and two at a time overall; the rest wait without holding a thread.
22const CHECK_LIMIT = 2;
23const directoryTails = new Map<string, Promise<unknown>>();
24const waiting: Array<() => void> = [];
25let running = 0;
26
27const access = async (path: string, mode: number) => {
28 if (running < CHECK_LIMIT) running++;
29 else await new Promise<void>((resume) => waiting.push(resume));
30 try {
31 await NodeFSP.access(path, mode);
32 // X_OK passes on a searchable directory, which Linux execve refuses with EACCES.
33 if (mode === NodeFS.constants.X_OK && (await NodeFSP.stat(path)).isDirectory()) {
34 return Object.assign(new Error(`access '${path}'`), { code: "EACCES" });
35 }
36 return undefined;
37 } catch (error) {
38 return error as NodeJS.ErrnoException;
39 } finally {
40 // A waiter takes over the slot.
41 const next = waiting.shift();
42 if (next === undefined) running--;
43 else next();
44 }
45};
46
47/** The errno error of `access(path, mode)`, or undefined when it passes. */
48const check = (directory: string, path: string, mode: number) => {
49 const result = (directoryTails.get(directory) ?? Promise.resolve()).then(() =>
50 access(path, mode),
51 );
52 directoryTails.set(directory, result);
53 void result.then(() => {
54 if (directoryTails.get(directory) === result) directoryTails.delete(directory);
55 });
56 return Effect.promise(() => result);
57};
58
59// The PATH the child searches, from the environment Effect's Node spawner gives it.
60const childPath = ({ env, extendEnv }: ChildProcess.CommandOptions) => {
61 if (env === undefined) return process.env.PATH;
62 if (!Object.hasOwn(env, "PATH")) return extendEnv === true ? process.env.PATH : undefined;
63 const value = env.PATH;
64 return value === undefined || !Redacted.isRedacted(value) ? value : Redacted.value(value);
65};
66
67// The spawn error Effect's Node spawner reports when execvp fails with `code`.
68const spawnFailure = (command: ChildProcess.StandardCommand, code: "ENOENT" | "EACCES") => {
69 const syscall = `spawn ${command.command}`;
70 return PlatformError.systemError({
71 _tag: code === "ENOENT" ? "NotFound" : "PermissionDenied",
72 module: "ChildProcess",
73 method: "spawn",
74 pathOrDescriptor: CommandLine.display([command.command, ...command.args], { format: "posix" }),
75 syscall,
76 cause: Object.assign(new Error(`${syscall} ${code}`), {
77 errno: code === "ENOENT" ? -2 : -13,
78 code,
79 syscall,
80 path: command.command,
81 spawnargs: command.args.map((arg) => (Redacted.isRedacted(arg) ? "<redacted>" : arg)),
82 }),
83 });
84};
85
86// Node throws ENOTDIR synchronously, without the command, and Effect's spawner maps the throw.
87const notDirectoryFailure = (command: ChildProcess.StandardCommand) =>
88 PlatformError.systemError({
89 _tag: "BadResource",
90 module: "ChildProcess",
91 method: "spawn",
92 pathOrDescriptor: CommandLine.display([command.command, ...command.args], { format: "posix" }),
93 syscall: "spawn",
94 cause: Object.assign(new Error("spawn ENOTDIR"), {
95 errno: -20,
96 code: "ENOTDIR",
97 syscall: "spawn",
98 }),
99 });
100
101// The error of the `FileSystem.access(cwd)` Effect's Node spawner runs before it spawns.
102const cwdFailure = (cwd: string, cause: NodeJS.ErrnoException) =>
103 PlatformError.systemError({
104 _tag:
105 cause.code === "ENOENT"
106 ? "NotFound"
107 : cause.code === "EACCES" || cause.code === "EPERM"
108 ? "PermissionDenied"
109 : cause.code === "ENOTDIR" || cause.code === "ELOOP"
110 ? "BadResource"
111 : "Unknown",
112 module: "FileSystem",
113 method: "access",
114 pathOrDescriptor: cwd,
115 syscall: cause.syscall,
116 cause,
117 });
118
119/**
120 * Fails as a native spawn does when the command is missing or not executable: callers read
121 * that error to tell a CLI that is not installed from one that failed. When PATH is exhausted,
122 * execvp reports EACCES if any candidate was denied, or the last lookup error otherwise.
123 */
124const findExecutable = Effect.fnUntraced(function* (
125 command: ChildProcess.StandardCommand,
126 cwd: string | undefined,
127) {
128 // Joined as text: the kernel resolves `..` after a symlink differently from a normalized path.
129 const fromCwd = (path: string) =>
130 cwd === undefined || path.startsWith("/") ? path : `${cwd}/${path}`;
131 const candidates = command.command.includes("/")
132 ? [fromCwd(command.command)]
133 : (childPath(command.options) ?? DEFAULT_PATH)
134 .split(":")
135 .map((entry) => `${fromCwd(entry || ".")}/${command.command}`);
136 let failure: "ENOENT" | "EACCES" | "ENOTDIR" = "ENOENT";
137 for (const candidate of candidates) {
138 const error = yield* check(
139 candidate.slice(0, candidate.lastIndexOf("/")) || "/",
140 candidate,
141 NodeFS.constants.X_OK,
142 );
143 const code = error?.code;
144 // Any other errno is left for `env` to report through its exit code.
145 if (code !== "ENOENT" && code !== "EACCES" && code !== "ENOTDIR") return;
146 if (failure !== "EACCES") failure = code;
147 }
148 if (failure === "ENOTDIR") return yield* notDirectoryFailure(command);
149 return yield* spawnFailure(command, failure);
150});
151
152const make = Effect.gen(function* () {
153 const native = yield* ChildProcessSpawner.ChildProcessSpawner;
154 if ((yield* HostProcess.Platform) !== "linux") return native;
155 if (!(yield* Effect.promise(supportsEnvChdir))) return native;
156 const path = yield* Path.Path;
157
158 // Runs inside the NonBlockingSpawner.spawn span.
159 const prepareStandard = Effect.fnUntraced(function* (input: ChildProcess.StandardCommand) {
160 const { cwd: givenCwd, shell, ...options } = input.options;
161 // Effect rejects a shell command with arguments, and a NUL, itself.
162 if (
163 (shell && input.args.length > 0) ||
164 [input.command, ...input.args].some((arg) =>
165 (Redacted.isRedacted(arg) ? Redacted.value(arg) : arg).includes("\0"),
166 )
167 ) {
168 return input;
169 }
170 // Node's shell mode on Unix, spelled out so the trampoline can run it.
171 const command = shell
172 ? ChildProcess.make(typeof shell === "string" ? shell : "/bin/sh", ["-c", input.command])
173 : input;
174 // Checked as given and entered resolved, as Effect's Node spawner does.
175 const cwd = givenCwd === undefined ? undefined : path.resolve(givenCwd);
176 const trampoline = envTrampoline(command.command, command.args, cwd);
177 if (trampoline === undefined) return input;
178 if (givenCwd !== undefined && cwd !== undefined) {
179 const error = yield* check(cwd, givenCwd, NodeFS.constants.F_OK);
180 if (error !== undefined) return yield* cwdFailure(givenCwd, error);
181 // Resolving `.` fails as the child's chdir would: ENOTDIR on a file, EACCES unsearchable.
182 const chdirError = yield* check(cwd, `${cwd}/.`, NodeFS.constants.F_OK);
183 if (chdirError?.code === "ENOTDIR") return yield* notDirectoryFailure(command);
184 if (chdirError?.code === "EACCES") return yield* spawnFailure(command, "EACCES");
185 }
186 yield* findExecutable(ChildProcess.make(command.command, command.args, options), cwd);
187 return ChildProcess.make(trampoline.command, trampoline.args, options);
188 });
189
190 const prepare = (
191 command: ChildProcess.Command,
192 ): Effect.Effect<ChildProcess.Command, PlatformError.PlatformError> =>
193 command._tag === "StandardCommand"
194 ? prepareStandard(command)
195 : Effect.map(Effect.all([prepare(command.left), prepare(command.right)]), ([left, right]) =>
196 ChildProcess.pipeTo(left, right, command.options),
197 );
198
199 return ChildProcessSpawner.make(
200 Effect.fn("NonBlockingSpawner.spawn")(function* (command) {
201 return yield* native.spawn(yield* prepare(command));
202 }),
203 );
204});
205
206/**
207 * On Linux with GNU `env`, replaces the provided `ChildProcessSpawner` with one that never
208 * hands libuv a cwd or a PATH search; elsewhere it passes the provided one through.
209 */
210export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make);