ChildProcessWorker.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function _child_process() {
  7. const data = require('child_process');
  8. _child_process = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _stream() {
  14. const data = require('stream');
  15. _stream = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _mergeStream() {
  21. const data = _interopRequireDefault(require('merge-stream'));
  22. _mergeStream = function () {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function _supportsColor() {
  28. const data = require('supports-color');
  29. _supportsColor = function () {
  30. return data;
  31. };
  32. return data;
  33. }
  34. function _types() {
  35. const data = require('../types');
  36. _types = function () {
  37. return data;
  38. };
  39. return data;
  40. }
  41. function _interopRequireDefault(obj) {
  42. return obj && obj.__esModule ? obj : {default: obj};
  43. }
  44. function _defineProperty(obj, key, value) {
  45. if (key in obj) {
  46. Object.defineProperty(obj, key, {
  47. value: value,
  48. enumerable: true,
  49. configurable: true,
  50. writable: true
  51. });
  52. } else {
  53. obj[key] = value;
  54. }
  55. return obj;
  56. }
  57. const SIGNAL_BASE_EXIT_CODE = 128;
  58. const SIGKILL_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 9;
  59. const SIGTERM_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 15; // How long to wait after SIGTERM before sending SIGKILL
  60. const SIGKILL_DELAY = 500;
  61. /**
  62. * This class wraps the child process and provides a nice interface to
  63. * communicate with. It takes care of:
  64. *
  65. * - Re-spawning the process if it dies.
  66. * - Queues calls while the worker is busy.
  67. * - Re-sends the requests if the worker blew up.
  68. *
  69. * The reason for queueing them here (since childProcess.send also has an
  70. * internal queue) is because the worker could be doing asynchronous work, and
  71. * this would lead to the child process to read its receiving buffer and start a
  72. * second call. By queueing calls here, we don't send the next call to the
  73. * children until we receive the result of the previous one.
  74. *
  75. * As soon as a request starts to be processed by a worker, its "processed"
  76. * field is changed to "true", so that other workers which might encounter the
  77. * same call skip it.
  78. */
  79. class ChildProcessWorker {
  80. constructor(options) {
  81. _defineProperty(this, '_child', void 0);
  82. _defineProperty(this, '_options', void 0);
  83. _defineProperty(this, '_request', void 0);
  84. _defineProperty(this, '_retries', void 0);
  85. _defineProperty(this, '_onProcessEnd', void 0);
  86. _defineProperty(this, '_fakeStream', void 0);
  87. _defineProperty(this, '_stdout', void 0);
  88. _defineProperty(this, '_stderr', void 0);
  89. _defineProperty(this, '_exitPromise', void 0);
  90. _defineProperty(this, '_resolveExitPromise', void 0);
  91. this._options = options;
  92. this._request = null;
  93. this._fakeStream = null;
  94. this._stdout = null;
  95. this._stderr = null;
  96. this._exitPromise = new Promise(resolve => {
  97. this._resolveExitPromise = resolve;
  98. });
  99. this.initialize();
  100. }
  101. initialize() {
  102. const forceColor = _supportsColor().stdout
  103. ? {
  104. FORCE_COLOR: '1'
  105. }
  106. : {};
  107. const child = (0, _child_process().fork)(
  108. require.resolve('./processChild'),
  109. [],
  110. {
  111. cwd: process.cwd(),
  112. env: {
  113. ...process.env,
  114. JEST_WORKER_ID: String(this._options.workerId + 1),
  115. // 0-indexed workerId, 1-indexed JEST_WORKER_ID
  116. ...forceColor
  117. },
  118. // Suppress --debug / --inspect flags while preserving others (like --harmony).
  119. execArgv: process.execArgv.filter(v => !/^--(debug|inspect)/.test(v)),
  120. silent: true,
  121. ...this._options.forkOptions
  122. }
  123. );
  124. if (child.stdout) {
  125. if (!this._stdout) {
  126. // We need to add a permanent stream to the merged stream to prevent it
  127. // from ending when the subprocess stream ends
  128. this._stdout = (0, _mergeStream().default)(this._getFakeStream());
  129. }
  130. this._stdout.add(child.stdout);
  131. }
  132. if (child.stderr) {
  133. if (!this._stderr) {
  134. // We need to add a permanent stream to the merged stream to prevent it
  135. // from ending when the subprocess stream ends
  136. this._stderr = (0, _mergeStream().default)(this._getFakeStream());
  137. }
  138. this._stderr.add(child.stderr);
  139. }
  140. child.on('message', this._onMessage.bind(this));
  141. child.on('exit', this._onExit.bind(this));
  142. child.send([
  143. _types().CHILD_MESSAGE_INITIALIZE,
  144. false,
  145. this._options.workerPath,
  146. this._options.setupArgs
  147. ]);
  148. this._child = child;
  149. this._retries++; // If we exceeded the amount of retries, we will emulate an error reply
  150. // coming from the child. This avoids code duplication related with cleaning
  151. // the queue, and scheduling the next call.
  152. if (this._retries > this._options.maxRetries) {
  153. const error = new Error('Call retries were exceeded');
  154. this._onMessage([
  155. _types().PARENT_MESSAGE_CLIENT_ERROR,
  156. error.name,
  157. error.message,
  158. error.stack,
  159. {
  160. type: 'WorkerError'
  161. }
  162. ]);
  163. }
  164. }
  165. _shutdown() {
  166. // End the temporary streams so the merged streams end too
  167. if (this._fakeStream) {
  168. this._fakeStream.end();
  169. this._fakeStream = null;
  170. }
  171. this._resolveExitPromise();
  172. }
  173. _onMessage(response) {
  174. let error;
  175. switch (response[0]) {
  176. case _types().PARENT_MESSAGE_OK:
  177. this._onProcessEnd(null, response[1]);
  178. break;
  179. case _types().PARENT_MESSAGE_CLIENT_ERROR:
  180. error = response[4];
  181. if (error != null && typeof error === 'object') {
  182. const extra = error; // @ts-ignore: no index
  183. const NativeCtor = global[response[1]];
  184. const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error;
  185. error = new Ctor(response[2]);
  186. error.type = response[1];
  187. error.stack = response[3];
  188. for (const key in extra) {
  189. // @ts-ignore: adding custom properties to errors.
  190. error[key] = extra[key];
  191. }
  192. }
  193. this._onProcessEnd(error, null);
  194. break;
  195. case _types().PARENT_MESSAGE_SETUP_ERROR:
  196. error = new Error('Error when calling setup: ' + response[2]); // @ts-ignore: adding custom properties to errors.
  197. error.type = response[1];
  198. error.stack = response[3];
  199. this._onProcessEnd(error, null);
  200. break;
  201. default:
  202. throw new TypeError('Unexpected response from worker: ' + response[0]);
  203. }
  204. }
  205. _onExit(exitCode) {
  206. if (
  207. exitCode !== 0 &&
  208. exitCode !== SIGTERM_EXIT_CODE &&
  209. exitCode !== SIGKILL_EXIT_CODE
  210. ) {
  211. this.initialize();
  212. if (this._request) {
  213. this._child.send(this._request);
  214. }
  215. } else {
  216. this._shutdown();
  217. }
  218. }
  219. send(request, onProcessStart, onProcessEnd) {
  220. onProcessStart(this);
  221. this._onProcessEnd = (...args) => {
  222. // Clean the request to avoid sending past requests to workers that fail
  223. // while waiting for a new request (timers, unhandled rejections...)
  224. this._request = null;
  225. return onProcessEnd(...args);
  226. };
  227. this._request = request;
  228. this._retries = 0;
  229. this._child.send(request);
  230. }
  231. waitForExit() {
  232. return this._exitPromise;
  233. }
  234. forceExit() {
  235. this._child.kill('SIGTERM');
  236. const sigkillTimeout = setTimeout(
  237. () => this._child.kill('SIGKILL'),
  238. SIGKILL_DELAY
  239. );
  240. this._exitPromise.then(() => clearTimeout(sigkillTimeout));
  241. }
  242. getWorkerId() {
  243. return this._options.workerId;
  244. }
  245. getStdout() {
  246. return this._stdout;
  247. }
  248. getStderr() {
  249. return this._stderr;
  250. }
  251. _getFakeStream() {
  252. if (!this._fakeStream) {
  253. this._fakeStream = new (_stream().PassThrough)();
  254. }
  255. return this._fakeStream;
  256. }
  257. }
  258. exports.default = ChildProcessWorker;