-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance.ts
More file actions
428 lines (384 loc) · 11.5 KB
/
performance.ts
File metadata and controls
428 lines (384 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* @fileoverview Performance monitoring utilities for profiling and optimization.
* Provides timing, profiling, and performance metric collection for identifying bottlenecks.
*/
import process from 'node:process'
import { debugLog } from './debug'
/**
* Performance metrics collected during execution.
*/
export type PerformanceMetrics = {
operation: string
duration: number
timestamp: number
metadata?: Record<string, unknown>
}
/**
* Global metrics collection (only in debug mode).
*/
const performanceMetrics: PerformanceMetrics[] = []
/**
* Check if performance tracking is enabled.
*/
function isPerfEnabled(): boolean {
return process.env['DEBUG']?.includes('perf') || false
}
/**
* Clear all collected performance metrics.
*
* @example
* import { clearPerformanceMetrics } from '@socketsecurity/lib/performance'
*
* clearPerformanceMetrics()
*/
export function clearPerformanceMetrics(): void {
performanceMetrics.length = 0
debugLog('[perf] Cleared performance metrics')
}
/**
* Create a performance report for the current execution.
* Only available when DEBUG=perf is enabled.
*
* @returns Formatted performance report
*
* @example
* import { generatePerformanceReport } from '@socketsecurity/lib/performance'
*
* console.log(generatePerformanceReport())
* // ╔═══════════════════════════════════════════════╗
* // ║ Performance Report ║
* // ╚═══════════════════════════════════════════════╝
* //
* // api-call:
* // Calls: 5
* // Avg: 246.8ms
* // Min: 100ms
* // Max: 500ms
* // Total: 1234ms
*/
export function generatePerformanceReport(): string {
if (!isPerfEnabled() || performanceMetrics.length === 0) {
return '(no performance data collected - enable with DEBUG=perf)'
}
const summary = getPerformanceSummary()
const operations = Object.keys(summary).sort()
let report = '\n╔═══════════════════════════════════════════════╗\n'
report += '║ Performance Report ║\n'
report += '╚═══════════════════════════════════════════════╝\n\n'
for (const operation of operations) {
const stats = summary[operation] as {
count: number
total: number
avg: number
min: number
max: number
}
report += `${operation}:\n`
report += ` Calls: ${stats.count}\n`
report += ` Avg: ${stats.avg}ms\n`
report += ` Min: ${stats.min}ms\n`
report += ` Max: ${stats.max}ms\n`
report += ` Total: ${stats.total}ms\n\n`
}
const totalDuration = Object.values(summary).reduce(
(sum, s) => sum + s.total,
0,
)
report += `Total measured time: ${Math.round(totalDuration * 100) / 100}ms\n`
return report
}
/**
* Get all collected performance metrics.
* Only available when DEBUG=perf is enabled.
*
* @returns Array of performance metrics
*
* @example
* import { getPerformanceMetrics } from '@socketsecurity/lib/performance'
*
* const metrics = getPerformanceMetrics()
* console.log(metrics)
*/
export function getPerformanceMetrics(): PerformanceMetrics[] {
return [...performanceMetrics]
}
/**
* Get performance summary statistics.
*
* @returns Summary of metrics grouped by operation
*
* @example
* import { getPerformanceSummary } from '@socketsecurity/lib/performance'
*
* const summary = getPerformanceSummary()
* console.log(summary)
* // {
* // 'api-call': { count: 5, total: 1234, avg: 246.8, min: 100, max: 500 },
* // 'file-read': { count: 10, total: 50, avg: 5, min: 2, max: 15 }
* // }
*/
export function getPerformanceSummary(): Record<
string,
{
count: number
total: number
avg: number
min: number
max: number
}
> {
const summary: Record<
string,
{ count: number; total: number; min: number; max: number }
> = { __proto__: null } as unknown as Record<
string,
{ count: number; total: number; min: number; max: number }
>
for (const metric of performanceMetrics) {
const { duration, operation } = metric
if (!summary[operation]) {
summary[operation] = {
count: 0,
total: 0,
min: Number.POSITIVE_INFINITY,
max: Number.NEGATIVE_INFINITY,
}
}
const stats = summary[operation] as {
count: number
total: number
min: number
max: number
}
stats.count++
stats.total += duration
stats.min = Math.min(stats.min, duration)
stats.max = Math.max(stats.max, duration)
}
// Calculate averages and return with proper typing
const result: Record<
string,
{ count: number; total: number; avg: number; min: number; max: number }
> = { __proto__: null } as unknown as Record<
string,
{ count: number; total: number; avg: number; min: number; max: number }
>
for (const { 0: operation, 1: stats } of Object.entries(summary)) {
result[operation] = {
count: stats.count,
total: Math.round(stats.total * 100) / 100,
avg: Math.round((stats.total / stats.count) * 100) / 100,
min: Math.round(stats.min * 100) / 100,
max: Math.round(stats.max * 100) / 100,
}
}
return result
}
/**
* Measure execution time of an async function.
*
* @param operation - Name of the operation
* @param fn - Async function to measure
* @param metadata - Optional metadata
* @returns Result of the function and duration
*
* @example
* import { measure } from '@socketsecurity/lib/performance'
*
* const { result, duration } = await measure('fetch-packages', async () => {
* return await fetchPackages()
* })
* console.log(`Fetched packages in ${duration}ms`)
*/
export async function measure<T>(
operation: string,
fn: () => Promise<T>,
metadata?: Record<string, unknown>,
): Promise<{ result: T; duration: number }> {
const stop = perfTimer(operation, metadata)
try {
const result = await fn()
stop({ success: true })
const metric = performanceMetrics[performanceMetrics.length - 1]
return { result, duration: metric?.duration || 0 }
} catch (e) {
stop({
success: false,
error: e instanceof Error ? e.message : 'Unknown',
})
throw e
}
}
/**
* Measure synchronous function execution time.
*
* @param operation - Name of the operation
* @param fn - Synchronous function to measure
* @param metadata - Optional metadata
* @returns Result of the function and duration
*
* @example
* import { measureSync } from '@socketsecurity/lib/performance'
*
* const { result, duration } = measureSync('parse-json', () => {
* return JSON.parse(data)
* })
*/
export function measureSync<T>(
operation: string,
fn: () => T,
metadata?: Record<string, unknown>,
): { result: T; duration: number } {
const stop = perfTimer(operation, metadata)
try {
const result = fn()
stop({ success: true })
const metric = performanceMetrics[performanceMetrics.length - 1]
return { result, duration: metric?.duration || 0 }
} catch (e) {
stop({
success: false,
error: e instanceof Error ? e.message : 'Unknown',
})
throw e
}
}
/**
* Mark a checkpoint in performance tracking.
* Useful for tracking progress through complex operations.
*
* @param checkpoint - Name of the checkpoint
* @param metadata - Optional metadata
*
* @example
* import { perfCheckpoint } from '@socketsecurity/lib/performance'
*
* perfCheckpoint('start-scan')
* // ... do work ...
* perfCheckpoint('fetch-packages', { count: 50 })
* // ... do work ...
* perfCheckpoint('analyze-issues', { issueCount: 10 })
* perfCheckpoint('end-scan')
*/
export function perfCheckpoint(
checkpoint: string,
metadata?: Record<string, unknown>,
): void {
if (!isPerfEnabled()) {
return
}
const metric: PerformanceMetrics = {
operation: `checkpoint:${checkpoint}`,
duration: 0,
timestamp: Date.now(),
...(metadata ? { metadata } : {}),
}
performanceMetrics.push(metric)
debugLog(`[perf] [CHECKPOINT] ${checkpoint}`)
}
/**
* Start a performance timer for an operation.
* Returns a stop function that records the duration.
*
* @param operation - Name of the operation being timed
* @param metadata - Optional metadata to attach to the metric
* @returns Stop function that completes the timing
*
* @example
* import { perfTimer } from '@socketsecurity/lib/performance'
*
* const stop = perfTimer('api-call')
* await fetchData()
* stop({ endpoint: '/npm/lodash/score' })
*/
export function perfTimer(
operation: string,
metadata?: Record<string, unknown>,
): (additionalMetadata?: Record<string, unknown>) => void {
if (!isPerfEnabled()) {
// No-op if perf tracking disabled
return () => {}
}
const start = performance.now()
debugLog(`[perf] [START] ${operation}`)
return (additionalMetadata?: Record<string, unknown>) => {
const duration = performance.now() - start
const metric: PerformanceMetrics = {
operation,
// Round to 2 decimals
duration: Math.round(duration * 100) / 100,
timestamp: Date.now(),
metadata: { ...metadata, ...additionalMetadata },
}
performanceMetrics.push(metric)
debugLog(`[perf] [END] ${operation} - ${metric.duration}ms`)
}
}
/**
* Print performance summary to console.
* Only prints when DEBUG=perf is enabled.
*
* @example
* import { printPerformanceSummary } from '@socketsecurity/lib/performance'
*
* printPerformanceSummary()
* // Performance Summary:
* // api-call: 5 calls, avg 246.8ms (min 100ms, max 500ms, total 1234ms)
* // file-read: 10 calls, avg 5ms (min 2ms, max 15ms, total 50ms)
*/
export function printPerformanceSummary(): void {
if (!isPerfEnabled() || performanceMetrics.length === 0) {
return
}
const summary = getPerformanceSummary()
const operations = Object.keys(summary).sort()
debugLog('[perf]\n=== Performance Summary ===')
for (const operation of operations) {
const stats = summary[operation] as {
count: number
total: number
avg: number
min: number
max: number
}
debugLog(
`[perf] ${operation}: ${stats.count} calls, avg ${stats.avg}ms (min ${stats.min}ms, max ${stats.max}ms, total ${stats.total}ms)`,
)
}
debugLog('[perf] =========================\n')
}
/**
* Track memory usage at a specific point.
* Only available when DEBUG=perf is enabled.
*
* @param label - Label for this memory snapshot
* @returns Memory usage in MB
*
* @example
* import { trackMemory } from '@socketsecurity/lib/performance'
*
* const memBefore = trackMemory('before-operation')
* await heavyOperation()
* const memAfter = trackMemory('after-operation')
* console.log(`Memory increased by ${memAfter - memBefore}MB`)
*/
export function trackMemory(label: string): number {
if (!isPerfEnabled()) {
return 0
}
const usage = process.memoryUsage()
const heapUsedMB = Math.round((usage.heapUsed / 1024 / 1024) * 100) / 100
debugLog(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`)
const metric: PerformanceMetrics = {
operation: `checkpoint:memory:${label}`,
duration: 0,
timestamp: Date.now(),
metadata: {
heapUsed: heapUsedMB,
heapTotal: Math.round((usage.heapTotal / 1024 / 1024) * 100) / 100,
external: Math.round((usage.external / 1024 / 1024) * 100) / 100,
},
}
performanceMetrics.push(metric)
return heapUsedMB
}