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