All files / lib/internal/main worker_thread.js

89.89% Statements 249/277
80% Branches 24/30
100% Functions 2/2
89.89% Lines 249/277

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 27813x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 710x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x                                   13x 13x 7585x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x     710x 710x 710x 710x 710x 710x 710x 710x 710x 4x 4x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 1203x 1203x 1203x 712x 712x 712x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 710x 227x 227x 227x 227x 227x 227x 227x 227x 227x 227x 227x 227x 710x 8x 8x   8x 483x 475x 475x 475x 475x 475x 475x 7585x 2959x 2959x 2959x 2959x 6875x 3916x 3916x 3916x 3916x 3916x 3916x 3916x 13x 13x 38x 38x 38x 38x 38x 38x 38x 1x 1x 1x 37x 37x 37x 4x 4x 33x 33x 1x 1x 1x 1x     1x     1x 33x 33x 33x 33x 33x 33x     33x 33x 33x 33x 33x 33x     33x 33x 33x 33x 33x 38x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x  
'use strict';
 
// In worker threads, execute the script sent through the
// message port.
 
const {
  ArrayPrototypeForEach,
  ArrayPrototypePushApply,
  ArrayPrototypeSplice,
  ObjectDefineProperty,
  PromisePrototypeThen,
  RegExpPrototypeExec,
  globalThis: { Atomics },
} = primordials;
 
const {
  patchProcessObject,
  setupCoverageHooks,
  setupInspectorHooks,
  setupWarningHandler,
  setupFetch,
  setupWebCrypto,
  setupCustomEvent,
  setupDebugEnv,
  setupPerfHooks,
  initializeDeprecations,
  initializeWASI,
  initializeCJSLoader,
  initializeESMLoader,
  initializeFrozenIntrinsics,
  initializeReport,
  initializeSourceMapsHandlers,
  loadPreloadModules,
  setupTraceCategoryState,
  markBootstrapComplete
} = require('internal/process/pre_execution');
 
const {
  threadId,
  getEnvMessagePort
} = internalBinding('worker');
 
const workerIo = require('internal/worker/io');
const {
  messageTypes: {
    // Messages that may be received by workers
    LOAD_SCRIPT,
    // Messages that may be posted from workers
    UP_AND_RUNNING,
    ERROR_MESSAGE,
    COULD_NOT_SERIALIZE_ERROR,
    // Messages that may be either received or posted
    STDIO_PAYLOAD,
    STDIO_WANTS_MORE_DATA,
  },
  kStdioWantsMoreDataCallback
} = workerIo;
 
const {
  onGlobalUncaughtException
} = require('internal/process/execution');
 
const publicWorker = require('worker_threads');
let debug = require('internal/util/debuglog').debuglog('worker', (fn) => {
  debug = fn;
});
 
const assert = require('internal/assert');
 
patchProcessObject();
setupInspectorHooks();
setupDebugEnv();
 
setupWarningHandler();
setupFetch();
setupWebCrypto();
setupCustomEvent();
initializeSourceMapsHandlers();
 
// Since worker threads cannot switch cwd, we do not need to
// overwrite the process.env.NODE_V8_COVERAGE variable.
if (process.env.NODE_V8_COVERAGE) {
  setupCoverageHooks(process.env.NODE_V8_COVERAGE);
}
 
debug(`[${threadId}] is setting up worker child environment`);
 
// Set up the message port and start listening
const port = getEnvMessagePort();
 
// If the main thread is spawned with env NODE_CHANNEL_FD, it's probably
// spawned by our child_process module. In the work threads, mark the
// related IPC properties as unavailable.
if (process.env.NODE_CHANNEL_FD) {
  const workerThreadSetup = require('internal/process/worker_thread_only');
  ObjectDefineProperty(process, 'channel', {
    __proto__: null,
    enumerable: false,
    get: workerThreadSetup.unavailable('process.channel')
  });

  ObjectDefineProperty(process, 'connected', {
    __proto__: null,
    enumerable: false,
    get: workerThreadSetup.unavailable('process.connected')
  });

  process.send = workerThreadSetup.unavailable('process.send()');
  process.disconnect =
    workerThreadSetup.unavailable('process.disconnect()');
}
 
