Log unconditionally uncaughtException and unhandledRejection in
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { parentPort, workerData } from 'worker_threads';
4
5 import { ThreadWorker } from 'poolifier';
6
7 import {
8 ChargingStationWorkerData,
9 ChargingStationWorkerMessage,
10 ChargingStationWorkerMessageEvents,
11 } from '../types/ChargingStationWorker';
12 import Utils from '../utils/Utils';
13 import WorkerConstants from '../worker/WorkerConstants';
14 import ChargingStation from './ChargingStation';
15 import { ChargingStationUtils } from './ChargingStationUtils';
16
17 // Conditionally export ThreadWorker instance for pool usage
18 export let threadWorker: ThreadWorker;
19 if (ChargingStationUtils.workerPoolInUse()) {
20 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
21 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
22 async: false,
23 });
24 } else {
25 // Add message listener to start charging station from main thread
26 addMessageListener();
27 if (Utils.isUndefined(workerData) === false) {
28 startChargingStation(workerData as ChargingStationWorkerData);
29 }
30 }
31
32 /**
33 * Listen messages send by the main thread
34 */
35 function addMessageListener(): void {
36 parentPort?.on('message', (message: ChargingStationWorkerMessage<ChargingStationWorkerData>) => {
37 if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) {
38 startChargingStation(message.data);
39 }
40 });
41 }
42
43 /**
44 * Create and start a charging station instance
45 *
46 * @param data workerData
47 */
48 function startChargingStation(data: ChargingStationWorkerData): void {
49 const station = new ChargingStation(data.index, data.templateFile);
50 station.start();
51 }
52
53 process.on('uncaughtException', (err) => {
54 throw err;
55 });
56
57 process.on('unhandledRejection', (reason) => {
58 throw reason;
59 });