Fix GH actions run on dependabot PRs.
[e-mobility-charging-stations-simulator.git] / src / charging-station / StationWorker.ts
index 68c3ea24c0f96c4def2f5c187050bd5e816dc04b..c3c5cb51346ce2f36f843f816c29eb27abbdb524 100644 (file)
@@ -1,8 +1,42 @@
-import { isMainThread, workerData } from 'worker_threads';
+// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
+
+import { StationWorkerData, WorkerEvents } from '../types/Worker';
+import { parentPort, workerData } from 'worker_threads';
 
 import ChargingStation from './ChargingStation';
+import Constants from '../utils/Constants';
+import { ThreadWorker } from 'poolifier';
+import Utils from '../utils/Utils';
+
+// Conditionally export ThreadWorker instance for pool usage
+export let threadWorker: ThreadWorker;
+if (Utils.workerPoolInUse()) {
+  threadWorker = new ThreadWorker<StationWorkerData>(startChargingStation, { maxInactiveTime: Constants.WORKER_POOL_MAX_INACTIVE_TIME, async: false });
+} else {
+  // Add message listener to start charging station from main thread
+  addMessageListener();
+  if (!Utils.isUndefined(workerData)) {
+    startChargingStation({ index: workerData.index as number, templateFile: workerData.templateFile as string });
+  }
+}
+
+/**
+ * Listen messages send by the main thread
+ */
+function addMessageListener(): void {
+  parentPort?.on('message', (message) => {
+    if (message.id === WorkerEvents.START_WORKER_ELEMENT) {
+      startChargingStation(message.workerData);
+    }
+  });
+}
 
-if (!isMainThread) {
-  const station = new ChargingStation(workerData.index as number, workerData.templateFile as string);
+/**
+ * Create and start a charging station instance
+ *
+ * @param {StationWorkerData} data workerData
+ */
+function startChargingStation(data: StationWorkerData): void {
+  const station = new ChargingStation(data.index, data.templateFile);
   station.start();
 }