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 from
'../types/Statistics';
11 // eslint-disable-next-line no-duplicate-imports
12 import type { StatisticsData
, TimeSeries
} from
'../types/Statistics';
13 import { CircularArray
, DEFAULT_CIRCULAR_ARRAY_SIZE
} from
'../utils/CircularArray';
14 import Configuration from
'../utils/Configuration';
15 import logger from
'../utils/Logger';
16 import Utils from
'../utils/Utils';
18 export default class PerformanceStatistics
{
19 private static readonly instances
: Map
<string, PerformanceStatistics
> = new Map
<
24 private readonly objId
: string;
25 private readonly objName
: string;
26 private performanceObserver
: PerformanceObserver
;
27 private readonly statistics
: Statistics
;
28 private displayInterval
: NodeJS
.Timeout
;
30 private constructor(objId
: string, objName
: string, uri
: URL
) {
32 this.objName
= objName
;
33 this.initializePerformanceObserver();
35 id
: this.objId
?? 'Object id not specified',
36 name
: this.objName
?? 'Object name not specified',
38 createdAt
: new Date(),
39 statisticsData
: new Map
<string, Partial
<StatisticsData
>>(),
43 public static getInstance(
47 ): PerformanceStatistics
| undefined {
48 if (!PerformanceStatistics
.instances
.has(objId
)) {
49 PerformanceStatistics
.instances
.set(objId
, new PerformanceStatistics(objId
, objName
, uri
));
51 return PerformanceStatistics
.instances
.get(objId
);
54 public static beginMeasure(id
: string): string {
55 const markId
= `${id.charAt(0).toUpperCase() + id.slice(1)}~${Utils.generateUUID()}`;
56 performance
.mark(markId
);
60 public static endMeasure(name
: string, markId
: string): void {
61 performance
.measure(name
, markId
);
62 performance
.clearMarks(markId
);
65 public addRequestStatistic(
66 command
: RequestCommand
| IncomingRequestCommand
,
67 messageType
: MessageType
69 switch (messageType
) {
70 case MessageType
.CALL_MESSAGE
:
72 this.statistics
.statisticsData
.has(command
) &&
73 this.statistics
.statisticsData
.get(command
)?.countRequest
75 this.statistics
.statisticsData
.get(command
).countRequest
++;
77 this.statistics
.statisticsData
.set(
79 Object.assign({ countRequest
: 1 }, this.statistics
.statisticsData
.get(command
))
83 case MessageType
.CALL_RESULT_MESSAGE
:
85 this.statistics
.statisticsData
.has(command
) &&
86 this.statistics
.statisticsData
.get(command
)?.countResponse
88 this.statistics
.statisticsData
.get(command
).countResponse
++;
90 this.statistics
.statisticsData
.set(
92 Object.assign({ countResponse
: 1 }, this.statistics
.statisticsData
.get(command
))
96 case MessageType
.CALL_ERROR_MESSAGE
:
98 this.statistics
.statisticsData
.has(command
) &&
99 this.statistics
.statisticsData
.get(command
)?.countError
101 this.statistics
.statisticsData
.get(command
).countError
++;
103 this.statistics
.statisticsData
.set(
105 Object.assign({ countError
: 1 }, this.statistics
.statisticsData
.get(command
))
110 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
111 logger
.error(`${this.logPrefix()} wrong message type ${messageType}`);
116 public start(): void {
117 this.startLogStatisticsInterval();
118 if (Configuration
.getPerformanceStorage().enabled
) {
120 `${this.logPrefix()} storage enabled: type ${
121 Configuration.getPerformanceStorage().type
122 }, uri: ${Configuration.getPerformanceStorage().uri}`
127 public stop(): void {
128 if (this.displayInterval
) {
129 clearInterval(this.displayInterval
);
131 performance
.clearMarks();
132 this.performanceObserver
?.disconnect();
135 public restart(): void {
140 private initializePerformanceObserver(): void {
141 this.performanceObserver
= new PerformanceObserver((list
) => {
142 const lastPerformanceEntry
= list
.getEntries()[0];
143 this.addPerformanceEntryToStatistics(lastPerformanceEntry
);
145 `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
149 this.performanceObserver
.observe({ entryTypes
: ['measure'] });
152 private logStatistics(): void {
153 logger
.info(this.logPrefix() + ' %j', this.statistics
);
156 private startLogStatisticsInterval(): void {
157 if (Configuration
.getLogStatisticsInterval() > 0) {
158 this.displayInterval
= setInterval(() => {
159 this.logStatistics();
160 }, Configuration
.getLogStatisticsInterval() * 1000);
164 Utils
.formatDurationSeconds(Configuration
.getLogStatisticsInterval())
169 ' log interval is set to ' +
170 Configuration
.getLogStatisticsInterval().toString() +
171 '. Not logging statistics'
176 private median(dataSet
: number[]): number {
177 if (Array.isArray(dataSet
) && dataSet
.length
=== 1) {
180 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
181 const middleIndex
= Math.floor(sortedDataSet
.length
/ 2);
182 if (sortedDataSet
.length
% 2) {
183 return sortedDataSet
[middleIndex
/ 2];
185 return (sortedDataSet
[middleIndex
- 1] + sortedDataSet
[middleIndex
]) / 2;
188 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
189 private percentile(dataSet
: number[], percentile
: number): number {
190 if (percentile
< 0 && percentile
> 100) {
191 throw new RangeError('Percentile is not between 0 and 100');
193 if (Utils
.isEmptyArray(dataSet
)) {
196 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
197 if (percentile
=== 0) {
198 return sortedDataSet
[0];
200 if (percentile
=== 100) {
201 return sortedDataSet
[sortedDataSet
.length
- 1];
203 const percentileIndex
= (percentile
/ 100) * sortedDataSet
.length
- 1;
204 if (Number.isInteger(percentileIndex
)) {
205 return (sortedDataSet
[percentileIndex
] + sortedDataSet
[percentileIndex
+ 1]) / 2;
207 return sortedDataSet
[Math.round(percentileIndex
)];
210 private stdDeviation(dataSet
: number[]): number {
211 let totalDataSet
= 0;
212 for (const data
of dataSet
) {
213 totalDataSet
+= data
;
215 const dataSetMean
= totalDataSet
/ dataSet
.length
;
216 let totalGeometricDeviation
= 0;
217 for (const data
of dataSet
) {
218 const deviation
= data
- dataSetMean
;
219 totalGeometricDeviation
+= deviation
* deviation
;
221 return Math.sqrt(totalGeometricDeviation
/ dataSet
.length
);
224 private addPerformanceEntryToStatistics(entry
: PerformanceEntry
): void {
225 let entryName
= entry
.name
;
227 const MAP_NAME
: Record
<string, string> = {};
228 if (MAP_NAME
[entryName
]) {
229 entryName
= MAP_NAME
[entryName
];
231 // Initialize command statistics
232 if (!this.statistics
.statisticsData
.has(entryName
)) {
233 this.statistics
.statisticsData
.set(entryName
, {});
235 // Update current statistics
236 this.statistics
.updatedAt
= new Date();
237 this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
=
238 this.statistics
.statisticsData
.get(entryName
)?.countTimeMeasurement
239 ? this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
+ 1
241 this.statistics
.statisticsData
.get(entryName
).currentTimeMeasurement
= entry
.duration
;
242 this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
=
243 this.statistics
.statisticsData
.get(entryName
)?.minTimeMeasurement
244 ? this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
> entry
.duration
246 : this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
248 this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
=
249 this.statistics
.statisticsData
.get(entryName
)?.maxTimeMeasurement
250 ? this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
< entry
.duration
252 : this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
254 this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
=
255 this.statistics
.statisticsData
.get(entryName
)?.totalTimeMeasurement
256 ? this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
+ entry
.duration
258 this.statistics
.statisticsData
.get(entryName
).avgTimeMeasurement
=
259 this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
/
260 this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
;
261 Array.isArray(this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
)
262 ? this.statistics
.statisticsData
264 .timeMeasurementSeries
.push({ timestamp
: entry
.startTime
, value
: entry
.duration
})
265 : (this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
=
266 new CircularArray
<TimeSeries
>(DEFAULT_CIRCULAR_ARRAY_SIZE
, {
267 timestamp
: entry
.startTime
,
268 value
: entry
.duration
,
270 this.statistics
.statisticsData
.get(entryName
).medTimeMeasurement
= this.median(
271 this.extractTimeSeriesValues(
272 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
275 this.statistics
.statisticsData
.get(entryName
).ninetyFiveThPercentileTimeMeasurement
=
277 this.extractTimeSeriesValues(
278 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
282 this.statistics
.statisticsData
.get(entryName
).stdDevTimeMeasurement
= this.stdDeviation(
283 this.extractTimeSeriesValues(
284 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
287 if (Configuration
.getPerformanceStorage().enabled
) {
288 parentPort
.postMessage(
289 MessageChannelUtils
.buildPerformanceStatisticsMessage(this.statistics
)
294 private extractTimeSeriesValues(timeSeries
: CircularArray
<TimeSeries
>): number[] {
295 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
298 private logPrefix(): string {
299 return Utils
.logPrefix(` ${this.objName} | Performance statistics`);