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