Unverified Commit 1066fbf7 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Improve deduping of concurrent `'use cache'` invocations (#91830)

With #71286, we implemented deduping of cache entries under certain
circumstances. For example, the following constructed example was fixed
with the PR:

```js
async function getCachedRandom() {
  'use cache'
  return Math.random()
}

const rand1 = await getCachedRandom()
const rand2 = await getCachedRandom()

assert(rand1 === rand2)
```

However, this implementation relied on awaiting the two calls
sequentially. When rendering components, this can usually not be
guaranteed. E.g. the following example was not properly deduped:

```jsx
async function Cached() {
  'use cache'
  return <p>{Math.random()}</p>
}

export default function Page() {
  return (
    <>
      <Cached />
      <Cached />
    </>
  )
}
```

This did render the same value, but only because we triggered two render
passes, and the last cached value was used for both elements in the
final render pass. But during the first render pass, the `Cached`
function was called twice, and the cache entry was also set twice.

With #75786, we also fixed the render scenario by wrapping the cached
function in `React.cache`. This however did not work for route handlers.
E.g. the first example rewritten as follows, and used in a route
handler, still wouldn't be deduped:

```js
const [rand1, rand2] = await Promise.all([
  getCachedRandom(),
  getCachedRandom(),
])
```

Furthermore, with this solution, nested cached functions could not be
deduped across different outer cache scopes. This is because each cache
scope creates its own `React.cache` scope. Example:

```jsx
async function Inner() {
  'use cache'
  return <p>{Math.random()}</p>
}

async function Outer1() {
  'use cache'
  return <Inner />
}

async function Outer2() {
  'use cache'
  return <Inner />
}

export default function Page() {
  return (
    <>
      <Outer1 />
      <Outer2 />
    </>
  )
}
```

This PR introduces two-layer invocation tracking that deduplicates these
cases without changing how cache handlers are implemented. Only the
first invocation (the "leader") performs the cache handler lookup and
generation. Subsequent invocations ("joiners") tee the leader's result
stream instead.

The deduplication scope starts after the Resume Data Cache (RDC) lookup
and before the cache handler `get`. The RDC phase is excluded because it
throws synchronous errors (dynamic usage errors) that need individual
stack traces per call site, and RDC lookups are local with no network
savings from deduplication.

Intra-request deduplication is stored on the `WorkStore` and keyed by
`serializedCacheKey` (the coarse key, which is safe because root params
are identical within a single request). Cross-request deduplication is
stored in a module-scope map keyed by `cacheHandlerKey`, which may
include root params on the warm path. Cross-request joiners must await
metadata for root param verification before forking the stream. If the
key mismatches (different root params), the joiner retries with a
recomputed key. Because metadata is checked before `fork()` is called, a
mismatched joiner never consumes a stream from the wrong entry.

Stream tee-ing is lazy via the `SharedCacheEntry` class: the leader
calls `fork()` to get its copy, and each joiner calls `fork()` on
demand. If no joiners exist, only one tee occurs. The
`SharedCacheResult` discriminated union wraps either a
`SharedCacheEntry` (for the cached case) or a hanging promise (for
`prerender-dynamic`).

Each invocation still decodes the stream independently via
`createFromReadableStream` with its own `temporaryReferences`, because
sharing the decoded result would cause cache poisoning when components
receive different non-serializable props (e.g. `children`).

Admittedly, this adds significant complexity to the `cache()` function.
Two classes help keep it manageable:
- `SharedCacheEntry` encapsulates stream ownership and lazy tee-ing so
that call sites don't need to reason about which streams have been
consumed or need cloning.
- `ResolvableSharedCacheResult` manages the deferred promise, map
registration, and lazy cleanup. Entries stay in the dedup maps until
collection completes (so late-arriving invocations can join while the
leader streams), then clean up automatically on resolve or reject.

A follow-up refactoring to extract the cache handler lookup and
generation into a separate function would help break up the function's
size.

closes #78703
parent a7d15733
......@@ -5,6 +5,7 @@ import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import type { AfterContext } from '../after/after-context'
import type { CacheLife } from '../use-cache/cache-life'
import type { SharedCacheResult } from '../use-cache/use-cache-wrapper'
// Share the instance module in the next-shared layer
import { workAsyncStorageInstance } from './work-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
......@@ -82,6 +83,16 @@ export interface WorkStore {
fetchMetrics?: FetchMetrics
shouldTrackFetchMetrics: boolean
/**
* Tracks pending `"use cache"` invocations within the current request scope,
* keyed by the serialized cache key (coarse key). Used for intra-request
* deduplication: when multiple components call the same cache function within
* a single request, only the first one runs (cache handler lookup +
* generation), and joiners tee its result stream.
* Root params are identical within a request, so the coarse key is sufficient.
*/
pendingCacheInvocations?: Map<string, Promise<SharedCacheResult>>
isDraftMode?: boolean
isUnstableNoStore?: boolean
isPrefetchRequest?: boolean
......
......@@ -11,7 +11,7 @@ import type { CollectedCacheResult } from '../use-cache/use-cache-wrapper'
*/
type CacheStore<T> = Pick<
Map<string, T>,
'entries' | 'keys' | 'size' | 'get' | 'set' | typeof Symbol.iterator
'entries' | 'keys' | 'size' | 'get' | 'set' | 'has' | typeof Symbol.iterator
>
/**
......
......@@ -76,6 +76,7 @@ import type { CacheLife } from './cache-life'
import { RenderStage } from '../app-render/staged-rendering'
import * as Log from '../../build/output/log'
import { getServerReact, getClientReact } from '../runtime-reacts.external'
import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'
interface PrivateCacheContext {
readonly kind: 'private'
......@@ -124,6 +125,120 @@ export type UseCacheLayoutProps = {
[slot: string]: any
}
/**
* Cache entry metadata for propagation. Separated from the stream to make
* ownership clear: metadata is freely shareable, streams must be explicitly
* tee'd for each consumer.
*/
interface CacheResultMetadata {
readonly tags: string[]
readonly revalidate: number
readonly expire: number
readonly stale: number
readonly timestamp: number
readonly readRootParamNames: ReadonlySet<string> | undefined
readonly hasExplicitRevalidate: boolean | undefined
readonly hasExplicitExpire: boolean | undefined
}
/**
* Encapsulates a pending cache invocation for deduping. Manages lazy stream
* tee-ing (via fork()) and metadata access for both intra-request and
* cross-request joiners.
*/
class SharedCacheEntry {
private stream: ReadableStream<Uint8Array>
/**
* The pending metadata promise. Cross-request joiners need to await this for
* root param verification BEFORE calling fork(). Intra-request joiners chain
* .then() for fire-and-forget propagation.
*/
public readonly pendingMetadata: Promise<CacheResultMetadata>
constructor(
stream: ReadableStream<Uint8Array>,
pendingMetadata: Promise<CacheResultMetadata>
) {
this.stream = stream
this.pendingMetadata = pendingMetadata
}
/**
* Tee the stream: returns a copy for the caller, replaces the internal stream
* with the remaining branch for future callers. Both the leader and joiners
* call this — everyone gets a fork.
*/
fork(): ReadableStream<Uint8Array> {
const [forked, remaining] = this.stream.tee()
this.stream = remaining
return forked
}
}
export type SharedCacheResult =
| {
readonly type: 'cached'
readonly entry: SharedCacheEntry
}
| {
readonly type: 'prerender-dynamic'
readonly hangingPromise: Promise<never>
}
/**
* Manages the deferred promise for a shared cache result, tracks which maps
* it's registered in, and drives cleanup from resolve/reject.
*
* For 'cached' results, cleanup is lazy: entries stay in the maps until
* metadata/collection resolves, giving late-arriving invocations a chance to
* join while the leader streams. For 'prerender-dynamic' and errors, cleanup
* is immediate.
*/
class ResolvableSharedCacheResult {
private readonly deferred = createPromiseWithResolvers<SharedCacheResult>()
private readonly registrations: Array<{
map: Map<string, Promise<SharedCacheResult>>
key: string
}> = []
registerIn(map: Map<string, Promise<SharedCacheResult>>, key: string): void {
map.set(key, this.deferred.promise)
this.registrations.push({ map, key })
}
resolve(result: SharedCacheResult): void {
this.deferred.resolve(result)
if (result.type === 'cached') {
result.entry.pendingMetadata.finally(this.cleanup.bind(this))
} else {
this.cleanup()
}
}
reject(error: unknown): void {
this.deferred.reject(error)
this.cleanup()
}
private cleanup(): void {
for (const { map, key } of this.registrations) {
map.delete(key)
}
}
}
/**
* Module-scope map for cross-request deduplication. Keyed by `cacheHandlerKey`
* (specific key on warm path, coarse key on cold path). Entries live only for
* the duration of the leader's invocation.
*/
const crossRequestPendingCacheInvocations = new Map<
string,
Promise<SharedCacheResult>
>()
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
......@@ -211,10 +326,58 @@ function saveToResumeDataCache(
// use the coarse key (without root param suffix). Unlike the cache handler,
// the RDC doesn't need root-param-specific keys for isolation.
prerenderResumeDataCache.cache.set(serializedCacheKey, rdcResult)
debug?.('Resume Data Cache entry saved', serializedCacheKey)
return savedCacheResult
}
/**
* A joiner's RDC context may differ from the leader's:
*
* - Intra-request: the leader was nested inside another cache (no accessible
* RDC) while this joiner is top-level and has one.
* - Cross-request: the leader belongs to a different request entirely — this
* request's RDC has never seen the entry.
*
* In both cases the joiner must save to its own RDC so its final prerender can
* resume from the entry. Constructs a `CollectedCacheResult` from a forked
* stream branch of the shared entry and the awaited metadata.
*
* The `cache.has()` guard avoids redundant saves when the intra-request leader
* already saved to the same RDC. Without it, this would needlessly tee the
* stream and overwrite an equivalent RDC entry.
*/
function saveSharedCacheEntryToResumeDataCache(
serializedCacheKey: string,
sharedCacheEntry: SharedCacheEntry,
prerenderResumeDataCache: PrerenderResumeDataCache | null
): void {
if (
!prerenderResumeDataCache ||
prerenderResumeDataCache.cache.has(serializedCacheKey)
) {
return
}
const rdcResult: Promise<CollectedCacheResult> =
sharedCacheEntry.pendingMetadata.then((metadata) => ({
entry: {
value: sharedCacheEntry.fork(),
tags: metadata.tags,
revalidate: metadata.revalidate,
expire: metadata.expire,
stale: metadata.stale,
timestamp: metadata.timestamp,
},
readRootParamNames: metadata.readRootParamNames,
hasExplicitRevalidate: metadata.hasExplicitRevalidate,
hasExplicitExpire: metadata.hasExplicitExpire,
}))
prerenderResumeDataCache.cache.set(serializedCacheKey, rdcResult)
debug?.('Resume Data Cache entry saved by joiner', serializedCacheKey)
}
function saveToCacheHandler(
cacheHandler: CacheHandler,
workStore: WorkStore,
......@@ -503,42 +666,41 @@ function generateCacheEntryWithCacheContext(
function propagateCacheLifeAndTagsToRevalidateStore(
revalidateStore: RevalidateStore,
entry: CacheEntry
metadata: CacheResultMetadata
): void {
const outerTags = (revalidateStore.tags ??= [])
for (const tag of entry.tags) {
for (const tag of metadata.tags) {
if (!outerTags.includes(tag)) {
outerTags.push(tag)
}
}
if (revalidateStore.stale > entry.stale) {
revalidateStore.stale = entry.stale
if (revalidateStore.stale > metadata.stale) {
revalidateStore.stale = metadata.stale
}
if (revalidateStore.revalidate > entry.revalidate) {
revalidateStore.revalidate = entry.revalidate
if (revalidateStore.revalidate > metadata.revalidate) {
revalidateStore.revalidate = metadata.revalidate
}
if (revalidateStore.expire > entry.expire) {
revalidateStore.expire = entry.expire
if (revalidateStore.expire > metadata.expire) {
revalidateStore.expire = metadata.expire
}
}
function propagateCacheStaleTimeToRequestStore(
requestStore: RequestStore,
entry: CacheEntry
metadata: CacheResultMetadata
): void {
if (requestStore.stale !== undefined && requestStore.stale > entry.stale) {
requestStore.stale = entry.stale
if (requestStore.stale !== undefined && requestStore.stale > metadata.stale) {
requestStore.stale = metadata.stale
}
}
function propagateCacheEntryMetadata(
cacheContext: CacheContext,
entry: CacheEntry,
readRootParamNames: ReadonlySet<string> | undefined
metadata: CacheResultMetadata
): void {
if (cacheContext.kind === 'private') {
switch (cacheContext.outerWorkUnitStore.type) {
......@@ -546,13 +708,13 @@ function propagateCacheEntryMetadata(
case 'private-cache':
propagateCacheLifeAndTagsToRevalidateStore(
cacheContext.outerWorkUnitStore,
entry
metadata
)
break
case 'request':
propagateCacheStaleTimeToRequestStore(
cacheContext.outerWorkUnitStore,
entry
metadata
)
break
case undefined:
......@@ -563,8 +725,8 @@ function propagateCacheEntryMetadata(
} else {
switch (cacheContext.outerWorkUnitStore.type) {
case 'cache':
if (readRootParamNames) {
for (const paramName of readRootParamNames) {
if (metadata.readRootParamNames) {
for (const paramName of metadata.readRootParamNames) {
cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName)
}
}
......@@ -576,13 +738,13 @@ function propagateCacheEntryMetadata(
case 'prerender-legacy':
propagateCacheLifeAndTagsToRevalidateStore(
cacheContext.outerWorkUnitStore,
entry
metadata
)
break
case 'request':
propagateCacheStaleTimeToRequestStore(
cacheContext.outerWorkUnitStore,
entry
metadata
)
break
case 'unstable-cache':
......@@ -611,8 +773,7 @@ function propagateCacheEntryMetadata(
*/
function maybePropagateCacheEntryMetadata(
cacheContext: CacheContext,
entry: CacheEntry,
readRootParamNames: ReadonlySet<string> | undefined
metadata: CacheResultMetadata
): void {
const outerWorkUnitStore = cacheContext.outerWorkUnitStore
......@@ -640,7 +801,7 @@ function maybePropagateCacheEntryMetadata(
case 'unstable-cache':
case 'prerender-legacy':
case 'prerender-ppr': {
propagateCacheEntryMetadata(cacheContext, entry, readRootParamNames)
propagateCacheEntryMetadata(cacheContext, metadata)
break
}
case 'generate-static-params':
......@@ -752,14 +913,27 @@ async function collectResult(
tags: collectedTags === null ? [] : collectedTags,
}
if (!cacheContext.skipPropagation) {
maybePropagateCacheEntryMetadata(
cacheContext,
entry,
const collected: CollectedCacheResult = {
entry,
hasExplicitRevalidate: innerCacheStore.explicitRevalidate !== undefined,
hasExplicitExpire: innerCacheStore.explicitExpire !== undefined,
readRootParamNames:
innerCacheStore.type === 'cache'
? innerCacheStore.readRootParamNames
: undefined
)
: undefined,
}
if (!cacheContext.skipPropagation) {
maybePropagateCacheEntryMetadata(cacheContext, {
tags: collected.entry.tags,
revalidate: collected.entry.revalidate,
expire: collected.entry.expire,
stale: collected.entry.stale,
timestamp: collected.entry.timestamp,
hasExplicitRevalidate: collected.hasExplicitRevalidate,
hasExplicitExpire: collected.hasExplicitExpire,
readRootParamNames: collected.readRootParamNames,
})
const cacheSignal = getCacheSignal(cacheContext.outerWorkUnitStore)
if (cacheSignal) {
......@@ -767,15 +941,7 @@ async function collectResult(
}
}
return {
entry,
hasExplicitRevalidate: innerCacheStore.explicitRevalidate !== undefined,
hasExplicitExpire: innerCacheStore.explicitExpire !== undefined,
readRootParamNames:
innerCacheStore.type === 'cache'
? innerCacheStore.readRootParamNames
: undefined,
}
return collected
}
type GenerateCacheEntryResult =
......@@ -860,7 +1026,7 @@ async function generateCacheEntryImpl(
// capture logs so that we can later replay them.
const resultPromise = createLazyResult(fn.bind(null, ...args))
let errors: Array<unknown> = []
const errors: Array<unknown> = []
// In the "Cache" environment, we only need to make sure that the error
// digests are handled correctly. Error formatting and reporting is not
......@@ -1780,11 +1946,16 @@ export async function cache(
// We want to make sure we only propagate cache life & tags if the
// entry was *not* omitted from the prerender. So we only do this
// after the above early returns.
propagateCacheEntryMetadata(
cacheContext,
rdcResult.entry,
rdcResult.readRootParamNames
)
propagateCacheEntryMetadata(cacheContext, {
tags: rdcResult.entry.tags,
revalidate: rdcResult.entry.revalidate,
expire: rdcResult.entry.expire,
stale: rdcResult.entry.stale,
timestamp: rdcResult.entry.timestamp,
hasExplicitRevalidate: rdcResult.hasExplicitRevalidate,
hasExplicitExpire: rdcResult.hasExplicitExpire,
readRootParamNames: rdcResult.readRootParamNames,
})
const [streamA, streamB] = rdcResult.entry.value.tee()
rdcResult.entry.value = streamB
......@@ -1874,251 +2045,473 @@ export async function cache(
}
}
// Intra-request deduplication: Within a single request, root params are
// fixed, so the coarse key (serializedCacheKey) is sufficient. If another
// invocation in this request is already handling the same cache entry
// (including the cache handler lookup and generation), we join it instead of
// doing redundant work. This also saves cache handler `get` calls which may
// be HTTP round-trips for remote handlers.
if (stream === undefined) {
const cacheSignal = getCacheSignal(workUnitStore)
if (cacheSignal) {
// Either the cache handler or the generation can be using I/O at this point.
// We need to track when they start and when they complete.
cacheSignal.beginRead()
}
const intraRequestPendingCacheInvocation =
workStore.pendingCacheInvocations?.get(serializedCacheKey)
const lazyRefreshTags = workStore.refreshTagsByCacheKind.get(kind)
if (intraRequestPendingCacheInvocation) {
const cacheSignal = getCacheSignal(workUnitStore)
cacheSignal?.beginRead()
if (lazyRefreshTags && !isResolvedLazyResult(lazyRefreshTags)) {
await lazyRefreshTags
}
debug?.('joining pending intra-request invocation', serializedCacheKey)
const sharedCacheResult = await intraRequestPendingCacheInvocation
let entry: CacheEntry | undefined
if (sharedCacheResult.type === 'prerender-dynamic') {
debug?.('joined invocation is prerender-dynamic', serializedCacheKey)
cacheSignal?.endRead()
return sharedCacheResult.hangingPromise
}
// We ignore existing cache entries when force revalidating.
if (cacheHandler && !shouldForceRevalidate(workStore, workUnitStore)) {
entry = await cacheHandler.get(cacheHandlerKey, implicitTags)
debug?.(
'joined invocation resolved with cached entry',
serializedCacheKey
)
// Check if this is a redirect entry (coarse key → specific key). Redirect
// entries have private tags encoding the root param names (one tag per
// param name, prefixed with _N_RP_).
if (entry && rootParams) {
const paramNames = new Set<string>()
for (const tag of entry.tags) {
if (tag.startsWith(NEXT_CACHE_ROOT_PARAM_TAG_ID)) {
paramNames.add(tag.slice(NEXT_CACHE_ROOT_PARAM_TAG_ID.length))
}
}
if (paramNames.size > 0) {
addKnownRootParamNames(id, paramNames)
cacheHandlerKey =
serializedCacheKey +
computeRootParamsCacheKeySuffix(rootParams, paramNames)
entry = await cacheHandler.get(cacheHandlerKey, implicitTags)
}
}
}
stream = sharedCacheResult.entry.fork()
if (entry) {
let implicitTagsExpiration = 0
if (workUnitStore.implicitTags) {
const lazyExpiration =
workUnitStore.implicitTags.expirationsByCacheKind.get(kind)
if (lazyExpiration) {
const expiration = isResolvedLazyResult(lazyExpiration)
? lazyExpiration.value
: await lazyExpiration
// If a cache handler returns an expiration time of Infinity, it
// signals to Next.js that it handles checking cache entries for
// staleness based on the expiration of the implicit tags passed
// into the `get` method. In this case, we keep the default of 0,
// which means that the implicit tags are not considered expired.
if (expiration < Infinity) {
implicitTagsExpiration = expiration
}
}
}
// If the leader was nested inside another cache (no accessible RDC), it
// couldn't save to the RDC. This joiner may be top-level with an RDC, in
// which case it must save here; otherwise the RDC lookup during the
// final prerender will miss.
saveSharedCacheEntryToResumeDataCache(
serializedCacheKey,
sharedCacheResult.entry,
prerenderResumeDataCache
)
if (
shouldDiscardCacheEntry(
entry,
workStore,
workUnitStore,
implicitTags,
implicitTagsExpiration
)
) {
debug?.('discarding expired entry', cacheHandlerKey)
entry = undefined
}
// End the cache signal read when the result is fully collected, not when
// the stream is available. Fire-and-forget propagation runs in the same
// .then() callback. .catch() prevents unhandled rejection if collection
// fails after the rendering stream was already resolved.
sharedCacheResult.entry.pendingMetadata
.then((metadata) => {
cacheSignal?.endRead()
maybePropagateCacheEntryMetadata(cacheContext, metadata)
})
.catch(() => {})
}
}
const currentTime = performance.timeOrigin + performance.now()
if (
entry !== undefined &&
(entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE)
) {
switch (workUnitStore.type) {
case 'prerender':
// In a Dynamic I/O prerender, if the cache entry has revalidate:
// 0 or if the expire time is under 5 minutes, then we consider
// this cache entry dynamic as it's not worth generating static
// pages for such data. It's better to leave a dynamic hole that
// can be filled in during the resume with a potentially cached
// entry.
if (entry.revalidate === 0) {
// Leader path: no pending intra-request invocation found. Check for a
// cross-request pending invocation, or become the leader for both.
if (stream === undefined) {
const resolvableSharedCacheResult = new ResolvableSharedCacheResult()
debug?.(
'registering as intra-request invocation leader',
serializedCacheKey
)
const intraRequestPendingCacheInvocations =
(workStore.pendingCacheInvocations ??= new Map<
string,
Promise<SharedCacheResult>
>())
resolvableSharedCacheResult.registerIn(
intraRequestPendingCacheInvocations,
serializedCacheKey
)
try {
// The loop handles cross-request root param mismatches: when a
// cross-request joiner discovers that the leader's root params differ
// from its own, it retries with a recomputed cacheHandlerKey. The loop
// exits when stream is assigned (cross-request joiner match or leader
// path) or via early return (prerender-dynamic).
while (stream === undefined) {
// Cross-request deduplication. Private caches are skipped because they
// contain per-request data that must not be shared across requests.
const crossRequestPendingCacheInvocation = isPrivate
? undefined
: crossRequestPendingCacheInvocations.get(cacheHandlerKey)
if (crossRequestPendingCacheInvocation) {
const cacheSignal = getCacheSignal(workUnitStore)
cacheSignal?.beginRead()
debug?.('joining pending cross-request invocation', cacheHandlerKey)
const sharedCacheResult = await crossRequestPendingCacheInvocation
if (sharedCacheResult.type === 'cached') {
// Root param verification: wait for metadata, then check key. MUST
// happen before fork() — if key mismatches, we retry without having
// used the stream.
const metadata = await sharedCacheResult.entry.pendingMetadata
// Ensure known root param names are up-to-date before verifying the
// key, since the leader's save path may not have updated them yet
// at this point.
if (metadata.readRootParamNames) {
addKnownRootParamNames(id, metadata.readRootParamNames)
}
const updatedRootParamNames = knownRootParamsByFunctionId.get(id)
if (updatedRootParamNames && rootParams) {
const newCacheHandlerKey =
serializedCacheKey +
computeRootParamsCacheKeySuffix(
rootParams,
updatedRootParamNames
)
if (newCacheHandlerKey !== cacheHandlerKey) {
debug?.(
'cross-request root param mismatch, retrying',
cacheHandlerKey,
'→',
newCacheHandlerKey
)
cacheSignal?.endRead()
cacheHandlerKey = newCacheHandlerKey
continue // stream is not used → retry with new key
}
}
// Key matches — safe to fork.
debug?.(
'omitting entry',
cacheHandlerKey,
'from static shell due to revalidate: 0'
'cross-request invocation matched, forking result',
cacheHandlerKey
)
cacheSignal?.endRead()
stream = sharedCacheResult.entry.fork()
maybePropagateCacheEntryMetadata(cacheContext, metadata)
// The cross-request leader belongs to a different request with its
// own RDC. Save to this request's RDC so its final prerender can
// resume from the entry.
saveSharedCacheEntryToResumeDataCache(
serializedCacheKey,
sharedCacheResult.entry,
prerenderResumeDataCache
)
// Resolve for intra-request joiners in this request. They get
// a fork from the same SharedCacheEntry.
resolvableSharedCacheResult.resolve(sharedCacheResult)
break
} else {
// prerender-dynamic — same root param check before hanging
const updatedRootParamNames = knownRootParamsByFunctionId.get(id)
if (updatedRootParamNames && rootParams) {
const newCacheHandlerKey =
serializedCacheKey +
computeRootParamsCacheKeySuffix(
rootParams,
updatedRootParamNames
)
if (newCacheHandlerKey !== cacheHandlerKey) {
debug?.(
'cross-request root param mismatch, retrying',
cacheHandlerKey,
'→',
newCacheHandlerKey
)
cacheSignal?.endRead()
cacheHandlerKey = newCacheHandlerKey
continue
}
}
debug?.(
'omitting entry',
cacheHandlerKey,
'from static shell due to short expire value:',
entry.expire
'cross-request invocation is prerender-dynamic',
cacheHandlerKey
)
if (prerenderResumeDataCache) {
prerenderResumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
}
cacheSignal?.endRead()
resolvableSharedCacheResult.resolve(sharedCacheResult)
return sharedCacheResult.hangingPromise
}
if (cacheSignal) {
cacheSignal.endRead()
}
return makeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
}
// No pending cross-request invocation — become the leader.
if (!isPrivate) {
debug?.(
'registering as cross-request invocation leader',
cacheHandlerKey
)
resolvableSharedCacheResult.registerIn(
crossRequestPendingCacheInvocations,
cacheHandlerKey
)
case 'request': {
if (process.env.NODE_ENV === 'development') {
// We delay the cache here so that it doesn't resolve in the static task --
// in a regular static prerender, it'd be a hanging promise, and we need to reflect that,
// so it has to resolve later.
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts.
// We don't end the cache read here, so this will always appear as a cache miss in the static stage,
// and thus will cause a restart even if all caches are filled.
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(undefined, workUnitStore, stage)
}
const cacheSignal = getCacheSignal(workUnitStore)
if (cacheSignal) {
// Either the cache handler or the generation can be using I/O at this
// point. We need to track when they start and when they complete.
cacheSignal.beginRead()
}
const lazyRefreshTags = workStore.refreshTagsByCacheKind.get(kind)
if (lazyRefreshTags && !isResolvedLazyResult(lazyRefreshTags)) {
await lazyRefreshTags
}
let entry: CacheEntry | undefined
// We ignore existing cache entries when force revalidating.
if (cacheHandler && !shouldForceRevalidate(workStore, workUnitStore)) {
entry = await cacheHandler.get(cacheHandlerKey, implicitTags)
// Check if this is a redirect entry (coarse key → specific key).
// Redirect entries have private tags encoding the root param names
// (one tag per param name, prefixed with _N_RP_).
if (entry && rootParams) {
const paramNames = new Set<string>()
for (const tag of entry.tags) {
if (tag.startsWith(NEXT_CACHE_ROOT_PARAM_TAG_ID)) {
paramNames.add(tag.slice(NEXT_CACHE_ROOT_PARAM_TAG_ID.length))
}
}
if (paramNames.size > 0) {
addKnownRootParamNames(id, paramNames)
cacheHandlerKey =
serializedCacheKey +
computeRootParamsCacheKeySuffix(rootParams, paramNames)
entry = await cacheHandler.get(cacheHandlerKey, implicitTags)
}
}
break
}
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
}
if (
entry === undefined ||
currentTime > entry.timestamp + entry.expire * 1000 ||
(workStore.isStaticGeneration &&
currentTime > entry.timestamp + entry.revalidate * 1000)
) {
// Miss. Generate a new result.
// If the cache entry is stale and we're prerendering, we don't want to use the
// stale entry since it would unnecessarily need to shorten the lifetime of the
// prerender. We're not time constrained here so we can re-generated it now.
// We need to run this inside a clean AsyncLocalStorage snapshot so that the cache
// generation cannot read anything from the context we're currently executing which
// might include request specific things like cookies() inside a React.cache().
// Note: It is important that we await at least once before this because it lets us
// pop out of any stack specific contexts as well - aka "Sync" Local Storage.
if (entry) {
if (currentTime > entry.timestamp + entry.expire * 1000) {
debug?.('entry is expired', cacheHandlerKey)
if (entry) {
let implicitTagsExpiration = 0
if (workUnitStore.implicitTags) {
const lazyExpiration =
workUnitStore.implicitTags.expirationsByCacheKind.get(kind)
if (lazyExpiration) {
const expiration = isResolvedLazyResult(lazyExpiration)
? lazyExpiration.value
: await lazyExpiration
// If a cache handler returns an expiration time of Infinity, it
// signals to Next.js that it handles checking cache entries for
// staleness based on the expiration of the implicit tags passed
// into the `get` method. In this case, we keep the default of 0,
// which means that the implicit tags are not considered expired.
if (expiration < Infinity) {
implicitTagsExpiration = expiration
}
}
}
if (
shouldDiscardCacheEntry(
entry,
workStore,
workUnitStore,
implicitTags,
implicitTagsExpiration
)
) {
debug?.('discarding expired entry', cacheHandlerKey)
entry = undefined
}
}
const currentTime = performance.timeOrigin + performance.now()
if (
workStore.isStaticGeneration &&
currentTime > entry.timestamp + entry.revalidate * 1000
entry !== undefined &&
(entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE)
) {
debug?.('static generation, entry is stale', cacheHandlerKey)
}
}
const result = await generateCacheEntry(
workStore,
cacheContext,
clientReferenceManifest,
encodedCacheKeyParts,
fn,
timeoutError
)
switch (workUnitStore.type) {
case 'prerender':
// In a Dynamic I/O prerender, if the cache entry has revalidate:
// 0 or if the expire time is under 5 minutes, then we consider
// this cache entry dynamic as it's not worth generating static
// pages for such data. It's better to leave a dynamic hole that
// can be filled in during the resume with a potentially cached
// entry.
if (entry.revalidate === 0) {
debug?.(
'omitting entry',
cacheHandlerKey,
'from static shell due to revalidate: 0'
)
} else {
debug?.(
'omitting entry',
cacheHandlerKey,
'from static shell due to short expire value:',
entry.expire
)
}
if (cacheSignal) {
cacheSignal.endRead()
}
if (result.type === 'prerender-dynamic') {
if (prerenderResumeDataCache) {
prerenderResumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
const hangingPromise = makeHangingPromise<never>(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
)
debug?.('leader resolved as prerender-dynamic', cacheHandlerKey)
resolvableSharedCacheResult.resolve({
type: 'prerender-dynamic',
hangingPromise,
})
return hangingPromise
case 'request': {
if (process.env.NODE_ENV === 'development') {
// We delay the cache here so that it doesn't resolve in the
// static task -- in a regular static prerender, it'd be a
// hanging promise, and we need to reflect that, so it has to
// resolve later.
// TODO(restart-on-cache-miss): Optimize this to avoid
// unnecessary restarts. We don't end the cache read here, so
// this will always appear as a cache miss in the static stage,
// and thus will cause a restart even if all caches are filled.
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(
undefined,
workUnitStore,
stage
)
}
break
}
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
}
return result.hangingPromise
}
const { stream: newStream, pendingCacheResult } = result
if (
entry === undefined ||
currentTime > entry.timestamp + entry.expire * 1000 ||
(workStore.isStaticGeneration &&
currentTime > entry.timestamp + entry.revalidate * 1000)
) {
// Miss. Generate a new result.
// If the cache entry is stale and we're prerendering, we don't want
// to use the stale entry since it would unnecessarily need to shorten
// the lifetime of the prerender. We're not time constrained here so
// we can re-generated it now.
// We need to run this inside a clean AsyncLocalStorage snapshot so
// that the cache generation cannot read anything from the context
// we're currently executing which might include request specific
// things like cookies() inside a React.cache().
// Note: It is important that we await at least once before this
// because it lets us pop out of any stack specific contexts as well -
// aka "Sync" Local Storage.
if (entry) {
if (currentTime > entry.timestamp + entry.expire * 1000) {
debug?.('entry is expired', cacheHandlerKey)
}
// When draft mode is enabled, we must not save the cache entry.
if (!workStore.isDraftMode) {
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
serializedCacheKey,
pendingCacheResult
)
if (
workStore.isStaticGeneration &&
currentTime > entry.timestamp + entry.revalidate * 1000
) {
debug?.('static generation, entry is stale', cacheHandlerKey)
}
}
if (cacheHandler) {
saveToCacheHandler(
cacheHandler,
const result = await generateCacheEntry(
workStore,
id,
serializedCacheKey,
savedCacheResult,
rootParams
cacheContext,
clientReferenceManifest,
encodedCacheKeyParts,
fn,
timeoutError
)
}
}
stream = newStream
} else {
// If we have an entry at this point, this can't be a private cache
// entry.
if (cacheContext.kind === 'private') {
throw new InvariantError(
`A private cache entry must not be retrieved from the cache handler.`
)
}
if (result.type === 'prerender-dynamic') {
debug?.(
'leader resolved as prerender-dynamic (generation)',
cacheHandlerKey
)
if (prerenderResumeDataCache) {
prerenderResumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
}
resolvableSharedCacheResult.resolve(result)
return result.hangingPromise
}
maybePropagateCacheEntryMetadata(
cacheContext,
entry,
knownRootParamsByFunctionId.get(id)
)
const { stream: newStream, pendingCacheResult } = result
// We want to return this stream, even if it's stale.
stream = entry.value
// When draft mode is enabled, we must not save the cache entry.
if (!workStore.isDraftMode) {
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
serializedCacheKey,
pendingCacheResult
)
// If we have a resume data cache, we need to clone the entry and add it
// to the resume data cache.
if (prerenderResumeDataCache) {
const [entryLeft, entryRight] = cloneCacheEntry(entry)
if (cacheSignal) {
stream = createTrackedReadableStream(entryLeft.value, cacheSignal)
if (cacheHandler) {
saveToCacheHandler(
cacheHandler,
workStore,
id,
serializedCacheKey,
savedCacheResult,
rootParams
)
}
}
debug?.('leader resolved with generated entry', cacheHandlerKey)
const pendingMetadata: Promise<CacheResultMetadata> =
pendingCacheResult.then((collected) => ({
tags: collected.entry.tags,
revalidate: collected.entry.revalidate,
expire: collected.entry.expire,
stale: collected.entry.stale,
timestamp: collected.entry.timestamp,
hasExplicitRevalidate: collected.hasExplicitRevalidate,
hasExplicitExpire: collected.hasExplicitExpire,
readRootParamNames: collected.readRootParamNames,
}))
const sharedCacheEntry = new SharedCacheEntry(
newStream,
pendingMetadata
)
stream = sharedCacheEntry.fork()
resolvableSharedCacheResult.resolve({
type: 'cached',
entry: sharedCacheEntry,
})
} else {
stream = entryLeft.value
}
// If we have an entry at this point, this can't be a private cache
// entry.
if (cacheContext.kind === 'private') {
throw new InvariantError(
`A private cache entry must not be retrieved from the cache handler.`
)
}
// The RDC is per-page and root params are fixed within a page, so we
// always use the coarse key (without root param suffix).
prerenderResumeDataCache.cache.set(
serializedCacheKey,
Promise.resolve({
entry: entryRight,
const entryMetadata: CacheResultMetadata = {
tags: entry.tags,
revalidate: entry.revalidate,
expire: entry.expire,
stale: entry.stale,
timestamp: entry.timestamp,
readRootParamNames: knownRootParamsByFunctionId.get(id),
// For pre-existing entries from cache handlers we don't know
// whether they had explicit cache life values or not. But we only
// need this information during prerendering when we produce new
......@@ -2127,60 +2520,102 @@ export async function cache(
// set this to undefined here.
hasExplicitRevalidate: undefined,
hasExplicitExpire: undefined,
readRootParamNames: knownRootParamNames,
})
)
} else {
// If we're not regenerating we need to signal that we've finished
// putting the entry into the cache scope at this point. Otherwise we do
// that inside generateCacheEntry.
cacheSignal?.endRead()
}
}
if (currentTime > entry.timestamp + entry.revalidate * 1000) {
// If this is stale, and we're not in a prerender (i.e. this is
// dynamic render), then we should warm up the cache with a fresh
// revalidated entry.
const result = await generateCacheEntry(
workStore,
// The background revalidation preserves the outer store for reading
// (e.g. implicitTags) but skips propagation of cache life and tags
// back to the outer scope.
{
kind: cacheContext.kind,
outerWorkUnitStore: cacheContext.outerWorkUnitStore,
skipPropagation: true,
outerOwnerStack: cacheContext.outerOwnerStack,
},
clientReferenceManifest,
encodedCacheKeyParts,
fn,
timeoutError
)
maybePropagateCacheEntryMetadata(cacheContext, entryMetadata)
if (result.type === 'cached') {
const { stream: ignoredStream, pendingCacheResult } = result
// We want to return this stream, even if it's stale.
stream = entry.value
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
serializedCacheKey,
pendingCacheResult
)
// If we have a resume data cache, we need to clone the entry and add
// it to the resume data cache.
if (prerenderResumeDataCache) {
const [entryLeft, entryRight] = cloneCacheEntry(entry)
if (cacheSignal) {
stream = createTrackedReadableStream(entryLeft.value, cacheSignal)
} else {
stream = entryLeft.value
}
if (cacheHandler) {
saveToCacheHandler(
cacheHandler,
workStore,
id,
// The RDC is per-page and root params are fixed within a page, so
// we always use the coarse key (without root param suffix).
prerenderResumeDataCache.cache.set(
serializedCacheKey,
savedCacheResult,
rootParams
Promise.resolve({
entry: entryRight,
hasExplicitRevalidate: entryMetadata.hasExplicitRevalidate,
hasExplicitExpire: entryMetadata.hasExplicitExpire,
readRootParamNames: entryMetadata.readRootParamNames,
})
)
} else {
// If we're not regenerating we need to signal that we've finished
// putting the entry into the cache scope at this point. Otherwise
// we do that inside generateCacheEntry.
cacheSignal?.endRead()
}
await ignoredStream.cancel()
debug?.('leader resolved with cache handler hit', cacheHandlerKey)
const sharedCacheEntry = new SharedCacheEntry(
stream,
Promise.resolve(entryMetadata)
)
stream = sharedCacheEntry.fork()
resolvableSharedCacheResult.resolve({
type: 'cached',
entry: sharedCacheEntry,
})
if (currentTime > entry.timestamp + entry.revalidate * 1000) {
// If this is stale, and we're not in a prerender (i.e. this is
// dynamic render), then we should warm up the cache with a fresh
// revalidated entry.
const result = await generateCacheEntry(
workStore,
// The background revalidation preserves the outer store for
// reading (e.g. implicitTags) but skips propagation of cache life
// and tags back to the outer scope.
{
kind: cacheContext.kind,
outerWorkUnitStore: cacheContext.outerWorkUnitStore,
skipPropagation: true,
outerOwnerStack: cacheContext.outerOwnerStack,
},
clientReferenceManifest,
encodedCacheKeyParts,
fn,
timeoutError
)
if (result.type === 'cached') {
const { stream: ignoredStream, pendingCacheResult } = result
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
serializedCacheKey,
pendingCacheResult
)
if (cacheHandler) {
saveToCacheHandler(
cacheHandler,
workStore,
id,
serializedCacheKey,
savedCacheResult,
rootParams
)
}
await ignoredStream.cancel()
}
}
}
}
} catch (error) {
resolvableSharedCacheResult.reject(error)
throw error
}
}
......
import { ReactNode, Suspense } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
export function generateStaticParams() {
return [
{ countryCode: 'ca', lang: 'en' },
{ countryCode: 'ca', lang: 'fr' },
]
}
import { countryCode, lang } from 'next/root-params'
import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
async function getCachedData() {
'use cache: remote'
// Simulate I/O latency so concurrent requests overlap.
await setTimeout(1000)
return {
countryCode: await countryCode(),
lang: await lang(),
random: Math.random(),
}
}
export default async function Page() {
await connection()
const result = await getCachedData()
return (
<p>
<span id="country">{result.countryCode}</span>{' '}
<span id="lang">{result.lang}</span>{' '}
<span id="random">{result.random}</span>
</p>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
useCache: true,
rootParams: true,
},
}
export default nextConfig
......@@ -285,3 +285,35 @@ describe('app-root-param-getters - cache - at build', () => {
})
}
})
describe('app-root-param-getters - cache dedup with root params', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'fixtures', 'use-cache-dedup'),
// In deploy mode, concurrent requests could hit different lambdas.
skipDeployment: true,
})
if (skipped) return
it('should dedupe same root params and isolate different root params', async () => {
// Three concurrent requests: ca/en, ca/fr, ca/fr.
const [$en, $fr1, $fr2] = await Promise.all([
next.render$('/ca/en'),
next.render$('/ca/fr'),
next.render$('/ca/fr'),
])
const randomEn = $en('#random').text()
const randomFr1 = $fr1('#random').text()
const randomFr2 = $fr2('#random').text()
expect(randomEn).toBeTruthy()
expect(randomFr1).toBeTruthy()
// ca/en and ca/fr should have different results (isolation).
expect(randomEn).not.toBe(randomFr1)
// Both ca/fr requests should have the same result (deduped).
expect(randomFr1).toBe(randomFr2)
})
})
import { cacheLife, cacheTag } from 'next/cache'
import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
async function Inner() {
'use cache'
await setTimeout(1000)
// This should lower the default cache lives of the outer cache scopes.
cacheLife({ revalidate: 180, expire: 300 })
cacheTag('inner')
return <p id="inner">{Math.random()}</p>
}
async function Outer1() {
'use cache'
cacheTag('outer1')
return <Inner />
}
async function Outer2() {
'use cache'
cacheTag('outer2')
return <Inner />
}
export default async function Page() {
await connection()
return (
<>
<Outer1 />
<Outer2 />
</>
)
}
......@@ -2,6 +2,8 @@
const defaultCacheHandler =
require('next/dist/server/lib/cache-handlers/default.external').default
const { AsyncLocalStorage } = require('node:async_hooks')
const snapshot = AsyncLocalStorage.snapshot()
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
......@@ -14,6 +16,15 @@ const cacheHandler = {
async set(cacheKey, pendingEntry) {
console.log('ModernCustomCacheHandler::set', cacheKey)
pendingEntry.then(({ revalidate, expire, tags }) => {
snapshot(() => {
console.log(
`ModernCustomCacheHandler::set-resolved-entry revalidate: ${revalidate}, expire: ${expire}, tags: ${tags}\n ${cacheKey}`
)
})
})
return defaultCacheHandler.set(cacheKey, pendingEntry)
},
......
......@@ -130,4 +130,27 @@ describe('use-cache-custom-handler', () => {
)
})
}
it('should dedupe nested caches across different outer cache scopes, and still propagate cache life/tags correctly', async () => {
await next.fetch('/nested')
await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::set-resolved-entry revalidate: 180, expire: 300, tags: inner`,
1
)
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::set-resolved-entry revalidate: 180, expire: 300, tags: outer1,inner`,
1
)
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::set-resolved-entry revalidate: 180, expire: 300, tags: outer2,inner`,
1
)
})
})
})
import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
async function getCachedRandom() {
'use cache'
// Simulate I/O latency so concurrent requests overlap.
await setTimeout(1000)
return Math.random()
}
export async function GET() {
await connection()
const rand = await getCachedRandom()
return Response.json({ rand })
}
......@@ -15,6 +15,24 @@ describe('use-cache-route-handler-only', () => {
expect(date1).toBe(date2)
})
if (!isNextDeploy) {
// In deploy mode, concurrent requests could hit different lambdas.
it('should dedupe concurrent cache invocations in route handlers', async () => {
// Restart to ensure a cold server. Without this, prior test activity
// can affect request timing enough for the concurrent requests to no
// longer overlap reliably.
await next.stop()
await next.start()
const [{ rand: first }, { rand: second }] = await Promise.all([
next.fetch('/node-dynamic').then((response) => response.json()),
next.fetch('/node-dynamic').then((response) => response.json()),
])
expect(first).toBe(second)
})
}
it('should be able to revalidate prerendered route handlers', async () => {
const response1 = await next.fetch('/node')
const { date1: date1a } = await response1.json()
......
import { cacheLife } from 'next/cache'
import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
async function getInnerData(id: string) {
'use cache'
await setTimeout(1000)
return new Date().toISOString()
}
......@@ -12,6 +15,8 @@ async function getOuterData(id: string) {
cacheLife({ revalidate: 5 })
console.log('use-cache-swr: generating outer data')
const innerData = await getInnerData('inner')
return { outer: new Date().toISOString(), inner: innerData }
......
// @ts-check
const { setTimeout } = require('timers/promises')
/**
* 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
......@@ -22,6 +24,8 @@ const cacheHandler = {
await pendingPromise
}
// Simulate some latency when fetching from a remote cache.
await setTimeout(200)
const entry = store.get(cacheKey)
if (!entry) {
console.log('PersistentCacheHandler::get', cacheKey, softTags, '-> miss')
......
......@@ -78,4 +78,37 @@ describe('use-cache-swr', () => {
// cache by its "inner" sentinel argument in the key.
expect(cliOutput).toMatch(/PersistentCacheHandler::get.*"inner".*_N_T_\//)
})
it('should dedupe SWR regens across concurrent requests', 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
// Fire multiple concurrent requests that all find the stale entry.
// Only one of them should trigger a background regen.
await Promise.all([next.fetch('/'), next.fetch('/'), next.fetch('/')])
// Wait for the background regen to complete.
await retry(() => {
const regenOutput = next.cliOutput.slice(outputIndex)
expect(regenOutput).toInclude('use-cache-swr: generating outer data')
})
const cliOutput = next.cliOutput.slice(outputIndex)
// The cache function should have been executed only once across all
// concurrent requests, not once per request.
const generationCalls = cliOutput.split('\n').filter(
(line) =>
line.includes('use-cache-swr: generating outer data') &&
// Ignore replayed logs that have a Cache badge.
!line.includes(' Cache ')
)
expect(generationCalls).toHaveLength(1)
})
})
import { connection } from 'next/server'
async function CachedWrapper({ children }: { children: React.ReactNode }) {
'use cache: remote'
return (
<div className="wrapper">
<p className="rand">{Math.random()}</p>
<p className="children">{children}</p>
</div>
)
}
export default async function Page() {
await connection()
return (
<div>
<CachedWrapper>
<span>Child A</span>
</CachedWrapper>
<CachedWrapper>
<span>Child B</span>
</CachedWrapper>
</div>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
async function Inner() {
await setTimeout(1000)
return <p className="inner">{Math.random()}</p>
}
// We're only using the id to force using a different cache key for different
// test scenarios.
async function InnerCached({ id }: { id: string; name: string }) {
'use cache: remote'
return (
<Suspense fallback={<p className="loading">Loading...</p>}>
<Inner />
</Suspense>
)
}
async function OuterCached1({ id }: { id: string; name: string }) {
'use cache: remote'
return <InnerCached id={id} name="inner" />
}
async function OuterCached2({ id }: { id: string; name: string }) {
'use cache: remote'
return <InnerCached id={id} name="inner" />
}
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
await connection()
const { id } = await params
return (
<>
<OuterCached1 id={id} name="outer1" />
<OuterCached2 id={id} name="outer2" />
</>
)
}
import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
async function PrivateCached() {
'use cache: private'
await setTimeout(1000)
return <p className="rand">{Math.random()}</p>
}
export default async function Page() {
await connection()
return (
<div>
<PrivateCached />
<PrivateCached />
</div>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
async function DelayedContent() {
await setTimeout(1000)
return <p className="content">{Math.random()}</p>
}
async function Cached() {
// We use a custom no-store cache handler here to ensure we're actually
// testing the deduping behavior in the cache wrapper, and not a pending set
// locking mechanism that the cache handler might implement (as the default
// handler does).
'use cache: no-store'
return (
<Suspense fallback={<p className="loading">Loading...</p>}>
<DelayedContent />
</Suspense>
)
}
export default async function Page() {
await connection()
return <Cached />
}
......@@ -6,6 +6,7 @@ const nextConfig = {
custom: require.resolve(
'next/dist/server/lib/cache-handlers/default.external'
),
'no-store': require.resolve('./no-store-handler.js'),
},
experimental: {
useCache: true,
......
// @ts-check
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const noStoreCacheHandler = {
async get(_cacheKey, _softTags) {
return undefined
},
async set(_cacheKey, _pendingEntry) {},
async refreshTags() {},
async getExpiration(_tags) {
return Infinity
},
async updateTags(_tags) {},
}
module.exports = noStoreCacheHandler
......@@ -30,6 +30,19 @@ describe('use-cache', () => {
return
}
let cliOutputLength: number
beforeEach(() => {
cliOutputLength = next.cliOutput.length
})
afterEach(async () => {
// eslint-disable-next-line jest/no-standalone-expect
expect(next.cliOutput.slice(cliOutputLength)).not.toContain(
'unhandledRejection'
)
})
it('should cache results', async () => {
const browser = await next.browser(`/?n=1`)
expect(await browser.waitForElementByCss('#x').text()).toBe('1')
......@@ -1489,6 +1502,103 @@ describe('use-cache', () => {
await assertNoConsoleErrors(browser)
})
it('should dedupe shared inner caches across different outer caches', async () => {
const browser = await next.browser('/nested/1')
const first = await browser.elementByCss('.inner:nth-of-type(1)').text()
const second = await browser.elementByCss('.inner:nth-of-type(2)').text()
expect(first).toBe(second)
})
if (!isNextDeploy) {
// In deploy mode, concurrent requests could hit different instances.
it('should dedupe a streaming cache across concurrent requests', async () => {
const [first, second] = await Promise.all([
next.render('/streaming'),
// Delay the second request to ensure deduping also works when the
// first request has already started streaming.
new Promise<string>((resolve) =>
setTimeout(() => resolve(next.render('/streaming')), 500)
),
])
// Both requests should contain the cached content.
expect(first).toContain('<p class="content">')
expect(second).toContain('<p class="content">')
// Both requests should get the same cached value.
const getContent = (html: string) =>
html.match(/<p class="content">([^<]+)<\/p>/)?.[1]
expect(getContent(first)).toBe(getContent(second))
// The leader streams with a loading boundary visible in the initial HTML,
// while the cross-request joiner resolves from the fully collected result
// with no loading boundary. We don't know which request is the leader,
// but exactly one should have it.
expect([first, second]).toSatisfy(function onlyOneRequestStreams([
a,
b,
]: string[]) {
return (
(a.includes('<p class="loading">') &&
!b.includes('<p class="loading">')) ||
(!a.includes('<p class="loading">') &&
b.includes('<p class="loading">'))
)
})
})
}
it('should resolve different children correctly when deduping', async () => {
const browser = await next.browser('/cached-with-children')
const childA = await browser
.elementByCss('.wrapper:first-child .children')
.text()
const childB = await browser
.elementByCss('.wrapper:last-child .children')
.text()
expect(childA).toBe('Child A')
expect(childB).toBe('Child B')
// The random value from the cache function should be the same for both
// wrappers, confirming the invocation was actually deduped.
const randA = await browser
.elementByCss('.wrapper:first-child .rand')
.text()
const randB = await browser.elementByCss('.wrapper:last-child .rand').text()
expect(randA).toBe(randB)
})
it('should dedupe private caches within a single request', async () => {
const browser = await next.browser('/private-dedup')
const first = await browser.elementByCss('.rand:nth-of-type(1)').text()
const second = await browser.elementByCss('.rand:nth-of-type(2)').text()
expect(first).toBe(second)
})
it('should not dedupe private caches across concurrent requests', async () => {
const [first$, second$] = await Promise.all([
next.render$('/private-dedup'),
next.render$('/private-dedup'),
])
const firstValue = first$('.rand').first().text()
const secondValue = second$('.rand').first().text()
// Across requests, private caches must NOT be deduped.
expect(firstValue).not.toBe(secondValue)
})
it('should stream the result of a deduped invocation', async () => {
const html = await next
.fetch('/nested/2')
.then((response) => response.text())
// The loading boundaries of both inner cache functions are expected to be
// shown while the page is loading.
expect(html).toIncludeRepeated('<p class="loading">Loading...</p>', 2)
})
})
async function getSanitizedLogs(browser: Playwright): Promise<string[]> {
......
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