Unverified Commit 88383fcc authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix fetch logging after revalidation via server action (#82643)

When revalidating a tag or path with a server action, we do want to log
any fetches that are made during the subsequent rerendering, when [fetch
logging](https://nextjs.org/docs/app/api-reference/config/next-config-js/logging#fetching)
is enabled.

This got accidentally broken in #64746, where we wrote:

> [...] this ensures we don't keep tracking fetch metrics after the
request has ended as we only report on request end

That's incorrect though, because we report fetch metrics when the
_response_ is closed, and not the request:


https://github.com/vercel/next.js/blob/0bd7423844e218b19537880a7fa4314749fdf57d/packages/next/src/server/dev/next-dev-server.ts#L530-L546

This is crucial for server actions, when the request is likely already
closed while we're rerendering and streaming the response to the client.

fixes #80444
closes NAR-307
parent 5d4e85d2
...@@ -1454,7 +1454,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -1454,7 +1454,6 @@ async function renderToHTMLOrFlightImpl(
renderOpts: RenderOpts, renderOpts: RenderOpts,
workStore: WorkStore, workStore: WorkStore,
parsedRequestHeaders: ParsedRequestHeaders, parsedRequestHeaders: ParsedRequestHeaders,
requestEndedState: { ended?: boolean },
postponedState: PostponedState | null, postponedState: PostponedState | null,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined, serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext, sharedContext: AppSharedContext,
...@@ -1555,9 +1554,13 @@ async function renderToHTMLOrFlightImpl( ...@@ -1555,9 +1554,13 @@ async function renderToHTMLOrFlightImpl(
process.env.NEXT_RUNTIME !== 'edge' && process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req) isNodeNextRequest(req)
) { ) {
req.originalRequest.on('end', () => { res.onClose(() => {
requestEndedState.ended = true // We stop tracking fetch metrics when the response closes, since we
// report them at that time.
workStore.shouldTrackFetchMetrics = false
})
req.originalRequest.on('end', () => {
if ('performance' in globalThis) { if ('performance' in globalThis) {
const metrics = getClientComponentLoaderMetrics({ reset: true }) const metrics = getClientComponentLoaderMetrics({ reset: true })
if (metrics) { if (metrics) {
...@@ -1966,7 +1969,6 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -1966,7 +1969,6 @@ export const renderToHTMLOrFlight: AppPageRender = (
const { isPrefetchRequest, previouslyRevalidatedTags } = parsedRequestHeaders const { isPrefetchRequest, previouslyRevalidatedTags } = parsedRequestHeaders
const requestEndedState = { ended: false }
let postponedState: PostponedState | null = null let postponedState: PostponedState | null = null
// If provided, the postpone state should be parsed so it can be provided to // If provided, the postpone state should be parsed so it can be provided to
...@@ -1996,7 +1998,6 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -1996,7 +1998,6 @@ export const renderToHTMLOrFlight: AppPageRender = (
const workStore = createWorkStore({ const workStore = createWorkStore({
page: renderOpts.routeModule.definition.page, page: renderOpts.routeModule.definition.page,
renderOpts, renderOpts,
requestEndedState,
// @TODO move to workUnitStore of type Request // @TODO move to workUnitStore of type Request
isPrefetchRequest, isPrefetchRequest,
buildId: sharedContext.buildId, buildId: sharedContext.buildId,
...@@ -2016,7 +2017,6 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -2016,7 +2017,6 @@ export const renderToHTMLOrFlight: AppPageRender = (
renderOpts, renderOpts,
workStore, workStore,
parsedRequestHeaders, parsedRequestHeaders,
requestEndedState,
postponedState, postponedState,
serverComponentsHmrCache, serverComponentsHmrCache,
sharedContext, sharedContext,
......
...@@ -85,13 +85,12 @@ export interface WorkStore { ...@@ -85,13 +85,12 @@ export interface WorkStore {
readonly refreshTagsByCacheKind: Map<string, LazyResult<void>> readonly refreshTagsByCacheKind: Map<string, LazyResult<void>>
fetchMetrics?: FetchMetrics fetchMetrics?: FetchMetrics
shouldTrackFetchMetrics: boolean
isDraftMode?: boolean isDraftMode?: boolean
isUnstableNoStore?: boolean isUnstableNoStore?: boolean
isPrefetchRequest?: boolean isPrefetchRequest?: boolean
requestEndedState?: { ended?: boolean }
buildId: string buildId: string
readonly reactLoadableManifest?: DeepReadonly< readonly reactLoadableManifest?: DeepReadonly<
......
...@@ -19,7 +19,6 @@ export type WorkStoreContext = { ...@@ -19,7 +19,6 @@ export type WorkStoreContext = {
*/ */
page: string page: string
requestEndedState?: { ended?: boolean }
isPrefetchRequest?: boolean isPrefetchRequest?: boolean
renderOpts: { renderOpts: {
cacheLifeProfiles?: { [profile: string]: CacheLife } cacheLifeProfiles?: { [profile: string]: CacheLife }
...@@ -77,7 +76,6 @@ export type WorkStoreContext = { ...@@ -77,7 +76,6 @@ export type WorkStoreContext = {
export function createWorkStore({ export function createWorkStore({
page, page,
renderOpts, renderOpts,
requestEndedState,
isPrefetchRequest, isPrefetchRequest,
buildId, buildId,
previouslyRevalidatedTags, previouslyRevalidatedTags,
...@@ -105,6 +103,17 @@ export function createWorkStore({ ...@@ -105,6 +103,17 @@ export function createWorkStore({
!renderOpts.isDraftMode && !renderOpts.isDraftMode &&
!renderOpts.isPossibleServerAction !renderOpts.isPossibleServerAction
const isDevelopment = renderOpts.dev ?? false
const shouldTrackFetchMetrics =
isDevelopment ||
// The only times we want to track fetch metrics outside of development is
// when we are performing a static generation and we either are in debug
// mode, or tracking fetch metrics was specifically opted into.
(isStaticGeneration &&
(!!process.env.NEXT_DEBUG_BUILD ||
process.env.NEXT_SSG_FETCH_METRICS === '1'))
const store: WorkStore = { const store: WorkStore = {
isStaticGeneration, isStaticGeneration,
page, page,
...@@ -122,7 +131,6 @@ export function createWorkStore({ ...@@ -122,7 +131,6 @@ export function createWorkStore({
isDraftMode: renderOpts.isDraftMode, isDraftMode: renderOpts.isDraftMode,
requestEndedState,
isPrefetchRequest, isPrefetchRequest,
buildId, buildId,
reactLoadableManifest: renderOpts?.reactLoadableManifest || {}, reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
...@@ -130,10 +138,11 @@ export function createWorkStore({ ...@@ -130,10 +138,11 @@ export function createWorkStore({
afterContext: createAfterContext(renderOpts), afterContext: createAfterContext(renderOpts),
cacheComponentsEnabled: renderOpts.experimental.cacheComponents, cacheComponentsEnabled: renderOpts.experimental.cacheComponents,
dev: renderOpts.dev ?? false, dev: isDevelopment,
previouslyRevalidatedTags, previouslyRevalidatedTags,
refreshTagsByCacheKind: createRefreshTagsByCacheKind(), refreshTagsByCacheKind: createRefreshTagsByCacheKind(),
runInCleanSnapshot: createSnapshot(), runInCleanSnapshot: createSnapshot(),
shouldTrackFetchMetrics,
} }
// TODO: remove this when we resolve accessing the store outside the execution context // TODO: remove this when we resolve accessing the store outside the execution context
......
...@@ -121,22 +121,7 @@ function trackFetchMetric( ...@@ -121,22 +121,7 @@ function trackFetchMetric(
workStore: WorkStore, workStore: WorkStore,
ctx: Omit<FetchMetric, 'end' | 'idx'> ctx: Omit<FetchMetric, 'end' | 'idx'>
) { ) {
// If the static generation store is not available, we can't track the fetch if (!workStore.shouldTrackFetchMetrics) {
if (!workStore) return
if (workStore.requestEndedState?.ended) return
const isDebugBuild =
(!!process.env.NEXT_DEBUG_BUILD ||
process.env.NEXT_SSG_FETCH_METRICS === '1') &&
workStore.isStaticGeneration
const isDevelopment = process.env.NODE_ENV === 'development'
if (
// The only time we want to track fetch metrics outside of development is when
// we are performing a static generation & we are in debug mode.
!isDebugBuild &&
!isDevelopment
) {
return return
} }
......
...@@ -297,7 +297,6 @@ export async function adapter( ...@@ -297,7 +297,6 @@ export async function adapter(
onClose: closeController.onClose.bind(closeController), onClose: closeController.onClose.bind(closeController),
onAfterTaskError: undefined, onAfterTaskError: undefined,
}, },
requestEndedState: { ended: false },
isPrefetchRequest: isPrefetchRequest:
request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1', request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',
buildId: buildId ?? '', buildId: buildId ?? '',
......
import { revalidateTag } from 'next/cache'
export const fetchCache = 'default-cache' export const fetchCache = 'default-cache'
async function AnotherRsc() { async function AnotherRsc() {
...@@ -55,7 +57,8 @@ async function FirstRsc() { ...@@ -55,7 +57,8 @@ async function FirstRsc() {
).then((res) => res.text()) ).then((res) => res.text())
const dataAutoCache = await fetch( const dataAutoCache = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?auto-cache' 'https://next-data-api-endpoint.vercel.app/api/random?auto-cache',
{ next: { tags: ['test-tag'] } }
).then((res) => res.text()) ).then((res) => res.text())
return ( return (
...@@ -72,12 +75,26 @@ async function FirstRsc() { ...@@ -72,12 +75,26 @@ async function FirstRsc() {
) )
} }
function RevalidateForm() {
return (
<form
action={async () => {
'use server'
revalidateTag('test-tag')
}}
>
<button id="revalidate-button">Revalidate</button>
</form>
)
}
export default async function Page() { export default async function Page() {
return ( return (
<> <>
<h1>Default Cache</h1> <h1>Default Cache</h1>
<FirstRsc /> <FirstRsc />
<AnotherRsc /> <AnotherRsc />
<RevalidateForm />
</> </>
) )
} }
...@@ -267,6 +267,29 @@ describe('app-dir - logging', () => { ...@@ -267,6 +267,29 @@ describe('app-dir - logging', () => {
}) })
}) })
it('should log requests for after revalidation via server action', async () => {
let outputIndex = next.cliOutput.length
const browser = await next.browser('/default-cache')
const expectedUrl = withFullUrlFetches
? 'https://next-data-api-endpoint.vercel.app/api/random'
: 'https://next-data-api-en../api/random'
await retry(() => {
const logs = stripAnsi(next.cliOutput.slice(outputIndex))
expect(logs).toIncludeRepeated(` │ GET ${expectedUrl}`, 7)
})
outputIndex = next.cliOutput.length
await browser.elementById('revalidate-button').click()
await retry(() => {
const logs = stripAnsi(next.cliOutput.slice(outputIndex))
expect(logs).toIncludeRepeated(` │ GET ${expectedUrl}`, 7)
})
})
describe('when logging.fetches.hmrRefreshes is true', () => { describe('when logging.fetches.hmrRefreshes is true', () => {
beforeAll(async () => { beforeAll(async () => {
await next.patchFile('next.config.js', (content) => await next.patchFile('next.config.js', (content) =>
......
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