Unverified Commit b420536f authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix false-positive nested-cache error for a short default profile (#95373)

Overriding the `default` `cacheLife` profile with a short cache life
(the built-in `expire` is `INFINITE_CACHE`) makes every `'use cache'`
without an inline `cacheLife()` inherit that short life. In this
configuration the nested-`'use cache'` error, in both its short-`expire`
and zero-`revalidate` variants, fired in two cases where it should not
have.

The error exists to catch a nested cache silently shortening an outer
cache that has no explicit `cacheLife`, degrading it to a dynamic hole
the developer did not choose. But with a short default profile, a single
non-nested `'use cache'` already resolves to a short life with nothing
nested, so the error fired with no nesting at all: in production this
killed the build, and in development it threw on the request. And even
for a genuinely nested cache, the warning is pointless here, because the
default profile already makes every cache a dynamic hole, so there is no
silent degradation to surprise the developer.

The throw condition keyed on a short life that was not set through an
inline `cacheLife()`, and a value inherited from the `default` profile
is non-explicit, so it matched. This change additionally requires that a
dynamic nested cache actually propagated its short life upward
(`dynamicNestedCacheError` is set) and that the `default` profile is
itself prerenderable. Otherwise the short-lived entry is omitted as a
dynamic hole instead, exactly as an inline short `cacheLife()` already
was. Genuine nesting under a prerenderable default profile still errors.

The nesting condition also subsumes the dev-only private-cache
exclusion: a private cache's `revalidate: 0` is forced by us rather than
by a nested cache and never carries a nested error, so the explicit
`kind !== 'private'` check is no longer needed.
parent 34dbafb4
...@@ -2262,6 +2262,23 @@ export async function cache( ...@@ -2262,6 +2262,23 @@ export async function cache(
rdcResult.entry.revalidate === 0 || rdcResult.entry.revalidate === 0 ||
rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE
) { ) {
// The nested-cache error only makes sense when a dynamic nested cache
// actually shortened an outer cache that has no explicit `cacheLife`
// (`dynamicNestedCacheError` is set), and only when the app's default
// profile is itself prerenderable. If the default profile is already
// dynamic (`revalidate: 0` or an `expire` under the prerenderable
// minimum), every cache is omitted from prerenders by default, so
// there is no silent degradation to warn about. A short life from the
// default profile, or from a dev private cache's self-imposed
// `revalidate: 0` (which never carries a nested error), therefore
// stays a dynamic hole rather than erroring.
const defaultCacheLife = workStore.cacheLifeProfiles?.['default']
assertDefaultCacheLife(defaultCacheLife)
const shouldReportNestedCacheError =
rdcResult.dynamicNestedCacheError !== undefined &&
defaultCacheLife.revalidate !== 0 &&
defaultCacheLife.expire >= MIN_PRERENDERABLE_EXPIRE
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
// In a Dynamic I/O prerender, if the cache entry has // In a Dynamic I/O prerender, if the cache entry has
...@@ -2271,7 +2288,10 @@ export async function cache( ...@@ -2271,7 +2288,10 @@ export async function cache(
// a dynamic hole that can be filled in during the resume with // a dynamic hole that can be filled in during the resume with
// a potentially cached entry. // a potentially cached entry.
if (rdcResult.entry.revalidate === 0) { if (rdcResult.entry.revalidate === 0) {
if (rdcResult.hasExplicitRevalidate === false) { if (
rdcResult.hasExplicitRevalidate === false &&
shouldReportNestedCacheError
) {
throw wrapAsInvalidDynamicUsageError( throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheZeroRevalidateErrorMessage, { new Error(nestedCacheZeroRevalidateErrorMessage, {
cause: rdcResult.dynamicNestedCacheError, cause: rdcResult.dynamicNestedCacheError,
...@@ -2284,7 +2304,10 @@ export async function cache( ...@@ -2284,7 +2304,10 @@ export async function cache(
'from static shell due to revalidate: 0' 'from static shell due to revalidate: 0'
) )
} else { } else {
if (rdcResult.hasExplicitExpire === false) { if (
rdcResult.hasExplicitExpire === false &&
shouldReportNestedCacheError
) {
throw wrapAsInvalidDynamicUsageError( throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheShortExpireErrorMessage, { new Error(nestedCacheShortExpireErrorMessage, {
cause: rdcResult.dynamicNestedCacheError, cause: rdcResult.dynamicNestedCacheError,
...@@ -2321,17 +2344,14 @@ export async function cache( ...@@ -2321,17 +2344,14 @@ export async function cache(
} }
case 'request': { case 'request': {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// These throws force the user to make an explicit cache life // These throws force an explicit cache life decision on an
// decision on an outer cache that an inner cache would // outer cache that a nested cache would otherwise silently
// otherwise silently shorten. A dev private cache's // shorten (see `shouldReportNestedCacheError` above). Otherwise
// `revalidate` is forced to 0 by us (not by a nested cache), so // the short-lived entry is deferred as a dynamic hole below.
// it's excluded from the first throw to avoid a false positive.
// Its forced `expire` is exactly MIN_PRERENDERABLE_EXPIRE, so
// it never trips the second throw and needs no exclusion there.
if ( if (
cacheContext.kind !== 'private' &&
rdcResult.entry.revalidate === 0 && rdcResult.entry.revalidate === 0 &&
rdcResult.hasExplicitRevalidate === false rdcResult.hasExplicitRevalidate === false &&
shouldReportNestedCacheError
) { ) {
throw wrapAsInvalidDynamicUsageError( throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheZeroRevalidateErrorMessage, { new Error(nestedCacheZeroRevalidateErrorMessage, {
...@@ -2341,7 +2361,8 @@ export async function cache( ...@@ -2341,7 +2361,8 @@ export async function cache(
} }
if ( if (
rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE && rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE &&
rdcResult.hasExplicitExpire === false rdcResult.hasExplicitExpire === false &&
shouldReportNestedCacheError
) { ) {
throw wrapAsInvalidDynamicUsageError( throw wrapAsInvalidDynamicUsageError(
new Error(nestedCacheShortExpireErrorMessage, { new Error(nestedCacheShortExpireErrorMessage, {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { cacheLife } from 'next/cache'
async function innerCache() {
'use cache'
cacheLife({ expire: 60 }) // short, under the prerenderable minimum
return new Date().toISOString()
}
async function outerCache() {
'use cache'
// No explicit `cacheLife`. Normally a short-lived cache nested inside an
// outer cache without an explicit `cacheLife` errors during prerendering,
// because the outer is silently degraded to a dynamic hole. Here it must not:
// this app's default profile is itself dynamic (`expire: 0`), so every cache
// is omitted from prerenders by default and there is nothing to warn about.
return innerCache()
}
async function NestedValue() {
const value = await outerCache()
return <p id="value">{value}</p>
}
export default function Page() {
return (
<Suspense fallback={<p id="fallback">Loading...</p>}>
<NestedValue />
</Suspense>
)
}
import { Suspense } from 'react'
// A single, non-nested `'use cache'` with no inline `cacheLife()`. It inherits
// the app's `default` profile, which is configured with `expire: 0`. That must
// be treated exactly like an inline `cacheLife({ expire: 0 })`: a dynamic hole
// excluded from the prerender, not a nested-cache misconfiguration. There is no
// outer cache here, so the "nested inside another use cache" error must not
// fire.
async function CachedValue() {
'use cache'
return <p id="value">{new Date().toISOString()}</p>
}
export default function Page() {
return (
<Suspense fallback={<p id="fallback">Loading...</p>}>
<CachedValue />
</Suspense>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
cacheLife: {
// Override the built-in `default` profile so that every `'use cache'`
// without an inline `cacheLife()` is dynamic (client-only) by default.
// `revalidate` and `stale` are backfilled from the built-in default. This
// is the configuration where a short default profile used to trip the
// nested-cache "no explicit cacheLife" build error on a cache that isn't
// nested at all.
default: { expire: 0 },
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const isoDateRegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
describe('use-cache-default-profile-expire-zero', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('treats a short default cacheLife profile as a dynamic hole, not a nested-cache error', async () => {
const browser = await next.browser('/')
const initialValue = await browser.elementById('value').text()
expect(initialValue).toMatch(isoDateRegExp)
// The short `expire` comes from the app's configured default profile, and
// the cache is not nested inside another one, so the nested-cache "no
// explicit cacheLife" error must never fire (in production it kills the
// build; in dev it throws on the request).
expect(next.cliOutput).not.toContain(
'nested-use-cache-no-explicit-cachelife'
)
// An `expire: 0` cache is a dynamic hole. In production it regenerates on
// every request; in dev it is served warm across reloads and re-warmed in
// the background. Either way, reloads converge to a fresh value.
await retry(async () => {
await browser.refresh()
const value = await browser.elementById('value').text()
expect(value).toMatch(isoDateRegExp)
expect(value).not.toEqual(initialValue)
})
})
it('does not error when a short-lived cache is nested under a dynamic default profile', async () => {
// A short-lived inner cache nested inside an outer cache without an
// explicit `cacheLife` normally errors during prerendering. But because the
// default profile is itself dynamic, the outer cache is omitted from
// prerenders by default, so there is no silent degradation to warn about
// and the nested cache renders as a dynamic hole instead.
const browser = await next.browser('/nested')
expect(await browser.elementById('value').text()).toMatch(isoDateRegExp)
expect(next.cliOutput).not.toContain(
'nested-use-cache-no-explicit-cachelife'
)
})
})
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