| 1 | const Configuration = require('../utils/Configuration'); |
| 2 | const EventEmitter = require('events'); |
| 3 | const {Worker} = require('worker_threads'); |
| 4 | const Pool = require('worker-threads-pool'); |
| 5 | |
| 6 | class Wrk { |
| 7 | /** |
| 8 | * Create a new `Wrk`. |
| 9 | * |
| 10 | * @param {String} workerScript |
| 11 | * @param {Object} workerData |
| 12 | */ |
| 13 | constructor(workerScript, workerData) { |
| 14 | if (Configuration.useWorkerPool()) { |
| 15 | this._pool = new Pool({max: Configuration.getWorkerPoolSize()}); |
| 16 | } |
| 17 | this._workerData = workerData; |
| 18 | this._workerScript = workerScript; |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * |
| 23 | * @return {Promise} |
| 24 | * @private |
| 25 | */ |
| 26 | _startWorkerWithPool() { |
| 27 | return new Promise((resolve, reject) => { |
| 28 | this._pool.acquire(this._workerScript, {workerData: this._workerData}, (err, worker) => { |
| 29 | if (err) { |
| 30 | return reject(err); |
| 31 | } |
| 32 | worker.once('message', resolve); |
| 33 | worker.once('error', reject); |
| 34 | }); |
| 35 | }); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * |
| 40 | * @return {Promise} |
| 41 | * @private |
| 42 | */ |
| 43 | _startWorker() { |
| 44 | return new Promise((resolve, reject) => { |
| 45 | const worker = new Worker(this._workerScript, {workerData: this._workerData}); |
| 46 | worker.on('message', resolve); |
| 47 | worker.on('error', reject); |
| 48 | worker.on('exit', (code) => { |
| 49 | if (code !== 0) { |
| 50 | reject(new Error(`Worker stopped with exit code ${code}`)); |
| 51 | } |
| 52 | }); |
| 53 | }); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * |
| 58 | * @return {Promise} |
| 59 | * @public |
| 60 | */ |
| 61 | start() { |
| 62 | if (Configuration.useWorkerPool()) { |
| 63 | if (Configuration.getWorkerPoolSize() > 10) { |
| 64 | EventEmitter.defaultMaxListeners = Configuration.getWorkerPoolSize() + 1; |
| 65 | } |
| 66 | return this._startWorkerWithPool(); |
| 67 | } |
| 68 | return this._startWorker(); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | module.exports = Wrk; |