Unverified Commit b0b7a429 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Fix missing runtime-follow up if hints are stale (#98278)

if a page didn't use runtime data during build but started doing so
after the revalidation (i.e. the hints say its statically-prefetchable
but now it's not), we're supposed to be doing a follow-up runtime
request based on the `needsRuntimeRequest` promise (introduced in
#96095), but this was not actually happening.

the bug goes as follows:
1. if we get an entry from a static prefetch, but `needsRuntimeRequest`
is true, we save it as `PPR` (or `StaticShell` if it's a shell rewound
from the static response). otherwise, we'd have saved it as `PPRRuntime`
(or `RuntimeShell` for shells) to indicate that it satisfies those
requests.
2. `wouldRuntimeRequestProvideMore` compares the runtime strategy for
the current static walk to the entry's strategy to check if it should do
a runtime request. this boils down to a comparison of `RuntimeShell >
PPR` for a shell request
3. however, in the `FetchStrategy` enum, `RuntimeShell = 2` and `PPR =
3`, so `RuntimeShell > PPR` is false, which makes
`wouldRuntimeRequestProvideMore` return `false`. so, if we have a `PPR`
entry, **we'll never do a follow-up runtime shell request**.

This is fixed by swapping the order of the two values in the enum.

Now, if we end up with a `PPR` response where `needsRuntimeRequest` is
true due to runtime data, that indicates that we *should've done a
runtime request in the first place*, we just didn't know we should do so
because the prefetch hint was stale, so the new ordering achieves the
correct behavior, i.e. `pingSegmentBundle` decides that it needs a
runtime shell request, which makes it match the intended PPF prefetching
behavior.

The enum ordering is a bit of a lie, because there is no single correct
ordering -- a `PPR` entry *might actually provide more content* than a
`ShellRuntime` entry if the route uses static params. In practice this
is resolved by the vary path (shell responses are keyed with fallback
params, and a PPR entry with static params would have the actual param
values, and the param-ful entry would end up being preferred) so the
strategy order wouldn't matter.

Now that `RuntimeShell` beats `PPR`, i had to disable the strategy
upgrading (`StaticShell -> RuntimeShell` and `PPR -> PPRRuntime`) on
routes that don't use Partial Prefetching -- otherwise, a
rewound`ShellRuntime` entry from a different param was winning over
`PPR` in `pingSegmentBundle`, so it was preventing issuing new static
requests even if we needed to do them. However, without PPF, the runtime
tiers are not meaningful anyway, so this should be fine.

### Other bugs

This fix also revealed a bug where `FetchStrategy.Full` requests were
writing a shell as `RuntimeShell` even though the byte offset only marks
a *static* shell. I've refactored the logic for picking the strategies
to fix this and make it more explicit.

### Edge cases

there is one (somewhat involved) edge case to this that i know of.
if the post-revalidation static response has:

1. a shell that didn't access runtime data (i.e. `needsRuntimeRequest =
false` in the shell stage)
2. a prefetch that did access runtime data (i.e. `needsRuntimeRequest =
true` in the static stage)

then we'll:

1. write the shell as `ShellRuntime` (because `needsRuntimeRequest =
false`, and a runtime shell would not in fact provide more data)
2. write the prefetch as `PPR` (and not `PPRRuntime`, because
`needsRuntimeRequest = true`, and a runtime prefetch *would* provide
more data)

with the new ordering, this means we'll end up preferring the
`ShellRuntime` entry over the `PPR` entry even though the shell is a
strict subset of it and would be missing static params and content gated
behind `prefetch()` or `navigation()`. (note that this only happens if
they share the same vary path)

this can be observed as follows:
1. when a `<Link prefetch={true}>` to such a page is revealed, we won't
request a runtime shell (due to already having a `ShellRuntime` entry),
but we will request a runtime prefetch (because `PPR` is not enough). so
far this is correct
2. if the navigation happens **before** this runtime prefetch completes,
we will display what we already have. but we'll prefer the rewound
`ShellRuntime` shell entry over than the `PPR` entry it originated from
because of the enum ordering. so we may end up not showing content
despite having it in the cache

i'm not sure how to resolve this yet, but i think the current
`recordedFetchStrategy` trick can't handle this, and we need a more
involved mechanism that can detect when the `PPR` entry is actually
better. i don't consider this a blocker for this fix though
parent f4449e8f
......@@ -2818,15 +2818,13 @@ function writeResponsePayloadsIntoCache(
// writeServerResponseIntoCache.
map: CacheMap<SegmentCacheEntry>
): Array<FulfilledSegmentCacheEntry> | null {
const isStaticResponse =
fetchStrategy === FetchStrategy.PPR ||
fetchStrategy === FetchStrategy.StaticShell
const shellWasRequested =
fetchStrategy === FetchStrategy.StaticShell ||
fetchStrategy === FetchStrategy.RuntimeShell
let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null
if (shellPayload === null) {
if (
shellPayload === null ||
// `FetchStrategy.LoadingBoundary` is not used in Cache Components,
// and we only recover shells in Cache Components.
fetchStrategy === FetchStrategy.LoadingBoundary
) {
if (fetchStrategy === FetchStrategy.StaticShell) {
// A static shell was requested but the response carries no shell (its
// shell byte offset read as 0 — a bug in Next.js itself — or the
......@@ -2864,7 +2862,8 @@ function writeResponsePayloadsIntoCache(
}
// This request either:
// - didn't allow recovering a shell (no staged rendering),
// - or was a (runtime) shell request, so we already have a shell without recovering anything.
// - or was a (runtime) shell request (that was NOT served by a fully static prerender)
// so we already have a shell without recovering anything.
// In either case, we don't have anything to consider other than the request itself,
// so the payload simply fulfills the spawned entries at the request's own keying.
fulfilledEntries = writeServerResponseIntoCache(
......@@ -2892,6 +2891,33 @@ function writeResponsePayloadsIntoCache(
// evidence, so it must not be parked in the shell slot on the strength
// of the missing split alone (see the keying derivation in
// writeSegmentDataIntoCache).
let contentFetchStrategy:
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| null
switch (fetchStrategy) {
case FetchStrategy.StaticShell: {
// a StaticShell always uses a PPR-tier request, so we need to fulfill
// the spawned shell entries at the PPR tier.
contentFetchStrategy = FetchStrategy.PPR
break
}
case FetchStrategy.RuntimeShell: {
// a runtime shell request is not normally rewindable, but fully static pages
// the server will return a static prerender result, which *is* rewindable.
contentFetchStrategy = FetchStrategy.PPRRuntime
break
}
case FetchStrategy.PPR:
case FetchStrategy.PPRRuntime:
case FetchStrategy.Full: {
// No shell was requested, so we don't need to override the fetch strategy.
contentFetchStrategy = null
}
}
fulfilledEntries = writeServerResponseIntoCache(
now,
fetchStrategy,
......@@ -2905,16 +2931,7 @@ function writeResponsePayloadsIntoCache(
isFullResponsePartial,
metadataVaryPath,
spawnedEntries,
// The full payload's tier: PPR for a static response, PPRRuntime for
// a runtime response (whose full payload is everything a runtime
// prefetch can produce when nothing lies below the shell). For a
// full-tier request it agrees with the request's own strategy, so
// only shell-tier requests pass it.
shellWasRequested
? isStaticResponse
? FetchStrategy.PPR
: FetchStrategy.PPRRuntime
: null,
contentFetchStrategy,
map
)
} else {
......@@ -2937,20 +2954,63 @@ function writeResponsePayloadsIntoCache(
// so the shell write's precedence checks and shadow eviction compare
// against the fresh concrete entry rather than whatever stale entry
// preceded it.
let responseFetchStrategy: FetchStrategy
let shellFetchStrategy: FetchStrategy
switch (fetchStrategy) {
case FetchStrategy.StaticShell:
case FetchStrategy.PPR: {
// Static request.
// a StaticShell fetch strategy performs a request that returns
// a PPR-tier response that can be rewound to a StaticShell response,
// So we upgrade the full response's strategy to `PPR`.
// (A static response's tier may be raised if we know that a static request
// would satisfy a runtime request -- see `recordedFetchStrategy` in
// `writeSegmentDataIntoCache`)
responseFetchStrategy = FetchStrategy.PPR
shellFetchStrategy = FetchStrategy.StaticShell
break
}
case FetchStrategy.RuntimeShell: {
// A runtime shell request is normally not rewindable -- it only produces
// the shell itself. However, if a page is fully static, a runtime shell
// will return a static prerender, i.e. the static content with an embedded shell.
// The page is static, so we can treat the content as runtime-complete.
responseFetchStrategy = FetchStrategy.PPRRuntime
shellFetchStrategy = FetchStrategy.RuntimeShell
break
}
case FetchStrategy.PPRRuntime: {
// A runtime prefetch response can be rewound into a runtime shell.
// (This may also be a fully static response, same as RuntimeShell above,
// in which case we also know that the shell is equivalent to a runtime shell)
responseFetchStrategy = FetchStrategy.PPRRuntime
shellFetchStrategy = FetchStrategy.RuntimeShell
break
}
case FetchStrategy.Full: {
// Navigation responses can be rewound into a *static* app shell.
// On PPF routes they also contain a runtime prefetch stream which will give us
// a runtime shell/prefetch, but that's handled separately from the main response.
// (see `writeRuntimePrefetchStreamIntoCache`)
responseFetchStrategy = FetchStrategy.Full
shellFetchStrategy = FetchStrategy.StaticShell
break
}
}
// We have to fulfill the correct pending entries depending on what was requested:
// - If we originally needed a shell but and got more content, the spawned entries
// should be fulfilled using the shell.
// - If we needed a speculative or full request but rewound it into a shell,
// the spawned entries should be fulfilled using the full response.
const wasShellRequested =
fetchStrategy === FetchStrategy.StaticShell ||
fetchStrategy === FetchStrategy.RuntimeShell
const fullFulfilledEntries = writeServerResponseIntoCache(
now,
// The full payload is written at the request's own tier, except for
// shell-tier requests: when a shell request returns more than the
// shell, the extra content is at least as complete as what the
// corresponding non-shell request would have returned — PPR for a
// StaticShell request, PPRRuntime for a RuntimeShell request. Record
// that tier so the scheduler doesn't re-request content this payload
// already provides. (Same rule as the coincident-shell case below.)
shellWasRequested
? isStaticResponse
? FetchStrategy.PPR
: FetchStrategy.PPRRuntime
: fetchStrategy,
responseFetchStrategy,
fullPayload,
baseTree,
predictedFromRoute,
......@@ -2960,13 +3020,14 @@ function writeResponsePayloadsIntoCache(
staleAt,
isFullResponsePartial,
metadataVaryPath,
shellWasRequested ? null : spawnedEntries,
wasShellRequested ? null : spawnedEntries,
null,
map
)
const shellFulfilledEntries = writeServerResponseIntoCache(
now,
isStaticResponse ? FetchStrategy.StaticShell : FetchStrategy.RuntimeShell,
shellFetchStrategy,
shellPayload,
baseTree,
predictedFromRoute,
......@@ -2984,11 +3045,11 @@ function writeResponsePayloadsIntoCache(
// by construction.
true,
metadataVaryPath,
shellWasRequested ? spawnedEntries : null,
wasShellRequested ? spawnedEntries : null,
null,
map
)
fulfilledEntries = shellWasRequested
fulfilledEntries = wasShellRequested
? shellFulfilledEntries
: fullFulfilledEntries
}
......@@ -3027,13 +3088,7 @@ function writeResponsePayloadsIntoCache(
*/
function writeServerResponseIntoCache(
now: number,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.RuntimeShell
| FetchStrategy.StaticShell
| FetchStrategy.Full,
fetchStrategy: FetchStrategy,
// The decoded response payload to write. For a per-segment prefetch
// response this is one of its payloads: the full response, or the
// truncated shell decode.
......@@ -3140,6 +3195,10 @@ function writeServerResponseIntoCache(
// unknown to use the default.
UnknownDynamicStaleTime
)
const requiresRuntimeCompleteness =
(navigationSeed.routeTree.prefetchHints &
PrefetchHint.SubtreeHasPartialPrefetching) !==
0
const treeDivergedFromPrediction =
predictedFromRoute !== null && navigationSeed.treeDivergedFromBase
......@@ -3196,6 +3255,7 @@ function writeServerResponseIntoCache(
spawnedEntries,
contentFetchStrategy,
isUpgradeableISRFallback,
requiresRuntimeCompleteness,
responseNeedsRuntimeRequest,
writtenEntries
)
......@@ -3230,6 +3290,7 @@ function writeServerResponseIntoCache(
spawnedEntries,
contentFetchStrategy,
isUpgradeableISRFallback,
requiresRuntimeCompleteness,
responseNeedsRuntimeRequest
)
if (writtenHeadEntry !== null) {
......@@ -3261,18 +3322,13 @@ function writeServerResponseIntoCache(
function writeTreeDataIntoCache(
now: number,
map: CacheMap<SegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.RuntimeShell
| FetchStrategy.StaticShell
| FetchStrategy.Full,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>,
staleAt: number,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,
contentFetchStrategy: FetchStrategy.PPR | FetchStrategy.PPRRuntime | null,
isUpgradeableISRFallback: boolean,
requiresRuntimeCompleteness: boolean,
responseNeedsRuntimeRequest: boolean | null,
// Accumulates the entries the walk wrote content into (fulfilled spawned
// entries and installed detached upserts), for LRU size accounting.
......@@ -3300,6 +3356,7 @@ function writeTreeDataIntoCache(
spawnedEntries,
contentFetchStrategy,
isUpgradeableISRFallback,
requiresRuntimeCompleteness,
responseNeedsRuntimeRequest
)
if (writtenEntry !== null) {
......@@ -3327,6 +3384,7 @@ function writeTreeDataIntoCache(
spawnedEntries,
contentFetchStrategy,
isUpgradeableISRFallback,
requiresRuntimeCompleteness,
responseNeedsRuntimeRequest,
writtenEntries
)
......@@ -3350,13 +3408,7 @@ function writeTreeDataIntoCache(
function writeSegmentDataIntoCache(
now: number,
map: CacheMap<SegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.RuntimeShell
| FetchStrategy.StaticShell
| FetchStrategy.Full,
fetchStrategy: FetchStrategy,
rsc: React.ReactNode,
isPartial: boolean,
staleAt: number,
......@@ -3368,8 +3420,7 @@ function writeSegmentDataIntoCache(
// drives matching and keying); null when they agree. It differs only for
// the coincident-shell case: a write that fulfills shell-keyed entries
// with a payload that IS the full response passes the full payload's tier
// (PPR for a per-segment static response, PPRRuntime for a RuntimeShell
// response) — see writeResponsePayloadsIntoCache.
// — see writeResponsePayloadsIntoCache.
contentFetchStrategy: FetchStrategy.PPR | FetchStrategy.PPRRuntime | null,
// Whether the response is an upgradeable fallback shell. Always false for
// live-render responses — they are never ISR fallbacks.
......@@ -3381,6 +3432,7 @@ function writeSegmentDataIntoCache(
// none; per-segment prefetch responses and prerendered page payloads
// (including the truncated initial payload) do — in which case the entry
// records the payload's tier unrefined.
requiresRuntimeCompleteness: boolean,
responseNeedsRuntimeRequest: boolean | null
): FulfilledSegmentCacheEntry | null {
// The strategy tier recorded on the entry — the tier of the content that
......@@ -3421,23 +3473,28 @@ function writeSegmentDataIntoCache(
// tier.
recordedFetchStrategy = contentFetchStrategy ?? fetchStrategy
} else {
// The verdict says this payload is runtime-complete: refine the recorded
// tier UP to the runtime tier of the same variant. Only the static
// tiers have a runtime counterpart to refine to; any other payload tier
// records itself — never below the payload's own tier. (This also makes
// the verdict inert for Full payloads, which matters because the Full
// flow decodes incrementally and `response.u` is read off the thenable's
// status — only sound on fully-buffered decodes. A prerendered page
// payload served to a Full prefetch carries a verdict; a not-yet-arrived
// row misreads as `false`, and without this clamp that would downgrade a
// Full-tier write to PPRRuntime.)
const payloadFetchStrategy = contentFetchStrategy ?? fetchStrategy
if (requiresRuntimeCompleteness) {
// The verdict says this payload does not need a runtime request.
// If we requested it at a static tier, raise the recorded tier up to the
// runtime tier of the same variant.
// This also makes the verdict a noop for Full payloads, which matters because
// the Full flow decodes incrementally, and synchronously reading `response.u`
// is only sound for a buffered payload.
recordedFetchStrategy =
payloadFetchStrategy === FetchStrategy.StaticShell
? FetchStrategy.RuntimeShell
: payloadFetchStrategy === FetchStrategy.PPR
? FetchStrategy.PPRRuntime
: payloadFetchStrategy
} else {
// Only upgrade static segments to their runtime equivalents if the route
// can use runtime requests. Otherwise, when re-using a shell segment across
// params, `pingSegmentBundle` for a PPR strategy would see a `ShellRuntime`
// shell entry and incorrectly decide that a new PPR request would not
// provide more content.
recordedFetchStrategy = payloadFetchStrategy
}
}
// Decide whether to re-key the entry under a more generic vary path based on
......@@ -3791,10 +3848,10 @@ function addSegmentPathToUrlInOutputExportMode(
* - `StaticShell` provides the shell-stage variant extracted from a static response —
* param-dependent content reduced to pending fallbacks, and never any content that
* depends on session data (cookies, headers)
* - `PPR` can provide static shells for each segment, including prerendered param-dependent
* content at concrete paths (excluding dynamic data)
* - `RuntimeShell` provides the shell stage rendered by a runtime request, which can
* additionally include shell-stage content that depends on session data
* - `PPR` can provide shells for each segment (even for segments that use dynamic data),
* including prerendered param-dependent content at concrete paths
* - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies
* - `Full` includes all the content, even if it uses dynamic data
*
......
......@@ -2259,6 +2259,8 @@ function pingSegmentBundle(
// entry itself — nothing ever pings a Rejected entry.
break
case EntryStatus.Fulfilled: {
let willBeSupersededByRuntimeRequest = false
if (walkRequiresRuntimeCompleteness(fetchStrategy, route)) {
const runtimeWouldProvideMore = wouldRuntimeRequestProvideMore(
nodeEntry,
fetchStrategy
......@@ -2287,7 +2289,18 @@ function pingSegmentBundle(
// eligible shell-tier entry withholds the signal for this pass:
// the static attempt spawned below blocks the task, and the re-run
// pass reads the attempt's result instead.)
needsRuntimeRequest = true
// If a runtime request would return more content skip the static path
// entirely — unless the entry is an eligible shell-tier entry (see above),
// whose static attempt IS this upgrade.
// Otherwise the runtime request covers this segment and supersedes
// anything a static fetch could add, so a static upgrade would at best
// duplicate it — delivering the same content twice — and at worst replace
// runtime content with static content.
willBeSupersededByRuntimeRequest = true
}
}
// For entries below this phase's tier, upgrade during the phase
......@@ -2295,23 +2308,8 @@ function pingSegmentBundle(
// Speculative phase is to bring the cache up to the
// per-link-concrete tier. `isPartial` ensures a complete entry isn't
// re-fetched.
//
// Exception: when a runtime request would return more AND this walk
// permits one, skip the static path entirely — unless the entry is
// an eligible shell-tier entry (see above), whose static attempt IS
// this upgrade. Otherwise the runtime request covers this segment
// and supersedes anything a static fetch could add, so a static
// upgrade would at best duplicate it — delivering the same content
// twice — and at worst replace runtime content with static content.
//
// When no runtime request is permitted, the signal is irrelevant:
// nothing can act on it, so it must not suppress the static upgrade.
// That's what keeps a link prefetching static content on top of a
// cached shell.
const willBeSupersededByRuntimeRequest =
runtimeWouldProvideMore &&
!shellEntryEligibleForStaticAttempt &&
walkRequiresRuntimeCompleteness(fetchStrategy, route)
// If we can use runtime requests and a runtime request would provide more
// data, we also skip the upgrade (see `willBeSupersededByRuntimeRequest`)
// Check if we should attempt to upgrade a fallback ISR response to
// a concrete version.
......
......@@ -59,8 +59,8 @@ export const enum FetchStrategy {
// session data (cookies, headers) — and less complete than PPR at concrete
// paths, which includes prerendered param-dependent content.
StaticShell = 1,
RuntimeShell = 2,
PPR = 3,
PPR = 2,
RuntimeShell = 3,
PPRRuntime = 4,
Full = 5,
}
......
export default async function Layout({ children }: LayoutProps<'/'>) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default async function Page() {
return (
<main>
<h2>Conditional cookies in the shell of a static page</h2>
<ul>
<li>
<LinkAccordion href="/static-conditional-cookies-in-shell/static-shell-equal-to-prefetch">
/static-conditional-cookies-in-shell/static-shell-equal-to-prefetch
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/static-conditional-cookies-in-shell/static-shell-smaller-than-prefetch">
/static-conditional-cookies-in-shell/static-shell-smaller-than-prefetch
</LinkAccordion>
</li>
</ul>
<h2>Conditional cookies in the shell of a partial page</h2>
<ul>
<li>
<LinkAccordion href="/partial-conditional-cookies-in-shell/static-shell-equal-to-prefetch">
/partial-conditional-cookies-in-shell/static-shell-equal-to-prefetch
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/partial-conditional-cookies-in-shell/static-shell-smaller-than-prefetch">
/partial-conditional-cookies-in-shell/static-shell-smaller-than-prefetch
</LinkAccordion>
</li>
</ul>
<h2>Conditional cookies in the prefetch of a partial page</h2>
<ul>
<li data-prefetch="auto">
<LinkAccordion href="/partial-conditional-cookies-in-prefetch">
/partial-conditional-cookies-in-prefetch (auto prefetch)
</LinkAccordion>
</li>
<li data-prefetch="true">
<LinkAccordion
href="/partial-conditional-cookies-in-prefetch"
prefetch={true}
>
/partial-conditional-cookies-in-prefetch (prefetch=true)
</LinkAccordion>
</li>
</ul>
</main>
)
}
import { ConditionalCookies } from '../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
export default async function Page() {
return (
<main>
<h1>Partial page that conditionally uses cookies in the prefetch</h1>
<Suspense
fallback={
<div id="prefetch-data-fallback">Loading prefetch data...</div>
}
>
<PrefetchOnly>
<div id="prefetch-data">Prefetch data</div>
<ConditionalCookies />
</PrefetchOnly>
</Suspense>
<Suspense
fallback={<div id="dynamic-data-fallback">Loading dynamic data...</div>}
>
<DynamicData />
</Suspense>
</main>
)
}
async function PrefetchOnly({ children }) {
await unstable_prefetch()
return children
}
async function DynamicData() {
await connection()
return <div id="dynamic-data">Dynamic data</div>
}
import { ConditionalCookies } from '../../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<h1>Partial page that conditionally uses cookies in the shell</h1>
<ConditionalCookies />
<Suspense
fallback={<div id="dynamic-data-fallback">Loading dynamic data...</div>}
>
<DynamicData />
</Suspense>
</main>
)
}
async function DynamicData() {
await connection()
return <div id="dynamic-data">Dynamic data</div>
}
import { ConditionalCookies } from '../../../cached-value'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_prefetch } from 'next/cache'
export default async function Page() {
return (
<main>
<h1>
Partial page that conditionally uses cookies in the shell, but also has
prefetch-only content
</h1>
<ConditionalCookies />
<Suspense
fallback={
<div id="prefetch-data-fallback">Loading prefetch data...</div>
}
>
<PrefetchData />
</Suspense>
<Suspense
fallback={<div id="dynamic-data-fallback">Loading dynamic data...</div>}
>
<DynamicData />
</Suspense>
</main>
)
}
async function DynamicData() {
await connection()
return <div id="dynamic-data">Dynamic data</div>
}
async function PrefetchData() {
await unstable_prefetch()
return <div id="prefetch-data">Prefetch data</div>
}
import { resetCachedValue } from '../../cached-value'
export async function POST() {
const newValue = await resetCachedValue()
return Response.json(newValue)
}
import { ConditionalCookies } from '../../../cached-value'
export default async function Page() {
return (
<main>
<h1>Static page that conditionally uses cookies in the shell</h1>
<ConditionalCookies />
</main>
)
}
import { ConditionalCookies } from '../../../cached-value'
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
export default async function Page() {
return (
<main>
<h1>
Static page that conditionally uses cookies in the shell, but also has
prefetch-only content
</h1>
<ConditionalCookies />
<Suspense
fallback={
<div id="prefetch-data-fallback">Loading prefetch data...</div>
}
>
<PrefetchData />
</Suspense>
</main>
)
}
async function PrefetchData() {
await unstable_prefetch()
return <div id="prefetch-data">Prefetch data</div>
}
import { updateCachedValue } from '../../cached-value'
export async function POST() {
const newValue = await updateCachedValue()
return Response.json(newValue)
}
import { cacheTag, revalidateTag, unstable_prefetch } from 'next/cache'
import * as fs from 'node:fs'
import { Suspense } from 'react'
import { cookies } from 'next/headers'
// value.json at the root of the app
let CACHE_FILE: string
if (process.env.CACHE_FILE) {
// allow overriding, because that can be useful when running the app directly
CACHE_FILE = process.env.CACHE_FILE
} else {
// resolving a relative path seems strangely difficult to do consistently
// in a way that works both when running the app directly and when running
// it in tests, so we rely on the app root being at CWD instead
CACHE_FILE = process.cwd() + '/value.json'
if (!fs.existsSync(/*turbopackIgnore: true*/ CACHE_FILE)) {
throw new Error(
`Cache file not found at ${CACHE_FILE}. This app must run with its root as CWD or provide a path to a cache file via the CACHE_FILE environment variable`
)
}
}
const CACHE_TAG = 'cache-value'
export type Value = { tag: 'original' | 'updated'; timestamp: number }
export async function updateCachedValue(): Promise<Value> {
const newValue: Value = { tag: 'updated', timestamp: Date.now() }
writeNewValue(newValue)
return newValue
}
export async function resetCachedValue(): Promise<Value> {
const newValue: Value = { tag: 'original', timestamp: -1 }
writeNewValue(newValue)
return newValue
}
function writeNewValue(value: Value) {
fs.writeFileSync(CACHE_FILE, JSON.stringify(value))
revalidateTag(CACHE_TAG, { expire: 0 })
}
export async function getCachedValue(): Promise<Value> {
'use cache'
cacheTag(CACHE_TAG)
const value: Value = JSON.parse(
fs.readFileSync(/*turbopackIgnore: true*/ CACHE_FILE, 'utf8')
)
return value
}
export async function ConditionalCookies() {
const cachedValue = await getCachedValue()
// The tag is "original" during build and switches to "updated" after revalidation.
const shouldUseCookies = cachedValue.tag !== 'original'
return (
<div>
<p>{`Cached value: ${cachedValue.tag}, cookies used: ${shouldUseCookies}`}</p>
{shouldUseCookies && (
<Suspense
fallback={<div id="cookie-data-fallback">Loading cookie data...</div>}
>
<CookieData />
</Suspense>
)}
</div>
)
}
async function CookieData() {
await cookies()
return (
<>
<div id="cookie-data">Cookie data</div>
<Suspense
fallback={
<div id="cookies-runtime-prefetch-data-fallback">
Loading runtime prefetch data... (behind cookies)
</div>
}
>
<RuntimePrefetchData />
</Suspense>
</>
)
}
async function RuntimePrefetchData() {
await unstable_prefetch()
return (
<div id="cookies-runtime-prefetch-data">
Runtime prefetch data (behind cookies)
</div>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: boolean
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
experimental: {
// reactDebugChannel: true
},
typescript: {
ignoreBuildErrors: true,
},
productionBrowserSourceMaps: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import { retry } from 'next-test-utils'
/**
* When a page switches from static to partial during a revalidation,
* it continues serving static prerender responses for navigations
* and runtime prefetches even though it shouldn't.
*
* This variable enables failing assertions that demonstrate this.
* We keep both codepaths to also demonstrate the current (incorrect) behavior.
* */
const REPRODUCE_STATIC_PAGE_UPGRADE_BUG =
!!process.env.REPRODUCE_STATIC_PAGE_UPGRADE_BUG || false
/**
* When a page switches from static to partial during a revalidation,
* and the response indicates that runtime data should be used,
* we'll perform a runtime follow up. However, if a navigation happens
* before the runtime prefetch completes and the shell and the prefetch
* share the same vary path, we'll show the static app shell
* instead of the static prefetch if the latter has more content.
*
* This variable enables failing assertions that demonstrate this.
* We keep both codepaths to also demonstrate the current (incorrect) behavior.
* */
const REPRODUCE_STATIC_SHELL_PRECEDENCE_BUG =
!!process.env.REPRODUCE_STATIC_SHELL_PRECEDENCE_BUG || false
describe('App Shell revalidation', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true, // modifies files at runtime
})
if (skipped) return
if (isNextDev) {
it('is skipped', () => {})
return
}
async function updateCachedValue() {
await next.fetch('/update-cached-value', { method: 'POST' })
}
async function resetCachedValue() {
await next.fetch('/reset-cached-value', { method: 'POST' })
}
async function updateAndWaitForRevalidation(route: string) {
await updateCachedValue()
await retry(async () => {
const response = await next.fetch(route).then((res) => res.text())
expect(response).toContain(`Cached value: updated`)
})
console.log(`--------------------------------------`)
console.log(`${route} :: finished revalidating`)
console.log(`--------------------------------------`)
}
// The tests are split into two to avoid dealing with browser caches
// after a revalidation.
// We do two assertions:
// 1. The page uses static requests if the page doesn't use runtime data
// (when the cache returns its initial value)
// 2. The page uses runtime follow-ups when the page *does* use runtime data
// (when the cache returns its updated value)
describe.each([
{
description:
'static page that only starts reading cookies in the shell after a revalidation',
route:
'/static-conditional-cookies-in-shell/static-shell-equal-to-prefetch',
hasPrefetchData: false,
},
{
// A variation of the previous test that includes prefetch-only content,
// to make sure that this also works if the extracted static shell is not
// equal to the static prefetch.
description:
'static page with prefetch-only content that only starts reading cookies in the shell after a revalidation',
route:
'/static-conditional-cookies-in-shell/static-shell-smaller-than-prefetch',
hasPrefetchData: true,
},
])('$description', ({ route, hasPrefetchData }) => {
// We should upgrade from a static shell to a runtime shell after a revalidation
// despite the build-time hints being stale.
afterAll(() => resetCachedValue())
it('uses static requests when the page does not use cookies', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a link to the page.
// It was fully static during build, so it should use static requests.
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
}, [
// Only a static request.
{ includes: 'Cached value: original', kind: 'static' },
{ includes: '', kind: 'runtime', block: 'reject' },
])
// The route is fully static, so we should navigate without extra requests.
await act(async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
}, 'no-requests')
})
it('[FAILING] starts using runtime requests when the page starts using cookies after a revalidation', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Update the cache and for revalidation to settle before opening the page
await updateAndWaitForRevalidation(route)
// Reveal a link to the page. We should see revalidated content.
// After the revalidation, the page starts using cookies in the shell.
if (REPRODUCE_STATIC_PAGE_UPGRADE_BUG) {
// Expected behavior
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
}, [
// First, a static request (because the page was statically optimized at build time).
// This response should signal to the client router that runtime requests are still needed.
{ includes: 'Cached value: updated', kind: 'static' },
// Then, a runtime shell follow-up.
{ includes: 'Cookie data', kind: 'runtime' },
// This should be a runtime shell, i.e. we should not see runtime prefetch content.
{
includes: 'Runtime prefetch data (behind cookies)',
block: 'reject',
},
])
} else {
// Actual behavior
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
}, [
// First, a static request (because the page was statically optimized at build time).
// This response should signal to the client router that runtime requests are still needed.
{ includes: 'Cached value: updated', kind: 'static' },
// We *do* issue a follow up runtime request, but it just returns
// the static prerender result (under a `next-router-prefetch: 3` response).
// It includes data gated behind `prefetch()` (which a shell would not do)...
{
includes: hasPrefetchData
? 'Prefetch data'
: 'Static page that conditionally uses cookies in the shell',
kind: 'runtime',
},
// ...and does not include cookies:
{ includes: 'Cookie data', kind: 'runtime', block: 'reject' },
])
}
// Navigate to the page. It became partial after revalidation, so we should
// do another request.
if (REPRODUCE_STATIC_PAGE_UPGRADE_BUG) {
// Expected behavior
await act(
async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
// We should show contents from the runtime shell while navigating.
expect(await browser.elementById('cookie-data').text()).toEqual(
'Cookie data'
)
},
// The runtime shell is complete, so no extra requests should be needed.
'no-requests'
)
expect(await browser.elementById('cookie-data').text()).toEqual(
'Cookie data'
)
} else {
// Actual behavior (incorrect)
await act(async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
// The server did not actually return a runtime shell, so we don't see cookies,
// just the static prerender result.
expect(
await browser.elementById('cookie-data-fallback').text()
).toEqual('Loading cookie data...')
if (hasPrefetchData) {
// We do however show `prefetch()` data, because a static prerender includes those.
expect(await browser.elementById('prefetch-data').text()).toBe(
'Prefetch data'
)
}
}, [
// The navigation request *also* incorrectly returns the (partial) static prerender
// result, which does not contain cookies.
{
includes:
'Static page that conditionally uses cookies in the shell',
},
{ includes: 'Cookie data', block: 'reject' },
])
// The navigation response was partial, so decoding the payload errors with
// with "Connection Closed" and crashes the page.
expect(await browser.elementById('__next_error__').text()).toContain(
'This page couldn’t load'
)
}
})
})
describe.each([
{
description:
'partial page that only starts reading cookies in the shell after a revalidation',
route:
'/partial-conditional-cookies-in-shell/static-shell-equal-to-prefetch',
hasPrefetchData: false,
},
{
// A variation of the previous test that includes prefetch-only content,
// to make sure that this also works if the extracted static shell is not
// equal to the static prefetch.
description:
'partial page with prefetch-only content that only starts reading cookies in the shell after a revalidation',
route:
'/partial-conditional-cookies-in-shell/static-shell-smaller-than-prefetch',
hasPrefetchData: true,
},
])('$description', ({ route, hasPrefetchData }) => {
// We should upgrade from a static shell to a runtime shell after a revalidation
// despite the build-time hints being stale.
afterAll(() => resetCachedValue())
it('uses static requests when the page does not use cookies', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a link to the page.
// It used dynamic data during build, so it's partial, but it did not
// use runtime data, so it should use static requests.
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
}, [
// Only a static request.
{ includes: 'Cached value: original', kind: 'static' },
{ includes: '', kind: 'runtime', block: 'reject' },
])
if (hasPrefetchData) {
// The route has static prefetch-only data. We should be showing it
// while the navigation is pending (instead of the extracted static app shell)
await act(async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
expect(await browser.elementById('prefetch-data').text()).toBe(
'Prefetch data'
)
})
}
})
it('starts using runtime requests when the page starts using cookies after a revalidation', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Update the cache and for revalidation to settle before opening the page
await updateAndWaitForRevalidation(route)
// Reveal a link to the page. We should see revalidated content.
// After the revalidation, the page starts using cookies in the shell.
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
}, [
// First, a static request (because the page was statically optimized at build time).
// This response should signal to the client router that runtime requests are still needed.
{ includes: 'Cached value: updated', kind: 'static' },
// Then, a runtime shell follow-up.
{ includes: 'Cookie data', kind: 'runtime' },
// This should be a runtime shell, i.e. we should not see runtime prefetch content.
{ includes: 'Runtime prefetch data (behind cookies)', block: 'reject' },
])
// Navigate to the page.
await act(async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
// We should show contents from the runtime shell while navigating.
expect(await browser.elementById('cookie-data').text()).toEqual(
'Cookie data'
)
}, [{ includes: 'Dynamic data' }])
expect(await browser.elementById('dynamic-data').text()).toEqual(
'Dynamic data'
)
})
})
describe('partial page that only starts reading cookies in the prefetch after a revalidation', () => {
// We should upgrade from a static shell to a runtime shell after a revalidation
// despite the build-time hints being stale.
const route = '/partial-conditional-cookies-in-prefetch'
afterAll(() => resetCachedValue())
it('uses static requests when the page does not use cookies', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a link to the page.
// It used dynamic data during build, so it's partial, but it did not
// use runtime data, so it should use static requests.
await act(async () => {
await browser
.elementByCss(
`[data-prefetch="auto"] input[data-link-accordion="${route}"]`
)
.click()
}, [
// Only a static request.
{ includes: 'Cached value: original', kind: 'static' },
{ includes: '', kind: 'runtime', block: 'reject' },
])
// The route has static prefetch-only data. We should be showing it
// while the navigation is pending (instead of the extracted static app shell)
await act(async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
expect(await browser.elementById('prefetch-data').text()).toBe(
'Prefetch data'
)
})
})
it('starts using runtime requests when the page starts using cookies after a revalidation', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Update the cache and for revalidation to settle before opening the page
await updateAndWaitForRevalidation(route)
// Reveal a prefetch-auto link to the page. We should see revalidated content.
// After the revalidation, the page starts using cookies in the prefetch,
// so we should not fetch a runtime shell.
await act(async () => {
await browser
.elementByCss(
`[data-prefetch="auto"] input[data-link-accordion="${route}"]`
)
.click()
}, [
// First, a static request (because the page was statically optimized at build time).
// This response should signal to the client router that runtime requests are still needed,
// but only for prefetches, not shells.
{ includes: 'Cached value: updated', kind: 'static' },
// There should not be a runtime follow up.
{ includes: '', kind: 'runtime', block: 'reject' },
])
// Reveal a prefetch-true link to the page.
// We have a sufficient shell, but the prefetch requires runtime data.
await act(async () => {
await browser
.elementByCss(
`[data-prefetch="true"] input[data-link-accordion="${route}"]`
)
.click()
}, [
{ includes: 'Runtime prefetch data (behind cookies)', kind: 'runtime' },
])
// Navigate to the page.
await act(async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
// We should show contents from the runtime prefetch while navigating.
expect(await browser.elementById('cookie-data').text()).toEqual(
'Cookie data'
)
expect(
await browser.elementById('cookies-runtime-prefetch-data').text()
).toEqual('Runtime prefetch data (behind cookies)')
}, [{ includes: 'Dynamic data' }])
expect(await browser.elementById('dynamic-data').text()).toEqual(
'Dynamic data'
)
})
it('[FAILING] shows static prefetch content if the runtime follow-up has not finished', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Update the cache and for revalidation to settle before opening the page
await updateAndWaitForRevalidation(route)
// Reveal a prefetch-auto link to the page. We should see revalidated content.
// After the revalidation, the page starts using cookies in the prefetch,
// so we should not fetch a runtime shell.
await act(async () => {
await browser
.elementByCss(
`[data-prefetch="auto"] input[data-link-accordion="${route}"]`
)
.click()
}, [
// First, a static request (because the page was statically optimized at build time).
// This response should signal to the client router that runtime requests are still needed,
// but only for prefetches, not shells.
{ includes: 'Cached value: updated', kind: 'static' },
// There should not be a runtime follow up.
{ includes: '', kind: 'runtime', block: 'reject' },
])
// Reveal a prefetch-true link to the page, but block its response, and navigate.
// We have a sufficient shell, but the prefetch requires runtime data.
// Howver, the the runtime request is blocked, so the client has to use
// the static data it prefetched from the first requests.
await act(async () => {
await act(async () => {
await browser
.elementByCss(
`[data-prefetch="true"] input[data-link-accordion="${route}"]`
)
.click()
}, [
{
includes: 'Runtime prefetch data (behind cookies)',
kind: 'runtime',
block: true,
},
])
// Navigate while the runtime prefetch is blocked.
await browser.elementByCss(`a[href="${route}"]`).click()
// We should show the most complete static prefetch we have
// (instead of the static app shell)
// However, the client currently prefers the shell, because it did not use any runtime data
// and was recorded at `FetchStrategy.ShellRuntime` which outranks the whole response's
// `FetchStrategy.PPR`, so it will be used despite technically containing less data.
if (REPRODUCE_STATIC_SHELL_PRECEDENCE_BUG) {
expect(await browser.elementById('prefetch-data').text()).toBe(
'Prefetch data'
)
} else {
expect(
await browser.elementById('prefetch-data-fallback').text()
).toBe('Loading prefetch data...')
}
})
})
})
})
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