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