diff --git a/src/io/PipeReader.rs b/src/io/PipeReader.rs index 762e064ccd1b..923f24118740 100644 --- a/src/io/PipeReader.rs +++ b/src/io/PipeReader.rs @@ -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] @@ -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(), + ) } } @@ -1101,7 +1109,10 @@ 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_(); @@ -1109,6 +1120,7 @@ impl WindowsBufferedReader { source.unref(); } } + previous } pub fn disable_keeping_process_alive(&mut self, _: C) { diff --git a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp index 05dbedda9385..b5675c02a72a 100644 --- a/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp +++ b/src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp @@ -25,6 +25,7 @@ #include "JSWritableStreamDefaultWriter.h" #include "ObjectBindings.h" #include "VectorSizeLimit.h" +#include "ZigGeneratedClasses.h" #include "ZigGlobalObject.h" #include @@ -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(controller->m_algorithms.algorithmContext.get()); + if (auto* source = dynamicDowncast(adapter->handle())) + FileReader__setReaderLocked(source->wrapped(), locked); +} + // ReadableStreamReaderGenericInitialize(reader, stream) void readableStreamReaderGenericInitialize(JSGlobalObject* globalObject, JSReadableStreamReaderBase* reader, JSReadableStream* stream) { @@ -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()); @@ -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(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; diff --git a/src/jsc/bindings/webcore/streams/WebStreamsInternals.h b/src/jsc/bindings/webcore/streams/WebStreamsInternals.h index a90f7fa8a62a..b244f5fbd761 100644 --- a/src/jsc/bindings/webcore/streams/WebStreamsInternals.h +++ b/src/jsc/bindings/webcore/streams/WebStreamsInternals.h @@ -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 diff --git a/src/runtime/webcore/FileReader.rs b/src/runtime/webcore/FileReader.rs index c22703418fec..b7b726ee1511 100644 --- a/src/runtime/webcore/FileReader.rs +++ b/src/runtime/webcore/FileReader.rs @@ -66,6 +66,8 @@ pub struct FileReader { /// path; `pull_into_sink` is the drain-ack resume. pub(crate) sink: JsCell, pub(crate) sink_paused: Cell, + /// 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, } impl Default for FileReader { @@ -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), } } } @@ -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. Its C++ callers are `userJS: no`: never dispatch a read here. + 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())); @@ -1068,6 +1085,14 @@ impl FileReader { pub(crate) type Source = readable_stream::NewSource; +/// `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. diff --git a/test/js/bun/console/console-iterator.test.ts b/test/js/bun/console/console-iterator.test.ts index f8fa86976645..22fae99e4fbc 100644 --- a/test/js/bun/console/console-iterator.test.ts +++ b/test/js/bun/console/console-iterator.test.ts @@ -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 = [ @@ -74,3 +74,198 @@ 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((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 () => { + 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); + }); + + // The release dropped a held ref, but the unref() after it is the last word: + // the next reader must not bring the ref back. The parent never closes stdin, + // so a child that kept the ref would wait for input and time the test out. + it("an explicit unref() after the release stays in effect for the next reader", async () => { + await using proc = spawn({ + cmd: [ + bunExe(), + "-e", + ` + (async () => { + for await (const line of console) { + console.log("ITER " + line); + break; + } + process.stdin.unref(); + const reader = Bun.stdin.stream().getReader(); + console.log("READING"); + await reader.read(); + console.log("unexpected read"); + })(); + `, + ], + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + env: bunEnv, + }); + proc.stdin.write("first\n"); + proc.stdin.flush(); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toBe("ITER first\nREADING\n"); + expect(exitCode).toBe(0); + }); +});