chore: version 1.1.94
[e-mobility-charging-stations-simulator.git] / src / performance / PerformanceStatistics.ts
index c41b2d59a2e0d157758e7b37643f34d8e17f90ad..aa0cc72325d903bf2de6ff0a8a44c8b959207f53 100644 (file)
@@ -1,15 +1,16 @@
-// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
+// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
 
+import type { URL } from 'node:url';
 import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks';
-import { URL } from 'url';
 import { parentPort } from 'worker_threads';
 
 import { MessageChannelUtils } from '../charging-station/MessageChannelUtils';
 import { MessageType } from '../types/ocpp/MessageType';
-import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
-import Statistics, { StatisticsData, TimeSeries } from '../types/Statistics';
-import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from '../utils/CircularArray';
+import type { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
+import type { Statistics, TimeSeries } from '../types/Statistics';
+import { CircularArray } from '../utils/CircularArray';
 import Configuration from '../utils/Configuration';
+import Constants from '../utils/Constants';
 import logger from '../utils/Logger';
 import Utils from '../utils/Utils';
 
@@ -21,9 +22,9 @@ export default class PerformanceStatistics {
 
   private readonly objId: string;
   private readonly objName: string;
-  private performanceObserver: PerformanceObserver;
+  private performanceObserver!: PerformanceObserver;
   private readonly statistics: Statistics;
-  private displayInterval: NodeJS.Timeout;
+  private displayInterval!: NodeJS.Timeout;
 
   private constructor(objId: string, objName: string, uri: URL) {
     this.objId = objId;
@@ -34,7 +35,7 @@ export default class PerformanceStatistics {
       name: this.objName ?? 'Object name not specified',
       uri: uri.toString(),
       createdAt: new Date(),
-      statisticsData: new Map<string, Partial<StatisticsData>>(),
+      statisticsData: new Map(),
     };
   }
 
@@ -50,7 +51,7 @@ export default 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)}~${Utils.generateUUID()}`;
     performance.mark(markId);
     return markId;
   }
@@ -58,6 +59,7 @@ export default class PerformanceStatistics {
   public static endMeasure(name: string, markId: string): void {
     performance.measure(name, markId);
     performance.clearMarks(markId);
+    performance.clearMeasures(name);
   }
 
   public addRequestStatistic(
@@ -127,6 +129,7 @@ export default class PerformanceStatistics {
       clearInterval(this.displayInterval);
     }
     performance.clearMarks();
+    performance.clearMeasures();
     this.performanceObserver?.disconnect();
   }
 
@@ -136,19 +139,22 @@ export default class PerformanceStatistics {
   }
 
   private initializePerformanceObserver(): void {
-    this.performanceObserver = new PerformanceObserver((list) => {
-      const lastPerformanceEntry = list.getEntries()[0];
+    this.performanceObserver = new PerformanceObserver((performanceObserverList) => {
+      const lastPerformanceEntry = performanceObserverList.getEntries()[0];
+      // logger.debug(
+      //   `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
+      //   lastPerformanceEntry
+      // );
       this.addPerformanceEntryToStatistics(lastPerformanceEntry);
-      logger.debug(
-        `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
-        lastPerformanceEntry
-      );
     });
     this.performanceObserver.observe({ entryTypes: ['measure'] });
   }
 
   private logStatistics(): void {
-    logger.info(this.logPrefix() + ' %j', this.statistics);
+    logger.info(`${this.logPrefix()}`, {
+      ...this.statistics,
+      statisticsData: Utils.JSONStringifyWithMapSupport(this.statistics.statisticsData),
+    });
   }
 
   private startLogStatisticsInterval(): void {
@@ -157,22 +163,19 @@ export default class PerformanceStatistics {
         this.logStatistics();
       }, Configuration.getLogStatisticsInterval() * 1000);
       logger.info(
-        this.logPrefix() +
-          ' logged every ' +
-          Utils.formatDurationSeconds(Configuration.getLogStatisticsInterval())
+        `${this.logPrefix()} logged every ${Utils.formatDurationSeconds(
+          Configuration.getLogStatisticsInterval()
+        )}`
       );
     } else {
       logger.info(
-        this.logPrefix() +
-          ' log interval is set to ' +
-          Configuration.getLogStatisticsInterval().toString() +
-          '. Not logging statistics'
+        `${this.logPrefix()} log interval is set to ${Configuration.getLogStatisticsInterval()?.toString()}. Not logging statistics`
       );
     }
   }
 
   private median(dataSet: number[]): number {
-    if (Array.isArray(dataSet) && dataSet.length === 1) {
+    if (Array.isArray(dataSet) === true && dataSet.length === 1) {
       return dataSet[0];
     }
     const sortedDataSet = dataSet.slice().sort((a, b) => a - b);
@@ -220,12 +223,7 @@ export default class PerformanceStatistics {
   }
 
   private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
-    let entryName = entry.name;
-    // Rename entry name
-    const MAP_NAME: Record<string, string> = {};
-    if (MAP_NAME[entryName]) {
-      entryName = MAP_NAME[entryName];
-    }
+    const entryName = entry.name;
     // Initialize command statistics
     if (!this.statistics.statisticsData.has(entryName)) {
       this.statistics.statisticsData.set(entryName, {});
@@ -256,12 +254,12 @@ export default class PerformanceStatistics {
     this.statistics.statisticsData.get(entryName).avgTimeMeasurement =
       this.statistics.statisticsData.get(entryName).totalTimeMeasurement /
       this.statistics.statisticsData.get(entryName).countTimeMeasurement;
-    Array.isArray(this.statistics.statisticsData.get(entryName).timeMeasurementSeries)
+    this.statistics.statisticsData.get(entryName)?.timeMeasurementSeries instanceof CircularArray
       ? this.statistics.statisticsData
           .get(entryName)
-          .timeMeasurementSeries.push({ timestamp: entry.startTime, value: entry.duration })
+          ?.timeMeasurementSeries?.push({ timestamp: entry.startTime, value: entry.duration })
       : (this.statistics.statisticsData.get(entryName).timeMeasurementSeries =
-          new CircularArray<TimeSeries>(DEFAULT_CIRCULAR_ARRAY_SIZE, {
+          new CircularArray<TimeSeries>(Constants.DEFAULT_CIRCULAR_BUFFER_CAPACITY, {
             timestamp: entry.startTime,
             value: entry.duration,
           }));
@@ -283,7 +281,7 @@ export default class PerformanceStatistics {
       )
     );
     if (Configuration.getPerformanceStorage().enabled) {
-      parentPort.postMessage(
+      parentPort?.postMessage(
         MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics)
       );
     }
@@ -293,7 +291,7 @@ export default class PerformanceStatistics {
     return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
   }
 
-  private logPrefix(): string {
+  private logPrefix = (): string => {
     return Utils.logPrefix(` ${this.objName} | Performance statistics`);
-  }
+  };
 }