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
*/
remainingPrerenderableParams?: readonly FallbackRouteParam[]
/**
* Whether this candidate must produce a nonempty static shell.
*/
throwOnEmptyStaticShell?: boolean
/**
* When defined, it describes the revalidation configuration for the fallback
* route.
......@@ -3888,6 +3893,8 @@ export default async function build(
experimentalPPR: isRoutePPREnabled,
remainingPrerenderableParams:
route.remainingPrerenderableParams,
throwOnEmptyStaticShell:
prerenderCandidate?.throwOnEmptyStaticShell,
renderingMode: isAppPPREnabled
? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC
......
......@@ -452,9 +452,9 @@ export function processMessage(
}
case HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED: {
// Re-fetch the current router tree so the render picks up the new set of
// statically-known params (and thus the fresh `fallbackParams`). Unlike
// `SERVER_COMPONENT_CHANGES` this does not store an HMR refresh hash, so
// it doesn't invalidate `"use cache"` entries.
// statically-known params (and thus the fresh `stagedFallbackParams`).
// Unlike `SERVER_COMPONENT_CHANGES` this does not store an HMR refresh
// hash, so it doesn't invalidate `"use cache"` entries.
if (
RuntimeErrorHandler.hadRuntimeError ||
document.documentElement.id === '__next_error__'
......
......@@ -784,7 +784,7 @@ export async function handleAction({
// which to resume the destination page.
const isActionOnlyFallbackRequest =
isFetchAction &&
requestStore.fallbackParams != null &&
ctx.fallbackRouteParams != null &&
typeof ctx.renderOpts.postponed === 'string'
const shouldSkipPageRendering =
actionWasForwarded || isActionOnlyFallbackRequest
......
......@@ -1356,7 +1356,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
ctx: AppRenderContext,
initialRequestStore: RequestStore,
createRequestStore: (() => RequestStore) | undefined,
fallbackParams: OpaqueFallbackRouteParams | null
stagedFallbackParams: OpaqueFallbackRouteParams | null
): Promise<RenderResult> {
const {
htmlRequestId,
......@@ -1509,7 +1509,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
getPayload,
onError,
shouldValidate,
fallbackRouteParams: fallbackParams,
fallbackRouteParams: stagedFallbackParams,
getDevRenderDidError: () => didErrorObservably,
navigationKind: {
type: 'prefetched-client',
......@@ -3006,7 +3006,10 @@ async function renderAppPage(
null
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 createRequestStore = createRequestStoreForRender.bind(
......@@ -3021,7 +3024,7 @@ async function renderAppPage(
isHmrRefresh,
serverComponentsHmrCache,
renderResumeDataCache,
fallbackParams,
stagedFallbackParams,
hmrRefreshHash
)
const requestStore = createRequestStore()
......@@ -3066,7 +3069,7 @@ async function renderAppPage(
ctx,
requestStore,
createRequestStore,
fallbackParams
stagedFallbackParams
)
} else if (cacheComponents && cachedNavigations) {
// MARK: RSC cacheComponents
......@@ -3113,7 +3116,7 @@ async function renderAppPage(
postponedState,
metadata,
undefined, // Prevent restartable-render behavior in dev + Cache Components mode
fallbackParams
stagedFallbackParams
)
return new RenderResult(stream, {
......@@ -3155,7 +3158,7 @@ async function renderAppPage(
// and we currently we don't copy changes over when creating a new store,
// so the restarted render wouldn't be correct.
didExecuteServerAction ? undefined : createRequestStore,
fallbackParams
stagedFallbackParams
)
// Forward an invalid-dynamic-usage error recorded by `'use cache'` only
......@@ -3531,7 +3534,7 @@ async function renderToStream(
postponedState: PostponedState | null,
metadata: AppPageRenderResultMetadata,
createRequestStore: (() => RequestStore) | undefined,
fallbackParams: OpaqueFallbackRouteParams | null
stagedFallbackParams: OpaqueFallbackRouteParams | null
): Promise<AnyStream> {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
// MARK: renderToStream setup
......@@ -3779,7 +3782,7 @@ async function renderToStream(
getPayload,
onError: serverComponentsErrorHandler,
shouldValidate: true,
fallbackRouteParams: fallbackParams,
fallbackRouteParams: stagedFallbackParams,
getDevRenderDidError: () => didErrorObservably,
// An initial HTML load serves the static shell; runtime and
// dynamic content stream in afterward.
......@@ -6683,8 +6686,9 @@ export async function runValidationInDevFromSnapshot(
// `requestFallbackRouteParams` reproduces `ctx.getDynamicParamFromSegment`
// exactly, so the depth-loop segment keys match the seed render's Flight.
// `fallbackRouteParams` is separate and only marks params unknown in the
// prerender stores.
// `fallbackRouteParams` is the staged set of the main-thread request store.
// 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
// base. We should maybe refactor this to make their different roles clearer.
......@@ -6733,7 +6737,7 @@ export async function runValidationInDevFromSnapshot(
isHmrRefresh: message.request.isHmrRefresh,
hmrRefreshHash: message.request.hmrRefreshHash,
serverComponentsHmrCache: undefined,
fallbackParams: requestFallbackRouteParams,
stagedFallbackParams: fallbackRouteParams,
})
const staticInputs = toDevValidationInputs(message.staticInputs, requestStore)
......@@ -9584,7 +9588,8 @@ async function prerenderToStream(
resumeDataCache,
cacheComponents,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
renderOpts.experimental.disableResumeDataCacheCompression,
fallbackRouteParams
)
}
reactServerResult.consume()
......@@ -10125,7 +10130,8 @@ async function prerenderToStream(
originalResumeDataCache,
cacheComponents,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
renderOpts.experimental.disableResumeDataCacheCompression,
fallbackRouteParams
)
originalFlightPrerenderResult.consume()
errorServerResult.consume()
......
import {
createPrerenderResumeDataCache,
deflateResumeDataCache,
stringifyResumeDataCache,
} from '../resume-data-cache/resume-data-cache'
import {
......@@ -85,6 +86,12 @@ describe('getDynamicHTMLPostponedState', () => {
"imageResponses": Map {},
"mutable": false,
},
"stagedFallbackParams": Map {
"slug" => [
"%%drp:slug:e9615126684e5%%",
"d",
],
},
"type": 2,
}
`)
......@@ -125,6 +132,7 @@ describe('getDynamicHTMLPostponedState', () => {
const parsed = parsePostponedState(state, params, undefined)
expect(parsed).toEqual({
type: DynamicState.HTML,
stagedFallbackParams: fallbackRouteParams,
data: [1, { [value]: value }],
renderResumeDataCache: {
cache: new Map(),
......@@ -142,44 +150,84 @@ describe('getDynamicHTMLPostponedState', () => {
})
describe('getDynamicDataPostponedState', () => {
it('serializes a data postponed state with fallback params', async () => {
const state = await getDynamicDataPostponedState(
createPrerenderResumeDataCache(),
isCacheComponentsEnabled
)
expect(state).toMatchInlineSnapshot(`"4:nullnull"`)
})
it.each([undefined, null, new Map()])(
'serializes a data postponed state with no fallback params (%p)',
async (fallbackRouteParams) => {
const state = await getDynamicDataPostponedState(
createPrerenderResumeDataCache(),
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 () => {
const resumeDataCache = createPrerenderResumeDataCache()
resumeDataCache.fetch.set('cache-key', {
kind: CachedRouteKind.FETCH,
data: {
headers: {},
body: 'cached body',
url: 'https://example.com',
},
revalidate: 60,
})
it.each([false, true])(
'serializes and parses fallback params and a cache (disableResumeDataCacheCompression: %s)',
async (disableResumeDataCacheCompression) => {
const fallbackRouteParams = createMockOpaqueFallbackRouteParams({
slug: ['%%drp:slug:e9615126684e5%%', 'd'],
})
const resumeDataCache = createPrerenderResumeDataCache()
resumeDataCache.fetch.set('cache-key', {
kind: CachedRouteKind.FETCH,
data: {
headers: {},
body: 'cached body',
url: 'https://example.com',
},
revalidate: 60,
})
const serializedResumeDataCache = await stringifyResumeDataCache(
resumeDataCache,
isCacheComponentsEnabled
)
const state = await getDynamicDataPostponedState(
resumeDataCache,
isCacheComponentsEnabled,
undefined,
true
)
const serializedResumeDataCache = await stringifyResumeDataCache(
resumeDataCache,
isCacheComponentsEnabled
)
const state = await getDynamicDataPostponedState(
resumeDataCache,
isCacheComponentsEnabled,
undefined,
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)
expect(parsed.renderResumeDataCache.fetch.get('cache-key')).toEqual(
resumeDataCache.fetch.get('cache-key')
)
})
const parsed = parsePostponedState(
state,
{ 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 () => {
const resumeDataCache = createPrerenderResumeDataCache()
......@@ -282,6 +330,7 @@ describe('parsePostponedState', () => {
// Ensure that it parsed it correctly.
expect(parsed).toEqual({
type: DynamicState.HTML,
stagedFallbackParams: new Map([['slug', '%%drp:slug:e9615126684e5%%']]),
data: expect.any(Object),
renderResumeDataCache: {
cache: new Map(),
......@@ -305,6 +354,7 @@ describe('parsePostponedState', () => {
// Ensure that it parsed it correctly.
expect(parsed).toEqual({
type: DynamicState.HTML,
stagedFallbackParams: null,
data: expect.any(Object),
renderResumeDataCache: {
cache: new Map(),
......@@ -317,7 +367,7 @@ describe('parsePostponedState', () => {
})
})
it('parses a data postponed state', () => {
it('parses a legacy data postponed state', () => {
const state = '4:nullnull'
const parsed = parsePostponedState(state, {}, undefined)
......@@ -333,5 +383,6 @@ describe('parsePostponedState', () => {
mutable: false,
},
})
expect(parsed).not.toHaveProperty('stagedFallbackParams')
})
})
......@@ -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 = {
/**
......@@ -34,6 +34,13 @@ export type DynamicDataPostponedState = {
*/
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.
*/
......@@ -49,6 +56,13 @@ export type DynamicHTMLPostponedState = {
*/
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.
*/
......@@ -156,10 +170,23 @@ export async function getDynamicDataPostponedState(
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache,
isCacheComponentsEnabled: boolean,
maxPostponedStateSizeBytes?: number,
disableResumeDataCacheCompression = false
disableResumeDataCacheCompression = false,
fallbackRouteParams?: OpaqueFallbackRouteParams | null
): 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(
'null',
postponedString,
resumeDataCache,
isCacheComponentsEnabled,
maxPostponedStateSizeBytes,
......@@ -234,6 +261,9 @@ export function parsePostponedState(
try {
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 }
}
......@@ -254,8 +284,18 @@ export function parsePostponedState(
match.length + length
)
) as OpaqueFallbackRouteParamEntries
const stagedFallbackParams =
replacements.length > 0 ? new Map(replacements) : null
let postponed = postponedString.slice(match.length + length)
if (postponed === 'null') {
return {
type: DynamicState.DATA,
stagedFallbackParams,
renderResumeDataCache,
}
}
for (const [
segmentKey,
[searchValue, dynamicParamType],
......@@ -281,6 +321,7 @@ export function parsePostponedState(
return {
type: DynamicState.HTML,
stagedFallbackParams,
data: JSON.parse(postponed),
renderResumeDataCache,
}
......@@ -288,6 +329,7 @@ export function parsePostponedState(
return {
type: DynamicState.HTML,
stagedFallbackParams: null,
data: JSON.parse(postponedString),
renderResumeDataCache,
}
......
......@@ -98,7 +98,11 @@ export interface RequestStore extends CommonWorkUnitStore {
hasIncompatibleShellContent?: boolean
cacheSignal?: CacheSignal | null
fallbackParams?: OpaqueFallbackRouteParams | null
/**
* These params resolve after the static stage without replacing their
* concrete values.
*/
stagedFallbackParams?: OpaqueFallbackRouteParams | null
varyParamsAccumulator?: ResponseVaryParamsAccumulator | null
// Only in build-time instant-validation or when rendering
......
......@@ -146,7 +146,7 @@ export type RequestStoreInputs = {
* edit, for every client, regardless of whether it runs the HMR client.
*/
hmrRefreshHash: string | undefined
fallbackParams: OpaqueFallbackRouteParams | null | undefined
stagedFallbackParams: OpaqueFallbackRouteParams | null | undefined
}
/**
......@@ -193,7 +193,7 @@ export function createRequestStoreForRender(
isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
resumeDataCache: ResumeDataCache | null,
fallbackParams: OpaqueFallbackRouteParams | null,
stagedFallbackParams: OpaqueFallbackRouteParams | null,
hmrRefreshHash: string | undefined
): RequestStore {
return createRequestStore({
......@@ -215,7 +215,7 @@ export function createRequestStoreForRender(
isHmrRefresh,
serverComponentsHmrCache,
hmrRefreshHash,
fallbackParams,
stagedFallbackParams,
})
}
......@@ -240,7 +240,7 @@ export function createRequestStoreForAPI(
isHmrRefresh: false,
serverComponentsHmrCache: undefined,
hmrRefreshHash,
fallbackParams: null,
stagedFallbackParams: null,
})
}
......@@ -264,7 +264,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
isHmrRefresh,
serverComponentsHmrCache,
hmrRefreshHash,
fallbackParams,
stagedFallbackParams,
} = inputs
const cache: {
......@@ -347,7 +347,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
serverComponentsHmrCache ||
(globalThis as any).__serverComponentsHmrCache,
hmrRefreshHash,
fallbackParams,
stagedFallbackParams,
}
}
......
......@@ -159,7 +159,10 @@ import { fixMojibake } from './lib/fix-mojibake'
import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'
import type { CacheControl } from './lib/cache-control'
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 type { ErrorModule } from './load-default-error-components'
import {
......@@ -2746,44 +2749,39 @@ export default abstract class Server<
if (isAppPath && this.nextConfig.cacheComponents) {
if (pathsResults.prerenderedRoutes?.length) {
// Replicate, on demand, the per-URL fallback set a production build
// writes to the prerender manifest. Production matches the requested
// URL to the most-specific prerendered route and defers that route's
// `fallbackRouteParams` (so `generateStaticParams`-covered params
// 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
// The source selection includes concrete routes with no fallback
// params. Otherwise it could choose a generic fallback for a fully
// generated URL.
let matchedRoute: PrerenderedRoute | undefined
for (const route of pathsResults.prerenderedRoutes) {
const fallbackRouteParams = route.fallbackRouteParams ?? []
if (!getRouteRegex(route.pathname).re.test(urlPathname)) {
continue
}
if (
perUrlFallbackRouteParams === null ||
fallbackRouteParams.length < perUrlFallbackRouteParams.length
matchedRoute === undefined ||
(route.fallbackRouteParams?.length ?? 0) <
(matchedRoute.fallbackRouteParams?.length ?? 0)
) {
perUrlFallbackRouteParams = fallbackRouteParams
matchedRoute = route
}
}
if (
perUrlFallbackRouteParams &&
perUrlFallbackRouteParams.length > 0
) {
if (matchedRoute) {
// Explicit shell requests render the matched artifact. Ordinary
// requests stage and validate the same required or completed shell
// target.
addRequestMeta(
req,
'fallbackRouteParams',
matchedRoute.fallbackRouteParams
? createOpaqueFallbackRouteParams(
matchedRoute.fallbackRouteParams
)
: null
)
addRequestMeta(
req,
'fallbackParams',
createOpaqueFallbackRouteParams(perUrlFallbackRouteParams)!
'stagedFallbackParams',
getStagedFallbackParams(matchedRoute)
)
}
}
......
......@@ -889,12 +889,12 @@ export default class DevServer extends Server {
}
this.staticPathsCache.set(pathname, value)
// Since generateStaticParams runs in the background, the fallbackParams
// accessed during a render are derived from the previous result served
// by the static paths cache. Now that the cache holds the new result,
// trigger a refresh so the next render picks up the new fallbackParams
// (e.g. so blocking-route validation reflects params that just became
// statically known).
// Since generateStaticParams runs in the background, the
// stagedFallbackParams accessed during a render are derived from the
// previous result served by the static paths cache. Now that the cache
// holds the new result, trigger a refresh so the next render picks up
// the new stagedFallbackParams (e.g. so blocking-route validation
// reflects params that just became statically known).
if (
isAppPath &&
this.nextConfig.cacheComponents &&
......
......@@ -169,7 +169,7 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> {
isHmrRefresh: msg.request.isHmrRefresh,
serverComponentsHmrCache: undefined,
hmrRefreshHash: msg.request.hmrRefreshHash,
fallbackParams: null,
stagedFallbackParams: null,
})
await workAsyncStorage.run(workStore, () =>
......
......@@ -319,10 +319,36 @@ export interface RequestMeta {
minimalMode?: boolean
/**
* The fallback params for this route. In dev, used for validating prerenders.
* In production, used to defer params resolution during staged rendering.
* Staged renders defer these route params until after the static stage. They
* 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()
......
......@@ -6,6 +6,7 @@ import type AppPageRouteModule from '../route-modules/app-page/module'
import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'
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 { InvariantError } from '../../shared/lib/invariant-error'
export type OpaqueFallbackRouteParamValue = [
/**
......@@ -75,6 +76,56 @@ export function createOpaqueFallbackRouteParams(
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(
param: Pick<FallbackRouteParam, 'paramName' | 'paramType'>
): string {
......
......@@ -101,12 +101,12 @@ export function createParamsFromClient(
)
}
if (process.env.NODE_ENV === 'development') {
const fallbackParams = workUnitStore.fallbackParams
const stagedFallbackParams = workUnitStore.stagedFallbackParams
const userspaceParams = underlyingParams
return createRenderParamsInDev(
underlyingParams,
userspaceParams,
fallbackParams,
stagedFallbackParams,
workStore,
workUnitStore
)
......@@ -178,12 +178,12 @@ export function createServerParamsForRoute(
}
case 'request':
if (process.env.NODE_ENV === 'development') {
const fallbackParams = workUnitStore.fallbackParams
const stagedFallbackParams = workUnitStore.stagedFallbackParams
const userspaceParams = underlyingParams
return createRenderParamsInDev(
underlyingParams,
userspaceParams,
fallbackParams,
stagedFallbackParams,
workStore,
workUnitStore
)
......@@ -501,11 +501,11 @@ function createRenderParamsForPage(
// No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations
if (process.env.NODE_ENV === 'development') {
const fallbackParams = workUnitStore.fallbackParams
const stagedFallbackParams = workUnitStore.stagedFallbackParams
return createRenderParamsInDev(
underlyingParams,
userspaceParams,
fallbackParams,
stagedFallbackParams,
workStore,
workUnitStore
)
......@@ -556,7 +556,9 @@ function createStagedRenderParamsImpl(
// 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.
if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {
if (
hasFallbackRouteParams(underlyingParams, workUnitStore.stagedFallbackParams)
) {
return createParamsPromiseFromTrigger(
asyncApiPromises.sharedParamsParent,
userspaceParams
......@@ -661,14 +663,14 @@ function createRenderParamsInProd(userspaceParams: Params): Promise<Params> {
function createRenderParamsInDev(
underlyingParams: Params,
userpaceParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined,
stagedFallbackParams: OpaqueFallbackRouteParams | null | undefined,
workStore: WorkStore,
requestStore: RequestStore
): Promise<Params> {
return makeDynamicallyTrackedParamsWithDevWarnings(
underlyingParams,
userpaceParams,
hasFallbackRouteParams(underlyingParams, fallbackParams),
hasFallbackRouteParams(underlyingParams, stagedFallbackParams),
workStore,
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'
describe('Cache Components Fallback Validation', () => {
const { next } = nextTestSetup({
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 () => {
// when the params are complete we don't expect to see any errors await params regarless of where there
// are Suspense boundaries.
const browser = await next.browser(
'/complete/prerendered/wrapped/prerendered'
)
await waitForNoRedbox(browser)
await expectNoValidationErrors(browser)
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 waitForNoRedbox(browser)
await expectNoValidationErrors(browser)
await browser.loadPage(
`${next.url}/complete/prerendered/unwrapped/prerendered`
)
await waitForNoRedbox(browser)
await expectNoValidationErrors(browser)
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 waitForNoRedbox(browser)
await expectNoValidationErrors(browser)
})
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', () => {
const browser = await next.browser(
'/partial/prerendered/wrapped/prerendered'
)
await waitForNoRedbox(browser)
await expectNoValidationErrors(browser)
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 waitForNoRedbox(browser)
await expectNoValidationErrors(browser)
await browser.loadPage(
`${next.url}/partial/prerendered/unwrapped/prerendered`
......@@ -84,16 +93,44 @@ describe('Cache Components Fallback Validation', () => {
"description": "Next.js encountered runtime data during prerendering.",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/partial/[top]/unwrapped/layout.tsx (8:3) @ Layout
> 8 | await params
| ^",
"source": "app/partial/[top]/unwrapped/[bottom]/page.tsx (6:26) @ Page
> 6 | Top: {(await props.params).top}, Bottom: {(await props.params).bottom}
| ^",
"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 () => {
// 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.
......
......@@ -3,6 +3,11 @@
*/
const nextConfig = {
cacheComponents: true,
experimental: {
instantInsights: {
validationLevel: 'manual-warning',
},
},
}
module.exports = nextConfig
......@@ -338,6 +338,8 @@ export function runDevWarmupTests({
// TODO: we should only label this as "Prefetch" if there's a prefetch config.
assertLog(logs, `after cookies`, '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 searchParams`, 'Prefetch')
......@@ -378,17 +380,16 @@ export function runDevWarmupTests({
})
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 assertLogs = async (browser: Playwright) => {
const logs = await browser.log()
// `en` is covered by `generateStaticParams`, so `lang` resolves in
// the static shell, unless we're rendering an App Shell, in which
// case they're deferred to the runtiem stage.
// The generators produce { lang: 'en', id: 'x' }. The optional
// /mixed/en/[id] shell can complete the novel id statically.
// `STATIC_LINK_DATA` accounts for App Shell deferral on navigation.
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', RUNTIME_LINK_DATA)
assertLog(logs, 'after params - id', STATIC_LINK_DATA)
}
if (isInitialLoad) {
......@@ -398,19 +399,15 @@ export function runDevWarmupTests({
}
})
it('uncovered leading param', async () => {
it('novel lang and id', async () => {
const path = '/mixed/fr/123'
const assertLogs = async (browser: Playwright) => {
const logs = await browser.log()
// `fr` is not covered by `generateStaticParams`, so the most-specific
// prerendered route matching this URL is the base route and its
// fallback set is both params. `lang` must therefore defer to the
// runtime stage too, not resolve in the static shell. (Picking the
// 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)
// Both params have generators. The optional /mixed/[lang]/[id]
// shell can complete both novel values statically.
assertLog(logs, 'after params - lang', STATIC_LINK_DATA)
assertLog(logs, 'after params - id', STATIC_LINK_DATA)
}
if (isInitialLoad) {
......@@ -420,17 +417,13 @@ export function runDevWarmupTests({
}
})
it('fully covered params', async () => {
it('fully generated params', async () => {
const path = '/mixed/en/x'
const assertLogs = async (browser: Playwright) => {
const logs = await browser.log()
// Both `en` and `x` are covered by `generateStaticParams`, so this
// is a fully prerendered concrete route and both params resolve in
// 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`.)
// This URL matches the concrete generated route. Neither param
// needs completion or fallback staging.
assertLog(logs, 'after params - lang', STATIC_LINK_DATA)
assertLog(logs, 'after params - id', STATIC_LINK_DATA)
}
......@@ -441,6 +434,30 @@ export function runDevWarmupTests({
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 () => {
......
import { Suspense } from 'react'
// `id` is covered by `generateStaticParams` only for `x`, so `/mixed/en/x` is a
// fully prerendered route (both params resolve in the static shell) while other
// ids such as `123` are deferred to the runtime stage. The parent `[lang]`
// layout reads `lang`; this page reads only `id`.
// Both params have generators, so the route has a fully generated shape. Novel
// values can complete an optional shell without deferring either param.
export function generateStaticParams() {
return [{ id: 'x' }]
}
......
......@@ -3,9 +3,9 @@ import { ReactNode, Suspense } from 'react'
export const instant = true
export const prefetch = 'partial'
// `lang` is covered by `generateStaticParams`. At this segment `params` only
// contains `lang`, so reading it here (rather than in the deeper page) lets us
// observe the stage `lang` resolves in independently of the uncovered `id`.
// The layout logs the resolution stage of `lang` independently of `id`. Its
// `params` object contains only `lang`, so the staging check does not consider
// `id`.
export function generateStaticParams() {
return [{ lang: 'en' }]
}
......
......@@ -32,6 +32,12 @@ export default function Page() {
<li>
<Link href="/mixed/en/x">/mixed/en/x</Link>
</li>
<li>
<Link href="/partial/en/123">/partial/en/123</Link>
</li>
<li>
<Link href="/partial/fr/123">/partial/fr/123</Link>
</li>
<li>
<Link href="/sync-io/static">/sync-io/static</Link>
</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'
// `id` is covered by `generateStaticParams` only for `x`, so `/mixed/en/x` is a
// fully prerendered route (both params resolve in the static shell) while other
// ids such as `123` are deferred to the runtime stage. The parent `[lang]`
// layout reads `lang`; this page reads only `id`.
// Both params have generators, so the route has a fully generated shape. Novel
// values can complete an optional shell without deferring either param.
export function generateStaticParams() {
return [{ id: 'x' }]
}
......
import { ReactNode, Suspense } from 'react'
// `lang` is covered by `generateStaticParams`. At this segment `params` only
// contains `lang`, so reading it here (rather than in the deeper page) lets us
// observe the stage `lang` resolves in independently of the uncovered `id`.
// The layout logs the resolution stage of `lang` independently of `id`. Its
// `params` object contains only `lang`, so the staging check does not consider
// `id`.
export function generateStaticParams() {
return [{ lang: 'en' }]
}
......
......@@ -32,6 +32,12 @@ export default function Page() {
<li>
<Link href="/mixed/en/x">/mixed/en/x</Link>
</li>
<li>
<Link href="/partial/en/123">/partial/en/123</Link>
</li>
<li>
<Link href="/partial/fr/123">/partial/fr/123</Link>
</li>
<li>
<Link href="/sync-io/static">/sync-io/static</Link>
</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 {
TracedComponentActiveSpan,
} from '../../traced-work'
// A navigation to an uncovered slug reads a deferred `params`, which is a
// blocking navigation. This suite exercises span creation during cache
// component validation, not Instant Navigation, so opt the route out of that
// validation: otherwise its blocking-route insight masks the `startActiveSpan`
// console error these tests assert.
// These routes exercise OTEL span creation during Cache Components validation.
// Automatic navigation-boundary insights are not the subject of this suite.
// Non-root params remain outside an App Shell even when statically available.
// The blocking opt-out keeps those insights from replacing the intentional
// `startActiveSpan` console error that the tests inspect.
export const instant = false
export function generateStaticParams() {
......
......@@ -9,11 +9,11 @@ import {
TracedComponentActiveSpan,
} from '../../traced-work'
// A navigation to an uncovered slug reads a deferred `params`, which is a
// blocking navigation. This suite exercises span creation during cache
// component validation, not Instant Navigation, so opt the route out of that
// validation: otherwise its blocking-route insight masks the `startActiveSpan`
// console error these tests assert.
// These routes exercise OTEL span creation during Cache Components validation.
// Automatic navigation-boundary insights are not the subject of this suite.
// Non-root params remain outside an App Shell even when statically available.
// The blocking opt-out keeps those insights from replacing the intentional
// `startActiveSpan` console error that the tests inspect.
export const instant = false
export function generateStaticParams() {
......
export { default } from '../../[slug]/server/page'
export const instant = false
import { isNextDev, nextTestSetup } from 'e2e-utils'
import {
getRedboxDescription,
getRedboxEnvironmentLabel,
openRedbox,
} from 'next-test-utils'
describe('cache-components OTEL spans', () => {
const { next, isTurbopack, isNextDeploy } = nextTestSetup({
......@@ -10,7 +15,7 @@ describe('cache-components OTEL spans', () => {
})
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')
if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(`
......@@ -57,8 +62,9 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.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 () => {
// 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
it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Cache Component - with a generated slug', async () => {
// Dev has no build-time page artifact; this case exercises the generated
// slug.
const browser = await next.browser('/prerendered/cache')
if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(`
......@@ -105,13 +111,13 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.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')
if (isTurbopack) {
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.",
"environmentLabel": "Prefetch",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": "app/traced-work.tsx (26:19) @ <anonymous>
> 26 | return tracer.startActiveSpan('span-active-span', fn)
......@@ -128,7 +134,7 @@ describe('cache-components OTEL spans', () => {
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.",
"environmentLabel": "Prefetch",
"environmentLabel": "Prerender",
"label": "Console Error",
"source": "app/traced-work.tsx (26:19) @ eval
> 26 | return tracer.startActiveSpan('span-active-span', fn)
......@@ -154,8 +160,9 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.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 () => {
// 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
it('should allow creating spans during cache component validation without triggering sync IO bailouts - inside a Server Component - with a generated slug', async () => {
// Dev has no build-time page artifact; this case exercises the generated
// slug.
const browser = await next.browser('/prerendered/server')
if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(`
......@@ -204,6 +211,19 @@ describe('cache-components OTEL spans', () => {
console.log('t7', await t7.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 {
it('should allow creating Spans during prerendering during the build - inside a Cache Components', async () => {
const browser = await next.browser('/prerendered/cache')
......
......@@ -1277,12 +1277,12 @@ Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic`
// Regression test for NAR-491: after adding `generateStaticParams`
// that covers the requested slug, the slug is no longer a fallback
// 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
// paths cache serves the previous result until then), the render
// triggered by the edit itself still uses the stale `fallbackParams`;
// a follow-up HMR update, sent once the recompute lands, is what
// syncs them.
// triggered by the edit itself still uses the stale
// `stagedFallbackParams`; a follow-up HMR update, sent once the
// recompute lands, is what syncs them.
const browser = await next.browser('/use-cache-params/foo')
await expect(browser).toDisplayCollapsedRedbox(`
......
......@@ -647,11 +647,13 @@ export function registerHeadAndReportingTests(
const result = await prerender(
'/shells/(default)/invalid-runtime-params/[slug]'
)
// TODO(app-shells): missing fallback params in build validation
// It seems like `workUnitStore.fallbackParams` is undefined
// during the validation render, which makes us treat these params as static.
// In partialPrefetching, static params are also delayed until the runtime stage,
// which ultimately makes the validation fail, but also hides the underlying issue.
// TODO(app-shells): Verify fallback params in build validation.
//
// This assertion can pass even if
// `workUnitStore.stagedFallbackParams` is missing. Without that set,
// 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))
.toMatchInlineSnapshot(`
......
......@@ -464,11 +464,12 @@ export function registerSuspenseBoundariesTests(
const result = await prerender(
'/suspense-in-root/runtime/invalid-no-suspense-around-params/[param]'
)
// TODO(app-shells): missing fallback params in build validation
// It seems like `workUnitStore.fallbackParams` is undefined
// during the validation render, which makes us treat these params as static.
// In partialPrefetching, static params are also delayed until the runtime stage,
// which ultimately makes the validation fail, but also hides the underlying issue.
// TODO(app-shells): Verify fallback params in build validation.
//
// This assertion can pass even if `workUnitStore.stagedFallbackParams` is
// missing. Without that set, 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))
.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 { randomUUID } from 'crypto'
import { nextTestSetup } from 'e2e-utils'
import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr'
import { retry, waitFor } from 'next-test-utils'
......@@ -132,6 +133,51 @@ describe('partial-fallback-shell-upgrade', () => {
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 () => {
const firstResult = await fetchSplitHTML('/prefix/b/foo')
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', () => {
'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 {
async function invokeAction(exportedName: string) {
const metadata = await next.readJSON(
'.next/server/app/events/[id]/group.meta'
)
async function invokeAction(
exportedName: string,
route = '/events/[id]/group',
pathname = route
) {
const metadata = await next.readJSON(`.next/server/app${route}.meta`)
const postponed = metadata.postponed as string
expect(postponed).toEqual(expect.any(String))
expect(postponed).toMatch(/^\d+:\d+\[\["id",/)
const manifest = await next.readJSON(
'.next/server/server-reference-manifest.json'
......@@ -51,19 +74,21 @@ describe('action-only fallback resume data cache', () => {
const actionId = Object.keys(manifest.node).find(
(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
// has selected the dynamic route's fallback and prepended its postponed
// state to the action body.
const actionBody = Buffer.from('[]')
const postponedBody = Buffer.from(postponed)
return next.fetch('/events/[id]/group', {
return next.fetch(pathname, {
method: 'POST',
headers: {
'content-type': 'text/plain;charset=UTF-8',
'next-action': actionId!,
'x-matched-path': '/events/[id]/group',
'next-action': actionId,
'x-matched-path': route,
'x-next-resume-state-length': String(postponedBody.byteLength),
},
body: Buffer.concat([postponedBody, actionBody]),
......@@ -80,6 +105,30 @@ describe('action-only fallback resume data cache', () => {
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 () => {
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