Merge branch 'master' of github.com:LucasBrazi06/ev-simulator into master-enterprise
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerDynamicPool.ts
1 import { DynamicThreadPool, PoolOptions } from 'poolifier';
2
3 import Constants from '../utils/Constants';
4 import Utils from '../utils/Utils';
5 import { Worker } from 'worker_threads';
6 import { WorkerData } from '../types/Worker';
7 import Wrk from './Wrk';
8
9 export default class WorkerDynamicPool<T> extends Wrk {
10 private pool: DynamicPool;
11
12 /**
13 * Create a new `WorkerDynamicPool`.
14 *
15 * @param {string} workerScript
16 */
17 constructor(workerScript: string, min: number, max: number,) {
18 super(workerScript);
19 this.pool = DynamicPool.getInstance(min, max, this.workerScript);
20 }
21
22 get size(): number {
23 return this.pool.workers.length;
24 }
25
26 get maxElementsPerWorker(): number {
27 return 1;
28 }
29
30 /**
31 *
32 * @return {Promise<void>}
33 * @public
34 */
35 // eslint-disable-next-line @typescript-eslint/no-empty-function
36 public async start(): Promise<void> { }
37
38 /**
39 *
40 * @return {Promise<void>}
41 * @public
42 */
43 public async stop(): Promise<void> {
44 return this.pool.destroy();
45 }
46
47 /**
48 *
49 * @return {Promise<void>}
50 * @public
51 */
52 public async addElement(elementData: T): Promise<void> {
53 await this.pool.execute(elementData);
54 // Start worker sequentially to optimize memory at startup
55 await Utils.sleep(Constants.START_WORKER_DELAY);
56 }
57 }
58
59 class DynamicPool extends DynamicThreadPool<WorkerData> {
60 private static instance: DynamicPool;
61
62 private constructor(min: number, max: number, workerScript: string, opts?: PoolOptions<Worker>) {
63 super(min, max, workerScript, opts);
64 }
65
66 public static getInstance(min: number, max: number, workerScript: string): DynamicPool {
67 if (!DynamicPool.instance) {
68 DynamicPool.instance = new DynamicPool(min, max, workerScript,
69 {
70 exitHandler: (code) => {
71 if (code !== 0) {
72 console.error(`Worker stopped with exit code ${code}`);
73 }
74 }
75 }
76 );
77 }
78 return DynamicPool.instance;
79 }
80 }