outgoing.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import {createDeferred} from '../utils/deferred.js';
  2. import {getFdSpecificValue} from '../arguments/specific.js';
  3. import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';
  4. import {validateStrictDeadlock} from './strict.js';
  5. // When `sendMessage()` is ongoing, any `message` being received waits before being emitted.
  6. // This allows calling one or multiple `await sendMessage()` followed by `await getOneMessage()`/`await getEachMessage()`.
  7. // Without running into a race condition when the other process sends a response too fast, before the current process set up a listener.
  8. export const startSendMessage = (anyProcess, wrappedMessage, strict) => {
  9. if (!OUTGOING_MESSAGES.has(anyProcess)) {
  10. OUTGOING_MESSAGES.set(anyProcess, new Set());
  11. }
  12. const outgoingMessages = OUTGOING_MESSAGES.get(anyProcess);
  13. const onMessageSent = createDeferred();
  14. const id = strict ? wrappedMessage.id : undefined;
  15. const outgoingMessage = {onMessageSent, id};
  16. outgoingMessages.add(outgoingMessage);
  17. return {outgoingMessages, outgoingMessage};
  18. };
  19. export const endSendMessage = ({outgoingMessages, outgoingMessage}) => {
  20. outgoingMessages.delete(outgoingMessage);
  21. outgoingMessage.onMessageSent.resolve();
  22. };
  23. // Await while `sendMessage()` is ongoing, unless there is already a `message` listener
  24. export const waitForOutgoingMessages = async (anyProcess, ipcEmitter, wrappedMessage) => {
  25. while (!hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0) {
  26. const outgoingMessages = [...OUTGOING_MESSAGES.get(anyProcess)];
  27. validateStrictDeadlock(outgoingMessages, wrappedMessage);
  28. // eslint-disable-next-line no-await-in-loop
  29. await Promise.all(outgoingMessages.map(({onMessageSent}) => onMessageSent));
  30. }
  31. };
  32. const OUTGOING_MESSAGES = new WeakMap();
  33. // Whether any `message` listener is setup
  34. export const hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount('message') > getMinListenerCount(anyProcess);
  35. // When `buffer` is `false`, we set up a `message` listener that should be ignored.
  36. // That listener is only meant to intercept `strict` acknowledgement responses.
  37. const getMinListenerCount = anyProcess => SUBPROCESS_OPTIONS.has(anyProcess)
  38. && !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, 'ipc')
  39. ? 1
  40. : 0;