All files / lib/internal worker.js

99.21% Statements 505/509
97.2% Branches 139/143
100% Functions 21/21
99.21% Lines 505/509

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 182x 118x 118x 118x 118x 118x 118x 118x 104x 104x 104x 374x 374x 104x 104x 118x 5x 5x 5x 3x 3x 5x 118x 13x 13x 13x 118x 782x 782x 779x 6x 779x 782x 118x 118x 118x 1054x 1054x 1054x 1054x 1052x 1052x 1054x 5x 5x 5x 1051x 1051x 1054x 470x 1x 1x 1x 1x 1x 1x 469x 469x 1054x 7x 7x 7x 581x 574x 574x 3x 3x 574x 8x 8x 8x 8x 8x 571x 563x 556x 556x 563x 7x 7x 574x 1034x 1034x 1054x 26x 26x 26x 26x 26x 1037x 1006x 1007x 1x 1x 1x 1x 1x 1033x 1033x 1033x 1054x 1054x 1054x 1054x 1054x 3x 3x 1032x 1x 1x 1x 1029x 1000x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1031x 1029x 1029x 990x 990x 990x 1029x 1029x 1005x 1005x 1005x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1031x 6x 1029x 1029x 1029x 2058x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 1054x 118x 118x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 224x 224x 224x 224x 999x 999x 1000x 118x 118x 1x 1x 118x 118x 47x 47x 47x 47x 118x 118x 6851x 6851x 786x 786x 6851x 1x 6851x 47x 6851x 3070x 3070x 3070x 3070x 3079x 3070x 3070x 3070x 6851x 2946x 2946x 2946x 2946x 6851x 1x 1x 6851x 118x 118x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 1000x 118x 118x 11077x 11076x 11076x 11077x 118x 118x 456x 456x 456x 456x 456x 2x 2x 2x 2x 2x 1x 1x 455x 455x 454x 454x 454x 454x 454x 454x 454x 454x 454x 456x 118x 118x 461x 458x 458x 458x 461x 118x 118x 8x 7x 7x 7x 8x 118x 118x 4487x 2486x 2486x 4487x 118x 118x 3x 3x 118x 118x 45x 45x 118x 118x 4x 4x 118x 118x 2x 1x 1x 2x 118x 118x 2x 2x 2x 1x 1x 1x 1x 2x 2x 118x 118x 1995x 1995x 1995x 1995x 1995x 1995x 1995x 1995x 1995x 1995x 1995x 118x 118x 1033x 1033x 1033x 1033x 8x 8x 10x 8x 10x 8x 10x 8x 8x 8x 1033x 118x 780x 780x 780x 780x 780x 780x 780x 780x 118x 8x 8x 8x 8x 8x 8x 1x 1x 7x 7x 8x 1x 1x 1x 1x 7x 8x         7x 7x 7x 7x 7x 7x 7x 7x 7x 8x 3x 3x 4x 4x 4x 4x 4x 8x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x  
'use strict';
 
const {
  ArrayPrototypeForEach,
  ArrayPrototypeMap,
  ArrayPrototypePush,
  Float64Array,
  FunctionPrototypeBind,
  JSONStringify,
  MathMax,
  ObjectCreate,
  ObjectEntries,
  Promise,
  PromiseResolve,
  ReflectApply,
  RegExpPrototypeTest,
  SafeArrayIterator,
  SafeMap,
  String,
  Symbol,
  SymbolFor,
  TypedArrayPrototypeFill,
  Uint32Array,
  globalThis: { Atomics, SharedArrayBuffer },
} = primordials;
 
const EventEmitter = require('events');
const assert = require('internal/assert');
const path = require('path');
const { now } = require('internal/perf/utils');
 
const errorCodes = require('internal/errors').codes;
const {
  ERR_WORKER_NOT_RUNNING,
  ERR_WORKER_PATH,
  ERR_WORKER_UNSERIALIZABLE_ERROR,
  ERR_WORKER_INVALID_EXEC_ARGV,
  ERR_INVALID_ARG_TYPE,
  ERR_INVALID_ARG_VALUE,
} = errorCodes;
const { getOptionValue } = require('internal/options');
 
