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