Skip to content
Myr

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

21 files+264 added−14 removed

modified:docs/ipc.md+2 added
182 unmodified lines
183184await execaNode({serialization: 'json'})`child.js`;185```186187Objects with a `type` property starting with `execa:ipc:` are reserved for Execa's internal messages, and should not be sent.188189## Messages order190191The messages are always received in the same order they were sent. Even when sent all at once.192
38 unmodified lines
modified:lib/ipc/forward.js+2 added
modified:lib/ipc/get-each.js+4 added-2 removed
modified:lib/ipc/get-one.js+5 added-1 removed
45 unmodified lines
46 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 }5455 throw error;56 } finally {57 controller.abort();58 removeReference(channel, reference);
40 unmodified lines
modified:lib/ipc/graceful.js+2 added-1 removed
39 unmodified lines
40 }4142 isCancelListening = true;4344 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 lines
modified:lib/ipc/send.js+4 added-2 removed
47 unmodified lines
48 methodName,49 isSubprocess,50 wrappedMessage,51 message,52 strict,53 });54 } catch (error) {55 disconnect(anyProcess);56 throw error;
2 unmodified lines
59 }60};6162// Used internally by `cancelSignal`62export const sendOneMessage = async ({anyProcess, methodName, isSubprocess, wrappedMessage, message}) => {63export const sendOneMessage = async ({anyProcess, methodName, isSubprocess, wrappedMessage, message, strict = false}) => {64 const sendMethod = getSendMethod(anyProcess);6566 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 lines
modified:lib/ipc/strict.js+17 added-7 removed
26 unmodified lines
2728// 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.30export const validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {31 if (wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners) {31 if (!isStrictRequest(wrappedMessage) || wrappedMessage.hasListeners) {32 return;33 }3435 for (const {id} of outgoingMessages) {
4 unmodified lines
40};4142// The other process then sends the acknowledgment back as a response43export const handleStrictRequest = async ({wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter}) => {44 if (wrappedMessage?.type !== REQUEST_TYPE || !anyProcess.connected) {44 if (!isStrictRequest(wrappedMessage)) {45 return wrappedMessage;46 }4748 const {id, message} = wrappedMessage;49 // The acknowledgment cannot be sent anymore, but the message is still delivered50 if (!anyProcess.connected) {51 return message;52 }5354 const response = {id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter)};5556 try {57 await sendMessage({
2 unmodified lines
60 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 }6970 return message;71};
15 unmodified lines
87};8889// Wait for the other process to receive the message from `sendMessage()`90export const waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => {83 if (wrappedMessage?.type !== REQUEST_TYPE) {84 return;85 }8691 const deferred = createDeferred();92 STRICT_RESPONSES[wrappedMessage.id] = {deferred, anyProcess};93 const controller = new AbortController();94
25 unmodified lines
120};121122const REQUEST_TYPE = 'execa:ipc:request';123const RESPONSE_TYPE = 'execa:ipc:response';124125// `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.127const isStrictRequest = wrappedMessage => wrappedMessage?.type === REQUEST_TYPE128 && Number.isInteger(wrappedMessage.id)129 && typeof wrappedMessage.hasListeners === 'boolean';
modified:lib/ipc/validation.js+12 added-1 removed
1import {inspect} from 'node:util';23// Validate the IPC channel is connected before receiving/sending messages4export const validateIpcMethod = ({methodName, isSubprocess, ipc, isConnected}) => {5 validateIpcOption(methodName, isSubprocess, ipc);6 validateConnection(methodName, isSubprocess, isConnected);
62 unmodified lines
69// Better error message when sending messages which cannot be serialized.70// Works with both `serialization: 'advanced'` and `serialization: 'json'`.71export 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};7677// `String()` throws with objects that have a `null` prototype or a throwing `toString()` method78const serializeInvalidMessage = message => {79 try {80 return String(message);81 } catch {82 return inspect(message);83 }84};8586const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)87 || SERIALIZATION_ERROR_MESSAGES.some(serializationErrorMessage => message.includes(serializationErrorMessage));8889// `error.code` set by Node.js when it failed to serialize the message
33 unmodified lines
added:test/fixtures/graceful-print-disconnected.js+12 added
1#!/usr/bin/env node2import process from 'node:process';3import {once} from 'node:events';4import {onAbortedSignal} from '../helpers/graceful.js';5import {getCancelSignal} from 'execa';67// Unlike `graceful-print.js`, Execa is imported before the parent process disconnects8process.send('.');9await once(process, 'disconnect');10const cancelSignal = await getCancelSignal();11await onAbortedSignal(cancelSignal);12console.log(cancelSignal.reason);
added:test/fixtures/ipc-get-concurrent.js+6 added
1#!/usr/bin/env node2import {argv} from 'node:process';3import {getOneMessage} from '../../index.js';45const messages = await Promise.all(Array.from({length: Number(argv[2])}, () => getOneMessage()));6console.log(messages.length);
added:test/fixtures/ipc-get-print-ready.js+6 added
1#!/usr/bin/env node2import {getOneMessage, sendMessage} from '../../index.js';34const messagePromise = getOneMessage();5await sendMessage('.');6console.log(await messagePromise);
added:test/fixtures/ipc-get-strict-disconnect.js+11 added
1#!/usr/bin/env node2import process from 'node:process';3import {getOneMessage} from '../../index.js';45const messagePromise = getOneMessage();6// Execa handles incoming messages on the next macrotask, so this disconnects before it does7process.once('message', () => {8 process.disconnect();9});10process.send('.');11console.log(JSON.stringify(await messagePromise));
added:test/fixtures/ipc-send-object.js+6 added
1#!/usr/bin/env node2import {argv} from 'node:process';3import {sendMessage} from '../../index.js';45// Sends any JSON message, so tests can send messages which look like Execa's internal IPC messages6await sendMessage(JSON.parse(argv[2]));
added:test/fixtures/ipc-send-strict-disconnect.js+11 added
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56// The acknowledgment cannot be received anymore7const sendPromise = sendMessage(foobarString, {strict: true});8process.disconnect();9try {10 await sendPromise;11} catch {}
modified:test/ipc/get-each.js+15 added
5 unmodified lines
6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString, foobarArray} from '../helpers/input.js';8import {PARALLEL_COUNT} from '../helpers/parallel.js';9import {iterateAllMessages} from '../helpers/ipc.js';10import {assertMaxListeners} from '../helpers/listeners.js';11/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */1213setFixtureDirectory();1415test('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});2829test('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 lines
modified:test/ipc/get-one.js+29 added
4 unmodified lines
5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString, foobarArray} from '../helpers/input.js';7import {isAlwaysTrue} from '../helpers/ipc.js';8import {PARALLEL_COUNT} from '../helpers/parallel.js';9import {assertMaxListeners} from '../helpers/listeners.js';1011setFixtureDirectory();1213test('subprocess.getOneMessage() can filter messages', async () => {
4 unmodified lines
18 const {ipcOutput} = await subprocess;19 assert.deepEqual(ipcOutput, foobarArray);20});2122test('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});2829test('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 lines
71 await subprocess;72 }));73});7475// The listeners are added to an internal emitter, so users cannot increase its maximum number of listeners76const 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};8485test('subprocess.getOneMessage() can be called many times at the same time', () => testConcurrentParent(undefined));86test('subprocess.getOneMessage() can be called many times at the same time, filter', () => testConcurrentParent(isAlwaysTrue));8788test('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});9596const 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 lines
modified:test/ipc/graceful.js+11 added
137 unmodified lines
138 assert.deepEqual(ipcOutput, []);139 assert.ok(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));140});141142test('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});152153test('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 lines
modified:test/ipc/send.js+10 added
39 unmodified lines
40 assert.equal(await subprocess.getOneMessage(), date.toJSON());41 await subprocess;42});4344const 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};5051test('Can send null-prototype objects', () => testNullPrototypeMessage('advanced'));52test('Can send null-prototype objects, serialization: "json"', () => testNullPrototypeMessage('json'));5354test('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 lines
modified:test/ipc/strict.js+79 added
35 unmodified lines
3637test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', () => testStrictSuccessParentEach(false));38test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', () => testStrictSuccessParentEach(true));3940// The message must not be wrapped with the `strict` metadata41test('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});4849test('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});5758// The acknowledgment cannot be sent back, but the message is still received59test('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});6869test('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});7374const 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 lines
330 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});334335// 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.337test('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 };345346 try {347 await subprocess.sendMessage(message);348 } finally {349 subprocess.kill();350 }351352 await assertRejects(subprocess);353});354355test('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});362363test('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});371372test('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 lines
86test('subprocess.sendMessage() cannot send functions, JSON', () => testInvalidPayload('json', () => {}, INVALID_TYPE_MESSAGE));87test('subprocess.sendMessage() cannot send cycles, JSON', () => testInvalidPayload('json', cycleObject, CYCLE_MESSAGE));88test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', () => testInvalidPayload('json', toJsonCycle, MAX_CALL_STACK_MESSAGE));8990// Those messages cannot be converted to a string either91const nullPrototypeCycle = {__proto__: null};92nullPrototypeCycle.self = nullPrototypeCycle;93const throwingToString = {94 callback() {},95 toString() {96 throw new Error('toString() failed');97 },98};99100test('subprocess.sendMessage() cannot send null-prototype objects with functions', () => testInvalidPayload('advanced', {__proto__: null, callback() {}}, CLONE_MESSAGE));101test('subprocess.sendMessage() cannot send objects with functions and a throwing toString()', () => testInvalidPayload('advanced', throwingToString, CLONE_MESSAGE));102test('subprocess.sendMessage() cannot send null-prototype cycles, JSON', () => testInvalidPayload('json', nullPrototypeCycle, CYCLE_MESSAGE));103104test('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 lines
modified:test/pipe/methods.js+6 added
188 unmodified lines
189190 const readerPromise = assertRejects(iterator.next(), {message: /Pipe canceled/});191 abortController.abort();192 await assertSettles(readerPromise);193 assert.equal(destination.nodeChildProcess.connected, true);194});195196test('The .pipe() return value .getEachMessage() cancels every pending reader', async t => {197 const abortController = new AbortController();
42 unmodified lines
240 }241242 await assertSettles(readerPromise);243 await assertRejects(piped, {message: /Pipe canceled/});244245 // 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};250251test('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