refactor: cleanup configuration class usage
authorJérôme Benoit <jerome.benoit@sap.com>
Mon, 17 Jul 2023 16:25:36 +0000 (18:25 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Mon, 17 Jul 2023 16:25:36 +0000 (18:25 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/Bootstrap.ts
src/charging-station/ui-server/UIServerFactory.ts
src/performance/PerformanceStatistics.ts
src/utils/Logger.ts

index 2c5d6a7d532b7f7d1eefabd17d8e8923b0c8e08f..957a2f6feefa1882f568a5af9cda192909dc7d10 100644 (file)
@@ -82,21 +82,19 @@ export class Bootstrap extends EventEmitter {
       dirname(fileURLToPath(import.meta.url)),
       `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`,
     );
-    Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
-      .enabled === true &&
-      (this.uiServer = UIServerFactory.getUIServerImplementation(
-        Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer),
-      ));
-    Configuration.getConfigurationSection<StorageConfiguration>(
-      ConfigurationSection.performanceStorage,
-    ).enabled === true &&
+    const uiServerConfiguration = Configuration.getConfigurationSection<UIServerConfiguration>(
+      ConfigurationSection.uiServer,
+    );
+    uiServerConfiguration.enabled === true &&
+      (this.uiServer = UIServerFactory.getUIServerImplementation(uiServerConfiguration));
+    const performanceStorageConfiguration =
+      Configuration.getConfigurationSection<StorageConfiguration>(
+        ConfigurationSection.performanceStorage,
+      );
+    performanceStorageConfiguration.enabled === true &&
       (this.storage = StorageFactory.getStorage(
-        Configuration.getConfigurationSection<StorageConfiguration>(
-          ConfigurationSection.performanceStorage,
-        ).type!,
-        Configuration.getConfigurationSection<StorageConfiguration>(
-          ConfigurationSection.performanceStorage,
-        ).uri!,
+        performanceStorageConfiguration.type!,
+        performanceStorageConfiguration.uri!,
         this.logPrefix(),
       ));
     Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
@@ -117,7 +115,10 @@ export class Bootstrap extends EventEmitter {
       if (this.starting === false) {
         this.starting = true;
         this.initializeCounters();
-        this.initializeWorkerImplementation();
+        const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>(
+          ConfigurationSection.worker,
+        );
+        this.initializeWorkerImplementation(workerConfiguration);
         await this.workerImplementation?.start();
         await this.storage?.open();
         this.uiServer?.start();
@@ -143,21 +144,13 @@ export class Bootstrap extends EventEmitter {
               this.version
             } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
               Configuration.workerDynamicPoolInUse()
-                ? `${Configuration.getConfigurationSection<WorkerConfiguration>(
-                    ConfigurationSection.worker,
-                  ).poolMinSize?.toString()}/`
+                ? `${workerConfiguration.poolMinSize?.toString()}/`
                 : ''
             }${this.workerImplementation?.size}${
               Configuration.workerPoolInUse()
-                ? `/${Configuration.getConfigurationSection<WorkerConfiguration>(
-                    ConfigurationSection.worker,
-                  ).poolMaxSize?.toString()}`
+                ? `/${workerConfiguration.poolMaxSize?.toString()}`
                 : ''
-            } worker(s) concurrently running in '${
-              Configuration.getConfigurationSection<WorkerConfiguration>(
-                ConfigurationSection.worker,
-              ).processType
-            }' mode${
+            } worker(s) concurrently running in '${workerConfiguration.processType}' mode${
               !isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
                 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)`
                 : ''
@@ -232,12 +225,9 @@ export class Bootstrap extends EventEmitter {
     await this.start();
   }
 
-  private initializeWorkerImplementation(): void {
+  private initializeWorkerImplementation(workerConfiguration: WorkerConfiguration): void {
     let elementsPerWorker: number | undefined;
-    if (
-      Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
-        ?.elementsPerWorker === 'auto'
-    ) {
+    if (workerConfiguration?.elementsPerWorker === 'auto') {
       elementsPerWorker =
         this.numberOfChargingStations > availableParallelism()
           ? Math.round(this.numberOfChargingStations / availableParallelism())
@@ -246,25 +236,13 @@ export class Bootstrap extends EventEmitter {
     this.workerImplementation === null &&
       (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
         this.workerScript,
-        Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
-          .processType!,
+        workerConfiguration.processType!,
         {
-          workerStartDelay: Configuration.getConfigurationSection<WorkerConfiguration>(
-            ConfigurationSection.worker,
-          ).startDelay,
-          elementStartDelay: Configuration.getConfigurationSection<WorkerConfiguration>(
-            ConfigurationSection.worker,
-          ).elementStartDelay,
-          poolMaxSize: Configuration.getConfigurationSection<WorkerConfiguration>(
-            ConfigurationSection.worker,
-          ).poolMaxSize!,
-          poolMinSize: Configuration.getConfigurationSection<WorkerConfiguration>(
-            ConfigurationSection.worker,
-          ).poolMinSize!,
-          elementsPerWorker:
-            elementsPerWorker ??
-            (Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
-              .elementsPerWorker as number),
+          workerStartDelay: workerConfiguration.startDelay,
+          elementStartDelay: workerConfiguration.elementStartDelay,
+          poolMaxSize: workerConfiguration.poolMaxSize!,
+          poolMinSize: workerConfiguration.poolMinSize!,
+          elementsPerWorker: elementsPerWorker ?? (workerConfiguration.elementsPerWorker as number),
           poolOptions: {
             messageHandler: this.messageHandler.bind(this) as (message: unknown) => void,
           },
index 2a6b521e42446cf0713b3a138db2051bf5eb53ba..c4006b0396d96c8d5ad50e902bfedf8ea2743c65 100644 (file)
@@ -4,8 +4,7 @@ import type { AbstractUIServer } from './AbstractUIServer';
 import { UIHttpServer } from './UIHttpServer';
 import { UIServerUtils } from './UIServerUtils';
 import { UIWebSocketServer } from './UIWebSocketServer';
-import { ApplicationProtocol, ConfigurationSection, type UIServerConfiguration } from '../../types';
-import { Configuration } from '../../utils';
+import { ApplicationProtocol, type UIServerConfiguration } from '../../types';
 
 export class UIServerFactory {
   private constructor() {
@@ -13,34 +12,20 @@ export class UIServerFactory {
   }
 
   public static getUIServerImplementation(
-    uiServerConfiguration?: UIServerConfiguration,
+    uiServerConfiguration: UIServerConfiguration,
   ): AbstractUIServer | null {
-    if (UIServerUtils.isLoopback(uiServerConfiguration!.options!.host!) === false) {
+    if (UIServerUtils.isLoopback(uiServerConfiguration.options!.host!) === false) {
       console.warn(
         chalk.yellow(
           'Loopback address not detected in UI server configuration. This is not recommended.',
         ),
       );
     }
-    switch (
-      uiServerConfiguration?.type ??
-      Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
-        .type
-    ) {
+    switch (uiServerConfiguration.type) {
       case ApplicationProtocol.WS:
-        return new UIWebSocketServer(
-          uiServerConfiguration ??
-            Configuration.getConfigurationSection<UIServerConfiguration>(
-              ConfigurationSection.uiServer,
-            ),
-        );
+        return new UIWebSocketServer(uiServerConfiguration);
       case ApplicationProtocol.HTTP:
-        return new UIHttpServer(
-          uiServerConfiguration ??
-            Configuration.getConfigurationSection<UIServerConfiguration>(
-              ConfigurationSection.uiServer,
-            ),
-        );
+        return new UIHttpServer(uiServerConfiguration);
       default:
         return null;
     }
index 6471265efa45136e3bf03c75f43de1ea58b54163..479fe0710b26b65797a3df973c99c744d8e6ba3c 100644 (file)
@@ -131,20 +131,14 @@ export class PerformanceStatistics {
 
   public start(): void {
     this.startLogStatisticsInterval();
-    if (
+    const performanceStorageConfiguration =
       Configuration.getConfigurationSection<StorageConfiguration>(
         ConfigurationSection.performanceStorage,
-      ).enabled
-    ) {
+      );
+    if (performanceStorageConfiguration.enabled) {
       logger.info(
-        `${this.logPrefix()} storage enabled: type ${
-          Configuration.getConfigurationSection<StorageConfiguration>(
-            ConfigurationSection.performanceStorage,
-          ).type
-        }, uri: ${
-          Configuration.getConfigurationSection<StorageConfiguration>(
-            ConfigurationSection.performanceStorage,
-          ).uri
+        `${this.logPrefix()} storage enabled: type ${performanceStorageConfiguration.type}, uri: ${
+          performanceStorageConfiguration.uri
         }`,
       );
     }
