Merge branch 'master' of github.com:LucasBrazi06/ev-simulator into master-enterprise
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
1 import { FixedThreadPool, FixedThreadPoolOptions } from 'poolifier';
2
3 import Constants from '../utils/Constants';
4 import Utils from '../utils/Utils';
5 import { WorkerData } from '../types/Worker';
6 import Wrk from './Wrk';
7
8 export default class WorkerStaticPool<T> extends Wrk {
9 private pool: StaticPool;
10
11 /**
12 * Create a new `WorkerStaticPool`.
13 *
14 * @param {string} workerScript
15 */
16 constructor(workerScript: string, numThreads: number) {
17 super(workerScript);
18 this.pool = StaticPool.getInstance(numThreads, this.workerScript);
19 }
20
21 get size(): number {
22 return this.pool.workers.length;
23 }
24
25 get maxElementsPerWorker(): number {
26 return 1;
27 }
28
29 /**
30 *
31 * @return {Promise<void>}
32 * @public
33 */
34 // eslint-disable-next-line @typescript-eslint/no-empty-function
35 public async start(): Promise<void> { }
36
37 /**
38 *
39 * @return {Promise<void>}
40 * @public
41 */
42 public async stop(): Promise<void> {
43 return this.pool.destroy();
44 }
45
46 /**
47 *
48 * @return {Promise<void>}
49 * @public
50 */
51 public async addElement(elementData: T): Promise<void> {
52 await this.pool.execute(elementData);
53 // Start worker sequentially to optimize memory at startup
54 await Utils.sleep(Constants.START_WORKER_DELAY);
55 }
56 }
57
58 class StaticPool extends FixedThreadPool<WorkerData> {
59 private static instance: StaticPool;
60
61 private constructor(numThreads: number, workerScript: string, opts?: FixedThreadPoolOptions) {
62 super(numThreads, workerScript, opts);
63 }
64
65 public static getInstance(numThreads: number, workerScript: string): StaticPool {
66 if (!StaticPool.instance) {
67 StaticPool.instance = new StaticPool(numThreads, workerScript,
68 {
69 exitHandler: (code) => {
70 if (code !== 0) {
71 console.error(`Worker stopped with exit code ${code}`);
72 }
73 }
74 }
75 );
76 }
77 return StaticPool.instance;
78 }
79 }