Silence some sonar code smells
[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 {string} workerScript
16 * @param {number} min
17 * @param {number} max
18 * @param {number} workerStartDelay
19 * @param {PoolOptions} 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 {Promise<void>}
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 {Promise<void>}
48 * @public
49 */
50 // eslint-disable-next-line @typescript-eslint/require-await
51 public async stop(): Promise<void> {
52 return this.pool.destroy();
53 }
54
55 /**
56 *
57 * @param {T} elementData
58 * @returns {Promise<void>}
59 * @public
60 */
61 public async addElement(elementData: T): Promise<void> {
62 await this.pool.execute(elementData);
63 // Start worker sequentially to optimize memory at startup
64 await Utils.sleep(this.workerStartDelay);
65 }
66 }