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