Unverified Commit 690f1ad8 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Validate `unstable_ensureStatic` nesting (#98357)

`ensureStatic` forms a hierarchy: `"auto" < "shell" < "prefetch" <
"navigation"`, with each value being more contrained than its
predecessor.

1. A child segment cannot relax constraints set by a parent segment, it
can only tighten them
- so `shell` in a layout and `prefetch` in a page is fine, but the
opposite is not
- note that setting `"auto"` in the child *is* allowed, because it means
"unconstrained" and is compatible with all the other configs
2. We can't have two conflicting levels set by two parallel slots (but
`auto` is compatible with any other constraint, so it's allowed, same as
above)
3. If a segment sets `ensureStatic = false`, then no other segments on
that route are allowed to constrain the route by setting anything higher
than `auto` (this is meant as a signal for e.g. "this segment
DELIBERATELY uses a runtime shell and should not be overridden to be
static")

Also adds exhaustive tests for all of these scenarios.
parent e09ac7d2
...@@ -312,6 +312,10 @@ import { ...@@ -312,6 +312,10 @@ import {
anySegmentNeedsInstantValidationInBuild, anySegmentNeedsInstantValidationInBuild,
resolveInstantConfigSamplesForPage, resolveInstantConfigSamplesForPage,
} from './instant-validation/instant-config' } from './instant-validation/instant-config'
import {
resolveEnsureStaticLevel,
EnsureStaticLevel,
} from './segment-config/ensure-static'
import { warnOnce } from '../../shared/lib/utils/warn-once' import { warnOnce } from '../../shared/lib/utils/warn-once'
import { import {
createWebDebugChannel, createWebDebugChannel,
...@@ -1452,6 +1456,12 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1452,6 +1456,12 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
} }
const prefetchMode = await getPrefetchingModeForPage(renderOpts, loaderTree) const prefetchMode = await getPrefetchingModeForPage(renderOpts, loaderTree)
// We currently don't need the `ensureStatic` level here, but
// we want to validate that it's correct.
await resolveEnsureStaticLevel(
loaderTree,
/* partialPrefetching */ prefetchMode === PrefetchingMode.Partial
)
// A client navigation into a Partial Prefetching route extends the shell // A client navigation into a Partial Prefetching route extends the shell
// through the runtime-prefetchable content: it has already settled on the // through the runtime-prefetchable content: it has already settled on the
...@@ -2393,12 +2403,16 @@ async function getErrorRSCPayload( ...@@ -2393,12 +2403,16 @@ async function getErrorRSCPayload(
) )
) )
const partialPrefetching =
Boolean(ctx.renderOpts.partialPrefetching) ||
(await anySegmentHasPartialPrefetchingEnabled(tree))
const initialTree = await createFullTransportTreeFromLoaderTree( const initialTree = await createFullTransportTreeFromLoaderTree(
tree, tree,
errorHints, errorHints,
errorPrefetchInliningEnabled, errorPrefetchInliningEnabled,
ctx.missingPrefetchHintPolicy, ctx.missingPrefetchHintPolicy,
Boolean(ctx.renderOpts.partialPrefetching), partialPrefetching,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query, query,
ctx.renderOpts.notFoundParams ctx.renderOpts.notFoundParams
...@@ -3735,6 +3749,15 @@ async function renderToStream( ...@@ -3735,6 +3749,15 @@ async function renderToStream(
// We only have a Prerender environment for projects opted into cacheComponents // We only have a Prerender environment for projects opted into cacheComponents
cacheComponents cacheComponents
) { ) {
const prefetchMode = await getPrefetchingModeForPage(renderOpts, tree)
// We currently don't need the `ensureStatic` level here, but
// we want to validate that it's correct.
await resolveEnsureStaticLevel(
tree,
/* partialPrefetching */ prefetchMode === PrefetchingMode.Partial
)
let debugChannelClientStream: ReplayableNodeStream | undefined let debugChannelClientStream: ReplayableNodeStream | undefined
// eslint-disable-next-line @typescript-eslint/no-shadow // eslint-disable-next-line @typescript-eslint/no-shadow
...@@ -3775,12 +3798,6 @@ async function renderToStream( ...@@ -3775,12 +3798,6 @@ async function renderToStream(
// or draft mode. // or draft mode.
!isBypassingCachesInDev(requestStore, workStore) !isBypassingCachesInDev(requestStore, workStore)
) { ) {
const loaderTree = ctx.componentMod.routeModule.userland.loaderTree
const prefetchMode = await getPrefetchingModeForPage(
renderOpts,
loaderTree
)
const { stream: serverStream, debugChannel: returnedDebugChannel } = const { stream: serverStream, debugChannel: returnedDebugChannel } =
await stagedRenderWithCachesInDev({ await stagedRenderWithCachesInDev({
prefetchMode, prefetchMode,
...@@ -8817,6 +8834,20 @@ async function prerenderToStream( ...@@ -8817,6 +8834,20 @@ async function prerenderToStream(
try { try {
if (cacheComponents) { if (cacheComponents) {
const partialPrefetching =
Boolean(ctx.renderOpts.partialPrefetching) ||
(await anySegmentHasPartialPrefetchingEnabled(tree))
let ensureStaticLevel = await resolveEnsureStaticLevel(
tree,
partialPrefetching
)
if (process.env.NEXT_PRIVATE_DEBUG_RUNTIME_DATA) {
console.log(
`${workStore.route} :: ensureStatic level = ${EnsureStaticLevel[ensureStaticLevel]}`
)
}
/** /**
* cacheComponents with PPR * cacheComponents with PPR
* *
......
import type {
AppSegmentConfig,
EnsureStatic,
} from '../../../build/segment-config/app/app-segment-config'
import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree'
import {
getLayoutOrPageModule,
type LoaderTree,
} from '../../lib/app-dir-module'
/**
* The outcome of resolving a route's `ensureStatic` config.
* The ordering is intentional -- higher values indicate a
* more constrained route that forces more request kinds to be static.
*
* A constraint also implies all its predecessors:
* - `Prefetch` implies `Shell`, i.e. if prefetches are static, so are shells.
* - `Navigation` implies `Prefetch` and `Shell`, i.e. if the whole page is static,
* then so are its shells and prefetches.
*
* Note that this flattens `"auto"` and `false` into `None`.
* This is because rendering code does not need to distinguish them --
* both indicate that the route follows normal Partial Prefetching semantics
* and does not force anything to be static.
* However, it is only correct to collapse them into one *after* resolving the
* config for the entire route, because they have different interactions with
* configs from other segments on the same route.
*/
export enum EnsureStaticLevel {
/** The route follows standard Partial Prefetching semantics. */
None = 0,
/** The route requires that app shells must be statically prerendered. */
Shell = 1,
/** The route requires that app shells and prefetches must be statically prerendered. */
Prefetch = 2,
/** The route requires that app shells, prefetches, and the whole page must be statically prerendered. */
Navigation = 3,
}
function getEnsureStaticLevel(ensureStatic: EnsureStatic) {
switch (ensureStatic) {
case 'auto':
case false: {
return EnsureStaticLevel.None
}
case 'shell': {
return EnsureStaticLevel.Shell
}
case 'prefetch': {
return EnsureStaticLevel.Prefetch
}
case 'navigation': {
return EnsureStaticLevel.Navigation
}
}
}
export async function resolveEnsureStaticLevel(
tree: LoaderTree,
partialPrefetching: boolean
): Promise<EnsureStaticLevel> {
let { config, filePath } = await resolveEnsureStaticConfigImpl(tree)
if (!partialPrefetching) {
// If Partial Prefetching is not enabled for this route, we only support
// a subset of `ensureStatic` values.
// (We error in `getAppPageStaticInfo` if `ensureStatic` is used without enabling
// Cache Components, so we don't have to assert that here)
switch (config) {
case 'auto': {
// Default to the equivalent of Cache Components prefetching behavior.
config = 'prefetch'
break
}
case false:
case 'shell': {
// Not meaningful in Cache Components without Partial Prefetching
const originalConfig = config
config = 'prefetch'
console.warn(
`${formatEnsureStaticExport(originalConfig)} has no effect unless the route is using Partial Prefetching.` +
`\n (from: ${filePath})`
)
break
}
case 'prefetch':
// Equivalent to regular Cache Components behavior, so we allow it
// without warning to avoid noise when doing gradual opt-in
break
case 'navigation':
// Meaningful in Cache Components, even without Partial Prefetching
break
default:
config satisfies never
}
}
if (config === 'navigation') {
throw new Error(
`\`${formatEnsureStaticExport(config)}\` is not implemented yet.` +
`\n (from: ${filePath})` +
``
)
}
return getEnsureStaticLevel(config)
}
type EnsureStaticWithSource = {
config: EnsureStatic
filePath: string | null
}
async function resolveEnsureStaticConfigImpl(
tree: LoaderTree
): Promise<EnsureStaticWithSource> {
const { mod: layoutOrPageMod, filePath } = await getLayoutOrPageModule(tree)
const config = getEnsureStaticConfigForModule(layoutOrPageMod)
const parentResult: EnsureStaticWithSource = {
config,
filePath: filePath ?? null,
}
// Walk the slots if any and validate that they don't have incompatible configs
// with each other. If compatible, pick the most constrained value from the slots.
let slotsResult: EnsureStaticWithSource | null = null
let slotResultKey: string | null = null
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
const childResult = await resolveEnsureStaticConfigImpl(parallelRoute)
if (!slotsResult) {
slotsResult = childResult
slotResultKey = parallelRouteKey
} else {
// Check if the child is compatible with the current result for the slots.
switch (compareEnsureStatic(childResult.config, slotsResult.config)) {
case Comparison.Compatible: {
// 'auto' is compatible with anything, but if the current result is 'auto' and the new one isn't,
// we want to use the more specific result.
if (slotsResult.config === 'auto' && childResult.config !== 'auto') {
slotsResult = childResult
slotResultKey = parallelRouteKey
}
break
}
case Comparison.Incompatible:
case Comparison.LessConstrained:
case Comparison.MoreConstrained: {
throw new Error(
`Parallel slots cannot have incompatible \`unstable_ensureStatic\`.` +
`\n ${formatParallelSlot(slotResultKey!)}: ` +
`\n ${formatEnsureStaticExport(slotsResult.config)}` +
`\n (from: ${slotsResult.filePath})` +
`\n` +
`\n ${formatParallelSlot(parallelRouteKey)}: ` +
`\n ${formatEnsureStaticExport(childResult.config)}` +
`\n (from: ${childResult.filePath})` +
`\n` +
`\n Possible fixes:` +
`\n - Remove one of the \`unstable_ensureStatic\` exports` +
`\n - Change one of the \`unstable_ensureStatic\` exports to match the other`
)
}
}
}
}
// Child segments can override the config from the parent with a more constrained value,
// but they cannot have a less constrained value.
if (!slotsResult) {
return parentResult
} else {
const comparison = compareEnsureStatic(
slotsResult.config,
parentResult.config
)
switch (comparison) {
case Comparison.Compatible: {
// 'auto' is compatible with anything, but if the parent result is 'auto' and the slots one isn't,
// we want to use the more constrained result.
if (parentResult.config === 'auto' && slotsResult.config !== 'auto') {
return slotsResult
} else {
return parentResult
}
}
case Comparison.MoreConstrained: {
return slotsResult
}
case Comparison.LessConstrained:
case Comparison.Incompatible: {
throw new Error(
(comparison === Comparison.LessConstrained
? `A child segment cannot override a parent segment with a less-constrained \`unstable_ensureStatic\`.`
: `A child segment cannot override a parent segment with an incompatible \`unstable_ensureStatic\`.`) +
`\n Parent has: ` +
`\n ${formatEnsureStaticExport(parentResult.config)}` +
`\n (from: ${parentResult.filePath})` +
`\n Child has: ` +
`\n ${formatEnsureStaticExport(slotsResult.config)}` +
`\n (from: ${slotsResult.filePath})` +
`\n` +
`\n Possible fixes:` +
`\n - Remove one of the \`unstable_ensureStatic\` exports` +
`\n - Change one of the \`unstable_ensureStatic\` exports to match the other`
)
}
}
}
}
function formatParallelSlot(slot: string) {
return slot === 'children' ? slot : `@${slot}`
}
function formatEnsureStaticExport(config: EnsureStatic) {
return `export const unstable_ensureStatic = ${JSON.stringify(config)}`
}
enum Comparison {
LessConstrained = 1,
Compatible = 2,
MoreConstrained = 3,
Incompatible = 4,
}
const ENSURE_STATIC_ORDER: Exclude<EnsureStatic, 'auto' | false>[] = [
'shell',
'prefetch',
'navigation',
]
function compareEnsureStatic(
left: EnsureStatic,
right: EnsureStatic
): Comparison {
// 'auto' is compatible with everything.
if (left === 'auto' || right === 'auto') {
return Comparison.Compatible
}
// `false` is compatible with false.
if (left === false && right === false) {
return Comparison.Compatible
}
// If only one of the values is `false` (we know it's not both), it's incompatible.
if (left === false || right === false) {
return Comparison.Incompatible
}
const leftSort = ENSURE_STATIC_ORDER.indexOf(left)
const rightSort = ENSURE_STATIC_ORDER.indexOf(right)
return leftSort < rightSort
? Comparison.LessConstrained
: leftSort === rightSort
? Comparison.Compatible
: Comparison.MoreConstrained
}
function getEnsureStaticConfigForModule(
mod: Record<string, any> | undefined
): EnsureStatic {
return (
(mod ? (mod as AppSegmentConfig).unstable_ensureStatic : undefined) ??
'auto'
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export const unstable_ensureStatic = 'auto'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export const unstable_ensureStatic = 'auto'
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_ensureStatic = 'auto'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export const unstable_ensureStatic = false
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_ensureStatic = 'auto'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export const unstable_ensureStatic = 'navigation'
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_ensureStatic = 'auto'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export const unstable_ensureStatic = 'prefetch'
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_ensureStatic = 'auto'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export const unstable_ensureStatic = 'shell'
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export const unstable_ensureStatic = 'auto'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Layout({ children }: { children: ReactNode }) {
return children
}
export default function Page() {
return <p>hello world</p>
}
export const unstable_ensureStatic = 'auto'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export default function Layout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<>
{left}
{right}
</>
)
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export default function Layout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<>
{left}
{right}
</>
)
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = false
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export default function Layout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<>
{left}
{right}
</>
)
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export default function Layout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<>
{left}
{right}
</>
)
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export default function Layout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<>
{left}
{right}
</>
)
}
export const unstable_ensureStatic = 'shell'
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export default function Layout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<>
{left}
{right}
</>
)
}
// Deliberately no export
// export const unstable_ensureStatic = ...
export default function Page() {
return <main>Page</main>
}
export const unstable_ensureStatic = 'prefetch'
export default function Page() {
return <main>Page</main>
}
import { ReactNode } from 'react'
export default function Layout({
left,
right,
}: {
left: ReactNode
right: ReactNode
}) {
return (
<>
{left}
{right}
</>
)
}
import { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
experimental: {
prerenderEarlyExit: false,
},
}
export default nextConfig
...@@ -956,10 +956,13 @@ export async function retry<T>( ...@@ -956,10 +956,13 @@ export async function retry<T>(
} }
} }
export async function waitForRedbox(browser: Playwright) { export async function waitForRedbox(
browser: Playwright,
{ waitInMs = 5000 } = {}
) {
const redbox = browser.locateRedbox() const redbox = browser.locateRedbox()
try { try {
await redbox.waitFor({ timeout: 5000 }) await redbox.waitFor({ timeout: waitInMs })
} catch (errorCause) { } catch (errorCause) {
const error = new Error('Expected Redbox but found no visible one.') const error = new Error('Expected Redbox but found no visible one.')
Error.captureStackTrace(error, waitForRedbox) Error.captureStackTrace(error, waitForRedbox)
......
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