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