Skip to content

Commit

Permalink
stream: fix finished w/ 'close' before 'finish'
Browse files Browse the repository at this point in the history
Emitting 'close' before 'finish' on a Writable should
result in a premature close error.

PR-URL: #31534
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Anna Henningsen <[email protected]>
  • Loading branch information
ronag authored and addaleax committed Feb 5, 2020
1 parent 6a6279e commit 234de6f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/internal/streams/end-of-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ function isWritable(stream) {
!!stream._writableState;
}

function isWritableFinished(stream) {
if (stream.writableFinished) return true;
const wState = stream._writableState;
if (!wState || wState.errored) return false;
return wState.finished || (wState.ended && wState.length === 0);
}

function eos(stream, opts, callback) {
if (arguments.length === 2) {
callback = opts;
Expand All @@ -49,10 +56,11 @@ function eos(stream, opts, callback) {
if (!stream.writable) onfinish();
};

let writableEnded = stream._writableState && stream._writableState.finished;
let writableFinished = stream.writableFinished ||
(stream._writableState && stream._writableState.finished);
const onfinish = () => {
writable = false;
writableEnded = true;
writableFinished = true;
if (!readable) callback.call(stream);
};

Expand All @@ -75,8 +83,8 @@ function eos(stream, opts, callback) {
err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
if (writable && !writableEnded) {
if (!stream._writableState || !stream._writableState.ended)
if (writable && !writableFinished) {
if (!isWritableFinished(stream))
err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
Expand Down
13 changes: 13 additions & 0 deletions test/parallel/test-stream-finished.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,16 @@ const { promisify } = require('util');
assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE');
}));
}

{
const w = new Writable({
write(chunk, encoding, callback) {
setImmediate(callback);
}
});
finished(w, common.mustCall((err) => {
assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE');
}));
w.end('asd');
w.destroy();
}

0 comments on commit 234de6f

Please sign in to comment.