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