11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst { SafeMap } = primordials;
31cb0ef41Sopenharmony_ciconst assert = require('internal/assert');
41cb0ef41Sopenharmony_ciconst dgram = require('internal/dgram');
51cb0ef41Sopenharmony_ciconst net = require('net');
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_cimodule.exports = SharedHandle;
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_cifunction SharedHandle(key, address, { port, addressType, fd, flags }) {
101cb0ef41Sopenharmony_ci  this.key = key;
111cb0ef41Sopenharmony_ci  this.workers = new SafeMap();
121cb0ef41Sopenharmony_ci  this.handle = null;
131cb0ef41Sopenharmony_ci  this.errno = 0;
141cb0ef41Sopenharmony_ci
151cb0ef41Sopenharmony_ci  let rval;
161cb0ef41Sopenharmony_ci  if (addressType === 'udp4' || addressType === 'udp6')
171cb0ef41Sopenharmony_ci    rval = dgram._createSocketHandle(address, port, addressType, fd, flags);
181cb0ef41Sopenharmony_ci  else
191cb0ef41Sopenharmony_ci    rval = net._createServerHandle(address, port, addressType, fd, flags);
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_ci  if (typeof rval === 'number')
221cb0ef41Sopenharmony_ci    this.errno = rval;
231cb0ef41Sopenharmony_ci  else
241cb0ef41Sopenharmony_ci    this.handle = rval;
251cb0ef41Sopenharmony_ci}
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_ciSharedHandle.prototype.add = function(worker, send) {
281cb0ef41Sopenharmony_ci  assert(!this.workers.has(worker.id));
291cb0ef41Sopenharmony_ci  this.workers.set(worker.id, worker);
301cb0ef41Sopenharmony_ci  send(this.errno, null, this.handle);
311cb0ef41Sopenharmony_ci};
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ciSharedHandle.prototype.remove = function(worker) {
341cb0ef41Sopenharmony_ci  if (!this.workers.has(worker.id))
351cb0ef41Sopenharmony_ci    return false;
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_ci  this.workers.delete(worker.id);
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_ci  if (this.workers.size !== 0)
401cb0ef41Sopenharmony_ci    return false;
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_ci  this.handle.close();
431cb0ef41Sopenharmony_ci  this.handle = null;
441cb0ef41Sopenharmony_ci  return true;
451cb0ef41Sopenharmony_ci};
46