Incoming requests payload validation with JSON schemas (#135)
[e-mobility-charging-stations-simulator.git] / src / performance / PerformanceStatistics.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
57939a9d 3import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks';
8114d10e
JB
4import { URL } from 'url';
5import { parentPort } from 'worker_threads';
63b48f77 6
98dc07fa 7import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
d2a64eb5 8import { MessageType } from '../types/ocpp/MessageType';
8114d10e
JB
9import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
10import Statistics, { StatisticsData, TimeSeries } from '../types/Statistics';
11import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from '../utils/CircularArray';
12import Configuration from '../utils/Configuration';
9f2e3130 13import logger from '../utils/Logger';
8114d10e 14import Utils from '../utils/Utils';
7dde0b73 15
54b1efe0 16export default class PerformanceStatistics {
e7aeea18
JB
17 private static readonly instances: Map<string, PerformanceStatistics> = new Map<
18 string,
19 PerformanceStatistics
20 >();
10068088 21
9e23580d 22 private readonly objId: string;
9f2e3130 23 private readonly objName: string;
aef1b33a 24 private performanceObserver: PerformanceObserver;
9e23580d 25 private readonly statistics: Statistics;
aef1b33a 26 private displayInterval: NodeJS.Timeout;
560bcf5b 27
9f2e3130 28 private constructor(objId: string, objName: string, uri: URL) {
c0560973 29 this.objId = objId;
9f2e3130 30 this.objName = objName;
aef1b33a 31 this.initializePerformanceObserver();
e7aeea18
JB
32 this.statistics = {
33 id: this.objId ?? 'Object id not specified',
34 name: this.objName ?? 'Object name not specified',
35 uri: uri.toString(),
36 createdAt: new Date(),
37 statisticsData: new Map<string, Partial<StatisticsData>>(),
38 };
9f2e3130
JB
39 }
40
41 public static getInstance(objId: string, objName: string, uri: URL): PerformanceStatistics {
42 if (!PerformanceStatistics.instances.has(objId)) {
43 PerformanceStatistics.instances.set(objId, new PerformanceStatistics(objId, objName, uri));
44 }
45 return PerformanceStatistics.instances.get(objId);
560bcf5b
JB
46 }
47
aef1b33a 48 public static beginMeasure(id: string): string {
c63c21bc
JB
49 const markId = `${id.charAt(0).toUpperCase() + id.slice(1)}~${Utils.generateUUID()}`;
50 performance.mark(markId);
51 return markId;
57939a9d
JB
52 }
53
c63c21bc
JB
54 public static endMeasure(name: string, markId: string): void {
55 performance.measure(name, markId);
56 performance.clearMarks(markId);
aef1b33a
JB
57 }
58
e7aeea18
JB
59 public addRequestStatistic(
60 command: RequestCommand | IncomingRequestCommand,
61 messageType: MessageType
62 ): void {
7f134aca 63 switch (messageType) {
d2a64eb5 64 case MessageType.CALL_MESSAGE:
e7aeea18
JB
65 if (
66 this.statistics.statisticsData.has(command) &&
67 this.statistics.statisticsData.get(command)?.countRequest
68 ) {
ff4b895e 69 this.statistics.statisticsData.get(command).countRequest++;
7dde0b73 70 } else {
e7aeea18
JB
71 this.statistics.statisticsData.set(
72 command,
73 Object.assign({ countRequest: 1 }, this.statistics.statisticsData.get(command))
74 );
7f134aca
JB
75 }
76 break;
d2a64eb5 77 case MessageType.CALL_RESULT_MESSAGE:
e7aeea18
JB
78 if (
79 this.statistics.statisticsData.has(command) &&
80 this.statistics.statisticsData.get(command)?.countResponse
81 ) {
ff4b895e 82 this.statistics.statisticsData.get(command).countResponse++;
7f134aca 83 } else {
e7aeea18
JB
84 this.statistics.statisticsData.set(
85 command,
86 Object.assign({ countResponse: 1 }, this.statistics.statisticsData.get(command))
87 );
7dde0b73 88 }
7f134aca 89 break;
d2a64eb5 90 case MessageType.CALL_ERROR_MESSAGE:
e7aeea18
JB
91 if (
92 this.statistics.statisticsData.has(command) &&
93 this.statistics.statisticsData.get(command)?.countError
94 ) {
ff4b895e 95 this.statistics.statisticsData.get(command).countError++;
7f134aca 96 } else {
e7aeea18
JB
97 this.statistics.statisticsData.set(
98 command,
99 Object.assign({ countError: 1 }, this.statistics.statisticsData.get(command))
100 );
7f134aca
JB
101 }
102 break;
103 default:
9534e74e 104 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
9f2e3130 105 logger.error(`${this.logPrefix()} wrong message type ${messageType}`);
7f134aca 106 break;
7dde0b73
JB
107 }
108 }
109
aef1b33a 110 public start(): void {
72f041bd
JB
111 this.startLogStatisticsInterval();
112 if (Configuration.getPerformanceStorage().enabled) {
e7aeea18
JB
113 logger.info(
114 `${this.logPrefix()} storage enabled: type ${
115 Configuration.getPerformanceStorage().type
116 }, uri: ${Configuration.getPerformanceStorage().uri}`
117 );
72f041bd 118 }
7dde0b73
JB
119 }
120
aef1b33a 121 public stop(): void {
7874b0b1
JB
122 if (this.displayInterval) {
123 clearInterval(this.displayInterval);
124 }
aef1b33a 125 performance.clearMarks();
087a502d
JB
126 this.performanceObserver?.disconnect();
127 }
128
129 public restart(): void {
130 this.stop();
131 this.start();
136c90ba
JB
132 }
133
aef1b33a
JB
134 private initializePerformanceObserver(): void {
135 this.performanceObserver = new PerformanceObserver((list) => {
eb835fa8
JB
136 const lastPerformanceEntry = list.getEntries()[0];
137 this.addPerformanceEntryToStatistics(lastPerformanceEntry);
e7aeea18
JB
138 logger.debug(
139 `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
140 lastPerformanceEntry
141 );
a0ba4ced 142 });
aef1b33a
JB
143 this.performanceObserver.observe({ entryTypes: ['measure'] });
144 }
145
aef1b33a 146 private logStatistics(): void {
9f2e3130 147 logger.info(this.logPrefix() + ' %j', this.statistics);
7dde0b73
JB
148 }
149
72f041bd
JB
150 private startLogStatisticsInterval(): void {
151 if (Configuration.getLogStatisticsInterval() > 0) {
aef1b33a
JB
152 this.displayInterval = setInterval(() => {
153 this.logStatistics();
72f041bd 154 }, Configuration.getLogStatisticsInterval() * 1000);
e7aeea18
JB
155 logger.info(
156 this.logPrefix() +
157 ' logged every ' +
158 Utils.formatDurationSeconds(Configuration.getLogStatisticsInterval())
159 );
aef1b33a 160 } else {
e7aeea18
JB
161 logger.info(
162 this.logPrefix() +
163 ' log interval is set to ' +
164 Configuration.getLogStatisticsInterval().toString() +
165 '. Not logging statistics'
166 );
7dde0b73
JB
167 }
168 }
169
6bf6769e
JB
170 private median(dataSet: number[]): number {
171 if (Array.isArray(dataSet) && dataSet.length === 1) {
172 return dataSet[0];
173 }
e7aeea18 174 const sortedDataSet = dataSet.slice().sort((a, b) => a - b);
6bf6769e
JB
175 const middleIndex = Math.floor(sortedDataSet.length / 2);
176 if (sortedDataSet.length % 2) {
177 return sortedDataSet[middleIndex / 2];
178 }
e7aeea18 179 return (sortedDataSet[middleIndex - 1] + sortedDataSet[middleIndex]) / 2;
6bf6769e
JB
180 }
181
b49422c6
JB
182 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
183 private percentile(dataSet: number[], percentile: number): number {
184 if (percentile < 0 && percentile > 100) {
185 throw new RangeError('Percentile is not between 0 and 100');
186 }
187 if (Utils.isEmptyArray(dataSet)) {
188 return 0;
189 }
e7aeea18 190 const sortedDataSet = dataSet.slice().sort((a, b) => a - b);
b49422c6
JB
191 if (percentile === 0) {
192 return sortedDataSet[0];
193 }
194 if (percentile === 100) {
195 return sortedDataSet[sortedDataSet.length - 1];
196 }
e7aeea18 197 const percentileIndex = (percentile / 100) * sortedDataSet.length - 1;
b49422c6
JB
198 if (Number.isInteger(percentileIndex)) {
199 return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2;
200 }
201 return sortedDataSet[Math.round(percentileIndex)];
202 }
203
aeada1fa
JB
204 private stdDeviation(dataSet: number[]): number {
205 let totalDataSet = 0;
206 for (const data of dataSet) {
207 totalDataSet += data;
208 }
209 const dataSetMean = totalDataSet / dataSet.length;
210 let totalGeometricDeviation = 0;
211 for (const data of dataSet) {
212 const deviation = data - dataSetMean;
213 totalGeometricDeviation += deviation * deviation;
214 }
215 return Math.sqrt(totalGeometricDeviation / dataSet.length);
216 }
217
b49422c6
JB
218 private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
219 let entryName = entry.name;
e9017bfc 220 // Rename entry name
b49422c6
JB
221 const MAP_NAME: Record<string, string> = {};
222 if (MAP_NAME[entryName]) {
223 entryName = MAP_NAME[entryName];
7ec46a9a
JB
224 }
225 // Initialize command statistics
ff4b895e
JB
226 if (!this.statistics.statisticsData.has(entryName)) {
227 this.statistics.statisticsData.set(entryName, {});
7ec46a9a 228 }
b49422c6 229 // Update current statistics
a6b3c6c3 230 this.statistics.updatedAt = new Date();
e7aeea18
JB
231 this.statistics.statisticsData.get(entryName).countTimeMeasurement =
232 this.statistics.statisticsData.get(entryName)?.countTimeMeasurement
233 ? this.statistics.statisticsData.get(entryName).countTimeMeasurement + 1
234 : 1;
ff4b895e 235 this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration;
e7aeea18
JB
236 this.statistics.statisticsData.get(entryName).minTimeMeasurement =
237 this.statistics.statisticsData.get(entryName)?.minTimeMeasurement
238 ? this.statistics.statisticsData.get(entryName).minTimeMeasurement > entry.duration
239 ? entry.duration
240 : this.statistics.statisticsData.get(entryName).minTimeMeasurement
241 : entry.duration;
242 this.statistics.statisticsData.get(entryName).maxTimeMeasurement =
243 this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement
244 ? this.statistics.statisticsData.get(entryName).maxTimeMeasurement < entry.duration
245 ? entry.duration
246 : this.statistics.statisticsData.get(entryName).maxTimeMeasurement
247 : entry.duration;
248 this.statistics.statisticsData.get(entryName).totalTimeMeasurement =
249 this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement
250 ? this.statistics.statisticsData.get(entryName).totalTimeMeasurement + entry.duration
251 : entry.duration;
252 this.statistics.statisticsData.get(entryName).avgTimeMeasurement =
253 this.statistics.statisticsData.get(entryName).totalTimeMeasurement /
254 this.statistics.statisticsData.get(entryName).countTimeMeasurement;
0c142310 255 Array.isArray(this.statistics.statisticsData.get(entryName).timeMeasurementSeries)
e7aeea18
JB
256 ? this.statistics.statisticsData
257 .get(entryName)
258 .timeMeasurementSeries.push({ timestamp: entry.startTime, value: entry.duration })
259 : (this.statistics.statisticsData.get(entryName).timeMeasurementSeries =
260 new CircularArray<TimeSeries>(DEFAULT_CIRCULAR_ARRAY_SIZE, {
261 timestamp: entry.startTime,
262 value: entry.duration,
263 }));
264 this.statistics.statisticsData.get(entryName).medTimeMeasurement = this.median(
265 this.extractTimeSeriesValues(
266 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
267 )
268 );
269 this.statistics.statisticsData.get(entryName).ninetyFiveThPercentileTimeMeasurement =
270 this.percentile(
271 this.extractTimeSeriesValues(
272 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
273 ),
274 95
275 );
276 this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = this.stdDeviation(
277 this.extractTimeSeriesValues(
278 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
279 )
280 );
72f041bd 281 if (Configuration.getPerformanceStorage().enabled) {
e7aeea18
JB
282 parentPort.postMessage({
283 id: ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS,
284 data: this.statistics,
285 });
72f041bd 286 }
7ec46a9a
JB
287 }
288
0c142310
JB
289 private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] {
290 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
291 }
292
c0560973 293 private logPrefix(): string {
9f2e3130 294 return Utils.logPrefix(` ${this.objName} | Performance statistics`);
6af9012e 295 }
7dde0b73 296}