summaryrefslogtreecommitdiff
path: root/lib/internal/main/worker_thread.js
blob: f290a4acb29a79b918274adca98cb4741b702e63 (plain)
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
'use strict';

// In worker threads, execute the script sent through the
// message port.

const { Object } = primordials;

const {
  patchProcessObject,
  setupCoverageHooks,
  setupInspectorHooks,
  setupWarningHandler,
  setupDebugEnv,
  initializeDeprecations,
  initializeESMLoader,
  initializeFrozenIntrinsics,
  initializeReport,
  loadPreloadModules,
  setupTraceCategoryState
} = require('internal/bootstrap/pre_execution');

const {
  threadId,
  getEnvMessagePort
} = internalBinding('worker');

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
} = require('internal/worker/io');

const {
  fatalException: originalFatalException
} = require('internal/process/execution');

const publicWorker = require('worker_threads');

patchProcessObject();
setupInspectorHooks();
setupDebugEnv();

const debug = require('internal/util/debuglog').debuglog('worker');

setupWarningHandler();

// 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');
  Object.defineProperty(process, 'channel', {
    enumerable: false,
    get: workerThreadSetup.unavailable('process.channel')
  });

  Object.defineProperty(process, 'connected', {
    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) {
    const {
      filename,
      doEval,
      workerData,
      publicPort,
      manifestSrc,
      manifestURL,
      hasStdin
    } = message;

    setupTraceCategoryState();
    initializeReport();
    if (manifestSrc) {
      require('internal/process/policy').setup(manifestSrc, manifestURL);
    }
    initializeDeprecations();
    initializeFrozenIntrinsics();
    initializeESMLoader();
    loadPreloadModules();
    publicWorker.parentPort = publicPort;
    publicWorker.workerData = workerData;

    if (!hasStdin)
      process.stdin.push(null);

    debug(`[${threadId}] starts worker script ${filename} ` +
          `(eval = ${eval}) at cwd = ${process.cwd()}`);
    port.unref();
    port.postMessage({ type: UP_AND_RUNNING });
    if (doEval) {
      const { evalScript } = require('internal/process/execution');
      evalScript('[worker eval]', filename);
    } else {
      process.argv[1] = filename; // script filename
      require('module').runMain();
    }
    return;
  } else if (message.type === STDIO_PAYLOAD) {
    const { stream, chunk, encoding } = message;
    process[stream].push(chunk, encoding);
    return;
  } else if (message.type === STDIO_WANTS_MORE_DATA) {
    const { stream } = message;
    process[stream][kStdioWantsMoreDataCallback]();
    return;
  }

  require('assert').fail(`Unknown worker message type ${message.type}`);
});

// Overwrite fatalException
process._fatalException = (error, fromPromise) => {
  debug(`[${threadId}] gets fatal exception`);
  let caught = false;
  try {
    caught = originalFatalException.call(this, error, fromPromise);
  } catch (e) {
    error = e;
  }
  debug(`[${threadId}] fatal exception caught = ${caught}`);

  if (!caught) {
    let serialized;
    try {
      const { serializeError } = require('internal/error-serdes');
      serialized = serializeError(error);
    } catch {}
    debug(`[${threadId}] fatal 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();
  }
};

markBootstrapComplete();

port.start();