Commit 80730456 authored by Jimmy Lai's avatar Jimmy Lai

Add perf marks, benchmark runner, and restore OTel startResponse span

- Add opt-in perf marks module (NEXT_PERF_MARKS=1) for SSR phase timing
- Add benchmark runner (bench/basic-app/run-bench.js) with CPU profiling and auto-comparison
- Restore NextNodeServer.startResponse to NextVanillaSpanAllowlist (fixes OTel test)
- Update AGENTS.md with benchmarking docs and streaming pipeline notes
- Enhance minimal-server with perf marks collection and CPU profiling support
parent dddf2c76
...@@ -54,9 +54,9 @@ pnpm --filter=next exec taskr <task> ...@@ -54,9 +54,9 @@ pnpm --filter=next exec taskr <task>
## Fast Local Development ## Fast Local Development
For iterative development, use watch mode + fast test execution: **`pnpm --filter=next dev` is the default for ALL iterative work**: editing, testing, and benchmarking. Start it at the beginning of any session that involves editing Next.js source code. Only use `pnpm --filter=next build` for one-off builds (after branch switch, before CI push).
**1. Start watch build in background:** **1. Start watch build in background (do this first):**
```bash ```bash
# Runs taskr in watch mode - auto-rebuilds on file changes # Runs taskr in watch mode - auto-rebuilds on file changes
...@@ -64,18 +64,18 @@ For iterative development, use watch mode + fast test execution: ...@@ -64,18 +64,18 @@ For iterative development, use watch mode + fast test execution:
pnpm --filter=next dev pnpm --filter=next dev
``` ```
**2. Run tests fast (no isolation, no packing):** **2. Edit, test, or benchmark** while watch auto-compiles to `packages/next/dist/`:
```bash ```bash
# NEXT_SKIP_ISOLATE=1 - skip packing Next.js for each test (much faster) # Run tests fast (no isolation, no packing)
# testonly - runs with --runInBand (no worker isolation overhead)
NEXT_SKIP_ISOLATE=1 NEXT_TEST_MODE=dev pnpm testonly test/path/to/test.ts NEXT_SKIP_ISOLATE=1 NEXT_TEST_MODE=dev pnpm testonly test/path/to/test.ts
# Run SSR benchmark
node bench/basic-app/run-bench.js
``` ```
**3. When done, kill the background watch process.** **3. When done, kill the background watch process.**
Only use full `pnpm --filter=next build` for one-off builds (after branch switch, before CI push).
**Always rebuild after switching branches:** **Always rebuild after switching branches:**
```bash ```bash
...@@ -83,6 +83,26 @@ git checkout <branch> ...@@ -83,6 +83,26 @@ git checkout <branch>
pnpm build # Required before running tests (Turborepo dedupes if unchanged) pnpm build # Required before running tests (Turborepo dedupes if unchanged)
``` ```
### Benchmarking
The `bench/basic-app/` directory contains a `force-dynamic` hello-world app with a pre-built `.next/`. The benchmark runner spawns a minimal server, warms up, and measures throughput and latency.
```bash
# Basic throughput test (runs c1 and c100)
node bench/basic-app/run-bench.js
# With CPU profiling (generates .cpuprofile + hot module analysis)
node bench/basic-app/run-bench.js --profile
# With SSR phase timing breakdown
node bench/basic-app/run-bench.js --marks --concurrency 1
# Custom options
node bench/basic-app/run-bench.js --concurrency 50 --duration 20
```
Results are saved to `bench/basic-app/last-run.json`. Re-running the benchmark automatically shows a comparison with the previous run (% change in req/s).
## Testing ## Testing
```bash ```bash
...@@ -250,12 +270,20 @@ When running Next.js integration tests, you must rebuild if source files have ch ...@@ -250,12 +270,20 @@ When running Next.js integration tests, you must rebuild if source files have ch
- **Edited Turbopack (Rust)?** → `pnpm swc-build-native` - **Edited Turbopack (Rust)?** → `pnpm swc-build-native`
- **Edited both?** → `pnpm turbo build build-native` - **Edited both?** → `pnpm turbo build build-native`
## SSR Streaming Pipeline
The SSR streaming pipeline lives in `packages/next/src/server/stream-utils/node-web-streams-helper.ts`. For dynamic SSR, `continueFizzStream` pipes React's output through `createUnifiedSSRTransformStream`, which handles buffered batching, metadata icon marks, deferred suffix, flight data injection, suffix movement, and head insertion in a single `TransformStream`. Prerendering paths use individual transforms chained separately.
Unit tests are co-located at `node-web-streams-helper.test.ts` and run against both the unified transform and the legacy chain of individual transforms.
## Development Anti-Patterns ## Development Anti-Patterns
### Test Gotchas ### Test Gotchas
- Mode-specific tests need `skipStart: true` + manual `next.start()` in `beforeAll` after mode check - Mode-specific tests need `skipStart: true` + manual `next.start()` in `beforeAll` after mode check
- Don't rely on exact log messages - filter by content patterns, find sequences not positions - Don't rely on exact log messages - filter by content patterns, find sequences not positions
- **Stream transform tests**: `scheduleImmediate`-based transforms (deferred suffix, buffered flush) don't work with synchronous test streams where all chunks are enqueued in `start()`. Use async chunk delivery with delays between chunks so `scheduleImmediate` callbacks fire between transforms. See `asyncStreamFromChunks` in `node-web-streams-helper.test.ts`
- **Co-located unit tests**: Server code can have `.test.ts` files next to the source (e.g., `node-web-streams-helper.test.ts`). These run with `pnpm test-unit` alongside tests in `test/unit/`
### Rust/Cargo ### Rust/Cargo
......
#!/usr/bin/env node
/**
* All-in-one SSR benchmark runner for Next.js
*
* Usage:
* node bench/basic-app/run-bench.js [options]
*
* Options:
* --profile Start server with CPU profiling, analyze after run
* --marks Enable NEXT_PERF_MARKS, collect phase timing
* --concurrency N Override concurrency (default: runs both c1 and c100)
* --duration N Seconds per benchmark run (default: 10)
* --warmup N Number of warmup requests (default: 50)
* --port N Port to use (default: 3000)
* --url PATH URL path to benchmark (default: /)
*/
const http = require('http')
const { spawn } = require('child_process')
const path = require('path')
const fs = require('fs')
// Parse CLI args
const args = process.argv.slice(2)
function getFlag(name) {
return args.includes(`--${name}`)
}
function getArg(name, defaultVal) {
const idx = args.indexOf(`--${name}`)
if (idx === -1 || idx + 1 >= args.length) return defaultVal
return args[idx + 1]
}
const PROFILE = getFlag('profile')
const MARKS = getFlag('marks')
const DURATION = parseInt(getArg('duration', '10'), 10)
const WARMUP_COUNT = parseInt(getArg('warmup', '50'), 10)
const PORT = parseInt(getArg('port', '3000'), 10)
const URL_PATH = getArg('url', '/')
const CONCURRENCY_ARG = getArg('concurrency', null)
// When --marks is used without explicit concurrency, default to c1 only
// since phase timing is only accurate at c1 (marks are global, not request-scoped)
const CONCURRENCIES = CONCURRENCY_ARG
? [parseInt(CONCURRENCY_ARG, 10)]
: MARKS
? [1]
: [1, 100]
const BENCH_DIR = path.resolve(__dirname)
const MINIMAL_SERVER = path.resolve(
__dirname,
'../next-minimal-server/bin/minimal-server.js'
)
const RESULTS_FILE = path.join(BENCH_DIR, 'last-run.json')
const ANALYZE_SCRIPT = path.resolve(
__dirname,
'../../scripts/analyze-profile.js'
)
function log(msg) {
process.stdout.write(`${msg}\n`)
}
function startServer() {
return new Promise((resolve, reject) => {
const env = {
...process.env,
PORT: String(PORT),
NODE_ENV: 'production',
}
if (PROFILE) {
env.NEXT_CPU_PROF = '1'
}
if (MARKS) {
env.NEXT_PERF_MARKS = '1'
}
const serverProcess = spawn('node', [MINIMAL_SERVER], {
cwd: BENCH_DIR,
env,
stdio: ['pipe', 'pipe', 'pipe'],
})
let started = false
let stderrBuf = ''
serverProcess.stdout.on('data', (data) => {
const str = data.toString()
if (!started && str.includes('next-cold-start')) {
started = true
resolve(serverProcess)
}
})
serverProcess.stderr.on('data', (data) => {
stderrBuf += data.toString()
})
// Also store stderr for later retrieval
serverProcess._stderrBuf = () => {
const buf = stderrBuf
stderrBuf = ''
return buf
}
serverProcess.on('error', reject)
serverProcess.on('exit', (code) => {
if (!started) {
reject(new Error(`Server exited with code ${code}`))
}
})
// Timeout if server doesn't start in 30s
setTimeout(() => {
if (!started) {
serverProcess.kill()
reject(new Error('Server start timeout'))
}
}, 30000)
})
}
function makeRequest() {
return new Promise((resolve, reject) => {
const start = performance.now()
const req = http.request(
{
hostname: '127.0.0.1',
port: PORT,
path: URL_PATH,
method: 'GET',
headers: { host: 'localhost' },
},
(res) => {
// Consume response body
res.on('data', () => {})
res.on('end', () => {
resolve({
duration: performance.now() - start,
statusCode: res.statusCode,
})
})
}
)
req.on('error', reject)
req.end()
})
}
async function warmup(count) {
log(`Warming up with ${count} requests...`)
for (let i = 0; i < count; i++) {
await makeRequest()
}
}
async function runBenchmark(concurrency, durationSec) {
const deadline = Date.now() + durationSec * 1000
let completed = 0
let errors = 0
const latencies = []
async function worker() {
while (Date.now() < deadline) {
try {
const result = await makeRequest()
latencies.push(result.duration)
completed++
} catch {
errors++
}
}
}
const workers = []
for (let i = 0; i < concurrency; i++) {
workers.push(worker())
}
await Promise.all(workers)
latencies.sort((a, b) => a - b)
const count = latencies.length
return {
concurrency,
duration: durationSec,
completed,
errors,
rps: completed / durationSec,
latency:
count > 0
? {
min: latencies[0],
p50: latencies[Math.floor(count * 0.5)],
p95: latencies[Math.floor(count * 0.95)],
p99: latencies[Math.floor(count * 0.99)],
max: latencies[count - 1],
avg: latencies.reduce((s, v) => s + v, 0) / count,
}
: null,
}
}
function formatNum(n, decimals = 2) {
return n.toFixed(decimals)
}
function printResults(results) {
log('')
log('='.repeat(80))
log(' SSR Benchmark Results')
log('='.repeat(80))
log('')
for (const r of results) {
log(` Concurrency: ${r.concurrency}`)
log(` Duration: ${r.duration}s`)
log(` Requests: ${r.completed} (${r.errors} errors)`)
log(` Throughput: ${formatNum(r.rps)} req/s`)
if (r.latency) {
log(
` Latency: avg=${formatNum(r.latency.avg)}ms p50=${formatNum(r.latency.p50)}ms p95=${formatNum(r.latency.p95)}ms p99=${formatNum(r.latency.p99)}ms min=${formatNum(r.latency.min)}ms max=${formatNum(r.latency.max)}ms`
)
}
log('')
}
}
function printComparison(current, previous) {
log('-'.repeat(80))
log(' Comparison with previous run')
log('-'.repeat(80))
log('')
for (const curr of current) {
const prev = previous.find((p) => p.concurrency === curr.concurrency)
if (!prev) continue
const delta = ((curr.rps - prev.rps) / prev.rps) * 100
const sign = delta >= 0 ? '+' : ''
const indicator = delta > 2 ? ' FASTER' : delta < -2 ? ' SLOWER' : ''
log(
` c${curr.concurrency}: ${formatNum(prev.rps)} -> ${formatNum(curr.rps)} req/s (${sign}${formatNum(delta)}%)${indicator}`
)
}
log('')
}
async function findCpuProfile() {
// CPU profiles are written to the cwd of the server process
const files = fs
.readdirSync(BENCH_DIR)
.filter((f) => f.endsWith('.cpuprofile'))
if (files.length === 0) return null
// Return the most recently modified one
files.sort((a, b) => {
const aStat = fs.statSync(path.join(BENCH_DIR, a))
const bStat = fs.statSync(path.join(BENCH_DIR, b))
return bStat.mtimeMs - aStat.mtimeMs
})
return path.join(BENCH_DIR, files[0])
}
async function analyzeProfile(profilePath) {
return new Promise((resolve) => {
const proc = spawn('node', [ANALYZE_SCRIPT, profilePath], {
stdio: 'inherit',
})
proc.on('exit', resolve)
})
}
async function main() {
log('Starting benchmark server...')
let server
try {
server = await startServer()
} catch (err) {
log(`Failed to start server: ${err.message}`)
process.exit(1)
}
log(`Server started on port ${PORT}`)
try {
await warmup(WARMUP_COUNT)
const results = []
for (const c of CONCURRENCIES) {
log(`\nBenchmarking with concurrency=${c} for ${DURATION}s...`)
const result = await runBenchmark(c, DURATION)
results.push(result)
}
printResults(results)
// Load previous results for comparison
if (fs.existsSync(RESULTS_FILE)) {
try {
const previous = JSON.parse(fs.readFileSync(RESULTS_FILE, 'utf-8'))
printComparison(results, previous)
} catch {
// Ignore corrupt previous results
}
}
// Save current results
fs.writeFileSync(RESULTS_FILE, JSON.stringify(results, null, 2))
log(`Results saved to ${RESULTS_FILE}`)
// Collect perf marks if enabled
if (MARKS) {
log('\nCollecting perf marks...')
// Give a moment for any pending marks
await new Promise((r) => setTimeout(r, 100))
server.kill('SIGUSR1')
// Wait for stats to be printed
await new Promise((r) => setTimeout(r, 500))
const stderr = server._stderrBuf()
if (stderr) {
log(stderr)
}
}
// Handle CPU profiling
if (PROFILE) {
log('\nSaving CPU profile...')
// Send SIGUSR2 to trigger saveCpuProfile() in the server
server.kill('SIGUSR2')
// Wait for the process to exit (it exits after writing the profile)
await new Promise((resolve) => {
server.on('exit', resolve)
setTimeout(resolve, 10000)
})
const profilePath = await findCpuProfile()
if (profilePath) {
log(`CPU profile saved: ${profilePath}`)
log('\nAnalyzing profile...\n')
await analyzeProfile(profilePath)
} else {
log('Warning: No .cpuprofile file found')
}
return
}
} finally {
// Kill server
if (server && !server.killed) {
server.kill('SIGTERM')
}
}
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
#!/usr/bin/env node #!/usr/bin/env node
process.env.NODE_ENV = 'production' process.env.NODE_ENV = 'production'
// CPU profiling: load early so it captures all module loading too
if (process.env.NEXT_CPU_PROF) {
require('next/dist/server/lib/cpu-profile')
}
require('../../../test/lib/react-channel-require-hook') require('../../../test/lib/react-channel-require-hook')
// Perf marks collection when NEXT_PERF_MARKS=1
const perfMarksEnabled = !!process.env.NEXT_PERF_MARKS
const markPhases = [
'ssr:request-start',
'ssr:render-start',
'ssr:react-render',
'ssr:stream-start',
'ssr:first-byte',
'ssr:request-end',
]
let markStats = {}
function resetMarkStats() {
markStats = {}
for (const name of markPhases) {
markStats[name] = []
}
// Also track durations between consecutive phases
for (let i = 0; i < markPhases.length - 1; i++) {
const key = `${markPhases[i]} -> ${markPhases[i + 1]}`
markStats[key] = []
}
markStats['ssr:total'] = []
}
if (perfMarksEnabled) {
resetMarkStats()
const { PerformanceObserver } = require('node:perf_hooks')
// Collect marks per request in a temporary buffer
let currentMarks = {}
const obs = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (markPhases.includes(entry.name)) {
currentMarks[entry.name] = entry.startTime
markStats[entry.name].push(entry.startTime)
// If this is the last mark, compute durations and reset
if (entry.name === 'ssr:request-end') {
for (let i = 0; i < markPhases.length - 1; i++) {
const from = markPhases[i]
const to = markPhases[i + 1]
if (currentMarks[from] != null && currentMarks[to] != null) {
const key = `${from} -> ${to}`
markStats[key].push(currentMarks[to] - currentMarks[from])
}
}
if (
currentMarks['ssr:request-start'] != null &&
currentMarks['ssr:request-end'] != null
) {
markStats['ssr:total'].push(
currentMarks['ssr:request-end'] -
currentMarks['ssr:request-start']
)
}
currentMarks = {}
performance.clearMarks()
}
}
}
})
obs.observe({ entryTypes: ['mark'] })
// On SIGUSR1, print aggregated stats and reset
process.on('SIGUSR1', () => {
const durationKeys = Object.keys(markStats).filter(
(k) => k.includes('->') || k === 'ssr:total'
)
if (durationKeys.length === 0) {
process.stderr.write('No perf marks collected yet.\n')
return
}
const lines = ['', '=== SSR Phase Timing ===']
for (const key of durationKeys) {
const values = markStats[key]
if (values.length === 0) continue
values.sort((a, b) => a - b)
const count = values.length
const min = values[0]
const max = values[count - 1]
const p50 = values[Math.floor(count * 0.5)]
const p95 = values[Math.floor(count * 0.95)]
const p99 = values[Math.floor(count * 0.99)]
const avg = values.reduce((s, v) => s + v, 0) / count
lines.push(
` ${key.padEnd(45)} n=${String(count).padStart(5)} avg=${avg.toFixed(2).padStart(8)}ms p50=${p50.toFixed(2).padStart(8)}ms p95=${p95.toFixed(2).padStart(8)}ms p99=${p99.toFixed(2).padStart(8)}ms min=${min.toFixed(2).padStart(8)}ms max=${max.toFixed(2).padStart(8)}ms`
)
}
lines.push('========================', '')
process.stderr.write(lines.join('\n'))
resetMarkStats()
})
}
console.time('next-cold-start') console.time('next-cold-start')
const NextServer = require('next/dist/server/next-server').default const NextServer = require('next/dist/server/next-server').default
const path = require('path') const path = require('path')
...@@ -26,13 +130,21 @@ const nextServer = new NextServer({ ...@@ -26,13 +130,21 @@ const nextServer = new NextServer({
const requestHandler = nextServer.getRequestHandler() const requestHandler = nextServer.getRequestHandler()
const port = parseInt(process.env.PORT || '3000', 10)
// SIGUSR2 triggers saveCpuProfile() and exits
if (process.env.NEXT_CPU_PROF) {
process.on('SIGUSR2', () => {
const { saveCpuProfile } = require('next/dist/server/lib/cpu-profile')
saveCpuProfile()
setTimeout(() => process.exit(0), 500)
})
}
require('http') require('http')
.createServer((req, res) => { .createServer((req, res) => {
console.time('next-request') return requestHandler(req, res)
return requestHandler(req, res).finally(() => {
console.timeEnd('next-request')
})
}) })
.listen(3000, () => { .listen(port, () => {
console.timeEnd('next-cold-start') console.timeEnd('next-cold-start')
}) })
...@@ -71,6 +71,7 @@ import { isRedirectError } from '../../client/components/redirect-error' ...@@ -71,6 +71,7 @@ import { isRedirectError } from '../../client/components/redirect-error'
import { getImplicitTags, type ImplicitTags } from '../lib/implicit-tags' import { getImplicitTags, type ImplicitTags } from '../lib/implicit-tags'
import { AppRenderSpan, NextNodeServerSpan } from '../lib/trace/constants' import { AppRenderSpan, NextNodeServerSpan } from '../lib/trace/constants'
import { getTracer, SpanStatusCode } from '../lib/trace/tracer' import { getTracer, SpanStatusCode } from '../lib/trace/tracer'
import { perfMark } from '../lib/perf-marks'
import { FlightRenderResult } from './flight-render-result' import { FlightRenderResult } from './flight-render-result'
import { import {
createReactServerErrorHandler, createReactServerErrorHandler,
...@@ -1868,6 +1869,8 @@ async function renderToHTMLOrFlightImpl( ...@@ -1868,6 +1869,8 @@ async function renderToHTMLOrFlightImpl(
interpolatedParams: Params, interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
) { ) {
perfMark('ssr:render-start')
const isNotFoundPath = pagePath === '/404' const isNotFoundPath = pagePath === '/404'
if (isNotFoundPath) { if (isNotFoundPath) {
res.statusCode = 404 res.statusCode = 404
...@@ -2951,6 +2954,7 @@ async function renderToStream( ...@@ -2951,6 +2954,7 @@ async function renderToStream(
require('react-dom/server') as typeof import('react-dom/server') require('react-dom/server') as typeof import('react-dom/server')
).renderToReadableStream ).renderToReadableStream
perfMark('ssr:react-render')
const htmlStream = await workUnitAsyncStorage.run( const htmlStream = await workUnitAsyncStorage.run(
requestStore, requestStore,
renderToReadableStream, renderToReadableStream,
......
...@@ -67,6 +67,7 @@ import RenderResult from './render-result' ...@@ -67,6 +67,7 @@ import RenderResult from './render-result'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import { perfMark } from './lib/perf-marks'
import { getServerUtils } from './server-utils' import { getServerUtils } from './server-utils'
import isError, { getProperError } from '../lib/is-error' import isError, { getProperError } from '../lib/is-error'
import { import {
...@@ -946,6 +947,8 @@ export default abstract class Server< ...@@ -946,6 +947,8 @@ export default abstract class Server<
parsedUrl?: NextUrlWithParsedQuery parsedUrl?: NextUrlWithParsedQuery
): Promise<void> { ): Promise<void> {
try { try {
perfMark('ssr:request-start')
// Wait for the matchers to be ready. // Wait for the matchers to be ready.
await this.matchers.waitTillReady() await this.matchers.waitTillReady()
......
// Gated performance marks for SSR profiling.
// Zero overhead when NEXT_PERF_MARKS is not set: the module-level boolean
// check means the function body is a no-op in production.
const enabled = !!process.env.NEXT_PERF_MARKS
/**
* Record a high-resolution performance mark.
* Only active when the NEXT_PERF_MARKS environment variable is set.
*
* Note: marks are global and not request-scoped. Phase timing is only
* accurate at concurrency=1. At higher concurrency, use throughput
* metrics instead.
*/
export function perfMark(name: string): void {
if (enabled) {
performance.mark(name)
}
}
...@@ -140,9 +140,7 @@ export const NextVanillaSpanAllowlist = new Set([ ...@@ -140,9 +140,7 @@ export const NextVanillaSpanAllowlist = new Set([
NextNodeServerSpan.createComponentTree, NextNodeServerSpan.createComponentTree,
NextNodeServerSpan.findPageComponents, NextNodeServerSpan.findPageComponents,
NextNodeServerSpan.getLayoutOrPageModule, NextNodeServerSpan.getLayoutOrPageModule,
// startResponse removed: it wraps a no-op `() => undefined` in pipe-readable.ts, NextNodeServerSpan.startResponse,
// so the span has no meaningful duration or children. Removing it avoids
// context.with(), startActiveSpan(), and rootSpanAttributesStore overhead per request.
NextNodeServerSpan.clientComponentLoading, NextNodeServerSpan.clientComponentLoading,
]) ])
......
...@@ -8,6 +8,7 @@ import { DetachedPromise } from '../lib/detached-promise' ...@@ -8,6 +8,7 @@ import { DetachedPromise } from '../lib/detached-promise'
import { getTracer } from './lib/trace/tracer' import { getTracer } from './lib/trace/tracer'
import { NextNodeServerSpan } from './lib/trace/constants' import { NextNodeServerSpan } from './lib/trace/constants'
import { getClientComponentLoaderMetrics } from './client-component-renderer-logger' import { getClientComponentLoaderMetrics } from './client-component-renderer-logger'
import { perfMark } from './lib/perf-marks'
// Cache env var at module level to avoid per-request process.env lookups // Cache env var at module level to avoid per-request process.env lookups
const NEXT_OTEL_PERFORMANCE_PREFIX = const NEXT_OTEL_PERFORMANCE_PREFIX =
...@@ -53,6 +54,7 @@ function createWriterFromResponse( ...@@ -53,6 +54,7 @@ function createWriterFromResponse(
// started writing chunks. // started writing chunks.
if (!started) { if (!started) {
started = true started = true
perfMark('ssr:first-byte')
if (NEXT_OTEL_PERFORMANCE_PREFIX) { if (NEXT_OTEL_PERFORMANCE_PREFIX) {
const metrics = getClientComponentLoaderMetrics() const metrics = getClientComponentLoaderMetrics()
...@@ -107,6 +109,8 @@ function createWriterFromResponse( ...@@ -107,6 +109,8 @@ function createWriterFromResponse(
res.destroy(err) res.destroy(err)
}, },
close: async () => { close: async () => {
perfMark('ssr:request-end')
// if a waitUntil promise was passed, wait for it to resolve before // if a waitUntil promise was passed, wait for it to resolve before
// ending the response. // ending the response.
if (waitUntilForEnd) { if (waitUntilForEnd) {
...@@ -137,6 +141,7 @@ export async function pipeToNodeResponse( ...@@ -137,6 +141,7 @@ export async function pipeToNodeResponse(
const writer = createWriterFromResponse(res, waitUntilForEnd) const writer = createWriterFromResponse(res, waitUntilForEnd)
perfMark('ssr:stream-start')
await readable.pipeTo(writer, { signal: controller.signal }) await readable.pipeTo(writer, { signal: controller.signal })
} catch (err: any) { } catch (err: any) {
// If this isn't related to an abort error, re-throw it. // If this isn't related to an abort error, re-throw it.
......
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