Add `reference` option to `getOneMessage()` and `getEachMessage()` (#1107)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 3b56977 · Browse files · 14 files·+133 added−23 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+133 added−23 removed
- tests:+27 added−3 removed
- other:+106 added−20 removed
Provenance
- Commit
ff02af6- Tree
ea498ee- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
3b56977
14 files changed+133 added−23 removed
modified:docs/api.md+26 added-2 removed
138 unmodified lines139 Ignore any `message` that returns `false`.140 141 [More info.](ipc.md#filter-messages)142 143-### getEachMessage()143+#### getOneMessageOptions.reference144 145+_Type_: `boolean`\146+_Default_: `true`147+148+Keep the subprocess alive while `getOneMessage()` is waiting.149+150+[More info.](ipc.md#keeping-the-subprocess-alive)151+152+### getEachMessage(getEachMessageOptions?)153+154+`getEachMessageOptions`: [`GetEachMessageOptions`](#geteachmessageoptions)\155 _Returns_: [`AsyncIterable<Message>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)156 157 Iterate over each `message` from the parent process.158 159 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.160 161 [More info.](ipc.md#listening-to-messages)162 163+#### getEachMessageOptions164+165+_Type_: `object`166+167+#### getEachMessageOptions.reference168+169+_Type_: `boolean`\170+_Default_: `true`171+172+Keep the subprocess alive while `getEachMessage()` is waiting.173+174+[More info.](ipc.md#keeping-the-subprocess-alive)175+176 ## Return value177 178 _TypeScript:_ [`ResultPromise`](typescript.md)\179 _Type:_ `Promise<object> | Subprocess`140 unmodified lines320 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.321 322 [More info.](ipc.md#exchanging-messages)323 301-### subprocess.getEachMessage()324+### subprocess.getEachMessage(getEachMessageOptions?)325 326+`getEachMessageOptions`: [`GetEachMessageOptions`](#geteachmessageoptions)\327 _Returns_: [`AsyncIterable<Message>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)328 329 Iterate over each `message` from the subprocess.330 829 unmodified linesmodified:docs/ipc.md+17 added
194 unmodified lines195 sendMessage('third'),196 ]);197 ```198 199+## Keeping the subprocess alive200+201+By default, the subprocess is kept alive as long as [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) or [`getEachMessage()`](api.md#geteachmessagegeteachmessageoptions) is waiting. This is recommended if you're sure the current process will send a message, as this prevents the subprocess from exiting too early.202+203+However, if you don't know whether a message will be sent, this can leave the subprocess hanging forever. In that case, the [`reference: false`](api.md#geteachmessageoptionsreference) option can be set.204+205+```js206+import {getEachMessage} from 'execa';207+208+// {type: 'gracefulExit'} is sometimes received, but not always209+for await (const message of getEachMessage()) {210+ if (message.type === 'gracefulExit') {211+ gracefulExit({reference: false});212+ }213+}214+```215+216 ## Debugging217 218 When the [`verbose`](api.md#optionsverbose) option is `'full'`, the IPC messages sent by the subprocess to the current process are [printed on the console](debugging.md#full-mode).219 7 unmodified linesmodified:lib/ipc/buffer-messages.js+1 added
23 unmodified lines24252627282930313214 unmodified lines23 unmodified lines channel: subprocess.channel, isSubprocess: false, ipc, shouldAwait: false, reference: true, })) { if (buffer) { checkIpcMaxBuffer(subprocess, ipcOutput, maxBuffer); ipcOutput.push(message);14 unmodified linesmodified:lib/ipc/get-each.js+7 added-5 removed
2 unmodified lines345677891011121314151616171819202122232424252627282910 unmodified lines40414243444546474810 unmodified lines59606162616364656667686970717271737475767712 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, channel, isSubprocess, ipc}) => loopOnMessages({export const getEachMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true} = {}) => loopOnMessages({ anyProcess, channel, isSubprocess, ipc, shouldAwait: !isSubprocess, reference,});
// Same but used internallyexport const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait}) => {export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference}) => { validateIpcMethod({ methodName: 'getEachMessage', isSubprocess, ipc, isConnected: isConnected(anyProcess), });
addReference(channel); addReference(channel, reference); const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess); const controller = new AbortController(); const state = {}; stopOnDisconnect(anyProcess, ipcEmitter, controller);10 unmodified lines isSubprocess, shouldAwait, controller, state, reference, });};
const stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {10 unmodified lines controller.abort(); } catch {}};
const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state}) {const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference}) { try { for await (const [message] of on(ipcEmitter, 'message', {signal: controller.signal})) { throwIfStrictError(state); yield message; } } catch { throwIfStrictError(state); } finally { controller.abort(); removeReference(channel); removeReference(channel, reference);
if (!isSubprocess) { disconnect(anyProcess); }12 unmodified linesmodified:lib/ipc/get-one.js+5 added-4 removed
7 unmodified lines8 import {getIpcEmitter, isConnected} from './forward.js';9 import {addReference, removeReference} from './reference.js';10 11 // Like `[sub]process.once('message')` but promise-based12-export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {filter} = {}) => {12+export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true, filter} = {}) => {13 validateIpcMethod({14 methodName: 'getOneMessage',15 isSubprocess,16 ipc,4 unmodified lines21 anyProcess,22 channel,23 isSubprocess,24 filter,25+ reference,26 });27 };28 28-const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter}) => {29- addReference(channel);29+const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter, reference}) => {30+ addReference(channel, reference);31 const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);32 const controller = new AbortController();33 try {34 return await Promise.race([5 unmodified lines40 disconnect(anyProcess);41 throw error;42 } finally {43 controller.abort();43- removeReference(channel);44+ removeReference(channel, reference);45 }46 };47 48 const getMessage = async (ipcEmitter, filter, {signal}) => {21 unmodified linesmodified:lib/ipc/reference.js+18 added-6 removed
3 unmodified lines4567889101112131415161712181920212223242526272829303132212233343536373839402930414243443 unmodified lines// This is not a problem with `sendMessage()` since Node.js handles that method automatically.// We do not use `anyProcess.channel.ref()` since this would prevent the automatic `.channel.refCounted()` Node.js is doing.// We keep a reference to `anyProcess.channel` since it might be `null` while `getOneMessage()` or `getEachMessage()` is still processing debounced messages.// See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L547export const addReference = channel => {export const addReference = (channel, reference) => { if (reference) { addReferenceCount(channel); }};
const addReferenceCount = channel => { channel.refCounted();};
export const removeReference = channel => {export const removeReference = (channel, reference) => { if (reference) { removeReferenceCount(channel); }};
const removeReferenceCount = channel => { channel.unrefCounted();};
// To proxy events, we setup some global listeners on the `message` and `disconnect` events.// Those should not keep the subprocess alive, so we remove the automatic counting that Node.js is doing.// See https://github.com/nodejs/node/blob/1b965270a9c273d4cf70e8808e9d28b9ada7844f/lib/child_process.js#L180export const undoAddedReferences = (channel, isSubprocess) => { if (isSubprocess) { removeReference(channel); removeReference(channel); removeReferenceCount(channel); removeReferenceCount(channel); }};
// Reverse it during `disconnect`export const redoAddedReferences = (channel, isSubprocess) => { if (isSubprocess) { addReference(channel); addReference(channel); addReferenceCount(channel); addReferenceCount(channel); }};added:test/fixtures/ipc-get-ref.js+4 added
1234#!/usr/bin/env nodeimport {getOneMessage} from '../../index.js';
getOneMessage();added:test/fixtures/ipc-get-unref.js+4 added
1234#!/usr/bin/env nodeimport {getOneMessage} from '../../index.js';
getOneMessage({reference: false});added:test/fixtures/ipc-iterate-ref.js+4 added
1+#!/usr/bin/env node2+import {getEachMessage} from '../../index.js';3+4+getEachMessage();added:test/fixtures/ipc-iterate-unref.js+4 added
1+#!/usr/bin/env node2+import {getEachMessage} from '../../index.js';3+4+getEachMessage({reference: false});modified:test/ipc/reference.js+11 added-3 removed
4 unmodified lines5 import {PARALLEL_COUNT} from '../helpers/parallel.js';6 7 setFixtureDirectory();8 9-const testKeepAliveSubprocess = async (t, fixtureName) => {9+const testReference = async (t, fixtureName) => {10 const {timedOut} = await t.throwsAsync(execa(fixtureName, {ipc: true, timeout: 1e3}));11 t.true(timedOut);12 };13 14-test('exports.getOneMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-echo.js');15-test('exports.getEachMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-iterate.js');14+test('exports.getOneMessage() keeps the subprocess alive', testReference, 'ipc-get-ref.js');15+test('exports.getEachMessage() keeps the subprocess alive', testReference, 'ipc-iterate-ref.js');16 17+const testUnreference = async (t, fixtureName) => {18+ const {ipcOutput} = await execa(fixtureName, {ipc: true});19+ t.deepEqual(ipcOutput, []);20+};21+22+test('exports.getOneMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-get-unref.js');23+test('exports.getEachMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-iterate-unref.js');24+25 test('exports.sendMessage() keeps the subprocess alive', async t => {26 const {ipcOutput} = await execa('ipc-send-repeat.js', [`${PARALLEL_COUNT}`], {ipc: true});27 const expectedOutput = Array.from({length: PARALLEL_COUNT}, (_, index) => index);28 t.deepEqual(ipcOutput, expectedOutput);101 unmodified linesmodified:test-d/ipc/get-each.test-d.ts+4 added
33 unmodified lines34 expectType<undefined>(execa('test', {ipc: false}).getEachMessage);35 expectType<undefined>(execa('test', {ipcInput: undefined}).getEachMessage);36 expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getEachMessage);37 38+subprocess.getEachMessage({reference: true} as const);39+getEachMessage({reference: true} as const);40+expectError(subprocess.getEachMessage({reference: 'true'} as const));41+expectError(getEachMessage({reference: 'true'} as const));modified:test-d/ipc/get-one.test-d.ts+7 added-1 removed
39 unmodified lines40 expectError(await subprocess.getOneMessage({filter(message: Message<'advanced'>) {}} as const));41 expectError(await subprocess.getOneMessage({filter: (message: Message<'json'>) => true} as const));42 expectError(await subprocess.getOneMessage({filter: (message: '') => true} as const));43 expectError(await subprocess.getOneMessage({filter: true} as const));44-expectError(await subprocess.getOneMessage({unknownOption: true} as const));44 45 await getOneMessage({filter: undefined} as const);46 await getOneMessage({filter: (message: Message) => true} as const);47 await getOneMessage({filter: (message: Message<'advanced'>) => true} as const);4 unmodified lines52 expectError(await getOneMessage({filter(message: Message) {}} as const));53 expectError(await getOneMessage({filter: (message: Message<'json'>) => true} as const));54 expectError(await getOneMessage({filter: (message: '') => true} as const));55 expectError(await getOneMessage({filter: true} as const));56+57+expectError(await subprocess.getOneMessage({unknownOption: true} as const));58 expectError(await getOneMessage({unknownOption: true} as const));59+60+await subprocess.getOneMessage({reference: true} as const);61+await getOneMessage({reference: true} as const);62+expectError(await subprocess.getOneMessage({reference: 'true'} as const));63+expectError(await getOneMessage({reference: 'true'} as const));modified:types/ipc.d.ts+21 added-2 removed
54 unmodified lines55 /**56 Ignore any `message` that returns `false`.57 */58 readonly filter?: (message: Message<Serialization>) => boolean;59+60+ /**61+ Keep the subprocess alive while `getOneMessage()` is waiting.62+63+ @default true64+ */65+ readonly reference?: boolean;66 };67 68 /**69 Receive a single `message` from the parent process.2 unmodified lines72 */73 export function getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;74 75 /**76+Options to `getEachMessage()` and `subprocess.getEachMessage()`77+*/78+type GetEachMessageOptions = {79+ /**80+ Keep the subprocess alive while `getEachMessage()` is waiting.81+82+ @default true83+ */84+ readonly reference?: boolean;85+};86+87+/**88 Iterate over each `message` from the parent process.89 90 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.91 */73-export function getEachMessage(): AsyncIterableIterator<Message>;92+export function getEachMessage(getEachMessageOptions?: GetEachMessageOptions): AsyncIterableIterator<Message>;93 94 // IPC methods in the current process95 export type IpcMethods<96 IpcEnabled extends boolean,18 unmodified lines115 Iterate over each `message` from the subprocess.116 117 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.118 */100- getEachMessage(): AsyncIterableIterator<Message<Serialization>>;119+ getEachMessage(getEachMessageOptions?: GetEachMessageOptions): AsyncIterableIterator<Message<Serialization>>;120 }121 // Those methods only work if the `ipc` option is `true`.122 // At runtime, they are actually defined, in order to provide with a nice error message.123 // At type check time, they are typed as `undefined` to prevent calling them.22 unmodified lines