Unverified Commit c1e485ce authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Instant] Validate blocking head (#89539)

Previously, instant validation would always use the dynamic stage for
the head, which means that we wouldn't catch errors related to a
blocking `generateViewport`. This is fixed here. We treat head as a
separate segment and use the appropriate stage (Static or Runtime)
depending on prefetch config.
 
Closes NAR-780
parent 55ffc562
...@@ -1069,5 +1069,6 @@ ...@@ -1069,5 +1069,6 @@
"1068": "Expected workStore to be initialized", "1068": "Expected workStore to be initialized",
"1069": "Invariant: cache entry \"%s\" not found in dir \"%s\"", "1069": "Invariant: cache entry \"%s\" not found in dir \"%s\"",
"1070": "image of size %s could not be tracked by lru cache", "1070": "image of size %s could not be tracked by lru cache",
"1071": "toNodeDebugChannel cannot be used in edge/web runtime, this is a bug in the Next.js codebase" "1071": "toNodeDebugChannel cannot be used in edge/web runtime, this is a bug in the Next.js codebase",
"1072": "Missing segment data: <head>"
} }
...@@ -976,6 +976,9 @@ export function trackDynamicHoleInRuntimeShell( ...@@ -976,6 +976,9 @@ export function trackDynamicHoleInRuntimeShell(
dynamicValidation.dynamicMetadata = error dynamicValidation.dynamicMetadata = error
return return
} else if (hasViewportRegex.test(componentStack)) { } else if (hasViewportRegex.test(componentStack)) {
// TODO(instant-validation): If the page only has holes caused by runtime data,
// we won't find out if there's a suspense-above-body and error for dynamic viewport
// even if there is in fact a suspense-above-body
const message = `Route "${workStore.route}": Uncached data or \`connection()\` was accessed inside \`generateViewport\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport` const message = `Route "${workStore.route}": Uncached data or \`connection()\` was accessed inside \`generateViewport\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`
const error = createErrorWithComponentOrOwnerStack( const error = createErrorWithComponentOrOwnerStack(
message, message,
......
...@@ -278,7 +278,6 @@ function traverseRootSeedDataSegments( ...@@ -278,7 +278,6 @@ function traverseRootSeedDataSegments(
seedData: CacheNodeSeedData seedData: CacheNodeSeedData
) => void ) => void
) { ) {
// TODO: handle head as well
const { flightRouterState, seedData } = const { flightRouterState, seedData } =
getRootDataFromPayload(initialRSCPayload) getRootDataFromPayload(initialRSCPayload)
...@@ -437,6 +436,8 @@ export async function collectStagedSegmentData( ...@@ -437,6 +436,8 @@ export async function collectStagedSegmentData(
// We have to preserve the stage information for each of them, // We have to preserve the stage information for each of them,
// so that we can later render each segment in any stage we need. // so that we can later render each segment in any stage we need.
const { head } = getRootDataFromPayload(payload)
const segments = new Map<SegmentPath, SegmentData>() const segments = new Map<SegmentPath, SegmentData>()
traverseRootSeedDataSegments(payload, (segmentPath, seedData) => { traverseRootSeedDataSegments(payload, (segmentPath, seedData) => {
segments.set(segmentPath, createSegmentData(seedData)) segments.set(segmentPath, createSegmentData(seedData))
...@@ -451,75 +452,73 @@ export async function collectStagedSegmentData( ...@@ -451,75 +452,73 @@ export async function collectStagedSegmentData(
[RenderStage.Runtime]: -1, [RenderStage.Runtime]: -1,
} }
const renderIntoCacheItem = async (
data: HeadData | SegmentData,
cacheEntry: SegmentCacheItem
): Promise<void> => {
const segmentDebugChannel = cacheEntry.debugChunks
? createDebugChannel()
: undefined
const itemStream = renderToReadableStream(
data,
clientReferenceManifest.clientModules,
{
filterStackFrame,
debugChannel: segmentDebugChannel?.serverSide,
environmentName,
startTime,
onError(error: unknown) {
const digest = getDigestForWellKnownError(error)
if (digest) {
return digest
}
// We don't need to log the errors because we would have already done that
// when generating the original Flight stream for the whole page.
if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
const workStore = workAsyncStorage.getStore()
printDebugThrownValueForProspectiveRender(
error,
workStore?.route ?? 'unknown route',
Phase.InstantValidation
)
}
},
}
)
await Promise.all([
// accumulate Flight chunks
(async () => {
for await (const chunk of itemStream.values()) {
writeChunk(cacheEntry.chunks, controller.currentStage, chunk)
}
})(),
// accumulate Debug chunks
segmentDebugChannel &&
(async () => {
for await (const chunk of segmentDebugChannel.clientSide.readable.values()) {
cacheEntry.debugChunks!.push(chunk)
}
})(),
])
}
await runInSequentialTasks( await runInSequentialTasks(
() => { () => {
for (const [segmentPath, segmentData] of segments) { {
const segmentCacheItem: SegmentCacheItem = { const headCacheItem = createSegmentCacheItem(!!fullPageDebugChunks)
chunks: { cache.head = headCacheItem
[RenderStage.Static]: [], pendingTasks.push(renderIntoCacheItem(head, headCacheItem))
[RenderStage.Runtime]: [], }
[RenderStage.Dynamic]: [],
},
debugChunks: fullPageDebugChunks ? [] : null,
}
cache.set(segmentPath, segmentCacheItem)
const segmentTask = async () => {
const segmentDebugChannel = fullPageDebugChunks
? createDebugChannel()
: undefined
const segmentStream = renderToReadableStream(
segmentData,
clientReferenceManifest.clientModules,
{
filterStackFrame,
debugChannel: segmentDebugChannel?.serverSide,
environmentName,
startTime,
onError(error: unknown) {
const digest = getDigestForWellKnownError(error)
if (digest) {
return digest
}
// We don't need to log the errors because we would have already done that
// when generating the original Flight stream for the whole page.
if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
const workStore = workAsyncStorage.getStore()
printDebugThrownValueForProspectiveRender(
error,
workStore?.route ?? 'unknown route',
Phase.InstantValidation
)
}
},
}
)
await Promise.all([ for (const [segmentPath, segmentData] of segments) {
// accumulate Flight chunks const segmentCacheItem = createSegmentCacheItem(!!fullPageDebugChunks)
(async () => { cache.segments.set(segmentPath, segmentCacheItem)
for await (const chunk of segmentStream.values()) { pendingTasks.push(renderIntoCacheItem(segmentData, segmentCacheItem))
writeChunk(
segmentCacheItem.chunks,
controller.currentStage,
chunk
)
}
})(),
// accumulate Debug chunks
segmentDebugChannel &&
(async () => {
for await (const chunk of segmentDebugChannel.clientSide.readable.values()) {
segmentCacheItem.debugChunks!.push(chunk)
}
})(),
])
}
pendingTasks.push(segmentTask())
} }
}, },
() => { () => {
...@@ -803,7 +802,7 @@ export async function createCombinedPayload( ...@@ -803,7 +802,7 @@ export async function createCombinedPayload(
/** mutable out-param - Which stages are actually used in the resulting payload */ /** mutable out-param - Which stages are actually used in the resulting payload */
usedSegmentKinds: Set<SegmentStage> usedSegmentKinds: Set<SegmentStage>
): Promise<InitialRSCPayload> { ): Promise<InitialRSCPayload> {
const { head, flightRouterState } = getRootDataFromPayload(initialRSCPayload) const { flightRouterState } = getRootDataFromPayload(initialRSCPayload)
const combinedSeedData = await createValidationSeedData( const combinedSeedData = await createValidationSeedData(
cache, cache,
validationRouteTree, validationRouteTree,
...@@ -815,6 +814,23 @@ export async function createCombinedPayload( ...@@ -815,6 +814,23 @@ export async function createCombinedPayload(
useRuntimeStageForPartialSegments, useRuntimeStageForPartialSegments,
usedSegmentKinds usedSegmentKinds
) )
// If we did a runtime prefetch for this navigation, then we'd get a runtime-stage head.
// Otherwise, we'd only have the `/_head` segment prefetch which is static.
// TODO(instant-validation): not sure about this as a way of detecting runtime prefetches
// (in the presence of `useRuntimeStageForPartialSegments`), but maybe it's actually correct?
const headStage = usedSegmentKinds.has(RenderStage.Runtime)
? RenderStage.Runtime
: RenderStage.Static
debug?.(` <head> - ${RenderStage[headStage]}`)
const head = await createValidationHead(
cache,
releaseSignal,
clientReferenceManifest,
stageEndTimes,
headStage
)
const combinedRSCPayload: InitialRSCPayload = { const combinedRSCPayload: InitialRSCPayload = {
...initialRSCPayload, ...initialRSCPayload,
f: [ f: [
...@@ -822,7 +838,7 @@ export async function createCombinedPayload( ...@@ -822,7 +838,7 @@ export async function createCombinedPayload(
[ [
flightRouterState satisfies FlightRouterState, flightRouterState satisfies FlightRouterState,
combinedSeedData satisfies CacheNodeSeedData, combinedSeedData satisfies CacheNodeSeedData,
head satisfies HeadData, // TODO: handle head better head satisfies HeadData,
], ],
], ],
} }
...@@ -926,7 +942,7 @@ function createValidationSeedData( ...@@ -926,7 +942,7 @@ function createValidationSeedData(
} }
debug?.(` ${path || '/'} - ${RenderStage[stage]}`) debug?.(` ${path || '/'} - ${RenderStage[stage]}`)
const segmentCacheItem = cache.get(path) const segmentCacheItem = cache.segments.get(path)
if (!segmentCacheItem) { if (!segmentCacheItem) {
throw new InvariantError(`Missing segment data: ${path}`) throw new InvariantError(`Missing segment data: ${path}`)
} }
...@@ -997,6 +1013,27 @@ function createValidationSeedData( ...@@ -997,6 +1013,27 @@ function createValidationSeedData(
) )
} }
async function createValidationHead(
cache: SegmentCache,
releaseSignal: AbortSignal,
clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes,
stage: RenderStage.Static | RenderStage.Runtime
): Promise<HeadData> {
const segmentCacheItem = cache.head
if (!segmentCacheItem) {
throw new InvariantError(`Missing segment data: <head>`)
}
return await deserializeFromChunks<HeadData>(
segmentCacheItem.chunks[stage],
segmentCacheItem.chunks[RenderStage.Dynamic],
segmentCacheItem.debugChunks,
releaseSignal,
clientReferenceManifest,
{ startTime: undefined, endTime: stageEndTimes[stage] }
)
}
type Timings = { type Timings = {
startTime?: number startTime?: number
endTime?: number endTime?: number
...@@ -1086,10 +1123,24 @@ function getCacheNodeSeedDataFromSegment( ...@@ -1086,10 +1123,24 @@ function getCacheNodeSeedDataFromSegment(
} }
function createSegmentCache(): SegmentCache { function createSegmentCache(): SegmentCache {
return new Map() return { head: null, segments: new Map() }
} }
export type SegmentCache = Map<SegmentPath, SegmentCacheItem> function createSegmentCacheItem(withDebugChunks: boolean): SegmentCacheItem {
return {
chunks: {
[RenderStage.Static]: [],
[RenderStage.Runtime]: [],
[RenderStage.Dynamic]: [],
},
debugChunks: withDebugChunks ? [] : null,
}
}
export type SegmentCache = {
head: SegmentCacheItem | null
segments: Map<SegmentPath, SegmentCacheItem>
}
type SegmentCacheItem = { type SegmentCacheItem = {
chunks: StageChunks chunks: StageChunks
......
import { ReactNode, Suspense } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function Layout({ children }: { children: ReactNode }) {
return (
<div>
<p>
This layout should have static instant UI. However, despite having a
suspense around children, it's not instant because of a dynamic
generateViewport in a child (which the Suspense doesn't catch.)
</p>
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
</div>
)
}
import type { Viewport } from 'next'
import { connection } from 'next/server'
export const unstable_instant = false
export async function generateViewport(): Promise<Viewport> {
await connection()
return {
themeColor: 'aliceblue',
}
}
export default async function Page() {
await connection()
return (
<main>
<p>
This page has a dynamic generateViewport. That's not prefetchable, but
it has <code>instant = false</code>, so blocking is valid. However, this
violates a static assertion in a parent layout, so ultimately it still
fails validation.
</p>
<p>
We also access runtime data in the page itself, because a static page
with a dynamic vieport is not allowed.
</p>
</main>
)
}
import type { Viewport } from 'next'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
// Note that we're inside a root layout with suspense, so we skip the static shell
export async function generateViewport(): Promise<Viewport> {
await connection()
return {
themeColor: 'aliceblue',
}
}
export default async function Page() {
await cookies()
return (
<main>
<p>This page has a dynamic generateViewport</p>
<p>
We also access dynamic data in the page itself, because a static page
with a dynamic viewport is not allowed.
</p>
<Suspense>
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return null
}
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export default async function Layout({ children }) {
return <>{children}</>
}
import type { Viewport } from 'next'
import { Suspense } from 'react'
import { cookies } from 'next/headers'
// This would be valid if it used a runtime prefetch (because then it wouldn't block navigation),
// but it's static, so it's invalid. As an extra sanity check, we put a runtime prefetch on the
// layout above, and that should not make this error go away.
export const unstable_instant = { prefetch: 'static' }
export async function generateViewport(): Promise<Viewport> {
await cookies()
return {
themeColor: 'aliceblue',
}
}
export default function Page() {
return (
<main>
<p>This page has a runtime generateViewport</p>
<p>
We also access runtime data in the page itself, because a fully static
page with a runtime vieport is not allowed.
</p>
<Suspense>
<Runtime />
</Suspense>
</main>
)
}
async function Runtime() {
await cookies()
return null
}
import { Metadata } from 'next'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ cookies: [] }],
}
export async function generateMetadata(): Promise<Metadata> {
await connection()
return {
title: 'Blocked by connection',
}
}
export default async function Page() {
await cookies()
return (
<main>
<p>
This page has a generateMetadata that accesses connection. It's
runtime-prefetchable, but metadata doesn't block, so it's fine.
</p>
<p>
We also access connection in the page itself, because a runtime page
with dynamic metadata is not allowed.
</p>
<Suspense>
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return null
}
import type { Viewport } from 'next'
import { connection } from 'next/server'
export const unstable_instant = false
export async function generateViewport(): Promise<Viewport> {
await connection()
return {
themeColor: 'aliceblue',
}
}
export default async function Page() {
await connection()
return (
<main>
<p>
This page has a dynamic generateViewport. That's not prefetchable, but
it has <code>instant = false</code>, so blocking is valid.
</p>
<p>
We also access runtime data in the page itself, because a static page
with a dynamic vieport is not allowed.
</p>
</main>
)
}
import { Metadata } from 'next'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'static',
}
export async function generateMetadata(): Promise<Metadata> {
await cookies()
return {
title: 'Blocked by cookies',
}
}
export default function Page() {
return (
<main>
<p>This page has a generateMetadata that accesses cookies.</p>
<p>
We also access cookies in the page itself, because a static page with
non-static metadata is not allowed.
</p>
<Suspense>
<Runtime />
</Suspense>
</main>
)
}
async function Runtime() {
await cookies()
return null
}
import type { Viewport } from 'next'
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
export async function generateViewport(): Promise<Viewport> {
await cookies()
return {
themeColor: 'aliceblue',
}
}
export default async function Page() {
await cookies()
return (
<main>
<p>This page has a runtime generateViewport</p>
<p>
We also access runtime data in the page itself, because a static page
with a runtime vieport is not allowed.
</p>
</main>
)
}
...@@ -128,6 +128,31 @@ export default async function Page() { ...@@ -128,6 +128,31 @@ export default async function Page() {
</li> </li>
</ul> </ul>
<h2>Head</h2>
<ul>
<li>
<DebugLinks href="/suspense-in-root/head/valid-dynamic-metadata-in-runtime" />
</li>
<li>
<DebugLinks href="/suspense-in-root/head/valid-runtime-metadata-in-static" />
</li>
<li>
<DebugLinks href="/suspense-in-root/head/valid-runtime-viewport-in-runtime" />
</li>
<li>
<DebugLinks href="/suspense-in-root/head/valid-dynamic-viewport-in-blocking" />
</li>
<li>
<DebugLinks href="/suspense-in-root/head/invalid-dynamic-viewport-in-blocking-inside-static" />
</li>
<li>
<DebugLinks href="/suspense-in-root/head/invalid-dynamic-viewport-in-runtime" />
</li>
<li>
<DebugLinks href="/suspense-in-root/head/invalid-runtime-viewport-in-static" />
</li>
</ul>
<h2>Disable Validation</h2> <h2>Disable Validation</h2>
<ul> <ul>
<li> <li>
......
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