build(deps): 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
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
6b57eb9a
JB
22class ChargingStationWorker extends AsyncResource {
23 constructor() {
24 super('ChargingStationWorker');
25 // Add message listener to create and start charging station from the main thread
26 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
27 if (message.id === WorkerMessageEvents.startWorkerElement) {
962a8159
JB
28 this.runInAsyncScope(
29 startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void,
30 this,
31 message.data
32 );
6b57eb9a
JB
33 }
34 });
35 }
6b57eb9a
JB
36}
37
38export let chargingStationWorker: ChargingStationWorker;
b8da29bc 39// Conditionally export ThreadWorker instance for pool usage
56a74dae 40export let threadWorker: ThreadWorker;
aa7d6d95 41if (Configuration.workerPoolInUse()) {
e7aeea18 42 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
3fa0f0ed 43 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
e7aeea18 44 });
74bbc59b 45} else {
6b57eb9a 46 chargingStationWorker = new ChargingStationWorker();
3d2ff9e4 47}