-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.ts
More file actions
213 lines (190 loc) · 5.7 KB
/
timer.ts
File metadata and controls
213 lines (190 loc) · 5.7 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
/**
* @fileoverview Recording-side helpers — `perfTimer` (returns a stop()
* closure), `measure` / `measureSync` (timed wrappers around an
* async / sync function), `perfCheckpoint` (zero-duration marker),
* and `trackMemory` (records heap-used at a label). All push rows
* into the shared metrics array when `isPerfEnabled()` is true.
*/
import process from 'node:process'
import { debugLog } from '../debug/output'
import { errorMessage } from '../errors/message'
import { DateNow } from '../primordials/date'
import { MathRound } from '../primordials/math'
import { performanceMetrics } from './_internal'
import { isPerfEnabled } from './enabled'
import type { PerformanceMetrics } from './types'
/**
* 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/perf/timer'
*
* 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: errorMessage(e),
})
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/perf/timer'
*
* 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: errorMessage(e),
})
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/perf/timer'
*
* 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: DateNow(),
...(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/perf/timer'
*
* 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: MathRound(duration * 100) / 100,
timestamp: DateNow(),
metadata: { ...metadata, ...additionalMetadata },
}
performanceMetrics.push(metric)
debugLog(`[perf] [END] ${operation} - ${metric.duration}ms`)
}
}
/**
* 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/perf/timer'
*
* 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 = MathRound((usage.heapUsed / 1024 / 1024) * 100) / 100
debugLog(`[perf] [MEMORY] ${label}: ${heapUsedMB}MB heap used`)
const metric: PerformanceMetrics = {
operation: `checkpoint:memory:${label}`,
duration: 0,
timestamp: DateNow(),
metadata: {
heapUsed: heapUsedMB,
heapTotal: MathRound((usage.heapTotal / 1024 / 1024) * 100) / 100,
external: MathRound((usage.external / 1024 / 1024) * 100) / 100,
},
}
performanceMetrics.push(metric)
return heapUsedMB
}