Skip to content

Commit f9d07be

Browse files
committed
Read the output of a child before telling the VM it exited and hold up to 16 MB of it, so the JDK's drain at exit finds all of it
1 parent 3950235 commit f9d07be

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

‎src/process-node.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ function findProgram(command: string, cwd: string, parentPath: string | undefine
4545
return Object.assign(new Error(denied ? "EACCES" : "ENOENT"), { code: denied ? "EACCES" : "ENOENT", errno: denied ? -13 : -2 });
4646
}
4747

48+
// A child's output waits in memory up to this many bytes before the child is held back. The JDK
49+
// reads what is left in a pipe when a child exits, so the output is better read than left in the pipe.
50+
const HELD = 1 << 24;
51+
4852
class Pipe implements ProcessPipe {
4953
private chunks: Uint8Array[] = [];
5054
private length = 0;
@@ -65,7 +69,7 @@ class Pipe implements ProcessPipe {
6569
input.on("data", (chunk: Buffer) => {
6670
this.chunks.push(new Uint8Array(chunk));
6771
this.length += chunk.length;
68-
if (this.length >= 65536) for (const stream of this.inputs) stream.pause();
72+
if (this.length >= HELD) for (const stream of this.inputs) stream.pause();
6973
this.notify();
7074
});
7175
let done = false;
@@ -93,7 +97,7 @@ class Pipe implements ProcessPipe {
9397
copied += take;
9498
}
9599
this.length -= n;
96-
if (this.length < 32768) for (const stream of this.inputs) stream.resume();
100+
if (this.length < HELD / 2) for (const stream of this.inputs) stream.resume();
97101
return n;
98102
}
99103
write(bytes: Uint8Array): Promise<string | null> {
@@ -249,7 +253,12 @@ export function processNatives(entry: string, jdk: string, packaged: boolean, ho
249253
merged?.writer.destroy();
250254
const status = (code: number | null, signal: NodeJS.Signals | null) =>
251255
code ?? 128 + ((os.constants.signals as Record<string, number>)[signal ?? ""] ?? 0);
252-
const exited = new Promise<number>((resolve) => child.once("exit", (code, signal) => resolve(status(code, signal))));
256+
// After exit the output still on its way is read before the VM hears of it: on close, or a
257+
// moment after exit when a grandchild keeps a pipe open
258+
const exited = new Promise<number>((resolve) => {
259+
child.once("exit", (code, signal) => { setTimeout(() => resolve(status(code, signal)), 250); });
260+
child.once("close", (code, signal) => resolve(status(code, signal)));
261+
});
253262
const created: number[] = [];
254263
for (let i = 0; i < 3; i++) {
255264
if (i === 2 && redirectError) {

0 commit comments

Comments
 (0)