const workerIo = require('internal/worker/io');
const {
  drainMessagePort,
  MessageChannel,
  messageTypes,
  kPort,
  kIncrementsPortRef,
  kWaitingStreams,
  kStdioWantsMoreDataCallback,
  setupPortReferencing,
  ReadableWorkerStdio,
  WritableWorkerStdio
} = workerIo;
const { deserializeError } = require('internal/error_serdes');
const { fileURLToPath, isURLInstance, pathToFileURL } = require('internal/url');
const { validateArray } = require('internal/validators');
 
const {
  ownsProcessState,
  isMainThread,
  resourceLimits: resourceLimitsRaw,
  threadId,
  Worker: WorkerImpl,
  kMaxYoungGenerationSizeMb,
  kMaxOldGenerationSizeMb,
  kCodeRangeSizeMb,
  kStackSizeMb,
  kTotalResourceLimitCount
} = internalBinding('worker');
 
const kHandle = Symbol('kHandle');
const kPublicPort = Symbol('kPublicPort');
const kDispose = Symbol('kDispose');
const kOnExit = Symbol('kOnExit');
const kOnMessage = Symbol('kOnMessage');
const kOnCouldNotSerializeErr = Symbol('kOnCouldNotSerializeErr');
const kOnErrorMessage = Symbol('kOnErrorMessage');
const kParentSideStdio = Symbol('kParentSideStdio');
const kLoopStartTime = Symbol('kLoopStartTime');
const kIsOnline = Symbol('kIsOnline');
 
const SHARE_ENV = SymbolFor('nodejs.worker_threads.SHARE_ENV');
let debug = require('internal/util/debuglog').debuglog('worker', (fn) => {
  debug = fn;
});
 
let cwdCounter;
 
const environmentData = new SafeMap();
 
if (isMainThread) {
  cwdCounter = new Uint32Array(new SharedArrayBuffer(4));
  const originalChdir = process.chdir;
  process.chdir = function(path) {
    Atomics.add(cwdCounter, 0, 1);
    originalChdir(path);
  };
}
 
function setEnvironmentData(key, value) {
  if (value === undefined)
    environmentData.delete(key);
  else
    environmentData.set(key, value);
}
 
function getEnvironmentData(key) {
  return environmentData.get(key);
}
 
function assignEnvironmentData(data) {
  if (data === undefined) return;
  data.forEach((value, key) => {
    environmentData.set(key, value);
  });
}
 
