fix: fix configuration section caching
authorJérôme Benoit <jerome.benoit@sap.com>
Sun, 16 Jul 2023 22:02:19 +0000 (00:02 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Sun, 16 Jul 2023 22:02:19 +0000 (00:02 +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/types/ConfigurationData.ts
src/types/index.ts
src/utils/Configuration.ts
src/utils/Logger.ts

index 15eb4fcef4ad469736d3d180133698ee7933164a..2c5d6a7d532b7f7d1eefabd17d8e8923b0c8e08f 100644 (file)
@@ -20,9 +20,13 @@ import {
   type ChargingStationWorkerMessage,
   type ChargingStationWorkerMessageData,
   ChargingStationWorkerMessageEvents,
+  ConfigurationSection,
   ProcedureName,
   type StationTemplateUrl,
   type Statistics,
+  type StorageConfiguration,
+  type UIServerConfiguration,
+  type WorkerConfiguration,
 } from '../types';
 import {
   Configuration,
@@ -78,12 +82,21 @@ export class Bootstrap extends EventEmitter {
       dirname(fileURLToPath(import.meta.url)),
       `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`,
     );
-    Configuration.getUIServer().enabled === true &&
-      (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer()));
-    Configuration.getPerformanceStorage().enabled === true &&
+    Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
+      .enabled === true &&
+      (this.uiServer = UIServerFactory.getUIServerImplementation(
+        Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer),
+      ));
+    Configuration.getConfigurationSection<StorageConfiguration>(
+      ConfigurationSection.performanceStorage,
+    ).enabled === true &&
       (this.storage = StorageFactory.getStorage(
-        Configuration.getPerformanceStorage().type!,
-        Configuration.getPerformanceStorage().uri!,
+        Configuration.getConfigurationSection<StorageConfiguration>(
+          ConfigurationSection.performanceStorage,
+        ).type!,
+        Configuration.getConfigurationSection<StorageConfiguration>(
+          ConfigurationSection.performanceStorage,
+        ).uri!,
         this.logPrefix(),
       ));
     Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
@@ -130,13 +143,21 @@ 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.getWorker().poolMinSize?.toString()}/`
+                ? `${Configuration.getConfigurationSection<WorkerConfiguration>(
+                    ConfigurationSection.worker,
+                  ).poolMinSize?.toString()}/`
                 : ''
             }${this.workerImplementation?.size}${
               Configuration.workerPoolInUse()
-                ? `/${Configuration.getWorker().poolMaxSize?.toString()}`
+                ? `/${Configuration.getConfigurationSection<WorkerConfiguration>(
+                    ConfigurationSection.worker,
+                  ).poolMaxSize?.toString()}`
                 : ''
-            } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
+            } worker(s) concurrently running in '${
+              Configuration.getConfigurationSection<WorkerConfiguration>(
+                ConfigurationSection.worker,
+              ).processType
+            }' mode${
               !isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
                 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)`
                 : ''