port.on('message', (message) => {
  if (message.type === LOAD_SCRIPT) {
    port.unref();
    const {
      argv,
      cwdCounter,
      filename,
      doEval,
      workerData,
      environmentData,
      publicPort,
      manifestSrc,
      manifestURL,
      hasStdin
    } = message;
 
    setupTraceCategoryState();
    setupPerfHooks();
    initializeReport();
    if (manifestSrc) {
      require('internal/process/policy').setup(manifestSrc, manifestURL);
    }
    initializeDeprecations();
    initializeWASI();
 
    require('internal/dns/utils').initializeDns();
 
    initializeCJSLoader();
    initializeESMLoader();
 
    if (argv !== undefined) {
      ArrayPrototypePushApply(process.argv, argv);
    }
    publicWorker.parentPort = publicPort;
    publicWorker.workerData = workerData;
 
    require('internal/worker').assignEnvironmentData(environmentData);
 
    // The counter is only passed to the workers created by the main thread, not
    // to workers created by other workers.
    let cachedCwd = '';
    let lastCounter = -1;
    const originalCwd = process.cwd;
 
    process.cwd = function() {
      const currentCounter = Atomics.load(cwdCounter, 0);
      if (currentCounter === lastCounter)
        return cachedCwd;
      lastCounter = currentCounter;
      cachedCwd = originalCwd();
      return cachedCwd;
    };
    workerIo.sharedCwdCounter = cwdCounter;
 
    const CJSLoader = require('internal/modules/cjs/loader');
    assert(!CJSLoader.hasLoadedAnyUserCJSModule);
    loadPreloadModules();
    initializeFrozenIntrinsics();
 
    if (!hasStdin)
      process.stdin.push(null);
 
    debug(`[${threadId}] starts worker script ${filename} ` +
          `(eval = ${doEval}) at cwd = ${process.cwd()}`);
    port.postMessage({ type: UP_AND_RUNNING });
    if (doEval === 'classic') {
      const { evalScript } = require('internal/process/execution');
      const name = '[worker eval]';
      // This is necessary for CJS module compilation.
      // TODO: pass this with something really internal.
      ObjectDefineProperty(process, '_eval', {
        __proto__: null,
        configurable: true,
        enumerable: true,
        value: filename,
      });
      ArrayPrototypeSplice(process.argv, 1, 0, name);
      evalScript(name, filename);
    } else if (doEval === 'module') {
      const { evalModule } = require('internal/process/execution');
      PromisePrototypeThen(evalModule(filename), undefined, (e) => {
        workerOnGlobalUncaughtException(e, true);
      });
    } else {
      // script filename
      // runMain here might be monkey-patched by users in --require.
      // XXX: the monkey-patchability here should probably be deprecated.
      ArrayPrototypeSplice(process.argv, 1, 0, filename);
      CJSLoader.Module.runMain(filename);
    }
  } else if (message.type === STDIO_PAYLOAD) {
    const { stream, chunks } = message;
    ArrayPrototypeForEach(chunks, ({ chunk, encoding }) => {
      process[stream].push(chunk, encoding);
    });
  } else {
    assert(
      message.type === STDIO_WANTS_MORE_DATA,
      `Unknown worker message type ${message.type}`
    );
    const { stream } = message;
    process[stream][kStdioWantsMoreDataCallback]();
  }
});
 
function workerOnGlobalUncaughtException(error, fromPromise) {
  debug(`[${threadId}] gets uncaught exception`);
  let handled = false;
  let handlerThrew = false;
  try {
    handled = onGlobalUncaughtException(error, fromPromise);
  } catch (e) {
    error = e;
    handlerThrew = true;
  }
  debug(`[${threadId}] uncaught exception handled = ${handled}`);
 
  if (handled) {
    return true;
  }
 
  if (!process._exiting) {
    try {
      process._exiting = true;
      process.exitCode = 1;
      if (!handlerThrew) {
        process.emit('exit', process.exitCode);
      }
    } catch {
      // Continue regardless of error.
    }
  }
 
  let serialized;
  try {
    const { serializeError } = require('internal/error_serdes');
    serialized = serializeError(error);
  } catch {
    // Continue regardless of error.
  }
  debug(`[${threadId}] uncaught exception serialized = ${!!serialized}`);
  if (serialized)
    port.postMessage({
      type: ERROR_MESSAGE,
      error: serialized
    });
  else
    port.postMessage({ type: COULD_NOT_SERIALIZE_ERROR });
 
  const { clearAsyncIdStack } = require('internal/async_hooks');
  clearAsyncIdStack();
 
  process.exit();
}
 
// Patch the global uncaught exception handler so it gets picked up by
// node::errors::TriggerUncaughtException().
process._fatalException = workerOnGlobalUncaughtException;
 
markBootstrapComplete();
 
// Necessary to reset RegExp statics before user code runs.
RegExpPrototypeExec(/^/, '');
 
port.start();