Unverified Commit bb129dd3 authored by Jan Kassens's avatar Jan Kassens Committed by GitHub

Use render lifecycle callback for fetch metrics cleanup (#100323)

# Human

This is part of factoring out `request` and `response` access from the
rendering path as we don't have real values for them when e.g.
pre-rendering at build time.

# AI below

## Summary

Use the existing `renderOpts.onClose` lifecycle callback to stop
tracking fetch metrics when the response closes. This removes a direct
response dependency and the request type check from App Router render
preparation while preserving production runtime cleanup.

Retain the Edge guard and exclude build-time prerenders from cleanup
registration. Their lifecycle closes before `after()` callbacks run, and
fetch metrics must remain enabled until export collects them. For Node
runtime requests, both the old and new callbacks subscribe to the same
response `close` event.

Add end-to-end coverage for build-time metrics and runtime cleanup. Dev
Cache Components can render again while preparing background validation
after the response closes, so those metric logs can arrive in either
order; this also occurs with canary's implementation. Only that dev case
permits the extra render record. Production assertions remain strict for
every record.

## Verification

- Fetch logging tests: 53 passed with Turbopack and 53 with Webpack in
dev.
- Lifecycle tests with the failing CI cache-components dev environment:
4 passed.
- Production lifecycle comparison: all 6 checks passed with both
canary's implementation and this PR. Temporarily restoring the dev-only
cleanup guard correctly failed the production runtime-prerender check.

<!-- NEXT_JS_LLM -->
parent dd904bb7
...@@ -205,7 +205,7 @@ import { ...@@ -205,7 +205,7 @@ import {
ClientComponentLoadTracker, ClientComponentLoadTracker,
wrapClientComponentLoader, wrapClientComponentLoader,
} from '../client-component-renderer-logger' } from '../client-component-renderer-logger'
import { isNodeNextRequest, isNodeNextResponse } from '../base-http/helpers' import { isNodeNextResponse } from '../base-http/helpers'
import { waitForResponseToFinish } from './wait-for-response' import { waitForResponseToFinish } from './wait-for-response'
import { import {
beginDevValidation, beginDevValidation,
...@@ -2638,12 +2638,12 @@ async function prepareAppPageRender( ...@@ -2638,12 +2638,12 @@ async function prepareAppPageRender(
} = renderOpts } = renderOpts
if ( if (
// The type check here ensures that `req` is correctly typed, and the // Build-time prerenders collect fetch metrics after running after() callbacks,
// environment variable check provides dead code elimination. // so they must keep tracking when their render lifecycle closes.
process.env.NEXT_RUNTIME !== 'edge' && !renderOpts.isBuildTimePrerendering &&
isNodeNextRequest(req) process.env.NEXT_RUNTIME !== 'edge'
) { ) {
res.onClose(() => { renderOpts.onClose(() => {
// We stop tracking fetch metrics when the response closes, since we // We stop tracking fetch metrics when the response closes, since we
// report them at that time. // report them at that time.
workStore.shouldTrackFetchMetrics = false workStore.shouldTrackFetchMetrics = false
......
import { MetricsPage } from '../../metrics'
export function generateStaticParams() {
return [{ slug: 'build' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return <MetricsPage id={slug} />
}
import { connection } from 'next/server'
import { MetricsPage } from '../../metrics'
export default async function Page() {
await connection()
return <MetricsPage id="dynamic" />
}
import type { ReactNode } from 'react'
import { Suspense } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<Suspense fallback="Loading...">{children}</Suspense>
</body>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
import { gate, retry } from 'next-test-utils'
// These assertions inspect local CLI output and build diagnostics.
// @force-gate !deploy
describe.each(['0', '1'])(
'fetch metrics (NEXT_SSG_FETCH_METRICS=%s)',
(enabled) => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
env: {
NEXT_SSG_FETCH_METRICS: enabled,
NEXT_DEBUG_BUILD: '',
},
})
function expectMetrics(
output: string,
id: string,
trackingDuringRender: boolean,
trackingAfterClose: boolean,
allowValidationRender = false
) {
const records = output
.split('\n')
.filter((line) => line.includes('FETCH_METRICS '))
.map((line) => JSON.parse(line.split('FETCH_METRICS ')[1]))
.filter((entry) => entry.id === id)
// Dev Cache Components prepares background validation with another render
// after response close. Its after() log can race with the original render.
// Keep production assertions strict for every render.
const record = allowValidationRender
? records.find(
(entry) => entry.trackingDuringRender === trackingDuringRender
)
: records[0]
expect(record).toBeDefined()
expect(record.trackingDuringRender).toBe(trackingDuringRender)
if (trackingDuringRender) {
expect(record.urlsBefore).toContain(`data:text/plain,render-${id}`)
} else {
expect(record.urlsBefore).toEqual([])
}
for (const entry of records) {
if (!allowValidationRender) {
expect(entry.trackingDuringRender).toBe(trackingDuringRender)
}
expect(entry.trackingAfterClose).toBe(trackingAfterClose)
if (trackingAfterClose) {
expect(entry.urlsAfter).toContain(`data:text/plain,after-${id}`)
} else {
expect(entry.urlsAfter).toEqual(entry.urlsBefore)
}
}
}
// @force-gate !dev
it('tracks build-time fetches through after() when metrics are enabled', async () => {
expectMetrics(next.cliOutput, 'build', enabled === '1', enabled === '1')
if (enabled === '1') {
const metrics = await next.readJSON(
'.next/diagnostics/fetch-metrics.json'
)
expect(metrics['/build']).toEqual(
expect.arrayContaining([
expect.objectContaining({ url: 'data:text/plain,render-build' }),
expect.objectContaining({ url: 'data:text/plain,after-build' }),
])
)
}
})
it('stops tracking runtime prerender fetches when the response closes', async () => {
// Cache Components resumes unknown params as a dynamic render, which does
// not collect production fetch metrics.
const cacheComponents = await gate((c) => c.cacheComponents)
const tracksPrerenderMetrics = enabled === '1' && !cacheComponents
const outputIndex = next.cliOutput.length
const response = await next.fetch('/runtime')
expect(response.status).toBe(200)
expect(await response.text()).toContain('runtime')
await retry(() => {
expectMetrics(
next.cliOutput.slice(outputIndex),
'runtime',
isNextDev || tracksPrerenderMetrics,
false,
isNextDev && cacheComponents
)
})
})
it('tracks dynamic renders only in development and stops on close', async () => {
const outputIndex = next.cliOutput.length
const response = await next.fetch('/dynamic')
expect(response.status).toBe(200)
expect(await response.text()).toContain('dynamic')
await retry(() => {
expectMetrics(
next.cliOutput.slice(outputIndex),
'dynamic',
isNextDev,
false
)
})
})
}
)
import { after } from 'next/server'
import { workAsyncStorage } from 'next/dist/server/app-render/work-async-storage.external'
export async function MetricsPage({ id }: { id: string }) {
const store = workAsyncStorage.getStore()!
const trackingDuringRender = store.shouldTrackFetchMetrics
await fetch(`data:text/plain,render-${id}`, { cache: 'force-cache' })
after(async () => {
const trackingAfterClose = store.shouldTrackFetchMetrics
const urlsBefore = (store.fetchMetrics ?? []).map((metric) => metric.url)
await fetch(`data:text/plain,after-${id}`, { cache: 'force-cache' })
const urlsAfter = (store.fetchMetrics ?? []).map((metric) => metric.url)
console.log(
'FETCH_METRICS ' +
JSON.stringify({
id,
trackingDuringRender,
trackingAfterClose,
urlsBefore,
urlsAfter,
})
)
})
return <p>{id}</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
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