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