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

@effect__platform-node-shared@4.2.0.patch

317 lines14.1 KB

1diff --git a/dist/NodeChildProcessSpawner.d.ts b/dist/NodeChildProcessSpawner.d.ts
2index 8d4fbd9ac654d24110de00a3a50ed6b8668f8cb1..cebce918b00077ee7c7505bd80aead6fb2bfd889 100644
3--- a/dist/NodeChildProcessSpawner.d.ts
4+++ b/dist/NodeChildProcessSpawner.d.ts
5@@ -35,6 +35,8 @@
6 * @stability unstable
7 * @since 4.0.0
8 */
9+import type * as NodeChildProcess from "node:child_process";
10+import type { Readable, Writable } from "node:stream";
11 import type * as Arr from "effect/Array";
12 import * as Context from "effect/Context";
13 import * as Duration from "effect/Duration";
14@@ -54,6 +56,19 @@ import { ChildProcessSpawner, ProcessId } from "effect/process/ChildProcessSpawn
15 * @since 4.0.0
16 */
17 export declare const layer: Layer.Layer<ChildProcessSpawner, never, FileSystem.FileSystem | Path.Path>;
18+export interface SpawnedChildProcess extends NodeJS.EventEmitter {
19+ readonly pid?: number | undefined;
20+ readonly exitCode: number | null;
21+ readonly signalCode: NodeJS.Signals | null;
22+ readonly stdin: Writable | null;
23+ readonly stdout: Readable | null;
24+ readonly stderr: Readable | null;
25+ readonly stdio: ReadonlyArray<Readable | Writable | null | undefined>;
26+ kill(signal?: NodeJS.Signals | number): boolean;
27+ ref(): void;
28+ unref(): void;
29+}
30+export declare const layerWithSpawn: (spawnProcess: (command: string, args: ReadonlyArray<string>, options: NodeChildProcess.SpawnOptions) => SpawnedChildProcess) => Layer.Layer<ChildProcessSpawner, never, FileSystem.FileSystem | Path.Path>;
31 declare const ProxyProcess_base: Context.ServiceClass<ProxyProcess, "@effect/platform-node/NodeChildProcessSpawner/ProxyProcess", {
32 readonly currentPid: Effect.Effect<Option.Option<ProcessId>>;
33 }>;
34diff --git a/dist/NodeChildProcessSpawner.js b/dist/NodeChildProcessSpawner.js
35index 3f8f1f1d151de7f87f23afebe74ca017d13e2fe9..4ecce2093977538686d806b58412aa53570e7ed8 100644
36--- a/dist/NodeChildProcessSpawner.js
37+++ b/dist/NodeChildProcessSpawner.js
38@@ -103,14 +103,30 @@ const isProcessAlive = (command, childProcess) => {
39 return isUnsignallableProcessGroup(error);
40 }
41 };
42-const taskkill = (childProcess, onExit = () => {}) => {
43+const taskkill = (childProcess, spawnProcess, onExit = () => {}) => {
44 if (hasExited(childProcess)) {
45 onExit(null);
46 return;
47 }
48- NodeChildProcess.execFile("taskkill", ["/pid", String(childProcess.pid), "/T", "/F"], {
49+ if (spawnProcess === undefined) {
50+ NodeChildProcess.execFile("taskkill", ["/pid", String(childProcess.pid), "/T", "/F"], {
51+ windowsHide: true
52+ }, onExit);
53+ return;
54+ }
55+ // Starts taskkill through the injected spawner so it gets the same off-thread launch as commands.
56+ let done = false;
57+ const finish = error => {
58+ if (done) return;
59+ done = true;
60+ onExit(error);
61+ };
62+ const killer = spawnProcess("taskkill", ["/pid", String(childProcess.pid), "/T", "/F"], {
63+ stdio: "ignore",
64 windowsHide: true
65- }, onExit);
66+ }, []);
67+ killer.on("error", finish);
68+ killer.on("exit", code => finish(code === 0 ? null : new Error(`taskkill exited with code ${code}`)));
69 };
70 const spawnDirect = (command, args, options, halfOpen) => {
71 const childProcess = NodeChildProcess.spawn(command, args, options);
72@@ -123,7 +139,7 @@ const spawnDirect = (command, args, options, halfOpen) => {
73 // Returns the function that launches a command. The proxy process layer waits
74 // here, interruptibly, for a proxy process that is ready, since the launch
75 // itself cannot be interrupted.
76-const makeWith = /*#__PURE__*/Effect.fnUntraced(function* (prepareSpawn, supportsInheritedFds) {
77+const makeWith = /*#__PURE__*/Effect.fnUntraced(function* (prepareSpawn, supportsInheritedFds, killSpawn) {
78 const fs = yield* FileSystem.FileSystem;
79 const path = yield* Path.Path;
80 const resolveWorkingDirectory = Effect.fnUntraced(function* (options) {
81@@ -418,7 +434,7 @@ const makeWith = /*#__PURE__*/Effect.fnUntraced(function* (prepareSpawn, support
82 const killProcessGroup = (command, childProcess, signal) => {
83 if (globalThis.process.platform === "win32") {
84 return Effect.callback(resume => {
85- taskkill(childProcess, error => {
86+ taskkill(childProcess, killSpawn, error => {
87 if (error) {
88 resume(Effect.fail(toPlatformError("kill", toError(error), command)));
89 } else {
90@@ -854,6 +870,7 @@ export class ProxyProcess extends /*#__PURE__*/Context.Service()("@effect/platfo
91 * @category layers
92 * @since 4.1.6
93 */
94+export const layerWithSpawn = spawnProcess => Layer.effect(ChildProcessSpawner, makeWith(Effect.succeed(spawnProcess), true, spawnProcess));
95 export const layerProxyProcess = options => Layer.effectContext(Effect.gen(function* () {
96 if (globalThis.process.platform === "win32") {
97 return yield* Effect.fail(PlatformError.systemError({
98diff --git a/dist/internal/proxyProcess.js b/dist/internal/proxyProcess.js
99index aa481514522573c3d707c362e8bce49ac43af1fa..e20e49e4cdd26feefe52a28bc5e293a5bb259ebb 100644
100--- a/dist/internal/proxyProcess.js
101+++ b/dist/internal/proxyProcess.js
102@@ -168,11 +168,16 @@ class Proxy {
103 child;
104 // Bounds the wait for `Ready`, and for the reply to each sent request
105 timers = /*#__PURE__*/new Map();
106+ heard = 0;
107+ // Spawns failed for a late reply, whose command is killed if it starts after all
108+ abandoned = /*#__PURE__*/new Set();
109+ socketPath;
110 constructor(options) {
111 this.options = options;
112 try {
113 this.directory = Fs.mkdtempSync(Path.join(Os.tmpdir(), "effect-proxy-"));
114 const socketPath = Path.join(this.directory, "socket");
115+ this.socketPath = socketPath;
116 if (Buffer.byteLength(socketPath) > maxSocketPathLength) {
117 throw new Error(`The proxy process socket path ${socketPath} exceeds ${maxSocketPathLength} bytes; set TMPDIR to a shorter directory`);
118 }
119@@ -190,7 +195,7 @@ class Proxy {
120 }
121 this.child = NodeChildProcess.spawn(options.executable ?? globalThis.process.execPath, options.args ?? ["--input-type=module", "-e", source], {
122 env,
123- stdio: ["inherit", "inherit", "inherit", "ipc"],
124+ stdio: ["inherit", "ignore", "ignore", "ipc"],
125 windowsHide: true
126 });
127 this.pid = this.child.pid;
128@@ -299,26 +304,50 @@ class Proxy {
129 }
130 startTimer(key) {
131 const millis = this.options.responseTimeoutMillis;
132- const timer = setTimeout(() => {
133- // Defer past the I/O poll so queued replies are read first; keep
134- // referenced so an idle loop still runs the check immediately.
135- setImmediate(() => {
136- if (this.timers.get(key) !== timer) return;
137- this.stop(Object.assign(new Error(`The proxy process did not respond within ${millis} ms`), {
138- code: "ETIMEDOUT"
139- }));
140- });
141- }, millis);
142- // Whatever waits for the reply keeps the application running
143- timer.unref();
144- this.timers.set(key, timer);
145+ // Effect-TS/effect#11008: a blocked event loop runs due timers before it reads waiting replies.
146+ const arm = heard => {
147+ const timer = setTimeout(() => {
148+ // Defer past the I/O poll so queued replies are read first; keep
149+ // referenced so an idle loop still runs the check immediately.
150+ setImmediate(() => {
151+ if (this.timers.get(key) !== timer) return;
152+ if (this.heard !== heard) return arm(this.heard);
153+ const error = Object.assign(new Error(`The proxy process did not respond within ${millis} ms`), {
154+ code: "ETIMEDOUT"
155+ });
156+ if (key === "ready") return this.stop(error);
157+ this.abandon(key, error);
158+ });
159+ }, millis);
160+ // Whatever waits for the reply keeps the application running
161+ timer.unref();
162+ this.timers.set(key, timer);
163+ };
164+ arm(this.heard);
165+ }
166+ /**
167+ * Fails one spawn whose reply is late, and stops taking spawns so the next
168+ * one goes to a new proxy process. The commands this one already runs are
169+ * left running, since a slow proxy process is not a dead one. With no other
170+ * command it is stopped, as nothing else depends on it.
171+ */
172+ abandon(id, error) {
173+ if (this.commands.size <= 1) return this.stop(error);
174+ this.timers.delete(id);
175+ this.abandoned.add(id);
176+ this.retired = true;
177+ this.commands.get(id)?.onError(error);
178 }
179 stopTimer(key) {
180 clearTimeout(this.timers.get(key));
181 this.timers.delete(key);
182 }
183 disconnect() {
184- if (this.child?.connected === true) this.child.disconnect();
185+ if (this.child?.connected === true) {
186+ // Tells the proxy process this is a deliberate close, not the application's death
187+ if (this.ready) this.child.send({ _tag: "Close" });
188+ this.child.disconnect();
189+ }
190 this.closeServer();
191 }
192 updateRef() {
193@@ -331,9 +360,19 @@ class Proxy {
194 }
195 }
196 receive(message) {
197+ this.heard++;
198 if (message._tag === "Ready") return this.onReady();
199 const command = this.commands.get(message.id);
200- if (command === undefined) return;
201+ if (command === undefined) {
202+ if (this.abandoned.delete(message.id) && message._tag === "Spawned") {
203+ try {
204+ globalThis.process.kill(message.pid, "SIGKILL");
205+ } catch {
206+ // ignored
207+ }
208+ }
209+ return;
210+ }
211 switch (message._tag) {
212 case "Spawned":
213 this.stopTimer(message.id);
214@@ -439,9 +478,11 @@ export const make = options => {
215 const get = () => {
216 if (current.exited) {
217 current = new Proxy(options);
218- } else if (current.credentials !== credentials()) {
219- // The application changed its credentials, so its commands must not
220- // run with the old ones
221+ } else if (current.retired || current.credentials !== credentials() || current.ready && !Fs.existsSync(current.socketPath)) {
222+ // It was late to reply to a spawn. Or the application changed its
223+ // credentials, so its commands must not run with the old ones. Or a
224+ // temp-directory cleanup deleted the socket, so every command's stdio
225+ // would fail to connect.
226 const previous = current;
227 current = new Proxy(options);
228 retired.add(previous);
229diff --git a/dist/internal/proxyProcessSource.js b/dist/internal/proxyProcessSource.js
230index 3cd0dabe30e9f90ac854462cdb65440d9acd5c83..3d11435f1ba567d0929505e85f54aa5e2d427560 100644
231--- a/dist/internal/proxyProcessSource.js
232+++ b/dist/internal/proxyProcessSource.js
233@@ -54,6 +54,8 @@ export const run = () => {
234 socket.write(header, (error) => error ? reject(error) : resolve(socket))
235 })
236 })
237+ // Each spawned command, with the process or group that kills it
238+ const running = new Map()
239 const spawn = async (socketPath , token , { args, command, id, options } ) => {
240 const stdio = await Promise.allSettled(
241 options.stdio.map((mode, fd) => mode === "pipe" ? connect(socketPath, token, id, fd) : mode)
242@@ -71,6 +73,8 @@ export const run = () => {
243 if (errno) throw new Error(\`setBlocking failed: \${Util.getSystemErrorName(errno)}\`)
244 }
245 const child = ChildProcess.spawn(command, args, { ...options, stdio: values })
246+ child.on("spawn", () => running.set(child, options.detached ? -child.pid : child.pid))
247+ child.on("exit", () => running.delete(child))
248 child.on("error", (error) => send({ _tag: "Error", id, error: serializeError(error) }))
249 child.on("spawn", () => send({ _tag: "Spawned", id, pid: child.pid }))
250 child.on("exit", (code, signal) => send({ _tag: "Exit", id, code, signal }))
251@@ -85,8 +89,19 @@ export const run = () => {
252 // the proxy process exits when its commands have exited.
253 process.on("SIGINT", () => {})
254 process.on("SIGTERM", () => {})
255+ // An application that was killed never stops its commands, so they die with its channel.
256+ // A deliberate close leaves them, so an unreferenced command can outlive the application.
257+ let closing = false
258+ process.on("disconnect", () => {
259+ if (closing) return
260+ for (const target of running.values()) {
261+ try {
262+ process.kill(target, "SIGKILL")
263+ } catch {}
264+ }
265+ })
266 process.once("message", ({ socketPath, token } ) => {
267- process.on("message", (request ) => spawn(socketPath, token, request))
268+ process.on("message", (request ) => request._tag === "Close" ? closing = true : spawn(socketPath, token, request))
269 send({ _tag: "Ready" })
270 })
271 }
272diff --git a/dist/internal/proxyProcessWorker.js b/dist/internal/proxyProcessWorker.js
273index 6694313fefcd21da1d020c46e616a2cb9c318bfd..92dd0a180952127c04f1ef6fcea4d35809c83f38 100644
274--- a/dist/internal/proxyProcessWorker.js
275+++ b/dist/internal/proxyProcessWorker.js
276@@ -49,6 +49,8 @@ export const run = () => {
277 socket.write(header, error => error ? reject(error) : resolve(socket));
278 });
279 });
280+ // Each spawned command, with the process or group that kills it
281+ const running = new Map();
282 const spawn = async (socketPath, token, {
283 args,
284 command,
285@@ -72,6 +74,8 @@ export const run = () => {
286 ...options,
287 stdio: values
288 });
289+ child.on("spawn", () => running.set(child, options.detached ? -child.pid : child.pid));
290+ child.on("exit", () => running.delete(child));
291 child.on("error", error => send({
292 _tag: "Error",
293 id,
294@@ -103,11 +107,22 @@ export const run = () => {
295 // the proxy process exits when its commands have exited.
296 process.on("SIGINT", () => {});
297 process.on("SIGTERM", () => {});
298+ // An application that was killed never stops its commands, so they die with its channel.
299+ // A deliberate close leaves them, so an unreferenced command can outlive the application.
300+ let closing = false;
301+ process.on("disconnect", () => {
302+ if (closing) return;
303+ for (const target of running.values()) {
304+ try {
305+ process.kill(target, "SIGKILL");
306+ } catch {}
307+ }
308+ });
309 process.once("message", ({
310 socketPath,
311 token
312 }) => {
313- process.on("message", request => spawn(socketPath, token, request));
314+ process.on("message", request => request._tag === "Close" ? closing = true : spawn(socketPath, token, request));
315 send({
316 _tag: "Ready"
317 });