Storage: use worker threads message passing to store performance records from
[e-mobility-charging-stations-simulator.git] / src / utils / PerformanceStatistics.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
ef72d3f5 3import { CircularArray, DEFAULT_CIRCULAR_ARRAY_SIZE } from './CircularArray';
c0560973 4import { IncomingRequestCommand, RequestCommand } from '../types/ocpp/Requests';
57939a9d 5import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks';
aef1b33a 6import Statistics, { StatisticsData } from '../types/Statistics';
63b48f77 7
6af9012e 8import Configuration from './Configuration';
d2a64eb5 9import { MessageType } from '../types/ocpp/MessageType';
6af9012e 10import Utils from './Utils';
81797102 11import { WorkerEvents } from '../types/Worker';
6af9012e 12import logger from './Logger';
81797102 13import { parentPort } from 'worker_threads';
7dde0b73 14
54b1efe0 15export default class PerformanceStatistics {
418106c8 16 private objId: string;
aef1b33a
JB
17 private performanceObserver: PerformanceObserver;
18 private statistics: Statistics;
19 private displayInterval: NodeJS.Timeout;
560bcf5b 20
c0560973
JB
21 public constructor(objId: string) {
22 this.objId = objId;
aef1b33a 23 this.initializePerformanceObserver();
72f041bd 24 this.statistics = { id: this.objId ?? 'Object id not specified', createdAt: new Date(), statisticsData: {} };
560bcf5b
JB
25 }
26
aef1b33a
JB
27 public static beginMeasure(id: string): string {
28 const beginId = 'begin' + id.charAt(0).toUpperCase() + id.slice(1);
29 performance.mark(beginId);
30 return beginId;
57939a9d
JB
31 }
32
aef1b33a
JB
33 public static endMeasure(name: string, beginId: string): void {
34 performance.measure(name, beginId);
333eb100 35 performance.clearMarks(beginId);
aef1b33a
JB
36 }
37
38 public addRequestStatistic(command: RequestCommand | IncomingRequestCommand, messageType: MessageType): void {
7f134aca 39 switch (messageType) {
d2a64eb5 40 case MessageType.CALL_MESSAGE:
aef1b33a
JB
41 if (this.statistics.statisticsData[command] && this.statistics.statisticsData[command].countRequest) {
42 this.statistics.statisticsData[command].countRequest++;
7dde0b73 43 } else {
aef1b33a
JB
44 this.statistics.statisticsData[command] = {} as StatisticsData;
45 this.statistics.statisticsData[command].countRequest = 1;
7f134aca
JB
46 }
47 break;
d2a64eb5 48 case MessageType.CALL_RESULT_MESSAGE:
aef1b33a
JB
49 if (this.statistics.statisticsData[command]) {
50 if (this.statistics.statisticsData[command].countResponse) {
51 this.statistics.statisticsData[command].countResponse++;
7f134aca 52 } else {
aef1b33a 53 this.statistics.statisticsData[command].countResponse = 1;
7f134aca
JB
54 }
55 } else {
aef1b33a
JB
56 this.statistics.statisticsData[command] = {} as StatisticsData;
57 this.statistics.statisticsData[command].countResponse = 1;
7dde0b73 58 }
7f134aca 59 break;
d2a64eb5 60 case MessageType.CALL_ERROR_MESSAGE:
aef1b33a
JB
61 if (this.statistics.statisticsData[command]) {
62 if (this.statistics.statisticsData[command].countError) {
63 this.statistics.statisticsData[command].countError++;
7f134aca 64 } else {
aef1b33a 65 this.statistics.statisticsData[command].countError = 1;
7f134aca
JB
66 }
67 } else {
aef1b33a
JB
68 this.statistics.statisticsData[command] = {} as StatisticsData;
69 this.statistics.statisticsData[command].countError = 1;
7f134aca
JB
70 }
71 break;
72 default:
54b1efe0 73 logger.error(`${this.logPrefix()} wrong message type ${messageType}`);
7f134aca 74 break;
7dde0b73
JB
75 }
76 }
77
aef1b33a 78 public start(): void {
72f041bd
JB
79 this.startLogStatisticsInterval();
80 if (Configuration.getPerformanceStorage().enabled) {
81 logger.info(`${this.logPrefix()} storage enabled: type ${Configuration.getPerformanceStorage().type}, URI: ${Configuration.getPerformanceStorage().URI}`);
82 }
7dde0b73
JB
83 }
84
aef1b33a 85 public stop(): void {
7874b0b1
JB
86 if (this.displayInterval) {
87 clearInterval(this.displayInterval);
88 }
aef1b33a 89 performance.clearMarks();
087a502d
JB
90 this.performanceObserver?.disconnect();
91 }
92
93 public restart(): void {
94 this.stop();
95 this.start();
136c90ba
JB
96 }
97
aef1b33a
JB
98 private initializePerformanceObserver(): void {
99 this.performanceObserver = new PerformanceObserver((list) => {
b49422c6
JB
100 this.addPerformanceEntryToStatistics(list.getEntries()[0]);
101 logger.debug(`${this.logPrefix()} '${list.getEntries()[0].name}' performance entry: %j`, list.getEntries()[0]);
a0ba4ced 102 });
aef1b33a
JB
103 this.performanceObserver.observe({ entryTypes: ['measure'] });
104 }
105
aef1b33a
JB
106 private logStatistics(): void {
107 logger.info(this.logPrefix() + ' %j', this.statistics);
7dde0b73
JB
108 }
109
72f041bd
JB
110 private startLogStatisticsInterval(): void {
111 if (Configuration.getLogStatisticsInterval() > 0) {
aef1b33a
JB
112 this.displayInterval = setInterval(() => {
113 this.logStatistics();
72f041bd
JB
114 }, Configuration.getLogStatisticsInterval() * 1000);
115 logger.info(this.logPrefix() + ' logged every ' + Utils.secondsToHHMMSS(Configuration.getLogStatisticsInterval()));
aef1b33a 116 } else {
72f041bd 117 logger.info(this.logPrefix() + ' log interval is set to ' + Configuration.getLogStatisticsInterval().toString() + '. Not logging statistics');
7dde0b73
JB
118 }
119 }
120
6bf6769e
JB
121 private median(dataSet: number[]): number {
122 if (Array.isArray(dataSet) && dataSet.length === 1) {
123 return dataSet[0];
124 }
2891f761 125 const sortedDataSet = dataSet.slice().sort((a, b) => (a - b));
6bf6769e
JB
126 const middleIndex = Math.floor(sortedDataSet.length / 2);
127 if (sortedDataSet.length % 2) {
128 return sortedDataSet[middleIndex / 2];
129 }
130 return (sortedDataSet[(middleIndex - 1)] + sortedDataSet[middleIndex]) / 2;
131 }
132
b49422c6
JB
133 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
134 private percentile(dataSet: number[], percentile: number): number {
135 if (percentile < 0 && percentile > 100) {
136 throw new RangeError('Percentile is not between 0 and 100');
137 }
138 if (Utils.isEmptyArray(dataSet)) {
139 return 0;
140 }
2891f761 141 const sortedDataSet = dataSet.slice().sort((a, b) => (a - b));
b49422c6
JB
142 if (percentile === 0) {
143 return sortedDataSet[0];
144 }
145 if (percentile === 100) {
146 return sortedDataSet[sortedDataSet.length - 1];
147 }
148 const percentileIndex = ((percentile / 100) * sortedDataSet.length) - 1;
149 if (Number.isInteger(percentileIndex)) {
150 return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2;
151 }
152 return sortedDataSet[Math.round(percentileIndex)];
153 }
154
aeada1fa
JB
155 private stdDeviation(dataSet: number[]): number {
156 let totalDataSet = 0;
157 for (const data of dataSet) {
158 totalDataSet += data;
159 }
160 const dataSetMean = totalDataSet / dataSet.length;
161 let totalGeometricDeviation = 0;
162 for (const data of dataSet) {
163 const deviation = data - dataSetMean;
164 totalGeometricDeviation += deviation * deviation;
165 }
166 return Math.sqrt(totalGeometricDeviation / dataSet.length);
167 }
168
b49422c6
JB
169 private addPerformanceEntryToStatistics(entry: PerformanceEntry): void {
170 let entryName = entry.name;
e9017bfc 171 // Rename entry name
b49422c6
JB
172 const MAP_NAME: Record<string, string> = {};
173 if (MAP_NAME[entryName]) {
174 entryName = MAP_NAME[entryName];
7ec46a9a
JB
175 }
176 // Initialize command statistics
b49422c6
JB
177 if (!this.statistics.statisticsData[entryName]) {
178 this.statistics.statisticsData[entryName] = {} as StatisticsData;
7ec46a9a 179 }
b49422c6 180 // Update current statistics
72f041bd 181 this.statistics.lastUpdatedAt = new Date();
b49422c6
JB
182 this.statistics.statisticsData[entryName].countTimeMeasurement = this.statistics.statisticsData[entryName].countTimeMeasurement ? this.statistics.statisticsData[entryName].countTimeMeasurement + 1 : 1;
183 this.statistics.statisticsData[entryName].currentTimeMeasurement = entry.duration;
184 this.statistics.statisticsData[entryName].minTimeMeasurement = this.statistics.statisticsData[entryName].minTimeMeasurement ? (this.statistics.statisticsData[entryName].minTimeMeasurement > entry.duration ? entry.duration : this.statistics.statisticsData[entryName].minTimeMeasurement) : entry.duration;
185 this.statistics.statisticsData[entryName].maxTimeMeasurement = this.statistics.statisticsData[entryName].maxTimeMeasurement ? (this.statistics.statisticsData[entryName].maxTimeMeasurement < entry.duration ? entry.duration : this.statistics.statisticsData[entryName].maxTimeMeasurement) : entry.duration;
186 this.statistics.statisticsData[entryName].totalTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement ? this.statistics.statisticsData[entryName].totalTimeMeasurement + entry.duration : entry.duration;
187 this.statistics.statisticsData[entryName].avgTimeMeasurement = this.statistics.statisticsData[entryName].totalTimeMeasurement / this.statistics.statisticsData[entryName].countTimeMeasurement;
188 Array.isArray(this.statistics.statisticsData[entryName].timeMeasurementSeries) ? this.statistics.statisticsData[entryName].timeMeasurementSeries.push(entry.duration) : this.statistics.statisticsData[entryName].timeMeasurementSeries = new CircularArray<number>(DEFAULT_CIRCULAR_ARRAY_SIZE, entry.duration);
189 this.statistics.statisticsData[entryName].medTimeMeasurement = this.median(this.statistics.statisticsData[entryName].timeMeasurementSeries);
190 this.statistics.statisticsData[entryName].ninetyFiveThPercentileTimeMeasurement = this.percentile(this.statistics.statisticsData[entryName].timeMeasurementSeries, 95);
191 this.statistics.statisticsData[entryName].stdDevTimeMeasurement = this.stdDeviation(this.statistics.statisticsData[entryName].timeMeasurementSeries);
72f041bd 192 if (Configuration.getPerformanceStorage().enabled) {
81797102 193 parentPort.postMessage({ id: WorkerEvents.PERFORMANCE_STATISTICS, data: this.statistics });
72f041bd 194 }
7ec46a9a
JB
195 }
196
c0560973 197 private logPrefix(): string {
54b1efe0 198 return Utils.logPrefix(` ${this.objId} | Performance statistics`);
6af9012e 199 }
7dde0b73 200}