Revert poolifier update to beta.
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
CommitLineData
a4624c96
JB
1import { FixedThreadPool, FixedThreadPoolOptions } from 'poolifier';
2
3import Constants from '../utils/Constants';
4import Utils from '../utils/Utils';
5import { WorkerData } from '../types/Worker';
6import Wrk from './Wrk';
a4624c96 7
8434025b 8export default class WorkerStaticPool<T> extends Wrk {
a4624c96
JB
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
ded13d97
JB
37 /**
38 *
39 * @return {Promise<void>}
40 * @public
41 */
42 public async stop(): Promise<void> {
43 return this.pool.destroy();
44 }
45
a4624c96
JB
46 /**
47 *
48 * @return {Promise<void>}
49 * @public
50 */
8434025b 51 public async addElement(elementData: T): Promise<void> {
a4624c96
JB
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
58class 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) {
1e924543 71 console.error(`Worker stopped with exit code ${code}`);
a4624c96
JB
72 }
73 }
74 }
75 );
76 }
77 return StaticPool.instance;
78 }
79}