Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 1 addition & 6 deletions src/jsc/bindings/webcore/streams/BunAsyncIterableSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,18 +168,13 @@ static void asyncIterReturnIteratorAndSettle(JSGlobalObject* globalObject, JSAsy
settlePullPromiseResolved(globalObject, op);
}

// Error tail (the original `finally` with a closingError): an already-gone consumer
// (ERR_INVALID_THIS) returns the iterator quietly; otherwise notify it via iterator.throw(error)
// and settle once that settles.
// The error tail: iterator.throw(error), then reject the pull promise (resolve it if cancelled).
static void asyncIterFinishWithError(JSGlobalObject* globalObject, JSAsyncIteratorSourceOperation* op, JSValue error)
{
auto& vm = getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
auto* runtime = JSStreamsRuntime::from(globalObject);

if (errorCodeIs(vm, error, "ERR_INVALID_THIS"_s))
RELEASE_AND_RETURN(scope, asyncIterReturnIteratorAndSettle(globalObject, op));

JSObject* iterator = op->iterator();
op->clearIterator();
JSValue thrown;
Expand Down
3 changes: 0 additions & 3 deletions src/jsc/bindings/webcore/streams/WebStreamsInternals.h
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,6 @@ void rejectStreamClosedPromise(JSC::VM&, JSWritableStream*, JSC::JSValue error);
void webStreamControllerError(JSC::JSGlobalObject*, JSReadableStream*, JSC::JSValue error); // userJS: yes — ReadableStreamOperations.cpp
void webStreamControllerError(JSC::JSGlobalObject*, JSWritableStream*, JSC::JSValue error); // userJS: yes — WritableStreamOperations.cpp

// error.code === code, for an own or inherited data property `code` (no getters or proxies run). userJS: no — WebStreamsMisc.cpp
bool errorCodeIs(JSC::VM&, JSC::JSValue error, WTF::ASCIILiteral code);

// Joins any pending bytes, strips a single leading BOM per stream (ignoreBOM=false), holds
// back a trailing incomplete sequence (unless `flush`), and decodes the remaining span via
// Bun's simdutf-backed UTF-8 path (invalid sequences replaced by U+FFFD). Returns nullptr
Expand Down
14 changes: 0 additions & 14 deletions src/jsc/bindings/webcore/streams/WebStreamsMisc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -430,20 +430,6 @@ JSPromise* invokeCallbackReturningPromiseFast(JSGlobalObject* globalObject, JSOb
});
}

bool errorCodeIs(VM& vm, JSValue error, ASCIILiteral code)
{
// Own or inherited *data* property only (Bun's coded errors keep `code` on a per-code
// prototype); structures' stored prototypes are followed, so no getter or proxy trap runs.
JSValue codeValue;
for (JSObject* object = error ? error.getObject() : nullptr; object && !codeValue; object = object->getPrototypeDirect().getObject())
codeValue = object->getDirect(vm, WebCore::builtinNames(vm).codePublicName());
auto* codeString = codeValue ? dynamicDowncast<JSString>(codeValue) : nullptr;
if (!codeString)
return false;
auto value = codeString->tryGetValue();
return WTF::equal(value.data, StringView(code));
}

// Shared [bound-convention] wrapper: target(contextCell, ...callArgs).
JSC::JSBoundFunction* createStreamsBoundHandler(JSGlobalObject* globalObject, JSFunction* target, JSCell* context)
{
Expand Down
61 changes: 45 additions & 16 deletions test/js/bun/http/async-iterator-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,23 +81,27 @@ 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 () => {
// An error from the generator with one of these codes reaches the consumer like any other error,
// whether the generator throws it or a native call in the generator does. The upload throws once
// its request is at the server, so the server sees an aborted body and not a complete one. text()
// and read() keep nothing alive: one that never settles shows up as a missing outcome.
test.each([
["ERR_INVALID_STATE", "const locked = new ReadableStream(); locked.getReader(); await locked.cancel();"],
["ERR_INVALID_THIS", "ReadableStream.prototype.tee.call({});"],
])("an %s error from the generator rejects the body", async (code, nativeThrow) => {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`async function* coded() {
`async function* coded(gate) {
yield "first;";
throw Object.assign(new TypeError("coded"), { code: "ERR_INVALID_STATE" });
await gate;
throw Object.assign(new TypeError("coded"), { code: "${code}" });
}
async function* lockedCancel() {
async function* native(gate) {
yield "first;";
const locked = new ReadableStream();
locked.getReader();
await locked.cancel();
await gate;
${nativeThrow}
}
async function drain(reader) {
while (!(await reader.read()).done);
Expand All @@ -106,10 +110,31 @@ describe.concurrent("Streaming body via", () => {
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]) {
const atServer = { coded: Promise.withResolvers(), native: Promise.withResolvers() };
const requestBodies = [];
const server = Bun.serve({
port: 0,
async fetch(req) {
const name = new URL(req.url).pathname.slice(1);
atServer[name].resolve();
const body = req.text().then(text => "complete, " + text.length + " bytes", () => "aborted");
requestBodies.push(body.then(v => (outcomes[name + " request body"] = v)));
await body;
return new Response("done");
},
});
const uploads = [];
for (const gen of [coded, native]) {
record(gen.name + " text()", new Response(gen()).text());
record(gen.name + " read()", drain(new Response(gen()).body.getReader()));
const body = gen(atServer[gen.name].promise);
uploads.push(
record(gen.name + " upload", fetch(server.url + gen.name, { method: "POST", body }).then(r => r.text())),
);
}
Promise.all(uploads)
.then(() => Promise.all(requestBodies))
.then(() => server.stop(true));
process.once("beforeExit", () => {
for (const name of Object.keys(outcomes).sort()) console.log(name + ": " + outcomes[name]);
});`,
Expand All @@ -120,12 +145,16 @@ describe.concurrent("Streaming body via", () => {

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",
`coded read(): rejected ${code}`,
"coded request body: aborted",
`coded text(): rejected ${code}`,
`coded upload: rejected ${code}`,
`native read(): rejected ${code}`,
"native request body: aborted",
`native text(): rejected ${code}`,
`native upload: rejected ${code}`,
]);
expect(stderr).not.toContain("ERR_INVALID_STATE");
expect(stderr).not.toContain(code);
expect(exitCode).toBe(0);
});

Expand Down
Loading