UNPKG

3.73 kBJavaScriptView Raw
1'use strict';
2
3function _worker_threads() {
4 const data = require('worker_threads');
5
6 _worker_threads = function () {
7 return data;
8 };
9
10 return data;
11}
12
13var _types = require('../types');
14
15/**
16 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
17 *
18 * This source code is licensed under the MIT license found in the
19 * LICENSE file in the root directory of this source tree.
20 */
21let file = null;
22let setupArgs = [];
23let initialized = false;
24/**
25 * This file is a small bootstrapper for workers. It sets up the communication
26 * between the worker and the parent process, interpreting parent messages and
27 * sending results back.
28 *
29 * The file loaded will be lazily initialized the first time any of the workers
30 * is called. This is done for optimal performance: if the farm is initialized,
31 * but no call is made to it, child Node processes will be consuming the least
32 * possible amount of memory.
33 *
34 * If an invalid message is detected, the child will exit (by throwing) with a
35 * non-zero exit code.
36 */
37
38const messageListener = request => {
39 switch (request[0]) {
40 case _types.CHILD_MESSAGE_INITIALIZE:
41 const init = request;
42 file = init[2];
43 setupArgs = request[3];
44 process.env.JEST_WORKER_ID = request[4];
45 break;
46
47 case _types.CHILD_MESSAGE_CALL:
48 const call = request;
49 execMethod(call[2], call[3]);
50 break;
51
52 case _types.CHILD_MESSAGE_END:
53 end();
54 break;
55
56 default:
57 throw new TypeError(
58 `Unexpected request from parent process: ${request[0]}`
59 );
60 }
61};
62
63_worker_threads().parentPort.on('message', messageListener);
64
65function reportSuccess(result) {
66 if (_worker_threads().isMainThread) {
67 throw new Error('Child can only be used on a forked process');
68 }
69
70 _worker_threads().parentPort.postMessage([_types.PARENT_MESSAGE_OK, result]);
71}
72
73function reportClientError(error) {
74 return reportError(error, _types.PARENT_MESSAGE_CLIENT_ERROR);
75}
76
77function reportInitializeError(error) {
78 return reportError(error, _types.PARENT_MESSAGE_SETUP_ERROR);
79}
80
81function reportError(error, type) {
82 if (_worker_threads().isMainThread) {
83 throw new Error('Child can only be used on a forked process');
84 }
85
86 if (error == null) {
87 error = new Error('"null" or "undefined" thrown');
88 }
89
90 _worker_threads().parentPort.postMessage([
91 type,
92 error.constructor && error.constructor.name,
93 error.message,
94 error.stack,
95 typeof error === 'object' ? {...error} : error
96 ]);
97}
98
99function end() {
100 const main = require(file);
101
102 if (!main.teardown) {
103 exitProcess();
104 return;
105 }
106
107 execFunction(main.teardown, main, [], exitProcess, exitProcess);
108}
109
110function exitProcess() {
111 // Clean up open handles so the worker ideally exits gracefully
112 _worker_threads().parentPort.removeListener('message', messageListener);
113}
114
115function execMethod(method, args) {
116 const main = require(file);
117
118 let fn;
119
120 if (method === 'default') {
121 fn = main.__esModule ? main['default'] : main;
122 } else {
123 fn = main[method];
124 }
125
126 function execHelper() {
127 execFunction(fn, main, args, reportSuccess, reportClientError);
128 }
129
130 if (initialized || !main.setup) {
131 execHelper();
132 return;
133 }
134
135 initialized = true;
136 execFunction(main.setup, main, setupArgs, execHelper, reportInitializeError);
137}
138
139const isPromise = obj =>
140 !!obj &&
141 (typeof obj === 'object' || typeof obj === 'function') &&
142 typeof obj.then === 'function';
143
144function execFunction(fn, ctx, args, onResult, onError) {
145 let result;
146
147 try {
148 result = fn.apply(ctx, args);
149 } catch (err) {
150 onError(err);
151 return;
152 }
153
154 if (isPromise(result)) {
155 result.then(onResult, onError);
156 } else {
157 onResult(result);
158 }
159}