Log errors in worker
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
1 import { FixedThreadPool } from 'poolifier';
2
3 import type { WorkerData, WorkerOptions } from '../types/Worker';
4 import Utils from '../utils/Utils';
5 import WorkerAbstract from './WorkerAbstract';
6 import { WorkerUtils } from './WorkerUtils';
7
8 export default class WorkerStaticPool extends WorkerAbstract<WorkerData> {
9 private readonly pool: FixedThreadPool<WorkerData>;
10
11 /**
12 * Create a new `WorkerStaticPool`.
13 *
14 * @param workerScript
15 * @param workerOptions
16 */
17 constructor(workerScript: string, workerOptions?: WorkerOptions) {
18 super(workerScript, workerOptions);
19 this.workerOptions.poolOptions.errorHandler =
20 this.workerOptions?.poolOptions?.errorHandler ?? WorkerUtils.defaultErrorHandler;
21 this.workerOptions.poolOptions.exitHandler =
22 this.workerOptions?.poolOptions?.exitHandler ?? WorkerUtils.defaultExitHandler;
23 this.pool = new FixedThreadPool(
24 this.workerOptions.poolMaxSize,
25 this.workerScript,
26 this.workerOptions.poolOptions
27 );
28 }
29
30 get size(): number {
31 return this.pool.workers.length;
32 }
33
34 get maxElementsPerWorker(): number | null {
35 return null;
36 }
37
38 /**
39 *
40 * @returns
41 * @public
42 */
43 public async start(): Promise<void> {
44 // This is intentional
45 }
46
47 /**
48 *
49 * @returns
50 * @public
51 */
52 public async stop(): Promise<void> {
53 return this.pool.destroy();
54 }
55
56 /**
57 *
58 * @param elementData
59 * @returns
60 * @public
61 */
62 public async addElement(elementData: WorkerData): Promise<void> {
63 await this.pool.execute(elementData);
64 // Start element sequentially to optimize memory at startup
65 this.workerOptions.elementStartDelay > 0 &&
66 (await Utils.sleep(this.workerOptions.elementStartDelay));
67 }
68 }