1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { PerformanceEntry
, PerformanceObserver
, performance
} from
'perf_hooks';
4 import type { URL
} from
'url';
5 import { parentPort
} from
'worker_threads';
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
, StatisticsData
, TimeSeries
} from
'../types/Statistics';
11 import { CircularArray
, DEFAULT_CIRCULAR_ARRAY_SIZE
} from
'../utils/CircularArray';
12 import Configuration from
'../utils/Configuration';
13 import logger from
'../utils/Logger';
14 import Utils from
'../utils/Utils';
16 export default class PerformanceStatistics
{
17 private static readonly instances
: Map
<string, PerformanceStatistics
> = new Map
<
22 private readonly objId
: string;
23 private readonly objName
: string;
24 private performanceObserver
: PerformanceObserver
;
25 private readonly statistics
: Statistics
;
26 private displayInterval
: NodeJS
.Timeout
;
28 private constructor(objId
: string, objName
: string, uri
: URL
) {
30 this.objName
= objName
;
31 this.initializePerformanceObserver();
33 id
: this.objId
?? 'Object id not specified',
34 name
: this.objName
?? 'Object name not specified',
36 createdAt
: new Date(),
37 statisticsData
: new Map
<string, Partial
<StatisticsData
>>(),
41 public static getInstance(
45 ): PerformanceStatistics
| undefined {
46 if (!PerformanceStatistics
.instances
.has(objId
)) {
47 PerformanceStatistics
.instances
.set(objId
, new PerformanceStatistics(objId
, objName
, uri
));
49 return PerformanceStatistics
.instances
.get(objId
);
52 public static beginMeasure(id
: string): string {
53 const markId
= `${id.charAt(0).toUpperCase() + id.slice(1)}~${Utils.generateUUID()}`;
54 performance
.mark(markId
);
58 public static endMeasure(name
: string, markId
: string): void {
59 performance
.measure(name
, markId
);
60 performance
.clearMarks(markId
);
63 public addRequestStatistic(
64 command
: RequestCommand
| IncomingRequestCommand
,
65 messageType
: MessageType
67 switch (messageType
) {
68 case MessageType
.CALL_MESSAGE
:
70 this.statistics
.statisticsData
.has(command
) &&
71 this.statistics
.statisticsData
.get(command
)?.countRequest
73 this.statistics
.statisticsData
.get(command
).countRequest
++;
75 this.statistics
.statisticsData
.set(
77 Object.assign({ countRequest
: 1 }, this.statistics
.statisticsData
.get(command
))
81 case MessageType
.CALL_RESULT_MESSAGE
:
83 this.statistics
.statisticsData
.has(command
) &&
84 this.statistics
.statisticsData
.get(command
)?.countResponse
86 this.statistics
.statisticsData
.get(command
).countResponse
++;
88 this.statistics
.statisticsData
.set(
90 Object.assign({ countResponse
: 1 }, this.statistics
.statisticsData
.get(command
))
94 case MessageType
.CALL_ERROR_MESSAGE
:
96 this.statistics
.statisticsData
.has(command
) &&
97 this.statistics
.statisticsData
.get(command
)?.countError
99 this.statistics
.statisticsData
.get(command
).countError
++;
101 this.statistics
.statisticsData
.set(
103 Object.assign({ countError
: 1 }, this.statistics
.statisticsData
.get(command
))
108 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
109 logger
.error(`${this.logPrefix()} wrong message type ${messageType}`);
114 public start(): void {
115 this.startLogStatisticsInterval();
116 if (Configuration
.getPerformanceStorage().enabled
) {
118 `${this.logPrefix()} storage enabled: type ${
119 Configuration.getPerformanceStorage().type
120 }, uri: ${Configuration.getPerformanceStorage().uri}`
125 public stop(): void {
126 if (this.displayInterval
) {
127 clearInterval(this.displayInterval
);
129 performance
.clearMarks();
130 this.performanceObserver
?.disconnect();
133 public restart(): void {
138 private initializePerformanceObserver(): void {
139 this.performanceObserver
= new PerformanceObserver((list
) => {
140 const lastPerformanceEntry
= list
.getEntries()[0];
141 this.addPerformanceEntryToStatistics(lastPerformanceEntry
);
143 `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
147 this.performanceObserver
.observe({ entryTypes
: ['measure'] });
150 private logStatistics(): void {
151 logger
.info(this.logPrefix() + ' %j', this.statistics
);
154 private startLogStatisticsInterval(): void {
155 if (Configuration
.getLogStatisticsInterval() > 0) {
156 this.displayInterval
= setInterval(() => {
157 this.logStatistics();
158 }, Configuration
.getLogStatisticsInterval() * 1000);
162 Utils
.formatDurationSeconds(Configuration
.getLogStatisticsInterval())
167 ' log interval is set to ' +
168 Configuration
.getLogStatisticsInterval().toString() +
169 '. Not logging statistics'
174 private median(dataSet
: number[]): number {
175 if (Array.isArray(dataSet
) && dataSet
.length
=== 1) {
178 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
179 const middleIndex
= Math.floor(sortedDataSet
.length
/ 2);
180 if (sortedDataSet
.length
% 2) {
181 return sortedDataSet
[middleIndex
/ 2];
183 return (sortedDataSet
[middleIndex
- 1] + sortedDataSet
[middleIndex
]) / 2;
186 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
187 private percentile(dataSet
: number[], percentile
: number): number {
188 if (percentile
< 0 && percentile
> 100) {
189 throw new RangeError('Percentile is not between 0 and 100');
191 if (Utils
.isEmptyArray(dataSet
)) {
194 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
195 if (percentile
=== 0) {
196 return sortedDataSet
[0];
198 if (percentile
=== 100) {
199 return sortedDataSet
[sortedDataSet
.length
- 1];
201 const percentileIndex
= (percentile
/ 100) * sortedDataSet
.length
- 1;
202 if (Number.isInteger(percentileIndex
)) {
203 return (sortedDataSet
[percentileIndex
] + sortedDataSet
[percentileIndex
+ 1]) / 2;
205 return sortedDataSet
[Math.round(percentileIndex
)];
208 private stdDeviation(dataSet
: number[]): number {
209 let totalDataSet
= 0;
210 for (const data
of dataSet
) {
211 totalDataSet
+= data
;
213 const dataSetMean
= totalDataSet
/ dataSet
.length
;
214 let totalGeometricDeviation
= 0;
215 for (const data
of dataSet
) {
216 const deviation
= data
- dataSetMean
;
217 totalGeometricDeviation
+= deviation
* deviation
;
219 return Math.sqrt(totalGeometricDeviation
/ dataSet
.length
);
222 private addPerformanceEntryToStatistics(entry
: PerformanceEntry
): void {
223 const entryName
= entry
.name
;
224 // Initialize command statistics
225 if (!this.statistics
.statisticsData
.has(entryName
)) {
226 this.statistics
.statisticsData
.set(entryName
, {});
228 // Update current statistics
229 this.statistics
.updatedAt
= new Date();
230 this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
=
231 this.statistics
.statisticsData
.get(entryName
)?.countTimeMeasurement
232 ? this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
+ 1
234 this.statistics
.statisticsData
.get(entryName
).currentTimeMeasurement
= entry
.duration
;
235 this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
=
236 this.statistics
.statisticsData
.get(entryName
)?.minTimeMeasurement
237 ? this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
> entry
.duration
239 : this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
241 this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
=
242 this.statistics
.statisticsData
.get(entryName
)?.maxTimeMeasurement
243 ? this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
< entry
.duration
245 : this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
247 this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
=
248 this.statistics
.statisticsData
.get(entryName
)?.totalTimeMeasurement
249 ? this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
+ entry
.duration
251 this.statistics
.statisticsData
.get(entryName
).avgTimeMeasurement
=
252 this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
/
253 this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
;
254 Array.isArray(this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
)
255 ? this.statistics
.statisticsData
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
,
263 this.statistics
.statisticsData
.get(entryName
).medTimeMeasurement
= this.median(
264 this.extractTimeSeriesValues(
265 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
268 this.statistics
.statisticsData
.get(entryName
).ninetyFiveThPercentileTimeMeasurement
=
270 this.extractTimeSeriesValues(
271 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
275 this.statistics
.statisticsData
.get(entryName
).stdDevTimeMeasurement
= this.stdDeviation(
276 this.extractTimeSeriesValues(
277 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
280 if (Configuration
.getPerformanceStorage().enabled
) {
281 parentPort
.postMessage(
282 MessageChannelUtils
.buildPerformanceStatisticsMessage(this.statistics
)
287 private extractTimeSeriesValues(timeSeries
: CircularArray
<TimeSeries
>): number[] {
288 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
291 private logPrefix(): string {
292 return Utils
.logPrefix(` ${this.objName} | Performance statistics`);