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