Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 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: 17 additions & 5 deletions src/io/PipeReader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,18 +232,21 @@ impl PosixBufferedReader {
}
}

pub fn update_ref(&mut self, value: bool) {
/// Returns the previous ref state.
pub fn update_ref(&mut self, value: bool) -> bool {
let previous = self.flags.contains(PosixFlags::KEEP_ALIVE);
// Remember the ref state so a poll created later (lazy start) honours
// an unref() that preceded the first registration.
self.flags.set(PosixFlags::KEEP_ALIVE, value);
let Some(poll) = self.handle.get_poll() else {
return;
return previous;
};
// An unarmed poll delivers nothing; `try_register_poll` applies KEEP_ALIVE when it arms.
if value && !poll.is_watching() {
return;
return previous;
}
poll.set_keeping_process_alive(self.vtable.event_loop(), value);
previous
}

#[inline]
Expand Down Expand Up @@ -1016,13 +1019,18 @@ bitflags::bitflags! {
/// When true, wait for the file operation callback before calling done().
/// Used to ensure proper cleanup ordering when closing during cancellation.
const DEFER_DONE_CALLBACK = 1 << 9;
const KEEP_ALIVE = 1 << 10; // default true
}
}

#[cfg(windows)]
impl WindowsFlags {
pub(crate) const fn new() -> Self {
Self::from_bits_truncate(WindowsFlags::CLOSE_HANDLE.bits() | WindowsFlags::IS_PAUSED.bits())
Self::from_bits_truncate(
WindowsFlags::CLOSE_HANDLE.bits()
| WindowsFlags::IS_PAUSED.bits()
| WindowsFlags::KEEP_ALIVE.bits(),
)
}
}

Expand Down Expand Up @@ -1101,14 +1109,18 @@ impl WindowsBufferedReader {
}
}

