Performance statistics: add JSON file storage support.
[e-mobility-charging-stations-simulator.git] / src / utils / PerformanceStatistics.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
ef72d3f5 3import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from './CircularArray';
c0560973 4import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
57939a9d 5import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks';
aef1b33a 6import Statistics, { StatisticsData } from '../types/Statistics';
63b48f77 7
6af9012e 8import Configuration from './Configuration';
d2a64eb5 9import { MessageType } from '../types/ocpp/MessageType';
72f041bd
JB
10import { Storage } from './performance-storage/Storage';
11import { StorageFactory } from './performance-storage/StorageFactory';
6af9012e
JB
12import Utils from './Utils';
13import logger from './Logger';
7dde0b73 14
54b1efe0 15export default class PerformanceStatistics {
72f041bd 16 private static storage: Storage;
418106c8 17 private objId: string;
aef1b33a
JB
18 private performanceObserver: PerformanceObserver;
19 private statistics: Statistics;
20 private displayInterval: NodeJS.Timeout;
560bcf5b 21
c0560973
JB
22 public constructor(objId: string) {
23 this.objId = objId;
aef1b33a 24 this.initializePerformanceObserver();
72f041bd 25 this.statistics = { id: this.objId ?? 'Object id not specified', createdAt: new Date(), statisticsData: {} };
560bcf5b
JB
26 }
27
aef1b33a
JB
28 public static beginMeasure(id: string): string {
29 const beginId = 'begin' + id.charAt(0).toUpperCase() + id.slice(1);
30 performance.mark(beginId);
31 return beginId;
57939a9d
JB
32 }
33
aef1b33a
JB
34 public static endMeasure(name: string, beginId: string): void {
35 performance.measure(name, beginId);
333eb100 36 performance.clearMarks(beginId);
aef1b33a
JB
37 }
38
39 public addRequestStatistic(command: RequestCommand | IncomingRequestCommand, messageType: MessageType): void {
7f134aca 40 switch (messageType) {
d2a64eb5 41 case MessageType.CALL_MESSAGE:
aef1b33a
JB
42 if (this.statistics.statisticsData[command] && this.statistics.statisticsData[command].countRequest) {
43 this.statistics.statisticsData[command].countRequest++;
7dde0b73 44 } else {
aef1b33a
JB
45 this.statistics.statisticsData[command] = {} as StatisticsData;
46 this.statistics.statisticsData[command].countRequest = 1;
7f134aca
JB
47 }
48 break;
d2a64eb5 49 case MessageType.CALL_RESULT_MESSAGE:
aef1b33a
JB
50 if (this.statistics.statisticsData[command]) {
51 if (this.statistics.statisticsData[command].countResponse) {
52 this.statistics.statisticsData[command].countResponse++;
7f134aca 53 } else {
aef1b33a 54 this.statistics.statisticsData[command].countResponse = 1;
7f134aca
JB
55 }
56 } else {
aef1b33a
JB
57 this.statistics.statisticsData[command] = {} as StatisticsData;
58 this.statistics.statisticsData[command].countResponse = 1;
7dde0b73 59 }
7f134aca 60 break;
d2a64eb5 61 case MessageType.CALL_ERROR_MESSAGE:
aef1b33a
JB
62 if (this.statistics.statisticsData[command]) {
63 if (this.statistics.statisticsData[command].countError) {
64 this.statistics.statisticsData[command].countError++;
7f134aca 65 } else {
aef1b33a 66 this.statistics.statisticsData[command].countError = 1;
7f134aca
JB
67 }
68 } else {
aef1b33a
JB
69 this.statistics.statisticsData[command] = {} as StatisticsData;
70 this.statistics.statisticsData[command].countError = 1;
7f134aca
JB
71 }
72 break;
73 default:
54b1efe0 74 logger.error(`${this.logPrefix()} wrong message type ${messageType}`);
7f134aca 75 break;
7dde0b73
JB
76 }
77 }
78
aef1b33a 79 public start(): void {
72f041bd
JB
80 this.startLogStatisticsInterval();
81 if (Configuration.getPerformanceStorage().enabled) {
82 logger.info(`${this.logPrefix()} storage enabled: type ${Configuration.getPerformanceStorage().type}, URI: ${Configuration.getPerformanceStorage().URI}`);
83 }
7dde0b73
JB
84 }
85
aef1b33a 86 public stop(): void {
7874b0b1
JB
87 if (this.displayInterval) {
88 clearInterval(this.displayInterval);
89 }
aef1b33a 90 performance.clearMarks();
087a502d
JB
91 this.performanceObserver?.disconnect();
92 }
93
94 public restart(): void {
95 this.stop();
96 this.start();
136c90ba
JB
97 }
98
aef1b33a
JB
99 private initializePerformanceObserver(): void {
100 this.performanceObserver = new PerformanceObserver((list) => {
b49422c6
JB
101 this.addPerformanceEntryToStatistics(list.getEntries()[0]);
102 logger.debug(`${this.logPrefix()} '${list.getEntries()[0].name}' performance entry: %j`, list.getEntries()[0]);
a0ba4ced 103 });
aef1b33a
JB
104 this.performanceObserver.observe({ entryTypes: ['measure'] });
105 }
106
aef1b33a
JB
107 private logStatistics(): void {
108 logger.info(this.logPrefix() + ' %j', this.statistics);
7dde0b73
JB
109 }
110
72f041bd
JB
111 private startLogStatisticsInterval(): void {
112 if (Configuration.getLogStatisticsInterval() > 0) {
aef1b33a
JB
113 this.displayInterval = setInterval(() => {
114 this.logStatistics();
72f041bd
JB
115 }, Configuration.getLogStatisticsInterval() * 1000);
116 logger.info(this.logPrefix() + ' logged every ' + Utils.secondsToHHMMSS(Configuration.getLogStatisticsInterval()));
aef1b33a 117 } else {
72f041bd 118 logger.info(this.logPrefix() + ' log interval is set to ' + Configuration.getLogStatisticsInterval().toString() + '. Not logging statistics');
7dde0b73
JB
119 }
120 }
121
6bf6769e
JB
122 private median(dataSet: number[]): number {
123 if (Array.isArray(dataSet) && dataSet.length === 1) {
124 return dataSet[0];
125 }
2891f761 126 const sortedDataSet = dataSet.slice().sort((a, b) => (a - b));
6bf6769e
JB
127 const middleIndex = Math.floor(sortedDataSet.length / 2);
128 if (sortedDataSet.length % 2) {
129 return sortedDataSet[middleIndex / 2];
130 }
131 return (sortedDataSet[(middleIndex - 1)] + sortedDataSet[middleIndex]) / 2;
132 }
133
b49422c6
JB
134 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
135 private percentile(dataSet: number[], percentile: number): number {
136 if (percentile < 0 && percentile > 100) {
137 throw new RangeError('Percentile is not between 0 and 100');
138 }
139 if (Utils.isEmptyArray(dataSet)) {
140 return 0;
141 }
2891f761 142 const sortedDataSet = dataSet.slice().sort((a, b) => (a - b));
b49422c6
JB
143 if (percentile === 0) {
144 return sortedDataSet[0];
145 }
146 if (percentile === 100) {
147 return sortedDataSet[sortedDataSet.length - 1];
148 }
149 const percentileIndex = ((percentile / 100) * sortedDataSet.length) - 1;
150 if (Number.isInteger(percentileIndex)) {
151 return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2;
152 }
153 return sortedDataSet[Math.round(percentileIndex)];
154 }
155
aeada1fa
JB
156 private stdDeviation(dataSet: number[]): number {
157 let totalDataSet = 0;
158 for (const data of dataSet) {
159 totalDataSet += data;
160 }
161 const dataSetMean = totalDataSet / dataSet.length;
162 let totalGeometricDeviation = 0;
163 for (const data of dataSet) {
164 const deviation = data - dataSetMean;
165 totalGeometricDeviation += deviation * deviation;
166 }
167 return Math.sqrt(totalGeometricDeviation / dataSet.length);
168 }
169
b49422c6
JB
170 private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
171 let entryName = entry.name;
e9017bfc 172 // Rename entry name
b49422c6
JB
173 const MAP_NAME: Record<string, string> = {};
174 if (MAP_NAME[entryName]) {
175 entryName = MAP_NAME[entryName];
7ec46a9a
JB
176 }
177 // Initialize command statistics
b49422c6
JB
178 if (!this.statistics.statisticsData[entryName]) {
179 this.statistics.statisticsData[entryName] = {} as StatisticsData;
7ec46a9a 180 }
b49422c6 181 // Update current statistics
72f041bd 182 this.statistics.lastUpdatedAt = new Date();
b49422c6
JB
183 this.statistics.statisticsData[entryName].countTimeMeasurement = this.statistics.statisticsData[entryName].countTimeMeasurement ? this.statistics.statisticsData[entryName].countTimeMeasurement + 1 : 1;
184 this.statistics.statisticsData[entryName].currentTimeMeasurement = entry.duration;
185 this.statistics.statisticsData[entryName].minTimeMeasurement = this.statistics.statisticsData[entryName].minTimeMeasurement ? (this.statistics.statisticsData[entryName].minTimeMeasurement > entry.duration ? entry.duration : this.statistics.statisticsData[entryName].minTimeMeasurement) : entry.duration;
186 this.statistics.statisticsData[entryName].maxTimeMeasurement = this.statistics.statisticsData[entryName].maxTimeMeasurement ? (this.statistics.statisticsData[entryName].maxTimeMeasurement < entry.duration ? entry.duration : this.statistics.statisticsData[entryName].maxTimeMeasurement) : entry.duration;
187 this.statistics.statisticsData[entryName].totalTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement ? this.statistics.statisticsData[entryName].totalTimeMeasurement + entry.duration : entry.duration;
188 this.statistics.statisticsData[entryName].avgTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement / this.statistics.statisticsData[entryName].countTimeMeasurement;
189 Array.isArray(this.statistics.statisticsData[entryName].timeMeasurementSeries) ? this.statistics.statisticsData[entryName].timeMeasurementSeries.push(entry.duration) : this.statistics.statisticsData[entryName].timeMeasurementSeries = new CircularArray<number>(DEFAULT_CIRCULAR_ARRAY_SIZE, entry.duration);
190 this.statistics.statisticsData[entryName].medTimeMeasurement = this.median(this.statistics.statisticsData[entryName].timeMeasurementSeries);
191 this.statistics.statisticsData[entryName].ninetyFiveThPercentileTimeMeasurement = this.percentile(this.statistics.statisticsData[entryName].timeMeasurementSeries, 95);
192 this.statistics.statisticsData[entryName].stdDevTimeMeasurement = this.stdDeviation(this.statistics.statisticsData[entryName].timeMeasurementSeries);
72f041bd
JB
193 if (Configuration.getPerformanceStorage().enabled) {
194 this.getStorage().storePerformanceStatistics(this.statistics);
195 }
7ec46a9a
JB
196 }
197
c0560973 198 private logPrefix(): string {
54b1efe0 199 return Utils.logPrefix(` ${this.objId} | Performance statistics`);
6af9012e 200 }
72f041bd
JB
201
202 private getStorage(): Storage {
203 if (!PerformanceStatistics.storage) {
204 PerformanceStatistics.storage = StorageFactory.getStorage(Configuration.getPerformanceStorage().type ,Configuration.getPerformanceStorage().URI, this.logPrefix());
205 }
206 return PerformanceStatistics.storage;
207 }
7dde0b73 208}