UI Server: rename defaults constants
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
index 6da954d16deb65044ce02544dd119580a272a14d..4fc46b059ffa9dfa1aa5ce4c99883e758eb12c68 100644 (file)
@@ -1,26 +1,29 @@
-import ConfigurationData, {
-  StationTemplateUrl,
-  StorageConfiguration,
+import fs from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+import chalk from 'chalk';
+
+import {
+  type ConfigurationData,
+  type StationTemplateUrl,
+  type StorageConfiguration,
   SupervisionUrlDistribution,
-  UIWebSocketServerConfiguration,
+  type UIServerConfiguration,
+  type WorkerConfiguration,
 } from '../types/ConfigurationData';
-
-import Constants from './Constants';
-import { EmptyObject } from '../types/EmptyObject';
+import type { EmptyObject } from '../types/EmptyObject';
+import type { HandleErrorParams } from '../types/Error';
 import { FileType } from '../types/FileType';
-import { HandleErrorParams } from '../types/Error';
-import { ServerOptions } from 'ws';
 import { StorageType } from '../types/Storage';
-import type { WorkerChoiceStrategy } from 'poolifier';
-import WorkerConstants from '../worker/WorkerConstants';
+import { ApplicationProtocol } from '../types/UIProtocol';
 import { WorkerProcessType } from '../types/Worker';
-import chalk from 'chalk';
-import fs from 'fs';
-import path from 'path';
+import WorkerConstants from '../worker/WorkerConstants';
+import Constants from './Constants';
 
 export default class Configuration {
   private static configurationFile = path.join(
-    path.resolve(__dirname, '../'),
+    path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
     'assets',
     'config.json'
   );
@@ -29,6 +32,10 @@ export default class Configuration {
   private static configuration: ConfigurationData | null = null;
   private static configurationChangeCallback: () => Promise<void>;
 
+  private constructor() {
+    // This is intentional
+  }
+
   static setConfigurationChangeCallback(cb: () => Promise<void>): void {
     Configuration.configurationChangeCallback = cb;
   }
@@ -42,44 +49,34 @@ export default class Configuration {
     // Read conf
     return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval')
       ? Configuration.getConfig().logStatisticsInterval
-      : 60;
+      : Constants.DEFAULT_LOG_STATISTICS_INTERVAL;
   }
 
-  static getUIWebSocketServer(): UIWebSocketServerConfiguration {
-    let options: ServerOptions = {
-      host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
-      port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT,
-    };
-    let uiWebSocketServerConfiguration: UIWebSocketServerConfiguration = {
-      enabled: true,
-      options,
-    };
+  static getUIServer(): UIServerConfiguration {
     if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiWebSocketServer')) {
-      if (
-        Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'options')
-      ) {
-        options = {
-          ...options,
-          ...(Configuration.objectHasOwnProperty(
-            Configuration.getConfig().uiWebSocketServer.options,
-            'host'
-          ) && { host: Configuration.getConfig().uiWebSocketServer.options.host }),
-          ...(Configuration.objectHasOwnProperty(
-            Configuration.getConfig().uiWebSocketServer.options,
-            'port'
-          ) && { port: Configuration.getConfig().uiWebSocketServer.options.port }),
-        };
-      }
-      uiWebSocketServerConfiguration = {
-        ...uiWebSocketServerConfiguration,
-        ...(Configuration.objectHasOwnProperty(
-          Configuration.getConfig().uiWebSocketServer,
-          'enabled'
-        ) && { enabled: Configuration.getConfig().uiWebSocketServer.enabled }),
-        options,
-      };
+      console.error(
+        chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration section 'uiWebSocketServer' usage. Use 'uiServer' instead}`
+      );
     }
-    return uiWebSocketServerConfiguration;
+    let uiServerConfiguration: UIServerConfiguration = {
+      enabled: false,
+      type: ApplicationProtocol.WS,
+      options: {
+        host: Constants.DEFAULT_UI_SERVER_HOST,
+        port: Constants.DEFAULT_UI_SERVER_PORT,
+      },
+    };
+    if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiServer')) {
+      uiServerConfiguration = Configuration.deepMerge(
+        uiServerConfiguration,
+        Configuration.getConfig().uiServer
+      );
+    }
+    if (Configuration.isCFEnvironment() === true) {
+      delete uiServerConfiguration.options.host;
+      uiServerConfiguration.options.port = parseInt(process.env.PORT);
+    }
+    return uiServerConfiguration;
   }
 
   static getPerformanceStorage(): StorageConfiguration {
@@ -92,22 +89,7 @@ export default class Configuration {
     if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
       storageConfiguration = {
         ...storageConfiguration,
-        ...(Configuration.objectHasOwnProperty(
-          Configuration.getConfig().performanceStorage,
-          'enabled'
-        ) && { enabled: Configuration.getConfig().performanceStorage.enabled }),
-        ...(Configuration.objectHasOwnProperty(
-          Configuration.getConfig().performanceStorage,
-          'type'
-        ) && { type: Configuration.getConfig().performanceStorage.type }),
-        ...(Configuration.objectHasOwnProperty(
-          Configuration.getConfig().performanceStorage,
-          'uri'
-        ) && {
-          uri: this.getDefaultPerformanceStorageUri(
-            Configuration.getConfig()?.performanceStorage?.type ?? StorageType.JSON_FILE
-          ),
-        }),
+        ...Configuration.getConfig().performanceStorage,
       };
     }
     return storageConfiguration;
@@ -158,57 +140,89 @@ export default class Configuration {
     return Configuration.getConfig().stationTemplateUrls;
   }
 
-  static getWorkerProcess(): WorkerProcessType {
+  static getWorker(): WorkerConfiguration {
     Configuration.warnDeprecatedConfigurationKey(
-      'useWorkerPool;',
+      'useWorkerPool',
       null,
-      "Use 'workerProcess' to define the type of worker process to use instead"
+      "Use 'worker' section to define the type of worker process model instead"
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'workerProcess',
+      null,
+      "Use 'worker' section to define the type of worker process model instead"
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'workerStartDelay',
+      null,
+      "Use 'worker' section to define the worker start delay instead"
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'chargingStationsPerWorker',
+      null,
+      "Use 'worker' section to define the number of element(s) per worker instead"
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'elementStartDelay',
+      null,
+      "Use 'worker' section to define the worker's element start delay instead"
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'workerPoolMinSize',
+      null,
+      "Use 'worker' section to define the worker pool minimum size instead"
     );
-    return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess')
-      ? Configuration.getConfig().workerProcess
-      : WorkerProcessType.WORKER_SET;
-  }
-
-  static getWorkerStartDelay(): number {
-    return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay')
-      ? Configuration.getConfig().workerStartDelay
-      : WorkerConstants.DEFAULT_WORKER_START_DELAY;
-  }
-
-  static getElementStartDelay(): number {
-    return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'elementStartDelay')
-      ? Configuration.getConfig().elementStartDelay
-      : WorkerConstants.DEFAULT_ELEMENT_START_DELAY;
-  }
-
-  static getWorkerPoolMinSize(): number {
-    return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize')
-      ? Configuration.getConfig().workerPoolMinSize
-      : WorkerConstants.DEFAULT_POOL_MIN_SIZE;
-  }
-
-  static getWorkerPoolMaxSize(): number {
     Configuration.warnDeprecatedConfigurationKey(
       'workerPoolSize;',
       null,
-      "Use 'workerPoolMaxSize' instead"
+      "Use 'worker' section to define the worker pool maximum size instead"
     );
-    return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize')
-      ? Configuration.getConfig().workerPoolMaxSize
-      : WorkerConstants.DEFAULT_POOL_MAX_SIZE;
-  }
-
-  static getWorkerPoolStrategy(): WorkerChoiceStrategy {
-    return Configuration.getConfig().workerPoolStrategy;
-  }
-
-  static getChargingStationsPerWorker(): number {
-    return Configuration.objectHasOwnProperty(
-      Configuration.getConfig(),
-      'chargingStationsPerWorker'
-    )
-      ? Configuration.getConfig().chargingStationsPerWorker
-      : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER;
+    Configuration.warnDeprecatedConfigurationKey(
+      'workerPoolMaxSize;',
+      null,
+      "Use 'worker' section to define the worker pool maximum size instead"
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'workerPoolStrategy;',
+      null,
+      "Use 'worker' section to define the worker pool strategy instead"
+    );
+    let workerConfiguration: WorkerConfiguration = {
+      processType: Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess')
+        ? Configuration.getConfig().workerProcess
+        : WorkerProcessType.WORKER_SET,
+      startDelay: Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay')
+        ? Configuration.getConfig().workerStartDelay
+        : WorkerConstants.DEFAULT_WORKER_START_DELAY,
+      elementsPerWorker: Configuration.objectHasOwnProperty(
+        Configuration.getConfig(),
+        'chargingStationsPerWorker'
+      )
+        ? Configuration.getConfig().chargingStationsPerWorker
+        : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER,
+      elementStartDelay: Configuration.objectHasOwnProperty(
+        Configuration.getConfig(),
+        'elementStartDelay'
+      )
+        ? Configuration.getConfig().elementStartDelay
+        : WorkerConstants.DEFAULT_ELEMENT_START_DELAY,
+      poolMinSize: Configuration.objectHasOwnProperty(
+        Configuration.getConfig(),
+        'workerPoolMinSize'
+      )
+        ? Configuration.getConfig().workerPoolMinSize
+        : WorkerConstants.DEFAULT_POOL_MIN_SIZE,
+      poolMaxSize: Configuration.objectHasOwnProperty(
+        Configuration.getConfig(),
+        'workerPoolMaxSize'
+      )
+        ? Configuration.getConfig().workerPoolMaxSize
+        : WorkerConstants.DEFAULT_POOL_MAX_SIZE,
+      poolStrategy: Configuration.getConfig().workerPoolStrategy,
+    };
+    if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'worker')) {
+      workerConfiguration = { ...workerConfiguration, ...Configuration.getConfig().worker };
+    }
+    return workerConfiguration;
   }
 
   static getLogConsole(): boolean {
@@ -363,21 +377,32 @@ export default class Configuration {
     }
   }
 
+  private static isCFEnvironment(): boolean {
+    return process.env.VCAP_APPLICATION !== undefined;
+  }
+
   private static getDefaultPerformanceStorageUri(storageType: StorageType) {
     const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
     switch (storageType) {
       case StorageType.JSON_FILE:
         return `file://${path.join(
-          path.resolve(__dirname, '../../'),
+          path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'),
           Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME
         )}`;
       case StorageType.SQLITE:
-        return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
+        return `file://${path.join(
+          path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'),
+          SQLiteFileName
+        )}`;
       default:
         throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
     }
   }
 
+  private static isObject(item): boolean {
+    return item && typeof item === 'object' && Array.isArray(item) === false;
+  }
+
   private static objectHasOwnProperty(object: unknown, property: string): boolean {
     return Object.prototype.hasOwnProperty.call(object, property) as boolean;
   }
@@ -386,6 +411,29 @@ export default class Configuration {
     return typeof obj === 'undefined';
   }
 
+  private static deepMerge(target: object, ...sources: object[]): object {
+    if (!sources.length) {
+      return target;
+    }
+    const source = sources.shift();
+
+    if (Configuration.isObject(target) && Configuration.isObject(source)) {
+      for (const key in source) {
+        if (Configuration.isObject(source[key])) {
+          if (!target[key]) {
+            Object.assign(target, { [key]: {} });
+          }
+          // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
+          Configuration.deepMerge(target[key], source[key]);
+        } else {
+          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+          Object.assign(target, { [key]: source[key] });
+        }
+      }
+    }
+    return Configuration.deepMerge(target, ...sources);
+  }
+
   private static handleFileException(
     logPrefix: string,
     fileType: FileType,