a263335c1bd59682220be9ebcfdc281c0e067d6d
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerDynamicPool.ts
1 import { WorkerData, WorkerOptions } from '../types/Worker';
2
3 import { DynamicThreadPool } from 'poolifier';
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 = this.workerOptions?.poolOptions?.exitHandler ?? WorkerUtils.defaultExitHandler;
20 this.pool = new DynamicThreadPool<WorkerData>(this.workerOptions.poolMinSize, this.workerOptions.poolMaxSize, this.workerScript, this.workerOptions.poolOptions);
21 }
22
23 get size(): number {
24 return this.pool.workers.length;
25 }
26
27 get maxElementsPerWorker(): number | null {
28 return null;
29 }
30
31 /**
32 *
33 * @returns
34 * @public
35 */
36 public async start(): Promise<void> {
37 // This is intentional
38 }
39
40 /**
41 *
42 * @returns
43 * @public
44 */
45 public async stop(): Promise<void> {
46 return this.pool.destroy();
47 }
48
49 /**
50 *
51 * @param elementData
52 * @returns
53 * @public
54 */
55 public async addElement(elementData: WorkerData): Promise<void> {
56 await this.pool.execute(elementData);
57 // Start element sequentially to optimize memory at startup
58 this.workerOptions.elementStartDelay > 0 && await Utils.sleep(this.workerOptions.elementStartDelay);
59 }
60 }