Skip to content
Myr

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

10 files+96 added−31 removed

modified:lib/ipc/buffer-messages.js+1 added
modified:lib/ipc/forward.js+15 added-5 removed
modified:lib/ipc/get-each.js+8 added-6 removed
modified:lib/ipc/get-one.js+11 added-6 removed
2 unmodified lines
3import {getIpcEmitter, isConnected} from './forward.js';4import {addReference, removeReference} from './reference.js';56// Like `[sub]process.once('message')` but promise-based7export const getOneMessage = ({anyProcess, isSubprocess, ipc}, {filter} = {}) => {7export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {filter} = {}) => {8 validateIpcMethod({9 methodName: 'getOneMessage',10 isSubprocess,11 ipc,12 isConnected: isConnected(anyProcess),13 });1415 return getOneMessageAsync(anyProcess, isSubprocess, filter);15 return getOneMessageAsync({16 anyProcess,17 channel,18 isSubprocess,19 filter,20 });21};2218const getOneMessageAsync = async (anyProcess, isSubprocess, filter) => {19 addReference(anyProcess);20 const ipcEmitter = getIpcEmitter(anyProcess, isSubprocess);23const 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};3738const getMessage = async (ipcEmitter, filter, {signal}) => {
16 unmodified lines
modified:lib/ipc/incoming.js+3 added-1 removed
modified:lib/ipc/methods.js+13 added-2 removed
15 unmodified lines
16const 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#L5475export const addReference = anyProcess => {6 anyProcess.channel?.refCounted();8export const addReference = channel => {9 channel.refCounted();10};119export const removeReference = anyProcess => {10 anyProcess.channel?.unrefCounted();12export const removeReference = channel => {13 channel.unrefCounted();14};1516// 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#L18016export const undoAddedReferences = (anyProcess, isSubprocess) => {19export const undoAddedReferences = (channel, isSubprocess) => {20 if (isSubprocess) {18 removeReference(anyProcess);19 removeReference(anyProcess);21 removeReference(channel);22 removeReference(channel);23 }24};2526// Reverse it during `disconnect`27export const redoAddedReferences = (channel, isSubprocess) => {28 if (isSubprocess) {29 addReference(channel);30 addReference(channel);31 }32};
modified:lib/ipc/send.js-3 removed
3 unmodified lines
4 handleSerializationError,5 disconnect,6} from './validation.js';7import {startSendMessage, endSendMessage} from './outgoing.js';8import {addReference, removeReference} from './reference.js';89// 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 lines
26 });27};2829const 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 lines
36 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 node2import process from 'node:process';3import {getOneMessage} from '../../index.js';45process.disconnect();6console.log(process.channel);7await getOneMessage();
modified:test/ipc/reference.js+19 added
98 unmodified lines
99 const {ipcOutput, stdout} = await subprocess;100 t.deepEqual(ipcOutput, ['.']);101 t.is(stdout, '.');102});103104test('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);108109 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});116117test('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});