perf: run charging station as async resource in the worker set mode
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import { AsyncResource } from 'node:async_hooks';
4 import { parentPort, workerData } from 'node:worker_threads';
5
6 import { ThreadWorker } from 'poolifier';
7
8 import { ChargingStation } from './ChargingStation';
9 import type { ChargingStationWorkerData } from '../types';
10 import { Configuration } from '../utils';
11 import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
12
13 /**
14 * Create and start a charging station instance
15 *
16 * @param data - workerData
17 */
18 const startChargingStation = (data: ChargingStationWorkerData): void => {
19 new ChargingStation(data.index, data.templateFile).start();
20 };
21
22 // Conditionally export ThreadWorker instance for pool usage
23 export let threadWorker: ThreadWorker;
24 if (Configuration.workerPoolInUse()) {
25 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
26 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
27 });
28 } else {
29 class ChargingStationWorker extends AsyncResource {
30 constructor() {
31 super('ChargingStationWorker');
32 }
33
34 public run(data: ChargingStationWorkerData): void {
35 this.runInAsyncScope(
36 startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void,
37 this,
38 data
39 );
40 }
41 }
42 // Add message listener to start charging station from main thread
43 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
44 if (message.id === WorkerMessageEvents.startWorkerElement) {
45 startChargingStation(message.data);
46 }
47 });
48 if (workerData !== undefined) {
49 new ChargingStationWorker().run(workerData as ChargingStationWorkerData);
50 }
51 }