diff --git a/src/js/builtins/ProcessObjectInternals.ts b/src/js/builtins/ProcessObjectInternals.ts index 781025562a29..8ea675755e15 100644 --- a/src/js/builtins/ProcessObjectInternals.ts +++ b/src/js/builtins/ProcessObjectInternals.ts @@ -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; diff --git a/src/js/internal/fs/streams.ts b/src/js/internal/fs/streams.ts index 9fd151b947ac..8547718d143b 100644 --- a/src/js/internal/fs/streams.ts +++ b/src/js/internal/fs/streams.ts @@ -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 / @@ -558,6 +559,14 @@ function writevAll(chunks, size, pos, cb, retries = 0) { }); } +// Like Writable's afterWrite: no 'drain' once the stream is ending or destroyed. +function emitDrain(stream: FSStream) { + const state = stream._writableState; + if (state === undefined || !(state.ending || state.destroyed)) { + stream.emit("drain"); + } +} + function _write(data, encoding, cb) { const fileSink = this[kWriteStreamFastPath]; @@ -566,7 +575,7 @@ function _write(data, encoding, cb) { if ($isPromise(maybePromise)) { maybePromise .then(() => { - this.emit("drain"); // Emit drain event + emitDrain(this); cb(null); }) .catch(cb); @@ -612,7 +621,7 @@ function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) maybePromise.then( () => { if (cb) cb(null); - this.emit("drain"); + emitDrain(this); }, err => { if (cb) cb(err); @@ -631,6 +640,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(); + 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("!"); @@ -660,7 +688,7 @@ function writeFast(this: FSStream, data: any, encoding: any, cb: any) { // mistaken for a write failure. maybePromise.then( () => { - this.emit("drain"); // Emit drain event + emitDrain(this); cb(null); }, err => { @@ -703,7 +731,7 @@ writeStreamPrototype._writev = function (data, cb) { if ($isPromise(maybePromise)) { maybePromise .then(() => { - this.emit("drain"); + emitDrain(this); cb(null); }) .catch(cb); diff --git a/test/js/node/child_process/child_process.test.ts b/test/js/node/child_process/child_process.test.ts index fe7f6ec07465..333f055e9514 100644 --- a/test/js/node/child_process/child_process.test.ts +++ b/test/js/node/child_process/child_process.test.ts @@ -389,6 +389,53 @@ 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"] }, + ); + const collect = (stream: NodeJS.ReadableStream) => + new Promise(resolve => { + let out = ""; + stream.on("data", d => (out += d)); + stream.on("end", () => resolve(out)); + }); + const stdout = collect(child.stdout!); + const stderr = collect(child.stderr!); + const exited = new Promise(resolve => child.on("exit", resolve)); + + // Node emits no 'drain' once end() has been called. + 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("drain", () => order.push("drain")); + child.stdin!.on("finish", () => order.push("finish")); + const { promise: ended, resolve: onEnd, reject } = Promise.withResolvers(); + child.stdin!.end(() => { + order.push("end"); + onEnd(); + }); + child.on("exit", code => reject(new Error(`child exited with ${code} before end(cb) ran`))); + child.send("go"); + + await ended; + expect(await stderr).toBe(""); + 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(); diff --git a/test/js/node/tty.test.ts b/test/js/node/tty.test.ts index 3eca2321a0fa..74b28d2e09f2 100644 --- a/test/js/node/tty.test.ts +++ b/test/js/node/tty.test.ts @@ -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", () => { @@ -192,6 +193,54 @@ 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. + // + // Windows: a write to an inherited stdout pipe blocks until the reader + // drains it (every write() returns true), so the child never reaches end() + // while the parent waits, and there is no backlog to flush. + it.skipIf(isWindows)("fires the callback after the backlog is flushed", async () => { + 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(resolve => { + let err = ""; + child.stderr!.on("data", d => (err += d)); + child.stderr!.on("end", () => resolve(err)); + }); + const { promise: ended, resolve: onEnd } = Promise.withResolvers(); + child.stdout!.on("end", onEnd); + const exited = new Promise(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) => WriteStream.prototype.getColorDepth.call(undefined, env);