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

@effect__platform-node-shared@4.2.0.patch

285 lines12.9 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..8bbee76d5e285dd043f22eda8f5f0588f1e4b22e 100644
100--- a/dist/internal/proxyProcess.js
101+++ b/dist/internal/proxyProcess.js
102@@ -168,11 +168,14 @@ 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+ socketPath;
108 constructor(options) {
109 this.options = options;
110 try {
111 this.directory = Fs.mkdtempSync(Path.join(Os.tmpdir(), "effect-proxy-"));
112 const socketPath = Path.join(this.directory, "socket");
113+ this.socketPath = socketPath;
114 if (Buffer.byteLength(socketPath) > maxSocketPathLength) {
115 throw new Error(`The proxy process socket path ${socketPath} exceeds ${maxSocketPathLength} bytes; set TMPDIR to a shorter directory`);
116 }
117@@ -190,7 +193,7 @@ class Proxy {
118 }
119 this.child = NodeChildProcess.spawn(options.executable ?? globalThis.process.execPath, options.args ?? ["--input-type=module", "-e", source], {
120 env,
121- stdio: ["inherit", "inherit", "inherit", "ipc"],
122+ stdio: ["inherit", "ignore", "ignore", "ipc"],
123 windowsHide: true
124 });
125 this.pid = this.child.pid;
126@@ -299,26 +302,35 @@ class Proxy {
127 }
128 startTimer(key) {
129 const millis = this.options.responseTimeoutMillis;
130- const timer = setTimeout(() => {
131- // Defer past the I/O poll so queued replies are read first; keep
132- // referenced so an idle loop still runs the check immediately.
133- setImmediate(() => {
134- if (this.timers.get(key) !== timer) return;
135- this.stop(Object.assign(new Error(`The proxy process did not respond within ${millis} ms`), {
136- code: "ETIMEDOUT"
137- }));
138- });
139- }, millis);
140- // Whatever waits for the reply keeps the application running
141- timer.unref();
142- this.timers.set(key, timer);
143+ // Effect-TS/effect#11008: a blocked event loop runs due timers before it reads waiting replies.
144+ const arm = heard => {
145+ const timer = setTimeout(() => {
146+ // Defer past the I/O poll so queued replies are read first; keep
147+ // referenced so an idle loop still runs the check immediately.
148+ setImmediate(() => {
149+ if (this.timers.get(key) !== timer) return;
150+ if (this.heard !== heard) return arm(this.heard);
151+ this.stop(Object.assign(new Error(`The proxy process did not respond within ${millis} ms`), {
152+ code: "ETIMEDOUT"
153+ }));
154+ });
155+ }, millis);
156+ // Whatever waits for the reply keeps the application running
157+ timer.unref();
158+ this.timers.set(key, timer);
159+ };
160+ arm(this.heard);
161 }
162 stopTimer(key) {
163 clearTimeout(this.timers.get(key));
164 this.timers.delete(key);
165 }
166 disconnect() {
167- if (this.child?.connected === true) this.child.disconnect();
168+ if (this.child?.connected === true) {
169+ // Tells the proxy process this is a deliberate close, not the application's death
170+ if (this.ready) this.child.send({ _tag: "Close" });
171+ this.child.disconnect();
172+ }
173 this.closeServer();
174 }
175 updateRef() {
176@@ -331,6 +343,7 @@ class Proxy {
177 }
178 }
179 receive(message) {
180+ this.heard++;
181 if (message._tag === "Ready") return this.onReady();
182 const command = this.commands.get(message.id);
183 if (command === undefined) return;
184@@ -439,9 +452,10 @@ export const make = options => {
185 const get = () => {
186 if (current.exited) {
187 current = new Proxy(options);
188- } else if (current.credentials !== credentials()) {
189+ } else if (current.credentials !== credentials() || current.ready && !Fs.existsSync(current.socketPath)) {
190 // The application changed its credentials, so its commands must not
191- // run with the old ones
192+ // run with the old ones. Or a temp-directory cleanup deleted the socket,
193+ // so every command's stdio would fail to connect.
194 const previous = current;
195 current = new Proxy(options);
196 retired.add(previous);
197diff --git a/dist/internal/proxyProcessSource.js b/dist/internal/proxyProcessSource.js
198index 3cd0dabe30e9f90ac854462cdb65440d9acd5c83..3d11435f1ba567d0929505e85f54aa5e2d427560 100644
199--- a/dist/internal/proxyProcessSource.js
200+++ b/dist/internal/proxyProcessSource.js
201@@ -54,6 +54,8 @@ export const run = () => {
202 socket.write(header, (error) => error ? reject(error) : resolve(socket))
203 })
204 })
205+ // Each spawned command, with the process or group that kills it
206+ const running = new Map()
207 const spawn = async (socketPath , token , { args, command, id, options } ) => {
208 const stdio = await Promise.allSettled(
209 options.stdio.map((mode, fd) => mode === "pipe" ? connect(socketPath, token, id, fd) : mode)
210@@ -71,6 +73,8 @@ export const run = () => {
211 if (errno) throw new Error(\`setBlocking failed: \${Util.getSystemErrorName(errno)}\`)
212 }
213 const child = ChildProcess.spawn(command, args, { ...options, stdio: values })
214+ child.on("spawn", () => running.set(child, options.detached ? -child.pid : child.pid))
215+ child.on("exit", () => running.delete(child))
216 child.on("error", (error) => send({ _tag: "Error", id, error: serializeError(error) }))
217 child.on("spawn", () => send({ _tag: "Spawned", id, pid: child.pid }))
218 child.on("exit", (code, signal) => send({ _tag: "Exit", id, code, signal }))
219@@ -85,8 +89,19 @@ export const run = () => {
220 // the proxy process exits when its commands have exited.
221 process.on("SIGINT", () => {})
222 process.on("SIGTERM", () => {})
223+ // An application that was killed never stops its commands, so they die with its channel.
224+ // A deliberate close leaves them, so an unreferenced command can outlive the application.
225+ let closing = false
226+ process.on("disconnect", () => {
227+ if (closing) return
228+ for (const target of running.values()) {
229+ try {
230+ process.kill(target, "SIGKILL")
231+ } catch {}
232+ }
233+ })
234 process.once("message", ({ socketPath, token } ) => {
235- process.on("message", (request ) => spawn(socketPath, token, request))
236+ process.on("message", (request ) => request._tag === "Close" ? closing = true : spawn(socketPath, token, request))
237 send({ _tag: "Ready" })
238 })
239 }
240diff --git a/dist/internal/proxyProcessWorker.js b/dist/internal/proxyProcessWorker.js
241index 6694313fefcd21da1d020c46e616a2cb9c318bfd..92dd0a180952127c04f1ef6fcea4d35809c83f38 100644
242--- a/dist/internal/proxyProcessWorker.js
243+++ b/dist/internal/proxyProcessWorker.js
244@@ -49,6 +49,8 @@ export const run = () => {
245 socket.write(header, error => error ? reject(error) : resolve(socket));
246 });
247 });
248+ // Each spawned command, with the process or group that kills it
249+ const running = new Map();
250 const spawn = async (socketPath, token, {
251 args,
252 command,
253@@ -72,6 +74,8 @@ export const run = () => {
254 ...options,
255 stdio: values
256 });
257+ child.on("spawn", () => running.set(child, options.detached ? -child.pid : child.pid));
258+ child.on("exit", () => running.delete(child));
259 child.on("error", error => send({
260 _tag: "Error",
261 id,
262@@ -103,11 +107,22 @@ export const run = () => {
263 // the proxy process exits when its commands have exited.
264 process.on("SIGINT", () => {});
265 process.on("SIGTERM", () => {});
266+ // An application that was killed never stops its commands, so they die with its channel.
267+ // A deliberate close leaves them, so an unreferenced command can outlive the application.
268+ let closing = false;
269+ process.on("disconnect", () => {
270+ if (closing) return;
271+ for (const target of running.values()) {
272+ try {
273+ process.kill(target, "SIGKILL");
274+ } catch {}
275+ }
276+ });
277 process.once("message", ({
278 socketPath,
279 token
280 }) => {
281- process.on("message", request => spawn(socketPath, token, request));
282+ process.on("message", request => request._tag === "Close" ? closing = true : spawn(socketPath, token, request));
283 send({
284 _tag: "Ready"
285 });