setup.js
This file
Path
lib/pipe/setup.js
240 lines · 8.5 KiB · JavaScript
Last changed by
Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
History of this fileTake it
The walk stopped after 200 commits: lines older than 9f65b86 point at it.
100% test coverage (#1018)ehmickybefore adoption9f65b86
line 1why, one step back1import isPlainObject from 'is-plain-obj';Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 2–5why, one step back2import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3import {initializeConcurrentStreams} from '../convert/concurrent.js';4import {createIterable} from '../convert/iterable.js';5import {createReadable} from '../convert/readable.js';Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
line 6why, one step back6import {createReadableStream} from '../convert/web.js';Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 7–8why, one step back7import {internalGetOneMessageOptions} from '../ipc/get-one.js';8import {internalGetEachMessageOptions} from '../ipc/get-each.js';100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 9–23why, one step back9import {normalizePipeArguments} from './pipe-arguments.js';10import {handlePipeArgumentsError} from './throw.js';11import {waitForBothSubprocesses} from './sequence.js';12import {pipeSubprocessStream} from './streaming.js';13import {unpipeOnAbort} from './abort.js';1415// Pipe a subprocess' `stdout`/`stderr`/`stdio` into another subprocess' `stdin`16export const pipeToSubprocess = (sourceInfo, ...pipeArguments) => {17 if (isPlainObject(pipeArguments[0])) {18 return pipeToSubprocess.bind(undefined, {19 ...sourceInfo,20 boundOptions: {...sourceInfo.boundOptions, ...pipeArguments[0]},21 });22 }23Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
lines 24–29why, one step back24 // The previous `.pipe()` failed because of its arguments, so there is no source. Its promise rejects with that error.25 // The destination is not spawned, since nothing would end its `stdin`.26 if (sourceInfo.source === undefined) {27 return sourceInfo.sourcePromise;28 }29100% test coverage (#1018)ehmickybefore adoption9f65b86
line 30why, one step back30 const {destination, ...normalizedInfo} = normalizePipeArguments(sourceInfo, ...pipeArguments);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 31–32why, one step back31 const pipeFailureController = new AbortController();32 const promise = handlePipePromise({...normalizedInfo, destination, pipeFailureController});100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 33–38why, one step back33 promise.pipe = pipeToSubprocess.bind(undefined, {34 ...sourceInfo,35 source: destination,36 sourcePromise: promise,37 boundOptions: {},38 });Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
line 39why, one step back39 forwardDestinationMethods(promise, destination, pipeFailureController.signal);100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 40–42why, one step back40 return promise;41};42Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 43–69why, one step back43/*44The return value of `.pipe()` exposes the destination subprocess' output, but its iteration and stream conversion methods must await the whole pipe so source failures are propagated too. The destination is `undefined` when `.pipe()` was passed invalid arguments, in which case the promise rejects and there is nothing to forward.45*/46const forwardDestinationMethods = (promise, destination, pipeFailureSignal) => {47 if (destination === undefined) {48 return;49 }5051 forwardReadableMethods(promise, destination);52 forwardIpcMethods(promise, destination, pipeFailureSignal);53};5455const forwardReadableMethods = (promise, destination) => {56 const subprocessOptions = SUBPROCESS_OPTIONS.get(destination);57 SUBPROCESS_OPTIONS.set(promise, subprocessOptions);58 promise.stdio = destination.stdio;59 promise.all = destination.all;6061 const {options: {encoding}} = subprocessOptions;62 const concurrentStreams = initializeConcurrentStreams();63 promise[Symbol.asyncIterator] = createIterable.bind(undefined, promise, encoding, {});64 promise.iterable = createIterable.bind(undefined, promise, encoding);65 promise.readable = createPipeReadable.bind(undefined, promise, {66 subprocess: promise,67 concurrentStreams,68 encoding,69 });Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
line 70why, one step back70 promise.readableStream = createReadableStream.bind(undefined, promise);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 71–83why, one step back71 forwardAll(promise, destination);72};7374const forwardAll = (promise, destination) => {75 if (destination.all === undefined) {76 promise.all = undefined;77 return;78 }7980 Object.defineProperty(promise, 'all', {81 get() {82 setAllProperty(promise, destination.all);83 const all = promise.readable({from: 'all'});Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
lines 84–85why, one step back84 // Like `subprocess.all`, the pipe's failure is handled by awaiting it, not by listening to the stream's `error` event. Consumers like `text(all)` still fail.85 all.on('error', () => {});Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 86–187why, one step back86 setAllProperty(promise, all);87 return all;88 },89 enumerable: true,90 configurable: true,91 });92};9394const setAllProperty = (promise, value) => {95 Object.defineProperty(promise, 'all', {96 value,97 writable: true,98 enumerable: true,99 configurable: true,100 });101};102103const createPipeReadable = (promise, readableOptions, ...arguments_) => {104 const readable = createReadable(readableOptions, ...arguments_);105 destroyOnPipeFailure(promise, readable);106 return readable;107};108109const destroyOnPipeFailure = async (promise, readable) => {110 try {111 await promise;112 } catch (error) {113 readable.destroy(error);114 }115};116117const forwardIpcMethods = (promise, destination, pipeFailureSignal) => {118 promise.sendMessage = destination.sendMessage;119 promise.getOneMessage = getOnePipeMessage.bind(undefined, destination, pipeFailureSignal);120 promise.getEachMessage = getEachPipeMessage.bind(undefined, promise, destination, pipeFailureSignal);121};122123const getOnePipeMessage = (destination, pipeFailureSignal, ...arguments_) => {124 const controller = new AbortController();125 const messagePromise = destination.getOneMessage(...addPipeOptions(arguments_, controller.signal, internalGetOneMessageOptions));126 return waitForOnePipeMessage(pipeFailureSignal, messagePromise, controller);127};128129const waitForOnePipeMessage = async (pipeFailureSignal, messagePromise, controller) => {130 try {131 return await Promise.race([messagePromise, getSignalRejection(pipeFailureSignal, controller.signal)]);132 } finally {133 controller.abort();134 }135};136137const getSignalRejection = (signal, listenerSignal) => new Promise((_, reject) => {138 if (signal.aborted) {139 reject(signal.reason);140 return;141 }142143 signal.addEventListener('abort', () => {144 reject(signal.reason);145 }, {once: true, signal: listenerSignal});146});147148const getEachPipeMessage = (promise, destination, pipeFailureSignal, ...arguments_) => {149 const controller = new AbortController();150 // Create the destination iterator before awaiting the pipe so option validation stays synchronous.151 const iterator = destination.getEachMessage(...addPipeOptions(arguments_, controller.signal, internalGetEachMessageOptions));152 abortOnSignal(pipeFailureSignal, controller);153 return iterateOnPipeMessages(promise, iterator, controller);154};155156const iterateOnPipeMessages = async function * (promise, iterator, controller) {157 try {158 yield * iterator;159 } finally {160 controller.abort();161 await promise;162 }163};164165const addPipeOptions = (arguments_, signal, internalOptionsSymbol) => {166 if (arguments_[0] === null) {167 // Preserve the public validation error from `getEachMessage(null)` instead of masking it with a pipe failure.168 return arguments_;169 }170171 const [options] = arguments_;172 // The returned pipe promise is awaited by the forwarded IPC iterator, so the destination IPC iterator must not also await the destination subprocess on close.173 return [{...options, [internalOptionsSymbol]: {signal, shouldAwait: false}}];174};175176const abortOnSignal = (signal, controller) => {177 if (signal.aborted) {178 controller.abort();179 return;180 }181182 // Interrupt pending IPC reads when the pipe rejects, including `unpipeSignal` cancellation while the destination keeps running.183 signal.addEventListener('abort', () => {184 controller.abort();185 }, {once: true, signal: controller.signal});186};187Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
line 188why, one step back188// `writable()`, `duplex()`, `writableStream()` and `transformStream()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
line 189why, one step back189100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 190–191why, one step back190// Asynchronous logic when piping subprocesses191const handlePipePromise = async ({Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
line 192why, one step back192 source,100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 193–202why, one step back193 sourcePromise,194 sourceStream,195 sourceOptions,196 sourceError,197 destination,198 destinationStream,199 destinationError,200 unpipeSignal,201 fileDescriptors,202 startTime,Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
line 203why, one step back203 pipeFailureController,100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 204–206why, one step back204}) => {205 const maxListenersController = new AbortController();206 try {Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
line 207why, one step back207 const subprocessPromises = getSubprocessPromises(sourcePromise, destination, source);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 208–216why, one step back208 handlePipeArgumentsError({209 sourceStream,210 sourceError,211 destinationStream,212 destinationError,213 fileDescriptors,214 sourceOptions,215 startTime,216 });100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 217–227why, one step back217 const mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController);218 return await Promise.race([219 waitForBothSubprocesses(subprocessPromises),220 ...unpipeOnAbort(unpipeSignal, {221 sourceStream,222 mergedStream,223 sourceOptions,224 fileDescriptors,225 startTime,226 }),227 ]);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 228–230why, one step back228 } catch (error) {229 pipeFailureController.abort(error);230 throw error;100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 231–238why, one step back231 } finally {232 maxListenersController.abort();233 }234};235236// `.pipe()` awaits the subprocess promises.237// When invalid arguments are passed to `.pipe()`, we throw an error, which prevents awaiting them.238// We need to ensure this does not create unhandled rejections.Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
lines 239–240why, one step back239// With `source.pipe(destination).pipe(secondDestination)`, the second `sourcePromise` is the first `.pipe()`, which rejects with the error of either subprocess. However, `secondDestination` is only piped from `destination`.240const getSubprocessPromises = (sourcePromise, destination, source) => Promise.allSettled([sourcePromise, destination, source]);