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