Unverified Commit 61f8830a authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Keep the resolved cache life for `cacheMaxMemorySize: 0` caches in dev (#95100)

To make `cacheMaxMemorySize: 0` fast in development, the `'use cache'`
wrapper forced every built-in cache entry to a dynamic cache life
(`revalidate: 0`, a five-minute `expire`) so that warm reads would serve
the stale value and regenerate a fresh one in the background. That
forcing leaked into the stored entry, and an entry with `revalidate: 0`
is treated as too dynamic to live in a static shell. On a warm reload of
a route that is fully cached and has no `<Suspense>` above the `'use
cache'`, the dev validation prerender read the entry and threw an error
claiming that a `'use cache'` with zero `revalidate` was nested inside
another `'use cache'` that has no explicit `cacheLife`, even though
nothing was actually nested, and reported the route as a blocking route.
The cold load was unaffected because the entry did not exist yet.

With this change the size-0 case no longer forces a dynamic cache life
and keeps the entry's resolved life instead: the explicit `cacheLife()`
values when the user set them, otherwise the default (a 15-minute
`revalidate` and an infinite `expire`). That default sits well above the
dynamic thresholds, so a fully cached route can be prerendered again and
the false-positive blocking error is gone. An explicitly short
`cacheLife()` still makes the route legitimately dynamic without a
spurious throw, because the explicit-revalidate and explicit-expire
flags are then set. Private caches are unchanged and remain
forced-dynamic.

So that reloads keep showing a fresh value now that the stored life is
no longer always stale, the background revalidation in the cache-hit
path also fires for size-0 built-in entries regardless of the stored
`revalidate`, restricted to the dynamic dev request render so the dev
validation prerender does not also regenerate.
parent ab4b1918
...@@ -1080,21 +1080,19 @@ async function collectResult( ...@@ -1080,21 +1080,19 @@ async function collectResult(
) )
// In development, force a dynamic cache life (`revalidate: 0`, `expire: // In development, force a dynamic cache life (`revalidate: 0`, `expire:
// DYNAMIC_EXPIRE`) for caches that have no real backing: private caches, and // DYNAMIC_EXPIRE`) for private caches, which have no real backing handler.
// any built-in (non-custom) kind when the in-memory cache is disabled // The zero revalidate makes every read serve stale-while-revalidate
// (`cacheMaxMemorySize: 0`). The zero revalidate makes every read serve // (regenerating a fresh entry in the background), and `DYNAMIC_EXPIRE` (5
// stale-while-revalidate (re-warming a fresh entry in the background) so warm // minutes) caps how long an entry lingers in the dedicated in-memory private
// reloads stay fast, and `DYNAMIC_EXPIRE` (5 minutes, the shortest expire not // handler. It is the shortest `expire` that isn't treated as dynamic; a
// treated as dynamically shortened) bounds how long an entry lingers in the // smaller `expire` would exclude the entry from prerenders. The size-0 case
// dev in-memory cache. Custom kinds keep their real cache life, since their // (`cacheMaxMemorySize: 0`) deliberately does NOT force this: it keeps its
// backing handler owns it. // resolved cache life so that the cache entry can be considered prerenderable
const forceDynamicCacheLifeInDev = // instead of being misread as a dynamic hole, and a separate dev revalidation
isPrivateCacheInDev || // (see the cache-hit path below) keeps its reloads showing a fresh value.
Boolean( // Custom kinds keep their real cache life too, since their backing handler
process.env.__NEXT_DEV_SERVER && // owns it.
isMemoryCacheDisabled() && const forceDynamicCacheLifeInDev = isPrivateCacheInDev
!isCustomCacheHandler(cacheContext.kind)
)
// If cacheLife() was used to set an explicit revalidate/expire/stale time we // If cacheLife() was used to set an explicit revalidate/expire/stale time we
// use that. Otherwise, we use the lowest of all inner fetch(), // use that. Otherwise, we use the lowest of all inner fetch(),
...@@ -3112,10 +3110,40 @@ export async function cache( ...@@ -3112,10 +3110,40 @@ export async function cache(
entry: sharedCacheEntry, entry: sharedCacheEntry,
}) })
if (currentTime > entry.timestamp + entry.revalidate * 1000) { // Trigger a background revalidation when the entry is stale (past its
// If this is stale, and we're not in a prerender (i.e. this is // `revalidate`), so the next read gets a fresh value without blocking
// dynamic render), then we should warm up the cache with a fresh // this one. In development with the in-memory cache disabled
// revalidated entry. // (`cacheMaxMemorySize: 0`), built-in entries keep their resolved
// (potentially non-dynamic) cache life, so an entry read back from
// the dev in-memory cache is normally still fresh and wouldn't
// revalidate on its own; revalidate those on every dynamic request
// render too, so each reload still shows a fresh value.
let shouldTriggerBackgroundRevalidation =
currentTime > entry.timestamp + entry.revalidate * 1000
if (
!shouldTriggerBackgroundRevalidation &&
process.env.__NEXT_DEV_SERVER &&
isMemoryCacheDisabled() &&
!isCustomCacheHandler(kind)
) {
switch (workUnitStore.type) {
case 'request':
shouldTriggerBackgroundRevalidation = true
break
case 'cache':
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
}
if (shouldTriggerBackgroundRevalidation) {
const revalidateCacheHandlerKey = cacheHandlerKey const revalidateCacheHandlerKey = cacheHandlerKey
const revalidatePromise = generateCacheEntry( const revalidatePromise = generateCacheEntry(
workStore, workStore,
......
...@@ -13,7 +13,7 @@ export function generateStaticParams() { ...@@ -13,7 +13,7 @@ export function generateStaticParams() {
async function getCachedValue(slug: string) { async function getCachedValue(slug: string) {
'use cache' 'use cache'
// A slow generation, so a warm reload that serves the stale entry is // A slow generation, so a warm reload that serves the cached entry is
// observably faster than a cold load that has to generate, and so a cold read // observably faster than a cold load that has to generate, and so a cold read
// is still pending at a staged-render boundary (which surfaces the cold cache // is still pending at a staged-render boundary (which surfaces the cold cache
// indicator). The slug keys the entry; the value itself is just a timestamp. // indicator). The slug keys the entry; the value itself is just a timestamp.
......
export default async function Home() {
'use cache'
return <p>Hello, world!</p>
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils' import { retry, waitFor, waitForNoErrorToast } from 'next-test-utils'
describe('use-cache-size-zero', () => { describe('use-cache-size-zero', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
...@@ -34,10 +34,11 @@ describe('use-cache-size-zero', () => { ...@@ -34,10 +34,11 @@ describe('use-cache-size-zero', () => {
.text() .text()
// Warm reload: `cacheMaxMemorySize: 0` still caches in development, so the // Warm reload: `cacheMaxMemorySize: 0` still caches in development, so the
// reload serves the same (stale) cached value instead of regenerating it. // reload serves the previously cached value fast instead of regenerating
// The forced `revalidate: 0` keeps the value a dynamic hole, so it still // it. The entry keeps its default (non-dynamic) cache life, so it's served
// streams behind the loading boundary - but it's the cached value, served // straight from the cache rather than treated as a dynamic hole. A
// fast, not a fresh generation. // background revalidation regenerates a fresh entry for the next reload
// (asserted below).
await browser.refresh({ waitUntil: 'commit' }) await browser.refresh({ waitUntil: 'commit' })
await retry(async () => { await retry(async () => {
expect( expect(
...@@ -84,4 +85,23 @@ describe('use-cache-size-zero', () => { ...@@ -84,4 +85,23 @@ describe('use-cache-size-zero', () => {
await waitFor(500) await waitFor(500)
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(false) expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(false)
}) })
it('does not surface a blocking-route error on a warm reload of a fully cached route', async () => {
const browser = await next.browser('/')
// Cold load: the page-level `'use cache'` misses and fills in the
// background while the result streams in immediately.
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('Hello, world!')
})
// Warm reload (the second request): the dev cache serves the cached value.
// The route has no dynamic data, so serving it from cache must not surface
// a false-positive blocking-route red box.
await browser.refresh()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('Hello, world!')
})
await waitForNoErrorToast(browser)
})
}) })
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