Unverified Commit 40188b5e authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[test] Cover `'use cache: private'` in route handlers (#97349)

The `use-cache-private` suite covered private caches in server
components only, so this adds a route handler that calls one `'use
cache: private'` function three times: a concurrent pair, and a third
call after a short delay. The concurrent pair joins a single in-flight
invocation, while the delayed call lands after the map of pending
intra-request invocations has dropped its entry, so it is served from
the completed entry that the request retains. Each call passes a fresh
object literal, which makes the React `cache()` memo miss on reference
equality so that the lookup falls through to the serialized cache key.
The cache function also reads a cookie, which covers that request APIs
are allowed inside a private cache in a route handler.

A second test asserts that nothing is shared across requests. In
production private entries are neither persisted nor deduped across
requests, so every request re-runs the cache function. In development
they are persisted and forced to `revalidate: 0`, so the next request is
served the stale entry while a fresh one warms in the background, which
the dev branch of the test follows. Both tests pass their own `id`
search param, and therefore use their own cache key, so the entry that
dev persists for one is never served to the other.

This also drops the claim that the directive is not available in route
handlers from the `'use cache: private'` reference. Nothing in the
source rejects it, and it was already allowed for request work unit
stores when that note was written.
parent d0798a04
...@@ -49,8 +49,6 @@ export default nextConfig ...@@ -49,8 +49,6 @@ export default nextConfig
Then add `'use cache: private'` to your function along with a `cacheLife` configuration. Then add `'use cache: private'` to your function along with a `cacheLife` configuration.
> **Good to know**: This directive is not available in Route Handlers.
### Basic example ### Basic example
In this example, we demonstrate that you can access cookies within a `'use cache: private'` scope: In this example, we demonstrate that you can access cookies within a `'use cache: private'` scope:
......
import { cacheLife } from 'next/cache'
import { cookies } from 'next/headers'
import type { NextRequest } from 'next/server'
import { setTimeout } from 'timers/promises'
async function getPrivateValue(params: { id: string }) {
'use cache: private'
// Setting a stale time doesn't have an effect in a route handler, but this
// might be a cache function that's shared with server components, so the
// cacheLife call should still be allowed.
cacheLife({ stale: 1000 })
// Simulate I/O latency so the concurrent calls below overlap.
await setTimeout(200)
// Reading cookies is allowed inside a private cache, also in a route handler.
const testCookie = (await cookies()).get('use-cache-private-test')
return `${params.id}:${testCookie?.value ?? '<empty>'}:${Math.random()}`
}
export async function GET(request: NextRequest) {
// The private cache already makes this route dynamic. The search param gives
// each test its own `id`, and therefore its own cache key, so the entry that
// dev persists for one test is never served to another.
const id = request.nextUrl.searchParams.get('id') ?? 'default'
// Each call passes a fresh object literal, so the React.cache memo that wraps
// every cache function misses on reference equality and the lookup falls
// through to the serialized cache key.
const [concurrentA, concurrentB] = await Promise.all([
getPrivateValue({ id }),
getPrivateValue({ id }),
])
// The map of pending intra-request invocations drops an entry once its fill
// completes, so this delay puts the call below outside the in-flight window.
// Reuse then depends on the completed entry that the request retains, not on
// joining a pending fill.
await setTimeout(100)
const sequential = await getPrivateValue({ id })
return Response.json({ concurrentA, concurrentB, sequential })
}
...@@ -121,6 +121,51 @@ describe('use-cache-private', () => { ...@@ -121,6 +121,51 @@ describe('use-cache-private', () => {
} }
}) })
it('dedupes private caches within a route handler request', async () => {
const response = await next.fetch('/route-handler?id=dedupe', {
headers: { cookie: 'use-cache-private-test=from-cookie' },
})
const { concurrentA, concurrentB, sequential } = await response.json()
// The cache function read the request's cookie.
expect(concurrentA).toStartWith('dedupe:from-cookie:')
// Two concurrent calls join a single in-flight invocation.
expect(concurrentB).toBe(concurrentA)
// A call made after the in-flight window has closed is served the entry
// that the request retained.
expect(sequential).toBe(concurrentA)
})
it('does not share a route handler private cache entry across requests', async () => {
const fetchValue = async () => {
const response = await next.fetch('/route-handler?id=cross-request')
const { concurrentA } = await response.json()
return concurrentA
}
const initialValue = await fetchValue()
if (isNextDev) {
// In dev the private entry is persisted and forced to `revalidate: 0`, so
// it is always stale and served immediately on the next request while a
// fresh entry warms in the background.
expect(await fetchValue()).toBe(initialValue)
// A subsequent request reflects the freshly warmed value.
await retry(async () => {
expect(await fetchValue()).not.toBe(initialValue)
})
} else {
// In production private entries are neither persisted nor deduped across
// requests, so every request re-runs the cache function.
expect(await fetchValue()).not.toBe(initialValue)
}
})
it('revalidates a persisted entry by tag in dev', async () => { it('revalidates a persisted entry by tag in dev', async () => {
if (!isNextDev) { if (!isNextDev) {
// Private caches are only persisted in development, so tag revalidation // Private caches are only persisted in development, so tag revalidation
......
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