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