WorkerSet: remove ugly hack to deal with async worker message handler
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
CommitLineData
4d7227e6 1import { FixedThreadPool } from 'poolifier';
8114d10e 2
6c1761d4 3import type { WorkerData, WorkerOptions } from '../types/Worker';
a4624c96 4import Utils from '../utils/Utils';
fd1fdf1b 5import WorkerAbstract from './WorkerAbstract';
7874b0b1 6import { WorkerUtils } from './WorkerUtils';
a4624c96 7
c3ee95af 8export default class WorkerStaticPool extends WorkerAbstract<WorkerData> {
f2bf9948 9 private readonly pool: FixedThreadPool<WorkerData>;
a4624c96
JB
10
11 /**
12 * Create a new `WorkerStaticPool`.
13 *
81797102 14 * @param workerScript
4d7227e6 15 * @param workerOptions
a4624c96 16 */
4d7227e6
JB
17 constructor(workerScript: string, workerOptions?: WorkerOptions) {
18 super(workerScript, workerOptions);
0f187001
JB
19 this.workerOptions.poolOptions.errorHandler =
20 this.workerOptions?.poolOptions?.errorHandler ?? WorkerUtils.defaultErrorHandler;
e7aeea18
JB
21 this.workerOptions.poolOptions.exitHandler =
22 this.workerOptions?.poolOptions?.exitHandler ?? WorkerUtils.defaultExitHandler;
23 this.pool = new FixedThreadPool(
24 this.workerOptions.poolMaxSize,
25 this.workerScript,
26 this.workerOptions.poolOptions
27 );
a4624c96
JB
28 }
29
30 get size(): number {
31 return this.pool.workers.length;
32 }
33
6e0964c8 34 get maxElementsPerWorker(): number | null {
85f78bc0 35 return null;
a4624c96
JB
36 }
37
38 /**
39 *
81797102 40 * @returns
a4624c96
JB
41 * @public
42 */
81797102
JB
43 public async start(): Promise<void> {
44 // This is intentional
45 }
a4624c96 46
ded13d97
JB
47 /**
48 *
81797102 49 * @returns
ded13d97
JB
50 * @public
51 */
52 public async stop(): Promise<void> {
53 return this.pool.destroy();
54 }
55
a4624c96
JB
56 /**
57 *
81797102
JB
58 * @param elementData
59 * @returns
a4624c96
JB
60 * @public
61 */
c3ee95af 62 public async addElement(elementData: WorkerData): Promise<void> {
a4624c96 63 await this.pool.execute(elementData);
4bfd80fa 64 // Start element sequentially to optimize memory at startup
e7aeea18
JB
65 this.workerOptions.elementStartDelay > 0 &&
66 (await Utils.sleep(this.workerOptions.elementStartDelay));
a4624c96
JB
67 }
68}