Merge pull request #1016 from SAP/dependabot/npm_and_yarn/types/node-20.11.30
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerDynamicPool.ts
CommitLineData
66a7748d 1import type { EventEmitterAsyncResource } from 'node:events'
2b59e7f7 2
66a7748d 3import { DynamicThreadPool, type PoolInfo } from 'poolifier'
8114d10e 4
66a7748d
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> {
66a7748d 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 */
66a7748d
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,
66a7748d
JB
24 this.workerOptions.poolOptions
25 )
a4624c96
JB
26 }
27
66a7748d
JB
28 get info (): PoolInfo {
29 return this.pool.info
b779c0f8
JB
30 }
31
66a7748d
JB
32 get size (): number {
33 return this.pool.info.workerNodes
a4624c96
JB
34 }
35
66a7748d
JB
36 get maxElementsPerWorker (): number | undefined {
37 return undefined
a4624c96
JB
38 }
39
66a7748d 40 get emitter (): EventEmitterAsyncResource | undefined {
5199f9fd 41 return this.pool.emitter
962a8159
JB
42 }
43
8baf3f8f 44 /** @inheritDoc */
24dc52e9
JB
45 public start (): void {
46 this.pool.start()
6c3cfef8 47 }
a4624c96 48
8baf3f8f 49 /** @inheritDoc */
66a7748d
JB
50 public async stop (): Promise<void> {
51 await this.pool.destroy()
ded13d97
JB
52 }
53
8baf3f8f 54 /** @inheritDoc */
66a7748d
JB
55 public async addElement (elementData: WorkerData): Promise<void> {
56 await this.pool.execute(elementData)
4bfd80fa 57 // Start element sequentially to optimize memory at startup
66a7748d 58 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
da47bc29 59 this.workerOptions.elementAddDelay! > 0 &&
66a7748d 60 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
da47bc29 61 (await sleep(randomizeDelay(this.workerOptions.elementAddDelay!)))
a4624c96
JB
62 }
63}