NodeThreadsWorker.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function path() {
  7. const data = _interopRequireWildcard(require('path'));
  8. path = 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 _worker_threads() {
  21. const data = require('worker_threads');
  22. _worker_threads = function () {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function _mergeStream() {
  28. const data = _interopRequireDefault(require('merge-stream'));
  29. _mergeStream = 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 _getRequireWildcardCache() {
  45. if (typeof WeakMap !== 'function') return null;
  46. var cache = new WeakMap();
  47. _getRequireWildcardCache = function () {
  48. return cache;
  49. };
  50. return cache;
  51. }
  52. function _interopRequireWildcard(obj) {
  53. if (obj && obj.__esModule) {
  54. return obj;
  55. }
  56. if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
  57. return {default: obj};
  58. }
  59. var cache = _getRequireWildcardCache();
  60. if (cache && cache.has(obj)) {
  61. return cache.get(obj);
  62. }
  63. var newObj = {};
  64. var hasPropertyDescriptor =
  65. Object.defineProperty && Object.getOwnPropertyDescriptor;
  66. for (var key in obj) {
  67. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  68. var desc = hasPropertyDescriptor
  69. ? Object.getOwnPropertyDescriptor(obj, key)
  70. : null;
  71. if (desc && (desc.get || desc.set)) {
  72. Object.defineProperty(newObj, key, desc);
  73. } else {
  74. newObj[key] = obj[key];
  75. }
  76. }
  77. }
  78. newObj.default = obj;
  79. if (cache) {
  80. cache.set(obj, newObj);
  81. }
  82. return newObj;
  83. }
  84. function _defineProperty(obj, key, value) {
  85. if (key in obj) {
  86. Object.defineProperty(obj, key, {
  87. value: value,
  88. enumerable: true,
  89. configurable: true,
  90. writable: true
  91. });
  92. } else {
  93. obj[key] = value;
  94. }
  95. return obj;
  96. }
  97. class ExperimentalWorker {
  98. constructor(options) {
  99. _defineProperty(this, '_worker', void 0);
  100. _defineProperty(this, '_options', void 0);
  101. _defineProperty(this, '_request', void 0);
  102. _defineProperty(this, '_retries', void 0);
  103. _defineProperty(this, '_onProcessEnd', void 0);
  104. _defineProperty(this, '_onCustomMessage', void 0);
  105. _defineProperty(this, '_fakeStream', void 0);
  106. _defineProperty(this, '_stdout', void 0);
  107. _defineProperty(this, '_stderr', void 0);
  108. _defineProperty(this, '_exitPromise', void 0);
  109. _defineProperty(this, '_resolveExitPromise', void 0);
  110. _defineProperty(this, '_forceExited', void 0);
  111. this._options = options;
  112. this._request = null;
  113. this._fakeStream = null;
  114. this._stdout = null;
  115. this._stderr = null;
  116. this._exitPromise = new Promise(resolve => {
  117. this._resolveExitPromise = resolve;
  118. });
  119. this._forceExited = false;
  120. this.initialize();
  121. }
  122. initialize() {
  123. this._worker = new (_worker_threads().Worker)(
  124. path().resolve(__dirname, './threadChild.js'),
  125. {
  126. eval: false,
  127. // @ts-expect-error: added in newer versions
  128. resourceLimits: this._options.resourceLimits,
  129. stderr: true,
  130. stdout: true,
  131. workerData: {
  132. cwd: process.cwd(),
  133. env: {
  134. ...process.env,
  135. JEST_WORKER_ID: String(this._options.workerId + 1) // 0-indexed workerId, 1-indexed JEST_WORKER_ID
  136. },
  137. // Suppress --debug / --inspect flags while preserving others (like --harmony).
  138. execArgv: process.execArgv.filter(v => !/^--(debug|inspect)/.test(v)),
  139. silent: true,
  140. ...this._options.forkOptions
  141. }
  142. }
  143. );
  144. if (this._worker.stdout) {
  145. if (!this._stdout) {
  146. // We need to add a permanent stream to the merged stream to prevent it
  147. // from ending when the subprocess stream ends
  148. this._stdout = (0, _mergeStream().default)(this._getFakeStream());
  149. }
  150. this._stdout.add(this._worker.stdout);
  151. }
  152. if (this._worker.stderr) {
  153. if (!this._stderr) {
  154. // We need to add a permanent stream to the merged stream to prevent it
  155. // from ending when the subprocess stream ends
  156. this._stderr = (0, _mergeStream().default)(this._getFakeStream());
  157. }
  158. this._stderr.add(this._worker.stderr);
  159. }
  160. this._worker.on('message', this._onMessage.bind(this));
  161. this._worker.on('exit', this._onExit.bind(this));
  162. this._worker.postMessage([
  163. _types().CHILD_MESSAGE_INITIALIZE,
  164. false,
  165. this._options.workerPath,
  166. this._options.setupArgs
  167. ]);
  168. this._retries++; // If we exceeded the amount of retries, we will emulate an error reply
  169. // coming from the child. This avoids code duplication related with cleaning
  170. // the queue, and scheduling the next call.
  171. if (this._retries > this._options.maxRetries) {
  172. const error = new Error('Call retries were exceeded');
  173. this._onMessage([
  174. _types().PARENT_MESSAGE_CLIENT_ERROR,
  175. error.name,
  176. error.message,
  177. error.stack,
  178. {
  179. type: 'WorkerError'
  180. }
  181. ]);
  182. }
  183. }
  184. _shutdown() {
  185. // End the permanent stream so the merged stream end too
  186. if (this._fakeStream) {
  187. this._fakeStream.end();
  188. this._fakeStream = null;
  189. }
  190. this._resolveExitPromise();
  191. }
  192. _onMessage(response) {
  193. let error;
  194. switch (response[0]) {
  195. case _types().PARENT_MESSAGE_OK:
  196. this._onProcessEnd(null, response[1]);
  197. break;
  198. case _types().PARENT_MESSAGE_CLIENT_ERROR:
  199. error = response[4];
  200. if (error != null && typeof error === 'object') {
  201. const extra = error; // @ts-expect-error: no index
  202. const NativeCtor = global[response[1]];
  203. const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error;
  204. error = new Ctor(response[2]);
  205. error.type = response[1];
  206. error.stack = response[3];
  207. for (const key in extra) {
  208. // @ts-expect-error: no index
  209. error[key] = extra[key];
  210. }
  211. }
  212. this._onProcessEnd(error, null);
  213. break;
  214. case _types().PARENT_MESSAGE_SETUP_ERROR:
  215. error = new Error('Error when calling setup: ' + response[2]); // @ts-expect-error: adding custom properties to errors.
  216. error.type = response[1];
  217. error.stack = response[3];
  218. this._onProcessEnd(error, null);
  219. break;
  220. case _types().PARENT_MESSAGE_CUSTOM:
  221. this._onCustomMessage(response[1]);
  222. break;
  223. default:
  224. throw new TypeError('Unexpected response from worker: ' + response[0]);
  225. }
  226. }
  227. _onExit(exitCode) {
  228. if (exitCode !== 0 && !this._forceExited) {
  229. this.initialize();
  230. if (this._request) {
  231. this._worker.postMessage(this._request);
  232. }
  233. } else {
  234. this._shutdown();
  235. }
  236. }
  237. waitForExit() {
  238. return this._exitPromise;
  239. }
  240. forceExit() {
  241. this._forceExited = true;
  242. this._worker.terminate();
  243. }
  244. send(request, onProcessStart, onProcessEnd, onCustomMessage) {
  245. onProcessStart(this);
  246. this._onProcessEnd = (...args) => {
  247. // Clean the request to avoid sending past requests to workers that fail
  248. // while waiting for a new request (timers, unhandled rejections...)
  249. this._request = null;
  250. return onProcessEnd(...args);
  251. };
  252. this._onCustomMessage = (...arg) => onCustomMessage(...arg);
  253. this._request = request;
  254. this._retries = 0;
  255. this._worker.postMessage(request);
  256. }
  257. getWorkerId() {
  258. return this._options.workerId;
  259. }
  260. getStdout() {
  261. return this._stdout;
  262. }
  263. getStderr() {
  264. return this._stderr;
  265. }
  266. _getFakeStream() {
  267. if (!this._fakeStream) {
  268. this._fakeStream = new (_stream().PassThrough)();
  269. }
  270. return this._fakeStream;
  271. }
  272. }
  273. exports.default = ExperimentalWorker;