Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
22 changes: 15 additions & 7 deletions src/io/PipeWriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -840,10 +840,15 @@ impl<Parent: PosixStreamingWriterParent> PosixStreamingWriter<Parent> {
return WriteResult::Wrote(buf_len);
}

self.try_write_newly_buffered_data()
self.try_write_newly_buffered_data(buf_len)
}

fn try_write_newly_buffered_data(&mut self) -> WriteResult {
/// `chunk_len` is the caller's chunk (already appended to `outgoing`).
/// `Wrote`/`Done` report bytes of *that chunk*, not bytes drained from the
/// buffer (which includes older chunks the buffer path already reported).
/// `Pending` keeps the drained count — its caller-facing value is
/// re-derived from `buffered_len()` (see `FileSink::bytes_accepted`).
Comment thread
robobun marked this conversation as resolved.
Resolved
fn try_write_newly_buffered_data(&mut self, chunk_len: usize) -> WriteResult {
debug_assert!(!self.is_done);

// Borrow `self.outgoing` only for the syscall. `try_write` takes `&self`
Expand All @@ -856,19 +861,22 @@ impl<Parent: PosixStreamingWriterParent> PosixStreamingWriter<Parent> {

match rc {
WriteResult::Wrote(amt) => {
if amt == self.outgoing.size() {
self.outgoing.reset();
self.parent_on_write(amt, WriteStatus::Drained);
} else {
if amt < self.outgoing.size() {
self.outgoing.wrote(amt);
self.parent_on_write(amt, WriteStatus::Pending);
Self::register_poll(self);
return WriteResult::Pending(amt);
}
self.outgoing.reset();
self.parent_on_write(amt, WriteStatus::Drained);
return WriteResult::Wrote(chunk_len);
}
WriteResult::Done(amt) => {
debug_assert!(self.outgoing.size() >= chunk_len);
let old_buffered = self.outgoing.size() - chunk_len;
self.outgoing.reset();
self.parent_on_write(amt, WriteStatus::EndOfFile);
return WriteResult::Done(amt.saturating_sub(old_buffered));
}
WriteResult::Pending(amt) => {
self.outgoing.wrote(amt);
Expand Down Expand Up @@ -910,7 +918,7 @@ impl<Parent: PosixStreamingWriterParent> PosixStreamingWriter<Parent> {
return WriteResult::Err(sys::Error::oom());
}

return self.try_write_newly_buffered_data();
return self.try_write_newly_buffered_data(buf.len());
}

let rc = self.try_write(self.force_sync, buf);
Expand Down
47 changes: 46 additions & 1 deletion test/js/bun/util/filesink.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createSocketPair, fileSinkInternals } from "bun:internal-for-testing";
import { describe, expect, it } from "bun:test";
import { bunEnv, bunExe, fileDescriptorLeakChecker, isLinux, isPosix, isWindows, tmpdirSync } from "harness";
import { bunEnv, bunExe, fileDescriptorLeakChecker, isLinux, isPosix, isWindows, tempDir, tmpdirSync } from "harness";
import { mkfifo } from "mkfifo";
import { join } from "node:path";

Expand Down Expand Up @@ -207,6 +207,51 @@ it("write result is not cumulative", async () => {
await util.promisify(fs.close)(fd);
});

// https://github.com/oven-sh/bun/issues/12194
//
// A chunk that pushes the sink's internal buffer past its auto-flush threshold
// must still report its own byte count. Previously the write() that triggered
// the drain returned the whole drained total (older buffered chunks included),
// so a `total += sink.write(chunk)` loop double-counted.
//
// Writes are issued without `await` in between so the auto-flush microtask
// cannot drain the buffer first. Skipped on Windows: there every write to a
// file-backed sink returns a (shared) promise, which the backpressured-write
// tests below already cover.
it.skipIf(!isPosix)("write result is not cumulative when the chunk flushes buffered bytes", async () => {
using dir = tempDir("filesink-cumulative", {});
const filename = path.join(String(dir), "test.bin");
const writer = Bun.file(filename).writer();

const ascii = Buffer.alloc(505, "a").toString();
const bytes = Buffer.alloc(64 * 1024, "c");
// Decoding as "latin1" keeps the JSString 8-bit so writer.write() reaches
// write_latin1's non-ASCII branch; decoding via utf8 would yield a 16-bit
// string that routes to write_utf16 instead.
const latin1 = Buffer.alloc(40_000, 0xe9).toString("latin1");
const utf16 = Buffer.alloc(20_000, "😀").toString();

const results = [
writer.write(ascii), // buffered
writer.write(bytes), // flushes `ascii` + itself
writer.write(Buffer.alloc(10, "d")), // buffered
writer.write(latin1), // flushes the 10 bytes + itself (latin1 path)
writer.write("e"), // buffered
writer.write(utf16), // flushes the 1 byte + itself (utf16 path)
];
await writer.end();

expect(results).toEqual([
Buffer.byteLength(ascii),
bytes.byteLength,
10,
Buffer.byteLength(latin1),
1,
Buffer.byteLength(utf16),
]);
expect(results.reduce((sum, n) => sum + n, 0)).toBe(fs.statSync(filename).size);
});

// A backpressured write buffers everything `write(2)` would not take, so the
// Promise it returns has to resolve with the chunk's own byte count. It used to
// resolve with the partial `write(2)` return instead.
Expand Down
Loading