All files / lib/internal/streams pipeline.js

97.21% Statements 384/395
95.96% Branches 119/124
100% Functions 16/16
97.21% Lines 384/395

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 39627x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 195x 195x 195x 163x 195x 195x 195x 191x 195x 195x 195x 195x 191x 76x 191x 195x 195x 195x 195x 27x 102x 102x 102x 102x 102x 102x 102x 27x 39x 39x 36x 39x 3x 3x 3x     39x 27x 3x 3x 1x 1x 2x 2x 3x 27x 42x 42x 42x 42x 42x 35x 8x 8x 35x 35x 31x 31x 31x 31x 42x 42x 42x 34x 3x 34x 31x 31x 4x 31x 27x 27x 31x 31x 42x 42x 42x 42x 42x 42x 42x     42x 42x 63x 6x 1x 63x 28x 28x 28x 28x 28x 28x 26x 26x 42x 16x 42x 42x 42x 42x 42x 27x 102x 102x 102x 27x 110x 110x 18x 18x 110x 110x 2x 2x 108x 108x 108x 110x 110x 110x 110x 110x 110x 110x 110x 110x 5x 5x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 268x 268x 110x 110x 273x 58x 58x 273x 273x 48x 48x 225x 273x 191x 191x 225x 273x 273x 273x 273x 103x 63x 63x 103x 103x 273x 110x 110x 110x 250x 250x 250x 250x 250x 250x 250x 173x 172x 172x 172x 172x 30x 30x 172x 173x 173x 173x 63x 63x 63x 51x 63x 44x 44x 63x 173x 173x 31x 19x 31x 31x 173x 250x 250x 108x 23x 23x 1x 1x 1x 108x 85x 85x     250x 39x 39x 39x 39x 14x 1x 1x 1x 39x 25x 4x 4x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 15x 15x 15x 10x 10x 2x 2x 10x 10x 10x 10x 15x 4x 4x 15x 15x 25x 8x 8x 10x 2x 2x 2x 23x 23x 23x 23x 23x 23x 23x 23x 25x 142x 103x 69x 69x 69x 20x 20x 103x 34x 34x 34x       103x 103x     250x 246x 110x 2x 2x 104x 104x 110x 27x 69x 69x 69x 59x 30x 30x 30x 69x 69x 69x 69x 69x 68x 68x 68x 68x 38x 38x 68x 69x 1x 1x 69x 69x 69x 69x 69x 69x 11x 69x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 69x 68x 68x 69x 69x 69x 27x 27x  
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).
 
'use strict';
 
const {
  ArrayIsArray,
  Promise,
  SymbolAsyncIterator,
} = primordials;
 
const eos = require('internal/streams/end-of-stream');
const { once } = require('internal/util');
const destroyImpl = require('internal/streams/destroy');
const Duplex = require('internal/streams/duplex');
const {
  aggregateTwoErrors,
  codes: {
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_RETURN_VALUE,
    ERR_MISSING_ARGS,
    ERR_STREAM_DESTROYED,
    ERR_STREAM_PREMATURE_CLOSE,
  },
  AbortError,
} = require('internal/errors');
 
const {
  validateFunction,
  validateAbortSignal
} = require('internal/validators');
 
const {
  isIterable,
  isReadable,
  isReadableNodeStream,
  isNodeStream,
} = require('internal/streams/utils');
const { AbortController } = require('internal/abort_controller');
 
let PassThrough;
let Readable;
 
function destroyer(stream, reading, writing) {
  let finished = false;
  stream.on('close', () => {
    finished = true;
  });
 
  const cleanup = eos(stream, { readable: reading, writable: writing }, (err) => {
    finished = !err;
  });
 
  return {
    destroy: (err) => {
      if (finished) return;
      finished = true;
      destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe'));
    },
    cleanup
  };
}
 
