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