fix: fix setInterval deferencing
[e-mobility-charging-stations-simulator.git] / src / performance / PerformanceStatistics.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import { type PerformanceEntry, PerformanceObserver, performance } from 'node:perf_hooks';
4 import type { URL } from 'node:url';
5 import { parentPort } from 'node:worker_threads';
6
7 import { MessageChannelUtils } from '../charging-station';
8 import {
9 type IncomingRequestCommand,
10 MessageType,
11 type RequestCommand,
12 type Statistics,
13 type TimeSeries,
14 } from '../types';
15 import { CircularArray, Configuration, Constants, Utils, logger } from '../utils';
16
17 export class PerformanceStatistics {
18 private static readonly instances: Map<string, PerformanceStatistics> = new Map<
19 string,
20 PerformanceStatistics
21 >();
22
23 private readonly objId: string;
24 private readonly objName: string;
25 private performanceObserver!: PerformanceObserver;
26 private readonly statistics: Statistics;
27 private displayInterval!: NodeJS.Timeout;
28
29 private constructor(objId: string, objName: string, uri: URL) {
30 this.objId = objId;
31 this.objName = objName;
32 this.initializePerformanceObserver();
33 this.statistics = {
34 id: this.objId ?? 'Object id not specified',
35 name: this.objName ?? 'Object name not specified',
36 uri: uri.toString(),
37 createdAt: new Date(),
38 statisticsData: new Map(),
39 };
40 }
41
42 public static getInstance(
43 objId: string,
44 objName: string,
45 uri: URL
46 ): PerformanceStatistics | undefined {
47 if (!PerformanceStatistics.instances.has(objId)) {
48 PerformanceStatistics.instances.set(objId, new PerformanceStatistics(objId, objName, uri));
49 }
50 return PerformanceStatistics.instances.get(objId);
51 }
52
53 public static beginMeasure(id: string): string {
54 const markId = `${id.charAt(0).toUpperCase()}${id.slice(1)}~${Utils.generateUUID()}`;
55 performance.mark(markId);
56 return markId;
57 }
58
59 public static endMeasure(name: string, markId: string): void {
60 performance.measure(name, markId);
61 performance.clearMarks(markId);
62 performance.clearMeasures(name);
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(command, {
78 ...this.statistics.statisticsData.get(command),
79 countRequest: 1,
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(command, {
91 ...this.statistics.statisticsData.get(command),
92 countResponse: 1,
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(command, {
104 ...this.statistics.statisticsData.get(command),
105 countError: 1,
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 delete this.displayInterval;
131 }
132 performance.clearMarks();
133 performance.clearMeasures();
134 this.performanceObserver?.disconnect();
135 }
136
137 public restart(): void {
138 this.stop();
139 this.start();
140 }
141
142 private initializePerformanceObserver(): void {
143 this.performanceObserver = new PerformanceObserver((performanceObserverList) => {
144 const lastPerformanceEntry = performanceObserverList.getEntries()[0];
145 // logger.debug(
146 // `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
147 // lastPerformanceEntry
148 // );
149 this.addPerformanceEntryToStatistics(lastPerformanceEntry);
150 });
151 this.performanceObserver.observe({ entryTypes: ['measure'] });
152 }
153
154 private logStatistics(): void {
155 logger.info(`${this.logPrefix()}`, {
156 ...this.statistics,
157 statisticsData: Utils.JSONStringifyWithMapSupport(this.statistics.statisticsData),
158 });
159 }
160
161 private startLogStatisticsInterval(): void {
162 if (Configuration.getLogStatisticsInterval() > 0 && !this.displayInterval) {
163 this.displayInterval = setInterval(() => {
164 this.logStatistics();
165 }, Configuration.getLogStatisticsInterval() * 1000);
166 logger.info(
167 `${this.logPrefix()} logged every ${Utils.formatDurationSeconds(
168 Configuration.getLogStatisticsInterval()
169 )}`
170 );
171 } else if (this.displayInterval) {
172 logger.info(
173 `${this.logPrefix()} already logged every ${Utils.formatDurationSeconds(
174 Configuration.getLogStatisticsInterval()
175 )}`
176 );
177 } else {
178 logger.info(
179 `${this.logPrefix()} log interval is set to ${Configuration.getLogStatisticsInterval()?.toString()}. Not logging statistics`
180 );
181 }
182 }
183
184 private median(dataSet: number[]): number {
185 if (Array.isArray(dataSet) === true && dataSet.length === 1) {
186 return dataSet[0];
187 }
188 const sortedDataSet = dataSet.slice().sort((a, b) => a - b);
189 const middleIndex = Math.floor(sortedDataSet.length / 2);
190 if (sortedDataSet.length % 2) {
191 return sortedDataSet[middleIndex / 2];
192 }
193 return (sortedDataSet[middleIndex - 1] + sortedDataSet[middleIndex]) / 2;
194 }
195
196 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
197 private percentile(dataSet: number[], percentile: number): number {
198 if (percentile < 0 && percentile > 100) {
199 throw new RangeError('Percentile is not between 0 and 100');
200 }
201 if (Utils.isEmptyArray(dataSet)) {
202 return 0;
203 }
204 const sortedDataSet = dataSet.slice().sort((a, b) => a - b);
205 if (percentile === 0) {
206 return sortedDataSet[0];
207 }
208 if (percentile === 100) {
209 return sortedDataSet[sortedDataSet.length - 1];
210 }
211 const percentileIndex = (percentile / 100) * sortedDataSet.length - 1;
212 if (Number.isInteger(percentileIndex)) {
213 return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2;
214 }
215 return sortedDataSet[Math.round(percentileIndex)];
216 }
217
218 private stdDeviation(dataSet: number[]): number {
219 let totalDataSet = 0;
220 for (const data of dataSet) {
221 totalDataSet += data;
222 }
223 const dataSetMean = totalDataSet / dataSet.length;
224 let totalGeometricDeviation = 0;
225 for (const data of dataSet) {
226 const deviation = data - dataSetMean;
227 totalGeometricDeviation += deviation * deviation;
228 }
229 return Math.sqrt(totalGeometricDeviation / dataSet.length);
230 }
231
232 private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
233 const entryName = entry.name;
234 // Initialize command statistics
235 if (!this.statistics.statisticsData.has(entryName)) {
236 this.statistics.statisticsData.set(entryName, {});
237 }
238 // Update current statistics
239 this.statistics.updatedAt = new Date();
240 this.statistics.statisticsData.get(entryName).countTimeMeasurement =
241 this.statistics.statisticsData.get(entryName)?.countTimeMeasurement
242 ? this.statistics.statisticsData.get(entryName).countTimeMeasurement + 1
243 : 1;
244 this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration;
245 this.statistics.statisticsData.get(entryName).minTimeMeasurement =
246 this.statistics.statisticsData.get(entryName)?.minTimeMeasurement
247 ? this.statistics.statisticsData.get(entryName).minTimeMeasurement > entry.duration
248 ? entry.duration
249 : this.statistics.statisticsData.get(entryName).minTimeMeasurement
250 : entry.duration;
251 this.statistics.statisticsData.get(entryName).maxTimeMeasurement =
252 this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement
253 ? this.statistics.statisticsData.get(entryName).maxTimeMeasurement < entry.duration
254 ? entry.duration
255 : this.statistics.statisticsData.get(entryName).maxTimeMeasurement
256 : entry.duration;
257 this.statistics.statisticsData.get(entryName).totalTimeMeasurement =
258 this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement
259 ? this.statistics.statisticsData.get(entryName).totalTimeMeasurement + entry.duration
260 : entry.duration;
261 this.statistics.statisticsData.get(entryName).avgTimeMeasurement =
262 this.statistics.statisticsData.get(entryName).totalTimeMeasurement /
263 this.statistics.statisticsData.get(entryName).countTimeMeasurement;
264 this.statistics.statisticsData.get(entryName)?.timeMeasurementSeries instanceof CircularArray
265 ? this.statistics.statisticsData
266 .get(entryName)
267 ?.timeMeasurementSeries?.push({ timestamp: entry.startTime, value: entry.duration })
268 : (this.statistics.statisticsData.get(entryName).timeMeasurementSeries =
269 new CircularArray<TimeSeries>(Constants.DEFAULT_CIRCULAR_BUFFER_CAPACITY, {
270 timestamp: entry.startTime,
271 value: entry.duration,
272 }));
273 this.statistics.statisticsData.get(entryName).medTimeMeasurement = this.median(
274 this.extractTimeSeriesValues(
275 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
276 )
277 );
278 this.statistics.statisticsData.get(entryName).ninetyFiveThPercentileTimeMeasurement =
279 this.percentile(
280 this.extractTimeSeriesValues(
281 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
282 ),
283 95
284 );
285 this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = this.stdDeviation(
286 this.extractTimeSeriesValues(
287 this.statistics.statisticsData.get(entryName).timeMeasurementSeries
288 )
289 );
290 if (Configuration.getPerformanceStorage().enabled) {
291 parentPort?.postMessage(
292 MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics)
293 );
294 }
295 }
296
297 private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] {
298 return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
299 }
300
301 private logPrefix = (): string => {
302 return Utils.logPrefix(` ${this.objName} | Performance statistics`);
303 };
304 }