Fix IPC edge cases
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 d3ec10d · Browse files · 21 files·+264 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+264 added−14 removed
- tests:+216 added−0 removed
- other:+48 added−14 removed
Provenance
- Commit
5f80cde- Tree
3779dc2- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
d3ec10d
21 files changed+264 added−14 removed
modified:docs/ipc.md+2 added
182 unmodified lines183 184 await execaNode({serialization: 'json'})`child.js`;185 ```186 187+Objects with a `type` property starting with `execa:ipc:` are reserved for Execa's internal messages, and should not be sent.188+189 ## Messages order190 191 The messages are always received in the same order they were sent. Even when sent all at once.192 38 unmodified linesmodified:lib/ipc/forward.js+2 added
11 unmodified lines1213141516171819202137 unmodified lines11 unmodified lines
// Use an `EventEmitter`, like the `process` that is being proxied // eslint-disable-next-line unicorn/prefer-event-target const ipcEmitter = new EventEmitter(); // Each pending `getOneMessage()` or `getEachMessage()` call adds listeners, which are removed once it ends. Users cannot reach this emitter to increase its maximum number of listeners. ipcEmitter.setMaxListeners(0); ipcEmitter.connected = true; IPC_EMITTERS.set(anyProcess, ipcEmitter); forwardEvents({ ipcEmitter,37 unmodified linesmodified:lib/ipc/get-each.js+4 added-2 removed
54 unmodified lines55565758596061626326 unmodified lines909192939394959697983 unmodified lines10210310410510510610710810911011110 unmodified lines54 unmodified lines shouldAwait, controller, state, reference, signal, });};
const stopOnAbort = (signal, controller) => {26 unmodified lines controller.abort(); } catch {}};
const iterateOnMessages = async function * ({anyProcess, waitProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference}) {const iterateOnMessages = async function * ({anyProcess, waitProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference, signal}) { try { for await (const [message] of on(ipcEmitter, 'message', {signal: controller.signal})) { throwIfStrictError(state); yield message;3 unmodified lines } finally { controller.abort(); removeReference(channel, reference);
if (!isSubprocess) { // When the internal `signal` stops the iteration, e.g. when a `.pipe()` is canceled, the subprocess keeps running and can still use IPC if (!isSubprocess && !signal?.aborted) { disconnect(anyProcess); }
if (shouldAwait) {10 unmodified linesmodified:lib/ipc/get-one.js+5 added-1 removed
45 unmodified lines46 throwOnDisconnect(ipcEmitter, isSubprocess, controller),47 throwOnStrictError(ipcEmitter, isSubprocess, controller),48 ]);49 } catch (error) {50+ // When the internal `signal` stops the read, e.g. when a `.pipe()` is canceled, the subprocess keeps running and can still use IPC51+ if (!signal?.aborted) {50- disconnect(anyProcess);52+ disconnect(anyProcess);53+ }54+55 throw error;56 } finally {57 controller.abort();58 removeReference(channel, reference);40 unmodified linesmodified:lib/ipc/graceful.js+2 added-1 removed
39 unmodified lines40 }41 42 isCancelListening = true;43 44- if (channel === null) {44+ // `channel` is retrieved when Execa is imported, so the current process might have disconnected since then45+ if (!anyProcess.connected) {46 abortOnDisconnect();47 return;48 }49 25 unmodified linesmodified:lib/ipc/send.js+4 added-2 removed
47 unmodified lines48 methodName,49 isSubprocess,50 wrappedMessage,51 message,52+ strict,53 });54 } catch (error) {55 disconnect(anyProcess);56 throw error;2 unmodified lines59 }60 };61 62 // Used internally by `cancelSignal`62-export const sendOneMessage = async ({anyProcess, methodName, isSubprocess, wrappedMessage, message}) => {63+export const sendOneMessage = async ({anyProcess, methodName, isSubprocess, wrappedMessage, message, strict = false}) => {64 const sendMethod = getSendMethod(anyProcess);65 66 try {67 await Promise.all([67- waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),68+ // Only messages sent with the `strict` option wait for an acknowledgment response69+ strict ? waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess) : undefined,70 sendMethod(wrappedMessage),71 ]);72 } catch (error) {73 handleEpipeError({error, methodName, isSubprocess});22 unmodified linesmodified:lib/ipc/strict.js+17 added-7 removed
26 unmodified lines27 28 // Handles when both processes are calling `sendMessage()` with `strict` at the same time.29 // If neither process is listening, this would create a deadlock. We detect it and throw.30 export const validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {31- if (wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners) {31+ if (!isStrictRequest(wrappedMessage) || wrappedMessage.hasListeners) {32 return;33 }34 35 for (const {id} of outgoingMessages) {4 unmodified lines40 };41 42 // The other process then sends the acknowledgment back as a response43 export const handleStrictRequest = async ({wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter}) => {44- if (wrappedMessage?.type !== REQUEST_TYPE || !anyProcess.connected) {44+ if (!isStrictRequest(wrappedMessage)) {45 return wrappedMessage;46 }47 48 const {id, message} = wrappedMessage;49+ // The acknowledgment cannot be sent anymore, but the message is still delivered50+ if (!anyProcess.connected) {51+ return message;52+ }53+54 const response = {id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter)};55 56 try {57 await sendMessage({2 unmodified lines60 isSubprocess,61 ipc: true,62 }, response);63 } catch (error) {64+ // When the other process disconnects right after sending the message, it cannot receive the acknowledgment anymore. Like above, the message is still delivered.65+ if (error.cause?.code !== 'EPIPE') {59- ipcEmitter.emit('strict:error', error);66+ ipcEmitter.emit('strict:error', error);67+ }68 }69 70 return message;71 };15 unmodified lines87 };88 89 // Wait for the other process to receive the message from `sendMessage()`90 export const waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => {83- if (wrappedMessage?.type !== REQUEST_TYPE) {84- return;85- }86-91 const deferred = createDeferred();92 STRICT_RESPONSES[wrappedMessage.id] = {deferred, anyProcess};93 const controller = new AbortController();94 25 unmodified lines120 };121 122 const REQUEST_TYPE = 'execa:ipc:request';123 const RESPONSE_TYPE = 'execa:ipc:response';124+125+// `id` and `hasListeners` are always defined in messages sent by `sendMessage()` with the `strict` option.126+// Messages with the same `type` but without them are user messages, which must be delivered as is.127+const isStrictRequest = wrappedMessage => wrappedMessage?.type === REQUEST_TYPE128+ && Number.isInteger(wrappedMessage.id)129+ && typeof wrappedMessage.hasListeners === 'boolean';modified:lib/ipc/validation.js+12 added-1 removed
1+import {inspect} from 'node:util';2+3 // Validate the IPC channel is connected before receiving/sending messages4 export const validateIpcMethod = ({methodName, isSubprocess, ipc, isConnected}) => {5 validateIpcOption(methodName, isSubprocess, ipc);6 validateConnection(methodName, isSubprocess, isConnected);62 unmodified lines69 // Better error message when sending messages which cannot be serialized.70 // Works with both `serialization: 'advanced'` and `serialization: 'json'`.71 export const handleSerializationError = ({error, methodName, isSubprocess, message}) => {72 if (isSerializationError(error)) {71- throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, {cause: error});73+ throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${serializeInvalidMessage(message)}.`, {cause: error});74 }75 };76 77+// `String()` throws with objects that have a `null` prototype or a throwing `toString()` method78+const serializeInvalidMessage = message => {79+ try {80+ return String(message);81+ } catch {82+ return inspect(message);83+ }84+};85+86 const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)87 || SERIALIZATION_ERROR_MESSAGES.some(serializationErrorMessage => message.includes(serializationErrorMessage));88 89 // `error.code` set by Node.js when it failed to serialize the message33 unmodified linesadded:test/fixtures/graceful-print-disconnected.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {once} from 'node:events';4+import {onAbortedSignal} from '../helpers/graceful.js';5+import {getCancelSignal} from 'execa';6+7+// Unlike `graceful-print.js`, Execa is imported before the parent process disconnects8+process.send('.');9+await once(process, 'disconnect');10+const cancelSignal = await getCancelSignal();11+await onAbortedSignal(cancelSignal);12+console.log(cancelSignal.reason);added:test/fixtures/ipc-get-concurrent.js+6 added
1+#!/usr/bin/env node2+import {argv} from 'node:process';3+import {getOneMessage} from '../../index.js';4+5+const messages = await Promise.all(Array.from({length: Number(argv[2])}, () => getOneMessage()));6+console.log(messages.length);added:test/fixtures/ipc-get-print-ready.js+6 added
1+#!/usr/bin/env node2+import {getOneMessage, sendMessage} from '../../index.js';3+4+const messagePromise = getOneMessage();5+await sendMessage('.');6+console.log(await messagePromise);added:test/fixtures/ipc-get-strict-disconnect.js+11 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getOneMessage} from '../../index.js';4+5+const messagePromise = getOneMessage();6+// Execa handles incoming messages on the next macrotask, so this disconnects before it does7+process.once('message', () => {8+ process.disconnect();9+});10+process.send('.');11+console.log(JSON.stringify(await messagePromise));added:test/fixtures/ipc-send-object.js+6 added
1+#!/usr/bin/env node2+import {argv} from 'node:process';3+import {sendMessage} from '../../index.js';4+5+// Sends any JSON message, so tests can send messages which look like Execa's internal IPC messages6+await sendMessage(JSON.parse(argv[2]));added:test/fixtures/ipc-send-strict-disconnect.js+11 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+6+// The acknowledgment cannot be received anymore7+const sendPromise = sendMessage(foobarString, {strict: true});8+process.disconnect();9+try {10+ await sendPromise;11+} catch {}modified:test/ipc/get-each.js+15 added
5 unmodified lines6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString, foobarArray} from '../helpers/input.js';8 import {PARALLEL_COUNT} from '../helpers/parallel.js';9 import {iterateAllMessages} from '../helpers/ipc.js';10+import {assertMaxListeners} from '../helpers/listeners.js';11 /* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */12 13 setFixtureDirectory();14 15+test('subprocess.getEachMessage() can be called many times at the same time', async () => {16+ const checkMaxListeners = assertMaxListeners();17+ const subprocess = execa('ipc-send.js', {ipc: true});18+ const messages = await Promise.all(Array.from({length: PARALLEL_COUNT}, async () => {19+ const iterator = subprocess.getEachMessage();20+ const {value} = await iterator.next();21+ await iterator.return();22+ return value;23+ }));24+ assert.deepEqual(messages, Array.from({length: PARALLEL_COUNT}, () => foobarString));25+ await subprocess;26+ checkMaxListeners();27+});28+29 test('Can iterate over IPC messages', async () => {30 let count = 0;31 const subprocess = execa('ipc-send-twice.js', {ipc: true});32 for await (const message of subprocess.getEachMessage()) {201 unmodified linesmodified:test/ipc/get-one.js+29 added
4 unmodified lines5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString, foobarArray} from '../helpers/input.js';7 import {isAlwaysTrue} from '../helpers/ipc.js';8 import {PARALLEL_COUNT} from '../helpers/parallel.js';9+import {assertMaxListeners} from '../helpers/listeners.js';10 11 setFixtureDirectory();12 13 test('subprocess.getOneMessage() can filter messages', async () => {4 unmodified lines18 const {ipcOutput} = await subprocess;19 assert.deepEqual(ipcOutput, foobarArray);20 });21 22+test('subprocess.getOneMessage() filter not matching any message rejects on exit', async () => {23+ const subprocess = execa('ipc-send.js', {ipc: true});24+ const error = await assertRejects(subprocess.getOneMessage({filter: () => false}));25+ assert.equal(error.message, 'subprocess.getOneMessage() could not complete: the subprocess exited or disconnected.');26+ await subprocess;27+});28+29 test('exports.getOneMessage() can filter messages', async () => {30 const subprocess = execa('ipc-echo-filter.js', {ipc: true});31 await subprocess.sendMessage(foobarArray[0]);32 await subprocess.sendMessage(foobarArray[1]);38 unmodified lines71 await subprocess;72 }));73 });74 75+// The listeners are added to an internal emitter, so users cannot increase its maximum number of listeners76+const testConcurrentParent = async filter => {77+ const checkMaxListeners = assertMaxListeners();78+ const subprocess = execa('ipc-send.js', {ipc: true});79+ const messages = await Promise.all(Array.from({length: PARALLEL_COUNT}, () => subprocess.getOneMessage({filter})));80+ assert.deepEqual(messages, Array.from({length: PARALLEL_COUNT}, () => foobarString));81+ await subprocess;82+ checkMaxListeners();83+};84+85+test('subprocess.getOneMessage() can be called many times at the same time', () => testConcurrentParent(undefined));86+test('subprocess.getOneMessage() can be called many times at the same time, filter', () => testConcurrentParent(isAlwaysTrue));87+88+test('exports.getOneMessage() can be called many times at the same time', async () => {89+ const subprocess = execa('ipc-get-concurrent.js', [`${PARALLEL_COUNT}`], {ipc: true});90+ await subprocess.sendMessage(foobarString, {strict: true});91+ const {stdout, stderr} = await subprocess;92+ assert.equal(stdout, `${PARALLEL_COUNT}`);93+ assert.equal(stderr, '');94+});95+96 const testTwice = async (buffer, filter) => {97 const subprocess = execa('ipc-send.js', {ipc: true, buffer});98 assert.deepEqual(99 await Promise.all([subprocess.getOneMessage({filter}), subprocess.getOneMessage({filter})]),63 unmodified linesmodified:test/ipc/graceful.js+11 added
137 unmodified lines138 assert.deepEqual(ipcOutput, []);139 assert.ok(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));140 });141 142+test('getCancelSignal() aborts if first called after disconnection', async () => {143+ const controller = new AbortController();144+ const subprocess = execa('graceful-print-disconnected.js', {cancelSignal: controller.signal, gracefulCancel: true});145+ assert.equal(await subprocess.getOneMessage(), '.');146+ subprocess.nodeChildProcess.disconnect();147+ const {isCanceled, ipcOutput, stdout} = await subprocess;148+ assert.equal(isCanceled, false);149+ assert.deepEqual(ipcOutput, ['.']);150+ assert.ok(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));151+});152+153 test('getCancelSignal() fails if no IPC', async () => {154 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, stderr} = await assertRejects(execa('graceful-none.js'));155 assert.equal(isCanceled, false);156 assert.equal(isGracefullyCanceled, false);92 unmodified linesmodified:test/ipc/send.js+10 added
39 unmodified lines40 assert.equal(await subprocess.getOneMessage(), date.toJSON());41 await subprocess;42 });43 44+const testNullPrototypeMessage = async serialization => {45+ const subprocess = execa('ipc-echo.js', {ipc: true, serialization});46+ await subprocess.sendMessage({__proto__: null, foo: foobarString});47+ assert.deepEqual({...await subprocess.getOneMessage()}, {foo: foobarString});48+ await subprocess;49+};50+51+test('Can send null-prototype objects', () => testNullPrototypeMessage('advanced'));52+test('Can send null-prototype objects, serialization: "json"', () => testNullPrototypeMessage('json'));53+54 test('Validates JSON payload with serialization: "json"', async () => {55 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});56 await assertRejects(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});57 await assertRejects(subprocess);98 unmodified linesmodified:test/ipc/strict.js+79 added
35 unmodified lines36 37 test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', () => testStrictSuccessParentEach(false));38 test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', () => testStrictSuccessParentEach(true));39 40+// The message must not be wrapped with the `strict` metadata41+test('subprocess.sendMessage() "strict" delivers the message if the subprocess disconnects before handling it', async () => {42+ const subprocess = execa('ipc-get-strict-disconnect.js', {ipc: true});43+ assert.equal(await subprocess.getOneMessage(), '.');44+ await assertRejects(subprocess.sendMessage(foobarString, {strict: true}), {message: /^subprocess\.sendMessage\(\) failed: /});45+ const {stdout} = await subprocess;46+ assert.equal(stdout, JSON.stringify(foobarString));47+});48+49+test('exports.sendMessage() "strict" delivers the message if the parent disconnects before handling it', async () => {50+ const subprocess = execa('ipc-send-strict.js', {ipc: true, reject: false});51+ subprocess.nodeChildProcess.once('message', () => {52+ subprocess.nodeChildProcess.disconnect();53+ });54+ const {ipcOutput} = await subprocess;55+ assert.deepEqual(ipcOutput, [foobarString]);56+});57+58+// The acknowledgment cannot be sent back, but the message is still received59+test('subprocess.sendMessage() "strict" delivers the message if the current process disconnects right after sending it', async () => {60+ const subprocess = execa('ipc-get-print-ready.js', {ipc: true});61+ assert.equal(await subprocess.getOneMessage(), '.');62+ const sendPromise = subprocess.sendMessage(foobarString, {strict: true});63+ subprocess.nodeChildProcess.disconnect();64+ await assertRejects(sendPromise);65+ const {stdout} = await subprocess;66+ assert.equal(stdout, foobarString);67+});68+69+test('exports.sendMessage() "strict" delivers the message if the subprocess disconnects right after sending it', async () => {70+ const {ipcOutput} = await execa('ipc-send-strict-disconnect.js', {ipc: true});71+ assert.deepEqual(ipcOutput, [foobarString]);72+});73+74 const testStrictMissingParent = async buffer => {75 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString, buffer});76 const promise = subprocess.getOneMessage();77 const secondPromise = subprocess.sendMessage(foobarString, {strict: true});252 unmodified lines330 assert.equal(exitCode, 1);331 assert.ok(stderr.includes('Error: sendMessage() failed: the parent process is sending a message too, instead of listening to incoming messages.'));332 assert.deepEqual(ipcOutput, []);333 });334+335+// Messages which look like Execa's internal `strict` messages but are sent without the `strict` option are user messages.336+// They must not wait for an acknowledgment response, and must be delivered as is.337+test('sendMessage() does not wait for an acknowledgment response unless the "strict" option is true', async () => {338+ const subprocess = execa('forever.js', {ipc: true});339+ const message = {340+ type: 'execa:ipc:request',341+ id: 0,342+ message: foobarString,343+ hasListeners: false,344+ };345+346+ try {347+ await subprocess.sendMessage(message);348+ } finally {349+ subprocess.kill();350+ }351+352+ await assertRejects(subprocess);353+});354+355+test('Messages with the internal "strict" request type are kept as is', async () => {356+ const message = {357+ type: 'execa:ipc:request',358+ };359+ const {ipcOutput} = await execa('ipc-send-object.js', [JSON.stringify(message)], {ipc: true});360+ assert.deepEqual(ipcOutput, [message]);361+});362+363+test('Messages with the internal "strict" request type are kept as is, from the parent', async () => {364+ const message = {365+ type: 'execa:ipc:request',366+ message: foobarString,367+ };368+ const {ipcOutput} = await execa('ipc-echo.js', {ipcInput: message});369+ assert.deepEqual(ipcOutput, [message]);370+});371+372+test('Messages with the internal "strict" request type do not fail pending "strict" sends', async () => {373+ const subprocess = execa('ipc-send-object.js', [JSON.stringify({type: 'execa:ipc:request'})], {ipc: true, buffer: {ipc: false}});374+ const sendPromise = subprocess.sendMessage(foobarString, {strict: true});375+ const {message} = await assertRejects(sendPromise);376+ assert.equal(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');377+ await subprocess;378+});modified:test/ipc/validation.js+14 added
85 unmodified lines86 test('subprocess.sendMessage() cannot send functions, JSON', () => testInvalidPayload('json', () => {}, INVALID_TYPE_MESSAGE));87 test('subprocess.sendMessage() cannot send cycles, JSON', () => testInvalidPayload('json', cycleObject, CYCLE_MESSAGE));88 test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', () => testInvalidPayload('json', toJsonCycle, MAX_CALL_STACK_MESSAGE));89 90+// Those messages cannot be converted to a string either91+const nullPrototypeCycle = {__proto__: null};92+nullPrototypeCycle.self = nullPrototypeCycle;93+const throwingToString = {94+ callback() {},95+ toString() {96+ throw new Error('toString() failed');97+ },98+};99+100+test('subprocess.sendMessage() cannot send null-prototype objects with functions', () => testInvalidPayload('advanced', {__proto__: null, callback() {}}, CLONE_MESSAGE));101+test('subprocess.sendMessage() cannot send objects with functions and a throwing toString()', () => testInvalidPayload('advanced', throwingToString, CLONE_MESSAGE));102+test('subprocess.sendMessage() cannot send null-prototype cycles, JSON', () => testInvalidPayload('json', nullPrototypeCycle, CYCLE_MESSAGE));103+104 test('exports.sendMessage() validates payload', async () => {105 const subprocess = execa('ipc-echo-item.js', {ipc: true});106 await subprocess.sendMessage([undefined]);107 const {message} = await assertRejects(subprocess);3 unmodified linesmodified:test/pipe/methods.js+6 added
188 unmodified lines189 190 const readerPromise = assertRejects(iterator.next(), {message: /Pipe canceled/});191 abortController.abort();192 await assertSettles(readerPromise);193+ assert.equal(destination.nodeChildProcess.connected, true);194 });195 196 test('The .pipe() return value .getEachMessage() cancels every pending reader', async t => {197 const abortController = new AbortController();42 unmodified lines240 }241 242 await assertSettles(readerPromise);243 await assertRejects(piped, {message: /Pipe canceled/});244+245+ // The destination keeps running after the pipe is canceled, so it must still be able to use IPC246+ assert.equal(destination.nodeChildProcess.connected, true);247+ await destination.sendMessage(foobarString);248+ await destination;249 };250 251 test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {252 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());210 unmodified lines