build(deps-dev): apply updates
[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';
6b57eb9a 4import { parentPort } 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
11353865
JB
13const moduleName = 'ChargingStationWorker';
14
e8a92d57 15/**
361c98f5 16 * Creates and starts a charging station instance
e8a92d57
JB
17 *
18 * @param data - workerData
19 */
20const startChargingStation = (data: ChargingStationWorkerData): void => {
a679a162 21 new ChargingStation(data.index, data.templateFile).start();
e8a92d57
JB
22};
23
6b57eb9a
JB
24class ChargingStationWorker extends AsyncResource {
25 constructor() {
11353865 26 super(moduleName);
6b57eb9a
JB
27 // Add message listener to create and start charging station from the main thread
28 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
29 if (message.id === WorkerMessageEvents.startWorkerElement) {
962a8159
JB
30 this.runInAsyncScope(
31 startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void,
32 this,
5edd8ba0 33 message.data,
962a8159 34 );
6b57eb9a
JB
35 }
36 });
37 }
6b57eb9a
JB
38}
39
6b2f4370 40export let chargingStationWorker: ChargingStationWorker | ThreadWorker<ChargingStationWorkerData>;
aa7d6d95 41if (Configuration.workerPoolInUse()) {
6b2f4370 42 chargingStationWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
3fa0f0ed 43 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
e7aeea18 44 });
74bbc59b 45} else {
6b57eb9a 46 chargingStationWorker = new ChargingStationWorker();
3d2ff9e4 47}