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';
9 type IncomingRequestCommand
,
10 type LogConfiguration
,
14 type StorageConfiguration
,
21 JSONStringifyWithMapSupport
,
22 buildPerformanceStatisticsMessage
,
23 extractTimeSeriesValues
,
24 formatDurationSeconds
,
33 export class PerformanceStatistics
{
34 private static readonly instances
: Map
<string, PerformanceStatistics
> = new Map
<
39 private readonly objId
: string;
40 private readonly objName
: string;
41 private performanceObserver
!: PerformanceObserver
;
42 private readonly statistics
: Statistics
;
43 private displayInterval
?: NodeJS
.Timeout
;
45 private constructor(objId
: string, objName
: string, uri
: URL
) {
47 this.objName
= objName
;
48 this.initializePerformanceObserver();
50 id
: this.objId
?? 'Object id not specified',
51 name
: this.objName
?? 'Object name not specified',
53 createdAt
: new Date(),
54 statisticsData
: new Map(),
58 public static getInstance(
62 ): PerformanceStatistics
| undefined {
63 if (!PerformanceStatistics
.instances
.has(objId
)) {
64 PerformanceStatistics
.instances
.set(objId
, new PerformanceStatistics(objId
, objName
, uri
));
66 return PerformanceStatistics
.instances
.get(objId
);
69 public static beginMeasure(id
: string): string {
70 const markId
= `${id.charAt(0).toUpperCase()}${id.slice(1)}~${generateUUID()}`;
71 performance
.mark(markId
);
75 public static endMeasure(name
: string, markId
: string): void {
76 performance
.measure(name
, markId
);
77 performance
.clearMarks(markId
);
78 performance
.clearMeasures(name
);
81 public addRequestStatistic(
82 command
: RequestCommand
| IncomingRequestCommand
,
83 messageType
: MessageType
,
85 switch (messageType
) {
86 case MessageType
.CALL_MESSAGE
:
88 this.statistics
.statisticsData
.has(command
) &&
89 this.statistics
.statisticsData
.get(command
)?.requestCount
91 ++this.statistics
.statisticsData
.get(command
)!.requestCount
!;
93 this.statistics
.statisticsData
.set(command
, {
94 ...this.statistics
.statisticsData
.get(command
),
99 case MessageType
.CALL_RESULT_MESSAGE
:
101 this.statistics
.statisticsData
.has(command
) &&
102 this.statistics
.statisticsData
.get(command
)?.responseCount
104 ++this.statistics
.statisticsData
.get(command
)!.responseCount
!;
106 this.statistics
.statisticsData
.set(command
, {
107 ...this.statistics
.statisticsData
.get(command
),
112 case MessageType
.CALL_ERROR_MESSAGE
:
114 this.statistics
.statisticsData
.has(command
) &&
115 this.statistics
.statisticsData
.get(command
)?.errorCount
117 ++this.statistics
.statisticsData
.get(command
)!.errorCount
!;
119 this.statistics
.statisticsData
.set(command
, {
120 ...this.statistics
.statisticsData
.get(command
),
126 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
127 logger
.error(`${this.logPrefix()} wrong message type ${messageType}`);
132 public start(): void {
133 this.startLogStatisticsInterval();
134 const performanceStorageConfiguration
=
135 Configuration
.getConfigurationSection
<StorageConfiguration
>(
136 ConfigurationSection
.performanceStorage
,
138 if (performanceStorageConfiguration
.enabled
) {
140 `${this.logPrefix()} storage enabled: type ${performanceStorageConfiguration.type}, uri: ${
141 performanceStorageConfiguration.uri
147 public stop(): void {
148 this.stopLogStatisticsInterval();
149 performance
.clearMarks();
150 performance
.clearMeasures();
151 this.performanceObserver
?.disconnect();
154 public restart(): void {
159 private initializePerformanceObserver(): void {
160 this.performanceObserver
= new PerformanceObserver((performanceObserverList
) => {
161 const lastPerformanceEntry
= performanceObserverList
.getEntries()[0];
163 // `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
164 // lastPerformanceEntry,
166 this.addPerformanceEntryToStatistics(lastPerformanceEntry
);
168 this.performanceObserver
.observe({ entryTypes
: ['measure'] });
171 private logStatistics(): void {
172 logger
.info(`${this.logPrefix()}`, {
174 statisticsData
: JSONStringifyWithMapSupport(this.statistics
.statisticsData
),
178 private startLogStatisticsInterval(): void {
179 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
180 ConfigurationSection
.log
,
182 const logStatisticsInterval
= logConfiguration
.enabled
183 ? logConfiguration
.statisticsInterval
!
185 if (logStatisticsInterval
> 0 && !this.displayInterval
) {
186 this.displayInterval
= setInterval(() => {
187 this.logStatistics();
188 }, logStatisticsInterval
* 1000);
190 `${this.logPrefix()} logged every ${formatDurationSeconds(logStatisticsInterval)}`,
192 } else if (this.displayInterval
) {
194 `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`,
196 } else if (logConfiguration
.enabled
) {
198 `${this.logPrefix()} log interval is set to ${logStatisticsInterval?.toString()}. Not logging statistics`,
203 private stopLogStatisticsInterval(): void {
204 if (this.displayInterval
) {
205 clearInterval(this.displayInterval
);
206 delete this.displayInterval
;
210 private addPerformanceEntryToStatistics(entry
: PerformanceEntry
): void {
211 const entryName
= entry
.name
;
212 // Initialize command statistics
213 if (!this.statistics
.statisticsData
.has(entryName
)) {
214 this.statistics
.statisticsData
.set(entryName
, {});
216 // Update current statistics
217 this.statistics
.updatedAt
= new Date();
218 this.statistics
.statisticsData
.get(entryName
)!.timeMeasurementCount
=
219 (this.statistics
.statisticsData
.get(entryName
)?.timeMeasurementCount
?? 0) + 1;
220 this.statistics
.statisticsData
.get(entryName
)!.currentTimeMeasurement
= entry
.duration
;
221 this.statistics
.statisticsData
.get(entryName
)!.minTimeMeasurement
= Math.min(
223 this.statistics
.statisticsData
.get(entryName
)?.minTimeMeasurement
?? Infinity,
225 this.statistics
.statisticsData
.get(entryName
)!.maxTimeMeasurement
= Math.max(
227 this.statistics
.statisticsData
.get(entryName
)?.maxTimeMeasurement
?? -Infinity,
229 this.statistics
.statisticsData
.get(entryName
)!.totalTimeMeasurement
=
230 (this.statistics
.statisticsData
.get(entryName
)?.totalTimeMeasurement
?? 0) + entry
.duration
;
231 this.statistics
.statisticsData
.get(entryName
)!.avgTimeMeasurement
=
232 this.statistics
.statisticsData
.get(entryName
)!.totalTimeMeasurement
! /
233 this.statistics
.statisticsData
.get(entryName
)!.timeMeasurementCount
!;
234 this.statistics
.statisticsData
.get(entryName
)?.measurementTimeSeries
instanceof CircularArray
235 ? this.statistics
.statisticsData
237 ?.measurementTimeSeries
?.push({ timestamp
: entry
.startTime
, value
: entry
.duration
})
238 : (this.statistics
.statisticsData
.get(entryName
)!.measurementTimeSeries
=
239 new CircularArray
<TimestampedData
>(Constants
.DEFAULT_CIRCULAR_BUFFER_CAPACITY
, {
240 timestamp
: entry
.startTime
,
241 value
: entry
.duration
,
243 this.statistics
.statisticsData
.get(entryName
)!.medTimeMeasurement
= median(
244 extractTimeSeriesValues(
245 this.statistics
.statisticsData
.get(entryName
)!.measurementTimeSeries
as TimestampedData
[],
248 this.statistics
.statisticsData
.get(entryName
)!.ninetyFiveThPercentileTimeMeasurement
=
250 extractTimeSeriesValues(
251 this.statistics
.statisticsData
.get(entryName
)!.measurementTimeSeries
as TimestampedData
[],
255 this.statistics
.statisticsData
.get(entryName
)!.stdDevTimeMeasurement
= stdDeviation(
256 extractTimeSeriesValues(
257 this.statistics
.statisticsData
.get(entryName
)!.measurementTimeSeries
as TimestampedData
[],
261 Configuration
.getConfigurationSection
<StorageConfiguration
>(
262 ConfigurationSection
.performanceStorage
,
265 parentPort
?.postMessage(buildPerformanceStatisticsMessage(this.statistics
));
269 private logPrefix
= (): string => {
270 return logPrefix(` ${this.objName} | Performance statistics`);