refactor: cleanup performance statistics variables namespace
[e-mobility-charging-stations-simulator.git] / src / performance / PerformanceStatistics.ts
index 61ef1b012946319ac1080fac1d9ca89b672fefd9..bd158ab80c8bcfe137d44ea213220a96dfec9077 100644 (file)
@@ -9,15 +9,21 @@ import {
   MessageType,
   type RequestCommand,
   type Statistics,
-  type TimeSeries,
+  type TimestampedData,
 } from '../types';
 import {
   CircularArray,
   Configuration,
   Constants,
-  MessageChannelUtils,
-  Utils,
+  JSONStringifyWithMapSupport,
+  buildPerformanceStatisticsMessage,
+  formatDurationSeconds,
+  generateUUID,
+  logPrefix,
   logger,
+  median,
+  nthPercentile,
+  stdDeviation,
 } from '../utils';
 
 export class PerformanceStatistics {
@@ -57,7 +63,7 @@ export class PerformanceStatistics {
   }
 
   public static beginMeasure(id: string): string {
-    const markId = `${id.charAt(0).toUpperCase()}${id.slice(1)}~${Utils.generateUUID()}`;
+    const markId = `${id.charAt(0).toUpperCase()}${id.slice(1)}~${generateUUID()}`;
     performance.mark(markId);
     return markId;
   }
@@ -157,26 +163,26 @@ export class PerformanceStatistics {
   private logStatistics(): void {
     logger.info(`${this.logPrefix()}`, {
       ...this.statistics,
-      statisticsData: Utils.JSONStringifyWithMapSupport(this.statistics.statisticsData),
+      statisticsData: JSONStringifyWithMapSupport(this.statistics.statisticsData),
     });
   }
 
   private startLogStatisticsInterval(): void {
-    const logStatisticsInterval = Configuration.getLogStatisticsInterval();
+    const logStatisticsInterval = Configuration.getLog().enabled
+      ? Configuration.getLog().statisticsInterval
+      : 0;
     if (logStatisticsInterval > 0 && !this.displayInterval) {
       this.displayInterval = setInterval(() => {
         this.logStatistics();
       }, logStatisticsInterval * 1000);
       logger.info(
-        `${this.logPrefix()} logged every ${Utils.formatDurationSeconds(logStatisticsInterval)}`
+        `${this.logPrefix()} logged every ${formatDurationSeconds(logStatisticsInterval)}`
       );
     } else if (this.displayInterval) {
       logger.info(
-        `${this.logPrefix()} already logged every ${Utils.formatDurationSeconds(
-          logStatisticsInterval
-        )}`
+        `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`
       );
-    } else {
+    } else if (Configuration.getLog().enabled) {
       logger.info(
         `${this.logPrefix()} log interval is set to ${logStatisticsInterval?.toString()}. Not logging statistics`
       );
@@ -199,67 +205,57 @@ export class PerformanceStatistics {
     // Update current statistics
     this.statistics.updatedAt = new Date();
     this.statistics.statisticsData.get(entryName).countTimeMeasurement =
-      this.statistics.statisticsData.get(entryName)?.countTimeMeasurement
-        ? this.statistics.statisticsData.get(entryName).countTimeMeasurement + 1
-        : 1;
+      (this.statistics.statisticsData.get(entryName)?.countTimeMeasurement ?? 0) + 1;
     this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration;
-    this.statistics.statisticsData.get(entryName).minTimeMeasurement =
-      this.statistics.statisticsData.get(entryName)?.minTimeMeasurement
-        ? this.statistics.statisticsData.get(entryName).minTimeMeasurement > entry.duration
-          ? entry.duration
-          : this.statistics.statisticsData.get(entryName).minTimeMeasurement
-        : entry.duration;
-    this.statistics.statisticsData.get(entryName).maxTimeMeasurement =
-      this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement
-        ? this.statistics.statisticsData.get(entryName).maxTimeMeasurement < entry.duration
-          ? entry.duration
-          : this.statistics.statisticsData.get(entryName).maxTimeMeasurement
-        : entry.duration;
+    this.statistics.statisticsData.get(entryName).minTimeMeasurement = Math.min(
+      entry.duration,
+      this.statistics.statisticsData.get(entryName)?.minTimeMeasurement ?? Infinity
+    );
+    this.statistics.statisticsData.get(entryName).maxTimeMeasurement = Math.max(
+      entry.duration,
+      this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement ?? -Infinity
+    );
     this.statistics.statisticsData.get(entryName).totalTimeMeasurement =
-      this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement
-        ? this.statistics.statisticsData.get(entryName).totalTimeMeasurement + entry.duration
-        : entry.duration;
+      (this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement ?? 0) + entry.duration;
     this.statistics.statisticsData.get(entryName).avgTimeMeasurement =
       this.statistics.statisticsData.get(entryName).totalTimeMeasurement /
       this.statistics.statisticsData.get(entryName).countTimeMeasurement;
-    this.statistics.statisticsData.get(entryName)?.timeMeasurementSeries instanceof CircularArray
+    this.statistics.statisticsData.get(entryName)?.measurementTimeSeries instanceof CircularArray
       ? this.statistics.statisticsData
           .get(entryName)
-          ?.timeMeasurementSeries?.push({ timestamp: entry.startTime, value: entry.duration })
-      : (this.statistics.statisticsData.get(entryName).timeMeasurementSeries =
-          new CircularArray<TimeSeries>(Constants.DEFAULT_CIRCULAR_BUFFER_CAPACITY, {
+          ?.measurementTimeSeries?.push({ timestamp: entry.startTime, value: entry.duration })
+      : (this.statistics.statisticsData.get(entryName).measurementTimeSeries =
+          new CircularArray<TimestampedData>(Constants.DEFAULT_CIRCULAR_BUFFER_CAPACITY, {
             timestamp: entry.startTime,
             value: entry.duration,
           }));
-    this.statistics.statisticsData.get(entryName).medTimeMeasurement = Utils.median(
+    this.statistics.statisticsData.get(entryName).medTimeMeasurement = median(
       this.extractTimeSeriesValues(
-        this.statistics.statisticsData.get(entryName).timeMeasurementSeries
+        this.statistics.statisticsData.get(entryName).measurementTimeSeries
       )
     );
     this.statistics.statisticsData.get(entryName).ninetyFiveThPercentileTimeMeasurement =
-      Utils.percentile(
+      nthPercentile(
         this.extractTimeSeriesValues(
-          this.statistics.statisticsData.get(entryName).timeMeasurementSeries
+          this.statistics.statisticsData.get(entryName).measurementTimeSeries
         ),
         95
       );
-    this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = Utils.stdDeviation(
+    this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = stdDeviation(
       this.extractTimeSeriesValues(
-        this.statistics.statisticsData.get(entryName).timeMeasurementSeries
+        this.statistics.statisticsData.get(entryName).measurementTimeSeries
       )
     );
     if (Configuration.getPerformanceStorage().enabled) {
-      parentPort?.postMessage(
-        MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics)
-      );
+      parentPort?.postMessage(buildPerformanceStatisticsMessage(this.statistics));
     }
   }
 
-  private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] {
+  private extractTimeSeriesValues(timeSeries: CircularArray<TimestampedData>): number[] {
     return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
   }
 
   private logPrefix = (): string => {
-    return Utils.logPrefix(` ${this.objName} | Performance statistics`);
+    return logPrefix(` ${this.objName} | Performance statistics`);
   };
 }