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 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
105 logger
.error(`${this.logPrefix()} wrong message type ${messageType}`);
110 public start(): void {
111 this.startLogStatisticsInterval();
112 if (Configuration
.getPerformanceStorage().enabled
) {
114 `${this.logPrefix()} storage enabled: type ${
115 Configuration.getPerformanceStorage().type
116 }, uri: ${Configuration.getPerformanceStorage().uri}`
121 public stop(): void {
122 if (this.displayInterval
) {
123 clearInterval(this.displayInterval
);
125 performance
.clearMarks();
126 this.performanceObserver
?.disconnect();
129 public restart(): void {
134 private initializePerformanceObserver(): void {
135 this.performanceObserver
= new PerformanceObserver((list
) => {
136 const lastPerformanceEntry
= list
.getEntries()[0];
137 this.addPerformanceEntryToStatistics(lastPerformanceEntry
);
139 `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
143 this.performanceObserver
.observe({ entryTypes
: ['measure'] });
146 private logStatistics(): void {
147 logger
.info(this.logPrefix() + ' %j', this.statistics
);
150 private startLogStatisticsInterval(): void {
151 if (Configuration
.getLogStatisticsInterval() > 0) {
152 this.displayInterval
= setInterval(() => {
153 this.logStatistics();
154 }, Configuration
.getLogStatisticsInterval() * 1000);
158 Utils
.formatDurationSeconds(Configuration
.getLogStatisticsInterval())
163 ' log interval is set to ' +
164 Configuration
.getLogStatisticsInterval().toString() +
165 '. Not logging statistics'
170 private median(dataSet
: number[]): number {
171 if (Array.isArray(dataSet
) && dataSet
.length
=== 1) {
174 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
175 const middleIndex
= Math.floor(sortedDataSet
.length
/ 2);
176 if (sortedDataSet
.length
% 2) {
177 return sortedDataSet
[middleIndex
/ 2];
179 return (sortedDataSet
[middleIndex
- 1] + sortedDataSet
[middleIndex
]) / 2;
182 // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree
183 private percentile(dataSet
: number[], percentile
: number): number {
184 if (percentile
< 0 && percentile
> 100) {
185 throw new RangeError('Percentile is not between 0 and 100');
187 if (Utils
.isEmptyArray(dataSet
)) {
190 const sortedDataSet
= dataSet
.slice().sort((a
, b
) => a
- b
);
191 if (percentile
=== 0) {
192 return sortedDataSet
[0];
194 if (percentile
=== 100) {
195 return sortedDataSet
[sortedDataSet
.length
- 1];
197 const percentileIndex
= (percentile
/ 100) * sortedDataSet
.length
- 1;
198 if (Number.isInteger(percentileIndex
)) {
199 return (sortedDataSet
[percentileIndex
] + sortedDataSet
[percentileIndex
+ 1]) / 2;
201 return sortedDataSet
[Math.round(percentileIndex
)];
204 private stdDeviation(dataSet
: number[]): number {
205 let totalDataSet
= 0;
206 for (const data
of dataSet
) {
207 totalDataSet
+= data
;
209 const dataSetMean
= totalDataSet
/ dataSet
.length
;
210 let totalGeometricDeviation
= 0;
211 for (const data
of dataSet
) {
212 const deviation
= data
- dataSetMean
;
213 totalGeometricDeviation
+= deviation
* deviation
;
215 return Math.sqrt(totalGeometricDeviation
/ dataSet
.length
);
218 private addPerformanceEntryToStatistics(entry
: PerformanceEntry
): void {
219 let entryName
= entry
.name
;
221 const MAP_NAME
: Record
<string, string> = {};
222 if (MAP_NAME
[entryName
]) {
223 entryName
= MAP_NAME
[entryName
];
225 // Initialize command statistics
226 if (!this.statistics
.statisticsData
.has(entryName
)) {
227 this.statistics
.statisticsData
.set(entryName
, {});
229 // Update current statistics
230 this.statistics
.updatedAt
= new Date();
231 this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
=
232 this.statistics
.statisticsData
.get(entryName
)?.countTimeMeasurement
233 ? this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
+ 1
235 this.statistics
.statisticsData
.get(entryName
).currentTimeMeasurement
= entry
.duration
;
236 this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
=
237 this.statistics
.statisticsData
.get(entryName
)?.minTimeMeasurement
238 ? this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
> entry
.duration
240 : this.statistics
.statisticsData
.get(entryName
).minTimeMeasurement
242 this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
=
243 this.statistics
.statisticsData
.get(entryName
)?.maxTimeMeasurement
244 ? this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
< entry
.duration
246 : this.statistics
.statisticsData
.get(entryName
).maxTimeMeasurement
248 this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
=
249 this.statistics
.statisticsData
.get(entryName
)?.totalTimeMeasurement
250 ? this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
+ entry
.duration
252 this.statistics
.statisticsData
.get(entryName
).avgTimeMeasurement
=
253 this.statistics
.statisticsData
.get(entryName
).totalTimeMeasurement
/
254 this.statistics
.statisticsData
.get(entryName
).countTimeMeasurement
;
255 Array.isArray(this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
)
256 ? this.statistics
.statisticsData
258 .timeMeasurementSeries
.push({ timestamp
: entry
.startTime
, value
: entry
.duration
})
259 : (this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
=
260 new CircularArray
<TimeSeries
>(DEFAULT_CIRCULAR_ARRAY_SIZE
, {
261 timestamp
: entry
.startTime
,
262 value
: entry
.duration
,
264 this.statistics
.statisticsData
.get(entryName
).medTimeMeasurement
= this.median(
265 this.extractTimeSeriesValues(
266 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
269 this.statistics
.statisticsData
.get(entryName
).ninetyFiveThPercentileTimeMeasurement
=
271 this.extractTimeSeriesValues(
272 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
276 this.statistics
.statisticsData
.get(entryName
).stdDevTimeMeasurement
= this.stdDeviation(
277 this.extractTimeSeriesValues(
278 this.statistics
.statisticsData
.get(entryName
).timeMeasurementSeries
281 if (Configuration
.getPerformanceStorage().enabled
) {
282 parentPort
.postMessage({
283 id
: ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
,
284 data
: this.statistics
,
289 private extractTimeSeriesValues(timeSeries
: CircularArray
<TimeSeries
>): number[] {
290 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
293 private logPrefix(): string {
294 return Utils
.logPrefix(` ${this.objName} | Performance statistics`);