1 import { Worker
, WorkerOptions
} from
'worker_threads';
3 import Configuration from
'../utils/Configuration';
4 import Constants from
'../utils/Constants';
5 import Pool from
'worker-threads-pool';
6 import WorkerData from
'../types/WorkerData';
8 export default class Wrk
{
9 private _workerScript
: string;
10 private _workerData
: WorkerData
;
11 private _worker
: Worker
;
12 private _maxWorkerElements
: number;
13 private _numWorkerElements
: number;
18 * @param {string} workerScript
19 * @param {WorkerData} workerData
21 constructor(workerScript
: string, workerData
: WorkerData
, maxWorkerElements
= 1) {
22 this._workerData
= workerData
;
23 this._workerScript
= workerScript
;
24 this._maxWorkerElements
= maxWorkerElements
;
25 this._numWorkerElements
= 0;
26 if (Configuration
.useWorkerPool()) {
27 WorkerPool
.maxConcurrentWorkers
= Configuration
.getWorkerPoolMaxSize();
36 async start(): Promise
<Worker
> {
37 if (Configuration
.useWorkerPool()) {
38 await this._startWorkerWithPool();
40 await this._startWorker();
50 addWorkerElement(workerData
: WorkerData
): void {
51 if (Configuration
.useWorkerPool()) {
52 throw Error('Cannot add Wrk element if the worker pool is enabled');
54 if (this._numWorkerElements
>= this._maxWorkerElements
) {
55 throw Error('Cannot add Wrk element: max number of elements per worker reached');
57 this._workerData
= workerData
;
58 this._worker
.postMessage({ id
: Constants
.START_WORKER_ELEMENT
, workerData
: workerData
});
59 this._numWorkerElements
++;
67 public getWorkerPoolSize(): number {
68 if (Configuration
.useWorkerPool()) {
69 return WorkerPool
.getPoolSize();
78 private async _startWorkerWithPool() {
79 return new Promise((resolve
, reject
) => {
80 WorkerPool
.acquire(this._workerScript
, { workerData
: this._workerData
}, (err
, worker
) => {
84 worker
.once('message', resolve
);
85 worker
.once('error', reject
);
86 this._worker
= worker
;
96 private async _startWorker() {
97 return new Promise((resolve
, reject
) => {
98 const worker
= new Worker(this._workerScript
, { workerData
: this._workerData
});
99 worker
.on('message', resolve
);
100 worker
.on('error', reject
);
101 worker
.on('exit', (code
) => {
103 reject(new Error(`Worker stopped with exit code ${code}`));
106 this._numWorkerElements
++;
107 this._worker
= worker
;
114 public static maxConcurrentWorkers
: number;
115 private static _instance
: Pool
;
117 private constructor() { }
119 public static getInstance(): Pool
{
120 if (!WorkerPool
._instance
) {
121 WorkerPool
._instance
= new Pool({ max
: WorkerPool
.maxConcurrentWorkers
});
123 return WorkerPool
._instance
;
126 public static acquire(filename
: string, options
: WorkerOptions
, callback
: (error
: Error | null, worker
: Worker
) => void): void {
127 WorkerPool
.getInstance().acquire(filename
, options
, callback
);
130 public static getPoolSize(): number {
131 return WorkerPool
.getInstance().size
;