1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { type PerformanceEntry
, PerformanceObserver
, performance
} from
'node:perf_hooks';
4 import type { URL
} from
'node:url';
5 import { parentPort
} from
'node:worker_threads';
7 import { secondsToMilliseconds
} from
'date-fns';
11 type IncomingRequestCommand
,
12 type LogConfiguration
,
16 type StorageConfiguration
,
23 JSONStringifyWithMapSupport
,
25 buildPerformanceStatisticsMessage
,
26 extractTimeSeriesValues
,
27 formatDurationSeconds
,
38 export class PerformanceStatistics
{
39 private static readonly instances
: Map
<string, PerformanceStatistics
> = new Map
<
44 private readonly objId
: string;
45 private readonly objName
: string;
46 private performanceObserver
!: PerformanceObserver
;
47 private readonly statistics
: Statistics
;
48 private displayInterval
?: NodeJS
.Timeout
;
50 private constructor(objId
: string, objName
: string, uri
: URL
) {
52 this.objName
= objName
;
53 this.initializePerformanceObserver();
55 id
: this.objId
?? 'Object id not specified',
56 name
: this.objName
?? 'Object name not specified',
58 createdAt
: new Date(),
59 statisticsData
: new Map(),
63 public static getInstance(
67 ): PerformanceStatistics
| undefined {
68 if (!PerformanceStatistics
.instances
.has(objId
)) {
69 PerformanceStatistics
.instances
.set(objId
, new PerformanceStatistics(objId
, objName
, uri
));
71 return PerformanceStatistics
.instances
.get(objId
);
74 public static beginMeasure(id
: string): string {
75 const markId
= `${id.charAt(0).toUpperCase()}${id.slice(1)}~${generateUUID()}`;
76 performance
.mark(markId
);
80 public static endMeasure(name
: string, markId
: string): void {
81 performance
.measure(name
, markId
);
82 performance
.clearMarks(markId
);
83 performance
.clearMeasures(name
);
86 public addRequestStatistic(
87 command
: RequestCommand
| IncomingRequestCommand
,
88 messageType
: MessageType
,
90 switch (messageType
) {
91 case MessageType
.CALL_MESSAGE
:
93 this.statistics
.statisticsData
.has(command
) &&
94 this.statistics
.statisticsData
.get(command
)?.requestCount
96 ++this.statistics
.statisticsData
.get(command
)!.requestCount
!;
98 this.statistics
.statisticsData
.set(command
, {
99 ...this.statistics
.statisticsData
.get(command
),
104 case MessageType
.CALL_RESULT_MESSAGE
:
106 this.statistics
.statisticsData
.has(command
) &&
107 this.statistics
.statisticsData
.get(command
)?.responseCount
109 ++this.statistics
.statisticsData
.get(command
)!.responseCount
!;
111 this.statistics
.statisticsData
.set(command
, {
112 ...this.statistics
.statisticsData
.get(command
),
117 case MessageType
.CALL_ERROR_MESSAGE
:
119 this.statistics
.statisticsData
.has(command
) &&
120 this.statistics
.statisticsData
.get(command
)?.errorCount
122 ++this.statistics
.statisticsData
.get(command
)!.errorCount
!;
124 this.statistics
.statisticsData
.set(command
, {
125 ...this.statistics
.statisticsData
.get(command
),
131 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
132 logger
.error(`${this.logPrefix()} wrong message type ${messageType}`);
137 public start(): void {
138 this.startLogStatisticsInterval();
139 const performanceStorageConfiguration
=
140 Configuration
.getConfigurationSection
<StorageConfiguration
>(
141 ConfigurationSection
.performanceStorage
,
143 if (performanceStorageConfiguration
.enabled
) {
145 `${this.logPrefix()} storage enabled: type ${performanceStorageConfiguration.type}, uri: ${
146 performanceStorageConfiguration.uri
152 public stop(): void {
153 this.stopLogStatisticsInterval();
154 performance
.clearMarks();
155 performance
.clearMeasures();
156 this.performanceObserver
?.disconnect();
159 public restart(): void {
164 private initializePerformanceObserver(): void {
165 this.performanceObserver
= new PerformanceObserver((performanceObserverList
) => {
166 const lastPerformanceEntry
= performanceObserverList
.getEntries()[0];
168 // `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
169 // lastPerformanceEntry,
171 this.addPerformanceEntryToStatistics(lastPerformanceEntry
);
173 this.performanceObserver
.observe({ entryTypes
: ['measure'] });
176 private logStatistics(): void {
177 logger
.info(`${this.logPrefix()}`, {
179 statisticsData
: JSONStringifyWithMapSupport(this.statistics
.statisticsData
),
183 private startLogStatisticsInterval(): void {
184 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
185 ConfigurationSection
.log
,
187 const logStatisticsInterval
= logConfiguration
.enabled
188 ? logConfiguration
.statisticsInterval
!
190 if (logStatisticsInterval
> 0 && !this.displayInterval
) {
191 this.displayInterval
= setInterval(() => {
192 this.logStatistics();
193 }, secondsToMilliseconds(logStatisticsInterval
));
195 `${this.logPrefix()} logged every ${formatDurationSeconds(logStatisticsInterval)}`,
197 } else if (this.displayInterval
) {
199 `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`,
201 } else if (logConfiguration
.enabled
) {
203 `${this.logPrefix()} log interval is set to ${logStatisticsInterval}. Not logging statistics`,
208 private stopLogStatisticsInterval(): void {
209 if (this.displayInterval
) {
210 clearInterval(this.displayInterval
);
211 delete this.displayInterval
;
215 private addPerformanceEntryToStatistics(entry
: PerformanceEntry
): void {
216 // Initialize command statistics
217 if (!this.statistics
.statisticsData
.has(entry
.name
)) {
218 this.statistics
.statisticsData
.set(entry
.name
, {});
220 // Update current statistics
221 this.statistics
.statisticsData
.get(entry
.name
)!.timeMeasurementCount
=
222 (this.statistics
.statisticsData
.get(entry
.name
)?.timeMeasurementCount
?? 0) + 1;
223 this.statistics
.statisticsData
.get(entry
.name
)!.currentTimeMeasurement
= entry
.duration
;
224 this.statistics
.statisticsData
.get(entry
.name
)!.minTimeMeasurement
= min(
226 this.statistics
.statisticsData
.get(entry
.name
)?.minTimeMeasurement
?? Infinity,
228 this.statistics
.statisticsData
.get(entry
.name
)!.maxTimeMeasurement
= max(
230 this.statistics
.statisticsData
.get(entry
.name
)?.maxTimeMeasurement
?? -Infinity,
232 this.statistics
.statisticsData
.get(entry
.name
)!.totalTimeMeasurement
=
233 (this.statistics
.statisticsData
.get(entry
.name
)?.totalTimeMeasurement
?? 0) + entry
.duration
;
234 this.statistics
.statisticsData
.get(entry
.name
)?.measurementTimeSeries
instanceof CircularArray
235 ? this.statistics
.statisticsData
237 ?.measurementTimeSeries
?.push({ timestamp
: entry
.startTime
, value
: entry
.duration
})
238 : (this.statistics
.statisticsData
.get(entry
.name
)!.measurementTimeSeries
=
239 new CircularArray
<TimestampedData
>(Constants
.DEFAULT_CIRCULAR_BUFFER_CAPACITY
, {
240 timestamp
: entry
.startTime
,
241 value
: entry
.duration
,
243 const timeMeasurementValues
= extractTimeSeriesValues(
244 this.statistics
.statisticsData
.get(entry
.name
)!.measurementTimeSeries
!,
246 this.statistics
.statisticsData
.get(entry
.name
)!.avgTimeMeasurement
=
247 average(timeMeasurementValues
);
248 this.statistics
.statisticsData
.get(entry
.name
)!.medTimeMeasurement
=
249 median(timeMeasurementValues
);
250 this.statistics
.statisticsData
.get(entry
.name
)!.ninetyFiveThPercentileTimeMeasurement
=
251 nthPercentile(timeMeasurementValues
, 95);
252 this.statistics
.statisticsData
.get(entry
.name
)!.stdDevTimeMeasurement
= stdDeviation(
253 timeMeasurementValues
,
254 this.statistics
.statisticsData
.get(entry
.name
)!.avgTimeMeasurement
,
256 this.statistics
.updatedAt
= new Date();
258 Configuration
.getConfigurationSection
<StorageConfiguration
>(
259 ConfigurationSection
.performanceStorage
,
262 parentPort
?.postMessage(buildPerformanceStatisticsMessage(this.statistics
));
266 private logPrefix
= (): string => {
267 return logPrefix(` ${this.objName} | Performance statistics`);