docs: improve code documentation
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerDynamicPool.ts
CommitLineData
962a8159 1import type EventEmitterAsyncResource from 'node:events';
0e4fa348 2
be245fda 3import { DynamicThreadPool, type PoolInfo } from 'poolifier';
8114d10e 4
268a74bb
JB
5import { WorkerAbstract } from './WorkerAbstract';
6import type { WorkerData, WorkerOptions } from './WorkerTypes';
be245fda 7import { sleep } from './WorkerUtils';
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 */
4d7227e6
JB
18 constructor(workerScript: string, workerOptions?: WorkerOptions) {
19 super(workerScript, workerOptions);
e7aeea18
JB
20 this.pool = new DynamicThreadPool<WorkerData>(
21 this.workerOptions.poolMinSize,
22 this.workerOptions.poolMaxSize,
23 this.workerScript,
24 this.workerOptions.poolOptions
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
962a8159
JB
40 get emitter(): EventEmitterAsyncResource | undefined {
41 return this.pool?.emitter;
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
789871d6 58 this.workerOptions.elementStartDelay > 0 && (await sleep(this.workerOptions.elementStartDelay));
a4624c96
JB
59 }
60}