build: switch to NodeNext module resolution
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerDynamicPool.ts
CommitLineData
38b2428f 1import type { EventEmitterAsyncResource } from 'node:events';
2b59e7f7
JB
2
3import { DynamicThreadPool, type PoolInfo } from 'poolifier';
8114d10e 4
a6ef1ece
JB
5import { WorkerAbstract } from './WorkerAbstract.js';
6import type { WorkerData, WorkerOptions } from './WorkerTypes.js';
7import { randomizeDelay, sleep } from './WorkerUtils.js';
a4624c96 8
268a74bb 9export class WorkerDynamicPool extends WorkerAbstract<WorkerData> {
f2bf9948 10 private readonly pool: DynamicThreadPool<WorkerData>;
a4624c96
JB
11
12 /**
361c98f5 13 * Creates a new `WorkerDynamicPool`.
a4624c96 14 *
0e4fa348
JB
15 * @param workerScript -
16 * @param workerOptions -
a4624c96 17 */
4a3807d1 18 constructor(workerScript: string, workerOptions: WorkerOptions) {
4d7227e6 19 super(workerScript, workerOptions);
e7aeea18
JB
20 this.pool = new DynamicThreadPool<WorkerData>(
21 this.workerOptions.poolMinSize,
22 this.workerOptions.poolMaxSize,
23 this.workerScript,
5edd8ba0 24 this.workerOptions.poolOptions,
e7aeea18 25 );
a4624c96
JB
26 }
27
b779c0f8
JB
28 get info(): PoolInfo {
29 return this.pool.info;
30 }
31
a4624c96 32 get size(): number {
b779c0f8 33 return this.pool.info.workerNodes;
a4624c96
JB
34 }
35
72092cfc
JB
36 get maxElementsPerWorker(): number | undefined {
37 return undefined;
a4624c96
JB
38 }
39
38b2428f
JB
40 get emitter(): EventEmitterAsyncResource | undefined {
41 return this.pool?.emitter;
962a8159
JB
42 }
43
8baf3f8f 44 /** @inheritDoc */
6c3cfef8
JB
45 public async start(): Promise<void> {
46 // This is intentional
47 }
a4624c96 48
8baf3f8f 49 /** @inheritDoc */
ded13d97
JB
50 public async stop(): Promise<void> {
51 return this.pool.destroy();
52 }
53
8baf3f8f 54 /** @inheritDoc */
c3ee95af 55 public async addElement(elementData: WorkerData): Promise<void> {
a4624c96 56 await this.pool.execute(elementData);
4bfd80fa 57 // Start element sequentially to optimize memory at startup
e1d9a0f4 58 this.workerOptions.elementStartDelay! > 0 &&
ab93b184 59 (await sleep(randomizeDelay(this.workerOptions.elementStartDelay!)));
a4624c96
JB
60 }
61}