pub fn update_ref(&mut self, value: bool) {
/// Returns the previous ref state.
pub fn update_ref(&mut self, value: bool) -> bool {
let previous = self.flags.contains(WindowsFlags::KEEP_ALIVE);
self.flags.set(WindowsFlags::KEEP_ALIVE, value);
if let Some(source) = self.source.as_mut() {
if value {
source.ref_();
} else {
source.unref();
}
}
previous
}

pub fn disable_keeping_process_alive<C>(&mut self, _: C) {
Expand Down
38 changes: 18 additions & 20 deletions src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "JSWritableStreamDefaultWriter.h"
#include "ObjectBindings.h"
#include "VectorSizeLimit.h"
#include "ZigGeneratedClasses.h"
#include "ZigGlobalObject.h"

#include <JavaScriptCore/InternalFieldTuple.h>
Expand Down Expand Up @@ -486,6 +487,19 @@ JSPromise* readableStreamCancel(JSGlobalObject* globalObject, JSReadableStream*
return result;
}

// Bun: a FileReader source (the only kind with an event-loop ref) drops that ref while no reader holds the stream.
static void setNativeSourceReaderLocked(JSReadableStream* stream, bool locked)
{
if (stream->m_controllerKind != ControllerKind::Default)
return;
auto* controller = defaultControllerOf(stream);
if (controller->m_algorithms.kind != SourceKind::Native)
return;
const auto* adapter = uncheckedDowncast<WebCore::JSNativeStreamSourceAdapter>(controller->m_algorithms.algorithmContext.get());
if (auto* source = dynamicDowncast<WebCore::JSFileInternalReadableStreamSource>(adapter->handle()))
FileReader__setReaderLocked(source->wrapped(), locked);
}

// ReadableStreamReaderGenericInitialize(reader, stream)
void readableStreamReaderGenericInitialize(JSGlobalObject* globalObject, JSReadableStreamReaderBase* reader, JSReadableStream* stream)
{
Expand All @@ -496,6 +510,7 @@ void readableStreamReaderGenericInitialize(JSGlobalObject* globalObject, JSReada
switch (stream->m_state) {
case ReadableStreamState::Readable:
reader->m_closedPromise.set(vm, reader, JSPromise::create(vm, globalObject->promiseStructure()));
setNativeSourceReaderLocked(stream, true);
return;
case ReadableStreamState::Closed: {
auto* closedPromise = promiseFulfilledWith(globalObject, JSC::jsUndefined());
Expand Down Expand Up @@ -551,27 +566,10 @@ void readableStreamReaderGenericRelease(JSGlobalObject* globalObject, JSReadable
}
break;
}
case ControllerKind::Default: {
auto* controller = defaultControllerOf(stream);
controller->releaseSteps();
// Bun: drop the native handle's event-loop ref when its consumer releases the lock.
if (controller->m_algorithms.kind == SourceKind::Native) {
const auto* adapter = uncheckedDowncast<WebCore::JSNativeStreamSourceAdapter>(controller->m_algorithms.algorithmContext.get());
if (auto* handle = adapter->handle()) {
JSValue updateRef = handle->getIfPropertyExists(globalObject, builtinNames(vm).updateRefPublicName());
RETURN_IF_EXCEPTION(scope, void());
if (updateRef && updateRef.isCallable()) {
auto callData = JSC::getCallData(updateRef);
MarkedArgumentBuffer args;
args.append(jsBoolean(false));
ASSERT(!args.hasOverflowed());
JSC::call(globalObject, updateRef, callData, handle, args);
RETURN_IF_EXCEPTION(scope, void());
}
}
}
case ControllerKind::Default:
defaultControllerOf(stream)->releaseSteps();
setNativeSourceReaderLocked(stream, false);
break;
}
case ControllerKind::Byte:
byteControllerOf(stream)->releaseSteps();
break;
Expand Down
4 changes: 3 additions & 1 deletion src/jsc/bindings/webcore/streams/WebStreamsInternals.h
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,9 @@ void setUpReadableStreamDefaultReader(JSC::JSGlobalObject*, JSReadableStreamDefa
void setUpReadableStreamBYOBReader(JSC::JSGlobalObject*, JSReadableStreamBYOBReader*, JSReadableStream*); // userJS: no — ReadableStreamOperations.cpp
JSC::JSPromise* readableStreamReaderGenericCancel(JSC::JSGlobalObject*, JSReadableStreamReaderBase*, JSC::JSValue reason); // userJS: yes — ReadableStreamOperations.cpp
void readableStreamReaderGenericInitialize(JSC::JSGlobalObject*, JSReadableStreamReaderBase*, JSReadableStream*); // userJS: no — ReadableStreamOperations.cpp
void readableStreamReaderGenericRelease(JSC::JSGlobalObject*, JSReadableStreamReaderBase*); // userJS: no (also runs Bun's native-handle updateRef(false) gate) — ReadableStreamOperations.cpp
void readableStreamReaderGenericRelease(JSC::JSGlobalObject*, JSReadableStreamReaderBase*); // userJS: no — ReadableStreamOperations.cpp
// Both of the above tell a FileReader source whether a reader holds its stream; the source drops its event-loop ref while none does.
extern "C" void FileReader__setReaderLocked(void* source, bool locked); // userJS: no — FileReader.rs

// Stream-level state ops.
JSC::JSPromise* readableStreamCancel(JSC::JSGlobalObject*, JSReadableStream*, JSC::JSValue reason); // userJS: yes — ReadableStreamOperations.cpp
Expand Down
25 changes: 25 additions & 0 deletions src/runtime/webcore/FileReader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ pub struct FileReader {
/// path; `pull_into_sink` is the drain-ack resume.
pub(crate) sink: JsCell<SinkHandle>,
pub(crate) sink_paused: Cell<bool>,
/// A reader release took a held event-loop ref away; the next reader lock gives it back. An explicit `updateRef` cancels that.
pub(crate) ref_dropped_on_release: Cell<bool>,
}

impl Default for FileReader {
Expand All @@ -90,6 +92,7 @@ impl Default for FileReader {
flowing: Cell::new(true),
sink: JsCell::new(SinkHandle::None),
sink_paused: Cell::new(false),
ref_dropped_on_release: Cell::new(false),
}
}
}
Expand Down Expand Up @@ -903,9 +906,23 @@ impl FileReader {
if self.done.get() {
return;
}
self.ref_dropped_on_release.set(false);
self.reader().update_ref(enable);
}

/// A reader locked (`true`) or released (`false`) the stream over this source. A released source does not keep the event loop alive.
pub(crate) fn set_reader_locked(&self, locked: bool) {
if self.done.get() {
return;
}
if !locked {
let was_ref = self.reader().update_ref(false);
self.ref_dropped_on_release.set(was_ref);
} else if self.ref_dropped_on_release.replace(false) {
self.reader().update_ref(true);
}
}

fn consume_reader_buffer(&self) {
if self.buffered.get().capacity() == 0 {
self.buffered.set(mem::take(self.reader().buffer()));
Expand Down Expand Up @@ -1068,6 +1085,14 @@ impl FileReader {

pub(crate) type Source = readable_stream::NewSource<FileReader>;

/// `readableStreamReaderGenericInitialize` / `readableStreamReaderGenericRelease` (C++): a reader locked or released the stream over this source.
#[unsafe(no_mangle)]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub(crate) extern "C" fn FileReader__setReaderLocked(source: *mut Source, locked: bool) {
// SAFETY: `source` is the live `Source` that the stream's native handle wraps.
unsafe { (*source).context.set_reader_locked(locked) };
}

/// Holds a ref on the `Source` that embeds a `FileReader` while a dispatch runs
/// user JS. Dropping it releases the ref and can free the source, so a pin must
/// outlive every use of the reader it protects.
Expand Down
162 changes: 161 additions & 1 deletion test/js/bun/console/console-iterator.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { spawn, spawnSync } from "bun";
import { describe, expect, it } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { bunEnv, bunExe, isWindows } from "harness";

describe("should work for static input", () => {
const inputs = [
Expand Down Expand Up @@ -74,3 +74,163 @@ it("can use the console iterator more than once", async () => {
expect(await stdout.text()).toBe('["hello","world"]["another"]');
proc.kill(0);
});

// Bun.stdin.stream() is one stream per process. Releasing its reader (which the
// console iterator does when the loop breaks) unrefs the native stdin reader so
// an abandoned stream does not keep the process alive. The next reader on that
// stream must ref it again, or the process exits with code 0 while a read is
// still pending. No top-level await in the child: it would keep the loop alive
// and hide the bug.
describe.concurrent("a later stdin consumer keeps the process alive after the reader is released", () => {
const afterConsoleBreak = `
(async () => {
for await (const line of console) {
console.log("ITER " + line);
break;
}
console.log("READY");
for await (const chunk of Bun.stdin.stream()) {
console.log("STREAM " + new TextDecoder().decode(chunk).trim());
break;
}
console.log("DONE");
})();
`;

const afterReleaseLock = `
(async () => {
const decoder = new TextDecoder();
const first = Bun.stdin.stream().getReader();
console.log("FIRST " + decoder.decode((await first.read()).value).trim());
first.releaseLock();
console.log("READY");
const second = Bun.stdin.stream().getReader();
console.log("SECOND " + decoder.decode((await second.read()).value).trim());
second.releaseLock();
console.log("DONE");
})();
`;

async function runWithPipe(script: string) {
await using proc = spawn({
cmd: [bunExe(), "-e", script],
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
env: bunEnv,
});
const reader = proc.stdout.getReader();
const decoder = new TextDecoder();
let output = "";
async function waitFor(marker: string) {
while (!output.includes(marker)) {
const { value, done } = await reader.read();
if (done) throw new Error(`stdout ended before ${JSON.stringify(marker)}; output=${JSON.stringify(output)}`);
output += decoder.decode(value, { stream: true });
}
}

proc.stdin.write("first\n");
proc.stdin.flush();
await waitFor("READY\n");
proc.stdin.write("second\n");
proc.stdin.flush();
await waitFor("DONE\n");
for (let { value, done } = await reader.read(); !done; { value, done } = await reader.read()) {
output += decoder.decode(value, { stream: true });
}
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(exitCode).toBe(0);
return output;
}

async function runWithTerminal(script: string) {
const decoder = new TextDecoder();
let output = "";
let waiting: { marker: string; resolve: () => void } | undefined;
await using proc = spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
terminal: {
data(_terminal, chunk) {
output += decoder.decode(chunk, { stream: true });
if (waiting && output.includes(waiting.marker)) waiting.resolve();
},
},
});
await using terminal = proc.terminal!;
function waitFor(marker: string) {
return new Promise<void>((resolve, reject) => {
waiting = { marker, resolve };
proc.exited.then(code =>
reject(
new Error(`child exited with ${code} before ${JSON.stringify(marker)}; output=${JSON.stringify(output)}`),
),
);
if (output.includes(marker)) resolve();
});
}
terminal.write("first\n");
await waitFor("READY");
terminal.write("second\n");
await waitFor("DONE");
expect(await proc.exited).toBe(0);
return output;
}

it("Bun.stdin.stream() after the console iterator breaks (pipe)", async () => {
expect(await runWithPipe(afterConsoleBreak)).toBe("ITER first\nREADY\nSTREAM second\nDONE\n");
});

it("a second reader after releaseLock() (pipe)", async () => {
expect(await runWithPipe(afterReleaseLock)).toBe("FIRST first\nREADY\nSECOND second\nDONE\n");
});

it.skipIf(isWindows)("Bun.stdin.stream() after the console iterator breaks (tty)", async () => {
const output = await runWithTerminal(afterConsoleBreak);
expect(output).toContain("ITER first");
expect(output).toContain("STREAM second");
});

it.skipIf(isWindows)("a second reader after releaseLock() (tty)", async () => {
const output = await runWithTerminal(afterReleaseLock);
expect(output).toContain("FIRST first");
expect(output).toContain("SECOND second");
});

// Only a ref that the release itself dropped comes back. A source the user
// unref'd on purpose stays unref'd across a releaseLock()/getReader() cycle.
it("a second reader does not undo an explicit unref()", async () => {
Comment thread
robobun marked this conversation as resolved.
Resolved
await using proc = spawn({
cmd: [
bunExe(),
"-e",
`
const child = Bun.spawn({
cmd: [${JSON.stringify(bunExe())}, "-e", "console.log('hi'); setTimeout(() => {}, 60_000)"],
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
});
process.on("exit", () => child.kill());
child.unref();
const first = child.stdout.getReader();
await first.read();
first.releaseLock();
const second = child.stdout.getReader();
second.read().then(() => console.log("unexpected second read"));
console.log("DONE");
`,
],
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
env: bunEnv,
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(stdout).toBe("DONE\n");
expect(exitCode).toBe(0);
});
});
Loading