Skip to content
Myr

Fix child process not handling multiple `error` events (#790)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent 81f0b2d · Browse files · 5 files+81 added−50 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+81 added−50 removed

  • tests:+37 added−4 removed
  • other:+44 added−46 removed

5 files+81 added−50 removed

modified:lib/kill.js+2 added-2 removed
modified:lib/stream.js+41 added-43 removed
1import {addAbortListener} from 'node:events';1import {once} from 'node:events';2import {finished} from 'node:stream/promises';3import {setImmediate} from 'node:timers/promises';4import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';5import mergeStreams from '@sindresorhus/merge-streams';
108 unmodified lines
114const waitForCustomStreamsEnd = (stdioStreamsGroups, waitForStream) => stdioStreamsGroups.flat()115 .filter(({type, value}) => type !== 'native' && !isStandardStream(value))116 .map(({value}) => waitForStream(value));117118// Like `once()` except it never rejects, especially not on `error` event.119const pEvent = (eventEmitter, eventName, {signal}) => new Promise(resolve => {120 const listener = (...payload) => {121 resolve([eventName, ...payload]);122 };123124 eventEmitter.once(eventName, listener);125 addAbortListener(signal, () => {126 eventEmitter.removeListener(eventName, listener);127 });128});129118// Wraps `finished(stream)` to handle the following case:119// - When the child process exits, Node.js automatically calls `childProcess.stdin.destroy()`, which we need to ignore.120// - However, we still need to throw if `childProcess.stdin.destroy()` is called before child process exit.133const onFinishedStream = async ([originalStdin], processExitPromise, stream) => {134 const finishedPromise = finished(stream, {cleanup: true});135 if (stream !== originalStdin) {136 await finishedPromise;137 return;138 }139140 try {141 await finishedPromise;142 } catch {143 await Promise.race([processExitPromise, finishedPromise]);144 }121const onFinishedStream = async ([originalStdin], exitPromise, stream) => {122 await Promise.race([123 ...(stream === originalStdin ? [exitPromise] : []),124 finished(stream, {cleanup: true}),125 ]);126};127147const throwOnProcessError = async processErrorPromise => {148 const [, error] = await processErrorPromise;128const throwOnProcessError = async (spawned, {signal}) => {129 const [error] = await once(spawned, 'error', {signal});130 throw error;131};132152// First the `spawn` event is emitted, then `exit`.153// If the `error` event is emitted:154// - before `spawn`: `exit` is never emitted.155// - after `spawn`: `exit` is always emitted.156// We only want to listen to `exit` if it will be emitted, i.e. if `spawn` has been emitted.157// Therefore, the arguments order of `Promise.race()` is significant.158const waitForFailedProcess = async (processSpawnPromise, processErrorPromise, processExitPromise) => {159 const [eventName] = await Promise.race([processSpawnPromise, processErrorPromise]);160 return eventName === 'spawn' ? processExitPromise : [];133// If `error` is emitted before `spawn`, `exit` will never be emitted.134// However, `error` might be emitted after `spawn`, e.g. with the `signal` option.135// In that case, `exit` will still be emitted.136// Since the `exit` event contains the signal name, we want to make sure we are listening for it.137// This function also takes into account the following unlikely cases:138// - `exit` being emitted in the same microtask as `spawn`139// - `error` being emitted multiple times140const waitForExit = async spawned => {141 const [spawnPayload, exitPayload] = await Promise.allSettled([142 once(spawned, 'spawn'),143 once(spawned, 'exit'),144 ]);145146 if (spawnPayload.status === 'rejected') {147 return [];148 }149150 return exitPayload.status === 'rejected'151 ? waitForProcessExit(spawned)152 : exitPayload.value;153};154155const waitForProcessExit = async spawned => {156 try {157 return await once(spawned, 'exit');158 } catch {159 return waitForProcessExit(spawned);160 }161};162163// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)164export const getSpawnedResult = async ({165 spawned,166 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},
1 unmodified line
168 stdioStreamsGroups,169 originalStreams,170 controller,171}) => {172 const processSpawnPromise = pEvent(spawned, 'spawn', controller);173 const processErrorPromise = pEvent(spawned, 'error', controller);174 const processExitPromise = pEvent(spawned, 'exit', controller);175 const waitForStream = onFinishedStream.bind(undefined, originalStreams, processExitPromise);172 const exitPromise = waitForExit(spawned);173 const waitForStream = onFinishedStream.bind(undefined, originalStreams, exitPromise);174175 const stdioPromises = waitForChildStreams({spawned, stdioStreamsGroups, encoding, buffer, maxBuffer, waitForStream});176 const allPromise = waitForAllStream({spawned, encoding, buffer, maxBuffer, waitForStream});177 const originalPromises = waitForOriginalStreams(originalStreams, spawned, waitForStream);
2 unmodified lines
180 try {181 return await Promise.race([182 Promise.all([183 undefined,186 processExitPromise,184 exitPromise,185 Promise.all(stdioPromises),186 allPromise,187 ...originalPromises,188 ...customStreamsEndPromises,189 ]),192 throwOnProcessError(processErrorPromise),190 throwOnProcessError(spawned, controller),191 ...throwOnTimeout(timeout, context, controller),192 ]);193 } catch (error) {194 spawned.kill();195 return Promise.all([196 error,199 waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise),197 exitPromise,198 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),199 getBufferedData(allPromise, encoding),200 Promise.allSettled(originalPromises),201 Promise.allSettled(customStreamsEndPromises),
3 unmodified lines
modified:test/stdio/async.js+1 added
modified:test/kill.js+36 added-4 removed
1import process from 'node:process';2import {once, defaultMaxListeners} from 'node:events';3import {constants} from 'node:os';4import {setTimeout} from 'node:timers/promises';4import {setTimeout, setImmediate} from 'node:timers/promises';5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa, execaSync} from '../index.js';
373 unmodified lines
382 abortController.abort();383 t.false(result.isCanceled);384});385386test('child process errors are handled', async t => {386test('child process errors are handled before spawn', async t => {387 const subprocess = execa('forever.js');388 subprocess.emit('error', new Error('test'));389 await t.throwsAsync(subprocess, {message: 'Command failed: forever.js\ntest'});388 const error = new Error('test');389 subprocess.emit('error', error);390 const thrownError = await t.throwsAsync(subprocess);391 t.is(thrownError, error);392 t.is(thrownError.exitCode, undefined);393 t.is(thrownError.signal, undefined);394 t.false(thrownError.isTerminated);395});396397test('child process errors are handled after spawn', async t => {398 const subprocess = execa('forever.js');399 await once(subprocess, 'spawn');400 const error = new Error('test');401 subprocess.emit('error', error);402 const thrownError = await t.throwsAsync(subprocess);403 t.is(thrownError, error);404 t.is(thrownError.exitCode, undefined);405 t.is(thrownError.signal, 'SIGTERM');406 t.true(thrownError.isTerminated);407});408409test('child process double errors are handled after spawn', async t => {410 const abortController = new AbortController();411 const subprocess = execa('forever.js', {signal: abortController.signal});412 await once(subprocess, 'spawn');413 const error = new Error('test');414 subprocess.emit('error', error);415 await setImmediate();416 abortController.abort();417 const thrownError = await t.throwsAsync(subprocess);418 t.is(thrownError, error);419 t.is(thrownError.exitCode, undefined);420 t.is(thrownError.signal, 'SIGTERM');421 t.true(thrownError.isTerminated);422});423424test('child process errors use killSignal', async t => {425 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});426 await once(subprocess, 'spawn');427 const error = new Error('test');
6 unmodified lines
modified:index.js+1 added-1 removed
173 unmodified lines
174 const context = {timedOut: false};175176 const [177 error,178 [, exitCode, signal],178 [exitCode, signal],179 stdioResults,180 allResult,181 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});182 controller.abort();
183 unmodified lines