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