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