feat: ensure charging station add op return its station info
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
index 545e88899da9a91629e3736d5025670f8b26c263..4f72d6dfdffef0ca7a65cb24a2103f19558ced6f 100644 (file)
@@ -15,6 +15,7 @@ import { BaseError } from '../exception/index.js'
 import { type Storage, StorageFactory } from '../performance/index.js'
 import {
   type ChargingStationData,
+  type ChargingStationInfo,
   type ChargingStationOptions,
   type ChargingStationWorkerData,
   type ChargingStationWorkerEventError,
@@ -59,12 +60,11 @@ enum exitCodes {
 
 export class Bootstrap extends EventEmitter {
   private static instance: Bootstrap | null = null
-  private workerImplementation?: WorkerAbstract<ChargingStationWorkerData>
+  private workerImplementation?: WorkerAbstract<ChargingStationWorkerData, ChargingStationInfo>
   private readonly uiServer: AbstractUIServer
   private storage?: Storage
   private readonly templateStatistics: Map<string, TemplateStatistics>
   private readonly version: string = version
-  private initializedCounters: boolean
   private started: boolean
   private starting: boolean
   private stopping: boolean
@@ -82,12 +82,14 @@ export class Bootstrap extends EventEmitter {
     this.starting = false
     this.stopping = false
     this.uiServerStarted = false
+    this.templateStatistics = new Map<string, TemplateStatistics>()
     this.uiServer = UIServerFactory.getUIServerImplementation(
       Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
     )
-    this.templateStatistics = new Map<string, TemplateStatistics>()
-    this.initializedCounters = false
     this.initializeCounters()
+    this.initializeWorkerImplementation(
+      Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
+    )
     Configuration.configurationChangeCallback = async () => {
       if (isMainThread) {
         await Bootstrap.getInstance().restart()
@@ -174,12 +176,12 @@ export class Bootstrap extends EventEmitter {
             )
           }
         )
-        this.initializeCounters()
-        const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>(
-          ConfigurationSection.worker
-        )
-        this.initializeWorkerImplementation(workerConfiguration)
-        await this.workerImplementation?.start()
+        // eslint-disable-next-line @typescript-eslint/unbound-method
+        if (isAsyncFunction(this.workerImplementation?.start)) {
+          await this.workerImplementation.start()
+        } else {
+          (this.workerImplementation?.start as () => void)()
+        }
         const performanceStorageConfiguration =
           Configuration.getConfigurationSection<StorageConfiguration>(
             ConfigurationSection.performanceStorage
@@ -220,6 +222,9 @@ export class Bootstrap extends EventEmitter {
             )
           }
         }
+        const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>(
+          ConfigurationSection.worker
+        )
         console.info(
           chalk.green(
             `Charging stations simulator ${
@@ -269,10 +274,8 @@ export class Bootstrap extends EventEmitter {
           console.error(chalk.red('Error while waiting for charging stations to stop: '), error)
         }
         await this.workerImplementation?.stop()
-        delete this.workerImplementation
         this.removeAllListeners()
         this.uiServer.clearCaches()
-        this.initializedCounters = false
         await this.storage?.close()
         delete this.storage
         this.started = false
@@ -295,6 +298,11 @@ export class Bootstrap extends EventEmitter {
       this.uiServer.stop()
       this.uiServerStarted = false
     }
+    this.initializeCounters()
+    // FIXME: initialize worker implementation only if the worker section has changed
+    this.initializeWorkerImplementation(
+      Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
+    )
     await this.start()
   }
 
@@ -339,7 +347,10 @@ export class Bootstrap extends EventEmitter {
             : 1
         break
     }
-    this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
+    this.workerImplementation = WorkerFactory.getWorkerImplementation<
+    ChargingStationWorkerData,
+    ChargingStationInfo
+    >(
       join(
         dirname(fileURLToPath(import.meta.url)),
         `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`
@@ -356,7 +367,9 @@ export class Bootstrap extends EventEmitter {
         elementsPerWorker,
         poolOptions: {
           messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
-          workerOptions: { resourceLimits: workerConfiguration.resourceLimits }
+          ...(workerConfiguration.resourceLimits != null && {
+            workerOptions: { resourceLimits: workerConfiguration.resourceLimits }
+          })
         }
       }
     )
@@ -487,47 +500,44 @@ export class Bootstrap extends EventEmitter {
   }
 
   private initializeCounters (): void {
-    if (!this.initializedCounters) {
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      const stationTemplateUrls = Configuration.getStationTemplateUrls()!
-      if (isNotEmptyArray(stationTemplateUrls)) {
-        for (const stationTemplateUrl of stationTemplateUrls) {
-          const templateName = buildTemplateName(stationTemplateUrl.file)
-          this.templateStatistics.set(templateName, {
-            configured: stationTemplateUrl.numberOfStations,
-            added: 0,
-            started: 0,
-            indexes: new Set<number>()
-          })
-          this.uiServer.chargingStationTemplates.add(templateName)
-        }
-        if (this.templateStatistics.size !== stationTemplateUrls.length) {
-          console.error(
-            chalk.red(
-              "'stationTemplateUrls' contains duplicate entries, please check your configuration"
-            )
-          )
-          exit(exitCodes.duplicateChargingStationTemplateUrls)
-        }
-      } else {
-        console.error(
-          chalk.red("'stationTemplateUrls' not defined or empty, please check your configuration")
-        )
-        exit(exitCodes.missingChargingStationsConfiguration)
+    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+    const stationTemplateUrls = Configuration.getStationTemplateUrls()!
+    if (isNotEmptyArray(stationTemplateUrls)) {
+      for (const stationTemplateUrl of stationTemplateUrls) {
+        const templateName = buildTemplateName(stationTemplateUrl.file)
+        this.templateStatistics.set(templateName, {
+          configured: stationTemplateUrl.numberOfStations,
+          added: 0,
+          started: 0,
+          indexes: new Set<number>()
+        })
+        this.uiServer.chargingStationTemplates.add(templateName)
       }
-      if (
-        this.numberOfConfiguredChargingStations === 0 &&
-        Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
-          .enabled !== true
-      ) {
+      if (this.templateStatistics.size !== stationTemplateUrls.length) {
         console.error(
           chalk.red(
-            "'stationTemplateUrls' has no charging station enabled and UI server is disabled, please check your configuration"
+            "'stationTemplateUrls' contains duplicate entries, please check your configuration"
           )
         )
-        exit(exitCodes.noChargingStationTemplates)
+        exit(exitCodes.duplicateChargingStationTemplateUrls)
       }
-      this.initializedCounters = true
+    } else {
+      console.error(
+        chalk.red("'stationTemplateUrls' not defined or empty, please check your configuration")
+      )
+      exit(exitCodes.missingChargingStationsConfiguration)
+    }
+    if (
+      this.numberOfConfiguredChargingStations === 0 &&
+      Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
+        .enabled !== true
+    ) {
+      console.error(
+        chalk.red(
+          "'stationTemplateUrls' has no charging station enabled and UI server is disabled, please check your configuration"
+        )
+      )
+      exit(exitCodes.noChargingStationTemplates)
     }
   }
 
@@ -535,13 +545,13 @@ export class Bootstrap extends EventEmitter {
     index: number,
     templateFile: string,
     options?: ChargingStationOptions
-  ): Promise<void> {
+  ): Promise<ChargingStationInfo | undefined> {
     if (!this.started && !this.starting) {
       throw new BaseError(
         'Cannot add charging station while the charging stations simulator is not started'
       )
     }
-    await this.workerImplementation?.addElement({
+    const stationInfo = await this.workerImplementation?.addElement({
       index,
       templateFile: join(
         dirname(fileURLToPath(import.meta.url)),
@@ -555,6 +565,7 @@ export class Bootstrap extends EventEmitter {
     const templateStatistics = this.templateStatistics.get(buildTemplateName(templateFile))!
     ++templateStatistics.added
     templateStatistics.indexes.add(index)
+    return stationInfo
   }
 
   private gracefulShutdown (): void {