@@ -213,7 +234,10 @@ export class Bootstrap extends EventEmitter {
 
   private initializeWorkerImplementation(): void {
     let elementsPerWorker: number | undefined;
-    if (Configuration.getWorker()?.elementsPerWorker === 'auto') {
+    if (
+      Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
+        ?.elementsPerWorker === 'auto'
+    ) {
       elementsPerWorker =
         this.numberOfChargingStations > availableParallelism()
           ? Math.round(this.numberOfChargingStations / availableParallelism())
@@ -222,14 +246,25 @@ export class Bootstrap extends EventEmitter {
     this.workerImplementation === null &&
       (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
         this.workerScript,
-        Configuration.getWorker().processType!,
+        Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
+          .processType!,
         {
-          workerStartDelay: Configuration.getWorker().startDelay,
-          elementStartDelay: Configuration.getWorker().elementStartDelay,
-          poolMaxSize: Configuration.getWorker().poolMaxSize!,
-          poolMinSize: Configuration.getWorker().poolMinSize!,
+          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.getWorker().elementsPerWorker as number),
+            elementsPerWorker ??
+            (Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
+              .elementsPerWorker as number),
           poolOptions: {
             messageHandler: this.messageHandler.bind(this) as (message: unknown) => void,
           },
index e0f4a78e25ac62ac9d27a8ea24329d222e8f4cbb..2a6b521e42446cf0713b3a138db2051bf5eb53ba 100644 (file)
@@ -4,7 +4,7 @@ import type { AbstractUIServer } from './AbstractUIServer';
 import { UIHttpServer } from './UIHttpServer';
 import { UIServerUtils } from './UIServerUtils';
 import { UIWebSocketServer } from './UIWebSocketServer';
-import { ApplicationProtocol, type UIServerConfiguration } from '../../types';
+import { ApplicationProtocol, ConfigurationSection, type UIServerConfiguration } from '../../types';
 import { Configuration } from '../../utils';
 
 export class UIServerFactory {
@@ -22,11 +22,25 @@ export class UIServerFactory {
         ),
       );
     }
-    switch (uiServerConfiguration?.type ?? Configuration.getUIServer().type) {
+    switch (
+      uiServerConfiguration?.type ??
+      Configuration.getConfigurationSection<UIServerConfiguration>(ConfigurationSection.uiServer)
+        .type
+    ) {
       case ApplicationProtocol.WS:
-        return new UIWebSocketServer(uiServerConfiguration ?? Configuration.getUIServer());
+        return new UIWebSocketServer(
+          uiServerConfiguration ??
+            Configuration.getConfigurationSection<UIServerConfiguration>(
+              ConfigurationSection.uiServer,
+            ),
+        );
       case ApplicationProtocol.HTTP:
-        return new UIHttpServer(uiServerConfiguration ?? Configuration.getUIServer());
+        return new UIHttpServer(
+          uiServerConfiguration ??
+            Configuration.getConfigurationSection<UIServerConfiguration>(
+              ConfigurationSection.uiServer,
+            ),
+        );
       default:
         return null;
     }
index 4b19e1d787ac6779bab3e2551511924a05e945c2..6471265efa45136e3bf03c75f43de1ea58b54163 100644 (file)
@@ -5,10 +5,13 @@ import type { URL } from 'node:url';
 import { parentPort } from 'node:worker_threads';
 
 import {
+  ConfigurationSection,
   type IncomingRequestCommand,
+  type LogConfiguration,
   MessageType,
   type RequestCommand,
   type Statistics,
+  type StorageConfiguration,
   type TimestampedData,
 } from '../types';
 import {
@@ -128,11 +131,21 @@ export class PerformanceStatistics {
 
   public start(): void {
     this.startLogStatisticsInterval();
-    if (Configuration.getPerformanceStorage().enabled) {
+    if (
+      Configuration.getConfigurationSection<StorageConfiguration>(
+        ConfigurationSection.performanceStorage,
+      ).enabled
+    ) {
       logger.info(
         `${this.logPrefix()} storage enabled: type ${
-          Configuration.getPerformanceStorage().type
-        }, uri: ${Configuration.getPerformanceStorage().uri}`,
+          Configuration.getConfigurationSection<StorageConfiguration>(
+            ConfigurationSection.performanceStorage,
+          ).type
+        }, uri: ${
+          Configuration.getConfigurationSection<StorageConfiguration>(
+            ConfigurationSection.performanceStorage,
+          ).uri
+        }`,
       );
     }
   }
@@ -169,8 +182,11 @@ export class PerformanceStatistics {
   }
 
   private startLogStatisticsInterval(): void {
-    const logStatisticsInterval = Configuration.getLog().enabled
-      ? Configuration.getLog().statisticsInterval!
+    const logStatisticsInterval = Configuration.getConfigurationSection<LogConfiguration>(
+      ConfigurationSection.log,
+    ).enabled
+      ? Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
+          .statisticsInterval!
       : 0;
     if (logStatisticsInterval > 0 && !this.displayInterval) {
       this.displayInterval = setInterval(() => {
@@ -183,7 +199,9 @@ export class PerformanceStatistics {
       logger.info(
         `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`,
       );
-    } else if (Configuration.getLog().enabled) {
+    } else if (
+      Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).enabled
+    ) {
       logger.info(
         `${this.logPrefix()} log interval is set to ${logStatisticsInterval?.toString()}. Not logging statistics`,
       );
@@ -247,7 +265,11 @@ export class PerformanceStatistics {
         this.statistics.statisticsData.get(entryName)!.measurementTimeSeries as TimestampedData[],
       ),
     );
-    if (Configuration.getPerformanceStorage().enabled) {
+    if (
+      Configuration.getConfigurationSection<StorageConfiguration>(
+        ConfigurationSection.performanceStorage,
+      ).enabled
+    ) {
       parentPort?.postMessage(buildPerformanceStatisticsMessage(this.statistics));
     }
   }
index 41d45e4a3ee71639fbc0975e804dc64e59e196b0..ebec3a0d81aa327f5831a8a80a8fd1e8444baa36 100644 (file)
@@ -8,6 +8,13 @@ import type { WorkerProcessType } from '../worker';
 
 type ServerOptions = ListenOptions;
 
+export enum ConfigurationSection {
+  log = 'log',
+  performanceStorage = 'performanceStorage',
+  worker = 'worker',
+  uiServer = 'uiServer',
+}
+
 export enum SupervisionUrlDistribution {
   ROUND_ROBIN = 'round-robin',
   RANDOM = 'random',
index 05828944e90cd87b1517c78a1889c3195cfbdc8d..436941aa8f060527c62499f027884771411deebd 100644 (file)
@@ -167,6 +167,7 @@ export {
 } from './ChargingStationTemplate';
 export {
   type ConfigurationData,
+  ConfigurationSection,
   type LogConfiguration,
   type StationTemplateUrl,
   type StorageConfiguration,
index 544f4a1022ef625404470dfbf427ebcf30443f00..d9c297e99636834542ba74589d173765eb4a1558 100644 (file)
@@ -10,6 +10,7 @@ import { hasOwnProp, isCFEnvironment, isNotEmptyString, isUndefined } from './Ut
 import {
   ApplicationProtocol,
   type ConfigurationData,
+  ConfigurationSection,
   FileType,
   type LogConfiguration,
   type StationTemplateUrl,
@@ -21,13 +22,6 @@ import {
 } from '../types';
 import { WorkerConstants, WorkerProcessType } from '../worker';
 
-enum ConfigurationSection {
-  log = 'log',
-  performanceStorage = 'performanceStorage',
-  worker = 'worker',
-  uiServer = 'uiServer',
-}
-
 export class Configuration {
   private static configurationFile = join(
     dirname(fileURLToPath(import.meta.url)),
@@ -40,7 +34,12 @@ export class Configuration {
   private static configurationSectionCache = new Map<
     ConfigurationSection,
     LogConfiguration | StorageConfiguration | WorkerConfiguration | UIServerConfiguration
-  >();
+  >([
+    [ConfigurationSection.log, Configuration.buildLogSection()],
+    [ConfigurationSection.performanceStorage, Configuration.buildPerformanceStorageSection()],
+    [ConfigurationSection.worker, Configuration.buildWorkerSection()],
+    [ConfigurationSection.uiServer, Configuration.buildUIServerSection()],
+  ]);
 
   private static configurationChangeCallback: () => Promise<void>;
 
@@ -52,7 +51,102 @@ export class Configuration {
     Configuration.configurationChangeCallback = cb;
   }
 
-  public static getUIServer(): UIServerConfiguration {
+  public static getConfigurationSection<T>(sectionName: ConfigurationSection): T {
+    return Configuration.configurationSectionCache.get(sectionName) as T;
+  }
+
+  public static getAutoReconnectMaxRetries(): number | undefined {
+    Configuration.warnDeprecatedConfigurationKey(
+      'autoReconnectTimeout',
+      undefined,
+      "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead",
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'connectionTimeout',
+      undefined,
+      "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead",
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'autoReconnectMaxRetries',
+      undefined,
+      'Use it in charging station template instead',
+    );
+    if (hasOwnProp(Configuration.getConfigurationData(), 'autoReconnectMaxRetries')) {
+      return Configuration.getConfigurationData()?.autoReconnectMaxRetries;
+    }
+  }
+
+  public static getStationTemplateUrls(): StationTemplateUrl[] | undefined {
+    Configuration.warnDeprecatedConfigurationKey(
+      'stationTemplateURLs',
+      undefined,
+      "Use 'stationTemplateUrls' instead",
+    );
+    // eslint-disable-next-line @typescript-eslint/dot-notation
+    !isUndefined(Configuration.getConfigurationData()!['stationTemplateURLs']) &&
+      (Configuration.getConfigurationData()!.stationTemplateUrls =
+        Configuration.getConfigurationData()![
+          // eslint-disable-next-line @typescript-eslint/dot-notation
+          'stationTemplateURLs'
+        ] as StationTemplateUrl[]);
+    Configuration.getConfigurationData()!.stationTemplateUrls.forEach(
+      (stationTemplateUrl: StationTemplateUrl) => {
+        // eslint-disable-next-line @typescript-eslint/dot-notation
+        if (!isUndefined(stationTemplateUrl['numberOfStation'])) {
+          console.error(
+            `${chalk.green(Configuration.logPrefix())} ${chalk.red(
+              `Deprecated configuration key 'numberOfStation' usage for template file '${stationTemplateUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead`,
+            )}`,
+          );
+        }
+      },
+    );
+    return Configuration.getConfigurationData()?.stationTemplateUrls;
+  }
+
+  public static workerPoolInUse(): boolean {
+    return [WorkerProcessType.dynamicPool, WorkerProcessType.staticPool].includes(
+      Configuration.buildWorkerSection().processType!,
+    );
+  }
+
+  public static workerDynamicPoolInUse(): boolean {
+    return Configuration.buildWorkerSection().processType === WorkerProcessType.dynamicPool;
+  }
+
+  public static getSupervisionUrls(): string | string[] | undefined {
+    Configuration.warnDeprecatedConfigurationKey(
+      'supervisionURLs',
+      undefined,
+      "Use 'supervisionUrls' instead",
+    );
+    // eslint-disable-next-line @typescript-eslint/dot-notation
+    if (!isUndefined(Configuration.getConfigurationData()!['supervisionURLs'])) {
+      Configuration.getConfigurationData()!.supervisionUrls = Configuration.getConfigurationData()![
+        // eslint-disable-next-line @typescript-eslint/dot-notation
+        'supervisionURLs'
+      ] as string | string[];
+    }
+    return Configuration.getConfigurationData()?.supervisionUrls;
+  }
+
+  public static getSupervisionUrlDistribution(): SupervisionUrlDistribution | undefined {
+    Configuration.warnDeprecatedConfigurationKey(
+      'distributeStationToTenantEqually',
+      undefined,
+      "Use 'supervisionUrlDistribution' instead",
+    );
+    Configuration.warnDeprecatedConfigurationKey(
+      'distributeStationsToTenantsEqually',
+      undefined,
+      "Use 'supervisionUrlDistribution' instead",
+    );
+    return hasOwnProp(Configuration.getConfigurationData(), 'supervisionUrlDistribution')
+      ? Configuration.getConfigurationData()?.supervisionUrlDistribution
+      : SupervisionUrlDistribution.ROUND_ROBIN;
+  }
+
+  private static buildUIServerSection(): UIServerConfiguration {
     if (hasOwnProp(Configuration.getConfigurationData(), 'uiWebSocketServer')) {
       console.error(
         `${chalk.green(Configuration.logPrefix())} ${chalk.red(
@@ -78,13 +172,10 @@ export class Configuration {
       delete uiServerConfiguration.options?.host;
       uiServerConfiguration.options!.port = parseInt(process.env.PORT!);
     }
-    return Configuration.getConfigurationSection<UIServerConfiguration>(
-      ConfigurationSection.uiServer,
-      uiServerConfiguration,
-    );
+    return uiServerConfiguration;
   }
 
-  public static getPerformanceStorage(): StorageConfiguration {
+  private static buildPerformanceStorageSection(): StorageConfiguration {
     Configuration.warnDeprecatedConfigurationKey(
       'URI',
       ConfigurationSection.performanceStorage,
@@ -108,62 +199,10 @@ export class Configuration {
           }),
       };
     }
-    return Configuration.getConfigurationSection<StorageConfiguration>(
-      ConfigurationSection.performanceStorage,
-      storageConfiguration,
-    );
+    return storageConfiguration;
   }
 
-  public static getAutoReconnectMaxRetries(): number | undefined {
-    Configuration.warnDeprecatedConfigurationKey(
-      'autoReconnectTimeout',
-      undefined,
-      "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead",
-    );
-    Configuration.warnDeprecatedConfigurationKey(
-      'connectionTimeout',
-      undefined,
-      "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead",
-    );
-    Configuration.warnDeprecatedConfigurationKey(
-      'autoReconnectMaxRetries',
-      undefined,
-      'Use it in charging station template instead',
-    );
-    if (hasOwnProp(Configuration.getConfigurationData(), 'autoReconnectMaxRetries')) {
-      return Configuration.getConfigurationData()?.autoReconnectMaxRetries;
-    }
-  }
-
-  public static getStationTemplateUrls(): StationTemplateUrl[] | undefined {
-    Configuration.warnDeprecatedConfigurationKey(
-      'stationTemplateURLs',
-      undefined,
-      "Use 'stationTemplateUrls' instead",
-    );
-    // eslint-disable-next-line @typescript-eslint/dot-notation
-    !isUndefined(Configuration.getConfigurationData()!['stationTemplateURLs']) &&
-      (Configuration.getConfigurationData()!.stationTemplateUrls =
-        Configuration.getConfigurationData()![
-          // eslint-disable-next-line @typescript-eslint/dot-notation
-          'stationTemplateURLs'
-        ] as StationTemplateUrl[]);
-    Configuration.getConfigurationData()!.stationTemplateUrls.forEach(
-      (stationTemplateUrl: StationTemplateUrl) => {
-        // eslint-disable-next-line @typescript-eslint/dot-notation
-        if (!isUndefined(stationTemplateUrl['numberOfStation'])) {
-          console.error(
-            `${chalk.green(Configuration.logPrefix())} ${chalk.red(
-              `Deprecated configuration key 'numberOfStation' usage for template file '${stationTemplateUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead`,
-            )}`,
-          );
-        }
-      },
-    );
-    return Configuration.getConfigurationData()?.stationTemplateUrls;
-  }
-
-  public static getLog(): LogConfiguration {
+  private static buildLogSection(): LogConfiguration {
     Configuration.warnDeprecatedConfigurationKey(
       'logEnabled',
       undefined,
@@ -261,13 +300,10 @@ export class Configuration {
       ...(hasOwnProp(Configuration.getConfigurationData(), ConfigurationSection.log) &&
         Configuration.getConfigurationData()?.log),
     };
-    return Configuration.getConfigurationSection<LogConfiguration>(
-      ConfigurationSection.log,
-      logConfiguration,
-    );
+    return logConfiguration;
   }
 
-  public static getWorker(): WorkerConfiguration {
+  private static buildWorkerSection(): WorkerConfiguration {
     Configuration.warnDeprecatedConfigurationKey(
       'useWorkerPool',
       undefined,
@@ -359,52 +395,7 @@ export class Configuration {
         `Invalid worker process type '${workerConfiguration.processType}' defined in configuration`,
       );
     }
-    return Configuration.getConfigurationSection<WorkerConfiguration>(
-      ConfigurationSection.worker,
-      workerConfiguration,
-    );
-  }
-
-  public static workerPoolInUse(): boolean {
-    return [WorkerProcessType.dynamicPool, WorkerProcessType.staticPool].includes(
-      Configuration.getWorker().processType!,
-    );
-  }
-
-  public static workerDynamicPoolInUse(): boolean {
-    return Configuration.getWorker().processType === WorkerProcessType.dynamicPool;
-  }
-
-  public static getSupervisionUrls(): string | string[] | undefined {
-    Configuration.warnDeprecatedConfigurationKey(
-      'supervisionURLs',
-      undefined,
-      "Use 'supervisionUrls' instead",
-    );
-    // eslint-disable-next-line @typescript-eslint/dot-notation
-    if (!isUndefined(Configuration.getConfigurationData()!['supervisionURLs'])) {
-      Configuration.getConfigurationData()!.supervisionUrls = Configuration.getConfigurationData()![
-        // eslint-disable-next-line @typescript-eslint/dot-notation
-        'supervisionURLs'
-      ] as string | string[];
-    }
-    return Configuration.getConfigurationData()?.supervisionUrls;
-  }
-
-  public static getSupervisionUrlDistribution(): SupervisionUrlDistribution | undefined {
-    Configuration.warnDeprecatedConfigurationKey(
-      'distributeStationToTenantEqually',
-      undefined,
-      "Use 'supervisionUrlDistribution' instead",
-    );
-    Configuration.warnDeprecatedConfigurationKey(
-      'distributeStationsToTenantsEqually',
-      undefined,
-      "Use 'supervisionUrlDistribution' instead",
-    );
-    return hasOwnProp(Configuration.getConfigurationData(), 'supervisionUrlDistribution')
-      ? Configuration.getConfigurationData()?.supervisionUrlDistribution
-      : SupervisionUrlDistribution.ROUND_ROBIN;
+    return workerConfiguration;
   }
 
   private static logPrefix = (): string => {
@@ -441,16 +432,6 @@ export class Configuration {
     }
   }
 
-  private static getConfigurationSection<T>(
-    sectionName: ConfigurationSection,
-    sectionConfiguration?: T,
-  ): T {
-    if (!Configuration.configurationSectionCache.has(sectionName) && sectionConfiguration) {
-      Configuration.configurationSectionCache.set(sectionName, sectionConfiguration);
-    }
-    return Configuration.configurationSectionCache.get(sectionName) as T;
-  }
-
   private static getConfigurationData(): ConfigurationData | null {
     if (!Configuration.configurationData) {
       try {
index a456fa73c2e3248219efad0d09dc0f4803612cf0..1e22e4050293eeb6c43d295d6d79933723feeef3 100644 (file)
@@ -5,17 +5,27 @@ import DailyRotateFile from 'winston-daily-rotate-file';
 
 import { Configuration } from './Configuration';
 import { insertAt } from './Utils';
+import { ConfigurationSection, type LogConfiguration } from '../types';
 
 let transports: transport[];
-if (Configuration.getLog().rotate === true) {
-  const logMaxFiles = Configuration.getLog().maxFiles;
-  const logMaxSize = Configuration.getLog().maxSize;
+if (
+  Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).rotate === true
+) {
+  const logMaxFiles = Configuration.getConfigurationSection<LogConfiguration>(
+    ConfigurationSection.log,
+  ).maxFiles;
+  const logMaxSize = Configuration.getConfigurationSection<LogConfiguration>(
+    ConfigurationSection.log,
+  ).maxSize;
   transports = [
     new DailyRotateFile({
       filename: insertAt(
-        Configuration.getLog().errorFile!,
+        Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
+          .errorFile!,
         '-%DATE%',
-        Configuration.getLog().errorFile!.indexOf('.log'),
+        Configuration.getConfigurationSection<LogConfiguration>(
+          ConfigurationSection.log,
+        ).errorFile!.indexOf('.log'),
       ),
       level: 'error',
       ...(logMaxFiles && { maxFiles: logMaxFiles }),
@@ -23,9 +33,11 @@ if (Configuration.getLog().rotate === true) {
     }),
     new DailyRotateFile({
       filename: insertAt(
-        Configuration.getLog().file!,
+        Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).file!,
         '-%DATE%',
-        Configuration.getLog().file!.indexOf('.log'),
+        Configuration.getConfigurationSection<LogConfiguration>(
+          ConfigurationSection.log,
+        ).file!.indexOf('.log'),
       ),
       ...(logMaxFiles && { maxFiles: logMaxFiles }),
       ...(logMaxSize && { maxSize: logMaxSize }),
@@ -33,15 +45,30 @@ if (Configuration.getLog().rotate === true) {
   ];
 } else {
   transports = [
-    new TransportType.File({ filename: Configuration.getLog().errorFile, level: 'error' }),
-    new TransportType.File({ filename: Configuration.getLog().file }),
+    new TransportType.File({
+      filename: Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
+        .errorFile,
+      level: 'error',
+    }),
+    new TransportType.File({
+      filename: Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
+        .file,
+    }),
   ];
 }
 
 export const logger = createLogger({
-  silent: !Configuration.getLog().enabled,
-  level: Configuration.getLog().level,
-  format: format.combine(format.splat(), (format[Configuration.getLog().format!] as FormatWrap)()),
+  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
+    )(),
+  ),
   transports,
 });
 
@@ -49,12 +76,17 @@ export const logger = createLogger({
 // If enabled, log to the `console` with the format:
 // `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
 //
-if (Configuration.getLog().console) {
+if (Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log).console) {
   logger.add(
     new TransportType.Console({
       format: format.combine(
         format.splat(),
-        (format[Configuration.getLog().format!] as FormatWrap)(),
+        (
+          format[
+            Configuration.getConfigurationSection<LogConfiguration>(ConfigurationSection.log)
+              .format!
+          ] as FormatWrap
+        )(),
       ),
     }),
   );