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(
renderOpts: RenderOpts,
workStore: WorkStore,
parsedRequestHeaders: ParsedRequestHeaders,
requestEndedState: { ended?: boolean },
postponedState: PostponedState | null,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext,
......@@ -1555,9 +1554,13 @@ async function renderToHTMLOrFlightImpl(
process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req)
) {
req.originalRequest.on('end', () => {
requestEndedState.ended = true
res.onClose(() => {
// 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) {
const metrics = getClientComponentLoaderMetrics({ reset: true })
if (metrics) {
......@@ -1966,7 +1969,6 @@ export const renderToHTMLOrFlight: AppPageRender = (
const { isPrefetchRequest, previouslyRevalidatedTags } = parsedRequestHeaders
const requestEndedState = { ended: false }
let postponedState: PostponedState | null = null
// If provided, the postpone state should be parsed so it can be provided to
......@@ -1996,7 +1998,6 @@ export const renderToHTMLOrFlight: AppPageRender = (
const workStore = createWorkStore({
page: renderOpts.routeModule.definition.page,
renderOpts,
requestEndedState,
// @TODO move to workUnitStore of type Request
isPrefetchRequest,
buildId: sharedContext.buildId,
......@@ -2016,7 +2017,6 @@ export const renderToHTMLOrFlight: AppPageRender = (
renderOpts,
workStore,
parsedRequestHeaders,
requestEndedState,
postponedState,
serverComponentsHmrCache,
sharedContext,
......
......@@ -85,13 +85,12 @@ export interface WorkStore {
readonly refreshTagsByCacheKind: Map<string, LazyResult<void>>
fetchMetrics?: FetchMetrics
shouldTrackFetchMetrics: boolean
isDraftMode?: boolean
isUnstableNoStore?: boolean
isPrefetchRequest?: boolean
requestEndedState?: { ended?: boolean }
buildId: string
readonly reactLoadableManifest?: DeepReadonly<
......
......@@ -19,7 +19,6 @@ export type WorkStoreContext = {
*/
page: string
requestEndedState?: { ended?: boolean }
isPrefetchRequest?: boolean
renderOpts: {
cacheLifeProfiles?: { [profile: string]: CacheLife }
......@@ -77,7 +76,6 @@ export type WorkStoreContext = {
export function createWorkStore({
page,
renderOpts,
requestEndedState,
isPrefetchRequest,
buildId,
previouslyRevalidatedTags,
......@@ -105,6 +103,17 @@ export function createWorkStore({
!renderOpts.isDraftMode &&
!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 = {
isStaticGeneration,
page,
......@@ -122,7 +131,6 @@ export function createWorkStore({
isDraftMode: renderOpts.isDraftMode,
requestEndedState,
isPrefetchRequest,
buildId,
reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
......@@ -130,10 +138,11 @@ export function createWorkStore({
afterContext: createAfterContext(renderOpts),
cacheComponentsEnabled: renderOpts.experimental.cacheComponents,
dev: renderOpts.dev ?? false,
dev: isDevelopment,
previouslyRevalidatedTags,
refreshTagsByCacheKind: createRefreshTagsByCacheKind(),
runInCleanSnapshot: createSnapshot(),
shouldTrackFetchMetrics,
}
// TODO: remove this when we resolve accessing the store outside the execution context
......
......@@ -121,22 +121,7 @@ function trackFetchMetric(
workStore: WorkStore,
ctx: Omit<FetchMetric, 'end' | 'idx'>
) {
// If the static generation store is not available, we can't track the fetch
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
) {
if (!workStore.shouldTrackFetchMetrics) {
return
}
......
......@@ -297,7 +297,6 @@ export async function adapter(
onClose: closeController.onClose.bind(closeController),
onAfterTaskError: undefined,
},
requestEndedState: { ended: false },
isPrefetchRequest:
request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',
buildId: buildId ?? '',
......
import { revalidateTag } from 'next/cache'
export const fetchCache = 'default-cache'
async function AnotherRsc() {
......@@ -55,7 +57,8 @@ async function FirstRsc() {
).then((res) => res.text())
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())
return (
......@@ -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() {
return (
<>
<h1>Default Cache</h1>
<FirstRsc />
<AnotherRsc />
<RevalidateForm />
</>
)
}
......@@ -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', () => {
beforeAll(async () => {
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