Skip to content

Commit

Permalink
stream: finish pipeline if dst closes before src
Browse files Browse the repository at this point in the history
If the destination stream is closed before the source has completed
the pipeline should finnish with premature close.

Fixes: #43682

PR-URL: #43701
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
  • Loading branch information
ronag committed Jul 11, 2022
1 parent b4a7d9f commit e4bf5dc
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/internal/streams/pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 20,7 @@ const {
ERR_INVALID_RETURN_VALUE,
ERR_MISSING_ARGS,
ERR_STREAM_DESTROYED,
ERR_STREAM_PREMATURE_CLOSE,
},
AbortError,
} = require('internal/errors');
Expand Down Expand Up @@ -344,13 345,24 @@ function pipelineImpl(streams, callback, opts) {
}

function pipe(src, dst, finish, { end }) {
let ended = false;
dst.on('close', () => {
if (!ended) {
// Finish if the destination closes before the source has completed.
finish(new ERR_STREAM_PREMATURE_CLOSE());
}
});

src.pipe(dst, { end });

if (end) {
// Compat. Before node v10.12.0 stdio used to throw an error so
// pipe() did/does not end() stdio destinations.
// Now they allow it but "secretly" don't close the underlying fd.
src.once('end', () => dst.end());
src.once('end', () => {
ended = true;
dst.end();
});
} else {
finish();
}
Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-stream-pipeline-duplex.js
Original file line number Diff line number Diff line change
@@ -0,0 1,21 @@
'use strict';

const common = require('../common');
const { pipeline, Duplex, PassThrough } = require('stream');
const assert = require('assert');

const remote = new PassThrough();
const local = new Duplex({
read() {},
write(chunk, enc, callback) {
callback();
}
});

pipeline(remote, local, remote, common.mustCall((err) => {
assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE');
}));

setImmediate(() => {
remote.end();
});

0 comments on commit e4bf5dc

Please sign in to comment.