Unverified Commit 1a295a63 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Align fallback parameter staging with shell validation (#98512)

`next dev` reported missing Suspense boundaries in layouts that the
build accepted. For `/[top]/items/[bottom]`, `generateStaticParams`
returned `[{ top: 't1' }]`, and the page wrapped its `bottom` access in
Suspense. A request for `/t2/items/b2` still reported the layout's
access to `top` as an error. Development treated both parameters as
unresolved because the requested `top` value was not generated, although
the required static shell only needed to defer `bottom`.

Production Cached Navigations used the same overly broad parameter set
and omitted eligible static content from repeat visits. Resumes also
reconstructed that set from the original build manifest, even after an
on-demand prerender had produced a more complete shell.

This replaces the alternative proposed in #98460. That proposal fixes
the development error by selecting a separate fallback parameter set for
validation while keeping response staging unchanged. The two sets are
not intended to differ for the same shell target. Correcting only
validation would preserve the incorrect staging decision and leave
production Cached Navigations without the eligible static content.

Staging and static-shell validation now use one `stagedFallbackParams`
set for each selected shell target. Required partial shells retain their
unresolved parameters, even when a later request can complete them.
Prerenders record their parameter set in postponed state, and resumes
use that recorded set rather than reconstructing it from the generic
source.

Dynamic RSC requests now read and revalidate the completed-shell cache
key, so they find partial artifacts that the fully resolved pathname
lookup missed. Request metadata and `RequestStore` both expose the set
as `stagedFallbackParams`. Action-only fallback detection checks actual
unresolved parameters instead of treating deferred values as missing.
parent 79daac38
...@@ -337,6 +337,11 @@ export interface DynamicPrerenderManifestRoute ...@@ -337,6 +337,11 @@ export interface DynamicPrerenderManifestRoute
*/ */
remainingPrerenderableParams?: readonly FallbackRouteParam[] remainingPrerenderableParams?: readonly FallbackRouteParam[]
/**
* Whether this candidate must produce a nonempty static shell.
*/
throwOnEmptyStaticShell?: boolean
/** /**
* When defined, it describes the revalidation configuration for the fallback * When defined, it describes the revalidation configuration for the fallback
* route. * route.
...@@ -3888,6 +3893,8 @@ export default async function build( ...@@ -3888,6 +3893,8 @@ export default async function build(
experimentalPPR: isRoutePPREnabled, experimentalPPR: isRoutePPREnabled,
remainingPrerenderableParams: remainingPrerenderableParams:
route.remainingPrerenderableParams, route.remainingPrerenderableParams,
throwOnEmptyStaticShell:
prerenderCandidate?.throwOnEmptyStaticShell,
renderingMode: isAppPPREnabled renderingMode: isAppPPREnabled
? isRoutePPREnabled ? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC ? RenderingMode.PARTIALLY_STATIC
......
...@@ -452,9 +452,9 @@ export function processMessage( ...@@ -452,9 +452,9 @@ export function processMessage(
} }
case HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED: { case HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED: {
// Re-fetch the current router tree so the render picks up the new set of // Re-fetch the current router tree so the render picks up the new set of
// statically-known params (and thus the fresh `fallbackParams`). Unlike // statically-known params (and thus the fresh `stagedFallbackParams`).
// `SERVER_COMPONENT_CHANGES` this does not store an HMR refresh hash, so // Unlike `SERVER_COMPONENT_CHANGES` this does not store an HMR refresh
// it doesn't invalidate `"use cache"` entries. // hash, so it doesn't invalidate `"use cache"` entries.
if ( if (
RuntimeErrorHandler.hadRuntimeError || RuntimeErrorHandler.hadRuntimeError ||
document.documentElement.id === '__next_error__' document.documentElement.id === '__next_error__'
......
...@@ -784,7 +784,7 @@ export async function handleAction({ ...@@ -784,7 +784,7 @@ export async function handleAction({
// which to resume the destination page. // which to resume the destination page.
const isActionOnlyFallbackRequest = const isActionOnlyFallbackRequest =
isFetchAction && isFetchAction &&
requestStore.fallbackParams != null && ctx.fallbackRouteParams != null &&
typeof ctx.renderOpts.postponed === 'string' typeof ctx.renderOpts.postponed === 'string'
const shouldSkipPageRendering = const shouldSkipPageRendering =
actionWasForwarded || isActionOnlyFallbackRequest actionWasForwarded || isActionOnlyFallbackRequest
......
...@@ -1356,7 +1356,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1356,7 +1356,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
ctx: AppRenderContext, ctx: AppRenderContext,
initialRequestStore: RequestStore, initialRequestStore: RequestStore,
createRequestStore: (() => RequestStore) | undefined, createRequestStore: (() => RequestStore) | undefined,
fallbackParams: OpaqueFallbackRouteParams | null stagedFallbackParams: OpaqueFallbackRouteParams | null
): Promise<RenderResult> { ): Promise<RenderResult> {
const { const {
htmlRequestId, htmlRequestId,
...@@ -1509,7 +1509,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1509,7 +1509,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
getPayload, getPayload,
onError, onError,
shouldValidate, shouldValidate,
fallbackRouteParams: fallbackParams, fallbackRouteParams: stagedFallbackParams,
getDevRenderDidError: () => didErrorObservably, getDevRenderDidError: () => didErrorObservably,
navigationKind: { navigationKind: {
type: 'prefetched-client', type: 'prefetched-client',
...@@ -3006,7 +3006,10 @@ async function renderAppPage( ...@@ -3006,7 +3006,10 @@ async function renderAppPage(
null null
const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment) const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment)
const fallbackParams = getRequestMeta(req, 'fallbackParams') || null const stagedFallbackParams =
postponedState?.stagedFallbackParams !== undefined
? postponedState.stagedFallbackParams
: (getRequestMeta(req, 'stagedFallbackParams') ?? null)
const hmrRefreshHash = getRequestMeta(req, 'hmrRefreshHash') const hmrRefreshHash = getRequestMeta(req, 'hmrRefreshHash')
const createRequestStore = createRequestStoreForRender.bind( const createRequestStore = createRequestStoreForRender.bind(
...@@ -3021,7 +3024,7 @@ async function renderAppPage( ...@@ -3021,7 +3024,7 @@ async function renderAppPage(
isHmrRefresh, isHmrRefresh,
serverComponentsHmrCache, serverComponentsHmrCache,
renderResumeDataCache, renderResumeDataCache,
fallbackParams, stagedFallbackParams,
hmrRefreshHash hmrRefreshHash
) )
const requestStore = createRequestStore() const requestStore = createRequestStore()
...@@ -3066,7 +3069,7 @@ async function renderAppPage( ...@@ -3066,7 +3069,7 @@ async function renderAppPage(
ctx, ctx,
requestStore, requestStore,
createRequestStore, createRequestStore,
fallbackParams stagedFallbackParams
) )
} else if (cacheComponents && cachedNavigations) { } else if (cacheComponents && cachedNavigations) {
// MARK: RSC cacheComponents // MARK: RSC cacheComponents
...@@ -3113,7 +3116,7 @@ async function renderAppPage( ...@@ -3113,7 +3116,7 @@ async function renderAppPage(
postponedState, postponedState,
metadata, metadata,
undefined, // Prevent restartable-render behavior in dev + Cache Components mode undefined, // Prevent restartable-render behavior in dev + Cache Components mode
fallbackParams stagedFallbackParams
) )
return new RenderResult(stream, { return new RenderResult(stream, {
...@@ -3155,7 +3158,7 @@ async function renderAppPage( ...@@ -3155,7 +3158,7 @@ async function renderAppPage(
// and we currently we don't copy changes over when creating a new store, // and we currently we don't copy changes over when creating a new store,
// so the restarted render wouldn't be correct. // so the restarted render wouldn't be correct.
didExecuteServerAction ? undefined : createRequestStore, didExecuteServerAction ? undefined : createRequestStore,
fallbackParams stagedFallbackParams
) )
// Forward an invalid-dynamic-usage error recorded by `'use cache'` only // Forward an invalid-dynamic-usage error recorded by `'use cache'` only
...@@ -3531,7 +3534,7 @@ async function renderToStream( ...@@ -3531,7 +3534,7 @@ async function renderToStream(
postponedState: PostponedState | null, postponedState: PostponedState | null,
metadata: AppPageRenderResultMetadata, metadata: AppPageRenderResultMetadata,
createRequestStore: (() => RequestStore) | undefined, createRequestStore: (() => RequestStore) | undefined,
fallbackParams: OpaqueFallbackRouteParams | null stagedFallbackParams: OpaqueFallbackRouteParams | null
): Promise<AnyStream> { ): Promise<AnyStream> {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */ /* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
// MARK: renderToStream setup // MARK: renderToStream setup
...@@ -3779,7 +3782,7 @@ async function renderToStream( ...@@ -3779,7 +3782,7 @@ async function renderToStream(
getPayload, getPayload,
onError: serverComponentsErrorHandler, onError: serverComponentsErrorHandler,
shouldValidate: true, shouldValidate: true,
fallbackRouteParams: fallbackParams, fallbackRouteParams: stagedFallbackParams,
getDevRenderDidError: () => didErrorObservably, getDevRenderDidError: () => didErrorObservably,
// An initial HTML load serves the static shell; runtime and // An initial HTML load serves the static shell; runtime and
// dynamic content stream in afterward. // dynamic content stream in afterward.
...@@ -6683,8 +6686,9 @@ export async function runValidationInDevFromSnapshot( ...@@ -6683,8 +6686,9 @@ export async function runValidationInDevFromSnapshot(
// `requestFallbackRouteParams` reproduces `ctx.getDynamicParamFromSegment` // `requestFallbackRouteParams` reproduces `ctx.getDynamicParamFromSegment`
// exactly, so the depth-loop segment keys match the seed render's Flight. // exactly, so the depth-loop segment keys match the seed render's Flight.
// `fallbackRouteParams` is separate and only marks params unknown in the // `fallbackRouteParams` is the staged set of the main-thread request store.
// prerender stores. // It marks params unknown in the prerender stores, and the worker's request
// store defers the same params, so both validation paths stage alike.
// //
// TODO: Those two fallback params sets are very confusing in the whole code // TODO: Those two fallback params sets are very confusing in the whole code
// base. We should maybe refactor this to make their different roles clearer. // base. We should maybe refactor this to make their different roles clearer.
...@@ -6733,7 +6737,7 @@ export async function runValidationInDevFromSnapshot( ...@@ -6733,7 +6737,7 @@ export async function runValidationInDevFromSnapshot(
isHmrRefresh: message.request.isHmrRefresh, isHmrRefresh: message.request.isHmrRefresh,
hmrRefreshHash: message.request.hmrRefreshHash, hmrRefreshHash: message.request.hmrRefreshHash,
serverComponentsHmrCache: undefined, serverComponentsHmrCache: undefined,
fallbackParams: requestFallbackRouteParams, stagedFallbackParams: fallbackRouteParams,
}) })
const staticInputs = toDevValidationInputs(message.staticInputs, requestStore) const staticInputs = toDevValidationInputs(message.staticInputs, requestStore)
...@@ -9584,7 +9588,8 @@ async function prerenderToStream( ...@@ -9584,7 +9588,8 @@ async function prerenderToStream(
resumeDataCache, resumeDataCache,
cacheComponents, cacheComponents,
renderOpts.experimental.maxPostponedStateSizeBytes, renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression renderOpts.experimental.disableResumeDataCacheCompression,
fallbackRouteParams
) )
} }
reactServerResult.consume() reactServerResult.consume()
...@@ -10125,7 +10130,8 @@ async function prerenderToStream( ...@@ -10125,7 +10130,8 @@ async function prerenderToStream(
originalResumeDataCache, originalResumeDataCache,
cacheComponents, cacheComponents,
renderOpts.experimental.maxPostponedStateSizeBytes, renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression renderOpts.experimental.disableResumeDataCacheCompression,
fallbackRouteParams
) )
originalFlightPrerenderResult.consume() originalFlightPrerenderResult.consume()
errorServerResult.consume() errorServerResult.consume()
......
import { import {
createPrerenderResumeDataCache, createPrerenderResumeDataCache,
deflateResumeDataCache,
stringifyResumeDataCache, stringifyResumeDataCache,
} from '../resume-data-cache/resume-data-cache' } from '../resume-data-cache/resume-data-cache'
import { import {
...@@ -85,6 +86,12 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -85,6 +86,12 @@ describe('getDynamicHTMLPostponedState', () => {
"imageResponses": Map {}, "imageResponses": Map {},
"mutable": false, "mutable": false,
}, },
"stagedFallbackParams": Map {
"slug" => [
"%%drp:slug:e9615126684e5%%",
"d",
],
},
"type": 2, "type": 2,
} }
`) `)
...@@ -125,6 +132,7 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -125,6 +132,7 @@ describe('getDynamicHTMLPostponedState', () => {
const parsed = parsePostponedState(state, params, undefined) const parsed = parsePostponedState(state, params, undefined)
expect(parsed).toEqual({ expect(parsed).toEqual({
type: DynamicState.HTML, type: DynamicState.HTML,
stagedFallbackParams: fallbackRouteParams,
data: [1, { [value]: value }], data: [1, { [value]: value }],
renderResumeDataCache: { renderResumeDataCache: {
cache: new Map(), cache: new Map(),
...@@ -142,44 +150,84 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -142,44 +150,84 @@ describe('getDynamicHTMLPostponedState', () => {
}) })
describe('getDynamicDataPostponedState', () => { describe('getDynamicDataPostponedState', () => {
it('serializes a data postponed state with fallback params', async () => { it.each([undefined, null, new Map()])(
const state = await getDynamicDataPostponedState( 'serializes a data postponed state with no fallback params (%p)',
createPrerenderResumeDataCache(), async (fallbackRouteParams) => {
isCacheComponentsEnabled const state = await getDynamicDataPostponedState(
) createPrerenderResumeDataCache(),
expect(state).toMatchInlineSnapshot(`"4:nullnull"`) isCacheComponentsEnabled,
}) undefined,
false,
fallbackRouteParams
)
expect(state).toBe(
fallbackRouteParams === undefined ? '4:nullnull' : '7:2[]nullnull'
)
const parsed = parsePostponedState(state, {}, undefined)
expect(parsed.type).toBe(DynamicState.DATA)
expect(parsed.stagedFallbackParams).toBe(
fallbackRouteParams === undefined ? undefined : null
)
}
)
it('serializes and parses an uncompressed cache when compression is disabled', async () => { it.each([false, true])(
const resumeDataCache = createPrerenderResumeDataCache() 'serializes and parses fallback params and a cache (disableResumeDataCacheCompression: %s)',
resumeDataCache.fetch.set('cache-key', { async (disableResumeDataCacheCompression) => {
kind: CachedRouteKind.FETCH, const fallbackRouteParams = createMockOpaqueFallbackRouteParams({
data: { slug: ['%%drp:slug:e9615126684e5%%', 'd'],
headers: {}, })
body: 'cached body', const resumeDataCache = createPrerenderResumeDataCache()
url: 'https://example.com', resumeDataCache.fetch.set('cache-key', {
}, kind: CachedRouteKind.FETCH,
revalidate: 60, data: {
}) headers: {},
body: 'cached body',
url: 'https://example.com',
},
revalidate: 60,
})
const serializedResumeDataCache = await stringifyResumeDataCache( const serializedResumeDataCache = await stringifyResumeDataCache(
resumeDataCache, resumeDataCache,
isCacheComponentsEnabled isCacheComponentsEnabled
) )
const state = await getDynamicDataPostponedState( const state = await getDynamicDataPostponedState(
resumeDataCache, resumeDataCache,
isCacheComponentsEnabled, isCacheComponentsEnabled,
undefined, undefined,
true disableResumeDataCacheCompression,
) fallbackRouteParams
)
expect(state).toBe(`4:null${serializedResumeDataCache}`) expect(state).toBe(
`51:45[["slug",["%%drp:slug:e9615126684e5%%","d"]]]null${
disableResumeDataCacheCompression
? serializedResumeDataCache
: deflateResumeDataCache(serializedResumeDataCache)
}`
)
const parsed = parsePostponedState(state, {}, undefined, true) const parsed = parsePostponedState(
expect(parsed.renderResumeDataCache.fetch.get('cache-key')).toEqual( state,
resumeDataCache.fetch.get('cache-key') { slug: '123' },
) undefined,
}) disableResumeDataCacheCompression
)
expect(parsed.type).toBe(DynamicState.DATA)
expect(parsed.stagedFallbackParams).toEqual(fallbackRouteParams)
expect(parsed.renderResumeDataCache.fetch.get('cache-key')).toEqual(
resumeDataCache.fetch.get('cache-key')
)
expect(
parseResumeDataCacheFromPostponedState(
state,
undefined,
disableResumeDataCacheCompression
).fetch.get('cache-key')
).toEqual(resumeDataCache.fetch.get('cache-key'))
}
)
it('warns when the uncompressed state would exceed the size limit', async () => { it('warns when the uncompressed state would exceed the size limit', async () => {
const resumeDataCache = createPrerenderResumeDataCache() const resumeDataCache = createPrerenderResumeDataCache()
...@@ -282,6 +330,7 @@ describe('parsePostponedState', () => { ...@@ -282,6 +330,7 @@ describe('parsePostponedState', () => {
// Ensure that it parsed it correctly. // Ensure that it parsed it correctly.
expect(parsed).toEqual({ expect(parsed).toEqual({
type: DynamicState.HTML, type: DynamicState.HTML,
stagedFallbackParams: new Map([['slug', '%%drp:slug:e9615126684e5%%']]),
data: expect.any(Object), data: expect.any(Object),
renderResumeDataCache: { renderResumeDataCache: {
cache: new Map(), cache: new Map(),
...@@ -305,6 +354,7 @@ describe('parsePostponedState', () => { ...@@ -305,6 +354,7 @@ describe('parsePostponedState', () => {
// Ensure that it parsed it correctly. // Ensure that it parsed it correctly.
expect(parsed).toEqual({ expect(parsed).toEqual({
type: DynamicState.HTML, type: DynamicState.HTML,
stagedFallbackParams: null,
data: expect.any(Object), data: expect.any(Object),
renderResumeDataCache: { renderResumeDataCache: {
cache: new Map(), cache: new Map(),
...@@ -317,7 +367,7 @@ describe('parsePostponedState', () => { ...@@ -317,7 +367,7 @@ describe('parsePostponedState', () => {
}) })
}) })
it('parses a data postponed state', () => { it('parses a legacy data postponed state', () => {
const state = '4:nullnull' const state = '4:nullnull'
const parsed = parsePostponedState(state, {}, undefined) const parsed = parsePostponedState(state, {}, undefined)
...@@ -333,5 +383,6 @@ describe('parsePostponedState', () => { ...@@ -333,5 +383,6 @@ describe('parsePostponedState', () => {
mutable: false, mutable: false,
}, },
}) })
expect(parsed).not.toHaveProperty('stagedFallbackParams')
}) })
}) })
...@@ -26,7 +26,7 @@ export enum DynamicState { ...@@ -26,7 +26,7 @@ export enum DynamicState {
} }
/** /**
* The postponed state for dynamic data. * A postponed state with a resume data cache but no React HTML-resume state.
*/ */
export type DynamicDataPostponedState = { export type DynamicDataPostponedState = {
/** /**
...@@ -34,6 +34,13 @@ export type DynamicDataPostponedState = { ...@@ -34,6 +34,13 @@ export type DynamicDataPostponedState = {
*/ */
readonly type: DynamicState.DATA readonly type: DynamicState.DATA
/**
* The params to defer during the resumed render. The render uses request
* metadata when this field is absent. `null` explicitly means no fallback
* params.
*/
readonly stagedFallbackParams?: OpaqueFallbackRouteParams | null
/** /**
* The immutable resume data cache. * The immutable resume data cache.
*/ */
...@@ -49,6 +56,13 @@ export type DynamicHTMLPostponedState = { ...@@ -49,6 +56,13 @@ export type DynamicHTMLPostponedState = {
*/ */
readonly type: DynamicState.HTML readonly type: DynamicState.HTML
/**
* The params to defer during the resumed render. An HTML state always records
* this set, and `null` means the prerender had no fallback params. Unlike the
* data state, it never falls back to request metadata.
*/
readonly stagedFallbackParams: OpaqueFallbackRouteParams | null
/** /**
* The postponed data used by React. * The postponed data used by React.
*/ */
...@@ -156,10 +170,23 @@ export async function getDynamicDataPostponedState( ...@@ -156,10 +170,23 @@ export async function getDynamicDataPostponedState(
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache, resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache,
isCacheComponentsEnabled: boolean, isCacheComponentsEnabled: boolean,
maxPostponedStateSizeBytes?: number, maxPostponedStateSizeBytes?: number,
disableResumeDataCacheCompression = false disableResumeDataCacheCompression = false,
fallbackRouteParams?: OpaqueFallbackRouteParams | null
): Promise<string> { ): Promise<string> {
let postponedString = 'null'
if (fallbackRouteParams !== undefined) {
const replacements: OpaqueFallbackRouteParamEntries = fallbackRouteParams
? Array.from(fallbackRouteParams.entries())
: []
const replacementsString = JSON.stringify(replacements)
// An empty replacements table records that this shell has no fallback
// params.
postponedString = `${replacementsString.length}${replacementsString}null`
}
return serializePostponedState( return serializePostponedState(
'null', postponedString,
resumeDataCache, resumeDataCache,
isCacheComponentsEnabled, isCacheComponentsEnabled,
maxPostponedStateSizeBytes, maxPostponedStateSizeBytes,
...@@ -234,6 +261,9 @@ export function parsePostponedState( ...@@ -234,6 +261,9 @@ export function parsePostponedState(
try { try {
if (postponedString === 'null') { if (postponedString === 'null') {
// Leave `stagedFallbackParams` unset for the `4:null<cache>` form. It
// contains no fallback-parameter information. A platform can send
// `4:nullnull` when it invokes the renderer without a cached shell.
return { type: DynamicState.DATA, renderResumeDataCache } return { type: DynamicState.DATA, renderResumeDataCache }
} }
...@@ -254,8 +284,18 @@ export function parsePostponedState( ...@@ -254,8 +284,18 @@ export function parsePostponedState(
match.length + length match.length + length
) )
) as OpaqueFallbackRouteParamEntries ) as OpaqueFallbackRouteParamEntries
const stagedFallbackParams =
replacements.length > 0 ? new Map(replacements) : null
let postponed = postponedString.slice(match.length + length) let postponed = postponedString.slice(match.length + length)
if (postponed === 'null') {
return {
type: DynamicState.DATA,
stagedFallbackParams,
renderResumeDataCache,
}
}
for (const [ for (const [
segmentKey, segmentKey,
[searchValue, dynamicParamType], [searchValue, dynamicParamType],
...@@ -281,6 +321,7 @@ export function parsePostponedState( ...@@ -281,6 +321,7 @@ export function parsePostponedState(
return { return {
type: DynamicState.HTML, type: DynamicState.HTML,
stagedFallbackParams,
data: JSON.parse(postponed), data: JSON.parse(postponed),
renderResumeDataCache, renderResumeDataCache,
} }
...@@ -288,6 +329,7 @@ export function parsePostponedState( ...@@ -288,6 +329,7 @@ export function parsePostponedState(
return { return {
type: DynamicState.HTML, type: DynamicState.HTML,
stagedFallbackParams: null,
data: JSON.parse(postponedString), data: JSON.parse(postponedString),
renderResumeDataCache, renderResumeDataCache,
} }
......
...@@ -98,7 +98,11 @@ export interface RequestStore extends CommonWorkUnitStore { ...@@ -98,7 +98,11 @@ export interface RequestStore extends CommonWorkUnitStore {
hasIncompatibleShellContent?: boolean hasIncompatibleShellContent?: boolean
cacheSignal?: CacheSignal | null cacheSignal?: CacheSignal | null
fallbackParams?: OpaqueFallbackRouteParams | null /**
* These params resolve after the static stage without replacing their
* concrete values.
*/
stagedFallbackParams?: OpaqueFallbackRouteParams | null
varyParamsAccumulator?: ResponseVaryParamsAccumulator | null varyParamsAccumulator?: ResponseVaryParamsAccumulator | null
// Only in build-time instant-validation or when rendering // Only in build-time instant-validation or when rendering
......
...@@ -146,7 +146,7 @@ export type RequestStoreInputs = { ...@@ -146,7 +146,7 @@ export type RequestStoreInputs = {
* edit, for every client, regardless of whether it runs the HMR client. * edit, for every client, regardless of whether it runs the HMR client.
*/ */
hmrRefreshHash: string | undefined hmrRefreshHash: string | undefined
fallbackParams: OpaqueFallbackRouteParams | null | undefined stagedFallbackParams: OpaqueFallbackRouteParams | null | undefined
} }
/** /**
...@@ -193,7 +193,7 @@ export function createRequestStoreForRender( ...@@ -193,7 +193,7 @@ export function createRequestStoreForRender(
isHmrRefresh: RequestContext['isHmrRefresh'], isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'], serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
resumeDataCache: ResumeDataCache | null, resumeDataCache: ResumeDataCache | null,
fallbackParams: OpaqueFallbackRouteParams | null, stagedFallbackParams: OpaqueFallbackRouteParams | null,
hmrRefreshHash: string | undefined hmrRefreshHash: string | undefined
): RequestStore { ): RequestStore {
return createRequestStore({ return createRequestStore({
...@@ -215,7 +215,7 @@ export function createRequestStoreForRender( ...@@ -215,7 +215,7 @@ export function createRequestStoreForRender(
isHmrRefresh, isHmrRefresh,
serverComponentsHmrCache, serverComponentsHmrCache,
hmrRefreshHash, hmrRefreshHash,
fallbackParams, stagedFallbackParams,
}) })
} }
...@@ -240,7 +240,7 @@ export function createRequestStoreForAPI( ...@@ -240,7 +240,7 @@ export function createRequestStoreForAPI(
isHmrRefresh: false, isHmrRefresh: false,
serverComponentsHmrCache: undefined, serverComponentsHmrCache: undefined,
hmrRefreshHash, hmrRefreshHash,
fallbackParams: null, stagedFallbackParams: null,
}) })
} }
...@@ -264,7 +264,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore { ...@@ -264,7 +264,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
isHmrRefresh, isHmrRefresh,
serverComponentsHmrCache, serverComponentsHmrCache,
hmrRefreshHash, hmrRefreshHash,
fallbackParams, stagedFallbackParams,
} = inputs } = inputs
const cache: { const cache: {
...@@ -347,7 +347,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore { ...@@ -347,7 +347,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
serverComponentsHmrCache || serverComponentsHmrCache ||
(globalThis as any).__serverComponentsHmrCache, (globalThis as any).__serverComponentsHmrCache,
hmrRefreshHash, hmrRefreshHash,
fallbackParams, stagedFallbackParams,
} }
} }
......
...@@ -159,7 +159,10 @@ import { fixMojibake } from './lib/fix-mojibake' ...@@ -159,7 +159,10 @@ import { fixMojibake } from './lib/fix-mojibake'
import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param' import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'
import type { CacheControl } from './lib/cache-control' import type { CacheControl } from './lib/cache-control'
import type { PrerenderedRoute } from '../build/static-paths/types' import type { PrerenderedRoute } from '../build/static-paths/types'
import { createOpaqueFallbackRouteParams } from './request/fallback-params' import {
createOpaqueFallbackRouteParams,
getStagedFallbackParams,
} from './request/fallback-params'
import { RouteKind } from './route-kind' import { RouteKind } from './route-kind'
import type { ErrorModule } from './load-default-error-components' import type { ErrorModule } from './load-default-error-components'
import { import {
...@@ -2746,44 +2749,39 @@ export default abstract class Server< ...@@ -2746,44 +2749,39 @@ export default abstract class Server<
if (isAppPath && this.nextConfig.cacheComponents) { if (isAppPath && this.nextConfig.cacheComponents) {
if (pathsResults.prerenderedRoutes?.length) { if (pathsResults.prerenderedRoutes?.length) {
// Replicate, on demand, the per-URL fallback set a production build // The source selection includes concrete routes with no fallback
// writes to the prerender manifest. Production matches the requested // params. Otherwise it could choose a generic fallback for a fully
// URL to the most-specific prerendered route and defers that route's // generated URL.
// `fallbackRouteParams` (so `generateStaticParams`-covered params let matchedRoute: PrerenderedRoute | undefined
// resolve in the static shell and only the uncovered ones are
// deferred). The dev prerender manifest isn't populated for these
// ad-hoc routes, but `getStaticPaths` already computed every
// prerendered route here, so we do the same match: among the routes
// whose canonical regex matches this URL, pick the one with the
// fewest fallback params (the most-specific) and thread it via the
// `fallbackParams` meta. A fully-covered concrete route (e.g.
// `/blog/a`) has zero fallback params and is the most-specific match
// for its own URL, so it must be considered alongside the others: it
// wins over the base dynamic route (`/blog/[slug]`) and leaves its
// statically-known params out of the deferred set.
let perUrlFallbackRouteParams: NonNullable<
(typeof pathsResults.prerenderedRoutes)[number]['fallbackRouteParams']
> | null = null
for (const route of pathsResults.prerenderedRoutes) { for (const route of pathsResults.prerenderedRoutes) {
const fallbackRouteParams = route.fallbackRouteParams ?? []
if (!getRouteRegex(route.pathname).re.test(urlPathname)) { if (!getRouteRegex(route.pathname).re.test(urlPathname)) {
continue continue
} }
if ( if (
perUrlFallbackRouteParams === null || matchedRoute === undefined ||
fallbackRouteParams.length < perUrlFallbackRouteParams.length (route.fallbackRouteParams?.length ?? 0) <
(matchedRoute.fallbackRouteParams?.length ?? 0)
) { ) {
perUrlFallbackRouteParams = fallbackRouteParams matchedRoute = route
} }
} }
if ( if (matchedRoute) {
perUrlFallbackRouteParams && // Explicit shell requests render the matched artifact. Ordinary
perUrlFallbackRouteParams.length > 0 // requests stage and validate the same required or completed shell
) { // target.
addRequestMeta(
req,
'fallbackRouteParams',
matchedRoute.fallbackRouteParams
? createOpaqueFallbackRouteParams(
matchedRoute.fallbackRouteParams
)
: null
)
addRequestMeta( addRequestMeta(
req, req,
'fallbackParams', 'stagedFallbackParams',
createOpaqueFallbackRouteParams(perUrlFallbackRouteParams)! getStagedFallbackParams(matchedRoute)
) )
} }
} }
......
...@@ -889,12 +889,12 @@ export default class DevServer extends Server { ...@@ -889,12 +889,12 @@ export default class DevServer extends Server {
} }
this.staticPathsCache.set(pathname, value) this.staticPathsCache.set(pathname, value)
// Since generateStaticParams runs in the background, the fallbackParams // Since generateStaticParams runs in the background, the
// accessed during a render are derived from the previous result served // stagedFallbackParams accessed during a render are derived from the
// by the static paths cache. Now that the cache holds the new result, // previous result served by the static paths cache. Now that the cache
// trigger a refresh so the next render picks up the new fallbackParams // holds the new result, trigger a refresh so the next render picks up
// (e.g. so blocking-route validation reflects params that just became // the new stagedFallbackParams (e.g. so blocking-route validation
// statically known). // reflects params that just became statically known).
if ( if (
isAppPath && isAppPath &&
this.nextConfig.cacheComponents && this.nextConfig.cacheComponents &&
......
...@@ -169,7 +169,7 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> { ...@@ -169,7 +169,7 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> {
isHmrRefresh: msg.request.isHmrRefresh, isHmrRefresh: msg.request.isHmrRefresh,
serverComponentsHmrCache: undefined, serverComponentsHmrCache: undefined,
hmrRefreshHash: msg.request.hmrRefreshHash, hmrRefreshHash: msg.request.hmrRefreshHash,
fallbackParams: null, stagedFallbackParams: null,
}) })
await workAsyncStorage.run(workStore, () => await workAsyncStorage.run(workStore, () =>
......
...@@ -319,10 +319,36 @@ export interface RequestMeta { ...@@ -319,10 +319,36 @@ export interface RequestMeta {
minimalMode?: boolean minimalMode?: boolean
/** /**
* The fallback params for this route. In dev, used for validating prerenders. * Staged renders defer these route params until after the static stage. They
* In production, used to defer params resolution during staged rendering. * keep their concrete request values instead of replacing them with
* placeholders. Dev static-shell validation uses the same set for the
* selected shell.
*
* For `/t2/items/b2` with selected shell `/t2/items/[bottom]`, this map
* contains only `bottom`:
* - A layout's `params` containing only `top` can resolve statically.
* - A page's `params` containing `bottom` waits until after the static stage.
*
* A set recorded in postponed state overrides this metadata on a resume,
* including an explicitly empty set.
*/
stagedFallbackParams?: OpaqueFallbackRouteParams | null
/**
* Dev static-shell debug renders use these params to prerender the matched
* source shell. The Instant Navigation Testing API uses this path too. The
* prerender substitutes opaque placeholders for these params rather than
* using their request values.
*
* Suppose `generateStaticParams` returns `[{ top: 't1' }]` for
* `/[top]/items/[bottom]`. A request for `/t2/items/b2` has:
* - Source `/[top]/items/[bottom]`: `top` and `bottom` are unresolved.
* - Completed shell `/t2/items/[bottom]`: only `bottom` is unresolved.
*
* This map contains the source's `top` and `bottom`. A debug render of that
* source also uses this map as `stagedFallbackParams`.
*/ */
fallbackParams?: OpaqueFallbackRouteParams fallbackRouteParams?: OpaqueFallbackRouteParams | null
/** /**
* DEV only: Request timings in process.hrtime.bigint() * DEV only: Request timings in process.hrtime.bigint()
......
...@@ -6,6 +6,7 @@ import type AppPageRouteModule from '../route-modules/app-page/module' ...@@ -6,6 +6,7 @@ import type AppPageRouteModule from '../route-modules/app-page/module'
import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app' import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'
import { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree' import { extractPathnameRouteParamSegmentsFromLoaderTree } from '../../build/static-paths/app/extract-pathname-route-param-segments-from-loader-tree'
import { getParamProperties } from '../../shared/lib/router/utils/get-segment-param' import { getParamProperties } from '../../shared/lib/router/utils/get-segment-param'
import { InvariantError } from '../../shared/lib/invariant-error'
export type OpaqueFallbackRouteParamValue = [ export type OpaqueFallbackRouteParamValue = [
/** /**
...@@ -75,6 +76,56 @@ export function createOpaqueFallbackRouteParams( ...@@ -75,6 +76,56 @@ export function createOpaqueFallbackRouteParams(
return keys return keys
} }
/**
* Selects the params that a staged render defers for the shell target that a
* request selects. Dev static-shell validation stages the same set, so it
* checks the shell that the build validates.
*
* The set derives from the build's shell metadata, not from the serving mode. A
* required shell (`throwOnEmptyStaticShell`) is the most specific shell the
* build generated for its params, and the build fails when its prelude is
* empty. Staging defers all of its fallback params, because the build validated
* exactly that shape. Any other shell may be empty, and a request completes it
* with the params that `generateStaticParams` can still supply. Only the params
* that completion never resolves stay deferred.
*
* `next start` without `partialPrefetching` keys ISR entries by the full
* pathname, so such an entry resolves every param. A cold staged render then
* defers params that the entry resolves, so its static stage contains less
* content. A resume reads the recorded set from the entry's postponed state.
*/
export function getStagedFallbackParams(route: {
fallbackRouteParams: readonly FallbackRouteParam[] | undefined
remainingPrerenderableParams?: readonly FallbackRouteParam[]
throwOnEmptyStaticShell?: boolean
}): OpaqueFallbackRouteParams | null {
const { fallbackRouteParams, remainingPrerenderableParams } = route
if (!fallbackRouteParams?.length) {
return null
}
if (route.throwOnEmptyStaticShell === undefined) {
throw new InvariantError(
'Expected throwOnEmptyStaticShell for a route with fallback params'
)
}
// A required shell keeps all of its fallback params deferred.
if (route.throwOnEmptyStaticShell || !remainingPrerenderableParams?.length) {
return createOpaqueFallbackRouteParams(fallbackRouteParams)
}
return createOpaqueFallbackRouteParams(
fallbackRouteParams.filter(
(param) =>
!remainingPrerenderableParams.some(
(prerenderableParam) =>
prerenderableParam.paramName === param.paramName
)
)
)
}
export function buildDynamicSegmentPlaceholder( export function buildDynamicSegmentPlaceholder(
param: Pick<FallbackRouteParam, 'paramName' | 'paramType'> param: Pick<FallbackRouteParam, 'paramName' | 'paramType'>
): string { ): string {
......
...@@ -101,12 +101,12 @@ export function createParamsFromClient( ...@@ -101,12 +101,12 @@ export function createParamsFromClient(
) )
} }
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const fallbackParams = workUnitStore.fallbackParams const stagedFallbackParams = workUnitStore.stagedFallbackParams
const userspaceParams = underlyingParams const userspaceParams = underlyingParams
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
userspaceParams, userspaceParams,
fallbackParams, stagedFallbackParams,
workStore, workStore,
workUnitStore workUnitStore
) )
...@@ -178,12 +178,12 @@ export function createServerParamsForRoute( ...@@ -178,12 +178,12 @@ export function createServerParamsForRoute(
} }
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const fallbackParams = workUnitStore.fallbackParams const stagedFallbackParams = workUnitStore.stagedFallbackParams
const userspaceParams = underlyingParams const userspaceParams = underlyingParams
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
userspaceParams, userspaceParams,
fallbackParams, stagedFallbackParams,
workStore, workStore,
workUnitStore workUnitStore
) )
...@@ -501,11 +501,11 @@ function createRenderParamsForPage( ...@@ -501,11 +501,11 @@ function createRenderParamsForPage(
// No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const fallbackParams = workUnitStore.fallbackParams const stagedFallbackParams = workUnitStore.stagedFallbackParams
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
userspaceParams, userspaceParams,
fallbackParams, stagedFallbackParams,
workStore, workStore,
workUnitStore workUnitStore
) )
...@@ -556,7 +556,9 @@ function createStagedRenderParamsImpl( ...@@ -556,7 +556,9 @@ function createStagedRenderParamsImpl(
// If we have fallback params, then they should always resolve in the runtime link data stage. // If we have fallback params, then they should always resolve in the runtime link data stage.
// We do this indirectly via the shared params parent for better debug info. // We do this indirectly via the shared params parent for better debug info.
if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) { if (
hasFallbackRouteParams(underlyingParams, workUnitStore.stagedFallbackParams)
) {
return createParamsPromiseFromTrigger( return createParamsPromiseFromTrigger(
asyncApiPromises.sharedParamsParent, asyncApiPromises.sharedParamsParent,
userspaceParams userspaceParams
...@@ -661,14 +663,14 @@ function createRenderParamsInProd(userspaceParams: Params): Promise<Params> { ...@@ -661,14 +663,14 @@ function createRenderParamsInProd(userspaceParams: Params): Promise<Params> {
function createRenderParamsInDev( function createRenderParamsInDev(
underlyingParams: Params, underlyingParams: Params,
userpaceParams: Params, userpaceParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined, stagedFallbackParams: OpaqueFallbackRouteParams | null | undefined,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore requestStore: RequestStore
): Promise<Params> { ): Promise<Params> {
return makeDynamicallyTrackedParamsWithDevWarnings( return makeDynamicallyTrackedParamsWithDevWarnings(
underlyingParams, underlyingParams,
userpaceParams, userpaceParams,
hasFallbackRouteParams(underlyingParams, fallbackParams), hasFallbackRouteParams(underlyingParams, stagedFallbackParams),
workStore, workStore,
requestStore requestStore
) )
......
import { Suspense } from 'react'
async function Content({ params }: { params: Promise<{ slug: string[] }> }) {
const { slug } = await params
return <p id="catchall">{slug.join('/')}</p>
}
export default function Page(props: { params: Promise<{ slug: string[] }> }) {
return (
<Suspense fallback="Loading params...">
<Content {...props} />
</Suspense>
)
}
export function generateStaticParams() {
return [{ top: 'short' }, { top: 'long', bottom: 'example' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { top, bottom } = await params
return <p>{`${top}/${bottom}`}</p>
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup, type Playwright } from 'e2e-utils'
import { getDevCliValidationOutput } from 'e2e-utils/instant-validation'
import { waitForNoRedbox } from 'next-test-utils' import { waitForNoRedbox } from 'next-test-utils'
describe('Cache Components Fallback Validation', () => { describe('Cache Components Fallback Validation', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
env: { NEXT_TEST_LOG_VALIDATION: '1' },
}) })
async function expectNoValidationErrors(browser: Playwright) {
expect(
await getDevCliValidationOutput(await browser.url(), () => next.cliOutput)
).not.toContain('Error: Route')
await waitForNoRedbox(browser)
}
it('should not warn about missing Suspense when accessing params if static params are completely known at build time', async () => { it('should not warn about missing Suspense when accessing params if static params are completely known at build time', async () => {
// when the params are complete we don't expect to see any errors await params regarless of where there // when the params are complete we don't expect to see any errors await params regarless of where there
// are Suspense boundaries. // are Suspense boundaries.
const browser = await next.browser( const browser = await next.browser(
'/complete/prerendered/wrapped/prerendered' '/complete/prerendered/wrapped/prerendered'
) )
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage(`${next.url}/complete/prerendered/wrapped/novel`) await browser.loadPage(`${next.url}/complete/prerendered/wrapped/novel`)
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage(`${next.url}/complete/novel/wrapped/novel`) await browser.loadPage(`${next.url}/complete/novel/wrapped/novel`)
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage( await browser.loadPage(
`${next.url}/complete/prerendered/unwrapped/prerendered` `${next.url}/complete/prerendered/unwrapped/prerendered`
) )
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage(`${next.url}/complete/prerendered/unwrapped/novel`) await browser.loadPage(`${next.url}/complete/prerendered/unwrapped/novel`)
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage(`${next.url}/complete/novel/unwrapped/novel`) await browser.loadPage(`${next.url}/complete/novel/unwrapped/novel`)
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
}) })
it('should warn about missing Suspense when accessing params if static params are partially known at build time', async () => { it('should warn about missing Suspense when accessing params if static params are partially known at build time', async () => {
...@@ -38,13 +47,13 @@ describe('Cache Components Fallback Validation', () => { ...@@ -38,13 +47,13 @@ describe('Cache Components Fallback Validation', () => {
const browser = await next.browser( const browser = await next.browser(
'/partial/prerendered/wrapped/prerendered' '/partial/prerendered/wrapped/prerendered'
) )
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage(`${next.url}/partial/prerendered/wrapped/novel`) await browser.loadPage(`${next.url}/partial/prerendered/wrapped/novel`)
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage(`${next.url}/partial/novel/wrapped/novel`) await browser.loadPage(`${next.url}/partial/novel/wrapped/novel`)
await waitForNoRedbox(browser) await expectNoValidationErrors(browser)
await browser.loadPage( await browser.loadPage(
`${next.url}/partial/prerendered/unwrapped/prerendered` `${next.url}/partial/prerendered/unwrapped/prerendered`
...@@ -84,16 +93,44 @@ describe('Cache Components Fallback Validation', () => { ...@@ -84,16 +93,44 @@ describe('Cache Components Fallback Validation', () => {
"description": "Next.js encountered runtime data during prerendering.", "description": "Next.js encountered runtime data during prerendering.",
"environmentLabel": "Server", "environmentLabel": "Server",
"label": "Blocking Route", "label": "Blocking Route",
"source": "app/partial/[top]/unwrapped/layout.tsx (8:3) @ Layout "source": "app/partial/[top]/unwrapped/[bottom]/page.tsx (6:26) @ Page
> 8 | await params > 6 | Top: {(await props.params).top}, Bottom: {(await props.params).bottom}
| ^", | ^",
"stack": [ "stack": [
"Layout app/partial/[top]/unwrapped/layout.tsx (8:3)", "Page app/partial/[top]/unwrapped/[bottom]/page.tsx (6:26)",
], ],
} }
`) `)
}) })
it('validates a required partial shell even when another branch can complete', async () => {
const browser = await next.browser('/mixed/short/novel')
const output = await getDevCliValidationOutput(
await browser.url(),
() => next.cliOutput
)
expect(output).toContain('Error: Route "/mixed/[top]/[bottom]"')
expect(output).toContain('app/mixed/[top]/[bottom]/page.tsx')
})
it('uses the complete shape for a branch with a more-specific example', async () => {
const browser = await next.browser('/mixed/long/novel')
await expectNoValidationErrors(browser)
await browser.loadPage(`${next.url}/mixed/novel/novel`)
await expectNoValidationErrors(browser)
})
it('preserves concrete catch-all values during validation', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/catchall/one/two')
expect(await browser.elementById('catchall').text()).toBe('one/two')
await expectNoValidationErrors(browser)
expect(next.cliOutput.slice(outputIndex)).not.toContain('TypeError')
})
it('should warn about missing Suspense when accessing params if static params are entirely missing at build time', async () => { it('should warn about missing Suspense when accessing params if static params are entirely missing at build time', async () => {
// when the params are partially complete we don't expect to see any errors awaiting the params that are known // when the params are partially complete we don't expect to see any errors awaiting the params that are known
// but do expect errors awaiting the params that are not known if not inside a Suspense boundary. // but do expect errors awaiting the params that are not known if not inside a Suspense boundary.
......
...@@ -3,6 +3,11 @@ ...@@ -3,6 +3,11 @@
*/ */
const nextConfig = { const nextConfig = {
cacheComponents: true, cacheComponents: true,
experimental: {
instantInsights: {
validationLevel: 'manual-warning',
},
},
} }
module.exports = nextConfig module.exports = nextConfig
...@@ -338,6 +338,8 @@ export function runDevWarmupTests({ ...@@ -338,6 +338,8 @@ export function runDevWarmupTests({
// TODO: we should only label this as "Prefetch" if there's a prefetch config. // TODO: we should only label this as "Prefetch" if there's a prefetch config.
assertLog(logs, `after cookies`, 'Prefetch') assertLog(logs, `after cookies`, 'Prefetch')
assertLog(logs, `after headers`, 'Prefetch') assertLog(logs, `after headers`, 'Prefetch')
// This route has no `generateStaticParams`, so its param stays
// runtime-only.
assertLog(logs, `after params`, 'Prefetch') assertLog(logs, `after params`, 'Prefetch')
assertLog(logs, `after searchParams`, 'Prefetch') assertLog(logs, `after searchParams`, 'Prefetch')
...@@ -378,17 +380,16 @@ export function runDevWarmupTests({ ...@@ -378,17 +380,16 @@ export function runDevWarmupTests({
}) })
describe('mixed static and fallback params resolve in the correct phase', () => { describe('mixed static and fallback params resolve in the correct phase', () => {
it('covered leading param', async () => { it('generated lang and novel id', async () => {
const path = '/mixed/en/123' const path = '/mixed/en/123'
const assertLogs = async (browser: Playwright) => { const assertLogs = async (browser: Playwright) => {
const logs = await browser.log() const logs = await browser.log()
// `en` is covered by `generateStaticParams`, so `lang` resolves in // The generators produce { lang: 'en', id: 'x' }. The optional
// the static shell, unless we're rendering an App Shell, in which // /mixed/en/[id] shell can complete the novel id statically.
// case they're deferred to the runtiem stage. // `STATIC_LINK_DATA` accounts for App Shell deferral on navigation.
assertLog(logs, 'after params - lang', STATIC_LINK_DATA) assertLog(logs, 'after params - lang', STATIC_LINK_DATA)
// `id` is never covered, so it's deferred to the runtime stage. assertLog(logs, 'after params - id', STATIC_LINK_DATA)
assertLog(logs, 'after params - id', RUNTIME_LINK_DATA)
} }
if (isInitialLoad) { if (isInitialLoad) {
...@@ -398,19 +399,15 @@ export function runDevWarmupTests({ ...@@ -398,19 +399,15 @@ export function runDevWarmupTests({
} }
}) })
it('uncovered leading param', async () => { it('novel lang and id', async () => {
const path = '/mixed/fr/123' const path = '/mixed/fr/123'
const assertLogs = async (browser: Playwright) => { const assertLogs = async (browser: Playwright) => {
const logs = await browser.log() const logs = await browser.log()
// `fr` is not covered by `generateStaticParams`, so the most-specific // Both params have generators. The optional /mixed/[lang]/[id]
// prerendered route matching this URL is the base route and its // shell can complete both novel values statically.
// fallback set is both params. `lang` must therefore defer to the assertLog(logs, 'after params - lang', STATIC_LINK_DATA)
// runtime stage too, not resolve in the static shell. (Picking the assertLog(logs, 'after params - id', STATIC_LINK_DATA)
// fewest-param route without matching the URL would resolve `lang`
// in `Prerender` here.)
assertLog(logs, 'after params - lang', RUNTIME_LINK_DATA)
assertLog(logs, 'after params - id', RUNTIME_LINK_DATA)
} }
if (isInitialLoad) { if (isInitialLoad) {
...@@ -420,17 +417,13 @@ export function runDevWarmupTests({ ...@@ -420,17 +417,13 @@ export function runDevWarmupTests({
} }
}) })
it('fully covered params', async () => { it('fully generated params', async () => {
const path = '/mixed/en/x' const path = '/mixed/en/x'
const assertLogs = async (browser: Playwright) => { const assertLogs = async (browser: Playwright) => {
const logs = await browser.log() const logs = await browser.log()
// Both `en` and `x` are covered by `generateStaticParams`, so this // This URL matches the concrete generated route. Neither param
// is a fully prerendered concrete route and both params resolve in // needs completion or fallback staging.
// the static shell unless we're rendering an App Shell, in which
// case they're deferred to the runtime stage.
// (Skipping the concrete route before matching the URL would let
// the base route win and defer the statically-known `id`.)
assertLog(logs, 'after params - lang', STATIC_LINK_DATA) assertLog(logs, 'after params - lang', STATIC_LINK_DATA)
assertLog(logs, 'after params - id', STATIC_LINK_DATA) assertLog(logs, 'after params - id', STATIC_LINK_DATA)
} }
...@@ -441,6 +434,30 @@ export function runDevWarmupTests({ ...@@ -441,6 +434,30 @@ export function runDevWarmupTests({
await testNavigation(path, assertLogs) await testNavigation(path, assertLogs)
} }
}) })
// Only lang has a generator, so id stays runtime-only.
// - en selects the required /partial/en/[id] shell.
// - fr completes lang from the optional /partial/[lang]/[id] shell.
it.each(['en', 'fr'])(
'partial generation with lang %s',
async (lang) => {
const path = `/partial/${lang}/123`
const assertLogs = async (browser: Playwright) => {
const logs = await browser.log()
assertLog(logs, 'after params - lang', STATIC_LINK_DATA)
assertLog(logs, 'after cache read - layout', STATIC_LINK_DATA)
assertLog(logs, 'after params - id', RUNTIME_LINK_DATA)
assertLog(logs, 'after cache read - page', RUNTIME_LINK_DATA)
}
if (isInitialLoad) {
await testInitialLoad(path, assertLogs)
} else {
await testNavigation(path, assertLogs)
}
}
)
}) })
it('sync IO in the static phase', async () => { it('sync IO in the static phase', async () => {
......
import { Suspense } from 'react' import { Suspense } from 'react'
// `id` is covered by `generateStaticParams` only for `x`, so `/mixed/en/x` is a // Both params have generators, so the route has a fully generated shape. Novel
// fully prerendered route (both params resolve in the static shell) while other // values can complete an optional shell without deferring either param.
// ids such as `123` are deferred to the runtime stage. The parent `[lang]`
// layout reads `lang`; this page reads only `id`.
export function generateStaticParams() { export function generateStaticParams() {
return [{ id: 'x' }] return [{ id: 'x' }]
} }
......
...@@ -3,9 +3,9 @@ import { ReactNode, Suspense } from 'react' ...@@ -3,9 +3,9 @@ import { ReactNode, Suspense } from 'react'
export const instant = true export const instant = true
export const prefetch = 'partial' export const prefetch = 'partial'
// `lang` is covered by `generateStaticParams`. At this segment `params` only // The layout logs the resolution stage of `lang` independently of `id`. Its
// contains `lang`, so reading it here (rather than in the deeper page) lets us // `params` object contains only `lang`, so the staging check does not consider
// observe the stage `lang` resolves in independently of the uncovered `id`. // `id`.
export function generateStaticParams() { export function generateStaticParams() {
return [{ lang: 'en' }] return [{ lang: 'en' }]
} }
......
...@@ -32,6 +32,12 @@ export default function Page() { ...@@ -32,6 +32,12 @@ export default function Page() {
<li> <li>
<Link href="/mixed/en/x">/mixed/en/x</Link> <Link href="/mixed/en/x">/mixed/en/x</Link>
</li> </li>
<li>
<Link href="/partial/en/123">/partial/en/123</Link>
</li>
<li>
<Link href="/partial/fr/123">/partial/fr/123</Link>
</li>
<li> <li>
<Link href="/sync-io/static">/sync-io/static</Link> <Link href="/sync-io/static">/sync-io/static</Link>
</li> </li>
......
import { Suspense } from 'react'
import { CachedData } from '../../../data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__'
export default function PartialIdPage({
params,
}: {
params: Promise<{ lang: string; id: string }>
}) {
return (
<main>
<Suspense fallback={<p>Waiting for id...</p>}>
<IdLabel params={params} />
</Suspense>
</main>
)
}
async function IdLabel({
params,
}: {
params: Promise<{ lang: string; id: string }>
}) {
const { id } = await params
console.log('after params - id')
return (
<>
<p>id: {id}</p>
<CachedData label="page" cacheKey={`${CACHE_KEY}-${id}`} />
</>
)
}
import { ReactNode, Suspense } from 'react'
import { CachedData } from '../../data-fetching'
export const instant = true
export const prefetch = 'partial'
const CACHE_KEY = __dirname + '/__LAYOUT__'
// Only lang has a generator. The child page leaves id as a fallback param.
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function PartialLangLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
return (
<>
<Suspense fallback={<p>Waiting for lang...</p>}>
<LangLabel params={params} />
</Suspense>
{children}
</>
)
}
async function LangLabel({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params
console.log('after params - lang')
return (
<>
<p>lang: {lang}</p>
<CachedData label="layout" cacheKey={`${CACHE_KEY}-${lang}`} />
</>
)
}
import { Suspense } from 'react' import { Suspense } from 'react'
// `id` is covered by `generateStaticParams` only for `x`, so `/mixed/en/x` is a // Both params have generators, so the route has a fully generated shape. Novel
// fully prerendered route (both params resolve in the static shell) while other // values can complete an optional shell without deferring either param.
// ids such as `123` are deferred to the runtime stage. The parent `[lang]`
// layout reads `lang`; this page reads only `id`.
export function generateStaticParams() { export function generateStaticParams() {
return [{ id: 'x' }] return [{ id: 'x' }]
} }
......
import { ReactNode, Suspense } from 'react' import { ReactNode, Suspense } from 'react'
// `lang` is covered by `generateStaticParams`. At this segment `params` only // The layout logs the resolution stage of `lang` independently of `id`. Its
// contains `lang`, so reading it here (rather than in the deeper page) lets us // `params` object contains only `lang`, so the staging check does not consider
// observe the stage `lang` resolves in independently of the uncovered `id`. // `id`.
export function generateStaticParams() { export function generateStaticParams() {
return [{ lang: 'en' }] return [{ lang: 'en' }]
} }
......
...@@ -32,6 +32,12 @@ export default function Page() { ...@@ -32,6 +32,12 @@ export default function Page() {
<li> <li>
<Link href="/mixed/en/x">/mixed/en/x</Link> <Link href="/mixed/en/x">/mixed/en/x</Link>
</li> </li>
<li>
<Link href="/partial/en/123">/partial/en/123</Link>
</li>
<li>
<Link href="/partial/fr/123">/partial/fr/123</Link>
</li>
<li> <li>
<Link href="/sync-io/static">/sync-io/static</Link> <Link href="/sync-io/static">/sync-io/static</Link>
</li> </li>
......
import { Suspense } from 'react'
import { CachedData } from '../../../data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__'
export default function PartialIdPage({
params,
}: {
params: Promise<{ lang: string; id: string }>
}) {
return (
<main>
<Suspense fallback={<p>Waiting for id...</p>}>
<IdLabel params={params} />
</Suspense>
</main>
)
}
async function IdLabel({
params,
}: {
params: Promise<{ lang: string; id: string }>
}) {
const { id } = await params
console.log('after params - id')
return (
<>
<p>id: {id}</p>
<CachedData label="page" cacheKey={`${CACHE_KEY}-${id}`} />
</>
)
}
import { ReactNode, Suspense } from 'react'
import { CachedData } from '../../data-fetching'
const CACHE_KEY = __dirname + '/__LAYOUT__'
// Only lang has a generator. The child page leaves id as a fallback param.
export function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function PartialLangLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
return (
<>
<Suspense fallback={<p>Waiting for lang...</p>}>
<LangLabel params={params} />
</Suspense>
{children}
</>
)
}
async function LangLabel({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params
console.log('after params - lang')
return (
<>
<p>lang: {lang}</p>
<CachedData label="layout" cacheKey={`${CACHE_KEY}-${lang}`} />
</>
)
}
...@@ -9,11 +9,11 @@ import { ...@@ -9,11 +9,11 @@ import {
TracedComponentActiveSpan, TracedComponentActiveSpan,
} from '../../traced-work' } from '../../traced-work'
// A navigation to an uncovered slug reads a deferred `params`, which is a // These routes exercise OTEL span creation during Cache Components validation.
// blocking navigation. This suite exercises span creation during cache // Automatic navigation-boundary insights are not the subject of this suite.
// component validation, not Instant Navigation, so opt the route out of that // Non-root params remain outside an App Shell even when statically available.
// validation: otherwise its blocking-route insight masks the `startActiveSpan` // The blocking opt-out keeps those insights from replacing the intentional
// console error these tests assert. // `startActiveSpan` console error that the tests inspect.
export const instant = false export const instant = false
export function generateStaticParams() { export function generateStaticParams() {
......
...@@ -9,11 +9,11 @@ import { ...@@ -9,11 +9,11 @@ import {
TracedComponentActiveSpan, TracedComponentActiveSpan,
} from '../../traced-work' } from '../../traced-work'
// A navigation to an uncovered slug reads a deferred `params`, which is a // These routes exercise OTEL span creation during Cache Components validation.
// blocking navigation. This suite exercises span creation during cache // Automatic navigation-boundary insights are not the subject of this suite.
// component validation, not Instant Navigation, so opt the route out of that // Non-root params remain outside an App Shell even when statically available.
// validation: otherwise its blocking-route insight masks the `startActiveSpan` // The blocking opt-out keeps those insights from replacing the intentional
// console error these tests assert. // `startActiveSpan` console error that the tests inspect.
export const instant = false export const instant = false
export function generateStaticParams() { export function generateStaticParams() {
......
export { default } from '../../[slug]/server/page'
export const instant = false
import { isNextDev, nextTestSetup } from 'e2e-utils' import { isNextDev, nextTestSetup } from 'e2e-utils'
import {
getRedboxDescription,
getRedboxEnvironmentLabel,
openRedbox,
} from 'next-test-utils'
describe('cache-components OTEL spans', () => { describe('cache-components OTEL spans', () => {
const { next, isTurbopack, isNextDeploy } = nextTestSetup({ const { next, isTurbopack, isNextDeploy } = nextTestSetup({
...@@ -10,7 +15,7 @@ describe('cache-components OTEL spans', () => { ...@@ -10,7 +15,7 @@ describe('cache-components OTEL spans', () => {
}) })
if (isNextDev) { if (isNextDev) {
it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Cache Component - without prerendering the page', async () => { it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Cache Component - with a novel slug', async () => {
const browser = await next.browser('/novel/cache') const browser = await next.browser('/novel/cache')
if (isTurbopack) { if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
...@@ -57,8 +62,9 @@ describe('cache-components OTEL spans', () => { ...@@ -57,8 +62,9 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.textContent()) console.log('t7', await t7.textContent())
console.log('t8', await t8.textContent()) console.log('t8', await t8.textContent())
}) })
it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Cache Component - with prerendering the page', async () => { it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Cache Component - with a generated slug', async () => {
// In dev there really isn't any prerendering but since this test case exists for prod testing I want to keep it exercised in the dev pathway too // Dev has no build-time page artifact; this case exercises the generated
// slug.
const browser = await next.browser('/prerendered/cache') const browser = await next.browser('/prerendered/cache')
if (isTurbopack) { if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
...@@ -105,13 +111,13 @@ describe('cache-components OTEL spans', () => { ...@@ -105,13 +111,13 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.textContent()) console.log('t7', await t7.textContent())
console.log('t8', await t8.textContent()) console.log('t8', await t8.textContent())
}) })
it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Server Component - without prerendering the page', async () => { it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Server Component - with a novel slug', async () => {
const browser = await next.browser('/novel/server') const browser = await next.browser('/novel/server')
if (isTurbopack) { if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
{ {
"description": "A Cache Function (\`use cache\`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.", "description": "A Cache Function (\`use cache\`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.",
"environmentLabel": "Prefetch", "environmentLabel": "Prerender",
"label": "Console Error", "label": "Console Error",
"source": "app/traced-work.tsx (26:19) @ <anonymous> "source": "app/traced-work.tsx (26:19) @ <anonymous>
> 26 | return tracer.startActiveSpan('span-active-span', fn) > 26 | return tracer.startActiveSpan('span-active-span', fn)
...@@ -128,7 +134,7 @@ describe('cache-components OTEL spans', () => { ...@@ -128,7 +134,7 @@ describe('cache-components OTEL spans', () => {
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
{ {
"description": "A Cache Function (\`use cache\`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.", "description": "A Cache Function (\`use cache\`) was passed to startActiveSpan which means it will receive a Span argument with a possibly random ID on every invocation leading to cache misses. Provide a wrapping function around the Cache Function that does not forward the Span argument to avoid this issue.",
"environmentLabel": "Prefetch", "environmentLabel": "Prerender",
"label": "Console Error", "label": "Console Error",
"source": "app/traced-work.tsx (26:19) @ eval "source": "app/traced-work.tsx (26:19) @ eval
> 26 | return tracer.startActiveSpan('span-active-span', fn) > 26 | return tracer.startActiveSpan('span-active-span', fn)
...@@ -154,8 +160,9 @@ describe('cache-components OTEL spans', () => { ...@@ -154,8 +160,9 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.textContent()) console.log('t7', await t7.textContent())
console.log('t8', await t8.textContent()) console.log('t8', await t8.textContent())
}) })
it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Server Component - with prerendering the page', async () => { it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Server Component - with a generated slug', async () => {
// In dev there really isn't any prerendering but since this test case exists for prod testing I want to keep it exercised in the dev pathway too // Dev has no build-time page artifact; this case exercises the generated
// slug.
const browser = await next.browser('/prerendered/server') const browser = await next.browser('/prerendered/server')
if (isTurbopack) { if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
...@@ -204,6 +211,19 @@ describe('cache-components OTEL spans', () => { ...@@ -204,6 +211,19 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.textContent()) console.log('t7', await t7.textContent())
console.log('t8', await t8.textContent()) console.log('t8', await t8.textContent())
}) })
it('keeps span diagnostics in the runtime stage when no slug is generated', async () => {
const browser = await next.browser('/runtime/novel')
await openRedbox(browser)
expect(await getRedboxDescription(browser)).toContain(
'A Cache Function (`use cache`) was passed to startActiveSpan'
)
expect(await getRedboxEnvironmentLabel(browser)).toBe('Prefetch')
for (const id of ['t7', 't8']) {
const spanId = await browser.elementByCss(`#${id} .span`).text()
expect(parseInt(spanId, 10)).toBeGreaterThan(0)
}
})
} else { } else {
it('should allow creating Spans during prerendering during the build - inside a Cache Components', async () => { it('should allow creating Spans during prerendering during the build - inside a Cache Components', async () => {
const browser = await next.browser('/prerendered/cache') const browser = await next.browser('/prerendered/cache')
......
...@@ -1277,12 +1277,12 @@ Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic` ...@@ -1277,12 +1277,12 @@ Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
// Regression test for NAR-491: after adding `generateStaticParams` // Regression test for NAR-491: after adding `generateStaticParams`
// that covers the requested slug, the slug is no longer a fallback // that covers the requested slug, the slug is no longer a fallback
// param, so the blocking-route validation must clear. This requires // param, so the blocking-route validation must clear. This requires
// the render to pick up the fresh `fallbackParams`. Because // the render to pick up the fresh `stagedFallbackParams`. Because
// `generateStaticParams` is recomputed in the background (the static // `generateStaticParams` is recomputed in the background (the static
// paths cache serves the previous result until then), the render // paths cache serves the previous result until then), the render
// triggered by the edit itself still uses the stale `fallbackParams`; // triggered by the edit itself still uses the stale
// a follow-up HMR update, sent once the recompute lands, is what // `stagedFallbackParams`; a follow-up HMR update, sent once the
// syncs them. // recompute lands, is what syncs them.
const browser = await next.browser('/use-cache-params/foo') const browser = await next.browser('/use-cache-params/foo')
await expect(browser).toDisplayCollapsedRedbox(` await expect(browser).toDisplayCollapsedRedbox(`
......
...@@ -647,11 +647,13 @@ export function registerHeadAndReportingTests( ...@@ -647,11 +647,13 @@ export function registerHeadAndReportingTests(
const result = await prerender( const result = await prerender(
'/shells/(default)/invalid-runtime-params/[slug]' '/shells/(default)/invalid-runtime-params/[slug]'
) )
// TODO(app-shells): missing fallback params in build validation // TODO(app-shells): Verify fallback params in build validation.
// It seems like `workUnitStore.fallbackParams` is undefined //
// during the validation render, which makes us treat these params as static. // This assertion can pass even if
// In partialPrefetching, static params are also delayed until the runtime stage, // `workUnitStore.stagedFallbackParams` is missing. Without that set,
// which ultimately makes the validation fail, but also hides the underlying issue. // validation treats these params as static. Partial Prefetching still
// delays them to the runtime stage, so the expected error does not
// detect the missing fallback params.
expect(extractBuildValidationError(result.cliOutput)) expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
......
...@@ -464,11 +464,12 @@ export function registerSuspenseBoundariesTests( ...@@ -464,11 +464,12 @@ export function registerSuspenseBoundariesTests(
const result = await prerender( const result = await prerender(
'/suspense-in-root/runtime/invalid-no-suspense-around-params/[param]' '/suspense-in-root/runtime/invalid-no-suspense-around-params/[param]'
) )
// TODO(app-shells): missing fallback params in build validation // TODO(app-shells): Verify fallback params in build validation.
// It seems like `workUnitStore.fallbackParams` is undefined //
// during the validation render, which makes us treat these params as static. // This assertion can pass even if `workUnitStore.stagedFallbackParams` is
// In partialPrefetching, static params are also delayed until the runtime stage, // missing. Without that set, validation treats these params as static.
// which ultimately makes the validation fail, but also hides the underlying issue. // Partial Prefetching still delays them to the runtime stage, so the
// expected error does not detect the missing fallback params.
expect(extractBuildValidationError(result.cliOutput)) expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
......
import { connection } from 'next/server'
import { Suspense } from 'react'
export function generateStaticParams() {
// The short entry requires a partial shell. The long entry also makes bottom
// prerenderable on demand.
return [{ top: 'short' }, { top: 'long', bottom: 'example' }]
}
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<>
<Suspense fallback={<div id="bottom-fallback">loading bottom...</div>}>
<Bottom params={params} />
</Suspense>
<Suspense fallback={<div id="dynamic-fallback">loading dynamic...</div>}>
<Dynamic />
</Suspense>
</>
)
}
async function Bottom({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { bottom } = await params
return <div id="bottom">{bottom}</div>
}
async function Dynamic() {
await connection()
return <div id="dynamic">Dynamic content</div>
}
import type { ReactNode } from 'react'
export default async function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return (
<div>
<div id="top">{top}</div>
{children}
</div>
)
}
import { Suspense, type ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<Suspense fallback={<div id="top-fallback">loading top...</div>}>
{children}
</Suspense>
)
}
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { randomUUID } from 'crypto'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr' import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr'
import { retry, waitFor } from 'next-test-utils' import { retry, waitFor } from 'next-test-utils'
...@@ -132,6 +133,51 @@ describe('partial-fallback-shell-upgrade', () => { ...@@ -132,6 +133,51 @@ describe('partial-fallback-shell-upgrade', () => {
expect(result.dynamicPart).not.toContain('<div id="two">foo</div>') expect(result.dynamicPart).not.toContain('<div id="two">foo</div>')
}) })
it('should upgrade a required fallback shell with mixed generateStaticParams lengths', async () => {
// A second cold path must still use the required source shell after the
// first exact path completes.
for (const bottom of [`first-${randomUUID()}`, `second-${randomUUID()}`]) {
const pathname = `/mixed/short/${bottom}`
const firstResult = await fetchSplitHTML(pathname)
expect(firstResult.static$('#top').text()).toBe('short')
expect(firstResult.static$('#top-fallback').length).toBe(0)
expect(firstResult.static$('#bottom').length).toBe(0)
expect(firstResult.static$('#bottom-fallback').text()).toBe(
'loading bottom...'
)
expect(firstResult.dynamicPart).toContain(
`<div id="bottom">${bottom}</div>`
)
expect(firstResult.static$('#dynamic').length).toBe(0)
expect(firstResult.static$('#dynamic-fallback').text()).toBe(
'loading dynamic...'
)
expect(firstResult.dynamicPart).toContain(
'<div id="dynamic">Dynamic content</div>'
)
await retry(async () => {
const completedResult = await fetchSplitHTML(pathname)
expect(completedResult.static$('#top').text()).toBe('short')
expect(completedResult.static$('#top-fallback').length).toBe(0)
expect(completedResult.static$('#bottom').text()).toBe(bottom)
expect(completedResult.static$('#bottom-fallback').length).toBe(0)
expect(completedResult.dynamicPart).not.toContain(
`<div id="bottom">${bottom}</div>`
)
expect(completedResult.static$('#dynamic').length).toBe(0)
expect(completedResult.static$('#dynamic-fallback').text()).toBe(
'loading dynamic...'
)
expect(completedResult.dynamicPart).toContain(
'<div id="dynamic">Dynamic content</div>'
)
})
}
})
it('should not keep upgrading once only fully dynamic params remain', async () => { it('should not keep upgrading once only fully dynamic params remain', async () => {
const firstResult = await fetchSplitHTML('/prefix/b/foo') const firstResult = await fetchSplitHTML('/prefix/b/foo')
const start = Date.now() const start = Date.now()
......
import { connection } from 'next/server'
import { Suspense } from 'react'
import { LinkAccordion } from '../../../../components/link-accordion'
export default function Page({
params,
}: {
params: Promise<{ top: string; step: string }>
}) {
return (
<main>
<Suspense fallback={<p>Loading hub...</p>}>
<Hub params={params} />
</Suspense>
</main>
)
}
async function Hub({
params,
}: {
params: Promise<{ top: string; step: string }>
}) {
await connection()
const { top, step } = await params
return (
<>
<h1>{`Fallback params hub ${step}`}</h1>
<div>
<LinkAccordion
href={`/required-fallback-params/${top}/b1`}
prefetch={false}
>
Required fallback shell
</LinkAccordion>
</div>
<div>
<LinkAccordion href={`/fully-static-params/${top}`} prefetch={false}>
Fully static page
</LinkAccordion>
</div>
{top === 'time' ? (
<LinkAccordion
href="/fully-static-params/time#full-prefetch"
prefetch={true}
>
Full prefetch
</LinkAccordion>
) : null}
</>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
export function generateStaticParams() {
return [{ top: 't1' }]
}
export default async function Page({
params,
}: {
params: Promise<{ top: string }>
}) {
const { top } = await params
const timestamp = top === 'time' ? Date.now() : null
return (
<main>
<p id="top">Top: {top}</p>
<p id="timestamp">{timestamp}</p>
{['a', 'b'].map((step) => (
<div key={step}>
<LinkAccordion
href={`/fallback-params-hub/${top}/${step}`}
prefetch={false}
>
Hub {step}
</LinkAccordion>
</div>
))}
</main>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export default function Page({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
return (
<>
<div id="bottom-boundary">
<Suspense fallback={<p>Loading bottom...</p>}>
<Bottom params={params} />
</Suspense>
</div>
<div id="connection-boundary">
<Suspense fallback={<p>Loading connection...</p>}>
<DynamicContent />
</Suspense>
</div>
</>
)
}
async function Bottom({
params,
}: {
params: Promise<{ top: string; bottom: string }>
}) {
const { bottom } = await params
return <p id="bottom">Bottom: {bottom}</p>
}
async function DynamicContent() {
await connection()
return <p id="dynamic-content">Dynamic content</p>
}
import type { ReactNode } from 'react'
import { LinkAccordion } from '../../../components/link-accordion'
export function generateStaticParams() {
return [{ top: 't1' }]
}
export default async function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<{ top: string }>
}) {
const { top } = await params
return (
<main>
<p id="top">Top: {top}</p>
{children}
{['a', 'b'].map((step) => (
<div key={step}>
<LinkAccordion
href={`/fallback-params-hub/${top}/${step}`}
prefetch={false}
>
Hub {step}
</LinkAccordion>
</div>
))}
</main>
)
}
...@@ -37,13 +37,36 @@ describe('action-only fallback resume data cache', () => { ...@@ -37,13 +37,36 @@ describe('action-only fallback resume data cache', () => {
'destination page rendered' 'destination page rendered'
) )
}) })
it('renders the concrete destination after an action revalidates it', async () => {
const browser = await next.browser('/concrete/foo')
const cachedValue = await browser
.elementByCss('#concrete-cached-value')
.text()
await browser.elementByCss('#revalidate-concrete').click()
await retry(async () => {
expect(
await browser.elementByCss('#concrete-action-result').text()
).toBe('concrete action result')
expect(await browser.elementByCss('#concrete-destination').text()).toBe(
'concrete destination page rendered: foo'
)
expect(
await browser.elementByCss('#concrete-cached-value').text()
).not.toBe(cachedValue)
})
})
} else { } else {
async function invokeAction(exportedName: string) { async function invokeAction(
const metadata = await next.readJSON( exportedName: string,
'.next/server/app/events/[id]/group.meta' route = '/events/[id]/group',
) pathname = route
) {
const metadata = await next.readJSON(`.next/server/app${route}.meta`)
const postponed = metadata.postponed as string const postponed = metadata.postponed as string
expect(postponed).toEqual(expect.any(String)) expect(postponed).toEqual(expect.any(String))
expect(postponed).toMatch(/^\d+:\d+\[\["id",/)
const manifest = await next.readJSON( const manifest = await next.readJSON(
'.next/server/server-reference-manifest.json' '.next/server/server-reference-manifest.json'
...@@ -51,19 +74,21 @@ describe('action-only fallback resume data cache', () => { ...@@ -51,19 +74,21 @@ describe('action-only fallback resume data cache', () => {
const actionId = Object.keys(manifest.node).find( const actionId = Object.keys(manifest.node).find(
(id) => manifest.node[id].exportedName === exportedName (id) => manifest.node[id].exportedName === exportedName
) )
expect(actionId).toEqual(expect.any(String)) if (!actionId) {
throw new Error(`Missing server action: ${exportedName}`)
}
// Simulate the request received by the action worker after the platform // Simulate the request received by the action worker after the platform
// has selected the dynamic route's fallback and prepended its postponed // has selected the dynamic route's fallback and prepended its postponed
// state to the action body. // state to the action body.
const actionBody = Buffer.from('[]') const actionBody = Buffer.from('[]')
const postponedBody = Buffer.from(postponed) const postponedBody = Buffer.from(postponed)
return next.fetch('/events/[id]/group', { return next.fetch(pathname, {
method: 'POST', method: 'POST',
headers: { headers: {
'content-type': 'text/plain;charset=UTF-8', 'content-type': 'text/plain;charset=UTF-8',
'next-action': actionId!, 'next-action': actionId,
'x-matched-path': '/events/[id]/group', 'x-matched-path': route,
'x-next-resume-state-length': String(postponedBody.byteLength), 'x-next-resume-state-length': String(postponedBody.byteLength),
}, },
body: Buffer.concat([postponedBody, actionBody]), body: Buffer.concat([postponedBody, actionBody]),
...@@ -80,6 +105,30 @@ describe('action-only fallback resume data cache', () => { ...@@ -80,6 +105,30 @@ describe('action-only fallback resume data cache', () => {
expect(responseBody).not.toContain('destination page rendered') expect(responseBody).not.toContain('destination page rendered')
}) })
it('renders the concrete destination with postponed state and preserves the action result and revalidation', async () => {
const outputIndex = next.cliOutput.length
// The request has a concrete id, but the injected fallback artifact still
// records id in its staging mask.
const response = await invokeAction(
'revalidateConcretePage',
'/concrete/[id]',
'/concrete/foo'
)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/x-component')
expect(response.headers.get('x-action-revalidated')).toBe('1')
const responseBody = await response.text()
expect(responseBody).toContain('concrete action result')
expect(responseBody).toContain('concrete destination page rendered: foo')
const output = next.cliOutput.slice(outputIndex)
expect(output).toContain('ActionOnlyFallbackCacheHandler::updateTags')
expect(output).toContain('_N_T_/concrete/foo')
expect(output).not.toContain('Failed to parse postponed state')
})
it('applies pending revalidations without rendering the fallback route when the action calls notFound', async () => { it('applies pending revalidations without rendering the fallback route when the action calls notFound', async () => {
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
......
'use server'
import { revalidatePath } from 'next/cache'
export async function revalidateConcretePage() {
revalidatePath('/concrete/foo')
return 'concrete action result'
}
'use client'
import { useState } from 'react'
import { revalidateConcretePage } from './actions'
export function Button() {
const [result, setResult] = useState('not called')
return (
<>
<button
id="revalidate-concrete"
onClick={async () => {
setResult(await revalidateConcretePage())
}}
>
revalidate concrete page
</button>
<p id="concrete-action-result">{result}</p>
</>
)
}
import { Suspense } from 'react'
import { Button } from './button'
async function CachedValue() {
'use cache'
return <p id="concrete-cached-value">{Math.random()}</p>
}
async function Destination({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<p id="concrete-destination">
{`concrete destination page rendered: ${id}`}
</p>
)
}
export default function Page({ params }: { params: Promise<{ id: string }> }) {
return (
<>
<CachedValue />
<Suspense fallback={<p>loading concrete destination</p>}>
<Destination params={params} />
</Suspense>
<Button />
</>
)
}
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