outgoing.js
This file
Path
lib/ipc/outgoing.js
53 lines · 2.4 KiB · JavaScript
Last changed by
Add `nodeChildProcess` to subprocess promises and make the subprocess a normal promise (#1255)Sindre Sorhusbefore adoptionade74bf
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import {createDeferred} from '../utils/deferred.js';import {getFdSpecificValue} from '../arguments/specific.js';import {validateStrictDeadlock} from './strict.js';
// When `sendMessage()` is ongoing, any `message` being received waits before being emitted.// This allows calling one or multiple `await sendMessage()` followed by `await getOneMessage()`/`await getEachMessage()`.// Without running into a race condition when the other process sends a response too fast, before the current process set up a listener.export const startSendMessage = (anyProcess, wrappedMessage, strict) => { if (!OUTGOING_MESSAGES.has(anyProcess)) { OUTGOING_MESSAGES.set(anyProcess, new Set()); }
const outgoingMessages = OUTGOING_MESSAGES.get(anyProcess); const onMessageSent = createDeferred(); const id = strict ? wrappedMessage.id : undefined; const outgoingMessage = {onMessageSent, id}; outgoingMessages.add(outgoingMessage); return {outgoingMessages, outgoingMessage};};
export const endSendMessage = ({outgoingMessages, outgoingMessage}) => { outgoingMessages.delete(outgoingMessage); outgoingMessage.onMessageSent.resolve();};
// Await while `sendMessage()` is ongoing, unless there is already a `message` listenerexport const waitForOutgoingMessages = async (anyProcess, ipcEmitter, wrappedMessage) => { while (!hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0) { const outgoingMessages = [...OUTGOING_MESSAGES.get(anyProcess)]; validateStrictDeadlock(outgoingMessages, wrappedMessage); // eslint-disable-next-line no-await-in-loop await Promise.all(outgoingMessages.map(({onMessageSent}) => onMessageSent)); }};
const OUTGOING_MESSAGES = new WeakMap();const IPC_SUBPROCESS_OPTIONS = new WeakMap();
export const setIpcSubprocessOptions = (subprocess, options) => { IPC_SUBPROCESS_OPTIONS.set(subprocess, options);};
// Whether any `message` listener is setupexport const hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount('message') > getMinListenerCount(anyProcess);
// When `buffer` is `false`, we set up a `message` listener that should be ignored.// That listener is only meant to intercept `strict` acknowledgement responses.const getMinListenerCount = anyProcess => getOptions(anyProcess) !== undefined && !getFdSpecificValue(getOptions(anyProcess).buffer, 'ipc') ? 1 : 0;
const getOptions = anyProcess => IPC_SUBPROCESS_OPTIONS.get(anyProcess);