Unverified Commit 34dbafb4 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Skip saving `expire: 0` values in the default cache handler in prod (#95363)

A `'use cache'` value with an explicit `cacheLife({ expire: 0 })` is
expired the moment it is produced, so in production the `'use cache'`
wrapper regenerates it on every read rather than serving the stored
copy. The entry written to the cache handler is never served back, so
persisting it is wasted work, and for a remote handler a needless
round-trip and stored payload.

Whether to skip that write is left to each cache handler. This change
implements it in the built-in default handler; a custom handler can opt
into the same behavior. Beyond the saved write, this makes `cacheLife({
expire: 0 })` a reliable way to keep a value out of the server-side
cache handler, which covers two cases. In a conditional opt-out, a
function with an otherwise normal cache life sets `expire: 0` for a
result that is not worth persisting, for example when an upstream fetch
errored. In client-only caching, a value is `expire: 0` by design so
that it lives only in the client cache, via Cached Navigations or
Runtime Prefetches when the route opts in, and never on the server.

The skip is gated on `!process.env.__NEXT_DEV_SERVER`. In production the
value is regenerated on every read regardless, so not storing it changes
nothing that is served. Development keeps storing it, because the
default handler's minimum retention serves the previously cached value
across reloads while the entry re-warms in the background.

A new `use-cache-default-handler-expire-zero` end-to-end test enables
the default handler's debug logging (`NEXT_PRIVATE_DEBUG_CACHE`) and
asserts on its `set()` decisions. Because the debug output is only
available from the CLI, the test skips deployment.
parent 6f592dec
...@@ -162,6 +162,18 @@ export function createDefaultCacheHandler(maxSize: number): CacheHandler { ...@@ -162,6 +162,18 @@ export function createDefaultCacheHandler(maxSize: number): CacheHandler {
let size = 0 let size = 0
try { try {
// In production an `expire: 0` entry is dynamic: the "use cache"
// wrapper regenerates it on every read instead of serving the stored
// copy, so persisting it would be a wasted write of a value that is
// never served back. Skip storing it so the next read is a plain miss.
// The dev server keeps it, because its minimum retention serves the
// previously cached value across reloads. The `finally` below still
// resolves the pending set.
if (!process.env.__NEXT_DEV_SERVER && entry.expire === 0) {
debug?.('set', cacheKey, 'skipped dynamic entry')
return
}
const [value, clonedValue] = entry.value.tee() const [value, clonedValue] = entry.value.tee()
entry.value = value entry.value = value
const reader = clonedValue.getReader() const reader = clonedValue.getReader()
......
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'
// The id prop is serialized into the cache key, so tests can grep the built-in
// default handler's debug output for a specific cache.
async function ShortLivedCache({ id }: { id: string }) {
'use cache'
cacheLife('seconds') // expire: 60, short but non-zero, still saved
return <p id="short-lived-value">{new Date().toISOString()}</p>
}
async function ExpireZeroCache({ id }: { id: string }) {
'use cache'
cacheLife({ expire: 0 }) // dynamic, not saved by the default handler in prod
return <p id="expire-zero-value">{new Date().toISOString()}</p>
}
export default function Page() {
return (
<main>
<Suspense>
<ShortLivedCache id="short-lived" />
</Suspense>
<Suspense>
<ExpireZeroCache id="expire-zero" />
</Suspense>
</main>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('use-cache-default-handler-expire-zero', () => {
const { next, skipped, isNextStart } = nextTestSetup({
files: __dirname,
// Enable the built-in default cache handler's debug logging so we can
// assert on its `set()` decisions in the CLI output. That output is not
// available on deploy, so skip the deploy variant.
env: { NEXT_PRIVATE_DEBUG_CACHE: '1' },
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextStart) {
it('does not save an expire:0 cache to the built-in default handler, but saves a short-lived one', async () => {
const browser = await next.browser('/')
expect(
await browser.elementById('expire-zero-value').text()
).toBeDateString()
expect(
await browser.elementById('short-lived-value').text()
).toBeDateString()
// The default handler skips storing the `expire: 0` entry (it would never
// be served back in production)...
expect(next.cliOutput).toMatch(
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] skipped dynamic entry/
)
// ...and never reports it as stored.
expect(next.cliOutput).not.toMatch(
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] done/
)
// The short-lived (`expire: 60`) cache is still stored.
expect(next.cliOutput).toMatch(
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"short-lived"}]\] done/
)
})
} else {
it('saves an expire:0 cache to the built-in default handler in dev', async () => {
const browser = await next.browser('/')
expect(
await browser.elementById('expire-zero-value').text()
).toBeDateString()
// In development the default handler keeps `expire: 0` entries (its
// minimum retention serves them warm across reloads), so it stores rather
// than skips.
await retry(async () => {
expect(next.cliOutput).toMatch(
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] done/
)
})
expect(next.cliOutput).not.toMatch(
/DefaultCacheHandler: set \["[A-Za-z0-9_-]+","([0-9a-f]{2})+",\[{"id":"expire-zero"}]\] skipped/
)
})
}
})
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