11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst {
41cb0ef41Sopenharmony_ci  ReflectApply,
51cb0ef41Sopenharmony_ci  SafeMap,
61cb0ef41Sopenharmony_ci} = primordials;
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_cimodule.exports = {
91cb0ef41Sopenharmony_ci  sendHelper,
101cb0ef41Sopenharmony_ci  internal,
111cb0ef41Sopenharmony_ci};
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ciconst callbacks = new SafeMap();
141cb0ef41Sopenharmony_cilet seq = 0;
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_cifunction sendHelper(proc, message, handle, cb) {
171cb0ef41Sopenharmony_ci  if (!proc.connected)
181cb0ef41Sopenharmony_ci    return false;
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_ci  // Mark message as internal. See INTERNAL_PREFIX
211cb0ef41Sopenharmony_ci  // in lib/internal/child_process.js
221cb0ef41Sopenharmony_ci  message = { cmd: 'NODE_CLUSTER', ...message, seq };
231cb0ef41Sopenharmony_ci
241cb0ef41Sopenharmony_ci  if (typeof cb === 'function')
251cb0ef41Sopenharmony_ci    callbacks.set(seq, cb);
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_ci  seq += 1;
281cb0ef41Sopenharmony_ci  return proc.send(message, handle);
291cb0ef41Sopenharmony_ci}
301cb0ef41Sopenharmony_ci
311cb0ef41Sopenharmony_ci// Returns an internalMessage listener that hands off normal messages
321cb0ef41Sopenharmony_ci// to the callback but intercepts and redirects ACK messages.
331cb0ef41Sopenharmony_cifunction internal(worker, cb) {
341cb0ef41Sopenharmony_ci  return function onInternalMessage(message, handle) {
351cb0ef41Sopenharmony_ci    if (message.cmd !== 'NODE_CLUSTER')
361cb0ef41Sopenharmony_ci      return;
371cb0ef41Sopenharmony_ci
381cb0ef41Sopenharmony_ci    let fn = cb;
391cb0ef41Sopenharmony_ci
401cb0ef41Sopenharmony_ci    if (message.ack !== undefined) {
411cb0ef41Sopenharmony_ci      const callback = callbacks.get(message.ack);
421cb0ef41Sopenharmony_ci
431cb0ef41Sopenharmony_ci      if (callback !== undefined) {
441cb0ef41Sopenharmony_ci        fn = callback;
451cb0ef41Sopenharmony_ci        callbacks.delete(message.ack);
461cb0ef41Sopenharmony_ci      }
471cb0ef41Sopenharmony_ci    }
481cb0ef41Sopenharmony_ci
491cb0ef41Sopenharmony_ci    ReflectApply(fn, worker, arguments);
501cb0ef41Sopenharmony_ci  };
511cb0ef41Sopenharmony_ci}
52