@@ -182,11 +176,11 @@ export class PerformanceStatistics {
   }
 
   private startLogStatisticsInterval(): void {
-    const logStatisticsInterval = Configuration.getConfigurationSection<LogConfiguration>(
+    const logConfiguration = Configuration.getConfigurationSection<LogConfiguration>(
       ConfigurationSection.log,
-    ).enabled
-      ? Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
-          .statisticsInterval!
+    );
+    const logStatisticsInterval = logConfiguration.enabled
+      ? logConfiguration.statisticsInterval!
       : 0;
     if (logStatisticsInterval > 0 && !this.displayInterval) {
       this.displayInterval = setInterval(() => {
@@ -199,9 +193,7 @@ export class PerformanceStatistics {
       logger.info(
         `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`,
       );
-    } else if (
-      Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).enabled
-    ) {
+    } else if (logConfiguration.enabled) {
       logger.info(
         `${this.logPrefix()} log interval is set to ${logStatisticsInterval?.toString()}. Not logging statistics`,
       );
index 1e22e4050293eeb6c43d295d6d79933723feeef3..6ea286b2b23d0b0a5cab66e10f24e7012d24f249 100644 (file)
@@ -7,38 +7,26 @@ import { Configuration } from './Configuration';
 import { insertAt } from './Utils';
 import { ConfigurationSection, type LogConfiguration } from '../types';
 
+const logConfiguration = Configuration.getConfigurationSection<LogConfiguration>(
+  ConfigurationSection.log,
+);
 let transports: transport[];
-if (
-  Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).rotate === true
-) {
-  const logMaxFiles = Configuration.getConfigurationSection<LogConfiguration>(
-    ConfigurationSection.log,
-  ).maxFiles;
-  const logMaxSize = Configuration.getConfigurationSection<LogConfiguration>(
-    ConfigurationSection.log,
-  ).maxSize;
+if (logConfiguration.rotate === true) {
+  const logMaxFiles = logConfiguration.maxFiles;
+  const logMaxSize = logConfiguration.maxSize;
   transports = [
     new DailyRotateFile({
       filename: insertAt(
-        Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
-          .errorFile!,
+        logConfiguration.errorFile!,
         '-%DATE%',
-        Configuration.getConfigurationSection<LogConfiguration>(
-          ConfigurationSection.log,
-        ).errorFile!.indexOf('.log'),
+        logConfiguration.errorFile!.indexOf('.log'),
       ),
       level: 'error',
       ...(logMaxFiles && { maxFiles: logMaxFiles }),
       ...(logMaxSize && { maxSize: logMaxSize }),
     }),
     new DailyRotateFile({
-      filename: insertAt(
-        Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).file!,
-        '-%DATE%',
-        Configuration.getConfigurationSection<LogConfiguration>(
-          ConfigurationSection.log,
-        ).file!.indexOf('.log'),
-      ),
+      filename: insertAt(logConfiguration.file!, '-%DATE%', logConfiguration.file!.indexOf('.log')),
       ...(logMaxFiles && { maxFiles: logMaxFiles }),
       ...(logMaxSize && { maxSize: logMaxSize }),
     }),
@@ -46,29 +34,19 @@ if (
 } else {
   transports = [
     new TransportType.File({
-      filename: Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
-        .errorFile,
+      filename: logConfiguration.errorFile,
       level: 'error',
     }),
     new TransportType.File({
-      filename: Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
-        .file,
+      filename: logConfiguration.file,
     }),
   ];
 }
 
 export const logger = createLogger({
-  silent: !Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
-    .enabled,
-  level: Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).level,
-  format: format.combine(
-    format.splat(),
-    (
-      format[
-        Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).format!
-      ] as FormatWrap
-    )(),
-  ),
+  silent: !logConfiguration.enabled,
+  level: logConfiguration.level,
+  format: format.combine(format.splat(), (format[logConfiguration.format!] as FormatWrap)()),
   transports,
 });
 
@@ -76,18 +54,10 @@ export const logger = createLogger({
 // If enabled, log to the `console` with the format:
 // `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
 //
-if (Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).console) {
+if (logConfiguration.console) {
   logger.add(
     new TransportType.Console({
-      format: format.combine(
-        format.splat(),
-        (
-          format[
-            Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
-              .format!
-          ] as FormatWrap
-        )(),
-      ),
+      format: format.combine(format.splat(), (format[logConfiguration.format!] as FormatWrap)()),
     }),
   );
 }