class Worker extends EventEmitter {
  constructor(filename, options = {}) {
    super();
    debug(`[${threadId}] create new worker`, filename, options);
    if (options.execArgv)
      validateArray(options.execArgv, 'options.execArgv');
 
    let argv;
    if (options.argv) {
      validateArray(options.argv, 'options.argv');
      argv = ArrayPrototypeMap(options.argv, String);
    }
 
    let url, doEval;
    if (options.eval) {
      if (typeof filename !== 'string') {
        throw new ERR_INVALID_ARG_VALUE(
          'options.eval',
          options.eval,
          'must be false when \'filename\' is not a string'
        );
      }
      url = null;
      doEval = 'classic';
    } else if (isURLInstance(filename) && filename.protocol === 'data:') {
      url = null;
      doEval = 'module';
      filename = `import ${JSONStringify(`${filename}`)}`;
    } else {
      doEval = false;
      if (isURLInstance(filename)) {
        url = filename;
        filename = fileURLToPath(filename);
      } else if (typeof filename !== 'string') {
        throw new ERR_INVALID_ARG_TYPE(
          'filename',
          ['string', 'URL'],
          filename
        );
      } else if (path.isAbsolute(filename) ||
                 RegExpPrototypeTest(/^\.\.?[\\/]/, filename)) {
        filename = path.resolve(filename);
        url = pathToFileURL(filename);
      } else {
        throw new ERR_WORKER_PATH(filename);
      }
    }
 
    let env;
    if (typeof options.env === 'object' && options.env !== null) {
      env = ObjectCreate(null);
      ArrayPrototypeForEach(
        ObjectEntries(options.env),
        ({ 0: key, 1: value }) => { env[key] = `${value}`; }
      );
    } else if (options.env == null) {
      env = process.env;
    } else if (options.env !== SHARE_ENV) {
      throw new ERR_INVALID_ARG_TYPE(
        'options.env',
        ['object', 'undefined', 'null', 'worker_threads.SHARE_ENV'],
        options.env);
    }
 
    // Set up the C++ handle for the worker, as well as some internal wiring.
    this[kHandle] = new WorkerImpl(url,
                                   env === process.env ? null : env,
                                   options.execArgv,
                                   parseResourceLimits(options.resourceLimits),
                                   !!(options.trackUnmanagedFds ?? true));
    if (this[kHandle].invalidExecArgv) {
      throw new ERR_WORKER_INVALID_EXEC_ARGV(this[kHandle].invalidExecArgv);
    }
    if (this[kHandle].invalidNodeOptions) {
      throw new ERR_WORKER_INVALID_EXEC_ARGV(
        this[kHandle].invalidNodeOptions, 'invalid NODE_OPTIONS env variable');
    }
    this[kHandle].onexit = (code, customErr, customErrReason) => {
      this[kOnExit](code, customErr, customErrReason);
    };
    this[kPort] = this[kHandle].messagePort;
    this[kPort].on('message', (data) => this[kOnMessage](data));
    this[kPort].start();
    this[kPort].unref();
    this[kPort][kWaitingStreams] = 0;
    debug(`[${threadId}] created Worker with ID ${this.threadId}`);
 
    let stdin = null;
    if (options.stdin)
      stdin = new WritableWorkerStdio(this[kPort], 'stdin');
    const stdout = new ReadableWorkerStdio(this[kPort], 'stdout');
    if (!options.stdout) {
      stdout[kIncrementsPortRef] = false;
      pipeWithoutWarning(stdout, process.stdout);
    }
    const stderr = new ReadableWorkerStdio(this[kPort], 'stderr');
    if (!options.stderr) {
      stderr[kIncrementsPortRef] = false;
      pipeWithoutWarning(stderr, process.stderr);
    }
 
    this[kParentSideStdio] = { stdin, stdout, stderr };
 
    const { port1, port2 } = new MessageChannel();
    const transferList = [port2];
    // If transferList is provided.
    if (options.transferList)
      ArrayPrototypePush(transferList,
                         ...new SafeArrayIterator(options.transferList));
 
    this[kPublicPort] = port1;
    ArrayPrototypeForEach(['message', 'messageerror'], (event) => {
      this[kPublicPort].on(event, (message) => this.emit(event, message));
    });
    setupPortReferencing(this[kPublicPort], this, 'message');
    this[kPort].postMessage({
      argv,
      type: messageTypes.LOAD_SCRIPT,
      filename,
      doEval,
      cwdCounter: cwdCounter || workerIo.sharedCwdCounter,
      workerData: options.workerData,
      environmentData,
      publicPort: port2,
      manifestURL: getOptionValue('--experimental-policy') ?
        require('internal/process/policy').url :
        null,
      manifestSrc: getOptionValue('--experimental-policy') ?
        require('internal/process/policy').src :
        null,
      hasStdin: !!options.stdin
    }, transferList);
    // Use this to cache the Worker's loopStart value once available.
    this[kLoopStartTime] = -1;
    this[kIsOnline] = false;
    this.performance = {
      eventLoopUtilization: FunctionPrototypeBind(eventLoopUtilization, this),
    };
    // Actually start the new thread now that everything is in place.
    this[kHandle].startThread();
 
    process.nextTick(() => process.emit('worker', this));
  }
 
