Fix deadlocks with IPC (#1104)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 691af8a · Browse files · 8 files·+74 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+74 added−27 removed
- tests:+16 added−9 removed
- other:+58 added−18 removed
Provenance
- Commit
465e427- Tree
793913f- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
691af8a
8 files changed+74 added−27 removed
modified:lib/ipc/incoming.js+1 added-1 removed
38 unmodified lines3940414243434445464729 unmodified lines38 unmodified lines }
while (incomingMessages.length > 0) { // eslint-disable-next-line no-await-in-loop await waitForOutgoingMessages(anyProcess, ipcEmitter); await waitForOutgoingMessages(anyProcess, ipcEmitter, wrappedMessage); // eslint-disable-next-line no-await-in-loop await scheduler.yield();
// eslint-disable-next-line no-await-in-loop29 unmodified linesmodified:lib/ipc/outgoing.js+13 added-8 removed
12345677891011121314151614151718192018192021222324252624272829303127323334353610 unmodified linesimport {createDeferred} from '../utils/deferred.js';import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';import {validateStrictDeadlock} from './strict.js';
// When `sendMessage()` is ongoing, any `message` being received waits before being emitted.// This allows calling one or multiple `await sendMessage()` followed by `await getOneMessage()`/`await getEachMessage()`.// Without running into a race condition when the other process sends a response too fast, before the current process set up a listener.export const startSendMessage = anyProcess => {export const startSendMessage = (anyProcess, wrappedMessage, strict) => { if (!OUTGOING_MESSAGES.has(anyProcess)) { OUTGOING_MESSAGES.set(anyProcess, new Set()); }
const outgoingMessages = OUTGOING_MESSAGES.get(anyProcess); const onMessageSent = createDeferred(); const id = strict ? wrappedMessage.id : undefined; const outgoingMessage = {onMessageSent, id}; outgoingMessages.add(onMessageSent); return {outgoingMessages, onMessageSent}; outgoingMessages.add(outgoingMessage); return {outgoingMessages, outgoingMessage};};
export const endSendMessage = ({outgoingMessages, onMessageSent}) => { outgoingMessages.delete(onMessageSent); onMessageSent.resolve();export const endSendMessage = ({outgoingMessages, outgoingMessage}) => { outgoingMessages.delete(outgoingMessage); outgoingMessage.onMessageSent.resolve();};
// Await while `sendMessage()` is ongoing, unless there is already a `message` listenerexport const waitForOutgoingMessages = async (anyProcess, ipcEmitter) => {export const waitForOutgoingMessages = async (anyProcess, ipcEmitter, wrappedMessage) => { while (!hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0) { const outgoingMessages = [...OUTGOING_MESSAGES.get(anyProcess)]; validateStrictDeadlock(outgoingMessages, wrappedMessage); // eslint-disable-next-line no-await-in-loop await Promise.all(OUTGOING_MESSAGES.get(anyProcess)); await Promise.all(outgoingMessages.map(({onMessageSent}) => onMessageSent)); }};
const OUTGOING_MESSAGES = new WeakMap();10 unmodified linesmodified:lib/ipc/send.js+1 added-1 removed
28 unmodified lines29303132333334353637383940414243444524 unmodified lines28 unmodified lines });};
const sendMessageAsync = async ({anyProcess, channel, isSubprocess, message, strict}) => { const outgoingMessagesState = startSendMessage(anyProcess); const sendMethod = getSendMethod(anyProcess); const wrappedMessage = handleSendStrict({ anyProcess, channel, isSubprocess, message, strict, }); const outgoingMessagesState = startSendMessage(anyProcess, wrappedMessage, strict);
try { await Promise.all([ waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),24 unmodified linesmodified:lib/ipc/strict.js+32 added-8 removed
1 import {once} from 'node:events';2 import {createDeferred} from '../utils/deferred.js';3 import {incrementMaxListeners} from '../utils/max-listeners.js';4 import {sendMessage} from './send.js';5-import {throwOnMissingStrict, throwOnStrictDisconnect} from './validation.js';5+import {throwOnMissingStrict, throwOnStrictDisconnect, throwOnStrictDeadlockError} from './validation.js';6 import {getIpcEmitter} from './forward.js';7 import {hasMessageListeners} from './outgoing.js';8 9 // When using the `strict` option, wrap the message with metadata during `sendMessage()`1 unmodified line11 if (!strict) {12 return message;13 }14 15- getIpcEmitter(anyProcess, channel, isSubprocess);16- return {id: count++, type: REQUEST_TYPE, message};15+ const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);16+ const hasListeners = hasMessageListeners(anyProcess, ipcEmitter);17+ return {18+ id: count++,19+ type: REQUEST_TYPE,20+ message,21+ hasListeners,22+ };23 };24 25 let count = 0n;26 27+// Handles when both processes are calling `sendMessage()` with `strict` at the same time.28+// If neither process is listening, this would create a deadlock. We detect it and throw.29+export const validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {30+ if (wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners) {31+ return;32+ }33+34+ for (const {id} of outgoingMessages) {35+ if (id !== undefined) {36+ STRICT_RESPONSES[id].resolve({isDeadlock: true, hasListeners: false});37+ }38+ }39+};40+41 // The other process then sends the acknowledgment back as a response42 export const handleStrictRequest = async ({wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter}) => {23- if (wrappedMessage?.type !== REQUEST_TYPE) {43+ if (wrappedMessage?.type !== REQUEST_TYPE || !anyProcess.connected) {44 return wrappedMessage;45 }46 47 const {id, message} = wrappedMessage;19 unmodified lines67 return false;68 }69 70 const {id, message: hasListeners} = wrappedMessage;51- STRICT_RESPONSES[id].resolve(hasListeners);71+ STRICT_RESPONSES[id]?.resolve({isDeadlock: false, hasListeners});72 return true;73 };74 75 // Wait for the other process to receive the message from `sendMessage()`3 unmodified lines79 }80 81 const deferred = createDeferred();82 STRICT_RESPONSES[wrappedMessage.id] = deferred;83+ const controller = new AbortController();84 85 try {65- const controller = new AbortController();66- const hasListeners = await Promise.race([86+ const {isDeadlock, hasListeners} = await Promise.race([87 deferred,88 throwOnDisconnect(anyProcess, isSubprocess, controller),89 ]);70- controller.abort();90 91+ if (isDeadlock) {92+ throwOnStrictDeadlockError(isSubprocess);93+ }94+95 if (!hasListeners) {96 throwOnMissingStrict(isSubprocess);97 }98 } finally {99+ controller.abort();100 delete STRICT_RESPONSES[wrappedMessage.id];101 }102 };103 10 unmodified linesmodified:lib/ipc/validation.js+11 added
22 unmodified lines23 export const throwOnEarlyDisconnect = isSubprocess => {24 throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25 };26 27+// When both processes use `sendMessage()` with `strict` at the same time28+export const throwOnStrictDeadlockError = isSubprocess => {29+ throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.30+This can be fixed by both sending a message and listening to incoming messages at the same time:31+32+const [receivedMessage] = await Promise.all([33+ ${getNamespaceName(isSubprocess)}getOneMessage(),34+ ${getNamespaceName(isSubprocess)}sendMessage(message, {strict: true}),35+]);`);36+};37+38 // When the other process used `strict` but the current process had I/O error calling `sendMessage()` for the response39 export const getStrictResponseError = (error, isSubprocess) => new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});40 41 // When using `strict` but the other process was not listening for messages57 unmodified linesmodified:test/fixtures/ipc-send-strict-listen.js+1 added-1 removed
1 #!/usr/bin/env node2 import {sendMessage, getOneMessage} from '../../index.js';3 import {foobarString} from '../helpers/input.js';4 5-const [message] = await Promise.race([5+const [message] = await Promise.all([6 getOneMessage(),7 sendMessage(foobarString, {strict: true}),8 ]);9 await sendMessage(message);modified:test/ipc/ipc-input.js+1 added-1 removed
45 unmodified lines46 t.true(message.includes('subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.'));47 t.true(cause.cause.message.includes('The "message" argument must be one of type string'));48 });49 50-test('Can use "ipcInput" option even if the subprocess is not listening to messages', async t => {50+test.serial('Can use "ipcInput" option even if the subprocess is not listening to messages', async t => {51 const {ipcOutput} = await execa('empty.js', {ipcInput: foobarString});52 t.deepEqual(ipcOutput, []);53 });modified:test/ipc/strict.js+14 added-7 removed
112 unmodified lines113 114 test('exports.sendMessage() "strict" fails if the current process uses once() and buffer false', async t => {115 const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}});116 const [message] = await once(subprocess, 'message');117- t.deepEqual(message, {id: 0n, type: 'execa:ipc:request', message: foobarString});117+ t.deepEqual(message, {118+ id: 0n,119+ type: 'execa:ipc:request',120+ message: foobarString,121+ hasListeners: false,122+ });123 124 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);125 t.is(exitCode, 1);126 t.false(isTerminated);67 unmodified lines194 t.deepEqual(ipcOutput, [foobarString, foobarString]);195 });196 197 test('Opposite sendMessage() "strict", current process listening, buffer false', async t => {193- const subprocess = execa('ipc-send-strict-get.js', {ipc: true, buffer: false});198+ const subprocess = execa('ipc-send-strict-get.js', {ipc: true, buffer: {ipc: false}});199 const [message] = await Promise.all([200 subprocess.getOneMessage(),201 subprocess.sendMessage(foobarString, {strict: true}),202 ]);4 unmodified lines207 t.deepEqual(ipcOutput, []);208 });209 210 test('Opposite sendMessage() "strict", subprocess listening, buffer false', async t => {206- const subprocess = execa('ipc-send-strict-listen.js', {ipc: true, buffer: false});211+ const subprocess = execa('ipc-send-strict-listen.js', {ipc: true, buffer: {ipc: false}});212 await subprocess.sendMessage(foobarString, {strict: true});213 t.is(await subprocess.getOneMessage(), foobarString);214 215 const {ipcOutput} = await subprocess;216 t.deepEqual(ipcOutput, []);217 });218 219 test('Opposite sendMessage() "strict", not listening, buffer false', async t => {215- const subprocess = execa('ipc-send-strict-get.js', {ipc: true, timeout: 1e3, buffer: false});220+ const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}});221 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));217- t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');222+ t.true(message.startsWith('subprocess.sendMessage() failed: the subprocess is sending a message too, instead of listening to incoming messages.'));223 219- const {timedOut, ipcOutput} = await t.throwsAsync(subprocess);220- t.true(timedOut);224+ const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);225+ t.is(exitCode, 1);226+ t.false(isTerminated);227+ t.true(stderr.includes('Error: sendMessage() failed: the parent process is sending a message too, instead of listening to incoming messages.'));228 t.deepEqual(ipcOutput, []);229 });