Skip to content
Myr

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

8 files+74 added−27 removed

modified:lib/ipc/incoming.js+1 added-1 removed
modified:lib/ipc/outgoing.js+13 added-8 removed
modified:lib/ipc/send.js+1 added-1 removed
modified:lib/ipc/strict.js+32 added-8 removed
1import {once} from 'node:events';2import {createDeferred} from '../utils/deferred.js';3import {incrementMaxListeners} from '../utils/max-listeners.js';4import {sendMessage} from './send.js';5import {throwOnMissingStrict, throwOnStrictDisconnect} from './validation.js';5import {throwOnMissingStrict, throwOnStrictDisconnect, throwOnStrictDeadlockError} from './validation.js';6import {getIpcEmitter} from './forward.js';7import {hasMessageListeners} from './outgoing.js';89// When using the `strict` option, wrap the message with metadata during `sendMessage()`
1 unmodified line
11 if (!strict) {12 return message;13 }1415 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};2425let count = 0n;2627// 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.29export const validateStrictDeadlock = (outgoingMessages, wrappedMessage) => {30 if (wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners) {31 return;32 }3334 for (const {id} of outgoingMessages) {35 if (id !== undefined) {36 STRICT_RESPONSES[id].resolve({isDeadlock: true, hasListeners: false});37 }38 }39};4041// The other process then sends the acknowledgment back as a response42export 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 }4647 const {id, message} = wrappedMessage;
19 unmodified lines
67 return false;68 }6970 const {id, message: hasListeners} = wrappedMessage;51 STRICT_RESPONSES[id].resolve(hasListeners);71 STRICT_RESPONSES[id]?.resolve({isDeadlock: false, hasListeners});72 return true;73};7475// Wait for the other process to receive the message from `sendMessage()`
3 unmodified lines
79 }8081 const deferred = createDeferred();82 STRICT_RESPONSES[wrappedMessage.id] = deferred;83 const controller = new AbortController();8485 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();9091 if (isDeadlock) {92 throwOnStrictDeadlockError(isSubprocess);93 }9495 if (!hasListeners) {96 throwOnMissingStrict(isSubprocess);97 }98 } finally {99 controller.abort();100 delete STRICT_RESPONSES[wrappedMessage.id];101 }102};103
10 unmodified lines
modified:lib/ipc/validation.js+11 added
22 unmodified lines
23export const throwOnEarlyDisconnect = isSubprocess => {24 throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25};2627// When both processes use `sendMessage()` with `strict` at the same time28export 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.30This can be fixed by both sending a message and listening to incoming messages at the same time:3132const [receivedMessage] = await Promise.all([33 ${getNamespaceName(isSubprocess)}getOneMessage(),34 ${getNamespaceName(isSubprocess)}sendMessage(message, {strict: true}),35]);`);36};3738// When the other process used `strict` but the current process had I/O error calling `sendMessage()` for the response39export const getStrictResponseError = (error, isSubprocess) => new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});4041// When using `strict` but the other process was not listening for messages
57 unmodified lines
modified:test/fixtures/ipc-send-strict-listen.js+1 added-1 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45const [message] = await Promise.race([5const [message] = await Promise.all([6 getOneMessage(),7 sendMessage(foobarString, {strict: true}),8]);9await sendMessage(message);
modified:test/ipc/ipc-input.js+1 added-1 removed
45 unmodified lines
46 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});4950test('Can use "ipcInput" option even if the subprocess is not listening to messages', async t => {50test.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 lines
113114test('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 });123124 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);125 t.is(exitCode, 1);126 t.false(isTerminated);
67 unmodified lines
194 t.deepEqual(ipcOutput, [foobarString, foobarString]);195});196197test('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 lines
207 t.deepEqual(ipcOutput, []);208});209210test('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);214215 const {ipcOutput} = await subprocess;216 t.deepEqual(ipcOutput, []);217});218219test('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.'));223219 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});