Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
77066e2
console.write: handle every failed write when given several arguments
dylan-conway Sep 21, 2026
fbf7c3a
console.write: only a Promise is pending; intrinsics for the array an…
dylan-conway Sep 21, 2026
7072113
console.write: sum the pending Promises without Promise.all
dylan-conway Sep 21, 2026
5c4dae0
console.write: write every argument natively
dylan-conway Sep 21, 2026
7288f3a
console-write test: check the pipe is broken, and cover mixed argumen…
dylan-conway Sep 21, 2026
10773d4
console.write: crediting the counts never replaces a stored error
dylan-conway Sep 21, 2026
33f6390
console.write: a pending operation a later argument settles; flush af…
dylan-conway Sep 21, 2026
28530c9
Sink: the flush result's conversion to JS is not generic
dylan-conway Sep 21, 2026
6afac97
FileSink: a write that flushes earlier chunks reports its own bytes
dylan-conway Sep 21, 2026
63035f1
console.write: a flush that leaves the sink backed up gives the calle…
dylan-conway Sep 21, 2026
e096f7c
FileSink: a write to a sink that failed reports the error it failed with
dylan-conway Sep 21, 2026
9716f7d
FileSink: a sink that was closed stays "done"
dylan-conway Sep 21, 2026
958f02e
FileSink: a write to a finished sink is "done" again
dylan-conway Sep 21, 2026
a2aaf97
filesink test: the un-awaited writes case is POSIX behaviour
dylan-conway Sep 21, 2026
8fcb219
Merge branch 'main' of github.com:oven-sh/bun into claude/filesink-wi…
dylan-conway Sep 21, 2026
9b14b3d
Terminal: the writer no longer reports more than the chunk
dylan-conway Sep 21, 2026
5c98ced
console.write: a Promise that never reaches the caller is not an unha…
dylan-conway Sep 21, 2026
54188c4
console.write: tell the sink's operations apart by their Promise
dylan-conway Sep 21, 2026
80f235d
console.write: carry only this call's bytes; shorter comments
dylan-conway Sep 21, 2026
ec2c027
console-write and filesink tests: the new spawning tests run concurre…
dylan-conway Sep 21, 2026
c45bae8
console.write: back to the loop in JS; mark the Promises it drops as …
dylan-conway Sep 21, 2026
a64b952
console-write test: the later write failing is how it always was
dylan-conway Sep 21, 2026
4e0d147
fs.promises.writeFile test: short and long chunks from an async iterator
dylan-conway Sep 21, 2026
92fb862
console.write: only a Promise that is already rejected is marked handled
dylan-conway Sep 21, 2026
44600fe
console.write: a write that settled before the call was over counts
dylan-conway Sep 22, 2026
ca1353b
console-write test: find the C library the way the harness does
dylan-conway Sep 22, 2026
9975cb5
console.write: what is not a Promise adds up as it did in 1.4.2
dylan-conway Sep 23, 2026
8ab6db2
console.write: no private slot; a failed write's Promise is told apar…
dylan-conway Sep 23, 2026
4133870
Merge branch 'main' of github.com:oven-sh/bun into claude/filesink-wi…
dylan-conway Sep 23, 2026
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
1 change: 1 addition & 0 deletions src/codegen/generate-js2native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const sourceFiles = readdirRecursiveWithExclusionsAndExtensionsSync(
const rustIdentifierPaths: Record<string, string> = {
"bun.rs": "bun.rs",
"ipc.rs": "runtime/ipc_host.rs",
"FileSink.rs": "runtime/webcore/FileSink.rs",
"Counters.rs": "jsc/Counters.rs",
"FrameworkRouter.rs": "runtime/bake/FrameworkRouter.rs",
"JSBundler.rs": "runtime/api/JSBundler.rs",
Expand Down
1 change: 1 addition & 0 deletions src/js/builtins/BunBuiltinNames.h
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ using namespace JSC;
macro(writable) \
macro(writableType) \
macro(write) \
macro(writeAll) \
macro(writer) \
macro(written) \
BUN_ADDITIONAL_BUILTIN_NAMES(macro)
Expand Down
29 changes: 11 additions & 18 deletions src/js/builtins/ConsoleObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,33 +119,26 @@ interface ConsoleWriter extends Bun.FileSink {
flush(wait?: boolean): number | Promise<number>;
}

export function write(this: Console & { $writer: ConsoleWriter | undefined }, input) {
// The signature of a builtin stays on one line: bundle-functions.ts does not parse a parameter list with braces in it.
interface ConsoleWithWriter {
$writer: ConsoleWriter | undefined;
$writeAll: (this: ConsoleWriter, ...chunks: unknown[]) => number | Promise<number>;
}

export function write(this: ConsoleWithWriter, input) {
if (!$isObject(this)) throw $ERR_INVALID_THIS("Console");

var writer = $getByIdDirectPrivate(this, "writer");
if (!writer) {
var length = $toLength(input?.length ?? 0);
writer = Bun.stdout.writer({ highWaterMark: length > 65536 ? length : 65536 });
$putByIdDirectPrivate(this, "writer", writer);
// Writes every argument and flushes once, natively: there a failed write is an error value and a backed-up one
// is the sink's one pending operation, where here they would be a Promise each to tell apart and to handle.
$putByIdDirectPrivate(this, "writeAll", $newRustFunction("FileSink.rs", "consoleWrite", 1));
}

// A backed-up writer (FileSink) returns a Promise instead of a count: one Promise, the same for every write made
// while it is backed up, of the bytes those writes added. The caller gets a Promise of the total then, because
// awaiting it waits for the drain and is where a write error (EPIPE from a reader that hung up) arrives.
var wrote = 0;
var pending: Promise<number> | undefined;
const count = $argumentCount();
var i = 0;
do {
const result = writer.write(arguments[i]);
if (typeof result === "number") wrote += result;
else pending = result;
} while (++i < count);

writer.flush(true);
if (pending === undefined) return wrote;
if (wrote === 0) return pending;
return pending.then(n => wrote + n);
return $getByIdDirectPrivate(this, "writeAll").$apply(writer, arguments);
}

// This is the `console.Console` constructor. It is mostly copied from Node.
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/webcore/FileSink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,12 @@ impl FileSink {
// `Sink.JSSink(@This(), "FileSink")` — generic-fn-returning-type → monomorphized type alias.
pub(crate) type JSSink = crate::webcore::sink::JSSink<FileSink>;

/// `console.write()` (src/js/builtins/ConsoleObject.ts): `this` is the console's writer, a `Bun.stdout.writer()`.
#[bun_jsc::host_fn]
pub(crate) fn console_write(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
JSSink::js_write_all(global, frame)
}

crate::impl_js_sink_abi!(FileSink, "FileSink");

// `JsSinkType` impl: routes the codegen `FileSink__*` thunks (via
Expand Down
108 changes: 87 additions & 21 deletions src/runtime/webcore/Sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,16 @@ impl<T: JsSinkType> JSSink<T> {
)));
}

let arg = frame.argument(0);
Ok(Self::write_value(this, global, frame.argument(0))?.to_js(&cx))
}

