Unverified Commit 9806642f authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix private-cache segment reuse across root params (#98810)

Private caches only tracked root-param reads in development. Production
runtime prefetches omitted these dependencies from their vary params
metadata, allowing the client to reuse content across different
root-param values.

This extends #98674 to `"use cache: private"`. Private caches now
collect root-param reads in production and inherit dependencies from
nested public and private caches. The existing response-level
propagation can then record those dependencies when it consumes the
cache entry.

Regression tests cover direct reads, public caches inside private
caches, and private caches inside private caches. Each case prefetches
English and German content, then verifies that navigation uses the
German result without another request.
parent 3e4af55d
...@@ -376,12 +376,9 @@ export interface PrivateUseCacheStore extends CommonUseCacheStore { ...@@ -376,12 +376,9 @@ export interface PrivateUseCacheStore extends CommonUseCacheStore {
readonly rootParams: Params readonly rootParams: Params
/** /**
* DEV-only: Tracks which root param names were read during this cache * Tracks which root param names were read during this cache invocation.
* invocation. In development, private caches are persisted (keyed by the
* request's cookies and headers), so reads of different root param values
* must produce different entries.
*/ */
readonly readRootParamNames: Set<string> | undefined readonly readRootParamNames: Set<string>
} }
export type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore export type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore
......
...@@ -102,12 +102,8 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -102,12 +102,8 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
break break
} }
case 'private-cache': { case 'private-cache': {
// In dev, private caches are persisted and keyed by root params (like workUnitStore.readRootParamNames.add(paramName)
// public caches), so we track which ones were read. return Promise.resolve(workUnitStore.rootParams[paramName])
if (workUnitStore.readRootParamNames) {
workUnitStore.readRootParamNames.add(paramName)
}
break
} }
case 'prerender-runtime': { case 'prerender-runtime': {
break break
......
...@@ -792,7 +792,7 @@ function createUseCacheStore( ...@@ -792,7 +792,7 @@ function createUseCacheStore(
outerWorkUnitStore outerWorkUnitStore
), ),
rootParams: outerWorkUnitStore.rootParams, rootParams: outerWorkUnitStore.rootParams,
readRootParamNames: process.env.__NEXT_DEV_SERVER ? new Set() : undefined, readRootParamNames: new Set<string>(),
// Every private cache scope is its own work unit. Any cache keyed on // Every private cache scope is its own work unit. Any cache keyed on
// headers() or cookies() needs to be invalidated. Otherwise some // headers() or cookies() needs to be invalidated. Otherwise some
// Next.js API semantics leak across render passes. // Next.js API semantics leak across render passes.
...@@ -981,8 +981,14 @@ function propagateCacheEntryMetadata( ...@@ -981,8 +981,14 @@ function propagateCacheEntryMetadata(
): void { ): void {
if (cacheContext.kind === 'private') { if (cacheContext.kind === 'private') {
switch (cacheContext.outerWorkUnitStore.type) { switch (cacheContext.outerWorkUnitStore.type) {
case 'prerender-runtime':
case 'private-cache': case 'private-cache':
if (metadata.readRootParamNames) {
for (const paramName of metadata.readRootParamNames) {
cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName)
}
}
// fallthrough
case 'prerender-runtime':
propagateCacheLifeAndTagsToRevalidateStore( propagateCacheLifeAndTagsToRevalidateStore(
cacheContext.outerWorkUnitStore, cacheContext.outerWorkUnitStore,
metadata metadata
...@@ -1002,11 +1008,6 @@ function propagateCacheEntryMetadata( ...@@ -1002,11 +1008,6 @@ function propagateCacheEntryMetadata(
} else { } else {
switch (cacheContext.outerWorkUnitStore.type) { switch (cacheContext.outerWorkUnitStore.type) {
case 'cache': case 'cache':
if (metadata.readRootParamNames) {
for (const paramName of metadata.readRootParamNames) {
cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName)
}
}
// If this entry's cache life is dynamic, record this invocation as the // If this entry's cache life is dynamic, record this invocation as the
// origin to use as `cause` when the outer cache surfaces the // origin to use as `cause` when the outer cache surfaces the
// nested-dynamic cache error. `??=` keeps the first occurrence so the // nested-dynamic cache error. `??=` keeps the first occurrence so the
...@@ -1021,6 +1022,12 @@ function propagateCacheEntryMetadata( ...@@ -1021,6 +1022,12 @@ function propagateCacheEntryMetadata(
} }
// fallthrough // fallthrough
case 'private-cache': case 'private-cache':
if (metadata.readRootParamNames) {
for (const paramName of metadata.readRootParamNames) {
cacheContext.outerWorkUnitStore.readRootParamNames.add(paramName)
}
}
// fallthrough
case 'prerender': case 'prerender':
case 'prerender-runtime': case 'prerender-runtime':
case 'prerender-legacy': case 'prerender-legacy':
...@@ -1065,12 +1072,11 @@ function propagateCacheEntryMetadata( ...@@ -1065,12 +1072,11 @@ function propagateCacheEntryMetadata(
* `propagateCacheEntryMetadata` is called unconditionally (after the omission * `propagateCacheEntryMetadata` is called unconditionally (after the omission
* checks have already filtered out short-lived entries). * checks have already filtered out short-lived entries).
* *
* Note: Root param names are only propagated to `readRootParamNames` when the * Nested caches propagate root param names into the enclosing cache's
* outer context is a `cache` store (i.e. an enclosing `"use cache"` function), * `readRootParamNames` set. This propagation is never deferred. Prerender
* which is never deferred. For prerender contexts, root param names are * contexts also register known root param names when they read the resume
* tracked separately via `addKnownRootParamNames` in the resume data cache * data cache. A response accumulator records the consumed entry's root vary
* read path. They're also recorded as root vary params (if tracked), so that * params to prevent segment reuse across different values.
* the client doesn't reuse the segment across different values.
*/ */
function maybePropagateCacheEntryMetadata( function maybePropagateCacheEntryMetadata(
cacheContext: CacheContext, cacheContext: CacheContext,
...@@ -1253,10 +1259,7 @@ async function collectResult( ...@@ -1253,10 +1259,7 @@ async function collectResult(
entry, entry,
hasExplicitRevalidate: innerCacheStore.explicitRevalidate !== undefined, hasExplicitRevalidate: innerCacheStore.explicitRevalidate !== undefined,
hasExplicitExpire: innerCacheStore.explicitExpire !== undefined, hasExplicitExpire: innerCacheStore.explicitExpire !== undefined,
readRootParamNames: readRootParamNames: innerCacheStore.readRootParamNames,
innerCacheStore.type === 'cache' || isPrivateCacheInDev
? innerCacheStore.readRootParamNames
: undefined,
// The store accumulates this from nested public caches that propagated a // The store accumulates this from nested public caches that propagated a
// dynamic life into us. // dynamic life into us.
dynamicNestedCacheError: dynamicNestedCacheError:
......
import { cacheLife } from 'next/cache'
import { locale } from 'next/root-params'
import { Suspense } from 'react'
export const prefetch = 'partial'
export default function Page() {
return (
<Suspense fallback="Loading locale...">
<PrivateContent />
</Suspense>
)
}
async function PrivateContent() {
'use cache: private'
cacheLife({ stale: 60 })
return <div id="private-root-param">{`Locale: ${await locale()}`}</div>
}
export function generateStaticParams() {
return [{ locale: 'en' }, { locale: 'de' }]
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
export default function Page() {
return (
<ul>
{['direct', 'public-child', 'private-child'].map((route) => (
<li key={route}>
<LinkAccordion
href={`/private-cached-root-params/en/${route}`}
prefetch
/>
<LinkAccordion
href={`/private-cached-root-params/de/${route}`}
prefetch
/>
</li>
))}
</ul>
)
}
import { cacheLife } from 'next/cache'
import { locale } from 'next/root-params'
import { Suspense } from 'react'
export const prefetch = 'partial'
export default function Page() {
return (
<Suspense fallback="Loading locale...">
<PrivateContent />
</Suspense>
)
}
async function PrivateContent() {
'use cache: private'
cacheLife({ stale: 60 })
return <div id="private-root-param">{`Locale: ${await getLocale()}`}</div>
}
async function getLocale() {
'use cache: private'
return locale()
}
import { cacheLife } from 'next/cache'
import { locale } from 'next/root-params'
import { Suspense } from 'react'
export const prefetch = 'partial'
export default function Page() {
return (
<Suspense fallback="Loading locale...">
<PrivateContent />
</Suspense>
)
}
async function PrivateContent() {
'use cache: private'
cacheLife({ stale: 60 })
return <div id="private-root-param">{`Locale: ${await getLocale()}`}</div>
}
async function getLocale() {
'use cache'
return locale()
}
...@@ -848,4 +848,44 @@ describe('segment cache - vary params', () => { ...@@ -848,4 +848,44 @@ describe('segment cache - vary params', () => {
'Locale: de' 'Locale: de'
) )
}) })
it.each(['direct', 'public-child', 'private-child'])(
'tracks root params in private caches (%s)',
async (route) => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/private-cached-root-params/en', {
beforePageLoad(page: Playwright.Page) {
act = createRouterAct(page)
},
})
const englishPath = `/private-cached-root-params/en/${route}`
const germanPath = `/private-cached-root-params/de/${route}`
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${englishPath}"]`)
.click()
},
{ includes: 'Locale: en' }
)
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${germanPath}"]`)
.click()
},
{ includes: 'Locale: de' }
)
await act(async () => {
await browser.elementByCss(`a[href="${germanPath}"]`).click()
}, 'no-requests')
expect(await browser.elementById('private-root-param').text()).toBe(
'Locale: de'
)
}
)
}) })
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