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.
  • Loading branch information
ronag committed Jan 29, 2020
1 parent 24e81d7 commit 1e9ab30
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
18 changes: 14 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,15 @@ function isWritable(stream) {
!!stream._writableState;
}

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

function eos(stream, opts, callback) {
if (arguments.length === 2) {
callback = opts;
Expand All @@ -49,10 +58,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 +85,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 1e9ab30

Please sign in to comment.