feat: add performance statistics to UI protocol
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
index 85ea77fb8b58d1d18d6424ee2f8c927080b03180..4fde42c4d3908a368e2424d3a77cbb3180b0d34c 100644 (file)
@@ -1,50 +1,67 @@
-// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
+// Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
 
-import {
-  ChargingStationWorkerData,
-  ChargingStationWorkerMessage,
-  ChargingStationWorkerMessageEvents,
-} from '../types/ChargingStationWorker';
-import { parentPort, workerData } from 'worker_threads';
+import { parentPort } from 'node:worker_threads'
 
-import ChargingStation from './ChargingStation';
-import { ChargingStationUtils } from './ChargingStationUtils';
-import { ThreadWorker } from 'poolifier';
-import Utils from '../utils/Utils';
-import WorkerConstants from '../worker/WorkerConstants';
+import { ThreadWorker } from 'poolifier'
 
-// Conditionally export ThreadWorker instance for pool usage
-export let threadWorker: ThreadWorker;
-if (ChargingStationUtils.workerPoolInUse()) {
-  threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
-    maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
-    async: false,
-  });
-} else {
-  // Add message listener to start charging station from main thread
-  addMessageListener();
-  if (!Utils.isUndefined(workerData)) {
-    startChargingStation(workerData as ChargingStationWorkerData);
-  }
-}
+import { ChargingStation } from './ChargingStation.js'
+import { BaseError } from '../exception/index.js'
+import type {
+  ChargingStationData,
+  ChargingStationWorkerData,
+  ChargingStationWorkerEventError,
+  ChargingStationWorkerMessage
+} from '../types/index.js'
+import { Configuration, buildChargingStationDataPayload } from '../utils/index.js'
+import { type WorkerMessage, WorkerMessageEvents } from '../worker/index.js'
 
-/**
- * Listen messages send by the main thread
- */
-function addMessageListener(): void {
-  parentPort?.on('message', (message: ChargingStationWorkerMessage) => {
-    if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) {
-      startChargingStation(message.data);
+export let chargingStationWorker: object
+if (Configuration.workerPoolInUse()) {
+  chargingStationWorker = new ThreadWorker<ChargingStationWorkerData>(
+    (data?: ChargingStationWorkerData): void => {
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion, no-new
+      new ChargingStation(data!.index, data!.templateFile)
     }
-  });
-}
-
-/**
- * Create and start a charging station instance
- *
- * @param data workerData
- */
-function startChargingStation(data: ChargingStationWorkerData): void {
-  const station = new ChargingStation(data.index, data.templateFile);
-  station.start();
+  )
+} else {
+  // eslint-disable-next-line @typescript-eslint/no-extraneous-class
+  class ChargingStationWorker<Data extends ChargingStationWorkerData> {
+    constructor () {
+      parentPort?.on('message', (message: WorkerMessage<Data>) => {
+        switch (message.event) {
+          case WorkerMessageEvents.addWorkerElement:
+            try {
+              const chargingStation = new ChargingStation(
+                message.data.index,
+                message.data.templateFile
+              )
+              parentPort?.postMessage({
+                event: WorkerMessageEvents.addedWorkerElement,
+                data: buildChargingStationDataPayload(chargingStation)
+              } satisfies ChargingStationWorkerMessage<ChargingStationData>)
+            } catch (error) {
+              parentPort?.postMessage({
+                event: WorkerMessageEvents.workerElementError,
+                data: {
+                  event: WorkerMessageEvents.addWorkerElement,
+                  name: (error as Error).name,
+                  message: (error as Error).message,
+                  stack: (error as Error).stack
+                }
+              } satisfies ChargingStationWorkerMessage<ChargingStationWorkerEventError>)
+            }
+            break
+          default:
+            throw new BaseError(
+              `Unknown worker event: '${message.event}' received with data: '${JSON.stringify(
+                message.data,
+                undefined,
+                2
+              )}'`
+            )
+        }
+      })
+    }
+  }
+  chargingStationWorker = new ChargingStationWorker<ChargingStationWorkerData>()
 }