Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
16 changes: 15 additions & 1 deletion src/js/builtins/ProcessObjectInternals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,21 @@ export function getStdioWriteStream(
stream.fd = fd;

const underlyingSink = stream[require("internal/fs/streams").kWriteStreamFastPath];
$assert(underlyingSink);
if (!underlyingSink && !stream._writableState.autoDestroy) {
// No FileSink: writes go through Writable, which parks them after a failed write until the stream is
// destroyed. Destroy it then (the _destroy above resets it), but keep end() final, as with a FileSink.
const write = stream._write;
stream._write = function (chunk, encoding, cb) {
write.$call(this, chunk, encoding, err => {
if (err) this._writableState.autoDestroy = true;
Comment thread
robobun marked this conversation as resolved.
Resolved
cb(err);
});
};
stream._final = function (cb) {
this._writableState.autoDestroy = false;
cb();
};
Comment thread
robobun marked this conversation as resolved.
Resolved
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return [stream, underlyingSink];
}

Expand Down
39 changes: 28 additions & 11 deletions src/js/internal/fs/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import type { FileSink } from "bun";
const { Readable, Writable, finished } = require("node:stream");
const fs = require("node:fs");
const { read, write, fsync, writev } = fs;
const { read, write, writeSync, fsync, writev } = fs;
const { FileHandle, kRef, kUnref, kFd } = (fs.promises as any).$data as {
FileHandle: { new (): FileHandle };
readonly kRef: unique symbol;
Expand Down Expand Up @@ -457,17 +457,21 @@ function WriteStream(this: FSStream, path: string | null | undefined, options?:
this.pos = start;
}

// A writer cannot be opened for every fd a caller may hand us -- a read-only
// descriptor is the common case, and node's tty.WriteStream accepts one. Fall
// back to the general path there, which surfaces the failure at write time the
// way node does, rather than throwing from the constructor.
// A writer cannot be opened for every fd a caller may hand us: its dup fails at the fd limit, and the event
// loop cannot poll every descriptor (macOS /dev/tty). Write synchronously there, like node's SyncWriteStream.
// A bad fd then fails at write time the way node does, rather than throwing from the constructor.
Comment thread
robobun marked this conversation as resolved.
Resolved
let fastWriter;
if (fastPath && fd != null) {
try {
fastWriter = Bun.file(fd).writer();
} catch {
fastPath = false;
this._write = underscoreWriteSync;
}
// Already-open fd (stdio): skip the async _construct round-trip so the
// stream is born constructed, like node's stdio streams (net.Socket /
// tty.WriteStream), which never allocate construct TickObjects.
Comment thread
robobun marked this conversation as resolved.
Resolved
this._construct = undefined;
}

// Enable fast path
Expand All @@ -477,12 +481,6 @@ function WriteStream(this: FSStream, path: string | null | undefined, options?:
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 /
// tty.WriteStream), which never allocate construct TickObjects.
this._construct = undefined;
}
}

Writable.$call(this, options);
Expand Down Expand Up @@ -602,6 +600,25 @@ function _write(data, encoding, cb) {
}
writeStreamPrototype._write = _write;

function underscoreWriteSync(this: FSStream, data: Buffer, encoding: any, cb: (err?: any) => void) {
const length = data.length;
let offset = 0;
while (offset < length) {
let written: number;
try {
written = writeSync(this.fd, data, offset, length - offset);
} catch (err: any) {
if (err?.code !== "EAGAIN") return cb(err);
// A non-blocking fd with no room: wait for the reader, as a blocking write would.
Bun.sleepSync(1);
Comment thread
robobun marked this conversation as resolved.
Resolved
continue;
}
this.bytesWritten += written;
offset += written;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
cb(null);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function underscoreWriteFast(this: FSStream, data: any, encoding: any, cb: any) {
let fileSink = this[kWriteStreamFastPath];
if (!fileSink) {
Expand Down
58 changes: 58 additions & 0 deletions test/js/node/process/process-stdio-no-sink-fixture.mjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

241 changes: 241 additions & 0 deletions test/js/node/process/process-stdio-no-sink.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isLinux, isWindows, tempDir } from "harness";
import { mkfifo } from "mkfifo";
import fs from "node:fs";
import path from "path";

// process.stdout / process.stderr with no FileSink. Bun.file(fd).writer() throws when its dup fails (the fd table is
// full when the stream is first read) or when the event loop cannot poll the fd. The stream then writes with
// fs.writeSync, and its callers must see the same stream as with a FileSink.
//
// POSIX only: on Windows the writer cannot fail for fd 1 or 2.
// Not concurrent: each test starts one bun, and on a debug build several at once come close to the test timeout.
describe.skipIf(isWindows)("process.stdout/stderr with no FileSink", () => {
const fixture = path.join(import.meta.dir, "process-stdio-no-sink-fixture.mjs");
// The fixture fills the fd table before it reads the stream. `ulimit -n` keeps that table small.
const atFdLimit = (...args: string[]) => ["/bin/sh", "-c", 'ulimit -n 64 && exec "$@"', "sh", bunExe(), ...args];
// A debug build prints other lines on stderr too. With no report, show them all.
const reportIn = (output: string) => {
const line = output.split("\n").find(line => line.startsWith('{"type":'));
return line === undefined ? output : JSON.parse(line);
};
const EPIPE6 = ["EPIPE", "EPIPE", "EPIPE", "EPIPE", "EPIPE", "EPIPE"];

test.each(["stdout", "stderr"] as const)(
"process.%s: every write gets its callback when the reader is gone",
async which => {
await using proc = Bun.spawn({
cmd: atFdLimit(fixture, which, "failed-writes"),
env: bunEnv,
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
});
const [data, report] = which === "stdout" ? [proc.stdout, proc.stderr] : [proc.stderr, proc.stdout];
await data.cancel();
proc.stdin.write("go");
await proc.stdin.end();
const [output, exitCode] = await Promise.all([report.text(), proc.exited]);
expect(reportIn(output)).toEqual({
type: "fs",
sink: false,
callbacks: EPIPE6,
errors: ["EPIPE", "EPIPE"],
writableLength: 0,
});
expect(exitCode).toBe(0);
},
);

// Pinned for a stream with a FileSink in process-stdout-write-after-end.test.ts.
test("process.stdout: a write after a finished end() is rejected", async () => {
await using proc = Bun.spawn({
cmd: atFdLimit(fixture, "stdout", "end-then-write"),
env: bunEnv,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(reportIn(stderr)).toEqual({
type: "fs",
sink: false,
callbacks: [null, "ERR_STREAM_WRITE_AFTER_END", "ERR_STREAM_WRITE_AFTER_END"],
errors: ["ERR_STREAM_WRITE_AFTER_END"],
writableEnded: true,
});
expect(stdout).toBe("AB");
expect(exitCode).toBe(0);
});

test("process.stdout: end(chunk) in the tick that first reads the stream delivers the chunk", async () => {
await using proc = Bun.spawn({
cmd: atFdLimit(fixture, "stdout", "end-in-first-tick"),
env: bunEnv,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(reportIn(stderr)).toEqual({
type: "fs",
sink: false,
callbacks: ["ERR_STREAM_WRITE_AFTER_END"],
errors: ["ERR_STREAM_WRITE_AFTER_END"],
});
expect(stdout).toBe("E");
expect(exitCode).toBe(0);
});

test.each(["stdout", "stderr"] as const)(
"process.%s: bytes written before process.exit() reach a pipe",
async which => {
await using proc = Bun.spawn({
cmd: atFdLimit(fixture, which, "write-then-exit"),
env: bunEnv,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const [data, report] = which === "stdout" ? [stdout, stderr] : [stderr, stdout];
expect(reportIn(report)).toEqual({ type: "fs", sink: false });
expect(data).toContain("written before exit\n");
expect(exitCode).toBe(0);
},
);

test("process.stdout: bytes written before process.exit() reach a file", async () => {
using dir = tempDir("stdio-no-sink", {});
const out = path.join(String(dir), "out.txt");
const fd = fs.openSync(out, "w");
try {
await using proc = Bun.spawn({
cmd: atFdLimit(fixture, "stdout", "write-then-exit"),
env: bunEnv,
stdin: "ignore",
stdout: fd,
stderr: "pipe",
});
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
expect(reportIn(stderr)).toEqual({ type: "fs", sink: false });
expect(fs.readFileSync(out, "utf8")).toBe("written before exit\n");
expect(exitCode).toBe(0);
} finally {
fs.closeSync(fd);
}
});

// Every stdio fd is the terminal here, so the bytes of the stream and the report arrive in one output.
test.each(["end-then-write", "write-then-exit"] as const)("process.stdout on a TTY: %s", async scenario => {
let output = "";
const closed = Promise.withResolvers<void>();
await using proc = Bun.spawn({
cmd: atFdLimit(fixture, "stdout", scenario),
env: bunEnv,
terminal: {
data(_terminal, chunk) {
output += Buffer.from(chunk).toString();
},
exit() {
closed.resolve();
},
},
});
await closed.promise;
output = output.replaceAll("\r\n", "\n");
const at = output.indexOf('{"type":');
// With no report, show everything the child printed.
const seen = at < 0 ? output : { written: output.slice(0, at), report: reportIn(output.slice(at)) };
const rejected = {
type: "tty",
sink: false,
callbacks: [null, "ERR_STREAM_WRITE_AFTER_END", "ERR_STREAM_WRITE_AFTER_END"],
errors: ["ERR_STREAM_WRITE_AFTER_END"],
writableEnded: true,
};
expect(seen).toEqual(
scenario === "end-then-write"
? { written: "AB", report: rejected }
: { written: "written before exit\n", report: { type: "tty", sink: false } },
);
expect(await proc.exited).toBe(0);
});

// Bun.file(1).writer() puts O_NONBLOCK on the stdout description and stays open, so the stream meets EAGAIN once
// the pipe is full. The parent starts to read only after the child has begun its write.
test("process.stdout: a write larger than a non-blocking pipe waits for the reader", async () => {
const size = 1 << 20;
const script = /* js */ `
const fs = require("fs");
void fs.WriteStream;
const writer = Bun.file(1).writer();
const held = [];
try {
for (;;) held.push(fs.openSync("/dev/null", "r"));
} catch {}
const stdout = process.stdout;
for (const fd of held) fs.closeSync(fd);
fs.writeSync(2, "writing\\n");
stdout.write(Buffer.alloc(${size}, "x"));
process.exit(writer ? 0 : 1);
`;
await using proc = Bun.spawn({
cmd: atFdLimit("-e", script),
env: bunEnv,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
let stderr = "";
for await (const chunk of proc.stderr) {
stderr += Buffer.from(chunk).toString();
Comment thread
robobun marked this conversation as resolved.
Resolved
if (stderr.includes("writing\n")) break;
}
const [stdout, exitCode] = await Promise.all([proc.stdout.bytes(), proc.exited]);
expect(stdout.length).toBe(size);
expect(Buffer.from(stdout).equals(Buffer.alloc(size, "x"))).toBe(true);
expect(exitCode).toBe(0);
});

// An O_PATH descriptor on a FIFO cannot be polled (epoll_ctl reports EBADF), so the stream has no FileSink and every
// write fails. Node has no such stream: its getter throws `open EBADF` for this fd.
const onFifo = /* js */ `
const fs = require("fs");
const [which, fifo] = process.argv.slice(1);
const fd = which === "stdout" ? 1 : 2;
fs.closeSync(fd);
const O_PATH = 0o10000000;
if (fs.openSync(fifo, O_PATH) !== fd) throw new Error("the fifo did not land on fd " + fd);
const stream = process[which];
const sink = Object.getOwnPropertySymbols(stream).some(s => s.description === "kWriteStreamFastPath");
const callbacks = [], errors = [];
const write = chunk => stream.write(chunk, e => callbacks.push(e?.code ?? null));
stream.on("error", e => {
if (errors.push(e.code) === 1) for (let i = 0; i < 5; i++) write("y");
});
write("x");
process.on("exit", () => {
const report = { type: stream._type, sink, callbacks, errors, writableLength: stream.writableLength };
fs.writeSync(fd === 1 ? 2 : 1, JSON.stringify(report) + "\\n");
});
`;
const EBADF6 = ["EBADF", "EBADF", "EBADF", "EBADF", "EBADF", "EBADF"];

test.skipIf(!isLinux).each(["stdout", "stderr"] as const)("process.%s on an O_PATH fifo", async which => {
using dir = tempDir("stdio-no-sink", {});
const fifo = path.join(String(dir), "fifo");
mkfifo(fifo);
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", onFifo, which, fifo],
env: bunEnv,
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
const expected = { type: "fs", sink: false, callbacks: EBADF6, errors: ["EBADF", "EBADF"], writableLength: 0 };
expect(reportIn(which === "stdout" ? stderr : stdout)).toEqual(expected);
expect(exitCode).toBe(0);
});
});
Loading