Strict null check fixes
[e-mobility-charging-stations-simulator.git] / src / performance / PerformanceStatistics.ts
index 6513bba5e98ade3a08b00f8e3fb41680c5a66296..6ac54aa42c451813f22c8d2cd1fe1d6e73979064 100644 (file)
@@ -1,4 +1,4 @@
-// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
+// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
 
 import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks';
 import type { URL } from 'url';
@@ -7,9 +7,7 @@ import { parentPort } from 'worker_threads';
 import { MessageChannelUtils } from '../charging-station/MessageChannelUtils';
 import { MessageType } from '../types/ocpp/MessageType';
 import type { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
-import type Statistics from '../types/Statistics';
-// eslint-disable-next-line no-duplicate-imports
-import type { StatisticsData, TimeSeries } from '../types/Statistics';
+import type { Statistics, TimeSeries } from '../types/Statistics';
 import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from '../utils/CircularArray';
 import Configuration from '../utils/Configuration';
 import logger from '../utils/Logger';
@@ -23,9 +21,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;
@@ -36,7 +34,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(),
     };
   }
 
@@ -52,7 +50,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;
   }
@@ -60,6 +58,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(
@@ -129,6 +128,7 @@ export default class PerformanceStatistics {
       clearInterval(this.displayInterval);
     }
     performance.clearMarks();
+    performance.clearMeasures();
     this.performanceObserver?.disconnect();
   }
 
@@ -138,19 +138,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 {
@@ -159,22 +162,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);
@@ -253,10 +253,10 @@ 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)
+    Array.isArray(this.statistics.statisticsData.get(entryName)?.timeMeasurementSeries) === true
       ? 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, {
             timestamp: entry.startTime,
@@ -280,7 +280,7 @@ export default class PerformanceStatistics {
       )
     );
     if (Configuration.getPerformanceStorage().enabled) {
-      parentPort.postMessage(
+      parentPort?.postMessage(
         MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics)
       );
     }