function popCallback(streams) {
  // Streams should never be an empty array. It should always contain at least
  // a single stream. Therefore optimize for the average case instead of
  // checking for length === 0 as well.
  validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]');
  return streams.pop();
}
 
function makeAsyncIterable(val) {
  if (isIterable(val)) {
    return val;
  } else if (isReadableNodeStream(val)) {
    // Legacy streams are not Iterable.
    return fromReadable(val);
  }
  throw new ERR_INVALID_ARG_TYPE(
    'val', ['Readable', 'Iterable', 'AsyncIterable'], val);
}
 
async function* fromReadable(val) {
  if (!Readable) {
    Readable = require('internal/streams/readable');
  }
 
  yield* Readable.prototype[SymbolAsyncIterator].call(val);
}
 
async function pump(iterable, writable, finish, { end }) {
  let error;
  let onresolve = null;
 
  const resume = (err) => {
    if (err) {
      error = err;
    }
 
    if (onresolve) {
      const callback = onresolve;
      onresolve = null;
      callback();
    }
  };
 
  const wait = () => new Promise((resolve, reject) => {
    if (error) {
      reject(error);
    } else {
      onresolve = () => {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      };
    }
  });
 
  writable.on('drain', resume);
  const cleanup = eos(writable, { readable: false }, resume);
 
  try {
    if (writable.writableNeedDrain) {
      await wait();
    }
 
    for await (const chunk of iterable) {
      if (!writable.write(chunk)) {
        await wait();
      }
    }
 
    if (end) {
      writable.end();
    }
 
    await wait();
 
    finish();
  } catch (err) {
    finish(error !== err ? aggregateTwoErrors(error, err) : err);
  } finally {
    cleanup();
    writable.off('drain', resume);
  }
}
 
function pipeline(...streams) {
  return pipelineImpl(streams, once(popCallback(streams)));
}
 
