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