Unverified Commit cf4d3ae8 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

partial fallbacks: only upgrade shells with remaining prerenderable params (#91158)

Partial fallback upgrading is currently too broad. Any PPR fallback shell can be treated as upgradeable, including routes with no `generateStaticParams` and shells that are already as specific as prerendering can make them.

In practice, that means we preserve `allowQuery` and enable background promotion for shells that should remain as partial fallbacks. That broadens the feature beyond the medium-cardinality case it was meant for and makes the build output imply per-param upgradeability when there are no prerenderable params left to fill.

This PR teaches static-path generation to compute `remainingPrerenderableParams` for each fallback shell: the unresolved pathname params that can still be filled by `generateStaticParams` in that branch. We then use that signal to gate partial fallback behavior.

With this change:

- `partialFallback` is only emitted for shells that still have prerenderable params remaining
- `allowQuery` with params is only preserved for those shells

Effectively, this limits partial fallback upgrading to shells that can still be made more specific by prerendering.
parent 68dade46
...@@ -37,6 +37,7 @@ import { ...@@ -37,6 +37,7 @@ import {
CACHE_ONE_YEAR_SECONDS, CACHE_ONE_YEAR_SECONDS,
HTML_CONTENT_TYPE_HEADER, HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE_HEADER,
NEXT_QUERY_PARAM_PREFIX,
NEXT_RESUME_HEADER, NEXT_RESUME_HEADER,
} from '../../lib/constants' } from '../../lib/constants'
...@@ -1591,6 +1592,7 @@ export async function handleBuildComplete({ ...@@ -1591,6 +1592,7 @@ export async function handleBuildComplete({
fallbackStatus, fallbackStatus,
fallbackSourceRoute, fallbackSourceRoute,
fallbackRootParams, fallbackRootParams,
remainingPrerenderableParams,
allowHeader, allowHeader,
dataRoute, dataRoute,
renderingMode, renderingMode,
...@@ -1602,19 +1604,32 @@ export async function handleBuildComplete({ ...@@ -1602,19 +1604,32 @@ export async function handleBuildComplete({
const isAppPage = Boolean(appOutputMap[srcRoute]) const isAppPage = Boolean(appOutputMap[srcRoute])
const meta = await getAppRouteMeta(dynamicRoute, isAppPage) const meta = await getAppRouteMeta(dynamicRoute, isAppPage)
const allowQuery = Object.values( const routeKeys =
routesManifest.dynamicRoutes.find( routesManifest.dynamicRoutes.find(
(item) => item.page === dynamicRoute (item) => item.page === dynamicRoute
)?.routeKeys || {} )?.routeKeys || {}
) const allowQuery = Object.values(routeKeys)
const partialFallbacksEnabled = const partialFallbacksEnabled =
config.experimental.partialFallbacks === true config.experimental.partialFallbacks === true
const partialFallback = const partialFallback =
partialFallbacksEnabled && partialFallbacksEnabled &&
isAppPage && isAppPage &&
remainingPrerenderableParams !== undefined &&
remainingPrerenderableParams.length > 0 &&
renderingMode === RenderingMode.PARTIALLY_STATIC && renderingMode === RenderingMode.PARTIALLY_STATIC &&
typeof fallback === 'string' && typeof fallback === 'string' &&
Boolean(meta.postponed) Boolean(meta.postponed)
// Today, consumers of this build output can only upgrade a fallback shell
// when all remaining route params become concrete in the upgraded entry.
// They cannot yet represent intermediate shells like `/[foo]/[bar] -> /foo/[bar]`,
// because we do not emit which fallback params should remain deferred after
// the upgrade. Until that contract exists, only emit `partialFallback` for
// the conservative case where the upgraded entry can become fully concrete.
const canEmitPartialFallback =
partialFallback &&
fallbackRootParams?.length === 0 &&
allowQuery.length === remainingPrerenderableParams?.length
let htmlAllowQuery = allowQuery let htmlAllowQuery = allowQuery
// We only want to vary on the shell contents if there is a fallback // We only want to vary on the shell contents if there is a fallback
...@@ -1632,12 +1647,18 @@ export async function handleBuildComplete({ ...@@ -1632,12 +1647,18 @@ export async function handleBuildComplete({
// RSC shell. // RSC shell.
else if (meta.postponed) { else if (meta.postponed) {
// If there's postponed fallback content, we usually collapse to a shared shell (`[]`). // If there's postponed fallback content, we usually collapse to a shared shell (`[]`).
// For opt-in partial fallbacks in cache components, keep route // For opt-in partial fallbacks in cache components, keep only the
// allowQuery so fallback shells can be upgraded per-param instead // params that can still complete this shell.
// of sharing one cache key. const remainingPrerenderableQueryKeys = new Set(
(remainingPrerenderableParams ?? []).map(
(param) => `${NEXT_QUERY_PARAM_PREFIX}${param.paramName}`
)
)
htmlAllowQuery = htmlAllowQuery =
partialFallback && routesManifest.rsc.clientParamParsing canEmitPartialFallback && routesManifest.rsc.clientParamParsing
? allowQuery ? Object.values(routeKeys).filter((routeKey) =>
remainingPrerenderableQueryKeys.has(routeKey)
)
: [] : []
} }
} }
...@@ -1683,7 +1704,7 @@ export async function handleBuildComplete({ ...@@ -1683,7 +1704,7 @@ export async function handleBuildComplete({
allowQuery: htmlAllowQuery, allowQuery: htmlAllowQuery,
allowHeader, allowHeader,
renderingMode, renderingMode,
partialFallback: partialFallback || undefined, partialFallback: canEmitPartialFallback || undefined,
bypassFor: isAppPage ? experimentalBypassFor : undefined, bypassFor: isAppPage ? experimentalBypassFor : undefined,
bypassToken: prerenderManifest.preview.previewModeId, bypassToken: prerenderManifest.preview.previewModeId,
}, },
......
...@@ -294,6 +294,13 @@ export interface DynamicPrerenderManifestRoute { ...@@ -294,6 +294,13 @@ export interface DynamicPrerenderManifestRoute {
experimentalBypassFor?: RouteHas[] experimentalBypassFor?: RouteHas[]
fallback: Fallback fallback: Fallback
/**
* The unresolved fallback route params that can still be specialized into a
* more specific prerendered shell because their segments export
* `generateStaticParams`.
*/
remainingPrerenderableParams?: readonly FallbackRouteParam[]
/** /**
* When defined, it describes the revalidation configuration for the fallback * When defined, it describes the revalidation configuration for the fallback
* route. * route.
...@@ -2067,6 +2074,8 @@ export default async function build( ...@@ -2067,6 +2074,8 @@ export default async function build(
defaultLocale: config.i18n?.defaultLocale, defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output, nextConfigOutput: config.output,
pprConfig: config.experimental.ppr, pprConfig: config.experimental.ppr,
partialFallbacksEnabled:
config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife, cacheLifeProfiles: config.cacheLife,
buildId, buildId,
clientAssetToken: clientAssetToken:
...@@ -2294,6 +2303,8 @@ export default async function build( ...@@ -2294,6 +2303,8 @@ export default async function build(
cacheMaxMemorySize: config.cacheMaxMemorySize, cacheMaxMemorySize: config.cacheMaxMemorySize,
nextConfigOutput: config.output, nextConfigOutput: config.output,
pprConfig: config.experimental.ppr, pprConfig: config.experimental.ppr,
partialFallbacksEnabled:
config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife, cacheLifeProfiles: config.cacheLife,
buildId, buildId,
clientAssetToken: clientAssetToken:
...@@ -3423,6 +3434,8 @@ export default async function build( ...@@ -3423,6 +3434,8 @@ export default async function build(
prerenderManifest.dynamicRoutes[route.pathname] = { prerenderManifest.dynamicRoutes[route.pathname] = {
experimentalPPR: isRoutePPREnabled, experimentalPPR: isRoutePPREnabled,
remainingPrerenderableParams:
route.remainingPrerenderableParams,
renderingMode: isAppPPREnabled renderingMode: isAppPPREnabled
? isRoutePPREnabled ? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC ? RenderingMode.PARTIALLY_STATIC
......
import { FallbackMode } from '../../lib/fallback' import { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params' import type { Params } from '../../server/request/params'
import { import {
assignErrorIfEmpty, assignStaticShellMetadata,
generateAllParamCombinations, generateAllParamCombinations,
calculateFallbackMode, calculateFallbackMode,
filterUniqueParams, filterUniqueParams,
...@@ -11,7 +11,26 @@ import type { PrerenderedRoute } from './types' ...@@ -11,7 +11,26 @@ import type { PrerenderedRoute } from './types'
import type { WorkStore } from '../../server/app-render/work-async-storage.external' import type { WorkStore } from '../../server/app-render/work-async-storage.external'
import type { AppSegment } from '../segment-config/app/app-segments' import type { AppSegment } from '../segment-config/app/app-segments'
describe('assignErrorIfEmpty', () => { function pathnameSegments(
...segments: Array<string | [string, boolean]>
): Array<{
paramName: string
hasGenerateStaticParams: boolean
}> {
return segments.map((segment) =>
Array.isArray(segment)
? {
paramName: segment[0],
hasGenerateStaticParams: segment[1],
}
: {
paramName: segment,
hasGenerateStaticParams: false,
}
)
}
describe('assignStaticShellMetadata', () => {
it('should assign throwOnEmptyStaticShell true for a static route with no children', () => { it('should assign throwOnEmptyStaticShell true for a static route with no children', () => {
const prerenderedRoutes: PrerenderedRoute[] = [ const prerenderedRoutes: PrerenderedRoute[] = [
{ {
...@@ -25,7 +44,7 @@ describe('assignErrorIfEmpty', () => { ...@@ -25,7 +44,7 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, []) assignStaticShellMetadata(prerenderedRoutes, [], true)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(true) expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(true)
}) })
...@@ -57,7 +76,7 @@ describe('assignErrorIfEmpty', () => { ...@@ -57,7 +76,7 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, [{ paramName: 'id' }]) assignStaticShellMetadata(prerenderedRoutes, pathnameSegments('id'), true)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true) expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
...@@ -131,10 +150,11 @@ describe('assignErrorIfEmpty', () => { ...@@ -131,10 +150,11 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, [ assignStaticShellMetadata(
{ paramName: 'id' }, prerenderedRoutes,
{ paramName: 'name' }, pathnameSegments('id', 'name'),
]) true
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false) expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
...@@ -188,23 +208,71 @@ describe('assignErrorIfEmpty', () => { ...@@ -188,23 +208,71 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, [ assignStaticShellMetadata(
{ paramName: 'id' }, prerenderedRoutes,
{ paramName: 'name' }, pathnameSegments('id', ['name', true], 'extra'),
{ paramName: 'extra' }, true
]) )
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false) expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[2].throwOnEmptyStaticShell).toBe(true) expect(prerenderedRoutes[2].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'name',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toEqual([
{
paramName: 'name',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[2].remainingPrerenderableParams).toBeUndefined()
}) })
it('should handle empty input', () => { it('should handle empty input', () => {
const prerenderedRoutes: PrerenderedRoute[] = [] const prerenderedRoutes: PrerenderedRoute[] = []
assignErrorIfEmpty(prerenderedRoutes, []) assignStaticShellMetadata(prerenderedRoutes, [], true)
expect(prerenderedRoutes).toEqual([]) expect(prerenderedRoutes).toEqual([])
}) })
it('should skip remaining prerenderable params when partial fallbacks are disabled', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[id]',
encodedPathname: '/[id]',
fallbackRouteParams: [
{
paramName: 'id',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1' },
pathname: '/1',
encodedPathname: '/1',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(prerenderedRoutes, pathnameSegments('id'), false)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toBeUndefined()
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
})
it('should handle blog/[slug] not throwing when concrete routes exist (from docs example)', () => { it('should handle blog/[slug] not throwing when concrete routes exist (from docs example)', () => {
const prerenderedRoutes: PrerenderedRoute[] = [ const prerenderedRoutes: PrerenderedRoute[] = [
{ {
...@@ -241,7 +309,7 @@ describe('assignErrorIfEmpty', () => { ...@@ -241,7 +309,7 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, [{ paramName: 'slug' }]) assignStaticShellMetadata(prerenderedRoutes, pathnameSegments('slug'), true)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) // Should not throw - has concrete children expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) // Should not throw - has concrete children
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true) // Should throw - concrete route expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true) // Should throw - concrete route
...@@ -293,10 +361,11 @@ describe('assignErrorIfEmpty', () => { ...@@ -293,10 +361,11 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, [ assignStaticShellMetadata(
{ paramName: 'id' }, prerenderedRoutes,
{ paramName: 'slug' }, pathnameSegments('id', 'slug'),
]) true
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) // Should not throw - has children expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) // Should not throw - has children
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false) // Should not throw - has children expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false) // Should not throw - has children
...@@ -374,11 +443,11 @@ describe('assignErrorIfEmpty', () => { ...@@ -374,11 +443,11 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, [ assignStaticShellMetadata(
{ paramName: 'category' }, prerenderedRoutes,
{ paramName: 'subcategory' }, pathnameSegments('category', 'subcategory', 'item'),
{ paramName: 'item' }, true
]) )
// All except the last one should not throw on empty static shell // All except the last one should not throw on empty static shell
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
...@@ -414,15 +483,126 @@ describe('assignErrorIfEmpty', () => { ...@@ -414,15 +483,126 @@ describe('assignErrorIfEmpty', () => {
}, },
] ]
assignErrorIfEmpty(prerenderedRoutes, [ assignStaticShellMetadata(
{ paramName: 'locale' }, prerenderedRoutes,
{ paramName: 'segments' }, pathnameSegments('locale', 'segments'),
]) true
)
// The route with more fallback params should not throw on empty static shell // The route with more fallback params should not throw on empty static shell
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true) expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
}) })
it('should specialize only unresolved params backed by generateStaticParams', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[one]/[two]',
encodedPathname: '/[one]/[two]',
fallbackRouteParams: [
{
paramName: 'one',
paramType: 'dynamic',
},
{
paramName: 'two',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { one: 'b' },
pathname: '/b/[two]',
encodedPathname: '/b/[two]',
fallbackRouteParams: [
{
paramName: 'two',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments(['one', true], 'two'),
true
)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'one',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
})
it('should stop specializing once it reaches a purely dynamic param', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[one]/[two]/[three]',
encodedPathname: '/[one]/[two]/[three]',
fallbackRouteParams: [
{
paramName: 'one',
paramType: 'dynamic',
},
{
paramName: 'two',
paramType: 'dynamic',
},
{
paramName: 'three',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { one: 'a' },
pathname: '/a/[two]/[three]',
encodedPathname: '/a/[two]/[three]',
fallbackRouteParams: [
{
paramName: 'two',
paramType: 'dynamic',
},
{
paramName: 'three',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments(['one', true], 'two', ['three', true]),
true
)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'one',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
})
}) })
describe('filterUniqueParams', () => { describe('filterUniqueParams', () => {
......
...@@ -406,22 +406,26 @@ interface TrieNode { ...@@ -406,22 +406,26 @@ interface TrieNode {
} }
/** /**
* Assigns the throwOnEmptyStaticShell property to each of the prerendered routes. * Assigns static shell metadata to each prerendered route.
* This function uses a Trie data structure to efficiently determine whether each route * This function uses a Trie data structure to efficiently determine whether each route
* should throw an error when its static shell is empty. * should throw an error when its static shell is empty and whether a fallback shell
* can still be completed into a more specific prerendered shell.
* *
* A route should not throw on empty static shell if it has child routes in the Trie. For example, * A route should not throw on empty static shell if it has child routes in the Trie. For example,
* if we have two routes, `/blog/first-post` and `/blog/[slug]`, the route for * if we have two routes, `/blog/first-post` and `/blog/[slug]`, the route for
* `/blog/[slug]` should not throw because `/blog/first-post` is a more specific concrete route. * `/blog/[slug]` should not throw because `/blog/first-post` is a more specific concrete route.
* *
* @param prerenderedRoutes - The prerendered routes. * @param prerenderedRoutes - The prerendered routes.
* @param pathnameSegments - The keys of the route parameters. * @param pathnameSegments - The pathname params and whether each one is still
* prerenderable via generateStaticParams.
*/ */
export function assignErrorIfEmpty( export function assignStaticShellMetadata(
prerenderedRoutes: readonly PrerenderedRoute[], prerenderedRoutes: readonly PrerenderedRoute[],
pathnameSegments: ReadonlyArray<{ pathnameSegments: ReadonlyArray<{
readonly paramName: string readonly paramName: string
}> readonly hasGenerateStaticParams: boolean
}>,
computeRemainingPrerenderableParams: boolean
): void { ): void {
// If there are no routes to process, exit early. // If there are no routes to process, exit early.
if (prerenderedRoutes.length === 0) { if (prerenderedRoutes.length === 0) {
...@@ -470,7 +474,10 @@ export function assignErrorIfEmpty( ...@@ -470,7 +474,10 @@ export function assignErrorIfEmpty(
if (!childNode) { if (!childNode) {
// If the child node doesn't exist, create a new one and add it to // If the child node doesn't exist, create a new one and add it to
// the current node's children. // the current node's children.
childNode = { children: new Map(), routes: [] } childNode = {
children: new Map(),
routes: [],
}
currentNode.children.set(valueKey, childNode) currentNode.children.set(valueKey, childNode)
} }
// Move deeper into the Trie to the `childNode` for the next parameter. // Move deeper into the Trie to the `childNode` for the next parameter.
...@@ -537,6 +544,45 @@ export function assignErrorIfEmpty( ...@@ -537,6 +544,45 @@ export function assignErrorIfEmpty(
} else { } else {
route.throwOnEmptyStaticShell = true // Should throw on empty static shell. route.throwOnEmptyStaticShell = true // Should throw on empty static shell.
} }
if (
computeRemainingPrerenderableParams &&
route.fallbackRouteParams &&
route.fallbackRouteParams.length > 0
) {
const fallbackRouteParamsByName = new Map(
route.fallbackRouteParams.map((param) => [param.paramName, param])
)
const remainingPrerenderableParams: FallbackRouteParam[] = []
// Only unresolved pathname params that can still be filled by
// generateStaticParams belong here. Once we hit an unresolved param
// that is purely dynamic, the rest of the shell also stays dynamic
// and cannot be completed into a more specific prerendered shell.
for (const segment of pathnameSegments) {
if (route.params.hasOwnProperty(segment.paramName)) {
continue
}
if (!segment.hasGenerateStaticParams) {
break
}
const fallbackRouteParam = fallbackRouteParamsByName.get(
segment.paramName
)
if (!fallbackRouteParam) {
break
}
remainingPrerenderableParams.push(fallbackRouteParam)
}
route.remainingPrerenderableParams =
remainingPrerenderableParams.length > 0
? remainingPrerenderableParams
: undefined
}
} }
} }
...@@ -696,6 +742,7 @@ export async function buildAppStaticPaths({ ...@@ -696,6 +742,7 @@ export async function buildAppStaticPaths({
nextConfigOutput, nextConfigOutput,
ComponentMod, ComponentMod,
isRoutePPREnabled = false, isRoutePPREnabled = false,
partialFallbacksEnabled = false,
buildId, buildId,
rootParamKeys, rootParamKeys,
}: { }: {
...@@ -718,6 +765,7 @@ export async function buildAppStaticPaths({ ...@@ -718,6 +765,7 @@ export async function buildAppStaticPaths({
nextConfigOutput: 'standalone' | 'export' | undefined nextConfigOutput: 'standalone' | 'export' | undefined
ComponentMod: AppPageModule | AppRouteModule ComponentMod: AppPageModule | AppRouteModule
isRoutePPREnabled: boolean isRoutePPREnabled: boolean
partialFallbacksEnabled?: boolean
buildId: string buildId: string
rootParamKeys: readonly string[] rootParamKeys: readonly string[]
}): Promise<StaticPathsResult> { }): Promise<StaticPathsResult> {
...@@ -780,6 +828,18 @@ export async function buildAppStaticPaths({ ...@@ -780,6 +828,18 @@ export async function buildAppStaticPaths({
store, store,
isRoutePPREnabled isRoutePPREnabled
) )
const generatedParamNames = new Set<string>()
for (const params of routeParams) {
for (const paramName of Object.keys(params)) {
generatedParamNames.add(paramName)
}
}
const prerenderablePathSegments = pathnameRouteParamSegments.map(
(segment) => ({
paramName: segment.paramName,
hasGenerateStaticParams: generatedParamNames.has(segment.paramName),
})
)
await afterRunner.executeAfter() await afterRunner.executeAfter()
...@@ -1000,7 +1060,11 @@ export async function buildAppStaticPaths({ ...@@ -1000,7 +1060,11 @@ export async function buildAppStaticPaths({
// Now we have to set the throwOnEmptyStaticShell for each of the routes. // Now we have to set the throwOnEmptyStaticShell for each of the routes.
if (prerenderedRoutes && cacheComponents) { if (prerenderedRoutes && cacheComponents) {
assignErrorIfEmpty(prerenderedRoutes, pathnameRouteParamSegments) assignStaticShellMetadata(
prerenderedRoutes,
prerenderablePathSegments,
partialFallbacksEnabled
)
} }
return { fallbackMode, prerenderedRoutes } return { fallbackMode, prerenderedRoutes }
......
...@@ -9,6 +9,7 @@ type StaticPrerenderedRoute = { ...@@ -9,6 +9,7 @@ type StaticPrerenderedRoute = {
readonly fallbackRouteParams: undefined readonly fallbackRouteParams: undefined
readonly fallbackMode: FallbackMode | undefined readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: undefined readonly fallbackRootParams: undefined
remainingPrerenderableParams?: undefined
/** /**
* When enabled, the route will be rendered with diagnostics enabled which * When enabled, the route will be rendered with diagnostics enabled which
...@@ -42,6 +43,7 @@ type FallbackPrerenderedRoute = { ...@@ -42,6 +43,7 @@ type FallbackPrerenderedRoute = {
readonly fallbackRouteParams: readonly FallbackRouteParam[] readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: readonly string[] readonly fallbackRootParams: readonly string[]
remainingPrerenderableParams?: readonly FallbackRouteParam[]
/** /**
* When enabled, the route will be rendered with diagnostics enabled which * When enabled, the route will be rendered with diagnostics enabled which
......
...@@ -992,6 +992,10 @@ export async function handler( ...@@ -992,6 +992,10 @@ export async function handler(
if ( if (
!isMinimalMode && !isMinimalMode &&
isRoutePPREnabled && isRoutePPREnabled &&
// Match the build-time contract: only fallback shells that can
// still be completed with prerenderable params should upgrade.
prerenderInfo?.remainingPrerenderableParams !== undefined &&
prerenderInfo.remainingPrerenderableParams.length > 0 &&
nextConfig.experimental.partialFallbacks === true && nextConfig.experimental.partialFallbacks === true &&
ssgCacheKey && ssgCacheKey &&
incrementalCache && incrementalCache &&
......
...@@ -667,6 +667,7 @@ export async function isPageStatic({ ...@@ -667,6 +667,7 @@ export async function isPageStatic({
cacheHandlers, cacheHandlers,
cacheLifeProfiles, cacheLifeProfiles,
pprConfig, pprConfig,
partialFallbacksEnabled,
buildId, buildId,
clientAssetToken, clientAssetToken,
sriEnabled, sriEnabled,
...@@ -694,6 +695,7 @@ export async function isPageStatic({ ...@@ -694,6 +695,7 @@ export async function isPageStatic({
} }
nextConfigOutput: 'standalone' | 'export' | undefined nextConfigOutput: 'standalone' | 'export' | undefined
pprConfig: ExperimentalPPRConfig | undefined pprConfig: ExperimentalPPRConfig | undefined
partialFallbacksEnabled: boolean
buildId: string buildId: string
clientAssetToken: string clientAssetToken: string
sriEnabled: boolean sriEnabled: boolean
...@@ -857,6 +859,7 @@ export async function isPageStatic({ ...@@ -857,6 +859,7 @@ export async function isPageStatic({
ComponentMod, ComponentMod,
nextConfigOutput, nextConfigOutput,
isRoutePPREnabled, isRoutePPREnabled,
partialFallbacksEnabled,
buildId, buildId,
rootParamKeys, rootParamKeys,
})) }))
......
...@@ -799,6 +799,8 @@ export default class DevServer extends Server { ...@@ -799,6 +799,8 @@ export default class DevServer extends Server {
pathname, pathname,
config: { config: {
pprConfig: this.nextConfig.experimental.ppr, pprConfig: this.nextConfig.experimental.ppr,
partialFallbacks:
this.nextConfig.experimental.partialFallbacks === true,
configFileName, configFileName,
cacheComponents: Boolean(this.nextConfig.cacheComponents), cacheComponents: Boolean(this.nextConfig.cacheComponents),
}, },
......
...@@ -30,6 +30,7 @@ import { parseAppRoute } from '../../shared/lib/router/routes/app' ...@@ -30,6 +30,7 @@ import { parseAppRoute } from '../../shared/lib/router/routes/app'
type RuntimeConfig = { type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined pprConfig: ExperimentalPPRConfig | undefined
partialFallbacks: boolean
configFileName: string configFileName: string
cacheComponents: boolean cacheComponents: boolean
} }
...@@ -147,6 +148,7 @@ export async function loadStaticPaths({ ...@@ -147,6 +148,7 @@ export async function loadStaticPaths({
ComponentMod: components.ComponentMod, ComponentMod: components.ComponentMod,
nextConfigOutput, nextConfigOutput,
isRoutePPREnabled, isRoutePPREnabled,
partialFallbacksEnabled: config.partialFallbacks,
buildId, buildId,
authInterrupts, authInterrupts,
rootParamKeys, rootParamKeys,
......
...@@ -90,6 +90,49 @@ describe('PrerenderManifestMatcher', () => { ...@@ -90,6 +90,49 @@ describe('PrerenderManifestMatcher', () => {
expect(result).toBe(route) expect(result).toBe(route)
}) })
it('should match unknown root branches against the generic source shell', () => {
const generatedRootRoute = createMockDynamicRoute({
fallbackSourceRoute: '/root-gsp/[lang]/[slug]',
routeRegex: '^/root-gsp/en/([^/]+?)(?:/)?$',
fallbackRootParams: [],
fallbackRouteParams: [
{
paramName: 'slug',
paramType: 'dynamic',
},
],
})
const genericRootRoute = createMockDynamicRoute({
fallbackSourceRoute: '/root-gsp/[lang]/[slug]',
routeRegex: '^/root-gsp/([^/]+?)/([^/]+?)(?:/)?$',
fallbackRootParams: ['lang'],
fallbackRouteParams: [
{
paramName: 'lang',
paramType: 'dynamic',
},
{
paramName: 'slug',
paramType: 'dynamic',
},
],
})
const manifest = createMockPrerenderManifest({
'/root-gsp/en/[slug]': generatedRootRoute,
'/root-gsp/[lang]/[slug]': genericRootRoute,
})
const matcher = new PrerenderManifestMatcher(
'/root-gsp/[lang]/[slug]',
manifest
)
expect(matcher.match('/root-gsp/en/two')).toBe(generatedRootRoute)
expect(matcher.match('/root-gsp/fr/two')).toBe(genericRootRoute)
})
}) })
describe('no match scenarios', () => { describe('no match scenarios', () => {
......
export default function Loading() {
return (
<div id="fallback" data-fallback>
loading...
</div>
)
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div id="agent">Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<div id="slug" data-slug={slug}>
{slug}
</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
...@@ -28,4 +28,24 @@ describe('partial-fallback-shell-upgrade', () => { ...@@ -28,4 +28,24 @@ describe('partial-fallback-shell-upgrade', () => {
expect($('#fallback').length).toBe(0) expect($('#fallback').length).toBe(0)
}) })
}) })
it('should not upgrade a route shell when no params were prerendered', async () => {
const pathname = '/no-gsp/two'
const start = Date.now()
await retry(
async () => {
const $ = await next.render$(pathname)
expect($('#fallback').text()).toBe('loading...')
expect($('#slug').closest('[hidden]').length).toBe(1)
if (Date.now() - start < 5000) {
throw new Error('continue polling fallback shell')
}
},
6000,
500,
'no-gsp fallback shell should remain unupgraded'
)
})
}) })
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
describe('adapter-partial-fallback', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should emit partial fallback metadata when infra can upgrade the shell', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const withGspPrerender = outputs.prerenders.find(
(output) => output.pathname === '/with-gsp/[slug]'
)
const withoutGspPrerender = outputs.prerenders.find(
(output) => output.pathname === '/without-gsp/[slug]'
)
const genericPrefixPrerender = outputs.prerenders.find(
(output) => output.pathname === '/prefix/[one]/[two]'
)
const generatedPrefixPrerender = outputs.prerenders.find(
(output) => output.pathname === '/prefix/b/[two]'
)
const genericDashedPrerender = outputs.prerenders.find(
(output) => output.pathname === '/dashed/[my-slug]/[two]'
)
const generatedDashedPrerender = outputs.prerenders.find(
(output) => output.pathname === '/dashed/b/[two]'
)
expect(withGspPrerender).toBeDefined()
expect(withoutGspPrerender).toBeDefined()
expect(genericPrefixPrerender).toBeDefined()
expect(generatedPrefixPrerender).toBeDefined()
expect(genericDashedPrerender).toBeDefined()
expect(generatedDashedPrerender).toBeDefined()
expect(withGspPrerender.config.partialFallback).toBe(true)
expect(withGspPrerender.config.allowQuery).toEqual(['nxtPslug'])
expect(withoutGspPrerender.config.partialFallback).toBeUndefined()
expect(withoutGspPrerender.config.allowQuery).toEqual([])
expect(genericPrefixPrerender.config.partialFallback).toBeUndefined()
expect(genericPrefixPrerender.config.allowQuery).toEqual([])
expect(generatedPrefixPrerender.config.partialFallback).toBeUndefined()
expect(generatedPrefixPrerender.config.allowQuery).toEqual([])
expect(genericDashedPrerender.config.partialFallback).toBeUndefined()
expect(genericDashedPrerender.config.allowQuery).toEqual([])
expect(generatedDashedPrerender.config.partialFallback).toBeUndefined()
expect(generatedDashedPrerender.config.allowQuery).toEqual([])
})
})
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ 'my-slug': string; two: string }>
}) {
const { 'my-slug': mySlug, two } = await params
return (
<div>
<div>
{mySlug}:{two}
</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ 'my-slug': 'b' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return <>{children}</>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>adapter partial fallback fixture</p>
}
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ one: string; two: string }>
}) {
const { one, two } = await params
return (
<div>
<div>
{one}:{two}
</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ one: 'b' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return <>{children}</>
}
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export function generateStaticParams() {
return [{ slug: 'one' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<div>{slug}</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<div>{slug}</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
import fs from 'fs/promises'
/** @type {import('next').NextAdapter } */
export default {
name: 'adapter-partial-fallback',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
adapterPath: require.resolve('./my-adapter.mjs'),
partialFallbacks: true,
},
}
module.exports = nextConfig
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