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