perf: run charging station as async resource in the worker set mode
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
c8eeb62b 2
a679a162 3import { AsyncResource } from 'node:async_hooks';
01f4001e 4import { parentPort, workerData } from 'node:worker_threads';
8114d10e
JB
5
6import { ThreadWorker } from 'poolifier';
7
4c3c0d59 8import { ChargingStation } from './ChargingStation';
268a74bb 9import type { ChargingStationWorkerData } from '../types';
a4e5c2e2 10import { Configuration } from '../utils';
268a74bb 11import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
7dde0b73 12
e8a92d57
JB
13/**
14 * Create and start a charging station instance
15 *
16 * @param data - workerData
17 */
18const startChargingStation = (data: ChargingStationWorkerData): void => {
a679a162 19 new ChargingStation(data.index, data.templateFile).start();
e8a92d57
JB
20};
21
b8da29bc 22// Conditionally export ThreadWorker instance for pool usage
56a74dae 23export let threadWorker: ThreadWorker;
aa7d6d95 24if (Configuration.workerPoolInUse()) {
e7aeea18 25 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
3fa0f0ed 26 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
e7aeea18 27 });
74bbc59b 28} else {
a679a162
JB
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 }
56a74dae 42 // Add message listener to start charging station from main thread
a679a162
JB
43 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
44 if (message.id === WorkerMessageEvents.startWorkerElement) {
45 startChargingStation(message.data);
46 }
47 });
a4e5c2e2 48 if (workerData !== undefined) {
a679a162 49 new ChargingStationWorker().run(workerData as ChargingStationWorkerData);
6013bc53 50 }
3d2ff9e4 51}