/// One chunk from JS into the sink: bytes as they are, a string by its encoding.
fn write_value(
this: &mut JSSink<T>,
global: &crate::webcore::jsc::JSGlobalObject,
arg: crate::webcore::jsc::JSValue,
) -> crate::webcore::jsc::JsResult<streams::result::Writable> {
use streams::result::Writable;
arg.ensure_still_alive();
let _keep = bun_jsc::EnsureStillAlive(arg);

Expand All @@ -534,14 +543,11 @@ impl<T: JsSinkType> JSSink<T> {
if let Some(buffer) = arg.as_array_buffer(global) {
let slice = buffer.slice();
if slice.is_empty() {
return Ok(JSValue::js_number(0.0));
return Ok(Writable::Owned(0));
}
// Borrowed view over GC-kept buffer for the duration of the call.
let data = bun_ptr::RawSlice::new(slice);
return Ok(this
.sink
.write_bytes(&streams::Result::Temporary(data))
.to_js(&cx));
return Ok(this.sink.write_bytes(&streams::Result::Temporary(data)));
}

if !arg.is_string() {
Expand All @@ -553,24 +559,75 @@ impl<T: JsSinkType> JSSink<T> {

let view = arg.to_js_string_view(global)?;
if view.is_empty() {
return Ok(JSValue::js_number(0.0));
return Ok(Writable::Owned(0));
}

if view.is_utf16() {
let utf16 = view.utf16();
let bytes: &[u8] = bytemuck::cast_slice(utf16);
let data = bun_ptr::RawSlice::new(bytes);
return Ok(this
.sink
.write_utf16(&streams::Result::Temporary(data))
.to_js(&cx));
return Ok(this.sink.write_utf16(&streams::Result::Temporary(data)));
}

let data = bun_ptr::RawSlice::new(view.latin1());
Ok(this
.sink
.write_latin1(&streams::Result::Temporary(data))
.to_js(&cx))
Ok(this.sink.write_latin1(&streams::Result::Temporary(data)))
}

/// `console.write(...chunks)`: every argument written in order, one flush, one result.
///
/// The sink's results are combined here, where a failed write is still an error value and a backed-up write
/// is still the sink's one pending operation. Turned into JS values one write at a time they are a rejected
/// Promise each, and a Promise the caller has to recognise as one it already holds.
pub(crate) fn js_write_all(
global: &crate::webcore::jsc::JSGlobalObject,
frame: &crate::webcore::jsc::CallFrame,
) -> crate::webcore::jsc::JsResult<crate::webcore::jsc::JSValue> {
use crate::webcore::jsc::JSValue;
use streams::result::Writable;
let cx = global.js_thread_of_caller(frame);
bun_core::mark_binding!();
let Some(this) = Self::get_this(global, frame)? else {
return Ok(JSValue::js_number(0.0));
};

if let Some(err) = this.sink.get_pending_error() {
return Err(global.throw_value(err));
}

let mut wrote: u64 = 0;
let mut pending: Option<(*mut streams::WritablePending, JSValue)> = None;
// No argument is one `undefined` chunk, which write_value() rejects as write() does.
for i in 0..frame.arguments_count().max(1) as usize {
match Self::write_value(this, global, frame.argument(i))? {
// Nothing after it can succeed either. The pending operation, if there is one, is given the error
// by the sink itself: this is only reached with nothing pending.
Writable::Err(err) => return Ok(Writable::Err(err).to_js(&cx)),
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
Writable::Pending(operation) => {
pending = Some((operation, Writable::Pending(operation).to_js(&cx)));
}
Writable::Owned(n)
| Writable::OwnedAndDone(n)
| Writable::Temporary(n)
| Writable::Backpressure(n) => wrote += n,
// A finished sink: nothing written.
Writable::Done => {}
}
}

let Some((operation, promise)) = pending else {
Self::flush_value(this, global, &cx, true)?;
return Ok(JSValue::from(wrote));
};
// The Promise resolves to what the pending operation consumed. The counts are part of this call's total
// too: a chunk written before the sink backed up, or a small one buffered beside the operation.
// SAFETY: `operation` is the sink's pending slot, which the sink owns and `this` keeps alive; nothing
// has run since the write that returned it, so it is still the pending one.
unsafe {
(*operation).consumed += wrote;
(*operation).result = Writable::Owned((*operation).consumed);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
Self::flush_value(this, global, &cx, true)?;
Ok(promise)
}

/// `${abi_name}__flush` host-fn body.
Expand All @@ -579,8 +636,6 @@ impl<T: JsSinkType> JSSink<T> {
frame: &crate::webcore::jsc::CallFrame,
) -> crate::webcore::jsc::JsResult<crate::webcore::jsc::JSValue> {
let cx = global.js_thread_of_caller(frame);
use crate::webcore::jsc::JSValue;
use bun_sys_jsc::ErrorJsc;
bun_core::mark_binding!();

let Some(this) = Self::get_this(global, frame)? else {
Expand All @@ -591,11 +646,22 @@ impl<T: JsSinkType> JSSink<T> {
return Err(global.throw_value(err));
}

let wait = frame.arguments_count() > 0
&& frame.argument(0).is_boolean()
&& frame.argument(0).as_boolean();
Self::flush_value(this, global, &cx, wait)
}

fn flush_value(
this: &mut JSSink<T>,
global: &crate::webcore::jsc::JSGlobalObject,
cx: &bun_jsc::JsThread<'_>,
wait: bool,
) -> crate::webcore::jsc::JsResult<crate::webcore::jsc::JSValue> {
use crate::webcore::jsc::JSValue;
use bun_sys_jsc::ErrorJsc;
if T::HAS_FLUSH_FROM_JS {
let wait = frame.arguments_count() > 0
&& frame.argument(0).is_boolean()
&& frame.argument(0).as_boolean();
return match this.sink.flush_from_js(&cx, wait) {
return match this.sink.flush_from_js(cx, wait) {
sys::Result::Ok(value) => Ok(value),
sys::Result::Err(err) => Err(global.throw_value(err.to_js(global)?)),
};
Expand Down
51 changes: 51 additions & 0 deletions test/js/bun/console/console-write.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ console.error(JSON.stringify({ one, two }));

// The Promise a backed-up console.write() returns is where its write error arrives: a script that
// awaits it can handle a reader that hung up, instead of dying with an unhandled rejection.
//
// Not on Windows: a write to a pipe whose reader is alive is accepted whole there and returns its byte
// count, so whether this script sees a Promise at all depends on whether the reader is already gone.
test.skipIf(isWindows).each([
["one argument", ""],
["several arguments", ', "tail"'],
Expand Down Expand Up @@ -134,3 +137,51 @@ try {
expect(stderr).toBe("caught EPIPE\n");
expect(exitCode).toBe(0);
});

// Every write to a pipe that is already broken fails on the spot. console.write() called the sink's write() once
// per argument and kept the last Promise it got back, so a script that awaited it and caught the error still died
// of the unhandled rejection of another argument's write (or, with a short last argument, of the flush throwing
// past the Promise it had).
//
// The child blocks in a synchronous read of stdin until the parent has closed its end of stdout, and checks with
// a writer of its own that the pipe really is broken, so the test cannot pass by the writes simply being queued.
const big = `Buffer.alloc(1024 * 1024, "a").toString()`;
test.each([
["two large arguments", `${big}, ${big}`],
["a large argument, then a short one", `${big}, "\\n"`],
["a short argument, then a large one", `"\\n", ${big}`],
])("an awaited console.write to a broken pipe fails once: %s", async (_label, args) => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
process.on("unhandledRejection", e => {
console.error("unhandledRejection " + e?.code);
});
require("node:fs").readSync(0, Buffer.alloc(1));
const probe = Bun.stdout.writer().write(${big});
console.error("pipe already broken: " + (probe instanceof Promise && Bun.peek.status(probe) === "rejected"));
if (probe instanceof Promise) probe.catch(() => {});
try {
await console.write(${args});
console.error("resolved");
} catch (e) {
console.error("caught " + e.code);
}
`,
],
env: bunEnv,
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
});

await proc.stdout.cancel();
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
proc.stdin.write("x");
await proc.stdin.end();

const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
expect(stderr).toBe("pipe already broken: true\ncaught EPIPE\n");
expect(exitCode).toBe(0);
});
3 changes: 3 additions & 0 deletions test/js/bun/util/filesink.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1153,6 +1153,9 @@ it("start() with invalid options throws instead of silently ignoring them", asyn
//
// The child blocks in a synchronous read of stdin between its two writes, so no event-loop turn can tell the sink
// about the hang-up first: the second write() is the one that finds out, with the first still pending.
//
// Not on Windows: a write to a pipe whose reader is alive is accepted whole there and returns its byte count, so
// there is no pending promise for a later write to fail beside.
it.skipIf(isWindows)("a write() that fails while another is pending rejects the pending promise once", async () => {
await using proc = Bun.spawn({
cmd: [
Expand Down
Loading