Refactor reference counting with IPC (#1089)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 97b17e6 · Browse files · 10 files·+96 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+96 added−31 removed
- tests:+26 added−0 removed
- other:+70 added−31 removed
Provenance
- Commit
18e607c- Tree
215451e- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
97b17e6
10 files changed+96 added−31 removed
modified:lib/ipc/buffer-messages.js+1 added
23 unmodified lines24252627282930313212 unmodified lines23 unmodified lines }
for await (const message of loopOnMessages({ anyProcess: subprocess, channel: subprocess.channel, isSubprocess: false, ipc, shouldAwait: false, })) {12 unmodified linesmodified:lib/ipc/forward.js+15 added-5 removed
3 unmodified lines4567889101112131415161718181920212223242526272829303127323334303135363738394041424344455 unmodified lines3 unmodified lines
// Forward the `message` and `disconnect` events from the process and subprocess to a proxy emitter.// This prevents the `error` event from stopping IPC.// This also allows debouncing the `message` event.export const getIpcEmitter = (anyProcess, isSubprocess) => {export const getIpcEmitter = (anyProcess, channel, isSubprocess) => { if (IPC_EMITTERS.has(anyProcess)) { return IPC_EMITTERS.get(anyProcess); }
// Use an `EventEmitter`, like the `process` that is being proxied // eslint-disable-next-line unicorn/prefer-event-target const ipcEmitter = new EventEmitter(); ipcEmitter.connected = true; IPC_EMITTERS.set(anyProcess, ipcEmitter); forwardEvents(ipcEmitter, anyProcess, isSubprocess); forwardEvents({ ipcEmitter, anyProcess, channel, isSubprocess, }); return ipcEmitter;};
const IPC_EMITTERS = new WeakMap();
// The `message` and `disconnect` events are buffered in the subprocess until the first listener is setup.// However, unbuffering happens after one tick, so this give enough time for the caller to setup the listener on the proxy emitter first.// See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L721const forwardEvents = (ipcEmitter, anyProcess, isSubprocess) => {const forwardEvents = ({ipcEmitter, anyProcess, channel, isSubprocess}) => { const boundOnMessage = onMessage.bind(undefined, anyProcess, ipcEmitter); anyProcess.on('message', boundOnMessage); anyProcess.once('disconnect', onDisconnect.bind(undefined, {anyProcess, ipcEmitter, boundOnMessage})); undoAddedReferences(anyProcess, isSubprocess); anyProcess.once('disconnect', onDisconnect.bind(undefined, { anyProcess, channel, ipcEmitter, boundOnMessage, })); undoAddedReferences(channel, isSubprocess);};
// Check whether there might still be some `message` events to receiveexport const isConnected = anyProcess => {5 unmodified linesmodified:lib/ipc/get-each.js+8 added-6 removed
2 unmodified lines34567789101112131415151617181920212223232424252627282930313233346 unmodified lines4142434443454647484950515052535455566 unmodified lines2 unmodified linesimport {getIpcEmitter, isConnected} from './forward.js';import {addReference, removeReference} from './reference.js';
// Like `[sub]process.on('message')` but promise-basedexport const getEachMessage = ({anyProcess, isSubprocess, ipc}) => loopOnMessages({export const getEachMessage = ({anyProcess, channel, isSubprocess, ipc}) => loopOnMessages({ anyProcess, channel, isSubprocess, ipc, shouldAwait: !isSubprocess,});
// Same but used internallyexport const loopOnMessages = ({anyProcess, isSubprocess, ipc, shouldAwait}) => {export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait}) => { validateIpcMethod({ methodName: 'getEachMessage', isSubprocess, ipc, isConnected: isConnected(anyProcess), });
addReference(anyProcess); const ipcEmitter = getIpcEmitter(anyProcess, isSubprocess); addReference(channel); const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess); const controller = new AbortController(); stopOnDisconnect(anyProcess, ipcEmitter, controller); return iterateOnMessages({ anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller,6 unmodified lines controller.abort(); } catch {}};
const iterateOnMessages = async function * ({anyProcess, ipcEmitter, isSubprocess, shouldAwait, controller}) {const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller}) { try { for await (const [message] of on(ipcEmitter, 'message', {signal: controller.signal})) { yield message; } } catch {} finally { controller.abort(); removeReference(anyProcess); removeReference(channel);
if (!isSubprocess) { disconnect(anyProcess); }6 unmodified linesmodified:lib/ipc/get-one.js+11 added-6 removed
2 unmodified lines3 import {getIpcEmitter, isConnected} from './forward.js';4 import {addReference, removeReference} from './reference.js';5 6 // Like `[sub]process.once('message')` but promise-based7-export const getOneMessage = ({anyProcess, isSubprocess, ipc}, {filter} = {}) => {7+export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {filter} = {}) => {8 validateIpcMethod({9 methodName: 'getOneMessage',10 isSubprocess,11 ipc,12 isConnected: isConnected(anyProcess),13 });14 15- return getOneMessageAsync(anyProcess, isSubprocess, filter);15+ return getOneMessageAsync({16+ anyProcess,17+ channel,18+ isSubprocess,19+ filter,20+ });21 };22 18-const getOneMessageAsync = async (anyProcess, isSubprocess, filter) => {19- addReference(anyProcess);20- const ipcEmitter = getIpcEmitter(anyProcess, isSubprocess);23+const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter}) => {24+ addReference(channel);25+ const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);26 const controller = new AbortController();27 try {28 return await Promise.race([29 getMessage(ipcEmitter, filter, controller),30 throwOnDisconnect(ipcEmitter, isSubprocess, controller),31 ]);32 } finally {33 controller.abort();29- removeReference(anyProcess);34+ removeReference(channel);35 }36 };37 38 const getMessage = async (ipcEmitter, filter, {signal}) => {16 unmodified linesmodified:lib/ipc/incoming.js+3 added-1 removed
1234567819 unmodified lines2829303131323334353637383940414243import {once} from 'node:events';import {scheduler} from 'node:timers/promises';import {waitForOutgoingMessages} from './outgoing.js';import {redoAddedReferences} from './reference.js';
// Debounce the `message` event so it is emitted at most once per macrotask.// This allows users to call `await getOneMessage()`/`getEachMessage()` multiple times in a row.export const onMessage = async (anyProcess, ipcEmitter, message) => {19 unmodified lines
const INCOMING_MESSAGES = new WeakMap();
// If the `message` event is currently debounced, the `disconnect` event must wait for itexport const onDisconnect = async ({anyProcess, ipcEmitter, boundOnMessage}) => {export const onDisconnect = async ({anyProcess, channel, ipcEmitter, boundOnMessage}) => { const incomingMessages = INCOMING_MESSAGES.get(anyProcess); while (incomingMessages?.length > 0) { // eslint-disable-next-line no-await-in-loop await once(ipcEmitter, 'message'); }
anyProcess.removeListener('message', boundOnMessage); redoAddedReferences(channel); ipcEmitter.connected = false; ipcEmitter.emit('disconnect');};modified:lib/ipc/methods.js+13 added-2 removed
15 unmodified lines16 const getIpcMethods = (anyProcess, isSubprocess, ipc) => {17 const anyProcessSend = anyProcess.send === undefined18 ? undefined19 : promisify(anyProcess.send.bind(anyProcess));20+ const {channel} = anyProcess;21 return {22 sendMessage: sendMessage.bind(undefined, {23 anyProcess,24 anyProcessSend,25 isSubprocess,26 ipc,27 }),27- getOneMessage: getOneMessage.bind(undefined, {anyProcess, isSubprocess, ipc}),28- getEachMessage: getEachMessage.bind(undefined, {anyProcess, isSubprocess, ipc}),28+ getOneMessage: getOneMessage.bind(undefined, {29+ anyProcess,30+ channel,31+ isSubprocess,32+ ipc,33+ }),34+ getEachMessage: getEachMessage.bind(undefined, {35+ anyProcess,36+ channel,37+ isSubprocess,38+ ipc,39+ }),40 };41 };modified:lib/ipc/reference.js+19 added-8 removed
1 // By default, Node.js keeps the subprocess alive while it has a `message` or `disconnect` listener.2 // We replicate the same logic for the events that we proxy.3-// This ensures the subprocess is kept alive while `sendMessage()`, `getOneMessage()` and `getEachMessage()` are ongoing.3+// This ensures the subprocess is kept alive while `getOneMessage()` and `getEachMessage()` are ongoing.4+// This is not a problem with `sendMessage()` since Node.js handles that method automatically.5+// We do not use `anyProcess.channel.ref()` since this would prevent the automatic `.channel.refCounted()` Node.js is doing.6+// We keep a reference to `anyProcess.channel` since it might be `null` while `getOneMessage()` or `getEachMessage()` is still processing debounced messages.7 // See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L5475-export const addReference = anyProcess => {6- anyProcess.channel?.refCounted();8+export const addReference = channel => {9+ channel.refCounted();10 };11 9-export const removeReference = anyProcess => {10- anyProcess.channel?.unrefCounted();12+export const removeReference = channel => {13+ channel.unrefCounted();14 };15 16 // To proxy events, we setup some global listeners on the `message` and `disconnect` events.17 // Those should not keep the subprocess alive, so we remove the automatic counting that Node.js is doing.18 // See https://github.com/nodejs/node/blob/1b965270a9c273d4cf70e8808e9d28b9ada7844f/lib/child_process.js#L18016-export const undoAddedReferences = (anyProcess, isSubprocess) => {19+export const undoAddedReferences = (channel, isSubprocess) => {20 if (isSubprocess) {18- removeReference(anyProcess);19- removeReference(anyProcess);21+ removeReference(channel);22+ removeReference(channel);23 }24 };25+26+// Reverse it during `disconnect`27+export const redoAddedReferences = (channel, isSubprocess) => {28+ if (isSubprocess) {29+ addReference(channel);30+ addReference(channel);31+ }32+};modified:lib/ipc/send.js-3 removed
3 unmodified lines4 handleSerializationError,5 disconnect,6 } from './validation.js';7 import {startSendMessage, endSendMessage} from './outgoing.js';8-import {addReference, removeReference} from './reference.js';8 9 // Like `[sub]process.send()` but promise-based.10 // We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.11 // Users would still need to `await subprocess` after the method is done.14 unmodified lines26 });27 };28 29 const sendMessageAsync = async ({anyProcess, anyProcessSend, isSubprocess, message}) => {31- addReference(anyProcess);30 const outgoingMessagesState = startSendMessage(anyProcess);31 try {32 await anyProcessSend(message);33 } catch (error) {2 unmodified lines36 handleSerializationError(error, isSubprocess, message);37 throw error;38 } finally {39 endSendMessage(outgoingMessagesState);42- removeReference(anyProcess);40 }41 };added:test/fixtures/ipc-disconnect-get.js+7 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getOneMessage} from '../../index.js';4+5+process.disconnect();6+console.log(process.channel);7+await getOneMessage();modified:test/ipc/reference.js+19 added
98 unmodified lines99 const {ipcOutput, stdout} = await subprocess;100 t.deepEqual(ipcOutput, ['.']);101 t.is(stdout, '.');102 });103+104+test('Can call subprocess.disconnect() right away', async t => {105+ const subprocess = execa('ipc-send.js', {ipc: true});106+ subprocess.disconnect();107+ t.is(subprocess.channel, null);108+109+ await t.throwsAsync(subprocess.getOneMessage(), {110+ message: /subprocess.getOneMessage\(\) could not complete/,111+ });112+ await t.throwsAsync(subprocess, {113+ message: /Error: sendMessage\(\) cannot be used/,114+ });115+});116+117+test('Can call process.disconnect() right away', async t => {118+ const {stdout, stderr} = await t.throwsAsync(execa('ipc-disconnect-get.js', {ipc: true}));119+ t.is(stdout, 'null');120+ t.true(stderr.includes('Error: getOneMessage() cannot be used'));121+});