Fix a subprocess which failed to spawn signaling the current process and never ending its streams
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 9842f1a · Browse files · 3 files·+129 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+129 added−18 removed
- tests:+78 added−0 removed
- other:+51 added−18 removed
Provenance
- Commit
5464d43- Tree
5d93938- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
9842f1a
3 files changed+129 added−18 removed
modified:lib/return/early-error.js+43 added-17 removed
1234568 unmodified lines15161718192021222324258 unmodified lines3435363734353637383940414243383940414217 unmodified lines6061626369707172737475646566676869707172737475767778798081828384858687888990919293949596979899100101102103import {ChildProcess} from 'node:child_process';import {callbackify} from 'node:util';import { PassThrough, Readable, Writable,8 unmodified linesexport const handleEarlyError = ({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo}) => { cleanupCustomStreams(fileDescriptors);
const subprocess = new ChildProcess(); // The subprocess never spawned, so there is no process to signal. // `ChildProcess.prototype.kill()` would signal the current process group instead, since its process id is `0`. subprocess.kill = () => false; const all = createDummyStreams(subprocess, fileDescriptors);
const earlyError = makeEarlyError({ error,8 unmodified lines return { subprocess, promise, all: options.all ? all : undefined, convertedStreams: { readable, writable, duplex, readableStream, writableStream, transformStream, iterable, [Symbol.asyncIterator]: iterable, }, convertedStreams: getConvertedStreams(promise), };};
const createDummyStreams = (subprocess, fileDescriptors) => {17 unmodified lines stream.end(); return stream;};
const readable = () => new Readable({read() {}});const writable = () => new Writable({write() {}});const duplex = () => new Duplex({read() {}, write() {}});const readableStream = () => Readable.toWeb(readable());const writableStream = () => Writable.toWeb(writable());const transformStream = () => Duplex.toWeb(duplex());const iterable = async function * () {};// The subprocess never started, so those streams have no contents.// Like when the subprocess did start, they end once its promise resolves, or error with its error, as opposed to hanging forever.const getConvertedStreams = promise => { const waitForPromise = async () => { await promise; };
const endReadable = function () { callbackify(waitForPromise)(error => { if (error) { this.destroy(error); } else { this.push(null); } }); };
const endWritable = callbackify(waitForPromise); const writeWritable = (chunk, encoding, done) => { endWritable(done); };
const readable = () => new Readable({read: endReadable}); const writable = () => new Writable({write: writeWritable, final: endWritable}); const duplex = () => new Duplex({read: endReadable, write: writeWritable, final: endWritable}); const iterable = () => readable()[Symbol.asyncIterator]();
return { readable, writable, duplex, readableStream: () => Readable.toWeb(readable()), writableStream: () => Writable.toWeb(writable()), transformStream: () => Duplex.toWeb(duplex()), iterable, [Symbol.asyncIterator]: iterable, };};
const handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);modified:lib/terminate/kill-descendants.js+8 added-1 removed
11 unmodified lines12131415161718192021222324252026272829303155 unmodified lines11 unmodified linesexport const getSpawnOptions = options => options.killDescendants && !isWindows ? {...options, detached: true} : options;
/*`subprocess.pid` is `undefined` when the subprocess failed to spawn, e.g. with `ENOENT`.`ChildProcess.prototype.kill()` then signals the current process group, since its process id is `0`.So, like `ChildProcess.prototype.kill()` does for a subprocess which already exited, nothing is signaled and `false` is returned.*/
// Returns the low-level function used to send a signal to the subprocess.// With the `killDescendants` option, the signal is sent to the whole process tree.export const getKillFunction = (subprocess, {killDescendants}) => { if (!killDescendants) { return subprocess.kill.bind(subprocess); const killSubprocess = subprocess.kill.bind(subprocess); return (...arguments_) => (subprocess.pid === undefined ? false : killSubprocess(...arguments_)); }
const killDescendantsFunction = isWindows ? killDescendantsWindows : killDescendantsUnix; return killDescendantsFunction.bind(undefined, subprocess);55 unmodified linesmodified:test/return/early-error.js+78 added
1 import {arch} from 'node:os';2 import process from 'node:process';3+import {finished} from 'node:stream/promises';4 import test from 'ava';5 import {execa, execaSync, $} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7+import {foobarString, foobarUint8Array} from '../helpers/input.js';8 import {fullStdio} from '../helpers/stdio.js';9 import {10 earlyErrorOptions,11 getEarlyErrorSubprocess,6 unmodified lines18 19 const isWindows = process.platform === 'win32';20 const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;21 22+// A nonexistent command fails asynchronously, so it does not go through the early error path, but the subprocess still has no process to signal23+test('kill() does not signal the current process when the command does not exist', async t => {24+ const subprocess = execa('nonexistent-command-for-execa');25+ t.is(subprocess.pid, undefined);26+ t.is(subprocess.kill(), false);27+ t.is((await t.throwsAsync(subprocess)).code, 'ENOENT');28+});29+30 test('execaSync() throws error if ENOENT', t => {31 t.throws(() => {32 execaSync('foo');33 }, {message: ENOENT_REGEXP});10 unmodified lines44 45 test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);46 test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);47 48+// The subprocess never spawned, so there is no process to signal.49+// `ChildProcess.prototype.kill()` would signal the current process group instead, since its process id is `0`.50+// The handle is replaced by a stub, so that a regression is caught by an assertion instead of killing this test process.51+test('kill() does not signal the current process on early errors', async t => {52+ const subprocess = getEarlyErrorSubprocess({reject: false});53+ let isSignaled = false;54+ subprocess.nodeChildProcess._handle = {55+ kill() {56+ isSignaled = true;57+ return 0;58+ },59+ };60+61+ t.is(subprocess.kill(), false);62+ t.false(isSignaled);63+ const {failed, isCanceled} = await subprocess;64+ t.true(failed);65+ t.false(isCanceled);66+});67+68 test('child_process.spawn() early errors are propagated', async t => {69 await t.throwsAsync(getEarlyErrorSubprocess(), expectedEarlyError);70 });71 70 unmodified lines142 test('child_process.spawn() early errors can use .readableStream()', testEarlyErrorWebConvertor, 'readableStream');143 test('child_process.spawn() early errors can use .writableStream()', testEarlyErrorWebConvertor, 'writableStream');144 test('child_process.spawn() early errors can use .transformStream()', testEarlyErrorWebConvertor, 'transformStream');145 146+// The subprocess never started, so those streams have no contents.147+// They must end right away, like `subprocess.stdout` and `.iterable()` do, instead of hanging forever.148+const testEarlyErrorReadableEnd = async (t, streamMethod) => {149+ const subprocess = getEarlyErrorSubprocess();150+ const chunks = await Array.fromAsync(subprocess[streamMethod]());151+152+ t.deepEqual(chunks, []);153+ await t.throwsAsync(subprocess);154+};155+156+test('child_process.spawn() early errors end .readable()', testEarlyErrorReadableEnd, 'readable');157+test('child_process.spawn() early errors end .duplex()', testEarlyErrorReadableEnd, 'duplex');158+test('child_process.spawn() early errors end .readableStream()', testEarlyErrorReadableEnd, 'readableStream');159+160+const testEarlyErrorWritableEnd = async (t, streamMethod) => {161+ const subprocess = getEarlyErrorSubprocess();162+ const stream = subprocess[streamMethod]();163+ stream.end(foobarString);164+ await finished(stream, {readable: false});165+166+ t.false(stream.writable);167+ await t.throwsAsync(subprocess);168+};169+170+test('child_process.spawn() early errors end .writable()', testEarlyErrorWritableEnd, 'writable');171+test('child_process.spawn() early errors end .duplex() writable side', testEarlyErrorWritableEnd, 'duplex');172+173+test('child_process.spawn() early errors end .writableStream()', async t => {174+ const subprocess = getEarlyErrorSubprocess();175+ const writer = subprocess.writableStream().getWriter();176+ await writer.write(foobarUint8Array);177+ await writer.close();178+179+ await t.throwsAsync(subprocess);180+});181+182+test('child_process.spawn() early errors end .transformStream()', async t => {183+ const subprocess = getEarlyErrorSubprocess();184+ const {readable, writable} = subprocess.transformStream();185+ const writer = writable.getWriter();186+ await writer.write(foobarUint8Array);187+ await writer.close();188+ const chunks = await Array.fromAsync(readable);189+190+ t.deepEqual(chunks, []);191+ await t.throwsAsync(subprocess);192+});193+194 const testEarlyErrorIpc = async (t, runIpcMethod) => {195 const subprocess = getEarlyErrorSubprocess({ipc: true});196 t.throws(() => {197 runIpcMethod(subprocess);39 unmodified lines