Unverified Commit fd5817d0 authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

feat: add --experimental-cpu-prof flag for dev, build, and start (#87946)

## What

Adds a `--experimental-cpu-prof` flag to `next dev`, `next build`, and
`next start` commands to capture V8 CPU profiles for debugging
performance bottlenecks.

## Why

When investigating slow builds, slow dev server startups, or production
server performance issues, having access to CPU profiles is invaluable.
This provides a first-party way to capture these profiles without
needing to manually set up the V8 inspector.

## How

- Adds `--experimental-cpu-prof` flag to CLI commands
- Uses V8's built-in CPU profiler via Node.js inspector module
- Profiles are saved to `.next/cpu-profiles/` with descriptive filenames
- Profiles are saved on process exit (Ctrl+C, SIGTERM, or normal exit)

### Profile files generated

**`next dev`:**
- `dev-main-*` - Parent process (dev server orchestration)
- `dev-server-*` - Child server process (request handling and rendering)

**`next build` (Turbopack):**
- `build-main-*` - Main build orchestration process
- `build-turbopack-*` - Turbopack compilation worker

**`next build` (Webpack):**
- `build-main-*` - Main build orchestration process
- `build-webpack-client-*` - Client bundle compilation worker
- `build-webpack-server-*` - Server bundle compilation worker
- `build-webpack-edge-server-*` - Edge runtime compilation worker

**`next start`:**
- `start-main-*` - Production server process

## Changes addressing PR review comments

- Removed signal handlers from `cpu-profile.ts` to prevent conflicts
with CLI cleanup logic (telemetry, traces, etc.)
- Added synchronous exit handler for non-signal process exits (errors,
`process.exit()` calls)
- CLI commands now explicitly call `saveCpuProfile()` as part of their
cleanup before exiting
- Replaced raw ANSI escape codes with `picocolors` library
- Added comprehensive documentation about profile file naming for each
command
- Added build profiling test that verifies correct profile generation
for both Turbopack and Webpack modes

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent 023be2e8
...@@ -56,6 +56,7 @@ The following commands are available: ...@@ -56,6 +56,7 @@ The following commands are available:
| `--experimental-https-cert <path>` | Path to a HTTPS certificate file. | | `--experimental-https-cert <path>` | Path to a HTTPS certificate file. |
| `--experimental-https-ca <path>` | Path to a HTTPS certificate authority file. | | `--experimental-https-ca <path>` | Path to a HTTPS certificate authority file. |
| `--experimental-upload-trace <traceUrl>` | Reports a subset of the debugging trace to a remote HTTP URL. | | `--experimental-upload-trace <traceUrl>` | Reports a subset of the debugging trace to a remote HTTP URL. |
| `--experimental-cpu-prof` | Enables CPU profiling using V8's inspector. Profiles are saved to `.next/cpu-profiles/` on exit. |
### `next build` options ### `next build` options
...@@ -87,6 +88,7 @@ The following options are available for the `next build` command: ...@@ -87,6 +88,7 @@ The following options are available for the `next build` command:
| `--experimental-build-mode [mode]` | Uses an experimental build mode. (choices: "compile", "generate", default: "default") | | `--experimental-build-mode [mode]` | Uses an experimental build mode. (choices: "compile", "generate", default: "default") |
| `--debug-prerender` | Debug prerender errors in development. | | `--debug-prerender` | Debug prerender errors in development. |
| `--debug-build-paths=<patterns>` | Build only specific routes for debugging. | | `--debug-build-paths=<patterns>` | Build only specific routes for debugging. |
| `--experimental-cpu-prof` | Enables CPU profiling using V8's inspector. Profiles are saved to `.next/cpu-profiles/` on exit. |
### `next start` options ### `next start` options
...@@ -101,6 +103,7 @@ The following options are available for the `next start` command: ...@@ -101,6 +103,7 @@ The following options are available for the `next start` command:
| `-p` or `--port <port>` | Specify a port number on which to start the application. (default: 3000, env: PORT) | | `-p` or `--port <port>` | Specify a port number on which to start the application. (default: 3000, env: PORT) |
| `-H` or `--hostname <hostname>` | Specify a hostname on which to start the application (default: 0.0.0.0). | | `-H` or `--hostname <hostname>` | Specify a hostname on which to start the application (default: 0.0.0.0). |
| `--keepAliveTimeout <keepAliveTimeout>` | Specify the maximum amount of milliseconds to wait before closing the inactive connections. | | `--keepAliveTimeout <keepAliveTimeout>` | Specify the maximum amount of milliseconds to wait before closing the inactive connections. |
| `--experimental-cpu-prof` | Enables CPU profiling using V8's inspector. Profiles are saved to `.next/cpu-profiles/` on exit. |
### `next info` options ### `next info` options
...@@ -334,6 +337,46 @@ NODE_OPTIONS='-r esm' next ...@@ -334,6 +337,46 @@ NODE_OPTIONS='-r esm' next
NODE_OPTIONS='--inspect' next NODE_OPTIONS='--inspect' next
``` ```
### CPU profiling
You can capture CPU profiles to analyze performance bottlenecks in your Next.js application. The `--experimental-cpu-prof` flag enables V8's built-in CPU profiler and saves profiles to `.next/cpu-profiles/` when the process exits:
```bash filename="Terminal"
# Profile the build process
next build --experimental-cpu-prof
# Profile the dev server (profile saved on Ctrl+C or SIGTERM)
next dev --experimental-cpu-prof
# Profile the production server
next start --experimental-cpu-prof
```
The generated `.cpuprofile` files can be opened in Chrome DevTools (Performance tab → Load profile) or other V8-compatible profiling tools.
> **Good to know**: Profile files are named with a descriptive prefix and timestamp. The profiles generated depend on the command:
>
> **`next dev`:**
>
> - `dev-main-*` - Parent process (dev server orchestration)
> - `dev-server-*` - Child server process (request handling and rendering) - this is typically what you want to analyze
>
> **`next build` (Turbopack):**
>
> - `build-main-*` - Main build orchestration process
> - `build-turbopack-*` - Turbopack compilation worker
>
> **`next build` (Webpack):**
>
> - `build-main-*` - Main build orchestration process
> - `build-webpack-client-*` - Client bundle compilation worker
> - `build-webpack-server-*` - Server bundle compilation worker
> - `build-webpack-edge-server-*` - Edge runtime compilation worker
>
> **`next start`:**
>
> - `start-main-*` - Production server process
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------- | | --------- | ------------------------------------------------------------------------------- |
| `v16.1.0` | Add the `next experimental-analyze` command | | `v16.1.0` | Add the `next experimental-analyze` command |
......
...@@ -186,15 +186,32 @@ program ...@@ -186,15 +186,32 @@ program
'--debug-build-paths <patterns>', '--debug-build-paths <patterns>',
'Comma-separated glob patterns or explicit paths for selective builds. Examples: "app/*", "app/page.tsx", "app/**/page.tsx"' 'Comma-separated glob patterns or explicit paths for selective builds. Examples: "app/*", "app/page.tsx", "app/**/page.tsx"'
) )
.option(
'--experimental-cpu-prof',
'Enable CPU profiling. Profile is saved to .next/cpu-profiles/ on completion.'
)
.action((directory: string, options: NextBuildOptions) => { .action((directory: string, options: NextBuildOptions) => {
if (options.experimentalNextConfigStripTypes) { if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true' process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
} }
if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'build-main'
const { join } = require('path') as typeof import('path')
const dir = directory || process.cwd()
process.env.NEXT_CPU_PROF_DIR = join(dir, '.next', 'cpu-profiles')
}
// ensure process exits after build completes so open handles/connections // ensure process exits after build completes so open handles/connections
// don't cause process to hang // don't cause process to hang
return import('../cli/next-build.js').then((mod) => return import('../cli/next-build.js').then((mod) =>
mod.nextBuild(options, directory).then(() => process.exit(0)) mod.nextBuild(options, directory).then(async () => {
// Save CPU profile before exiting if enabled
if (options.experimentalCpuProf) {
await mod.saveCpuProfile()
}
process.exit(0)
})
) )
}) })
.usage('[directory] [options]') .usage('[directory] [options]')
...@@ -297,11 +314,22 @@ program ...@@ -297,11 +314,22 @@ program
'--experimental-next-config-strip-types', '--experimental-next-config-strip-types',
'Use Node.js native TypeScript resolution for next.config.(ts|mts)' 'Use Node.js native TypeScript resolution for next.config.(ts|mts)'
) )
.option(
'--experimental-cpu-prof',
'Enable CPU profiling. Profiles are saved to .next/cpu-profiles/ on exit.'
)
.action( .action(
(directory: string, options: NextDevOptions, { _optionValueSources }) => { (directory: string, options: NextDevOptions, { _optionValueSources }) => {
if (options.experimentalNextConfigStripTypes) { if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true' process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
} }
if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'dev-main'
const { join } = require('path') as typeof import('path')
const dir = directory || process.cwd()
process.env.NEXT_CPU_PROF_DIR = join(dir, '.next', 'cpu-profiles')
}
const portSource = _optionValueSources.port const portSource = _optionValueSources.port
import('../cli/next-dev.js').then((mod) => import('../cli/next-dev.js').then((mod) =>
mod.nextDev(options, portSource, directory) mod.nextDev(options, portSource, directory)
...@@ -363,10 +391,21 @@ program ...@@ -363,10 +391,21 @@ program
'--experimental-next-config-strip-types', '--experimental-next-config-strip-types',
'Use Node.js native TypeScript resolution for next.config.(ts|mts)' 'Use Node.js native TypeScript resolution for next.config.(ts|mts)'
) )
.option(
'--experimental-cpu-prof',
'Enable CPU profiling. Profiles are saved to .next/cpu-profiles/ on exit.'
)
.action((directory: string, options: NextStartOptions) => { .action((directory: string, options: NextStartOptions) => {
if (options.experimentalNextConfigStripTypes) { if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true' process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
} }
if (options.experimentalCpuProf) {
process.env.NEXT_CPU_PROF = '1'
process.env.__NEXT_PRIVATE_CPU_PROFILE = 'start-main'
const { join } = require('path') as typeof import('path')
const dir = directory || process.cwd()
process.env.NEXT_CPU_PROF_DIR = join(dir, '.next', 'cpu-profiles')
}
return import('../cli/next-start.js').then((mod) => return import('../cli/next-start.js').then((mod) =>
mod.nextStart(options, directory) mod.nextStart(options, directory)
) )
......
// Import cpu-profile to start profiling early if enabled
import '../server/lib/cpu-profile'
import { Span } from '../trace' import { Span } from '../trace'
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
......
...@@ -831,6 +831,15 @@ export function createStaticWorker( ...@@ -831,6 +831,15 @@ export function createStaticWorker(
isolatedMemory: true, isolatedMemory: true,
enableWorkerThreads: config.experimental.workerThreads, enableWorkerThreads: config.experimental.workerThreads,
exposedMethods: staticWorkerExposedMethods, exposedMethods: staticWorkerExposedMethods,
forkOptions: process.env.NEXT_CPU_PROF
? {
env: {
NEXT_CPU_PROF: '1',
NEXT_CPU_PROF_DIR: process.env.NEXT_CPU_PROF_DIR,
__NEXT_PRIVATE_CPU_PROFILE: 'build-static-worker',
},
}
: undefined,
}) as StaticWorker }) as StaticWorker
} }
...@@ -1735,6 +1744,15 @@ export default async function build( ...@@ -1735,6 +1744,15 @@ export default async function build(
isolatedMemory: false, isolatedMemory: false,
numWorkers: 1, numWorkers: 1,
exposedMethods: ['collectBuildTraces'], exposedMethods: ['collectBuildTraces'],
forkOptions: process.env.NEXT_CPU_PROF
? {
env: {
NEXT_CPU_PROF: '1',
NEXT_CPU_PROF_DIR: process.env.NEXT_CPU_PROF_DIR,
__NEXT_PRIVATE_CPU_PROFILE: 'build-trace-worker',
},
}
: undefined,
} }
) as Worker & typeof import('./collect-build-traces') ) as Worker & typeof import('./collect-build-traces')
......
// Import cpu-profile first to start profiling early if enabled
import { saveCpuProfile } from '../../server/lib/cpu-profile'
import path from 'path' import path from 'path'
import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import { isFileSystemCacheEnabledForBuild } from '../../shared/lib/turbopack/utils' import { isFileSystemCacheEnabledForBuild } from '../../shared/lib/turbopack/utils'
...@@ -261,6 +263,8 @@ export async function workerMain(workerData: { ...@@ -261,6 +263,8 @@ export async function workerMain(workerData: {
} finally { } finally {
// Always flush telemetry before worker exits (waits for async operations like setTimeout in debug mode) // Always flush telemetry before worker exits (waits for async operations like setTimeout in debug mode)
await telemetry.flush() await telemetry.flush()
// Save CPU profile before worker exits
await saveCpuProfile()
} }
} }
......
...@@ -17,6 +17,13 @@ async function turbopackBuildWithWorker(): ReturnType< ...@@ -17,6 +17,13 @@ async function turbopackBuildWithWorker(): ReturnType<
forkOptions: { forkOptions: {
env: { env: {
NEXT_PRIVATE_BUILD_WORKER: '1', NEXT_PRIVATE_BUILD_WORKER: '1',
...(process.env.NEXT_CPU_PROF
? {
NEXT_CPU_PROF: '1',
NEXT_CPU_PROF_DIR: process.env.NEXT_CPU_PROF_DIR,
__NEXT_PRIVATE_CPU_PROFILE: 'build-turbopack',
}
: undefined),
}, },
}, },
}) as Worker & typeof import('./impl') }) as Worker & typeof import('./impl')
......
// Import cpu-profile first to start profiling early if enabled
import { saveCpuProfile } from '../../server/lib/cpu-profile'
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import { stringBufferUtils } from 'next/dist/compiled/webpack-sources3' import { stringBufferUtils } from 'next/dist/compiled/webpack-sources3'
import { red } from '../../lib/picocolors' import { red } from '../../lib/picocolors'
...@@ -416,5 +418,8 @@ export async function workerMain(workerData: { ...@@ -416,5 +418,8 @@ export async function workerMain(workerData: {
NextBuildContext.nextBuildSpan.stop() NextBuildContext.nextBuildSpan.stop()
await telemetry.flush() await telemetry.flush()
// Save CPU profile before worker exits
await saveCpuProfile()
return { ...result, debugTraceEvents: getTraceEvents() } return { ...result, debugTraceEvents: getTraceEvents() }
} }
...@@ -54,6 +54,13 @@ async function webpackBuildWithWorker( ...@@ -54,6 +54,13 @@ async function webpackBuildWithWorker(
forkOptions: { forkOptions: {
env: { env: {
NEXT_PRIVATE_BUILD_WORKER: '1', NEXT_PRIVATE_BUILD_WORKER: '1',
...(process.env.NEXT_CPU_PROF
? {
NEXT_CPU_PROF: '1',
NEXT_CPU_PROF_DIR: process.env.NEXT_CPU_PROF_DIR,
__NEXT_PRIVATE_CPU_PROFILE: `build-webpack-${compilerName}`,
}
: undefined),
}, },
}, },
}) as Worker & typeof import('./impl') }) as Worker & typeof import('./impl')
......
import '../server/require-hook' import '../server/require-hook'
// Import cpu-profile to start profiling early if enabled
import '../server/lib/cpu-profile'
export { export {
getDefinedNamedExports, getDefinedNamedExports,
......
#!/usr/bin/env node #!/usr/bin/env node
import '../server/lib/cpu-profile' import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import { italic } from '../lib/picocolors' import { italic } from '../lib/picocolors'
import analyze from '../build/analyze' import analyze from '../build/analyze'
...@@ -18,8 +19,14 @@ export type NextAnalyzeOptions = { ...@@ -18,8 +19,14 @@ export type NextAnalyzeOptions = {
} }
const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => { const nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {
process.on('SIGTERM', () => process.exit(143)) process.on('SIGTERM', () => {
process.on('SIGINT', () => process.exit(130)) saveCpuProfile()
process.exit(143)
})
process.on('SIGINT', () => {
saveCpuProfile()
process.exit(130)
})
const { profile, mangling, experimentalAppOnly, output, port } = options const { profile, mangling, experimentalAppOnly, output, port } = options
......
#!/usr/bin/env node #!/usr/bin/env node
import '../server/lib/cpu-profile' import { saveCpuProfile } from '../server/lib/cpu-profile'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import { italic } from '../lib/picocolors' import { italic } from '../lib/picocolors'
import build from '../build' import build from '../build'
...@@ -32,11 +32,18 @@ export type NextBuildOptions = { ...@@ -32,11 +32,18 @@ export type NextBuildOptions = {
experimentalUploadTrace?: string experimentalUploadTrace?: string
experimentalNextConfigStripTypes?: boolean experimentalNextConfigStripTypes?: boolean
debugBuildPaths?: string debugBuildPaths?: string
experimentalCpuProf?: boolean
} }
const nextBuild = async (options: NextBuildOptions, directory?: string) => { const nextBuild = async (options: NextBuildOptions, directory?: string) => {
process.on('SIGTERM', () => process.exit(143)) process.on('SIGTERM', () => {
process.on('SIGINT', () => process.exit(130)) saveCpuProfile()
process.exit(143)
})
process.on('SIGINT', () => {
saveCpuProfile()
process.exit(130)
})
const { const {
experimentalAnalyze, experimentalAnalyze,
...@@ -157,4 +164,4 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => { ...@@ -157,4 +164,4 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
}) })
} }
export { nextBuild } export { nextBuild, saveCpuProfile }
#!/usr/bin/env node #!/usr/bin/env node
import '../server/lib/cpu-profile' import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import type { StartServerOptions } from '../server/lib/start-server' import type { StartServerOptions } from '../server/lib/start-server'
import { import {
RESTART_EXIT_CODE, RESTART_EXIT_CODE,
...@@ -60,6 +61,7 @@ export type NextDevOptions = { ...@@ -60,6 +61,7 @@ export type NextDevOptions = {
experimentalHttpsCa?: string experimentalHttpsCa?: string
experimentalUploadTrace?: string experimentalUploadTrace?: string
experimentalNextConfigStripTypes?: boolean experimentalNextConfigStripTypes?: boolean
experimentalCpuProf?: boolean
} }
type PortSource = 'cli' | 'default' | 'env' type PortSource = 'cli' | 'default' | 'env'
...@@ -162,6 +164,9 @@ const handleSessionStop = async (signal: NodeJS.Signals | number | null) => { ...@@ -162,6 +164,9 @@ const handleSessionStop = async (signal: NodeJS.Signals | number | null) => {
}) })
} }
// Save CPU profile if it was enabled (before exiting)
saveCpuProfile()
// ensure we re-enable the terminal cursor before exiting // ensure we re-enable the terminal cursor before exiting
// the program, or the cursor could remain hidden // the program, or the cursor could remain hidden
process.stdout.write('\x1B[?25h') process.stdout.write('\x1B[?25h')
...@@ -189,6 +194,12 @@ const nextDev = async ( ...@@ -189,6 +194,12 @@ const nextDev = async (
printAndExit(`> No such directory exists as the project root: ${dir}`) printAndExit(`> No such directory exists as the project root: ${dir}`)
} }
if (options.experimentalCpuProf) {
Log.info(
`CPU profiling enabled. Profile will be saved to .next/cpu-profiles/ on exit (Ctrl+C).`
)
}
async function preflight(skipOnReboot: boolean) { async function preflight(skipOnReboot: boolean) {
const { getPackageVersion, getDependencies } = (await Promise.resolve( const { getPackageVersion, getDependencies } = (await Promise.resolve(
require('../lib/get-package-version') as typeof import('../lib/get-package-version') require('../lib/get-package-version') as typeof import('../lib/get-package-version')
...@@ -318,6 +329,14 @@ const nextDev = async ( ...@@ -318,6 +329,14 @@ const nextDev = async (
// https://github.com/nodejs/node/issues/29949 // https://github.com/nodejs/node/issues/29949
WATCHPACK_WATCHER_LIMIT: WATCHPACK_WATCHER_LIMIT:
os.platform() === 'darwin' ? '20' : undefined, os.platform() === 'darwin' ? '20' : undefined,
// Enable CPU profiling if requested
...(options.experimentalCpuProf
? {
NEXT_CPU_PROF: '1',
NEXT_CPU_PROF_DIR: path.join(dir, '.next', 'cpu-profiles'),
__NEXT_PRIVATE_CPU_PROFILE: 'dev-server',
}
: undefined),
}, },
}) })
......
#!/usr/bin/env node #!/usr/bin/env node
import '../server/lib/cpu-profile' import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import { startServer } from '../server/lib/start-server' import { startServer } from '../server/lib/start-server'
import { printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
...@@ -8,12 +9,14 @@ import { ...@@ -8,12 +9,14 @@ import {
getReservedPortExplanation, getReservedPortExplanation,
isPortIsReserved, isPortIsReserved,
} from '../lib/helpers/get-reserved-port' } from '../lib/helpers/get-reserved-port'
import * as Log from '../build/output/log'
export type NextStartOptions = { export type NextStartOptions = {
port: number port: number
hostname?: string hostname?: string
keepAliveTimeout?: number keepAliveTimeout?: number
experimentalNextConfigStripTypes?: boolean experimentalNextConfigStripTypes?: boolean
experimentalCpuProf?: boolean
} }
/** /**
...@@ -32,6 +35,13 @@ const nextStart = async (options: NextStartOptions, directory?: string) => { ...@@ -32,6 +35,13 @@ const nextStart = async (options: NextStartOptions, directory?: string) => {
printAndExit(getReservedPortExplanation(port), 1) printAndExit(getReservedPortExplanation(port), 1)
} }
if (options.experimentalCpuProf) {
Log.info(`CPU profiling enabled. Profile will be saved on exit (Ctrl+C).`)
// Save CPU profile on shutdown signals, but let start-server.ts handle graceful exit
process.on('SIGTERM', () => saveCpuProfile())
process.on('SIGINT', () => saveCpuProfile())
}
await startServer({ await startServer({
dir, dir,
isDev: false, isDev: false,
......
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
let session: import('inspector').Session | null = null
let profileSaved = false
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 session = new Session() session = new Session()
session.connect() session.connect()
session.post('Profiler.enable') session.post('Profiler.enable')
session.post('Profiler.start') session.post('Profiler.start')
function saveProfile() { process.on('exit', () => {
session.post('Profiler.stop', (error, param) => { saveCpuProfile()
if (error) { })
console.error('Cannot generate CPU profiling:', error) }
return
}
// Write profile to disk /**
const filename = `${ * Save the CPU profile to disk.
privateCpuProfileName || 'CPU.main' *
}.${Date.now()}.cpuprofile` * This is synchronous despite the callback-based API because inspector's
fs.writeFileSync(`./${filename}`, JSON.stringify(param.profile)) * session.post() executes its callback synchronously when connected to
process.exit(0) * the same process (via session.connect()).
}) */
export function saveCpuProfile(): void {
if (!session || profileSaved || !isCpuProfileEnabled) {
return
} }
process.on('SIGINT', saveProfile) profileSaved = true
process.on('SIGTERM', saveProfile)
process.on('exit', saveProfile) const fs = require('fs') as typeof import('fs')
const path = require('path') as typeof import('path')
session!.post('Profiler.stop', (error, param) => {
if (error) {
console.error('Cannot generate CPU profiling:', error)
return
}
const timestamp = new Date()
.toISOString()
.replace(/[:.]/g, '-')
.slice(0, 19)
const baseName = privateCpuProfileName || 'cpu-profile'
const filename = `${baseName}-${timestamp}.cpuprofile`
let outputPath: string
if (cpuProfileDir) {
if (!fs.existsSync(cpuProfileDir)) {
fs.mkdirSync(cpuProfileDir, { recursive: true })
}
outputPath = path.join(cpuProfileDir, filename)
} else {
outputPath = `./${filename}`
}
fs.writeFileSync(outputPath, JSON.stringify(param.profile))
const { green } =
require('../../lib/picocolors') as typeof import('../../lib/picocolors')
console.log(`\n${green('CPU profile saved:')} ${outputPath}`)
console.log('Open in Chrome DevTools → Performance tab → Load profile')
})
} }
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export default function Home() {
return <h1>Hello from CPU Profiling Test</h1>
}
import { nextTestSetup, isNextDeploy } from 'e2e-utils'
import { pathExists, readdir } from 'fs-extra'
import { join } from 'path'
describe('CPU Profiling - next build', () => {
const { next, isNextDev, skipped, isTurbopack } = nextTestSetup({
files: __dirname,
buildCommand: 'pnpm next build --experimental-cpu-prof',
dependencies: {},
skipStart: true,
skipDeployment: true,
})
// CPU profiling only works with local `next build`, not dev or deploy modes
if (isNextDev || isNextDeploy || skipped) {
it('skip for development/deploy mode', () => {})
return
}
beforeAll(async () => {
// Run the build with CPU profiling enabled
await next.build()
})
it('should create CPU profile files after build', async () => {
const profileDir = join(next.testDir, '.next', 'cpu-profiles')
const profileDirExists = await pathExists(profileDir)
expect(profileDirExists).toBe(true)
const files = await readdir(profileDir)
const cpuProfiles = files.filter((f: string) => f.endsWith('.cpuprofile'))
// Main profile should always exist
expect(cpuProfiles.some((f) => f.startsWith('build-main-'))).toBe(true)
if (isTurbopack) {
// Turbopack mode generates: build-main, build-turbopack
expect(cpuProfiles.length).toBe(2)
expect(cpuProfiles.some((f) => f.startsWith('build-turbopack-'))).toBe(
true
)
} else {
// Webpack mode generates: build-main, build-webpack-client, build-webpack-server, build-webpack-edge-server
expect(cpuProfiles.length).toBe(4)
expect(
cpuProfiles.some((f) => f.startsWith('build-webpack-client-'))
).toBe(true)
expect(
cpuProfiles.some((f) => f.startsWith('build-webpack-server-'))
).toBe(true)
expect(
cpuProfiles.some((f) => f.startsWith('build-webpack-edge-server-'))
).toBe(true)
}
})
})
import { nextTestSetup } from 'e2e-utils'
import { pathExists, readdir } from 'fs-extra'
import { join } from 'path'
import { retry } from 'next-test-utils'
describe('CPU Profiling - next dev', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
startCommand: 'pnpm next dev --experimental-cpu-prof',
dependencies: {},
})
if (!isNextDev) {
it('skip for production mode', () => {})
return
}
it('should create CPU profile files on exit', async () => {
const profileDir = join(next.testDir, '.next', 'cpu-profiles')
// Make a request to ensure the server is running
const res = await next.fetch('/')
expect(res.status).toBe(200)
// Stop the server with SIGTERM to trigger profile save (SIGKILL doesn't allow cleanup)
await next.stop('SIGTERM')
// Retry until profile files are written
const cpuProfiles = await retry(async () => {
const profileDirExists = await pathExists(profileDir)
expect(profileDirExists).toBe(true)
const files = await readdir(profileDir)
const profiles = files.filter((f: string) => f.endsWith('.cpuprofile'))
expect(profiles.length).toBeGreaterThanOrEqual(1)
return profiles
})
// Verify profile names are meaningful
for (const profile of cpuProfiles) {
expect(profile).toMatch(
/^(dev-main|dev-server)-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.cpuprofile$/
)
}
})
})
import { nextTestSetup, isNextDeploy } from 'e2e-utils'
import { pathExists, readdir } from 'fs-extra'
import { join } from 'path'
import { retry } from 'next-test-utils'
describe('CPU Profiling - next start', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
startCommand: 'pnpm next start --experimental-cpu-prof',
dependencies: {},
skipStart: true, // Skip auto-start to avoid failure in dev/deploy mode
})
// CPU profiling only works with local `next start`, not dev or deploy modes
if (isNextDev || isNextDeploy || skipped) {
it('skip for development/deploy mode', () => {})
return
}
beforeAll(async () => {
await next.start()
})
it('should create CPU profile files on exit', async () => {
const profileDir = join(next.testDir, '.next', 'cpu-profiles')
// Make a request to ensure the server is running
const res = await next.fetch('/')
expect(res.status).toBe(200)
// Stop the server with SIGTERM to trigger profile save (SIGKILL doesn't allow cleanup)
await next.stop('SIGTERM')
// Retry until profile files are written
const cpuProfiles = await retry(async () => {
const profileDirExists = await pathExists(profileDir)
expect(profileDirExists).toBe(true)
const files = await readdir(profileDir)
const profiles = files.filter((f: string) => f.endsWith('.cpuprofile'))
expect(profiles.length).toBeGreaterThan(0)
return profiles
})
// Verify profile name is meaningful (start-main)
for (const profile of cpuProfiles) {
expect(profile).toMatch(
/^start-main-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.cpuprofile$/
)
}
})
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export default function Page() {
return <h1>Hello</h1>
}
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"noEmit": true,
"incremental": true,
"module": "esnext",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"plugins": [
{
"name": "next"
}
]
},
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts",
"**/*.ts",
"**/*.tsx"
],
"exclude": ["node_modules"]
}
/* eslint-env jest */
import { remove, pathExists, readdir } from 'fs-extra'
import { nextBuild } from 'next-test-utils'
import { join } from 'path'
const fixturesDir = join(__dirname, '..', 'fixtures')
const appDir = join(fixturesDir, 'basic-app')
describe('CPU Profiling', () => {
beforeEach(async () => {
await remove(join(appDir, '.next'))
})
describe('next build --experimental-cpu-prof', () => {
it('should create CPU profile files with meaningful names', async () => {
const profileDir = join(appDir, '.next', 'cpu-profiles')
const { stdout } = await nextBuild(appDir, ['--experimental-cpu-prof'], {
stdout: true,
stderr: true,
})
expect(stdout).toContain('CPU profile saved')
const profileDirExists = await pathExists(profileDir)
expect(profileDirExists).toBe(true)
const files = await readdir(profileDir)
const cpuProfiles = files.filter((f) => f.endsWith('.cpuprofile'))
expect(cpuProfiles.length).toBeGreaterThan(0)
// Verify profile names are meaningful (not just random numbers)
for (const profile of cpuProfiles) {
// Profile names should contain descriptive prefixes like 'build-main', 'build-webpack-server', etc.
expect(profile).toMatch(
/^(build-main|build-webpack-(server|client|edge-server)|build-turbopack|build-static-worker|build-trace-worker)-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.cpuprofile$/
)
}
})
it('should create profiles for worker processes', async () => {
const profileDir = join(appDir, '.next', 'cpu-profiles')
await nextBuild(appDir, ['--experimental-cpu-prof'], {
stdout: true,
stderr: true,
})
const files = await readdir(profileDir)
const cpuProfiles = files.filter((f) => f.endsWith('.cpuprofile'))
// Should have at least main process profile and potentially worker profiles
expect(cpuProfiles.length).toBeGreaterThanOrEqual(1)
// Verify we have the main build profile
const mainProfile = cpuProfiles.find((f) => f.startsWith('build-main'))
expect(mainProfile).toBeDefined()
})
})
})
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