  [kOnExit](code, customErr, customErrReason) {
    debug(`[${threadId}] hears end event for Worker ${this.threadId}`);
    drainMessagePort(this[kPublicPort]);
    drainMessagePort(this[kPort]);
    this.removeAllListeners('message');
    this.removeAllListeners('messageerrors');
    this[kPublicPort].unref();
    this[kPort].unref();
    this[kDispose]();
    if (customErr) {
      debug(`[${threadId}] failing with custom error ${customErr} \
        and with reason ${customErrReason}`);
      this.emit('error', new errorCodes[customErr](customErrReason));
    }
    this.emit('exit', code);
    this.removeAllListeners();
  }
 
  [kOnCouldNotSerializeErr]() {
    this.emit('error', new ERR_WORKER_UNSERIALIZABLE_ERROR());
  }
 
  [kOnErrorMessage](serialized) {
    // This is what is called for uncaught exceptions.
    const error = deserializeError(serialized);
    this.emit('error', error);
  }
 
  [kOnMessage](message) {
    switch (message.type) {
      case messageTypes.UP_AND_RUNNING:
        this[kIsOnline] = true;
        return this.emit('online');
      case messageTypes.COULD_NOT_SERIALIZE_ERROR:
        return this[kOnCouldNotSerializeErr]();
      case messageTypes.ERROR_MESSAGE:
        return this[kOnErrorMessage](message.error);
      case messageTypes.STDIO_PAYLOAD:
      {
        const { stream, chunks } = message;
        const readable = this[kParentSideStdio][stream];
        ArrayPrototypeForEach(chunks, ({ chunk, encoding }) => {
          readable.push(chunk, encoding);
        });
        return;
      }
      case messageTypes.STDIO_WANTS_MORE_DATA:
      {
        const { stream } = message;
        return this[kParentSideStdio][stream][kStdioWantsMoreDataCallback]();
      }
    }
 
    assert.fail(`Unknown worker message type ${message.type}`);
  }
 
  [kDispose]() {
    this[kHandle].onexit = null;
    this[kHandle] = null;
    this[kPort] = null;
    this[kPublicPort] = null;
 
    const { stdout, stderr } = this[kParentSideStdio];
 
    if (!stdout.readableEnded) {
      debug(`[${threadId}] explicitly closes stdout for ${this.threadId}`);
      stdout.push(null);
    }
    if (!stderr.readableEnded) {
      debug(`[${threadId}] explicitly closes stderr for ${this.threadId}`);
      stderr.push(null);
    }
  }
 
  postMessage(...args) {
    if (this[kPublicPort] === null) return;
 
    ReflectApply(this[kPublicPort].postMessage, this[kPublicPort], args);
  }
 
  terminate(callback) {
    debug(`[${threadId}] terminates Worker with ID ${this.threadId}`);
 
    this.ref();
 
    if (typeof callback === 'function') {
      process.emitWarning(
        'Passing a callback to worker.terminate() is deprecated. ' +
        'It returns a Promise instead.',
        'DeprecationWarning', 'DEP0132');
      if (this[kHandle] === null) return PromiseResolve();
      this.once('exit', (exitCode) => callback(null, exitCode));
    }
 
    if (this[kHandle] === null) return PromiseResolve();
 
    this[kHandle].stopThread();
 
    // Do not use events.once() here, because the 'exit' event will always be
    // emitted regardless of any errors, and the point is to only resolve
    // once the thread has actually stopped.
    return new Promise((resolve) => {
      this.once('exit', resolve);
    });
  }
 
  ref() {
    if (this[kHandle] === null) return;
 
    this[kHandle].ref();
    this[kPublicPort].ref();
  }
 
  unref() {
    if (this[kHandle] === null) return;
 
    this[kHandle].unref();
    this[kPublicPort].unref();
  }
 
  get threadId() {
    if (this[kHandle] === null) return -1;
 
    return this[kHandle].threadId;
  }
 
  get stdin() {
    return this[kParentSideStdio].stdin;
  }
 
  get stdout() {
    return this[kParentSideStdio].stdout;
  }
 
  get stderr() {
    return this[kParentSideStdio].stderr;
  }
 
  get resourceLimits() {
    if (this[kHandle] === null) return {};
 
    return makeResourceLimits(this[kHandle].getResourceLimits());
  }
 
