Commit | Line | Data |
---|---|---|
edd13439 | 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
c8eeb62b | 2 | |
130783a7 | 3 | import type { URL } from 'node:url'; |
57939a9d | 4 | import { PerformanceEntry, PerformanceObserver, performance } from 'perf_hooks'; |
8114d10e | 5 | import { parentPort } from 'worker_threads'; |
63b48f77 | 6 | |
32de5a57 | 7 | import { MessageChannelUtils } from '../charging-station/MessageChannelUtils'; |
268a74bb JB |
8 | import { |
9 | type IncomingRequestCommand, | |
10 | MessageType, | |
11 | type RequestCommand, | |
12 | type Statistics, | |
13 | type TimeSeries, | |
14 | } from '../types'; | |
9a15316c | 15 | import { CircularArray } from '../utils/CircularArray'; |
268a74bb JB |
16 | import { Configuration } from '../utils/Configuration'; |
17 | import { Constants } from '../utils/Constants'; | |
18 | import { logger } from '../utils/Logger'; | |
19 | import { Utils } from '../utils/Utils'; | |
7dde0b73 | 20 | |
268a74bb | 21 | export class PerformanceStatistics { |
e7aeea18 JB |
22 | private static readonly instances: Map<string, PerformanceStatistics> = new Map< |
23 | string, | |
24 | PerformanceStatistics | |
25 | >(); | |
10068088 | 26 | |
9e23580d | 27 | private readonly objId: string; |
9f2e3130 | 28 | private readonly objName: string; |
1895299d | 29 | private performanceObserver!: PerformanceObserver; |
9e23580d | 30 | private readonly statistics: Statistics; |
1895299d | 31 | private displayInterval!: NodeJS.Timeout; |
560bcf5b | 32 | |
9f2e3130 | 33 | private constructor(objId: string, objName: string, uri: URL) { |
c0560973 | 34 | this.objId = objId; |
9f2e3130 | 35 | this.objName = objName; |
aef1b33a | 36 | this.initializePerformanceObserver(); |
e7aeea18 JB |
37 | this.statistics = { |
38 | id: this.objId ?? 'Object id not specified', | |
39 | name: this.objName ?? 'Object name not specified', | |
40 | uri: uri.toString(), | |
41 | createdAt: new Date(), | |
1e4b0e4b | 42 | statisticsData: new Map(), |
e7aeea18 | 43 | }; |
9f2e3130 JB |
44 | } |
45 | ||
844e496b JB |
46 | public static getInstance( |
47 | objId: string, | |
48 | objName: string, | |
49 | uri: URL | |
50 | ): PerformanceStatistics | undefined { | |
9f2e3130 JB |
51 | if (!PerformanceStatistics.instances.has(objId)) { |
52 | PerformanceStatistics.instances.set(objId, new PerformanceStatistics(objId, objName, uri)); | |
53 | } | |
54 | return PerformanceStatistics.instances.get(objId); | |
560bcf5b JB |
55 | } |
56 | ||
aef1b33a | 57 | public static beginMeasure(id: string): string { |
14ecae6a | 58 | const markId = `${id.charAt(0).toUpperCase()}${id.slice(1)}~${Utils.generateUUID()}`; |
c63c21bc JB |
59 | performance.mark(markId); |
60 | return markId; | |
57939a9d JB |
61 | } |
62 | ||
c63c21bc JB |
63 | public static endMeasure(name: string, markId: string): void { |
64 | performance.measure(name, markId); | |
65 | performance.clearMarks(markId); | |
c60af6ca | 66 | performance.clearMeasures(name); |
aef1b33a JB |
67 | } |
68 | ||
e7aeea18 JB |
69 | public addRequestStatistic( |
70 | command: RequestCommand | IncomingRequestCommand, | |
71 | messageType: MessageType | |
72 | ): void { | |
7f134aca | 73 | switch (messageType) { |
d2a64eb5 | 74 | case MessageType.CALL_MESSAGE: |
e7aeea18 JB |
75 | if ( |
76 | this.statistics.statisticsData.has(command) && | |
77 | this.statistics.statisticsData.get(command)?.countRequest | |
78 | ) { | |
ff4b895e | 79 | this.statistics.statisticsData.get(command).countRequest++; |
7dde0b73 | 80 | } else { |
e7aeea18 JB |
81 | this.statistics.statisticsData.set( |
82 | command, | |
83 | Object.assign({ countRequest: 1 }, this.statistics.statisticsData.get(command)) | |
84 | ); | |
7f134aca JB |
85 | } |
86 | break; | |
d2a64eb5 | 87 | case MessageType.CALL_RESULT_MESSAGE: |
e7aeea18 JB |
88 | if ( |
89 | this.statistics.statisticsData.has(command) && | |
90 | this.statistics.statisticsData.get(command)?.countResponse | |
91 | ) { | |
ff4b895e | 92 | this.statistics.statisticsData.get(command).countResponse++; |
7f134aca | 93 | } else { |
e7aeea18 JB |
94 | this.statistics.statisticsData.set( |
95 | command, | |
96 | Object.assign({ countResponse: 1 }, this.statistics.statisticsData.get(command)) | |
97 | ); | |
7dde0b73 | 98 | } |
7f134aca | 99 | break; |
d2a64eb5 | 100 | case MessageType.CALL_ERROR_MESSAGE: |
e7aeea18 JB |
101 | if ( |
102 | this.statistics.statisticsData.has(command) && | |
103 | this.statistics.statisticsData.get(command)?.countError | |
104 | ) { | |
ff4b895e | 105 | this.statistics.statisticsData.get(command).countError++; |
7f134aca | 106 | } else { |
e7aeea18 JB |
107 | this.statistics.statisticsData.set( |
108 | command, | |
109 | Object.assign({ countError: 1 }, this.statistics.statisticsData.get(command)) | |
110 | ); | |
7f134aca JB |
111 | } |
112 | break; | |
113 | default: | |
9534e74e | 114 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
9f2e3130 | 115 | logger.error(`${this.logPrefix()} wrong message type ${messageType}`); |
7f134aca | 116 | break; |
7dde0b73 JB |
117 | } |
118 | } | |
119 | ||
aef1b33a | 120 | public start(): void { |
72f041bd JB |
121 | this.startLogStatisticsInterval(); |
122 | if (Configuration.getPerformanceStorage().enabled) { | |
e7aeea18 JB |
123 | logger.info( |
124 | `${this.logPrefix()} storage enabled: type ${ | |
125 | Configuration.getPerformanceStorage().type | |
126 | }, uri: ${Configuration.getPerformanceStorage().uri}` | |
127 | ); | |
72f041bd | 128 | } |
7dde0b73 JB |
129 | } |
130 | ||
aef1b33a | 131 | public stop(): void { |
7874b0b1 JB |
132 | if (this.displayInterval) { |
133 | clearInterval(this.displayInterval); | |
134 | } | |
aef1b33a | 135 | performance.clearMarks(); |
c60af6ca | 136 | performance.clearMeasures(); |
087a502d JB |
137 | this.performanceObserver?.disconnect(); |
138 | } | |
139 | ||
140 | public restart(): void { | |
141 | this.stop(); | |
142 | this.start(); | |
136c90ba JB |
143 | } |
144 | ||
aef1b33a | 145 | private initializePerformanceObserver(): void { |
72092cfc | 146 | this.performanceObserver = new PerformanceObserver((performanceObserverList) => { |
c60af6ca | 147 | const lastPerformanceEntry = performanceObserverList.getEntries()[0]; |
9d1dc4b1 JB |
148 | // logger.debug( |
149 | // `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`, | |
150 | // lastPerformanceEntry | |
151 | // ); | |
eb835fa8 | 152 | this.addPerformanceEntryToStatistics(lastPerformanceEntry); |
a0ba4ced | 153 | }); |
aef1b33a JB |
154 | this.performanceObserver.observe({ entryTypes: ['measure'] }); |
155 | } | |
156 | ||
aef1b33a | 157 | private logStatistics(): void { |
c60af6ca JB |
158 | logger.info(`${this.logPrefix()}`, { |
159 | ...this.statistics, | |
160 | statisticsData: Utils.JSONStringifyWithMapSupport(this.statistics.statisticsData), | |
161 | }); | |
7dde0b73 JB |
162 | } |
163 | ||
72f041bd JB |
164 | private startLogStatisticsInterval(): void { |
165 | if (Configuration.getLogStatisticsInterval() > 0) { | |
aef1b33a JB |
166 | this.displayInterval = setInterval(() => { |
167 | this.logStatistics(); | |
72f041bd | 168 | }, Configuration.getLogStatisticsInterval() * 1000); |
e7aeea18 | 169 | logger.info( |
44eb6026 JB |
170 | `${this.logPrefix()} logged every ${Utils.formatDurationSeconds( |
171 | Configuration.getLogStatisticsInterval() | |
172 | )}` | |
e7aeea18 | 173 | ); |
aef1b33a | 174 | } else { |
e7aeea18 | 175 | logger.info( |
72092cfc | 176 | `${this.logPrefix()} log interval is set to ${Configuration.getLogStatisticsInterval()?.toString()}. Not logging statistics` |
e7aeea18 | 177 | ); |
7dde0b73 JB |
178 | } |
179 | } | |
180 | ||
6bf6769e | 181 | private median(dataSet: number[]): number { |
5f7e72c1 | 182 | if (Array.isArray(dataSet) === true && dataSet.length === 1) { |
6bf6769e JB |
183 | return dataSet[0]; |
184 | } | |
e7aeea18 | 185 | const sortedDataSet = dataSet.slice().sort((a, b) => a - b); |
6bf6769e JB |
186 | const middleIndex = Math.floor(sortedDataSet.length / 2); |
187 | if (sortedDataSet.length % 2) { | |
188 | return sortedDataSet[middleIndex / 2]; | |
189 | } | |
e7aeea18 | 190 | return (sortedDataSet[middleIndex - 1] + sortedDataSet[middleIndex]) / 2; |
6bf6769e JB |
191 | } |
192 | ||
b49422c6 JB |
193 | // TODO: use order statistics tree https://en.wikipedia.org/wiki/Order_statistic_tree |
194 | private percentile(dataSet: number[], percentile: number): number { | |
195 | if (percentile < 0 && percentile > 100) { | |
196 | throw new RangeError('Percentile is not between 0 and 100'); | |
197 | } | |
198 | if (Utils.isEmptyArray(dataSet)) { | |
199 | return 0; | |
200 | } | |
e7aeea18 | 201 | const sortedDataSet = dataSet.slice().sort((a, b) => a - b); |
b49422c6 JB |
202 | if (percentile === 0) { |
203 | return sortedDataSet[0]; | |
204 | } | |
205 | if (percentile === 100) { | |
206 | return sortedDataSet[sortedDataSet.length - 1]; | |
207 | } | |
e7aeea18 | 208 | const percentileIndex = (percentile / 100) * sortedDataSet.length - 1; |
b49422c6 JB |
209 | if (Number.isInteger(percentileIndex)) { |
210 | return (sortedDataSet[percentileIndex] + sortedDataSet[percentileIndex + 1]) / 2; | |
211 | } | |
212 | return sortedDataSet[Math.round(percentileIndex)]; | |
213 | } | |
214 | ||
aeada1fa JB |
215 | private stdDeviation(dataSet: number[]): number { |
216 | let totalDataSet = 0; | |
217 | for (const data of dataSet) { | |
218 | totalDataSet += data; | |
219 | } | |
220 | const dataSetMean = totalDataSet / dataSet.length; | |
221 | let totalGeometricDeviation = 0; | |
222 | for (const data of dataSet) { | |
223 | const deviation = data - dataSetMean; | |
224 | totalGeometricDeviation += deviation * deviation; | |
225 | } | |
226 | return Math.sqrt(totalGeometricDeviation / dataSet.length); | |
227 | } | |
228 | ||
b49422c6 | 229 | private addPerformanceEntryToStatistics(entry: PerformanceEntry): void { |
976d11ec | 230 | const entryName = entry.name; |
7ec46a9a | 231 | // Initialize command statistics |
ff4b895e JB |
232 | if (!this.statistics.statisticsData.has(entryName)) { |
233 | this.statistics.statisticsData.set(entryName, {}); | |
7ec46a9a | 234 | } |
b49422c6 | 235 | // Update current statistics |
a6b3c6c3 | 236 | this.statistics.updatedAt = new Date(); |
e7aeea18 JB |
237 | this.statistics.statisticsData.get(entryName).countTimeMeasurement = |
238 | this.statistics.statisticsData.get(entryName)?.countTimeMeasurement | |
239 | ? this.statistics.statisticsData.get(entryName).countTimeMeasurement + 1 | |
240 | : 1; | |
ff4b895e | 241 | this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration; |
e7aeea18 JB |
242 | this.statistics.statisticsData.get(entryName).minTimeMeasurement = |
243 | this.statistics.statisticsData.get(entryName)?.minTimeMeasurement | |
244 | ? this.statistics.statisticsData.get(entryName).minTimeMeasurement > entry.duration | |
245 | ? entry.duration | |
246 | : this.statistics.statisticsData.get(entryName).minTimeMeasurement | |
247 | : entry.duration; | |
248 | this.statistics.statisticsData.get(entryName).maxTimeMeasurement = | |
249 | this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement | |
250 | ? this.statistics.statisticsData.get(entryName).maxTimeMeasurement < entry.duration | |
251 | ? entry.duration | |
252 | : this.statistics.statisticsData.get(entryName).maxTimeMeasurement | |
253 | : entry.duration; | |
254 | this.statistics.statisticsData.get(entryName).totalTimeMeasurement = | |
255 | this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement | |
256 | ? this.statistics.statisticsData.get(entryName).totalTimeMeasurement + entry.duration | |
257 | : entry.duration; | |
258 | this.statistics.statisticsData.get(entryName).avgTimeMeasurement = | |
259 | this.statistics.statisticsData.get(entryName).totalTimeMeasurement / | |
260 | this.statistics.statisticsData.get(entryName).countTimeMeasurement; | |
9a15316c | 261 | this.statistics.statisticsData.get(entryName)?.timeMeasurementSeries instanceof CircularArray |
e7aeea18 JB |
262 | ? this.statistics.statisticsData |
263 | .get(entryName) | |
72092cfc | 264 | ?.timeMeasurementSeries?.push({ timestamp: entry.startTime, value: entry.duration }) |
e7aeea18 | 265 | : (this.statistics.statisticsData.get(entryName).timeMeasurementSeries = |
9a15316c | 266 | new CircularArray<TimeSeries>(Constants.DEFAULT_CIRCULAR_BUFFER_CAPACITY, { |
e7aeea18 JB |
267 | timestamp: entry.startTime, |
268 | value: entry.duration, | |
269 | })); | |
270 | this.statistics.statisticsData.get(entryName).medTimeMeasurement = this.median( | |
271 | this.extractTimeSeriesValues( | |
272 | this.statistics.statisticsData.get(entryName).timeMeasurementSeries | |
273 | ) | |
274 | ); | |
275 | this.statistics.statisticsData.get(entryName).ninetyFiveThPercentileTimeMeasurement = | |
276 | this.percentile( | |
277 | this.extractTimeSeriesValues( | |
278 | this.statistics.statisticsData.get(entryName).timeMeasurementSeries | |
279 | ), | |
280 | 95 | |
281 | ); | |
282 | this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = this.stdDeviation( | |
283 | this.extractTimeSeriesValues( | |
284 | this.statistics.statisticsData.get(entryName).timeMeasurementSeries | |
285 | ) | |
286 | ); | |
72f041bd | 287 | if (Configuration.getPerformanceStorage().enabled) { |
1895299d | 288 | parentPort?.postMessage( |
32de5a57 LM |
289 | MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics) |
290 | ); | |
72f041bd | 291 | } |
7ec46a9a JB |
292 | } |
293 | ||
0c142310 | 294 | private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] { |
72092cfc | 295 | return timeSeries.map((timeSeriesItem) => timeSeriesItem.value); |
0c142310 JB |
296 | } |
297 | ||
8b7072dc | 298 | private logPrefix = (): string => { |
9f2e3130 | 299 | return Utils.logPrefix(` ${this.objName} | Performance statistics`); |
8b7072dc | 300 | }; |
7dde0b73 | 301 | } |