From 649cb43a1bcbe875952baa67caa98bec3c0dbf1e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:49:31 +0000 Subject: [PATCH 1/3] streams: add the ERR_INVALID_STATE code to the locked-stream errors of cancel, pipeTo and pipeThrough ReadableStream.prototype.cancel, pipeTo and pipeThrough reject or throw a plain TypeError when the stream, or the destination WritableStream, is locked. Bun 1.3.14 and Node.js give this error the ERR_INVALID_STATE code. tee() and getReader() already do. Use the same error here, with the message that Node.js uses. --- .../webcore/streams/JSReadableStream.cpp | 10 +++--- test/js/web/streams/streams.test.js | 31 +++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.cpp b/src/jsc/bindings/webcore/streams/JSReadableStream.cpp index c3bf08fa6150..7c954ba95d3a 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.cpp +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.cpp @@ -594,7 +594,7 @@ JSC_DEFINE_HOST_FUNCTION(jsReadableStreamPrototypeFunction_cancel, (JSGlobalObje if (!stream) [[unlikely]] RELEASE_AND_RETURN(scope, JSValue::encode(promiseRejectedWith(lexicalGlobalObject, createTypeError(lexicalGlobalObject, "ReadableStream.prototype.cancel can only be called on a ReadableStream"_s)))); if (isReadableStreamLocked(stream)) - RELEASE_AND_RETURN(scope, JSValue::encode(promiseRejectedWith(lexicalGlobalObject, createTypeError(lexicalGlobalObject, "Cannot cancel a locked ReadableStream"_s)))); + RELEASE_AND_RETURN(scope, JSValue::encode(promiseRejectedWith(lexicalGlobalObject, Bun::createError(lexicalGlobalObject, Bun::ErrorCode::ERR_INVALID_STATE_TypeError, "Invalid state: ReadableStream is locked"_s)))); auto* promise = readableStreamCancel(lexicalGlobalObject, stream, callFrame->argument(0)); RETURN_IF_EXCEPTION(scope, {}); return JSValue::encode(promise); @@ -667,9 +667,9 @@ JSC_DEFINE_HOST_FUNCTION(jsReadableStreamPrototypeFunction_pipeThrough, (JSGloba RETURN_IF_EXCEPTION(scope, {}); if (isReadableStreamLocked(stream)) - return throwVMTypeError(lexicalGlobalObject, scope, "Cannot pipe a locked ReadableStream"_s); + return Bun::throwError(lexicalGlobalObject, scope, Bun::ErrorCode::ERR_INVALID_STATE_TypeError, "Invalid state: The ReadableStream is locked"_s); if (isWritableStreamLocked(transformWritable)) - return throwVMTypeError(lexicalGlobalObject, scope, "Cannot pipe to a locked WritableStream"_s); + return Bun::throwError(lexicalGlobalObject, scope, Bun::ErrorCode::ERR_INVALID_STATE_TypeError, "Invalid state: The WritableStream is locked"_s); auto* promise = readableStreamPipeTo(lexicalGlobalObject, stream, transformWritable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); RETURN_IF_EXCEPTION(scope, {}); @@ -694,9 +694,9 @@ JSC_DEFINE_HOST_FUNCTION(jsReadableStreamPrototypeFunction_pipeTo, (JSGlobalObje ConvertedStreamPipeOptions options = convertStreamPipeOptions(vm, lexicalGlobalObject, callFrame->argument(1)); RETURN_IF_EXCEPTION(scope, nullptr); if (isReadableStreamLocked(stream)) - RELEASE_AND_RETURN(scope, promiseRejectedWith(lexicalGlobalObject, createTypeError(lexicalGlobalObject, "Cannot pipe a locked ReadableStream"_s))); + RELEASE_AND_RETURN(scope, promiseRejectedWith(lexicalGlobalObject, Bun::createError(lexicalGlobalObject, Bun::ErrorCode::ERR_INVALID_STATE_TypeError, "Invalid state: The ReadableStream is locked"_s))); if (isWritableStreamLocked(destination)) - RELEASE_AND_RETURN(scope, promiseRejectedWith(lexicalGlobalObject, createTypeError(lexicalGlobalObject, "Cannot pipe to a locked WritableStream"_s))); + RELEASE_AND_RETURN(scope, promiseRejectedWith(lexicalGlobalObject, Bun::createError(lexicalGlobalObject, Bun::ErrorCode::ERR_INVALID_STATE_TypeError, "Invalid state: The WritableStream is locked"_s))); RELEASE_AND_RETURN(scope, readableStreamPipeTo(lexicalGlobalObject, stream, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal)); }))); } diff --git a/test/js/web/streams/streams.test.js b/test/js/web/streams/streams.test.js index b49f29f3b3d5..8a631d48b156 100644 --- a/test/js/web/streams/streams.test.js +++ b/test/js/web/streams/streams.test.js @@ -2200,6 +2200,37 @@ it("ReadableStream rejects pending reads when the lock is released", async () => expect((await reader.read()).value).toBe("456"); }); +// A locked stream fails these with a TypeError (WHATWG) that carries Node's +// ERR_INVALID_STATE code and message (node compatibility). +const invalidState = message => expect.objectContaining({ name: "TypeError", code: "ERR_INVALID_STATE", message }); + +it("a locked ReadableStream fails cancel, pipeTo, pipeThrough, tee and getReader with ERR_INVALID_STATE", async () => { + const stream = new ReadableStream(); + stream.getReader(); + + await expect(stream.cancel()).rejects.toThrow(invalidState("Invalid state: ReadableStream is locked")); + await expect(stream.pipeTo(new WritableStream())).rejects.toThrow( + invalidState("Invalid state: The ReadableStream is locked"), + ); + expect(() => stream.pipeThrough(new TransformStream())).toThrow( + invalidState("Invalid state: The ReadableStream is locked"), + ); + expect(() => stream.tee()).toThrow(invalidState("Invalid state: ReadableStream is locked")); + expect(() => stream.getReader()).toThrow(invalidState("Invalid state: ReadableStream is locked")); +}); + +it("pipeTo and pipeThrough into a locked WritableStream fail with ERR_INVALID_STATE", async () => { + const destination = new WritableStream(); + destination.getWriter(); + + await expect(new ReadableStream().pipeTo(destination)).rejects.toThrow( + invalidState("Invalid state: The WritableStream is locked"), + ); + expect(() => new ReadableStream().pipeThrough({ readable: new ReadableStream(), writable: destination })).toThrow( + invalidState("Invalid state: The WritableStream is locked"), + ); +}); + it("new Response(stream).arrayBuffer() (bytes)", async () => { var queue = [Buffer.from("abdefgh")]; var stream = new ReadableStream({ From e06335dccb001278b5ca2d6503c11a2066c0fa0e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 21:16:37 +0000 Subject: [PATCH 2/3] streams: do not swallow an ERR_INVALID_STATE error from an async-iterable body asyncIterFinishWithError resolved the pull of an async-iterable body when the error had the ERR_INVALID_STATE code, and it did not close the stream. The consumer then got a truncated body, or a read() that never settles. The check replaced the test for a closed direct controller that the JS implementation had. A closed direct controller does not throw now, and no sink throws this code, so the check matched only errors from the iterator. A cancelled stream still resolves the pull through m_cancelled. --- .../streams/BunAsyncIterableSource.cpp | 13 +---- .../webcore/streams/JSStreamsRuntime.h | 7 ++- .../js/bun/http/async-iterator-stream.test.ts | 48 +++++++++++++++++++ 3 files changed, 53 insertions(+), 15 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/BunAsyncIterableSource.cpp b/src/jsc/bindings/webcore/streams/BunAsyncIterableSource.cpp index e5ec87edb25f..b71a8207f8c1 100644 --- a/src/jsc/bindings/webcore/streams/BunAsyncIterableSource.cpp +++ b/src/jsc/bindings/webcore/streams/BunAsyncIterableSource.cpp @@ -179,7 +179,6 @@ static void asyncIterFinishWithError(JSGlobalObject* globalObject, JSAsyncIterat if (errorCodeIs(vm, error, "ERR_INVALID_THIS"_s)) RELEASE_AND_RETURN(scope, asyncIterReturnIteratorAndSettle(globalObject, op)); - bool swallowByCode = errorCodeIs(vm, error, "ERR_INVALID_STATE"_s); JSObject* iterator = op->iterator(); op->clearIterator(); @@ -195,11 +194,11 @@ static void asyncIterFinishWithError(JSGlobalObject* globalObject, JSAsyncIterat if (auto* thrownPromise = asPromise(thrown)) { markPromiseAsHandled(vm, thrownPromise); auto* context = JSC::InternalFieldTuple::create(vm, globalObject->internalFieldTupleStructure(), op, error); - auto* handler = swallowByCode ? runtime->onAsyncIterableSourceErrorSwallowed() : runtime->onAsyncIterableSourceErrorRethrow(); + auto* handler = runtime->onAsyncIterableSourceErrorRethrow(); thrownPromise->performPromiseThenWithContext(vm, globalObject, handler, handler, jsUndefined(), context); return; } - if (swallowByCode || op->m_cancelled) { + if (op->m_cancelled) { settlePullPromiseResolved(globalObject, op); return; } @@ -401,14 +400,6 @@ JSC_DEFINE_HOST_FUNCTION(jsWebStreamsHandler_onAsyncIterableSourceErrorRethrow, return JSValue::encode(jsUndefined()); } -JSC_DEFINE_HOST_FUNCTION(jsWebStreamsHandler_onAsyncIterableSourceErrorSwallowed, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - auto* tuple = uncheckedDowncast(callFrame->uncheckedArgument(1)); - auto* op = uncheckedDowncast(tuple->getInternalField(0)); - settlePullPromiseResolved(globalObject, op); - return JSValue::encode(jsUndefined()); -} - // context = the reason cancel() threw into the iterator. The iterator letting that reason // propagate is the expected outcome of a cancel and resolves it; anything else thrown while // unwinding (a throwing `finally`) still rejects it. diff --git a/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h b/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h index 2e7198796dd2..a9d01dd9a66f 100644 --- a/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h +++ b/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h @@ -86,9 +86,9 @@ namespace WebCore { V(onByteTeeReaderClosedRejected) // owner: BunAsyncIterableSource.cpp. context = the JSAsyncIteratorSourceOperation, EXCEPT -// onAsyncIterableSourceErrorRethrow / onAsyncIterableSourceErrorSwallowed, whose context is -// an InternalFieldTuple{op, originalError} (registered on iter.throw()'s settlement), and -// onAsyncIterableSourceCancelRejected, whose context is the reason cancel() threw into the iterator. +// onAsyncIterableSourceErrorRethrow, whose context is an InternalFieldTuple{op, originalError} +// (registered on iter.throw()'s settlement), and onAsyncIterableSourceCancelRejected, whose +// context is the reason cancel() threw into the iterator. #define FOR_EACH_WEB_STREAMS_REACTION_HANDLER_ASYNC_ITERABLE_SOURCE(V) \ V(onAsyncIterableSourceNextFulfilled) \ V(onAsyncIterableSourceFlushFulfilled) \ @@ -96,7 +96,6 @@ namespace WebCore { V(onAsyncIterableSourceEndFulfilled) \ V(onAsyncIterableSourceCleanupSettled) \ V(onAsyncIterableSourceErrorRethrow) \ - V(onAsyncIterableSourceErrorSwallowed) \ V(onAsyncIterableSourceCancelRejected) // owner: JSReadableStreamAsyncIterator.cpp. context = the JSReadableStreamAsyncIterator, diff --git a/test/js/bun/http/async-iterator-stream.test.ts b/test/js/bun/http/async-iterator-stream.test.ts index 537f30cc3000..3d24f310de07 100644 --- a/test/js/bun/http/async-iterator-stream.test.ts +++ b/test/js/bun/http/async-iterator-stream.test.ts @@ -81,6 +81,54 @@ describe.concurrent("Streaming body via", () => { expect(exitCode).toBe(0); }); + // An error from the generator with the ERR_INVALID_STATE code reaches the consumer like any other + // error. The subprocess awaits nothing at the top level, so a read() that never settles shows up + // as a missing outcome. + test("an ERR_INVALID_STATE error from the generator rejects the body", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + `async function* coded() { + yield "first;"; + throw Object.assign(new TypeError("coded"), { code: "ERR_INVALID_STATE" }); + } + async function* lockedCancel() { + yield "first;"; + const locked = new ReadableStream(); + locked.getReader(); + await locked.cancel(); + } + async function drain(reader) { + while (!(await reader.read()).done); + return "drained"; + } + const outcomes = {}; + const record = (name, promise) => + promise.then(v => (outcomes[name] = "resolved " + v), e => (outcomes[name] = "rejected " + e.code)); + for (const gen of [coded, lockedCancel]) { + record(gen.name + " text()", new Response(gen()).text()); + record(gen.name + " read()", drain(new Response(gen()).body.getReader())); + } + process.once("beforeExit", () => { + for (const name of Object.keys(outcomes).sort()) console.log(name + ": " + outcomes[name]); + });`, + ], + env: bunEnv, + stderr: "pipe", + }); + + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout.trim().split(/\r?\n/)).toEqual([ + "coded read(): rejected ERR_INVALID_STATE", + "coded text(): rejected ERR_INVALID_STATE", + "lockedCancel read(): rejected ERR_INVALID_STATE", + "lockedCancel text(): rejected ERR_INVALID_STATE", + ]); + expect(stderr).not.toContain("ERR_INVALID_STATE"); + expect(exitCode).toBe(0); + }); + test("an iterator returning thenables (non-native promises) streams", async () => { let n = 0; const iterator = { From 93fa7cdc46be752b0c32fca5104d9caca4af379c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 21 Sep 2026 21:47:31 +0000 Subject: [PATCH 3/3] streams: keep the handler context comment to a one-line change --- src/jsc/bindings/webcore/streams/JSStreamsRuntime.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h b/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h index a9d01dd9a66f..02c66e874f45 100644 --- a/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h +++ b/src/jsc/bindings/webcore/streams/JSStreamsRuntime.h @@ -86,9 +86,9 @@ namespace WebCore { V(onByteTeeReaderClosedRejected) // owner: BunAsyncIterableSource.cpp. context = the JSAsyncIteratorSourceOperation, EXCEPT -// onAsyncIterableSourceErrorRethrow, whose context is an InternalFieldTuple{op, originalError} -// (registered on iter.throw()'s settlement), and onAsyncIterableSourceCancelRejected, whose -// context is the reason cancel() threw into the iterator. +// onAsyncIterableSourceErrorRethrow, whose context is +// an InternalFieldTuple{op, originalError} (registered on iter.throw()'s settlement), and +// onAsyncIterableSourceCancelRejected, whose context is the reason cancel() threw into the iterator. #define FOR_EACH_WEB_STREAMS_REACTION_HANDLER_ASYNC_ITERABLE_SOURCE(V) \ V(onAsyncIterableSourceNextFulfilled) \ V(onAsyncIterableSourceFlushFulfilled) \