Commit 6b32b20d authored by Jimmy Lai's avatar Jimmy Lai

refactor: use inspector API for CPU profiling instead of CLI flags

Consolidate CPU profiling to use the inspector-based approach in
cpu-profile.ts instead of injecting --cpu-prof CLI flags:

- Enhance cpu-profile.ts to support NEXT_CPU_PROF_DIR for output path
- Remove redundant --cpu-prof flag injection from next-dev.ts
- Update profiling script to use NEXT_CPU_PROF env var

The inspector API is cleaner and doesn't require modifying execArgv
for forked processes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: 's avatarClaude Opus 4.5 <noreply@anthropic.com>
parent e55cd63d
...@@ -319,18 +319,8 @@ const nextDev = async ( ...@@ -319,18 +319,8 @@ const nextDev = async (
nodeOptions.inspect = formatDebugAddress(address) nodeOptions.inspect = formatDebugAddress(address)
} }
// Build execArgv for the child process
const execArgv: string[] = []
// Support CPU profiling via NEXT_CPU_PROF_DIR env var
if (process.env.NEXT_CPU_PROF_DIR) {
execArgv.push('--cpu-prof')
execArgv.push(`--cpu-prof-dir=${process.env.NEXT_CPU_PROF_DIR}`)
}
child = fork(startServerPath, { child = fork(startServerPath, {
stdio: 'inherit', stdio: 'inherit',
execArgv: execArgv.length > 0 ? execArgv : undefined,
env: { env: {
...defaultEnv, ...defaultEnv,
...(bundler === Bundler.Turbopack ...(bundler === Bundler.Turbopack
......
const privateCpuProfileName = process.env.__NEXT_PRIVATE_CPU_PROFILE const privateCpuProfileName = process.env.__NEXT_PRIVATE_CPU_PROFILE
const isCpuProfileEnabled = process.env.NEXT_CPU_PROF || privateCpuProfileName const isCpuProfileEnabled = process.env.NEXT_CPU_PROF || privateCpuProfileName
const cpuProfileDir = process.env.NEXT_CPU_PROF_DIR
if (isCpuProfileEnabled) { if (isCpuProfileEnabled) {
const { Session } = require('inspector') as typeof import('inspector') const { Session } = require('inspector') as typeof import('inspector')
const fs = require('fs') as typeof import('fs') const fs = require('fs') as typeof import('fs')
const path = require('path') as typeof import('path')
const session = new Session() const session = new Session()
session.connect() session.connect()
...@@ -11,7 +13,12 @@ if (isCpuProfileEnabled) { ...@@ -11,7 +13,12 @@ if (isCpuProfileEnabled) {
session.post('Profiler.enable') session.post('Profiler.enable')
session.post('Profiler.start') session.post('Profiler.start')
let profileSaved = false
function saveProfile() { function saveProfile() {
if (profileSaved) return
profileSaved = true
session.post('Profiler.stop', (error, param) => { session.post('Profiler.stop', (error, param) => {
if (error) { if (error) {
console.error('Cannot generate CPU profiling:', error) console.error('Cannot generate CPU profiling:', error)
...@@ -20,13 +27,22 @@ if (isCpuProfileEnabled) { ...@@ -20,13 +27,22 @@ if (isCpuProfileEnabled) {
// Write profile to disk // Write profile to disk
const filename = `${ const filename = `${
privateCpuProfileName || 'CPU.main' privateCpuProfileName || 'CPU'
}.${Date.now()}.cpuprofile` }.${process.pid}.${Date.now()}.cpuprofile`
fs.writeFileSync(`./${filename}`, JSON.stringify(param.profile)) const outputPath = cpuProfileDir
process.exit(0) ? path.join(cpuProfileDir, filename)
: `./${filename}`
// Ensure output directory exists
if (cpuProfileDir) {
fs.mkdirSync(cpuProfileDir, { recursive: true })
}
fs.writeFileSync(outputPath, JSON.stringify(param.profile))
}) })
} }
process.on('SIGINT', saveProfile) process.on('SIGINT', saveProfile)
process.on('SIGTERM', saveProfile) process.on('SIGTERM', saveProfile)
process.on('exit', saveProfile) process.on('beforeExit', saveProfile)
} }
...@@ -96,30 +96,19 @@ async function runProfile() { ...@@ -96,30 +96,19 @@ async function runProfile() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let resolved = false let resolved = false
// Build the command based on whether we're profiling parent or child // Enable CPU profiling via inspector API
let spawnArgs const spawnEnv = {
let spawnEnv = { ...process.env, FORCE_COLOR: '0' } ...process.env,
FORCE_COLOR: '0',
if (profileParent) { NEXT_CPU_PROF: '1',
// Profile the parent process (next-dev.ts) NEXT_CPU_PROF_DIR: outputDir,
spawnArgs = [
process.execPath,
[
'--cpu-prof',
`--cpu-prof-dir=${outputDir}`,
nextBin,
'dev',
bundlerFlag,
],
]
} else {
// Profile the child process (start-server.ts)
// next-dev.ts checks NEXT_CPU_PROF_DIR and passes --cpu-prof to the forked child
spawnEnv.NEXT_CPU_PROF_DIR = outputDir
spawnArgs = [nextBin, ['dev', bundlerFlag]]
} }
// Profile either parent or child process
const spawnArgs = profileParent
? [process.execPath, [nextBin, 'dev', bundlerFlag]]
: [nextBin, ['dev', bundlerFlag]]
const child = spawn(spawnArgs[0], spawnArgs[1], { const child = spawn(spawnArgs[0], spawnArgs[1], {
cwd: testDir, cwd: testDir,
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
...@@ -222,15 +211,16 @@ async function runCliProfile() { ...@@ -222,15 +211,16 @@ async function runCliProfile() {
console.log('') console.log('')
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const child = spawn( const child = spawn(process.execPath, [nextBin, '--help'], {
process.execPath, cwd: process.cwd(),
['--cpu-prof', `--cpu-prof-dir=${outputDir}`, nextBin, '--help'], stdio: ['ignore', 'pipe', 'pipe'],
{ env: {
cwd: process.cwd(), ...process.env,
stdio: ['ignore', 'pipe', 'pipe'], FORCE_COLOR: '0',
env: { ...process.env, FORCE_COLOR: '0' }, NEXT_CPU_PROF: '1',
} NEXT_CPU_PROF_DIR: outputDir,
) },
})
child.stdout.on('data', () => {}) child.stdout.on('data', () => {})
child.stderr.on('data', () => {}) child.stderr.on('data', () => {})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment