Skip to content
Myr

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

14 files+133 added−23 removed

modified:docs/api.md+26 added-2 removed
138 unmodified lines
139Ignore any `message` that returns `false`.140141[More info.](ipc.md#filter-messages)142143### getEachMessage()143#### getOneMessageOptions.reference144145_Type_: `boolean`\146_Default_: `true`147148Keep the subprocess alive while `getOneMessage()` is waiting.149150[More info.](ipc.md#keeping-the-subprocess-alive)151152### getEachMessage(getEachMessageOptions?)153154`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)156157Iterate over each `message` from the parent process.158159This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.160161[More info.](ipc.md#listening-to-messages)162163#### getEachMessageOptions164165_Type_: `object`166167#### getEachMessageOptions.reference168169_Type_: `boolean`\170_Default_: `true`171172Keep the subprocess alive while `getEachMessage()` is waiting.173174[More info.](ipc.md#keeping-the-subprocess-alive)175176## Return value177178_TypeScript:_ [`ResultPromise`](typescript.md)\179_Type:_ `Promise<object> | Subprocess`
140 unmodified lines
320This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.321322[More info.](ipc.md#exchanging-messages)323301### subprocess.getEachMessage()324### subprocess.getEachMessage(getEachMessageOptions?)325326`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)328329Iterate over each `message` from the subprocess.330
829 unmodified lines
modified:docs/ipc.md+17 added
194 unmodified lines
195 sendMessage('third'),196]);197```198199## Keeping the subprocess alive200201By 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.202203However, 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.204205```js206import {getEachMessage} from 'execa';207208// {type: 'gracefulExit'} is sometimes received, but not always209for await (const message of getEachMessage()) {210 if (message.type === 'gracefulExit') {211 gracefulExit({reference: false});212 }213}214```215216## Debugging217218When 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 lines
modified:lib/ipc/buffer-messages.js+1 added
modified:lib/ipc/get-each.js+7 added-5 removed
modified:lib/ipc/get-one.js+5 added-4 removed
7 unmodified lines
8import {getIpcEmitter, isConnected} from './forward.js';9import {addReference, removeReference} from './reference.js';1011// Like `[sub]process.once('message')` but promise-based12export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {filter} = {}) => {12export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true, filter} = {}) => {13 validateIpcMethod({14 methodName: 'getOneMessage',15 isSubprocess,16 ipc,
4 unmodified lines
21 anyProcess,22 channel,23 isSubprocess,24 filter,25 reference,26 });27};2828const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter}) => {29 addReference(channel);29const 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 lines
40 disconnect(anyProcess);41 throw error;42 } finally {43 controller.abort();43 removeReference(channel);44 removeReference(channel, reference);45 }46};4748const getMessage = async (ipcEmitter, filter, {signal}) => {
21 unmodified lines
modified:lib/ipc/reference.js+18 added-6 removed
added:test/fixtures/ipc-get-ref.js+4 added
added:test/fixtures/ipc-get-unref.js+4 added
added:test/fixtures/ipc-iterate-ref.js+4 added
1#!/usr/bin/env node2import {getEachMessage} from '../../index.js';34getEachMessage();
added:test/fixtures/ipc-iterate-unref.js+4 added
1#!/usr/bin/env node2import {getEachMessage} from '../../index.js';34getEachMessage({reference: false});
modified:test/ipc/reference.js+11 added-3 removed
4 unmodified lines
5import {PARALLEL_COUNT} from '../helpers/parallel.js';67setFixtureDirectory();89const testKeepAliveSubprocess = async (t, fixtureName) => {9const testReference = async (t, fixtureName) => {10 const {timedOut} = await t.throwsAsync(execa(fixtureName, {ipc: true, timeout: 1e3}));11 t.true(timedOut);12};1314test('exports.getOneMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-echo.js');15test('exports.getEachMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-iterate.js');14test('exports.getOneMessage() keeps the subprocess alive', testReference, 'ipc-get-ref.js');15test('exports.getEachMessage() keeps the subprocess alive', testReference, 'ipc-iterate-ref.js');1617const testUnreference = async (t, fixtureName) => {18 const {ipcOutput} = await execa(fixtureName, {ipc: true});19 t.deepEqual(ipcOutput, []);20};2122test('exports.getOneMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-get-unref.js');23test('exports.getEachMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-iterate-unref.js');2425test('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 lines
modified:test-d/ipc/get-each.test-d.ts+4 added
33 unmodified lines
34expectType<undefined>(execa('test', {ipc: false}).getEachMessage);35expectType<undefined>(execa('test', {ipcInput: undefined}).getEachMessage);36expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getEachMessage);3738subprocess.getEachMessage({reference: true} as const);39getEachMessage({reference: true} as const);40expectError(subprocess.getEachMessage({reference: 'true'} as const));41expectError(getEachMessage({reference: 'true'} as const));
modified:test-d/ipc/get-one.test-d.ts+7 added-1 removed
39 unmodified lines
40expectError(await subprocess.getOneMessage({filter(message: Message<'advanced'>) {}} as const));41expectError(await subprocess.getOneMessage({filter: (message: Message<'json'>) => true} as const));42expectError(await subprocess.getOneMessage({filter: (message: '') => true} as const));43expectError(await subprocess.getOneMessage({filter: true} as const));44expectError(await subprocess.getOneMessage({unknownOption: true} as const));4445await getOneMessage({filter: undefined} as const);46await getOneMessage({filter: (message: Message) => true} as const);47await getOneMessage({filter: (message: Message<'advanced'>) => true} as const);
4 unmodified lines
52expectError(await getOneMessage({filter(message: Message) {}} as const));53expectError(await getOneMessage({filter: (message: Message<'json'>) => true} as const));54expectError(await getOneMessage({filter: (message: '') => true} as const));55expectError(await getOneMessage({filter: true} as const));5657expectError(await subprocess.getOneMessage({unknownOption: true} as const));58expectError(await getOneMessage({unknownOption: true} as const));5960await subprocess.getOneMessage({reference: true} as const);61await getOneMessage({reference: true} as const);62expectError(await subprocess.getOneMessage({reference: 'true'} as const));63expectError(await getOneMessage({reference: 'true'} as const));
modified:types/ipc.d.ts+21 added-2 removed
54 unmodified lines
55 /**56 Ignore any `message` that returns `false`.57 */58 readonly filter?: (message: Message<Serialization>) => boolean;5960 /**61 Keep the subprocess alive while `getOneMessage()` is waiting.6263 @default true64 */65 readonly reference?: boolean;66};6768/**69Receive a single `message` from the parent process.
2 unmodified lines
72*/73export function getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;7475/**76Options to `getEachMessage()` and `subprocess.getEachMessage()`77*/78type GetEachMessageOptions = {79 /**80 Keep the subprocess alive while `getEachMessage()` is waiting.8182 @default true83 */84 readonly reference?: boolean;85};8687/**88Iterate over each `message` from the parent process.8990This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.91*/73export function getEachMessage(): AsyncIterableIterator<Message>;92export function getEachMessage(getEachMessageOptions?: GetEachMessageOptions): AsyncIterableIterator<Message>;9394// IPC methods in the current process95export type IpcMethods<96 IpcEnabled extends boolean,
18 unmodified lines
115 Iterate over each `message` from the subprocess.116117 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