Strict null check fixes
[e-mobility-charging-stations-simulator.git] / src / performance / PerformanceStatistics.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
c8eeb62b 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';
1e4b0e4b 10import type { Statistics, 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;
1895299d 24 private performanceObserver!: PerformanceObserver;
9e23580d 25 private readonly statistics: Statistics;
1895299d 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(),
1e4b0e4b 37 statisticsData: new Map(),
e7aeea18 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 {
14ecae6a 53 const markId = `${id.charAt(0).toUpperCase()}${id.slice(1)}~${Utils.generateUUID()}`;
c63c21bc
JB
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 {
72092cfc 141 this.performanceObserver = new PerformanceObserver((performanceObserverList) => {
c60af6ca 142 const lastPerformanceEntry = performanceObserverList.getEntries()[0];
9d1dc4b1
JB
143 // logger.debug(
144 // `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
145 // lastPerformanceEntry
146 // );
eb835fa8 147 this.addPerformanceEntryToStatistics(lastPerformanceEntry);
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 164 logger.info(
44eb6026
JB
165 `${this.logPrefix()} logged every ${Utils.formatDurationSeconds(
166 Configuration.getLogStatisticsInterval()
167 )}`
e7aeea18 168 );
aef1b33a 169 } else {
e7aeea18 170 logger.info(
72092cfc 171 `${this.logPrefix()} log interval is set to ${Configuration.getLogStatisticsInterval()?.toString()}. Not logging statistics`
e7aeea18 172 );
7dde0b73
JB
173 }
174 }
175
6bf6769e 176 private median(dataSet: number[]): number {
5f7e72c1 177 if (Array.isArray(dataSet) === true && dataSet.length === 1) {
6bf6769e
JB
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 224 private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
976d11ec 225 const entryName = entry.name;
7ec46a9a 226 // Initialize command statistics
ff4b895e
JB
227 if (!this.statistics.statisticsData.has(entryName)) {
228 this.statistics.statisticsData.set(entryName, {});
7ec46a9a 229 }
b49422c6 230 // Update current statistics
a6b3c6c3 231 this.statistics.updatedAt = new Date();
e7aeea18
JB
232 this.statistics.statisticsData.get(entryName).countTimeMeasurement =
233 this.statistics.statisticsData.get(entryName)?.countTimeMeasurement
234 ? this.statistics.statisticsData.get(entryName).countTimeMeasurement + 1
235 : 1;
ff4b895e 236 this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration;
e7aeea18
JB
237 this.statistics.statisticsData.get(entryName).minTimeMeasurement =
238 this.statistics.statisticsData.get(entryName)?.minTimeMeasurement
239 ? this.statistics.statisticsData.get(entryName).minTimeMeasurement > entry.duration
240 ? entry.duration
241 : this.statistics.statisticsData.get(entryName).minTimeMeasurement
242 : entry.duration;
243 this.statistics.statisticsData.get(entryName).maxTimeMeasurement =
244 this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement
245 ? this.statistics.statisticsData.get(entryName).maxTimeMeasurement < entry.duration
246 ? entry.duration
247 : this.statistics.statisticsData.get(entryName).maxTimeMeasurement
248 : entry.duration;
249 this.statistics.statisticsData.get(entryName).totalTimeMeasurement =
250 this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement
251 ? this.statistics.statisticsData.get(entryName).totalTimeMeasurement + entry.duration
252 : entry.duration;
253 this.statistics.statisticsData.get(entryName).avgTimeMeasurement =
254 this.statistics.statisticsData.get(entryName).totalTimeMeasurement /
255 this.statistics.statisticsData.get(entryName).countTimeMeasurement;
72092cfc 256 Array.isArray(this.statistics.statisticsData.get(entryName)?.timeMeasurementSeries) === true
e7aeea18
JB
257 ? this.statistics.statisticsData
258 .get(entryName)
72092cfc 259 ?.timeMeasurementSeries?.push({ timestamp: entry.startTime, value: entry.duration })
e7aeea18
JB
260 : (this.statistics.statisticsData.get(entryName).timeMeasurementSeries =
261 new CircularArray<TimeSeries>(DEFAULT_CIRCULAR_ARRAY_SIZE, {
262 timestamp: entry.startTime,
263 value: entry.duration,
264 }));
265 this.statistics.statisticsData.get(entryName).medTimeMeasurement = this.median(
266 this.extractTimeSeriesValues(
267 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
268 )
269 );
270 this.statistics.statisticsData.get(entryName).ninetyFiveThPercentileTimeMeasurement =
271 this.percentile(
272 this.extractTimeSeriesValues(
273 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
274 ),
275 95
276 );
277 this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = this.stdDeviation(
278 this.extractTimeSeriesValues(
279 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
280 )
281 );
72f041bd 282 if (Configuration.getPerformanceStorage().enabled) {
1895299d 283 parentPort?.postMessage(
32de5a57
LM
284 MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics)
285 );
72f041bd 286 }
7ec46a9a
JB
287 }
288
0c142310 289 private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] {
72092cfc 290 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
0c142310
JB
291 }
292
c0560973 293 private logPrefix(): string {
9f2e3130 294 return Utils.logPrefix(` ${this.objName} | Performance statistics`);
6af9012e 295 }
7dde0b73 296}