function pipelineImpl(streams, callback, opts) {
  if (streams.length === 1 && ArrayIsArray(streams[0])) {
    streams = streams[0];
  }
 
  if (streams.length < 2) {
    throw new ERR_MISSING_ARGS('streams');
  }
 
  const ac = new AbortController();
  const signal = ac.signal;
  const outerSignal = opts?.signal;
 
  // Need to cleanup event listeners if last stream is readable
  // https://github.com/nodejs/node/issues/35452
  const lastStreamCleanup = [];
 
  validateAbortSignal(outerSignal, 'options.signal');
 
  function abort() {
    finishImpl(new AbortError());
  }
 
  outerSignal?.addEventListener('abort', abort);
 
  let error;
  let value;
  const destroys = [];
 
  let finishCount = 0;
 
  function finish(err) {
    finishImpl(err, --finishCount === 0);
  }
 
  function finishImpl(err, final) {
    if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {
      error = err;
    }
 
    if (!error && !final) {
      return;
    }
 
    while (destroys.length) {
      destroys.shift()(error);
    }
 
    outerSignal?.removeEventListener('abort', abort);
    ac.abort();
 
    if (final) {
      if (!error) {
        lastStreamCleanup.forEach((fn) => fn());
      }
      process.nextTick(callback, error, value);
    }
  }
 
  let ret;
  for (let i = 0; i < streams.length; i++) {
    const stream = streams[i];
    const reading = i < streams.length - 1;
    const writing = i > 0;
    const end = reading || opts?.end !== false;
    const isLastStream = i === streams.length - 1;
 
    if (isNodeStream(stream)) {
      if (end) {
        const { destroy, cleanup } = destroyer(stream, reading, writing);
        destroys.push(destroy);
 
        if (isReadable(stream) && isLastStream) {
          lastStreamCleanup.push(cleanup);
        }
      }
 
      // Catch stream errors that occur after pipe/pump has completed.
      function onError(err) {
        if (
          err &&
          err.name !== 'AbortError' &&
          err.code !== 'ERR_STREAM_PREMATURE_CLOSE'
        ) {
          finish(err);
        }
      }
      stream.on('error', onError);
      if (isReadable(stream) && isLastStream) {
        lastStreamCleanup.push(() => {
          stream.removeListener('error', onError);
        });
      }
    }
 
    if (i === 0) {
      if (typeof stream === 'function') {
        ret = stream({ signal });
        if (!isIterable(ret)) {
          throw new ERR_INVALID_RETURN_VALUE(
            'Iterable, AsyncIterable or Stream', 'source', ret);
        }
      } else if (isIterable(stream) || isReadableNodeStream(stream)) {
        ret = stream;
      } else {
        ret = Duplex.from(stream);
      }
    } else if (typeof stream === 'function') {
      ret = makeAsyncIterable(ret);
      ret = stream(ret, { signal });
 
      if (reading) {
        if (!isIterable(ret, true)) {
          throw new ERR_INVALID_RETURN_VALUE(
            'AsyncIterable', `transform[${i - 1}]`, ret);
        }
      } else {
        if (!PassThrough) {
          PassThrough = require('internal/streams/passthrough');
        }
 
        // If the last argument to pipeline is not a stream
        // we must create a proxy stream so that pipeline(...)
        // always returns a stream which can be further
        // composed through `.pipe(stream)`.
 
        const pt = new PassThrough({
          objectMode: true
        });
 
        // Handle Promises/A+ spec, `then` could be a getter that throws on
        // second use.
        const then = ret?.then;
        if (typeof then === 'function') {
          finishCount++;
          then.call(ret,
                    (val) => {
                      value = val;
                      if (val != null) {
                        pt.write(val);
                      }
                      if (end) {
                        pt.end();
                      }
                      process.nextTick(finish);
                    }, (err) => {
                      pt.destroy(err);
                      process.nextTick(finish, err);
                    },
          );
        } else if (isIterable(ret, true)) {
          finishCount++;
          pump(ret, pt, finish, { end });
        } else {
          throw new ERR_INVALID_RETURN_VALUE(
            'AsyncIterable or Promise', 'destination', ret);
        }
 
        ret = pt;
 
        const { destroy, cleanup } = destroyer(ret, false, true);
        destroys.push(destroy);
        if (isLastStream) {
          lastStreamCleanup.push(cleanup);
        }
      }
    } else if (isNodeStream(stream)) {
      if (isReadableNodeStream(ret)) {
        finishCount += 2;
        const cleanup = pipe(ret, stream, finish, { end });
        if (isReadable(stream) && isLastStream) {
          lastStreamCleanup.push(cleanup);
        }
      } else if (isIterable(ret)) {
        finishCount++;
        pump(ret, stream, finish, { end });
      } else {
        throw new ERR_INVALID_ARG_TYPE(
          'val', ['Readable', 'Iterable', 'AsyncIterable'], ret);
      }
      ret = stream;
    } else {
      ret = Duplex.from(stream);
    }
  }
 
  if (signal?.aborted || outerSignal?.aborted) {
    process.nextTick(abort);
  }
 
  return ret;
}
 
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', () => {
      ended = true;
      dst.end();
    });
  } else {
    finish();
  }
 
  eos(src, { readable: true, writable: false }, (err) => {
    const rState = src._readableState;
    if (
      err &&
      err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&
      (rState && rState.ended && !rState.errored && !rState.errorEmitted)
    ) {
      // Some readable streams will emit 'close' before 'end'. However, since
      // this is on the readable side 'end' should still be emitted if the
      // stream has been ended and no error emitted. This should be allowed in
      // favor of backwards compatibility. Since the stream is piped to a
      // destination this should not result in any observable difference.
      // We don't need to check if this is a writable premature close since
      // eos will only fail with premature close on the reading side for
      // duplex streams.
      src
        .once('end', finish)
        .once('error', finish);
    } else {
      finish(err);
    }
  });
  return eos(dst, { readable: false, writable: true }, finish);
}
 
module.exports = { pipelineImpl, pipeline };