Unverified Commit 576d3a33 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PP] Instant validation - error for unguarded static params (#94595)

Follow-up to #95151, implementing support for validating awaits of
static params (i.e. when using `generateStaticParams`)

An app shell cannot contain any link data. This poses a challenge when
we're trying to re-use the dev render for instant validation, because we
have to make a choice:
1. either we resolve static params (from `generateStaticParams`) in the
`Static` stage, and get an accurate *static HTML shell* (used for the
initial navigation), but an incorrect app shell
2. or we resolve them in the `ShellRuntime` stage and we get an accurate
App Shell, but cannot validate a static HTML shell (which would contain
static params)

We'll use order 2 in the main render whenever client-navigating to a
page with `partialPrefetching` enabled. We still need a render with
order 1 for Static Shell Validation, so we perform a second, partial
render that aborts before the dynamic stage (because only instant
navigation needs the dynamic stage). As an optimization, we can skip the
secondary render if the page doesn't have static params, because in that
case the two orders are equivalent.

If we're performing an initial load, we'll use order 1 (to reflect the
HTML shell). in this case, we'll do a full secondary render with order
2. Same as above, we can skip the secondary render if there's no static
params.

---

Where params resolve (order 1 vs order 2) is controlled by
`requestStore.needsSessionShell`. We then end up with two sets of
"validation inputs" (mainly rendered chunks) that we can feed into
static and instant validation respectively.

Also note that this PR doesn't touch `environmentName`, because that
required changing too many tests. This will be addressed in a follow-up.
parent c2edfabc
......@@ -1390,5 +1390,6 @@
"1389": "Expected the empty `generateStaticParams` error to be injected by the compiler.",
"1390": "Route \"%s\": Next.js encountered link data in \\`generateMetadata()\\`.\\n\\nThis route's metadata is blocked, but the rest of its content can be prefetched. \\`params\\` or \\`searchParams\\` accessed in \\`generateMetadata()\\` prevent it from being prefetched.\\n\\nWays to fix this:\\n - [static] Use a static metadata export instead of \\`generateMetadata()\\`\\n https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#use-static-metadata\\n - [dynamic] Render a marker component that calls \\`await connection()\\` inside \\`<Suspense>\\` on the page\\n https://nextjs.org/docs/messages/blocking-prerender-metadata-runtime#mark-the-route-as-dynamic",
"1391": "Route \"%s\": Next.js encountered link data during prerendering or a navigation.\\n\\n\\`params\\` or \\`searchParams\\` accessed outside of \\`<Suspense>\\` prevents the navigation from being instant, leading to a slower user experience.\\n\\nWays to fix this:\\n - [stream] Provide a placeholder with \\`<Suspense fallback={...}>\\` around the data access\\n https://nextjs.org/docs/messages/blocking-prerender-runtime#wrap-in-or-move-into-suspense\\n - [block] Set \\`export const instant = false\\` to silence this warning and allow a blocking route\\n https://nextjs.org/docs/messages/blocking-prerender-runtime#allow-blocking-route",
"1392": "Route \"%s\": Next.js encountered link data in \\`generateViewport()\\`.\\n\\n\\`params\\`, or \\`searchParams\\` in \\`generateViewport()\\` prevents the page from being prerendered, leading to a slower user experience.\\n\\nWays to fix this:\\n - [static] Use a static viewport export instead of \\`generateViewport()\\`\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\\n - [block] Set \\`export const instant = false\\` to silence this warning and allow a blocking route\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route"
"1392": "Route \"%s\": Next.js encountered link data in \\`generateViewport()\\`.\\n\\n\\`params\\`, or \\`searchParams\\` in \\`generateViewport()\\` prevents the page from being prerendered, leading to a slower user experience.\\n\\nWays to fix this:\\n - [static] Use a static viewport export instead of \\`generateViewport()\\`\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\\n - [block] Set \\`export const instant = false\\` to silence this warning and allow a blocking route\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#allow-blocking-route",
"1393": "An unexpected error occurred during validation"
}
......@@ -74,17 +74,21 @@ export interface RequestStore extends CommonWorkUnitStore {
resumeDataCache: ResumeDataCache | null
stale?: number
stagedRendering?: StagedRenderingController | null
asyncApiPromises?: AsyncApiPromises
needsSessionShell?: boolean // DEV-only
cacheSignal?: CacheSignal | null
fallbackParams?: OpaqueFallbackRouteParams | null
varyParamsAccumulator?: ResponseVaryParamsAccumulator | null
// Only in build-time instant-validation
// Only in build-time instant-validation or when rendering
// a secondary stream for static shell validation
// We mirror the controller/renderSignal from prerender stores to allow aborting the render
// in case we hit an error that makes it unnecessary to continue
controller?: AbortController
renderSignal?: AbortSignal
// Only in build-time instant-validation
validationSamples?: InstantValidationSamples
validationSampleTracking?: InstantValidationSampleTracking | null
......
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import type { Params } from '../request/params'
export function hasNonRootStaticParams(
params: Params,
rootParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined
) {
for (const paramName in params) {
if (
!Object.hasOwn(rootParams, paramName) &&
isStaticParam(paramName, fallbackParams)
) {
return true
}
}
return false
}
function isStaticParam(
paramName: string,
fallbackParams: OpaqueFallbackRouteParams | null | undefined
) {
// NOTE: Assume that undefined fallback params mean that all of the params are static.
if (!fallbackParams) return true
// If the param isn't a fallback param, it must be static.
return !fallbackParams.has(paramName)
}
export function allParamsAreRootParams(
underlyingParams: Params,
rootParams: Params
) {
for (const paramName in underlyingParams) {
if (!Object.hasOwn(rootParams, paramName)) {
return false
}
}
return true
}
export function isEmptyParams(params: Params): boolean {
for (const _paramKey in params) {
return false
}
return true
}
export function hasFallbackRouteParams(
underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined
): boolean {
if (fallbackParams) {
for (let key in underlyingParams) {
if (fallbackParams.has(key)) {
return true
}
}
}
return false
}
......@@ -76,10 +76,8 @@ export function io(expression: string, type: SyncIOApiType) {
syncIOError = applyOwnerStack(syncIOError)
stageController.syncInterruptCurrentStageWithReason(syncIOError)
// A build-time validation render uses a 'request' store type, but may be abortable.
// If we're in the second, restarted render of the restart-on-cache miss flow,
// Sync IO is an error, and unlike dev, there's no need to continue the render past the sync IO,
// so we can abort it.
// A validation render uses a 'request' store type, but may be abortable.
// If we're rendering with filled caches, Sync IO is an error and should trigger an abort.
if (
workUnitStore.controller &&
!workUnitStore.controller.signal.aborted
......
......@@ -40,6 +40,11 @@ import {
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
import { RenderStage } from '../app-render/staged-rendering'
import {
isEmptyParams,
hasFallbackRouteParams,
allParamsAreRootParams,
} from '../lib/params-utils'
export type ParamValue = string | Array<string> | undefined
export type Params = Record<string, ParamValue>
......@@ -594,9 +599,13 @@ function createStagedRenderParamsImpl(
!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)
) {
// For a dynamic request we generally want to recover a static shell,
// so static params can resolve in the static stage.
// Session shells are handled with a separate render.
const staticParamsStages = RENDER_STAGES_BY_DATA_KIND.staticLinkData
// so static params can resolve in the static stage, because session
// shells are handled with a separate render.
// However, in dev we might need to recover a session shell for instant validation.
// This is indicated by `needsSessionShell`.
const staticParamsStages = workUnitStore.needsSessionShell
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
: RENDER_STAGES_BY_DATA_KIND.staticLinkData
const stage = isRuntimePrefetchable
? staticParamsStages.early
: staticParamsStages.late
......@@ -606,15 +615,6 @@ function createStagedRenderParamsImpl(
return makeUntrackedParams(userspaceParams)
}
function allParamsAreRootParams(underlyingParams: Params, rootParams: Params) {
for (const paramName in underlyingParams) {
if (!Object.hasOwn(rootParams, paramName)) {
return false
}
}
return true
}
function createParamsPromiseFromTrigger(
trigger: Promise<any>,
userspaceParams: Params
......@@ -638,27 +638,6 @@ function createParamsPromiseFromTrigger(
function noop() {}
function isEmptyParams(params: Params): boolean {
for (const _paramKey in params) {
return false
}
return true
}
function hasFallbackRouteParams(
underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined
): boolean {
if (fallbackParams) {
for (let key in underlyingParams) {
if (fallbackParams.has(key)) {
return true
}
}
}
return false
}
function createServerParamsProxyForInstantValidation(
underlyingParams: Params,
workStore: WorkStore,
......
......@@ -2,6 +2,8 @@ import { nextTestSetup, type Playwright } from 'e2e-utils'
import { retry } from 'next-test-utils'
import * as nodePath from 'node:path'
const partialPrefetching = !!process.env.__NEXT_PARTIAL_PREFETCHING
describe.each([
{
description: 'without runtime prefetch configs',
......@@ -220,6 +222,15 @@ describe.each([
{ description: 'initial load', isInitialLoad: true },
{ description: 'navigation', isInitialLoad: false },
])('$description', ({ isInitialLoad }) => {
// Static
const STATIC_LINK_DATA = isInitialLoad
? 'Prerender'
: // If we're rendering an App Shell, static params are deferred until the runtime stage.
partialPrefetching || hasRuntimePrefetch
? RUNTIME_ENV
: 'Prerender'
const RUNTIME_LINK_DATA = RUNTIME_ENV
describe('cached data resolves in the correct phase', () => {
it('cached data + cached fetch', async () => {
const path = '/simple'
......@@ -375,10 +386,11 @@ describe.each([
const assertLogs = async (browser: Playwright) => {
const logs = await browser.log()
// `en` is covered by `generateStaticParams`, so `lang` resolves in
// the static shell.
assertLog(logs, 'after params - lang', 'Prerender')
// the static shell, unless we're rendering an App Shell, in which
// case they're deferred to the runtiem stage.
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_ENV)
assertLog(logs, 'after params - id', RUNTIME_LINK_DATA)
}
if (isInitialLoad) {
......@@ -399,8 +411,8 @@ describe.each([
// 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_ENV)
assertLog(logs, 'after params - id', RUNTIME_ENV)
assertLog(logs, 'after params - lang', RUNTIME_LINK_DATA)
assertLog(logs, 'after params - id', RUNTIME_LINK_DATA)
}
if (isInitialLoad) {
......@@ -417,11 +429,12 @@ describe.each([
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. (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', 'Prerender')
assertLog(logs, 'after params - id', 'Prerender')
// 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 - id', STATIC_LINK_DATA)
}
if (isInitialLoad) {
......
import { PageForSlug } from '../shared'
export default function Page() {
return <PageForSlug slug="cold-badge" />
}
import { PageForSlug } from '../shared'
export default function Page() {
return <PageForSlug slug="purged" />
}
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
// A distinct slug per test, so each test exercises its own cache entry and no
// cache hits are shared across tests (the first request for a slug is a genuine
// cold miss). Declaring the slugs also keeps `params` statically known, so the
// page shell doesn't depend on dynamic params. In development this does not
// pre-fill the cache.
export function generateStaticParams() {
return [{ slug: 'cold-badge' }, { slug: 'purged' }]
}
async function getCachedValue(slug: string) {
'use cache'
......@@ -28,13 +19,13 @@ async function CachedValue({ slug }: { slug: string }) {
return <p id="value">{value}</p>
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
// We use a distinct slug per test, so each test exercises its own cache entry and no
// cache hits are shared across tests (the first request for a slug is a genuine
// cold miss).
// NOTE: we're not using generateStaticParams because
// those resolve after the shell in `partialPrefetching`,
// and the test needs the cache to be part of the shell.
export async function PageForSlug({ slug }: { slug: string }) {
return (
<main>
<Suspense fallback={<p id="loading">Loading...</p>}>
......
import { PageForSlug } from '../shared'
export default function Page() {
return <PageForSlug slug="cold-badge" />
}
import { PageForSlug } from '../shared'
export default function Page() {
return <PageForSlug slug="reload" />
}
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
// A distinct slug per test, so each test exercises its own cache entry and no
// cache hits are shared across tests (the first request for a slug is a genuine
// cold miss). Declaring the slugs also keeps `params` statically known, so the
// page shell doesn't depend on dynamic params. In development this does not
// pre-fill the cache.
export function generateStaticParams() {
return [{ slug: 'reload' }, { slug: 'cold-badge' }]
}
async function getCachedValue(slug: string) {
'use cache'
......@@ -28,13 +19,10 @@ async function CachedValue({ slug }: { slug: string }) {
return <p id="value">{value}</p>
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
export async function PageForSlug({ slug }: { slug: string }) {
// NOTE: we're not using generateStaticParams because
// those resolve after the shell in `partialPrefetching`,
// and the test needs the cache to be part of the shell
return (
<main>
<Suspense fallback={<p id="loading">Loading...</p>}>
......
import { Instant } from 'next'
export const instant: Instant = {
level: 'experimental-error',
unstable_samples: [{ params: { slug: '123' } }],
}
export async function generateStaticParams() {
return [{ slug: '123' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<main>
<p>
This page is missing a suspense around a link data access, but this page
is intended to run without partialPrefetching, so this is still allowed.
</p>
<LinkData params={params} />
</main>
)
}
async function LinkData({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return <div>{`Static slug: ${slug}`}</div>
}
......@@ -301,6 +301,13 @@ export default async function Page() {
<DebugLinks href="/suspense-in-root/disable-validation/disable-build" />
</li>
</ul>
<h2>Without partialPrefetching</h2>
<ul>
<li>
<DebugLinks href="/suspense-in-root/non-app-shell/valid-unguarded-static-params/123" />
</li>
</ul>
</main>
)
}
......@@ -99,6 +99,7 @@ describe('browser-chunks', () => {
"src/server/app-render/work-unit-async-storage.external.ts",
"src/server/create-deduped-by-callsite-server-error-logger.ts",
"src/server/dynamic-rendering-utils.ts",
"src/server/lib/params-utils.ts",
"src/server/request/params.ts",
"src/server/request/search-params.ts",
"src/server/request/utils.ts",
......@@ -133,6 +134,7 @@ describe('browser-chunks', () => {
"src/server/app-render/work-unit-async-storage.external.ts",
"src/server/create-deduped-by-callsite-server-error-logger.ts",
"src/server/dynamic-rendering-utils.ts",
"src/server/lib/params-utils.ts",
"src/server/request/params.ts",
"src/server/request/search-params.ts",
"src/server/request/utils.ts",
......
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