1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { CircularArray
, DEFAULT_CIRCULAR_ARRAY_SIZE
} from
'../utils/CircularArray';
4 import { IncomingRequestCommand
, RequestCommand
} from
'../types/ocpp/Requests';
5 import { PerformanceEntry
, PerformanceObserver
, performance
} from
'perf_hooks';
6 import Statistics
, { StatisticsData
, TimeSeries
} from
'../types/Statistics';
8 import { ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
9 import Configuration from
'../utils/Configuration';
10 import { MessageType
} from
'../types/ocpp/MessageType';
11 import { URL
} from
'url';
12 import Utils from
'../utils/Utils';
13 import logger from
'../utils/Logger';
14 import { parentPort
} from
'worker_threads';
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(objId
: string, objName
: string, uri
: URL
): PerformanceStatistics
{
42 if (!PerformanceStatistics
.instances
.has(objId
)) {
43 PerformanceStatistics
.instances
.set(objId
, new PerformanceStatistics(objId
, objName
, uri
));
45 return PerformanceStatistics
.instances
.get(objId
);
48 public static beginMeasure(id
: string): string {
49 const markId
= `${id.charAt(0).toUpperCase() + id.slice(1)}~${Utils.generateUUID()}`;
50 performance
.mark(markId
);
54 public static endMeasure(name
: string, markId
: string): void {
55 performance
.measure(name
, markId
);
56 performance
.clearMarks(markId
);
59 public addRequestStatistic(
60 command
: RequestCommand
| IncomingRequestCommand
,
61 messageType
: MessageType
63 switch (messageType
) {
64 case MessageType
.CALL_MESSAGE
:
66 this.statistics
.statisticsData
.has(command
) &&
67 this.statistics
.statisticsData
.get(command
)?.countRequest
69 this.statistics
.statisticsData
.get(command
).countRequest
++;
71 this.statistics
.statisticsData
.set(
73 Object.assign({ countRequest
: 1 }, this.statistics
.statisticsData
.get(command
))
77 case MessageType
.CALL_RESULT_MESSAGE
:
79 this.statistics
.statisticsData
.has(command
) &&
80 this.statistics
.statisticsData
.get(command
)?.countResponse
82 this.statistics
.statisticsData
.get(command
).countResponse
++;
84 this.statistics
.statisticsData
.set(
86 Object.assign({ countResponse
: 1 }, this.statistics
.statisticsData
.get(command
))
90 case MessageType
.CALL_ERROR_MESSAGE
:
92 this.statistics
.statisticsData
.has(command
) &&
93 this.statistics
.statisticsData
.get(command
)?.countError
95 this.statistics
.statisticsData
.get(command
).countError
++;
97 this.statistics
.statisticsData
.set(
99 Object.assign({ countError
: 1 }, this.statistics
.statisticsData
.get(command
))
104 logger
.error(`${this.logPrefix()} wrong message type ${messageType}`);
109 public start(): void {
110 this.startLogStatisticsInterval();
111 if (Configuration
.getPerformanceStorage().enabled
) {
113 `${this.logPrefix()} storage enabled: type ${
114 Configuration.getPerformanceStorage().type
115 }, uri: ${Configuration.getPerformanceStorage().uri}`
120 public stop(): void {
121 if (this.displayInterval
) {
122 clearInterval(this.displayInterval
);
124 performance
.clearMarks();
125 this.performanceObserver
?.disconnect();
128 public restart(): void {
133 private initializePerformanceObserver(): void {
134 this.performanceObserver
= new PerformanceObserver((list
) => {
135 const lastPerformanceEntry
= list
.getEntries()[0];
136 this.addPerformanceEntryToStatistics(lastPerformanceEntry
);
138 `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
142 this.performanceObserver
.observe({ entryTypes
: ['measure'] });
145 private logStatistics(): void {
146 logger
.info(this.logPrefix() + ' %j', this.statistics
);
149 private startLogStatisticsInterval(): void {
150 if (Configuration
.getLogStatisticsInterval() > 0) {
151 this.displayInterval
= setInterval(() => {
152 this.logStatistics();
153 }, Configuration
.getLogStatisticsInterval() * 1000);
157 Utils
.formatDurationSeconds(Configuration
.getLogStatisticsInterval())
162 ' log interval is set to ' +
163 Configuration
.getLogStatisticsInterval().toString() +
164 '. Not logging statistics'
169 private median(dataSet
: number[]): number {
170 if (Array.isArray(dataSet
) && dataSet
.length
=== 1) {
173 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
174 const middleIndex
= Math.floor(sortedDataSet
.length
/ 2);
175 if (sortedDataSet
.length
% 2) {
176 return sortedDataSet
[middleIndex
/ 2];
178 return (sortedDataSet
[middleIndex
- 1] + sortedDataSet
[middleIndex
]) / 2;
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');
186 if (Utils
.isEmptyArray(dataSet
)) {
189 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
190 if (percentile
=== 0) {
191 return sortedDataSet
[0];
193 if (percentile
=== 100) {
194 return sortedDataSet
[sortedDataSet
.length
- 1];
196 const percentileIndex
= (percentile
/ 100) * sortedDataSet
.length
- 1;
197 if (Number.isInteger(percentileIndex
)) {
198 return (sortedDataSet
[percentileIndex
] + sortedDataSet
[percentileIndex
+ 1]) / 2;
200 return sortedDataSet
[Math.round(percentileIndex
)];
203 private stdDeviation(dataSet
: number[]): number {
204 let totalDataSet
= 0;
205 for (const data
of dataSet
) {
206 totalDataSet
+= data
;
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
;
214 return Math.sqrt(totalGeometricDeviation
/ dataSet
.length
);
217 private addPerformanceEntryToStatistics(entry
: PerformanceEntry
): void {
218 let entryName
= entry
.name
;
220 const MAP_NAME
: Record
<string, string> = {};
221 if (MAP_NAME
[entryName
]) {
222 entryName
= MAP_NAME
[entryName
];
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 id
: ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
,
283 data
: this.statistics
,
288 private extractTimeSeriesValues(timeSeries
: CircularArray
<TimeSeries
>): number[] {
289 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
292 private logPrefix(): string {
293 return Utils
.logPrefix(` ${this.objName} | Performance statistics`);