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