Skip to content

Commit

Permalink
stream: add AbortSignal to promisified pipeline
Browse files Browse the repository at this point in the history
add support for AbortSignal to promisified pipeline.

Resolves: #37321
  • Loading branch information
Nitzan Uziely committed Feb 13, 2021
1 parent 88d9268 commit 0100a60
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 1 deletion.
22 changes: 21 additions & 1 deletion lib/stream/promises.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,42 @@
'use strict';

const {
ArrayPrototypePop,
Promise,
} = primordials;

const {
addAbortSignalNoValidate,
} = require('internal/streams/add-abort-signal');

const {
validateAbortSignal,
} = require('internal/validators');

let pl;
let eos;

function pipeline(...streams) {
if (!pl) pl = require('internal/streams/pipeline');
let signal;
const lastArg = streams[streams.length - 1];
if (typeof lastArg === 'object' && 'aborted' in lastArg) {
signal = ArrayPrototypePop(streams);
}
return new Promise((resolve, reject) => {
pl(...streams, (err, value) => {
if (signal) {
validateAbortSignal(signal);
}
const pipe = pl(...streams, (err, value) => {
if (err) {
reject(err);
} else {
resolve(value);
}
});
if (signal) {
addAbortSignalNoValidate(signal, pipe);
}
});
}

Expand Down
72 changes: 72 additions & 0 deletions test/parallel/test-stream-pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,78 @@ const net = require('net');
run();
}

{
// Check aborted signal without values
const pipelinePromise = promisify(pipeline);
async function run() {
const ac = new AbortController();
const { signal } = ac;
async function* producer() {
ac.abort();
await Promise.resolve();
yield '8';
}

const w = new Writable({
write(chunk, encoding, callback) {
callback();
}
});
await pipelinePromise(producer, w, signal);
}

assert.rejects(run, { name: 'AbortError' }).then(common.mustCall());
}

{
// Check aborted signal after init.
const pipelinePromise = promisify(pipeline);
async function run() {
const ac = new AbortController();
const { signal } = ac;
async function* producer() {
yield '5';
await Promise.resolve();
ac.abort();
await Promise.resolve();
yield '8';
}

const w = new Writable({
write(chunk, encoding, callback) {
callback();
}
});
await pipelinePromise(producer, w, signal);
}

assert.rejects(run, { name: 'AbortError' }).then(common.mustCall());
}

{
// Check pre-aborted signal
const pipelinePromise = promisify(pipeline);
async function run() {
const ac = new AbortController();
const { signal } = ac;
ac.abort();
async function* producer() {
yield '5';
await Promise.resolve();
yield '8';
}

const w = new Writable({
write(chunk, encoding, callback) {
callback();
}
});
await pipelinePromise(producer, w, signal);
}

assert.rejects(run, { name: 'AbortError' }).then(common.mustCall());
}

{
const read = new Readable({
read() {}
Expand Down

0 comments on commit 0100a60

Please sign in to comment.