UI Server: Improve error handling
[e-mobility-charging-stations-simulator.git] / src / performance / PerformanceStatistics.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks';
4 import type { URL } from 'url';
5 import { parentPort } from 'worker_threads';
6
7 import { MessageChannelUtils } from '../charging-station/MessageChannelUtils';
8 import { MessageType } from '../types/ocpp/MessageType';
9 import type { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
10 import type Statistics from '../types/Statistics';
11 // eslint-disable-next-line no-duplicate-imports
12 import type { StatisticsData, TimeSeries } from '../types/Statistics';
13 import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from '../utils/CircularArray';
14 import Configuration from '../utils/Configuration';
15 import logger from '../utils/Logger';
16 import Utils from '../utils/Utils';
17
18 export default class PerformanceStatistics {
19 private static readonly instances: Map<string, PerformanceStatistics> = new Map<
20 string,
21 PerformanceStatistics
22 >();
23
24 private readonly objId: string;
25 private readonly objName: string;
26 private performanceObserver: PerformanceObserver;
27 private readonly statistics: Statistics;
28 private displayInterval: NodeJS.Timeout;
29
30 private constructor(objId: string, objName: string, uri: URL) {
31 this.objId = objId;
32 this.objName = objName;
33 this.initializePerformanceObserver();
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 };
41 }
42
43 public static getInstance(
44 objId: string,
45 objName: string,
46 uri: URL
47 ): PerformanceStatistics | undefined {
48 if (!PerformanceStatistics.instances.has(objId)) {
49 PerformanceStatistics.instances.set(objId, new PerformanceStatistics(objId, objName, uri));
50 }
51 return PerformanceStatistics.instances.get(objId);
52 }
53
54 public static beginMeasure(id: string): string {
55 const markId = `${id.charAt(0).toUpperCase() + id.slice(1)}~${Utils.generateUUID()}`;
56 performance.mark(markId);
57 return markId;
58 }
59
60 public static endMeasure(name: string, markId: string): void {
61 performance.measure(name, markId);
62 performance.clearMarks(markId);
63 }
64
65 public addRequestStatistic(
66 command: RequestCommand | IncomingRequestCommand,
67 messageType: MessageType
68 ): void {
69 switch (messageType) {
70 case MessageType.CALL_MESSAGE:
71 if (
72 this.statistics.statisticsData.has(command) &&
73 this.statistics.statisticsData.get(command)?.countRequest
74 ) {
75 this.statistics.statisticsData.get(command).countRequest++;
76 } else {
77 this.statistics.statisticsData.set(
78 command,
79 Object.assign({ countRequest: 1 }, this.statistics.statisticsData.get(command))
80 );
81 }
82 break;
83 case MessageType.CALL_RESULT_MESSAGE:
84 if (
85 this.statistics.statisticsData.has(command) &&
86 this.statistics.statisticsData.get(command)?.countResponse
87 ) {
88 this.statistics.statisticsData.get(command).countResponse++;
89 } else {
90 this.statistics.statisticsData.set(
91 command,
92 Object.assign({ countResponse: 1 }, this.statistics.statisticsData.get(command))
93 );
94 }
95 break;
96 case MessageType.CALL_ERROR_MESSAGE:
97 if (
98 this.statistics.statisticsData.has(command) &&
99 this.statistics.statisticsData.get(command)?.countError
100 ) {
101 this.statistics.statisticsData.get(command).countError++;
102 } else {
103 this.statistics.statisticsData.set(
104 command,
105 Object.assign({ countError: 1 }, this.statistics.statisticsData.get(command))
106 );
107 }
108 break;
109 default:
110 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
111 logger.error(`${this.logPrefix()} wrong message type ${messageType}`);
112 break;
113 }
114 }
115
116 public start(): void {
117 this.startLogStatisticsInterval();
118 if (Configuration.getPerformanceStorage().enabled) {
119 logger.info(
120 `${this.logPrefix()} storage enabled: type ${
121 Configuration.getPerformanceStorage().type
122 }, uri: ${Configuration.getPerformanceStorage().uri}`
123 );
124 }
125 }
126
127 public stop(): void {
128 if (this.displayInterval) {
129 clearInterval(this.displayInterval);
130 }
131 performance.clearMarks();
132 this.performanceObserver?.disconnect();
133 }
134
135 public restart(): void {
136 this.stop();
137 this.start();
138 }
139
140 private initializePerformanceObserver(): void {
141 this.performanceObserver = new PerformanceObserver((list) => {
142 const lastPerformanceEntry = list.getEntries()[0];
143 this.addPerformanceEntryToStatistics(lastPerformanceEntry);
144 logger.debug(
145 `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
146 lastPerformanceEntry
147 );
148 });
149 this.performanceObserver.observe({ entryTypes: ['measure'] });
150 }
151
152 private logStatistics(): void {
153 logger.info(this.logPrefix() + ' %j', this.statistics);
154 }
155
156 private startLogStatisticsInterval(): void {
157 if (Configuration.getLogStatisticsInterval() > 0) {
158 this.displayInterval = setInterval(() => {
159 this.logStatistics();
160 }, Configuration.getLogStatisticsInterval() * 1000);
161 logger.info(
162 this.logPrefix() +
163 ' logged every ' +
164 Utils.formatDurationSeconds(Configuration.getLogStatisticsInterval())
165 );
166 } else {
167 logger.info(
168 this.logPrefix() +
169 ' log interval is set to ' +
170 Configuration.getLogStatisticsInterval().toString() +
171 '. Not logging statistics'
172 );
173 }
174 }
175
176 private median(dataSet: number[]): number {
177 if (Array.isArray(dataSet) && dataSet.length === 1) {
178 return dataSet[0];
179 }
180 const sortedDataSet = dataSet.slice().sort((a, b) => a - b);
181 const middleIndex = Math.floor(sortedDataSet.length / 2);
182 if (sortedDataSet.length % 2) {
183 return sortedDataSet[middleIndex / 2];
184 }
185 return (sortedDataSet[middleIndex - 1] + sortedDataSet[middleIndex]) / 2;
186 }
187
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 }
196 const sortedDataSet = dataSet.slice().sort((a, b) => a - b);
197 if (percentile === 0) {
198 return sortedDataSet[0];
199 }
200 if (percentile === 100) {
201 return sortedDataSet[sortedDataSet.length - 1];
202 }
203 const percentileIndex = (percentile / 100) * sortedDataSet.length - 1;
204 if (Number.isInteger(percentileIndex)) {
205 return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2;
206 }
207 return sortedDataSet[Math.round(percentileIndex)];
208 }
209
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
224 private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
225 const entryName = entry.name;
226 // Initialize command statistics
227 if (!this.statistics.statisticsData.has(entryName)) {
228 this.statistics.statisticsData.set(entryName, {});
229 }
230 // Update current statistics
231 this.statistics.updatedAt = new Date();
232 this.statistics.statisticsData.get(entryName).countTimeMeasurement =
233 this.statistics.statisticsData.get(entryName)?.countTimeMeasurement
234 ? this.statistics.statisticsData.get(entryName).countTimeMeasurement + 1
235 : 1;
236 this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration;
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;
256 Array.isArray(this.statistics.statisticsData.get(entryName).timeMeasurementSeries)
257 ? this.statistics.statisticsData
258 .get(entryName)
259 .timeMeasurementSeries.push({ timestamp: entry.startTime, value: entry.duration })
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 );
282 if (Configuration.getPerformanceStorage().enabled) {
283 parentPort.postMessage(
284 MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics)
285 );
286 }
287 }
288
289 private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] {
290 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
291 }
292
293 private logPrefix(): string {
294 return Utils.logPrefix(` ${this.objName} | Performance statistics`);
295 }
296 }