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

re-introduce partial fallback -> route upgrading (#89063)

In https://github.com/vercel/next.js/pull/69282, we landed support for
Partial Fallback Prerendering. The intention behind this feature was to
be able to upgrade from a partial fallback (essentially the UI produced
when `await params` is dynamic, ie the param was not part of
`generateStaticParams` at build time) to a route shell (when the param
values are filled in, and thus we can prerender more of the page).

It was reverted in https://github.com/vercel/next.js/pull/79258 because
we didn't add first-class support to this in the build output API and
the necessary infrastructure changes to perform similar behavior that
this PR does to trigger a background revalidation with params filled in.

This re-lands the feature in Next.js now that upstream support landed
(https://github.com/vercel/vercel/pull/14703,
https://github.com/vercel/vercel/pull/15338, and Vercel infra changes
which are rolling out)
parent 0268c7b3
...@@ -935,8 +935,8 @@ export async function handler( ...@@ -935,8 +935,8 @@ export async function handler(
: normalizedSrcPage : normalizedSrcPage
const fallbackRouteParams = const fallbackRouteParams =
// If we're in production and we have fallback route params, then we // If we're in production and we have fallback route params, always
// can use the manifest fallback route params. // use them for the fallback shell.
isProduction && prerenderInfo?.fallbackRouteParams isProduction && prerenderInfo?.fallbackRouteParams
? createOpaqueFallbackRouteParams( ? createOpaqueFallbackRouteParams(
prerenderInfo.fallbackRouteParams prerenderInfo.fallbackRouteParams
...@@ -976,6 +976,57 @@ export async function handler( ...@@ -976,6 +976,57 @@ export async function handler(
// Otherwise, if we did get a fallback response, we should return it. // Otherwise, if we did get a fallback response, we should return it.
if (fallbackResponse) { if (fallbackResponse) {
if (
!isMinimalMode &&
isRoutePPREnabled &&
ssgCacheKey &&
incrementalCache &&
!isOnDemandRevalidate &&
!isDebugFallbackShell &&
// The testing API relies on deterministic shell behavior, so
// don't upgrade fallback shells in the background when it's
// exposed.
!exposeTestingApi &&
// Instant Navigation Testing API requests intentionally keep
// the route in shell mode; don't upgrade these in background.
!isInstantNavigationTest &&
// Avoid background revalidate during prefetches; this can trigger
// static prerender errors that surface as 500s for the prefetch
// request itself.
!isPrefetchRSCRequest
) {
scheduleOnNextTick(async () => {
const responseCache = routeModule.getResponseCache(req)
try {
await responseCache.revalidate(
ssgCacheKey,
incrementalCache,
isRoutePPREnabled,
false,
(c) => {
return doRender({
span: c.span,
// Route shell render should not use the fallback params.
postponed: undefined,
fallbackRouteParams: null,
forceStaticRender: true,
})
},
// We don't have a prior entry for this param-specific shell.
null,
hasResolved,
ctx.waitUntil
)
} catch (err) {
console.error(
'Error revalidating the page in the background',
err
)
}
})
}
// Remove the cache control from the response to prevent it from being // Remove the cache control from the response to prevent it from being
// used in the surrounding cache. // used in the surrounding cache.
delete fallbackResponse.cacheControl delete fallbackResponse.cacheControl
......
...@@ -570,6 +570,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -570,6 +570,7 @@ export class IncrementalCache implements IncrementalCacheType {
} }
let entry: IncrementalResponseCacheEntry | null = null let entry: IncrementalResponseCacheEntry | null = null
const { isFallback } = ctx
const cacheControl = this.cacheControls.get(toRoute(cacheKey)) const cacheControl = this.cacheControls.get(toRoute(cacheKey))
let isStale: boolean | -1 | undefined let isStale: boolean | -1 | undefined
...@@ -621,6 +622,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -621,6 +622,7 @@ export class IncrementalCache implements IncrementalCacheType {
cacheControl, cacheControl,
revalidateAfter, revalidateAfter,
value: cacheData.value, value: cacheData.value,
isFallback,
} }
} }
...@@ -638,6 +640,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -638,6 +640,7 @@ export class IncrementalCache implements IncrementalCacheType {
value: null, value: null,
cacheControl, cacheControl,
revalidateAfter, revalidateAfter,
isFallback,
} }
this.set(cacheKey, entry.value, { ...ctx, cacheControl }) this.set(cacheKey, entry.value, { ...ctx, cacheControl })
} }
......
...@@ -143,6 +143,7 @@ export interface IncrementalResponseCacheEntry { ...@@ -143,6 +143,7 @@ export interface IncrementalResponseCacheEntry {
*/ */
isStale?: boolean | -1 isStale?: boolean | -1
isMiss?: boolean isMiss?: boolean
isFallback?: boolean
value: Exclude<IncrementalCacheValue, CachedFetchValue> | null value: Exclude<IncrementalCacheValue, CachedFetchValue> | null
} }
...@@ -178,6 +179,7 @@ export type ResponseCacheEntry = { ...@@ -178,6 +179,7 @@ export type ResponseCacheEntry = {
value: ResponseCacheValue | null value: ResponseCacheValue | null
isStale?: boolean | -1 isStale?: boolean | -1
isMiss?: boolean isMiss?: boolean
isFallback?: boolean
} }
/** /**
......
...@@ -48,6 +48,7 @@ export async function toResponseCacheEntry( ...@@ -48,6 +48,7 @@ export async function toResponseCacheEntry(
isMiss: response.isMiss, isMiss: response.isMiss,
isStale: response.isStale, isStale: response.isStale,
cacheControl: response.cacheControl, cacheControl: response.cacheControl,
isFallback: response.isFallback,
value: value:
response.value?.kind === CachedRouteKind.PAGES response.value?.kind === CachedRouteKind.PAGES
? ({ ? ({
......
...@@ -87,10 +87,10 @@ describe('fallback-shells', () => { ...@@ -87,10 +87,10 @@ describe('fallback-shells', () => {
isNextDev ? 'runtime' : 'buildtime' isNextDev ? 'runtime' : 'buildtime'
) )
// `/bar` was not prerendered, and thus resumes the fallback shell.
await browser.loadPage( await browser.loadPage(
new URL( new URL(
'/with-cached-io/with-static-params/with-suspense/params-in-page/bar', // Use a unique slug so earlier tests don't upgrade this route.
`/with-cached-io/with-static-params/with-suspense/params-in-page/baz`,
next.url next.url
).href ).href
) )
......
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 async function generateStaticParams() {
return [{ slug: 'one' }]
}
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>
)
}
import type { ReactNode } from 'react'
export default async function RootLayout({
children,
}: {
children: ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('partial-fallback-shell-upgrade', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('skipped in dev', () => {})
return
}
it('should upgrade the fallback shell to a route shell', async () => {
const pathname = '/two'
let $ = await next.render$(pathname)
expect($('#fallback').text()).toBe('loading...')
expect($('#slug').closest('[hidden]').length).toBe(1)
await retry(async () => {
$ = await next.render$(pathname)
expect($('#slug').closest('[hidden]').length).toBe(0)
expect($('#fallback').length).toBe(0)
})
})
})
...@@ -85,7 +85,8 @@ describe('middleware-static-rewrite', () => { ...@@ -85,7 +85,8 @@ describe('middleware-static-rewrite', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
if (isNextDeploy) { if (isNextDeploy) {
expect(getCacheHeader(res)).toMatch(/MISS|HIT|PRERENDER/) // We produced a partial fallback shell for rewrite/[slug], so we shouldn't see a cache HIT.
expect(getCacheHeader(res)).toMatch(/MISS|PRERENDER/)
} else { } else {
expect(res.headers.get('x-nextjs-cache')).toBe(null) expect(res.headers.get('x-nextjs-cache')).toBe(null)
} }
...@@ -106,20 +107,25 @@ describe('middleware-static-rewrite', () => { ...@@ -106,20 +107,25 @@ describe('middleware-static-rewrite', () => {
if (isNextDeploy) { if (isNextDeploy) {
expect(getCacheHeader(res)).toBe('HIT') expect(getCacheHeader(res)).toBe('HIT')
} else { } else {
expect(res.headers.get('x-nextjs-cache')).toBe(null) expect(res.headers.get('x-nextjs-cache')).toBe('HIT')
} }
})
html = await res.text()
$ = cheerio.load(html)
expect($('[data-rewrite-slug]').data('rewrite-slug')).toBe('not-broken')
expect($('[data-layout="/"]').data('sentinel')).toBe('buildtime') html = await res.text()
expect($('[data-layout="/rewrite"]').data('sentinel')).toBe('buildtime') $ = cheerio.load(html)
expect($('[data-layout="/rewrite/[slug]"]').data('sentinel')).toBe(
'runtime' expect($('[data-rewrite-slug]').data('rewrite-slug')).toBe('not-broken')
)
// With partial fallback upgrading, the cached entry upgrades from a
// fallback shell to a full route render.
// These assertions are part of the outer retry block because the fallback->route shell upgrade
// happens in the background. It's possible to see a cache HIT for the fallback shell before it
// switches to the full route shell.
expect($('[data-layout="/"]').data('sentinel')).toBe('runtime')
expect($('[data-layout="/rewrite"]').data('sentinel')).toBe('runtime')
expect($('[data-layout="/rewrite/[slug]"]').data('sentinel')).toBe(
'runtime'
)
})
}) })
it('should revalidate the overview page without replacing it with a 404', async () => { it('should revalidate the overview page without replacing it with a 404', async () => {
......
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