refactor: encapsulate worker in an object
[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 } 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 class 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) {
28 this.run(message.data);
29 }
30 });
31 }
32
33 private run(data: ChargingStationWorkerData): void {
34 this.runInAsyncScope(
35 startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void,
36 this,
37 data
38 );
39 }
40 }
41
42 export let chargingStationWorker: ChargingStationWorker;
43 // Conditionally export ThreadWorker instance for pool usage
44 export let threadWorker: ThreadWorker;
45 if (Configuration.workerPoolInUse()) {
46 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
47 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
48 });
49 } else {
50 chargingStationWorker = new ChargingStationWorker();
51 }