  getHeapSnapshot() {
    const heapSnapshotTaker = this[kHandle] && this[kHandle].takeHeapSnapshot();
    return new Promise((resolve, reject) => {
      if (!heapSnapshotTaker) return reject(new ERR_WORKER_NOT_RUNNING());
      heapSnapshotTaker.ondone = (handle) => {
        const { HeapSnapshotStream } = require('internal/heap_utils');
        resolve(new HeapSnapshotStream(handle));
      };
    });
  }
}
 
function pipeWithoutWarning(source, dest) {
  const sourceMaxListeners = source._maxListeners;
  const destMaxListeners = dest._maxListeners;
  source.setMaxListeners(Infinity);
  dest.setMaxListeners(Infinity);
 
  source.pipe(dest);
 
  source._maxListeners = sourceMaxListeners;
  dest._maxListeners = destMaxListeners;
}
 
const resourceLimitsArray = new Float64Array(kTotalResourceLimitCount);
function parseResourceLimits(obj) {
  const ret = resourceLimitsArray;
  TypedArrayPrototypeFill(ret, -1);
  if (typeof obj !== 'object' || obj === null) return ret;
 
  if (typeof obj.maxOldGenerationSizeMb === 'number')
    ret[kMaxOldGenerationSizeMb] = MathMax(obj.maxOldGenerationSizeMb, 2);
  if (typeof obj.maxYoungGenerationSizeMb === 'number')
    ret[kMaxYoungGenerationSizeMb] = obj.maxYoungGenerationSizeMb;
  if (typeof obj.codeRangeSizeMb === 'number')
    ret[kCodeRangeSizeMb] = obj.codeRangeSizeMb;
  if (typeof obj.stackSizeMb === 'number')
    ret[kStackSizeMb] = obj.stackSizeMb;
  return ret;
}
 
function makeResourceLimits(float64arr) {
  return {
    maxYoungGenerationSizeMb: float64arr[kMaxYoungGenerationSizeMb],
    maxOldGenerationSizeMb: float64arr[kMaxOldGenerationSizeMb],
    codeRangeSizeMb: float64arr[kCodeRangeSizeMb],
    stackSizeMb: float64arr[kStackSizeMb]
  };
}
 
function eventLoopUtilization(util1, util2) {
  // TODO(trevnorris): Works to solve the thread-safe read/write issue of
  // loopTime, but has the drawback that it can't be set until the event loop
  // has had a chance to turn. So it will be impossible to read the ELU of
  // a worker thread immediately after it's been created.
  if (!this[kIsOnline] || !this[kHandle]) {
    return { idle: 0, active: 0, utilization: 0 };
  }
 
  // Cache loopStart, since it's only written to once.
  if (this[kLoopStartTime] === -1) {
    this[kLoopStartTime] = this[kHandle].loopStartTime();
    if (this[kLoopStartTime] === -1)
      return { idle: 0, active: 0, utilization: 0 };
  }
 
  if (util2) {
    const idle = util1.idle - util2.idle;
    const active = util1.active - util2.active;
    return { idle, active, utilization: active / (idle + active) };
  }
 
  const idle = this[kHandle].loopIdleTime();
 
  // Using performance.now() here is fine since it's always the time from
  // the beginning of the process, and is why it needs to be offset by the
  // loopStart time (which is also calculated from the beginning of the
  // process).
  const active = now() - this[kLoopStartTime] - idle;
 
  if (!util1) {
    return { idle, active, utilization: active / (idle + active) };
  }
 
  const idle_delta = idle - util1.idle;
  const active_delta = active - util1.active;
  const utilization = active_delta / (idle_delta + active_delta);
  return { idle: idle_delta, active: active_delta, utilization };
}
 
module.exports = {
  ownsProcessState,
  isMainThread,
  SHARE_ENV,
  resourceLimits:
    !isMainThread ? makeResourceLimits(resourceLimitsRaw) : {},
  setEnvironmentData,
  getEnvironmentData,
  assignEnvironmentData,
  threadId,
  Worker,
};