Ensure performance statistics is started before connection to the OCPP
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerDynamicPool.ts
CommitLineData
c32882b0 1import { DynamicThreadPool, PoolOptions } from 'poolifier';
a4624c96 2
a4624c96 3import Utils from '../utils/Utils';
c32882b0 4import { Worker } from 'worker_threads';
fd1fdf1b 5import WorkerAbstract from './WorkerAbstract';
a4624c96 6import { WorkerData } from '../types/Worker';
7874b0b1 7import { WorkerUtils } from './WorkerUtils';
a4624c96 8
fd1fdf1b 9export default class WorkerDynamicPool<T> extends WorkerAbstract {
a4624c96
JB
10 private pool: DynamicPool;
11
12 /**
13 * Create a new `WorkerDynamicPool`.
14 *
15 * @param {string} workerScript
e71cccf3
JB
16 * @param {number} min
17 * @param {number} max
322c9192 18 * @param {number} workerStartDelay
9efbac5b 19 * @param {PoolOptions} opts
a4624c96 20 */
9efbac5b 21 constructor(workerScript: string, min: number, max: number, workerStartDelay?: number, opts?: PoolOptions<Worker>) {
322c9192 22 super(workerScript, workerStartDelay);
9efbac5b 23 this.pool = DynamicPool.getInstance(min, max, this.workerScript, opts);
a4624c96
JB
24 }
25
26 get size(): number {
27 return this.pool.workers.length;
28 }
29
6e0964c8 30 get maxElementsPerWorker(): number | null {
85f78bc0 31 return null;
a4624c96
JB
32 }
33
34 /**
35 *
3340259a 36 * @returns {Promise<void>}
a4624c96
JB
37 * @public
38 */
39 // eslint-disable-next-line @typescript-eslint/no-empty-function
40 public async start(): Promise<void> { }
41
ded13d97
JB
42 /**
43 *
3340259a 44 * @returns {Promise<void>}
ded13d97
JB
45 * @public
46 */
fd1fdf1b 47 // eslint-disable-next-line @typescript-eslint/require-await
ded13d97
JB
48 public async stop(): Promise<void> {
49 return this.pool.destroy();
50 }
51
a4624c96
JB
52 /**
53 *
6e0964c8 54 * @param {T} elementData
3340259a 55 * @returns {Promise<void>}
a4624c96
JB
56 * @public
57 */
8434025b 58 public async addElement(elementData: T): Promise<void> {
a4624c96
JB
59 await this.pool.execute(elementData);
60 // Start worker sequentially to optimize memory at startup
322c9192 61 await Utils.sleep(this.workerStartDelay);
a4624c96
JB
62 }
63}
64
65class DynamicPool extends DynamicThreadPool<WorkerData> {
66 private static instance: DynamicPool;
67
63b19acd
JB
68 private constructor(min: number, max: number, workerScript: string, opts?: PoolOptions<Worker>) {
69 super(min, max, workerScript, opts);
a4624c96
JB
70 }
71
9efbac5b 72 public static getInstance(min: number, max: number, workerScript: string, opts?: PoolOptions<Worker>): DynamicPool {
a4624c96 73 if (!DynamicPool.instance) {
7874b0b1 74 opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler;
9efbac5b 75 DynamicPool.instance = new DynamicPool(min, max, workerScript, opts);
a4624c96
JB
76 }
77 return DynamicPool.instance;
78 }
79}