Optimize worker handlers calls by binding them to the current instance
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerStaticPool.ts
CommitLineData
0e4fa348
JB
1import type { Worker } from 'worker_threads';
2
3import { type ErrorHandler, type ExitHandler, FixedThreadPool } from 'poolifier';
8114d10e 4
6c1761d4 5import type { WorkerData, WorkerOptions } from '../types/Worker';
a4624c96 6import Utils from '../utils/Utils';
fd1fdf1b 7import WorkerAbstract from './WorkerAbstract';
7874b0b1 8import { WorkerUtils } from './WorkerUtils';
a4624c96 9
c3ee95af 10export default class WorkerStaticPool extends WorkerAbstract<WorkerData> {
f2bf9948 11 private readonly pool: FixedThreadPool<WorkerData>;
a4624c96
JB
12
13 /**
14 * Create a new `WorkerStaticPool`.
15 *
0e4fa348
JB
16 * @param workerScript -
17 * @param workerOptions -
a4624c96 18 */
4d7227e6
JB
19 constructor(workerScript: string, workerOptions?: WorkerOptions) {
20 super(workerScript, workerOptions);
0e4fa348
JB
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);
e7aeea18
JB
28 this.pool = new FixedThreadPool(
29 this.workerOptions.poolMaxSize,
30 this.workerScript,
31 this.workerOptions.poolOptions
32 );
a4624c96
JB
33 }
34
35 get size(): number {
36 return this.pool.workers.length;
37 }
38
6e0964c8 39 get maxElementsPerWorker(): number | null {
85f78bc0 40 return null;
a4624c96
JB
41 }
42
43 /**
44 *
81797102 45 * @returns
a4624c96
JB
46 * @public
47 */
81797102
JB
48 public async start(): Promise<void> {
49 // This is intentional
50 }
a4624c96 51
ded13d97
JB
52 /**
53 *
81797102 54 * @returns
ded13d97
JB
55 * @public
56 */
57 public async stop(): Promise<void> {
58 return this.pool.destroy();
59 }
60
a4624c96
JB
61 /**
62 *
0e4fa348 63 * @param elementData -
81797102 64 * @returns
a4624c96
JB
65 * @public
66 */
c3ee95af 67 public async addElement(elementData: WorkerData): Promise<void> {
a4624c96 68 await this.pool.execute(elementData);
4bfd80fa 69 // Start element sequentially to optimize memory at startup
e7aeea18
JB
70 this.workerOptions.elementStartDelay > 0 &&
71 (await Utils.sleep(this.workerOptions.elementStartDelay));
a4624c96
JB
72 }
73}