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
,
36 export class PerformanceStatistics
{
37 private static readonly instances
: Map
<string, PerformanceStatistics
> = new Map
<
42 private readonly objId
: string;
43 private readonly objName
: string;
44 private performanceObserver
!: PerformanceObserver
;
45 private readonly statistics
: Statistics
;
46 private displayInterval
?: NodeJS
.Timeout
;
48 private constructor(objId
: string, objName
: string, uri
: URL
) {
50 this.objName
= objName
;
51 this.initializePerformanceObserver();
53 id
: this.objId
?? 'Object id not specified',
54 name
: this.objName
?? 'Object name not specified',
56 createdAt
: new Date(),
57 statisticsData
: new Map(),
61 public static getInstance(
65 ): PerformanceStatistics
| undefined {
66 if (!PerformanceStatistics
.instances
.has(objId
)) {
67 PerformanceStatistics
.instances
.set(objId
, new PerformanceStatistics(objId
, objName
, uri
));
69 return PerformanceStatistics
.instances
.get(objId
);
72 public static beginMeasure(id
: string): string {
73 const markId
= `${id.charAt(0).toUpperCase()}${id.slice(1)}~${generateUUID()}`;
74 performance
.mark(markId
);
78 public static endMeasure(name
: string, markId
: string): void {
79 performance
.measure(name
, markId
);
80 performance
.clearMarks(markId
);
81 performance
.clearMeasures(name
);
84 public addRequestStatistic(
85 command
: RequestCommand
| IncomingRequestCommand
,
86 messageType
: MessageType
,
88 switch (messageType
) {
89 case MessageType
.CALL_MESSAGE
:
91 this.statistics
.statisticsData
.has(command
) &&
92 this.statistics
.statisticsData
.get(command
)?.requestCount
94 ++this.statistics
.statisticsData
.get(command
)!.requestCount
!;
96 this.statistics
.statisticsData
.set(command
, {
97 ...this.statistics
.statisticsData
.get(command
),
102 case MessageType
.CALL_RESULT_MESSAGE
:
104 this.statistics
.statisticsData
.has(command
) &&
105 this.statistics
.statisticsData
.get(command
)?.responseCount
107 ++this.statistics
.statisticsData
.get(command
)!.responseCount
!;
109 this.statistics
.statisticsData
.set(command
, {
110 ...this.statistics
.statisticsData
.get(command
),
115 case MessageType
.CALL_ERROR_MESSAGE
:
117 this.statistics
.statisticsData
.has(command
) &&
118 this.statistics
.statisticsData
.get(command
)?.errorCount
120 ++this.statistics
.statisticsData
.get(command
)!.errorCount
!;
122 this.statistics
.statisticsData
.set(command
, {
123 ...this.statistics
.statisticsData
.get(command
),
129 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
130 logger
.error(`${this.logPrefix()} wrong message type ${messageType}`);
135 public start(): void {
136 this.startLogStatisticsInterval();
137 const performanceStorageConfiguration
=
138 Configuration
.getConfigurationSection
<StorageConfiguration
>(
139 ConfigurationSection
.performanceStorage
,
141 if (performanceStorageConfiguration
.enabled
) {
143 `${this.logPrefix()} storage enabled: type ${performanceStorageConfiguration.type}, uri: ${
144 performanceStorageConfiguration.uri
150 public stop(): void {
151 this.stopLogStatisticsInterval();
152 performance
.clearMarks();
153 performance
.clearMeasures();
154 this.performanceObserver
?.disconnect();
157 public restart(): void {
162 private initializePerformanceObserver(): void {
163 this.performanceObserver
= new PerformanceObserver((performanceObserverList
) => {
164 const lastPerformanceEntry
= performanceObserverList
.getEntries()[0];
166 // `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
167 // lastPerformanceEntry,
169 this.addPerformanceEntryToStatistics(lastPerformanceEntry
);
171 this.performanceObserver
.observe({ entryTypes
: ['measure'] });
174 private logStatistics(): void {
175 logger
.info(`${this.logPrefix()}`, {
177 statisticsData
: JSONStringifyWithMapSupport(this.statistics
.statisticsData
),
181 private startLogStatisticsInterval(): void {
182 const logConfiguration
= Configuration
.getConfigurationSection
<LogConfiguration
>(
183 ConfigurationSection
.log
,
185 const logStatisticsInterval
= logConfiguration
.enabled
186 ? logConfiguration
.statisticsInterval
!
188 if (logStatisticsInterval
> 0 && !this.displayInterval
) {
189 this.displayInterval
= setInterval(() => {
190 this.logStatistics();
191 }, secondsToMilliseconds(logStatisticsInterval
));
193 `${this.logPrefix()} logged every ${formatDurationSeconds(logStatisticsInterval)}`,
195 } else if (this.displayInterval
) {
197 `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`,
199 } else if (logConfiguration
.enabled
) {
201 `${this.logPrefix()} log interval is set to ${logStatisticsInterval}. Not logging statistics`,
206 private stopLogStatisticsInterval(): void {
207 if (this.displayInterval
) {
208 clearInterval(this.displayInterval
);
209 delete this.displayInterval
;
213 private addPerformanceEntryToStatistics(entry
: PerformanceEntry
): void {
214 const entryName
= entry
.name
;
215 // Initialize command statistics
216 if (!this.statistics
.statisticsData
.has(entryName
)) {
217 this.statistics
.statisticsData
.set(entryName
, {});
219 // Update current statistics
220 this.statistics
.statisticsData
.get(entryName
)!.timeMeasurementCount
=
221 (this.statistics
.statisticsData
.get(entryName
)?.timeMeasurementCount
?? 0) + 1;
222 this.statistics
.statisticsData
.get(entryName
)!.currentTimeMeasurement
= entry
.duration
;
223 this.statistics
.statisticsData
.get(entryName
)!.minTimeMeasurement
= Math.min(
225 this.statistics
.statisticsData
.get(entryName
)?.minTimeMeasurement
?? Infinity,
227 this.statistics
.statisticsData
.get(entryName
)!.maxTimeMeasurement
= Math.max(
229 this.statistics
.statisticsData
.get(entryName
)?.maxTimeMeasurement
?? -Infinity,
231 this.statistics
.statisticsData
.get(entryName
)!.totalTimeMeasurement
=
232 (this.statistics
.statisticsData
.get(entryName
)?.totalTimeMeasurement
?? 0) + entry
.duration
;
233 this.statistics
.statisticsData
.get(entryName
)?.measurementTimeSeries
instanceof CircularArray
234 ? this.statistics
.statisticsData
236 ?.measurementTimeSeries
?.push({ timestamp
: entry
.startTime
, value
: entry
.duration
})
237 : (this.statistics
.statisticsData
.get(entryName
)!.measurementTimeSeries
=
238 new CircularArray
<TimestampedData
>(Constants
.DEFAULT_CIRCULAR_BUFFER_CAPACITY
, {
239 timestamp
: entry
.startTime
,
240 value
: entry
.duration
,
242 const timeMeasurementValues
= extractTimeSeriesValues(
243 this.statistics
.statisticsData
.get(entryName
)!.measurementTimeSeries
!,
245 this.statistics
.statisticsData
.get(entryName
)!.avgTimeMeasurement
=
246 average(timeMeasurementValues
);
247 this.statistics
.statisticsData
.get(entryName
)!.medTimeMeasurement
=
248 median(timeMeasurementValues
);
249 this.statistics
.statisticsData
.get(entryName
)!.ninetyFiveThPercentileTimeMeasurement
=
250 nthPercentile(timeMeasurementValues
, 95);
251 this.statistics
.statisticsData
.get(entryName
)!.stdDevTimeMeasurement
= stdDeviation(
252 timeMeasurementValues
,
253 this.statistics
.statisticsData
.get(entryName
)!.avgTimeMeasurement
,
255 this.statistics
.updatedAt
= new Date();
257 Configuration
.getConfigurationSection
<StorageConfiguration
>(
258 ConfigurationSection
.performanceStorage
,
261 parentPort
?.postMessage(buildPerformanceStatisticsMessage(this.statistics
));
265 private logPrefix
= (): string => {
266 return logPrefix(` ${this.objName} | Performance statistics`);