Report premature close from a destroyed stream's iterator (#4759)

* Report premature close from a destroyed stream's iterator

* Report a destroyed stream's hook error from a parked iterator
This commit is contained in:
Chris Tate
2026-12-03 10:41:13 +00:00
committed by GitHub
parent e69f023b19
commit d33962ddd9
7 changed files with 181 additions and 0 deletions
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/stream-destroy-hook-iterator-error.ts"
],
"diags": []
}
@@ -0,0 +1 @@
{"order":["<repo>/tests/corpus/stream-destroy-iterator-premature-close.ts"],"diags":[]}
+43
View File
@@ -1791,6 +1791,16 @@ static void scr_stream_next_wake_job(ScrClosure *job) {
static void scr_stream_settle_next_waiter(ScrStream *s) {
ScrStreamState *st = s->st;
if (!st->r.next_waiter || st->r.next_reading) return;
if (st->destroyed && st->destroy_cb != NULL && !st->close_scheduled &&
!st->error_scheduled) {
/* A destroy hook that has not called its callback back yet may still
* report an error of its own: Node's iterator waits for the eos
* 'error'/'close' the callback precedes, so a destroy() with no
* argument is not a premature close until the hook has answered.
* Once the callback has scheduled its close/error tick the answer is
* in and the waiter settles below. */
return;
}
if (st->errored && !st->error_emitted) {
/* Node's iterator learns of the error from its eos 'error' listener,
* after the listeners registered before it: the waiter rejects once
@@ -1846,6 +1856,19 @@ static void scr_stream_settle_next_waiter(ScrStream *s) {
scr_st_tick(s, SCR_ST_NEXT_EOF, NULL, NULL);
return;
}
if (!st->r.ended) {
/* Node's iterator reports a readable destroyed before its end as the
* eos premature close; destroy(err) reached the errored branch above. */
ScrPromise *w = st->r.next_waiter;
st->r.next_waiter = NULL;
ScrError *err = scr_stream_mkerr("ERR_STREAM_PREMATURE_CLOSE", "Premature close");
scr_throw_obj(scr_error_retain(err), &scr_error_retain_v, &scr_error_release_v,
scr_error_trace_arg());
scr_error_release(err);
scr_promise_reject_pending(w);
scr_promise_release(w);
return;
}
ScrPromise *w = st->r.next_waiter;
st->r.next_waiter = NULL;
scr_stream_next_fulfill(st, w, NULL, SCR_ENTRY_BYTES);
@@ -8596,6 +8619,26 @@ void scr_stream_destroy_done(ScrStream *s, ScrError *err /*moves*/) {
st->close_scheduled = true;
scr_st_tick(s, SCR_ST_CLOSE, NULL, NULL);
}
/* The hook's answer decides a parked iterator now: its error through the
* queued 'error' tick, a swallowed destroy(err) at once, or the premature
* close a clean callback leaves. A stream torn down without a destroy hook
* keeps its old close-tick path (do_destroy/run_destroy) untouched. */
if (!scr_exc_pending()) {
if (!err && st->errored && !st->error_emitted && !st->error_scheduled) {
ScrPromise *w = st->r.next_waiter;
if (w != NULL && !st->r.next_reading) {
st->r.next_waiter = NULL;
st->next_err_consumed = true;
st->r.next_open = false;
scr_throw_obj(scr_error_retain(st->errored), &scr_error_retain_v,
&scr_error_release_v, scr_error_trace_arg());
scr_promise_reject_pending(w);
scr_promise_release(w);
}
} else {
scr_stream_settle_next(s);
}
}
}
/* Transform._write's callback after the transform pushed its output:
@@ -0,0 +1,79 @@
// A readable with a destroy hook, destroyed while a for-await iterator is
// parked. Node's iterator reports the hook's error (destroy() with no
// argument included): the eos 'error' listener runs before the premature
// close a silent destroy would give it. A hook that calls back with no error
// keeps the premature close, an asynchronous hook keeps the iterator pending
// until it answers, and destroy(err) whose hook swallows the error still
// rejects with the stored error at 'close'.
import { Readable } from "node:stream";
function report(label: string, error: unknown): void {
const err = error as Error & { code?: string };
console.log(label, JSON.stringify(err.message), err.code === undefined ? "none" : err.code);
}
async function main(): Promise<void> {
const sync = new Readable({
read() {},
destroy(_error: Error | null, callback: (error?: Error | null) => void) {
callback(new Error("sync hook"));
},
});
const syncNext = sync[Symbol.asyncIterator]().next();
sync.destroy();
try {
await syncNext;
console.log("sync served");
} catch (error) {
report("sync", error);
}
const syncErrored = sync.errored;
console.log("sync stored", syncErrored === null ? "none" : syncErrored.message);
const clean = new Readable({
read() {},
destroy(_error: Error | null, callback: (error?: Error | null) => void) {
callback();
},
});
const cleanNext = clean[Symbol.asyncIterator]().next();
clean.destroy();
try {
await cleanNext;
console.log("clean served");
} catch (error) {
report("clean", error);
}
const swallow = new Readable({
read() {},
destroy(_error: Error | null, callback: (error?: Error | null) => void) {
callback();
},
});
const swallowNext = swallow[Symbol.asyncIterator]().next();
swallow.destroy(new Error("swallowed"));
try {
await swallowNext;
console.log("swallow served");
} catch (error) {
report("swallow", error);
}
const late = new Readable({
read() {},
destroy(_error: Error | null, callback: (error?: Error | null) => void) {
setTimeout(() => callback(new Error("late hook")), 10);
},
});
const lateNext = late[Symbol.asyncIterator]().next();
late.destroy();
try {
await lateNext;
console.log("late served");
} catch (error) {
report("late", error);
}
}
await main();
@@ -0,0 +1,50 @@
// A readable destroyed without an end or an error while a for-await iterator
// is open (or before it starts): Node's iterator rejects with the eos
// premature close, and a stream that ended before the destroy still completes
// normally. destroy(error) delivers its own error. Chunks print as a count,
// so a read boundary never shows.
import { Readable } from "node:stream";
const before = new Readable({ read() {} });
before.destroy();
try {
for await (const chunk of before) console.log(`before chunk ${chunk.length > 0}`);
console.log("before end");
} catch (error) {
const err = error as Error & { code?: string };
console.log(`before error ${JSON.stringify(err.message)} ${err.code}`);
}
const during = new Readable({ read() {} });
during.push("one");
during.push("two");
let received = 0;
try {
for await (const chunk of during) {
received += chunk.length > 0 ? 1 : 0;
during.destroy();
}
console.log("during end");
} catch (error) {
const err = error as Error & { code?: string };
console.log(`during error ${JSON.stringify(err.message)} ${err.code} chunks ${received}`);
}
console.log(`during destroyed ${during.destroyed} readableEnded ${during.readableEnded}`);
const withError = new Readable({ read() {} });
withError.destroy(new Error("boom"));
try {
for await (const chunk of withError) console.log(`withError chunk ${chunk.length > 0}`);
console.log("withError end");
} catch (error) {
console.log(`withError error ${JSON.stringify((error as Error).message)}`);
}
const normal = Readable.from(["z"]);
try {
for await (const chunk of normal) console.log(`normal chunk ${chunk.length > 0}`);
console.log(`normal end ${normal.destroyed}`);
} catch (error) {
const err = error as Error & { code?: string };
console.log(`normal error ${JSON.stringify(err.message)} ${err.code}`);
}
@@ -0,0 +1 @@
{ "plain": 2200, "san": 2600 }
@@ -0,0 +1 @@
{ "plain": 2000 }