-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpreload.js
More file actions
518 lines (454 loc) Β· 16.9 KB
/
preload.js
File metadata and controls
518 lines (454 loc) Β· 16.9 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
'use strict'
const fs = require('fs')
const path = require('path')
const pprof = require('@datadog/pprof')
const { spawn } = require('child_process')
const cpuProfiler = pprof.time
const heapProfiler = pprof.heap
let isCpuProfilerRunning = false
let isHeapProfilerRunning = false
let sourceMapper = null
const autoStart = process.env.FLAME_AUTO_START === 'true'
const mdFormat = process.env.FLAME_MD_FORMAT || 'summary'
// Initialize sourcemap support if enabled
const sourcemapDirs = process.env.FLAME_SOURCEMAP_DIRS
const nodeModulesSourceMaps = process.env.FLAME_NODE_MODULES_SOURCE_MAPS
let sourceMapperPromise = null
let nodeModulesMapperPromise = null
// Helper: resolve module path from node_modules
function resolveModulePath (appPath, moduleName) {
try {
const resolved = require.resolve(moduleName, { paths: [appPath] })
const nodeModulesIndex = resolved.lastIndexOf('node_modules')
if (nodeModulesIndex === -1) return null
const afterNodeModules = resolved.substring(nodeModulesIndex + 'node_modules'.length + 1)
const parts = afterNodeModules.split(path.sep)
if (moduleName.startsWith('@')) {
return path.join(resolved.substring(0, nodeModulesIndex), 'node_modules', parts[0], parts[1])
} else {
return path.join(resolved.substring(0, nodeModulesIndex), 'node_modules', parts[0])
}
} catch {
return null
}
}
// Helper: walk directory for .map files
async function * walkForMapFiles (dir) {
const fsPromises = require('fs').promises
async function * walkRecursive (currentDir) {
try {
const dirHandle = await fsPromises.opendir(currentDir)
for await (const entry of dirHandle) {
const entryPath = path.join(currentDir, entry.name)
if (entry.isDirectory() && entry.name !== '.git') {
yield * walkRecursive(entryPath)
} else if (entry.isFile() && /\.[cm]?js\.map$/.test(entry.name)) {
yield entryPath
}
}
} catch {
// Silently ignore permission errors
}
}
yield * walkRecursive(dir)
}
// Helper: process sourcemap file
async function processSourceMapFile (mapPath) {
try {
const fsPromises = require('fs').promises
const sourceMap = require('source-map')
const contents = await fsPromises.readFile(mapPath, 'utf8')
const consumer = await new sourceMap.SourceMapConsumer(contents)
const dir = path.dirname(mapPath)
const generatedPathCandidates = []
if (consumer.file) {
generatedPathCandidates.push(path.resolve(dir, consumer.file))
}
generatedPathCandidates.push(path.resolve(dir, path.basename(mapPath, '.map')))
for (const generatedPath of generatedPathCandidates) {
try {
await fsPromises.access(generatedPath)
return {
generatedPath,
info: { mapFileDir: dir, mapConsumer: consumer }
}
} catch {}
}
return null
} catch {
return null
}
}
// Load sourcemaps from node_modules packages
async function loadNodeModulesSourceMaps (moduleNames, debug = false) {
const entries = new Map()
for (const moduleName of moduleNames) {
const modulePath = resolveModulePath(process.cwd(), moduleName)
if (!modulePath) {
if (debug) {
console.warn(`β οΈ Could not resolve module: ${moduleName}`)
}
continue
}
if (debug) {
console.log(`πΊοΈ Scanning ${moduleName} for sourcemaps...`)
}
let mapCount = 0
for await (const mapFile of walkForMapFiles(modulePath)) {
const entry = await processSourceMapFile(mapFile)
if (entry) {
entries.set(entry.generatedPath, entry.info)
mapCount++
}
}
if (debug) {
console.log(`πΊοΈ Loaded ${mapCount} sourcemaps from ${moduleName}`)
}
}
return entries
}
// Start loading node_modules sourcemaps if configured
if (nodeModulesSourceMaps) {
const mods = nodeModulesSourceMaps.split(',').filter(m => m.trim())
if (mods.length > 0) {
console.log(`πΊοΈ Loading sourcemaps from node_modules: ${mods.join(', ')}`)
nodeModulesMapperPromise = loadNodeModulesSourceMaps(mods, false)
.then(entries => {
console.log(`πΊοΈ Loaded ${entries.size} sourcemaps from node_modules`)
return entries
})
.catch(error => {
console.error('β οΈ Warning: Failed to load node_modules sourcemaps:', error.message)
return new Map()
})
}
}
// Parse sourcemap directories
const dirs = sourcemapDirs
? sourcemapDirs.split(path.delimiter).filter(d => d.trim())
: []
// Initialize sourcemaps if we have either dirs or node_modules sourcemaps
if (dirs.length > 0 || nodeModulesMapperPromise) {
const { SourceMapper } = require('@datadog/pprof/out/src/sourcemapper/sourcemapper')
if (dirs.length > 0) {
console.log(`πΊοΈ Initializing sourcemap support for directories: ${dirs.join(', ')}`)
}
sourceMapperPromise = (async () => {
try {
// Create SourceMapper from dirs if provided, otherwise create empty one
const mapper = dirs.length > 0
? await SourceMapper.create(dirs)
: new SourceMapper(false)
// Merge node_modules sourcemaps if available
if (nodeModulesMapperPromise) {
const nodeModulesEntries = await nodeModulesMapperPromise
for (const [generatedPath, info] of nodeModulesEntries) {
mapper.infoMap.set(generatedPath, info)
}
}
sourceMapper = mapper
console.log('πΊοΈ Sourcemap initialization complete')
return mapper
} catch (error) {
console.error('β οΈ Warning: Failed to initialize sourcemaps:', error.message)
return null
}
})()
}
function generateFlamegraph (pprofPath, outputPath) {
return new Promise((resolve, reject) => {
// Find the flame CLI
const flameBinPath = path.resolve(__dirname, 'bin', 'flame.js')
const args = [flameBinPath, 'generate', '-o', outputPath, pprofPath]
const child = spawn('node', args, { stdio: 'pipe' })
let stdout = ''
let stderr = ''
child.stdout.on('data', (data) => {
stdout += data.toString()
})
child.stderr.on('data', (data) => {
stderr += data.toString()
})
child.on('close', (code) => {
if (code === 0) {
resolve({ stdout, stderr })
} else {
reject(new Error(`Flamegraph generation failed: ${stderr || stdout}`))
}
})
child.on('error', (error) => {
reject(error)
})
})
}
async function generateMarkdown (pprofPath, outputPath, format = 'summary') {
const { convert } = await import('pprof-to-md')
const markdown = convert(pprofPath, {
format,
profileName: path.basename(pprofPath)
})
fs.writeFileSync(outputPath, markdown)
return { outputPath }
}
function stopProfilerQuick () {
if (!isCpuProfilerRunning && !isHeapProfilerRunning) {
return null
}
console.log('Stopping profilers and writing profiles to disk...')
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const filenames = []
try {
if (isCpuProfilerRunning) {
const cpuProfileData = cpuProfiler.stop()
const cpuProfile = cpuProfileData.encode()
const cpuFilename = `cpu-profile-${timestamp}.pb`
fs.writeFileSync(cpuFilename, cpuProfile)
console.log(`π₯ CPU profile written to: ${cpuFilename}`)
if (sourceMapper) {
console.log('πΊοΈ Profile includes sourcemap translations')
}
filenames.push(cpuFilename)
isCpuProfilerRunning = false
}
if (isHeapProfilerRunning) {
const heapProfileData = heapProfiler.profile(undefined, sourceMapper)
heapProfiler.stop()
const heapProfile = heapProfileData.encode()
const heapFilename = `heap-profile-${timestamp}.pb`
fs.writeFileSync(heapFilename, heapProfile)
console.log(`π₯ Heap profile written to: ${heapFilename}`)
if (sourceMapper) {
console.log('πΊοΈ Profile includes sourcemap translations')
}
filenames.push(heapFilename)
isHeapProfilerRunning = false
}
return filenames
} catch (error) {
console.error('Error generating profiles:', error)
isCpuProfilerRunning = false
isHeapProfilerRunning = false
return null
}
}
async function stopProfilerAndSave (generateHtml = false) {
if (!isCpuProfilerRunning && !isHeapProfilerRunning) {
return null
}
console.log('Stopping profilers and writing profiles to disk...')
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const filenames = []
try {
if (isCpuProfilerRunning) {
const cpuProfileData = cpuProfiler.stop()
const cpuProfile = cpuProfileData.encode()
const cpuFilename = `cpu-profile-${timestamp}.pb`
fs.writeFileSync(cpuFilename, cpuProfile)
console.log(`π₯ CPU profile written to: ${cpuFilename}`)
if (sourceMapper) {
console.log('πΊοΈ Profile includes sourcemap translations')
}
filenames.push(cpuFilename)
isCpuProfilerRunning = false
if (generateHtml) {
const htmlFilename = cpuFilename.replace('.pb', '.html')
console.log('π₯ Generating CPU flamegraph...')
try {
await generateFlamegraph(cpuFilename, htmlFilename)
console.log(`π₯ CPU flamegraph generated: ${htmlFilename}`)
console.log(`π₯ Open file://${path.resolve(htmlFilename)} in your browser to view the CPU flamegraph`)
} catch (error) {
console.error('Warning: Failed to generate CPU flamegraph:', error.message)
}
// Generate markdown analysis
const mdFilename = cpuFilename.replace('.pb', '.md')
console.log('π₯ Generating CPU markdown analysis...')
try {
await generateMarkdown(cpuFilename, mdFilename, mdFormat)
console.log(`π₯ CPU markdown generated: ${mdFilename}`)
} catch (error) {
console.error('Warning: Failed to generate CPU markdown:', error.message)
}
}
}
if (isHeapProfilerRunning) {
const heapProfileData = heapProfiler.profile(undefined, sourceMapper)
heapProfiler.stop()
const heapProfile = heapProfileData.encode()
const heapFilename = `heap-profile-${timestamp}.pb`
fs.writeFileSync(heapFilename, heapProfile)
console.log(`π₯ Heap profile written to: ${heapFilename}`)
if (sourceMapper) {
console.log('πΊοΈ Profile includes sourcemap translations')
}
filenames.push(heapFilename)
isHeapProfilerRunning = false
if (generateHtml) {
const htmlFilename = heapFilename.replace('.pb', '.html')
console.log('π₯ Generating heap flamegraph...')
try {
await generateFlamegraph(heapFilename, htmlFilename)
console.log(`π₯ Heap flamegraph generated: ${htmlFilename}`)
console.log(`π₯ Open file://${path.resolve(htmlFilename)} in your browser to view the heap flamegraph`)
} catch (error) {
console.error('Warning: Failed to generate heap flamegraph:', error.message)
}
// Generate markdown analysis
const mdFilename = heapFilename.replace('.pb', '.md')
console.log('π₯ Generating heap markdown analysis...')
try {
await generateMarkdown(heapFilename, mdFilename, mdFormat)
console.log(`π₯ Heap markdown generated: ${mdFilename}`)
} catch (error) {
console.error('Warning: Failed to generate heap markdown:', error.message)
}
}
}
return filenames
} catch (error) {
console.error('Error generating profiles:', error)
isCpuProfilerRunning = false
isHeapProfilerRunning = false
return null
}
}
function generateHtmlAsync (filenames) {
if (!Array.isArray(filenames)) {
filenames = [filenames]
}
filenames.forEach(filename => {
const htmlFilename = filename.replace('.pb', '.html')
const profileType = filename.includes('cpu-profile') ? 'CPU' : 'Heap'
console.log(`π₯ Generating ${profileType} flamegraph...`)
console.log(`π₯ Flamegraph will be saved as: ${htmlFilename}`)
console.log(`π₯ Open file://${path.resolve(htmlFilename)} in your browser once generation completes`)
generateFlamegraph(filename, htmlFilename)
.then(() => {
console.log(`π₯ ${profileType} flamegraph generation completed`)
})
.catch(error => {
console.error(`Warning: Failed to generate ${profileType} flamegraph:`, error.message)
})
// Generate markdown analysis
const mdFilename = filename.replace('.pb', '.md')
console.log(`π₯ Generating ${profileType} markdown analysis...`)
generateMarkdown(filename, mdFilename, mdFormat)
.then(() => {
console.log(`π₯ ${profileType} markdown generated: ${mdFilename}`)
})
.catch(error => {
console.error(`Warning: Failed to generate ${profileType} markdown:`, error.message)
})
})
}
function toggleProfiler () {
if (!isCpuProfilerRunning && !isHeapProfilerRunning) {
console.log('Starting CPU and heap profilers...')
// Start CPU profiler with sourcemap support if available
const cpuProfilerOptions = sourceMapper ? { sourceMapper } : undefined
cpuProfiler.start(cpuProfilerOptions)
// Start heap profiler with default parameters
// intervalBytes: 512KB (512 * 1024)
// stackDepth: 64
heapProfiler.start(512 * 1024, 64)
isCpuProfilerRunning = true
isHeapProfilerRunning = true
} else {
// Manual toggle - don't generate HTML
stopProfilerAndSave(false)
}
}
// Set up signal handling (SIGUSR2 on Unix-like systems)
if (process.platform !== 'win32') {
process.on('SIGUSR2', toggleProfiler)
console.log('Flame preload script loaded. Send SIGUSR2 to toggle profiling.')
} else {
// On Windows, we use SIGINT (Ctrl-C) or set up alternative IPC
console.log('Flame preload script loaded. Windows platform detected.')
console.log('Use the CLI toggle command or send SIGINT to control profiling.')
}
console.log(`Process PID: ${process.pid}`)
// Auto-start profiling if enabled
if (autoStart) {
// Parse delay option
const delayValue = process.env.FLAME_DELAY || 'until-started'
async function startProfiling () {
// Wait for sourcemaps to be initialized before starting profiling
if (sourceMapperPromise) {
await sourceMapperPromise
}
console.log('π₯ Auto-starting CPU and heap profilers...')
toggleProfiler()
}
// Apply delay before starting profiler
if (delayValue === 'none') {
// No delay - start immediately
startProfiling()
} else if (delayValue === 'until-started') {
// Special case: delay until next full event loop tick
// setImmediate runs after I/O events but before timers
// setTimeout(..., 0) then ensures we're at the start of the next event loop iteration
setImmediate(() => {
setTimeout(startProfiling, 0)
})
} else {
// Numeric delay in milliseconds
const delayMs = parseInt(delayValue, 10)
if (!isNaN(delayMs) && delayMs >= 0) {
setTimeout(startProfiling, delayMs)
} else {
console.error(`Invalid FLAME_DELAY value: ${delayValue}. Starting immediately.`)
startProfiling()
}
}
let exitHandlerCalled = false
// Auto-stop profiling when the process is about to exit
process.on('beforeExit', async () => {
if ((isCpuProfilerRunning || isHeapProfilerRunning) && !exitHandlerCalled) {
exitHandlerCalled = true
console.log('π₯ Process exiting, stopping profilers...')
await stopProfilerAndSave(true) // Generate HTML on exit
}
})
// Handle explicit process.exit() calls
const originalExit = process.exit
process.exit = function (code) {
if ((isCpuProfilerRunning || isHeapProfilerRunning) && !exitHandlerCalled) {
exitHandlerCalled = true
console.log('π₯ Process exiting, stopping profilers...')
// For process.exit(), we need to handle async differently since we can't await here
stopProfilerAndSave(true).then(() => {
return originalExit.call(this, code)
}).catch(() => {
return originalExit.call(this, code)
})
// Return without calling originalExit immediately - let the promise handle it
return
}
return originalExit.call(this, code)
}
process.on('SIGINT', () => {
if ((isCpuProfilerRunning || isHeapProfilerRunning) && !exitHandlerCalled) {
exitHandlerCalled = true
console.log('\nπ₯ SIGINT received, stopping profilers...')
// For signals, do a quick synchronous save and show HTML info immediately
const filenames = stopProfilerQuick()
if (filenames) {
generateHtmlAsync(filenames)
}
}
process.exit(0)
})
process.on('SIGTERM', () => {
if ((isCpuProfilerRunning || isHeapProfilerRunning) && !exitHandlerCalled) {
exitHandlerCalled = true
console.log('\nπ₯ SIGTERM received, stopping profilers...')
// For signals, do a quick synchronous save and show HTML info immediately
const filenames = stopProfilerQuick()
if (filenames) {
generateHtmlAsync(filenames)
}
}
process.exit(0)
})
}