Unverified Commit 9bec0cce authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Avoid `undefined` outer work unit store in `"use cache"` (#91190)

The `outerWorkUnitStore` in the public cache context could previously be `undefined`, which was needed when `"use cache"` was called without a `WorkUnitStore` (e.g. inside `generateStaticParams`) and during background revalidation of stale cache entries (SWR). With the previous commit providing a `GenerateStaticParamsStore` for `generateStaticParams`, the only remaining source of `undefined` was the SWR background revalidation path, which intentionally discarded the store to prevent cache life and tags from propagating back to the outer scope.

A `skipPropagation` flag was added to `CacheContext` to decouple the propagation concern from the store reference. The SWR background regen now passes `skipPropagation: true` while keeping the outer store intact for reads (e.g. `implicitTags`). Previously, nested `"use cache"` calls during SWR regen would pass empty `softTags` to `cacheHandler.get()` because the store was `undefined`. Now they correctly receive the page's implicit tags.

With `| undefined` removed from `PublicCacheContext.outerWorkUnitStore`, all unnecessary existence checks (`?.`, `if (x)`, `case undefined:`, ternaries) were cleaned up throughout `use-cache-wrapper.ts`, and the `shouldForceRevalidate` and `shouldDiscardCacheEntry` signatures were tightened from `WorkUnitStore | undefined` to `WorkUnitStore`.

Note that module-scope `"use cache"` usage (calling a cached function at the top level of a module) was already prevented before this change by the `WorkStore` check, which throws if no `WorkStore` is present. The new `WorkUnitStore` check is an additional guard that comes after it.

This also unblocks a future change to support root params inside `"use cache"` with cache keying. Since the outer work unit store is now always defined, `rootParams` can be threaded from the outer store into the cache store. The only exception will be `UnstableCacheStore`, which doesn't carry `rootParams` and can't include them in its cache key.

A new `use-cache-swr` test suite was added with a persistent cache handler that does not drop entries at revalidate time (unlike the default in-memory handler), which enables testing the server-side SWR code path that was previously uncovered.

> [!TIP]
> Best reviewed with hidden whitespace changes.
parent 4f693363
...@@ -1132,5 +1132,6 @@ ...@@ -1132,5 +1132,6 @@
"1131": "createServerParamsForRoute should not be called inside generateStaticParams.", "1131": "createServerParamsForRoute should not be called inside generateStaticParams.",
"1132": "Route %s used \\`draftMode()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context", "1132": "Route %s used \\`draftMode()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1133": "createSearchParamsFromClient should not be called inside generateStaticParams.", "1133": "createSearchParamsFromClient should not be called inside generateStaticParams.",
"1134": "Route %s used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context" "1134": "Route %s used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1135": "\"use cache\" cannot be used outside of App Router. Expected a WorkUnitStore."
} }
import { Suspense } from 'react'
export default function RootLayout({ children }) {
return (
<html>
<head />
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
import { cacheLife } from 'next/cache'
import { connection } from 'next/server'
async function getInnerData(id: string) {
'use cache'
return new Date().toISOString()
}
async function getOuterData(id: string) {
'use cache'
cacheLife({ revalidate: 5 })
const innerData = await getInnerData('inner')
return { outer: new Date().toISOString(), inner: innerData }
}
export default async function Page() {
await connection()
const data = await getOuterData('outer')
return (
<main>
<p id="outer-data">{data.outer}</p>
<p id="inner-data">{data.inner}</p>
</main>
)
}
// @ts-check
/**
* A persistent cache handler that does NOT drop entries at revalidate time.
* This allows the framework's SWR code path to trigger, unlike the default
* in-memory handler which expires entries at revalidate time.
*/
/** @type {Map<string, import('next/dist/server/lib/cache-handlers/types').CacheEntry>} */
const store = new Map()
/** @type {Map<string, Promise<void>>} */
const pendingSets = new Map()
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const cacheHandler = {
async get(cacheKey, softTags) {
const pendingPromise = pendingSets.get(cacheKey)
if (pendingPromise) {
await pendingPromise
}
const entry = store.get(cacheKey)
if (!entry) {
console.log('PersistentCacheHandler::get', cacheKey, softTags, '-> miss')
return undefined
}
const [returnStream, savedStream] = entry.value.tee()
entry.value = savedStream
console.log(
'PersistentCacheHandler::get',
cacheKey,
softTags,
'-> hit, revalidate:',
entry.revalidate
)
return { ...entry, value: returnStream }
},
async set(cacheKey, pendingEntry) {
/** @type {() => void} */
let resolvePending = () => {}
const pendingPromise = new Promise((resolve) => {
resolvePending = /** @type {() => void} */ (resolve)
})
pendingSets.set(cacheKey, pendingPromise)
try {
const entry = await pendingEntry
const [value, clonedValue] = entry.value.tee()
entry.value = value
// Consume the cloned stream to ensure the entry is fully resolved.
const reader = clonedValue.getReader()
while (!(await reader.read()).done) {}
store.set(cacheKey, entry)
console.log('PersistentCacheHandler::set', cacheKey)
} catch (err) {
console.log('PersistentCacheHandler::set', cacheKey, 'failed', err)
} finally {
resolvePending()
pendingSets.delete(cacheKey)
}
},
async refreshTags() {},
async getExpiration(_tags) {
return Infinity
},
async updateTags(_tags) {},
}
module.exports = cacheHandler
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
cacheHandlers: {
default: require.resolve('./handler.js'),
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('use-cache-swr', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
let outputIndex: number
beforeEach(() => {
outputIndex = next.cliOutput.length
})
it('should serve stale data and then pre-warmed data on subsequent request', async () => {
const browser = await next.browser('/')
const initialOuter = await browser.elementById('outer-data').text()
expect(initialOuter).toBeDateString()
// Wait for the outer cache to go stale (revalidate: 5).
await new Promise((resolve) => setTimeout(resolve, 6000))
// This request should trigger SWR: the handler returns the stale entry,
// the framework serves it to the client, and kicks off a background regen.
await browser.refresh()
const afterStale = await browser.elementById('outer-data').text()
// The stale data should be the same as the initial data.
expect(afterStale).toBe(initialOuter)
// Wait for the background regen to complete by polling for its set log.
await retry(() => {
const regenOutput = next.cliOutput.slice(outputIndex)
expect(regenOutput).toMatch(/PersistentCacheHandler::set.*"outer"/)
})
// Reset output index to capture only the next request's handler logs.
outputIndex = next.cliOutput.length
// Refresh again. The pre-warmed entry from the SWR regen should be served.
await browser.refresh()
const afterRegen = await browser.elementById('outer-data').text()
// The data should now be fresh (different from the stale data).
expect(afterRegen).not.toBe(initialOuter)
// Verify this was served from the pre-warmed cache (get hit, no set).
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toMatch(/PersistentCacheHandler::get.*"outer".*-> hit/)
expect(cliOutput).not.toMatch(/PersistentCacheHandler::set.*"outer"/)
})
it('should pass implicit tags to cache handler get() for nested caches during SWR', async () => {
const browser = await next.browser('/')
await browser.elementById('outer-data').text()
// Wait for the outer cache to go stale (revalidate: 5).
await new Promise((resolve) => setTimeout(resolve, 6000))
// Reset output index to capture only the SWR-related logs.
outputIndex = next.cliOutput.length
// This triggers SWR: stale outer is served, background regen starts.
// During regen, the outer fn re-executes and calls the inner "use cache".
// The inner cache's get() should receive the page's implicit tags.
await browser.refresh()
// Wait for the background regen to complete.
await new Promise((resolve) => setTimeout(resolve, 1000))
const cliOutput = next.cliOutput.slice(outputIndex)
// The inner cache's get() during SWR regen should include the page's
// implicit tags (softTags), not an empty array. We identify the inner
// cache by its "inner" sentinel argument in the key.
expect(cliOutput).toMatch(/PersistentCacheHandler::get.*"inner".*_N_T_\//)
})
})
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