Apply dependencies update
[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
c3ee95af 9export default class WorkerDynamicPool extends WorkerAbstract<WorkerData> {
f2bf9948 10 private readonly pool: DynamicThreadPool<WorkerData>;
a4624c96
JB
11
12 /**
13 * Create a new `WorkerDynamicPool`.
14 *
81797102
JB
15 * @param workerScript
16 * @param min
17 * @param max
18 * @param workerStartDelay
19 * @param opts
a4624c96 20 */
ffd71f2c
JB
21 constructor(workerScript: string, min: number, max: number, workerStartDelay?: number, opts?: PoolOptions<Worker>) {
22 super(workerScript, workerStartDelay);
8df3f0a9
JB
23 opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler;
24 this.pool = new DynamicThreadPool<WorkerData>(min, max, this.workerScript, opts);
a4624c96
JB
25 }
26
27 get size(): number {
28 return this.pool.workers.length;
29 }
30
6e0964c8 31 get maxElementsPerWorker(): number | null {
85f78bc0 32 return null;
a4624c96
JB
33 }
34
35 /**
36 *
81797102 37 * @returns
a4624c96
JB
38 * @public
39 */
6c3cfef8
JB
40 public async start(): Promise<void> {
41 // This is intentional
42 }
a4624c96 43
ded13d97
JB
44 /**
45 *
81797102 46 * @returns
ded13d97
JB
47 * @public
48 */
49 public async stop(): Promise<void> {
50 return this.pool.destroy();
51 }
52
a4624c96
JB
53 /**
54 *
81797102
JB
55 * @param elementData
56 * @returns
a4624c96
JB
57 * @public
58 */
c3ee95af 59 public async addElement(elementData: WorkerData): Promise<void> {
a4624c96
JB
60 await this.pool.execute(elementData);
61 // Start worker sequentially to optimize memory at startup
322c9192 62 await Utils.sleep(this.workerStartDelay);
a4624c96
JB
63 }
64}