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