Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 0 additions & 20 deletions src/js/builtins/ProcessObjectInternals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,26 +85,6 @@ export function getStdioWriteStream(
});
}
};

const kFastPath = require("internal/fs/streams").kWriteStreamFastPath;
stream._final = function (cb) {
try {
const sink = this[kFastPath];
if (sink && sink !== true) {
const result = sink.flush();
if ($isPromise(result)) {
result.then(
() => cb(null),
err => cb(err),
);
return;
}
}
cb(null);
} catch (err) {
cb(err);
}
};
}

stream._isStdio = true;
Expand Down
20 changes: 20 additions & 0 deletions src/js/internal/fs/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ function WriteStream(this: FSStream, path: string | null | undefined, options?:
this._write = underscoreWriteFast;
this._writev = undefined;
this.write = writeFast as any;
this._final = finalFast;
if (fd != null) {
// Already-open fd (stdio): skip the async _construct round-trip so the
// stream is born constructed, like node's stdio streams (net.Socket /
Expand Down Expand Up @@ -631,6 +632,25 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any)
}
}

function finalFast(this: FSStream, cb: (err?: any) => void) {
const fileSink = this[kWriteStreamFastPath];
if (!fileSink || fileSink === true) {
cb(null);
return;
}
try {
const maybePromise = fileSink.flush();
Comment thread
robobun marked this conversation as resolved.
Resolved
if ($isPromise(maybePromise)) {
maybePromise.then(() => cb(null), cb);
return;
}
} catch (err) {
cb(err);
return;
}
cb(null);
}

// This function implementation is not correct.
const writablePrototypeWrite = Writable.prototype.write;
const kWriteMonkeyPatchDefense = Symbol("!");
Expand Down
40 changes: 40 additions & 0 deletions test/js/node/child_process/child_process.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,46 @@ describe("spawn()", () => {
expect(result.trim()).toBe("hello");
});

// The child does not read stdin until the parent tells it to over IPC, so
// every write past the pipe buffer sits in the parent's sink when end() runs.
it("stdin.end(cb) and 'finish' wait for the backlog to drain", async () => {
const child = spawn(
bunExe(),
[
"-e",
`let n = 0;
process.on("message", () => {
process.stdin.on("data", d => { n += d.length; });
process.stdin.on("end", () => { process.stdout.write(String(n)); process.disconnect(); });
});`,
],
{ env: bunEnv, stdio: ["pipe", "pipe", "pipe", "ipc"] },
);
Comment thread
robobun marked this conversation as resolved.
Resolved
const stdout = new Promise<string>(resolve => {
let out = "";
child.stdout!.on("data", d => (out += d));
child.stdout!.on("end", () => resolve(out));
});
const exited = new Promise<number | null>(resolve => child.on("exit", resolve));

const order: string[] = [];
const chunk = Buffer.alloc(256 * 1024, 1);
for (let i = 0; i < 3; i++) child.stdin!.write(chunk);
child.stdin!.write(chunk, () => order.push("write"));
child.stdin!.on("finish", () => order.push("finish"));
const { promise: ended, resolve: onEnd } = Promise.withResolvers<void>();
child.stdin!.end(() => {
order.push("end");
onEnd();
});
child.send("go");

await ended;
expect(await stdout).toBe(String(4 * chunk.length));
expect(order).toEqual(["write", "end", "finish"]);
expect(await exited).toBe(0);
});

it("should allow us to timeout hanging processes", async () => {
const child = spawn(shellExe(), ["-c", "sleep", "2"], { timeout: 3 });
const start = performance.now();
Expand Down
45 changes: 45 additions & 0 deletions test/js/node/tty.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it, test } from "bun:test";
import { bunEnv, bunExe, isWindows } from "harness";
import { spawn } from "node:child_process";
import { WriteStream } from "node:tty";

describe("ReadStream.prototype.setRawMode", () => {
Expand Down Expand Up @@ -192,6 +193,50 @@ describe("ReadStream.prototype.setRawMode", () => {
});
});

describe("WriteStream end()", () => {
// The parent does not read the child's stdout until the child has called
// end(), so most of the 1 MiB sits in the stream's sink at that point. The
// callback must wait for it, or process.exit truncates the output.
it.skipIf(isWindows)("fires the callback after the backlog is flushed", async () => {
Comment thread
robobun marked this conversation as resolved.
Resolved
const child = spawn(
bunExe(),
[
"-e",
`const { WriteStream } = require("node:tty");
const out = new WriteStream(1);
const chunk = Buffer.alloc(256 * 1024, 120);
for (let i = 0; i < 4; i++) out.write(chunk);
out.end(() => process.exit(0));
process.send("ending");`,
],
{ env: bunEnv, stdio: ["ignore", "pipe", "pipe", "ipc"] },
);
let received = 0;
let reading = false;
// 'exit' is the fallback for a child that dies before it sends "ending".
const read = () => {
if (reading) return;
reading = true;
child.stdout!.on("data", d => (received += d.length));
};
child.on("message", read);
child.on("exit", read);
const stderr = new Promise<string>(resolve => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let err = "";
child.stderr!.on("data", d => (err += d));
child.stderr!.on("end", () => resolve(err));
});
const { promise: ended, resolve: onEnd } = Promise.withResolvers<void>();
child.stdout!.on("end", onEnd);
const exited = new Promise<number | null>(resolve => child.on("exit", resolve));

await ended;
expect(await stderr).toBe("");
expect(received).toBe(4 * 256 * 1024);
expect(await exited).toBe(0);
});
});

describe("WriteStream.prototype.getColorDepth", () => {
const getColorDepth = (env: Record<string, string>) => WriteStream.prototype.getColorDepth.call(undefined, env);

Expand Down
Loading