Unverified Commit 02a73c59 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Rename `DYNAMIC_EXPIRE` and `DYNAMIC_STALE` to describe what they gate (#95361)

The `DYNAMIC_EXPIRE` and `DYNAMIC_STALE` constants read as if the value
itself is a dynamic expire or stale time, but every comparison is
`expire < DYNAMIC_EXPIRE` / `stale < DYNAMIC_STALE`, so the value is the
exclusive upper bound of the dynamic range: it is the smallest value
that is *not* dynamic, not a dynamic value. The names are backwards at
the boundary, which is easy to misread.

The two thresholds also gate different things. `expire` gates whether a
cache entry is included in the static prerender: below the threshold it
becomes a dynamic hole, though a short-`expire` value is still served
during a runtime prefetch. `stale` gates whether an entry is included in
a runtime prefetch or app shell.

This renames them to name that consequence: `MIN_PRERENDERABLE_EXPIRE`
and `MIN_PREFETCHABLE_STALE`. It reads correctly both at the comparison
sites (`expire < MIN_PRERENDERABLE_EXPIRE` is "below the minimum
prerenderable expire", i.e. dynamic) and at the one site that uses the
value directly, where private caches force `expire:
MIN_PRERENDERABLE_EXPIRE` precisely because it is the shortest expire
that stays prerenderable (and so is retained without being reclassified
as a short-expire dynamic hole). This is a pure rename with no behavior
change.


---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
parent a25865f1
...@@ -366,8 +366,8 @@ export interface PublicUseCacheStore extends CommonUseCacheStore { ...@@ -366,8 +366,8 @@ export interface PublicUseCacheStore extends CommonUseCacheStore {
readonly readRootParamNames: Set<string> readonly readRootParamNames: Set<string>
/** /**
* The first nested public `'use cache'` invocation with a dynamic cache life * The first nested public `'use cache'` invocation with a dynamic cache life
* (`revalidate === 0` or `expire < DYNAMIC_EXPIRE`) that propagated up to * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated
* this store. Used as `cause` for the nested-dynamic cache error so the * up to this store. Used as `cause` for the nested-dynamic cache error so the
* redbox can point at the inner invocation site, not just the outer one. * redbox can point at the inner invocation site, not just the outer one.
*/ */
dynamicNestedCacheError: Error | undefined dynamicNestedCacheError: Error | undefined
......
...@@ -3,7 +3,7 @@ import { ...@@ -3,7 +3,7 @@ import {
stringToUint8Array, stringToUint8Array,
} from '../app-render/encryption-utils' } from '../app-render/encryption-utils'
import type { CachedFetchValue } from '../response-cache/types' import type { CachedFetchValue } from '../response-cache/types'
import { DYNAMIC_EXPIRE } from '../use-cache/constants' import { MIN_PRERENDERABLE_EXPIRE } from '../use-cache/constants'
import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper' import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper'
/** /**
...@@ -135,7 +135,8 @@ export async function serializeUseCacheCacheStore( ...@@ -135,7 +135,8 @@ export async function serializeUseCacheCacheStore(
}) => { }) => {
if ( if (
isCacheComponentsEnabled && isCacheComponentsEnabled &&
(entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE) (entry.revalidate === 0 ||
entry.expire < MIN_PRERENDERABLE_EXPIRE)
) { ) {
// The entry was omitted from the prerender result, and subsequently // The entry was omitted from the prerender result, and subsequently
// does not need to be included in the serialized RDC. // does not need to be included in the serialized RDC.
......
export const DYNAMIC_EXPIRE = 300 // 5 minutes export const MIN_PRERENDERABLE_EXPIRE = 300 // 5 minutes
export const DYNAMIC_STALE = 30 // 30 seconds export const MIN_PREFETCHABLE_STALE = 30 // 30 seconds
...@@ -59,7 +59,7 @@ import { ...@@ -59,7 +59,7 @@ import {
} from '../app-render/create-error-handler' } from '../app-render/create-error-handler'
import { createDigestWithErrorCode } from '../../lib/error-telemetry-utils' import { createDigestWithErrorCode } from '../../lib/error-telemetry-utils'
import stringHash from 'next/dist/compiled/string-hash' import stringHash from 'next/dist/compiled/string-hash'
import { DYNAMIC_EXPIRE, DYNAMIC_STALE } from './constants' import { MIN_PRERENDERABLE_EXPIRE, MIN_PREFETCHABLE_STALE } from './constants'
import { NEXT_CACHE_ROOT_PARAM_TAG_ID } from '../../lib/constants' import { NEXT_CACHE_ROOT_PARAM_TAG_ID } from '../../lib/constants'
import { import {
getCacheHandler, getCacheHandler,
...@@ -907,7 +907,8 @@ function propagateCacheEntryMetadata( ...@@ -907,7 +907,8 @@ function propagateCacheEntryMetadata(
// cause points at the immediate dynamic child. // cause points at the immediate dynamic child.
if ( if (
cacheContext.dynamicNestedCacheError !== undefined && cacheContext.dynamicNestedCacheError !== undefined &&
(metadata.revalidate === 0 || metadata.expire < DYNAMIC_EXPIRE) (metadata.revalidate === 0 ||
metadata.expire < MIN_PRERENDERABLE_EXPIRE)
) { ) {
cacheContext.outerWorkUnitStore.dynamicNestedCacheError ??= cacheContext.outerWorkUnitStore.dynamicNestedCacheError ??=
cacheContext.dynamicNestedCacheError cacheContext.dynamicNestedCacheError
...@@ -1085,18 +1086,18 @@ async function collectResult( ...@@ -1085,18 +1086,18 @@ 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 private caches, which have no real backing handler. // MIN_PRERENDERABLE_EXPIRE`) for private caches, which have no real backing
// The zero revalidate makes every read serve stale-while-revalidate // handler. The zero revalidate makes every read serve stale-while-revalidate
// (regenerating a fresh entry in the background), and `DYNAMIC_EXPIRE` (5 // (regenerating a fresh entry in the background), and
// minutes) caps how long an entry lingers in the dedicated in-memory private // `MIN_PRERENDERABLE_EXPIRE` (5 minutes) caps how long an entry lingers in
// handler. It is the shortest `expire` that isn't treated as dynamic; a // the dedicated in-memory private handler. It is the shortest `expire` that
// smaller `expire` would exclude the entry from prerenders. The size-0 case // isn't treated as dynamic; a smaller `expire` would exclude the entry from
// (`cacheMaxMemorySize: 0`) deliberately does NOT force this: it keeps its // prerenders. The size-0 case (`cacheMaxMemorySize: 0`) deliberately does NOT
// resolved cache life so that the cache entry can be considered prerenderable // force this: it keeps its resolved cache life so that the cache entry can be
// instead of being misread as a dynamic hole, and a separate dev revalidation // considered prerenderable instead of being misread as a dynamic hole, and a
// (see the cache-hit path below) keeps its reloads showing a fresh value. // separate dev revalidation (see the cache-hit path below) keeps its reloads
// Custom kinds keep their real cache life too, since their backing handler // showing a fresh value. Custom kinds keep their real cache life too, since
// owns it. // their backing handler owns it.
const forceDynamicCacheLifeInDev = isPrivateCacheInDev const forceDynamicCacheLifeInDev = isPrivateCacheInDev
// 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
...@@ -1108,7 +1109,7 @@ async function collectResult( ...@@ -1108,7 +1109,7 @@ async function collectResult(
? innerCacheStore.explicitRevalidate ? innerCacheStore.explicitRevalidate
: innerCacheStore.revalidate : innerCacheStore.revalidate
const collectedExpire = forceDynamicCacheLifeInDev const collectedExpire = forceDynamicCacheLifeInDev
? DYNAMIC_EXPIRE ? MIN_PRERENDERABLE_EXPIRE
: innerCacheStore.explicitExpire !== undefined : innerCacheStore.explicitExpire !== undefined
? innerCacheStore.explicitExpire ? innerCacheStore.explicitExpire
: innerCacheStore.expire : innerCacheStore.expire
...@@ -2254,7 +2255,7 @@ export async function cache( ...@@ -2254,7 +2255,7 @@ export async function cache(
if (rdcResult !== undefined) { if (rdcResult !== undefined) {
if ( if (
rdcResult.entry.revalidate === 0 || rdcResult.entry.revalidate === 0 ||
rdcResult.entry.expire < DYNAMIC_EXPIRE rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE
) { ) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
...@@ -2320,8 +2321,8 @@ export async function cache( ...@@ -2320,8 +2321,8 @@ export async function cache(
// otherwise silently shorten. A dev private cache's // otherwise silently shorten. A dev private cache's
// `revalidate` is forced to 0 by us (not by a nested cache), so // `revalidate` is forced to 0 by us (not by a nested cache), so
// it's excluded from the first throw to avoid a false positive. // it's excluded from the first throw to avoid a false positive.
// Its forced `expire` is exactly DYNAMIC_EXPIRE, so it never // Its forced `expire` is exactly MIN_PRERENDERABLE_EXPIRE, so
// trips the second throw and needs no exclusion there. // it never trips the second throw and needs no exclusion there.
if ( if (
cacheContext.kind !== 'private' && cacheContext.kind !== 'private' &&
rdcResult.entry.revalidate === 0 && rdcResult.entry.revalidate === 0 &&
...@@ -2334,7 +2335,7 @@ export async function cache( ...@@ -2334,7 +2335,7 @@ export async function cache(
) )
} }
if ( if (
rdcResult.entry.expire < DYNAMIC_EXPIRE && rdcResult.entry.expire < MIN_PRERENDERABLE_EXPIRE &&
rdcResult.hasExplicitExpire === false rdcResult.hasExplicitExpire === false
) { ) {
throw wrapAsInvalidDynamicUsageError( throw wrapAsInvalidDynamicUsageError(
...@@ -2378,7 +2379,7 @@ export async function cache( ...@@ -2378,7 +2379,7 @@ export async function cache(
} }
} }
if (rdcResult.entry.stale < DYNAMIC_STALE) { if (rdcResult.entry.stale < MIN_PREFETCHABLE_STALE) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
...@@ -2826,7 +2827,7 @@ export async function cache( ...@@ -2826,7 +2827,7 @@ export async function cache(
const currentTime = performance.timeOrigin + performance.now() const currentTime = performance.timeOrigin + performance.now()
if ( if (
entry !== undefined && entry !== undefined &&
(entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE) (entry.revalidate === 0 || entry.expire < MIN_PRERENDERABLE_EXPIRE)
) { ) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': case 'prerender':
...@@ -2903,7 +2904,7 @@ export async function cache( ...@@ -2903,7 +2904,7 @@ export async function cache(
} }
} }
if (entry !== undefined && entry.stale < DYNAMIC_STALE) { if (entry !== undefined && entry.stale < MIN_PREFETCHABLE_STALE) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'request': { case 'request': {
// A short stale time excludes the entry from prerenders. // A short stale time excludes the entry from prerenders.
......
...@@ -13,7 +13,7 @@ export default async function Page() { ...@@ -13,7 +13,7 @@ export default async function Page() {
This page uses a short-lived private cache (with cacheLife("seconds")), This page uses a short-lived private cache (with cacheLife("seconds")),
which should not be included in a static prefetch, but should be which should not be included in a static prefetch, but should be
included in a runtime prefetch, because it has a long enough stale time included in a runtime prefetch, because it has a long enough stale time
(&ge; DYNAMIC_STALE, 30s) (&ge; MIN_PREFETCHABLE_STALE, 30s)
</p> </p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache /> <ShortLivedCache />
......
...@@ -11,8 +11,8 @@ export default async function Page() { ...@@ -11,8 +11,8 @@ export default async function Page() {
<DebugRenderKind /> <DebugRenderKind />
<p id="intro"> <p id="intro">
This page uses a short-lived private cache (staleTime &lt; This page uses a short-lived private cache (staleTime &lt;
DYNAMIC_STALE, which is 30s), which should not be included in a runtime MIN_PREFETCHABLE_STALE, which is 30s), which should not be included in a
prefetch runtime prefetch
</p> </p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<CachedButShortLived /> <CachedButShortLived />
......
...@@ -13,7 +13,7 @@ export default async function Page() { ...@@ -13,7 +13,7 @@ export default async function Page() {
This page uses a short-lived public cache (with cacheLife("seconds")), This page uses a short-lived public cache (with cacheLife("seconds")),
which should not be included in a static prefetch, but should be which should not be included in a static prefetch, but should be
included in a runtime prefetch, because it has a long enough stale time included in a runtime prefetch, because it has a long enough stale time
(&ge; DYNAMIC_STALE, 30s) (&ge; MIN_PREFETCHABLE_STALE, 30s)
</p> </p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache /> <ShortLivedCache />
......
...@@ -10,10 +10,10 @@ export default async function Page() { ...@@ -10,10 +10,10 @@ export default async function Page() {
<main> <main>
<DebugRenderKind /> <DebugRenderKind />
<p id="intro"> <p id="intro">
This page uses a short-lived public cache (expire &lt; DYNAMIC_EXPIRE, This page uses a short-lived public cache (expire &lt;
5min), which should not be included in a static prefetch, but should be MIN_PRERENDERABLE_EXPIRE, 5min), which should not be included in a
included in a runtime prefetch, because it has a long enough stale time static prefetch, but should be included in a runtime prefetch, because
(&ge; DYNAMIC_STALE, 30s) it has a long enough stale time (&ge; MIN_PREFETCHABLE_STALE, 30s)
</p> </p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache /> <ShortLivedCache />
...@@ -25,9 +25,9 @@ export default async function Page() { ...@@ -25,9 +25,9 @@ export default async function Page() {
async function ShortLivedCache() { async function ShortLivedCache() {
'use cache' 'use cache'
cacheLife({ cacheLife({
stale: 60, // > DYNAMIC_STALE stale: 60, // >= MIN_PREFETCHABLE_STALE
revalidate: 2 * 60, revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE expire: 3 * 60, // < MIN_PRERENDERABLE_EXPIRE
}) })
await cachedDelay([__filename]) await cachedDelay([__filename])
......
...@@ -10,10 +10,11 @@ export default async function Page() { ...@@ -10,10 +10,11 @@ export default async function Page() {
<main> <main>
<DebugRenderKind /> <DebugRenderKind />
<p id="intro"> <p id="intro">
This page uses a short-lived public cache (expire &lt; DYNAMIC_EXPIRE, This page uses a short-lived public cache (expire &lt;
5min), which should not be included in a static prefetch, and should MIN_PRERENDERABLE_EXPIRE, 5min), which should not be included in a
also not be included in a runtime prefetch, because it has a short static prefetch, and should also not be included in a runtime prefetch,
enough stale time (&lt; DYNAMIC_STALE, 30s) because it has a short enough stale time (&lt; MIN_PREFETCHABLE_STALE,
30s)
</p> </p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}> <Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache /> <ShortLivedCache />
...@@ -25,9 +26,9 @@ export default async function Page() { ...@@ -25,9 +26,9 @@ export default async function Page() {
async function ShortLivedCache() { async function ShortLivedCache() {
'use cache' 'use cache'
cacheLife({ cacheLife({
stale: 20, // < DYNAMIC_STALE stale: 20, // < MIN_PREFETCHABLE_STALE
revalidate: 2 * 60, revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE expire: 3 * 60, // < MIN_PRERENDERABLE_EXPIRE
}) })
await cachedDelay([__filename]) await cachedDelay([__filename])
......
...@@ -715,25 +715,32 @@ describe('runtime prefetching', () => { ...@@ -715,25 +715,32 @@ describe('runtime prefetching', () => {
describe('cache stale time handling', () => { describe('cache stale time handling', () => {
it.each([ it.each([
{ {
// If a cache has an expiration time under 5min (DYNAMIC_EXPIRE), we omit it from static prerenders. // If a cache has an expiration time under 5min
// However, it should still be included in a runtime prefetch if its stale time is >=30s. (DYNAMIC_STALE) // (MIN_PRERENDERABLE_EXPIRE), we omit it from static prerenders.
// However, it should still be included in a runtime prefetch if its
// stale time is >=30s. (MIN_PREFETCHABLE_STALE)
description: description:
'includes short-lived public caches with a long enough staleTime', 'includes short-lived public caches with a long enough staleTime',
staticContent: 'This page uses a short-lived public cache', staticContent: 'This page uses a short-lived public cache',
path: '/caches/public-short-expire-long-stale', path: '/caches/public-short-expire-long-stale',
}, },
{ {
// If a cache has an expiration time under 5min (DYNAMIC_EXPIRE), we omit it from static prerenders. // If a cache has an expiration time under 5min
// However, it should still be included in a runtime prefetch if its stale time is >=30s. (DYNAMIC_STALE) // (MIN_PRERENDERABLE_EXPIRE), we omit it from static prerenders.
// `cacheLife("seconds")` is deliberately set to have a stale time of 30s to stay above this treshold. // However, it should still be included in a runtime prefetch if its
// stale time is >=30s. (MIN_PREFETCHABLE_STALE) `cacheLife("seconds")`
// is deliberately set to have a stale time of 30s to stay above this
// treshold.
description: 'includes public caches with cacheLife("seconds")', description: 'includes public caches with cacheLife("seconds")',
staticContent: 'This page uses a short-lived public cache', staticContent: 'This page uses a short-lived public cache',
path: '/caches/public-seconds', path: '/caches/public-seconds',
}, },
{ {
// A Private cache will always be omitted from static prerenders. // A Private cache will always be omitted from static prerenders.
// However, it should still be included in a runtime prefetch if its stale time is >=30s. (DYNAMIC_STALE) // However, it should still be included in a runtime prefetch if its
// `cacheLife("seconds")` is deliberately set to have a stale time of 30s to stay above this treshold. // stale time is >=30s. (MIN_PREFETCHABLE_STALE) `cacheLife("seconds")`
// is deliberately set to have a stale time of 30s to stay above this
// treshold.
description: 'includes private caches with cacheLife("seconds")', description: 'includes private caches with cacheLife("seconds")',
staticContent: 'This page uses a short-lived private cache', staticContent: 'This page uses a short-lived private cache',
path: '/caches/private-seconds', path: '/caches/private-seconds',
...@@ -777,7 +784,8 @@ describe('runtime prefetching', () => { ...@@ -777,7 +784,8 @@ describe('runtime prefetching', () => {
}) })
it('omits short-lived public caches with a short enough staleTime', async () => { it('omits short-lived public caches with a short enough staleTime', async () => {
// If a cache has a stale time below 30s (DYNAMIC_STALE), we should omit it from runtime prefetches. // If a cache has a stale time below 30s (MIN_PREFETCHABLE_STALE), we
// should omit it from runtime prefetches.
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
...@@ -837,7 +845,8 @@ describe('runtime prefetching', () => { ...@@ -837,7 +845,8 @@ describe('runtime prefetching', () => {
}) })
it('omits private caches with a short enough staleTime', async () => { it('omits private caches with a short enough staleTime', async () => {
// If a cache has a stale time below 30s (DYNAMIC_STALE), we should omit it from runtime prefetches. // If a cache has a stale time below 30s (MIN_PREFETCHABLE_STALE), we
// should omit it from runtime prefetches.
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
......
...@@ -3,18 +3,19 @@ import { Suspense } from 'react' ...@@ -3,18 +3,19 @@ import { Suspense } from 'react'
async function getCachedRandom() { async function getCachedRandom() {
'use cache' 'use cache'
// Long-lived (stale >= DYNAMIC_STALE, expire >= DYNAMIC_EXPIRE): stays in the // Long-lived (stale >= MIN_PREFETCHABLE_STALE, expire >=
// static shell. // MIN_PRERENDERABLE_EXPIRE): stays in the static shell.
cacheLife({ stale: 60, revalidate: 100, expire: 1000 }) cacheLife({ stale: 60, revalidate: 100, expire: 1000 })
return Math.random() return Math.random()
} }
async function ShortStaleCache() { async function ShortStaleCache() {
'use cache' 'use cache'
// Long expire (>= DYNAMIC_EXPIRE, 5min) and a non-zero revalidate, but a // Long expire (>= MIN_PRERENDERABLE_EXPIRE, 5min) and a non-zero revalidate,
// stale time below DYNAMIC_STALE (30s). This isolates the short-stale // but a stale time below MIN_PREFETCHABLE_STALE (30s). This isolates the
// exclusion: the entry is omitted from the static shell purely because of its // short-stale exclusion: the entry is omitted from the static shell purely
// short stale time, not because of a short expire or revalidate: 0. // because of its short stale time, not because of a short expire or
// revalidate: 0.
cacheLife({ stale: 18, revalidate: 100, expire: 1000 }) cacheLife({ stale: 18, revalidate: 100, expire: 1000 })
return <p id="y">{new Date().toISOString()}</p> return <p id="y">{new Date().toISOString()}</p>
} }
......
...@@ -13,8 +13,9 @@ const nextConfig = { ...@@ -13,8 +13,9 @@ const nextConfig = {
}, },
cacheLife: { cacheLife: {
frequent: { frequent: {
// >= DYNAMIC_STALE (30s) so the cache is still eligible for the static // >= MIN_PREFETCHABLE_STALE (30s) so the cache is still eligible for the
// shell. A shorter stale time would exclude it from static prerenders. // static shell. A shorter stale time would exclude it from static
// prerenders.
stale: 30, stale: 30,
revalidate: 100, revalidate: 100,
expire: 300, expire: 300,
......
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