fix: fix worker configuration merge issue
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
index faa29e6859abeb94881ae1ddb06fec951b4127c6..64953a9687a8f730a233ce7517ffa1f2842bbd3c 100644 (file)
@@ -5,14 +5,11 @@ import { dirname, extname, join } from 'node:path'
 import process, { exit } from 'node:process'
 import { fileURLToPath } from 'node:url'
 import { isMainThread } from 'node:worker_threads'
-import type { Worker } from 'worker_threads'
 
 import chalk from 'chalk'
-import { type MessageHandler, availableParallelism } from 'poolifier'
+import { availableParallelism, type MessageHandler } from 'poolifier'
+import type { Worker } from 'worker_threads'
 
-import { buildTemplateName, waitChargingStationEvents } from './Helpers.js'
-import type { AbstractUIServer } from './ui-server/AbstractUIServer.js'
-import { UIServerFactory } from './ui-server/UIServerFactory.js'
 import { version } from '../../package.json'
 import { BaseError } from '../exception/index.js'
 import { type Storage, StorageFactory } from '../performance/index.js'
@@ -25,28 +22,30 @@ import {
   type ChargingStationWorkerMessageData,
   ChargingStationWorkerMessageEvents,
   ConfigurationSection,
-  type InternalTemplateStatistics,
   ProcedureName,
   type SimulatorState,
   type Statistics,
   type StorageConfiguration,
+  type TemplateStatistics,
   type UIServerConfiguration,
   type WorkerConfiguration
 } from '../types/index.js'
 import {
   Configuration,
   Constants,
-  buildTemplateStatisticsPayload,
   formatDurationMilliSeconds,
   generateUUID,
   handleUncaughtException,
   handleUnhandledRejection,
   isAsyncFunction,
   isNotEmptyArray,
-  logPrefix,
-  logger
+  logger,
+  logPrefix
 } from '../utils/index.js'
 import { type WorkerAbstract, WorkerFactory } from '../worker/index.js'
+import { buildTemplateName, waitChargingStationEvents } from './Helpers.js'
+import type { AbstractUIServer } from './ui-server/AbstractUIServer.js'
+import { UIServerFactory } from './ui-server/UIServerFactory.js'
 
 const moduleName = 'Bootstrap'
 
@@ -63,7 +62,7 @@ export class Bootstrap extends EventEmitter {
   private workerImplementation?: WorkerAbstract<ChargingStationWorkerData>
   private readonly uiServer: AbstractUIServer
   private storage?: Storage
-  private readonly templateStatistics: Map<string, InternalTemplateStatistics>
+  private readonly templateStatistics: Map<string, TemplateStatistics>
   private readonly version: string = version
   private initializedCounters: boolean
   private started: boolean
@@ -82,12 +81,15 @@ export class Bootstrap extends EventEmitter {
     this.started = false
     this.starting = false
     this.stopping = false
+    this.initializedCounters = false
     this.uiServerStarted = false
+    this.templateStatistics = new Map<string, TemplateStatistics>()
+    this.initializeWorkerImplementation(
+      Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
+    )
     this.uiServer = UIServerFactory.getUIServerImplementation(
       Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
     )
-    this.templateStatistics = new Map<string, InternalTemplateStatistics>()
-    this.initializedCounters = false
     this.initializeCounters()
     Configuration.configurationChangeCallback = async () => {
       if (isMainThread) {
@@ -118,7 +120,7 @@ export class Bootstrap extends EventEmitter {
     return {
       version: this.version,
       started: this.started,
-      templateStatistics: buildTemplateStatisticsPayload(this.templateStatistics)
+      templateStatistics: this.templateStatistics
     }
   }
 
@@ -176,11 +178,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
@@ -221,6 +224,9 @@ export class Bootstrap extends EventEmitter {
             )
           }
         }
+        const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>(
+          ConfigurationSection.worker
+        )
         console.info(
           chalk.green(
             `Charging stations simulator ${
@@ -270,7 +276,6 @@ 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
@@ -288,6 +293,10 @@ export class Bootstrap extends EventEmitter {
 
   private async restart (): Promise<void> {
     await this.stop()
+    // FIXME: initialize worker implementation only if the worker section has changed
+    this.initializeWorkerImplementation(
+      Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
+    )
     if (
       this.uiServerStarted &&
       Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
@@ -300,7 +309,7 @@ export class Bootstrap extends EventEmitter {
   }
 
   private async waitChargingStationsStopped (): Promise<string> {
-    return await new Promise<string>((resolve, reject) => {
+    return await new Promise<string>((resolve, reject: (reason?: unknown) => void) => {
       const waitTimeout = setTimeout(() => {
         const timeoutMessage = `Timeout ${formatDurationMilliSeconds(
           Constants.STOP_CHARGING_STATIONS_TIMEOUT
@@ -349,7 +358,7 @@ export class Bootstrap extends EventEmitter {
       workerConfiguration.processType!,
       {
         workerStartDelay: workerConfiguration.startDelay,
-        elementStartDelay: workerConfiguration.elementStartDelay,
+        elementAddDelay: workerConfiguration.elementAddDelay,
         // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
         poolMaxSize: workerConfiguration.poolMaxSize!,
         // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -357,7 +366,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 }
+          })
         }
       }
     )
@@ -572,7 +583,7 @@ export class Bootstrap extends EventEmitter {
             exit(exitCodes.gracefulShutdownError)
           })
       })
-      .catch(error => {
+      .catch((error: unknown) => {
         console.error(chalk.red('Error while shutdowning charging stations simulator: '), error)
         exit(exitCodes.gracefulShutdownError)
       })