feat: ensure charging station add op return its station info
[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
3b09e788
JB
9export class WorkerDynamicPool<D extends WorkerData, R extends WorkerData> extends WorkerAbstract<
10D,
11R
12> {
13 private readonly pool: DynamicThreadPool<D, R>
a4624c96
JB
14
15 /**
361c98f5 16 * Creates a new `WorkerDynamicPool`.
a4624c96 17 *
0e4fa348
JB
18 * @param workerScript -
19 * @param workerOptions -
a4624c96 20 */
66a7748d
JB
21 constructor (workerScript: string, workerOptions: WorkerOptions) {
22 super(workerScript, workerOptions)
3b09e788 23 this.pool = new DynamicThreadPool<D, R>(
e7aeea18
JB
24 this.workerOptions.poolMinSize,
25 this.workerOptions.poolMaxSize,
26 this.workerScript,
66a7748d
JB
27 this.workerOptions.poolOptions
28 )
a4624c96
JB
29 }
30
66a7748d
JB
31 get info (): PoolInfo {
32 return this.pool.info
b779c0f8
JB
33 }
34
66a7748d
JB
35 get size (): number {
36 return this.pool.info.workerNodes
a4624c96
JB
37 }
38
66a7748d
JB
39 get maxElementsPerWorker (): number | undefined {
40 return undefined
a4624c96
JB
41 }
42
66a7748d 43 get emitter (): EventEmitterAsyncResource | undefined {
5199f9fd 44 return this.pool.emitter
962a8159
JB
45 }
46
8baf3f8f 47 /** @inheritDoc */
24dc52e9
JB
48 public start (): void {
49 this.pool.start()
6c3cfef8 50 }
a4624c96 51
8baf3f8f 52 /** @inheritDoc */
66a7748d
JB
53 public async stop (): Promise<void> {
54 await this.pool.destroy()
ded13d97
JB
55 }
56
8baf3f8f 57 /** @inheritDoc */
3b09e788
JB
58 public async addElement (elementData: D): Promise<R> {
59 const response = await this.pool.execute(elementData)
4bfd80fa 60 // Start element sequentially to optimize memory at startup
66a7748d 61 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
da47bc29 62 this.workerOptions.elementAddDelay! > 0 &&
66a7748d 63 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
da47bc29 64 (await sleep(randomizeDelay(this.workerOptions.elementAddDelay!)))
3b09e788 65 return response
a4624c96
JB
66 }
67}