Unverified Commit 8c661813 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Consolidate Resume Data Caches and partially revert #88556 (#94194)

This consolidates the two Resume Data Caches into a single discriminated
union and reverts three non-load-bearing changes from #88556. The result
sets up a follow-up that fixes a bug where pages exporting
`unstable_instant = false` cause their `'use cache'` reads to be
incorrectly treated as dynamic.

The cache wrapper short-circuits a `'use cache'` miss to a dynamic hole
when prerendering a fallback shell that was seeded with a read-only RDC
from an earlier phase. The reasoning is that the seed was filled by a
phase-1 prerender of a more-specific sibling route, so a miss in phase-2
means the cache key depends on a fallback param. In PR #79743, we set up
an XOR on the work unit store that directly encoded this distinction: a
prerender carried either a mutable `PrerenderResumeDataCache` (a phase-1
prerender filling caches as it runs) or an immutable
`RenderResumeDataCache` (a phase-2 fallback shell reading from a
phase-1-seeded cache), never both. The bail-out didn't use that signal
directly, though; it was gated on `workUnitStore.allowEmptyStaticShell`,
which at the time happened to coincide with "we have a read-only seed"
because the fallback-shell flow was the only thing setting it. #89077
later widened that flag to also cover `unstable_instant = false`, which
has no seed, so the bail-out started firing for routes that should be
allowed to fill their caches normally. #88556 broke the XOR by carrying
both caches at the same time. In a follow-up, the flag check is replaced
with a precise `workUnitStore.resumeDataCache?.mutable === false`, which
only lands cleanly once the XOR is back.

The three reverts: (1) at the start of the Cache Components branch of
`prerenderToStream`, phase-2 no longer creates a fresh mutable RDC
alongside the prefilled one — it just uses the seed; (2) the swap
between the prospective and final prerender passes that replaced the
prefilled RDC with a freeze of the (now-gone) mutable one is removed, so
the final pass reads from the same seed as the prospective pass; (3) the
line in the cache wrapper that mirrored prefilled-RDC hits into the
mutable RDC (only useful to feed the swap) is removed. The actual fix
from #88556 — selecting the seed RDC by matching known params,
`buildRDCCacheByPage` in `export/index.ts` — is kept, and the
`ppr-root-param-fallback` test suite that was added in that PR still
passes.

On top of the revert, the two RDC types now carry a `mutable: true |
false` discriminator, the store fields collapse into one
`resumeDataCache: ResumeDataCache | null`, and the specialized
`getPrerenderResumeDataCache` / `getRenderResumeDataCache` helpers are
replaced by a single `getResumeDataCache` returning the union. Call
sites narrow via `resumeDataCache?.mutable` directly, and the typing-lie
in the old `getRenderResumeDataCache` (coercing a mutable cache to
read-only via spread) is gone. Restoring the XOR as two separate fields
would have worked, but the discriminated union makes the invariant
compiler-enforced and removes a typing-lie that the original design
already carried — and the revert touches the same call sites anyway, so
bundling the refactor in one pass was cleaner than splitting it.
parent 0a355571
......@@ -1285,5 +1285,6 @@
"1284": "Cache Components error recovery expected an original prerender resume data cache",
"1285": "Cache Components error recovery expected an original prerender store",
"1286": "Cache Components error recovery unexpectedly produced a dynamic HTML hole",
"1287": "Expected stream state to be initialized before reading"
"1287": "Expected stream state to be initialized before reading",
"1288": "Cache Components error recovery expected an original resume data cache"
}
......@@ -20,8 +20,7 @@ import {
} from './manifests-singleton'
import {
getCacheSignal,
getPrerenderResumeDataCache,
getRenderResumeDataCache,
getResumeDataCache,
workUnitAsyncStorage,
} from './work-unit-async-storage.external'
import { createHangingInputAbortSignal } from './dynamic-rendering'
......@@ -153,11 +152,8 @@ export const encryptActionBoundArgs = React.cache(
})
}
const prerenderResumeDataCache = workUnitStore
? getPrerenderResumeDataCache(workUnitStore)
: null
const renderResumeDataCache = workUnitStore
? getRenderResumeDataCache(workUnitStore)
const resumeDataCache = workUnitStore
? getResumeDataCache(workUnitStore)
: null
// Using Flight to serialize the args into a string.
......@@ -176,8 +172,7 @@ export const encryptActionBoundArgs = React.cache(
// but React ignores those as long as no debug channel is passed on the decode side, so it's fine:
// https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L1711-L1729
// https://github.com/facebook/react/blob/bb8a76c6cc77ea2976d690ea09f5a1b3d9b1792a/packages/react-client/src/ReactFlightClient.js#L4005-L4025
process.env.NODE_ENV === 'development' &&
(prerenderResumeDataCache || renderResumeDataCache)
process.env.NODE_ENV === 'development' && resumeDataCache
? {
writable: new WritableStream(),
}
......@@ -227,9 +222,7 @@ export const encryptActionBoundArgs = React.cache(
const cacheKey = actionId + serialized
const cachedEncrypted =
prerenderResumeDataCache?.encryptedBoundArgs.get(cacheKey) ??
renderResumeDataCache?.encryptedBoundArgs.get(cacheKey)
const cachedEncrypted = resumeDataCache?.encryptedBoundArgs.get(cacheKey)
if (cachedEncrypted) {
return cachedEncrypted
......@@ -238,7 +231,9 @@ export const encryptActionBoundArgs = React.cache(
const encrypted = await encodeActionBoundArg(actionId, serialized)
endReadIfStarted()
prerenderResumeDataCache?.encryptedBoundArgs.set(cacheKey, encrypted)
if (resumeDataCache?.mutable) {
resumeDataCache.encryptedBoundArgs.set(cacheKey, encrypted)
}
return encrypted
}
......@@ -256,18 +251,17 @@ export async function decryptActionBoundArgs(
if (workUnitStore) {
const cacheSignal = getCacheSignal(workUnitStore)
const prerenderResumeDataCache = getPrerenderResumeDataCache(workUnitStore)
const renderResumeDataCache = getRenderResumeDataCache(workUnitStore)
const resumeDataCache = getResumeDataCache(workUnitStore)
decrypted =
prerenderResumeDataCache?.decryptedBoundArgs.get(encrypted) ??
renderResumeDataCache?.decryptedBoundArgs.get(encrypted)
decrypted = resumeDataCache?.decryptedBoundArgs.get(encrypted)
if (!decrypted) {
cacheSignal?.beginRead()
decrypted = await decodeActionBoundArg(actionId, encrypted)
cacheSignal?.endRead()
prerenderResumeDataCache?.decryptedBoundArgs.set(encrypted, decrypted)
if (resumeDataCache?.mutable) {
resumeDataCache.decryptedBoundArgs.set(encrypted, decrypted)
}
}
} else {
decrypted = await decodeActionBoundArg(actionId, encrypted)
......
......@@ -77,6 +77,7 @@ describe('getDynamicHTMLPostponedState', () => {
"decryptedBoundArgs": Map {},
"encryptedBoundArgs": Map {},
"fetch": Map {},
"mutable": false,
},
"type": 2,
}
......@@ -124,6 +125,7 @@ describe('getDynamicHTMLPostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
mutable: false,
},
})
......@@ -159,6 +161,7 @@ describe('parsePostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
mutable: false,
},
})
......@@ -180,6 +183,7 @@ describe('parsePostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
mutable: false,
},
})
})
......@@ -196,6 +200,7 @@ describe('parsePostponedState', () => {
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
mutable: false,
},
})
})
......
......@@ -208,7 +208,9 @@ export function parsePostponedState(
console.error('Failed to parse postponed state', err)
return {
type: DynamicState.DATA,
renderResumeDataCache: createPrerenderResumeDataCache(),
renderResumeDataCache: createRenderResumeDataCache(
createPrerenderResumeDataCache()
),
}
}
}
......
......@@ -12,8 +12,8 @@ import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
import type { ServerComponentsHmrCache } from '../response-cache'
import type {
RenderResumeDataCache,
PrerenderResumeDataCache,
ResumeDataCache,
} from '../resume-data-cache/resume-data-cache'
import type { Params } from '../request/params'
import type { ImplicitTags } from '../lib/implicit-tags'
......@@ -66,15 +66,17 @@ export interface RequestStore extends CommonWorkUnitStore {
readonly rootParams: Params
/**
* The resume data cache for this request. This will be a immutable cache.
* The resume data cache for this request. Either a mutable
* `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or
* an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed
* state). Narrow via `resumeDataCache.mutable` to tell them apart.
*/
renderResumeDataCache: RenderResumeDataCache | null
resumeDataCache: ResumeDataCache | null
stale?: number
stagedRendering?: StagedRenderingController | null
asyncApiPromises?: AsyncApiPromises
cacheSignal?: CacheSignal | null
prerenderResumeDataCache?: PrerenderResumeDataCache | null
fallbackParams?: OpaqueFallbackRouteParams | null
varyParamsAccumulator?: ResponseVaryParamsAccumulator | null
......@@ -252,17 +254,14 @@ interface PrerenderStoreModernCommon
readonly rootParams: Params
/**
* A mutable resume data cache for this prerender.
* The resume data cache for this prerender. Either a mutable
* `PrerenderResumeDataCache` that fills as this prerender runs, or an
* immutable `RenderResumeDataCache` provided by an earlier phase when the
* prerender is supposed to read from prefilled caches only (e.g. when
* prerendering an optional fallback shell). Narrow via
* `resumeDataCache.mutable` to tell them apart.
*/
prerenderResumeDataCache: PrerenderResumeDataCache | null
/**
* An immutable resume data cache for this prerender. This may be provided
* instead of the `prerenderResumeDataCache` if the prerender is not supposed
* to fill caches, and only read from prefilled caches, e.g. when prerendering
* an optional fallback shell.
*/
renderResumeDataCache: RenderResumeDataCache | null
resumeDataCache: ResumeDataCache | null
/**
* The HMR refresh hash is only provided in dev mode. It is needed for the dev
......@@ -309,9 +308,9 @@ export interface PrerenderStorePPR
readonly fallbackRouteParams: OpaqueFallbackRouteParams | null
/**
* The resume data cache for this prerender.
* The resume data cache for this prerender. Always mutable in PPR mode.
*/
prerenderResumeDataCache: PrerenderResumeDataCache
resumeDataCache: PrerenderResumeDataCache
}
export interface PrerenderStoreLegacy
......@@ -442,56 +441,22 @@ export function throwInvariantForMissingStore(): never {
throw new InvariantError('Expected workUnitAsyncStorage to have a store.')
}
export function getPrerenderResumeDataCache(
workUnitStore: WorkUnitStore
): PrerenderResumeDataCache | null {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
return workUnitStore.prerenderResumeDataCache
case 'prerender-client':
case 'validation-client':
// TODO eliminate fetch caching in client scope and stop exposing this data
// cache during SSR.
return workUnitStore.prerenderResumeDataCache
case 'request': {
// In dev, we might fill caches even during a dynamic request.
if (workUnitStore.prerenderResumeDataCache) {
return workUnitStore.prerenderResumeDataCache
}
// fallthrough
}
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
return null
default:
return workUnitStore satisfies never
}
}
export function getRenderResumeDataCache(
/**
* Returns the resume data cache for the given work unit store, regardless of
* whether it is mutable (`PrerenderResumeDataCache`) or read-only
* (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.
*/
export function getResumeDataCache(
workUnitStore: WorkUnitStore
): RenderResumeDataCache | null {
): ResumeDataCache | null {
switch (workUnitStore.type) {
case 'request':
case 'prerender':
case 'prerender-runtime':
case 'prerender-client':
case 'validation-client':
if (workUnitStore.renderResumeDataCache) {
// If we are in a prerender, we might have a render resume data cache
// that is used to read from prefilled caches.
return workUnitStore.renderResumeDataCache
}
// fallthrough
case 'prerender-ppr':
// Otherwise we return the mutable resume data cache here as an immutable
// version of the cache as it can also be used for reading.
return workUnitStore.prerenderResumeDataCache ?? null
return workUnitStore.resumeDataCache
case 'cache':
case 'private-cache':
case 'unstable-cache':
......
......@@ -21,7 +21,7 @@ import { ResponseCookies, RequestCookies } from '../web/spec-extension/cookies'
import { DraftModeProvider } from './draft-mode-provider'
import { splitCookiesString } from '../web/utils'
import type { ServerComponentsHmrCache } from '../response-cache'
import type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { Params } from '../request/params'
import type { ImplicitTags } from '../lib/implicit-tags'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
......@@ -102,7 +102,7 @@ export type RequestStoreInputs = {
url: { pathname: string; search?: string }
rootParams: Params
implicitTags: ImplicitTags
renderResumeDataCache: RenderResumeDataCache | null
resumeDataCache: ResumeDataCache | null
previewProps: WrapperRenderOpts['previewProps']
isHmrRefresh: boolean | undefined
serverComponentsHmrCache: ServerComponentsHmrCache | undefined
......@@ -152,7 +152,7 @@ export function createRequestStoreForRender(
previewProps: WrapperRenderOpts['previewProps'],
isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
renderResumeDataCache: RenderResumeDataCache | null,
resumeDataCache: ResumeDataCache | null,
fallbackParams: OpaqueFallbackRouteParams | null
): RequestStore {
return createRequestStore({
......@@ -169,7 +169,7 @@ export function createRequestStoreForRender(
url,
rootParams,
implicitTags,
renderResumeDataCache,
resumeDataCache,
previewProps,
isHmrRefresh,
serverComponentsHmrCache,
......@@ -192,7 +192,7 @@ export function createRequestStoreForAPI(
url,
rootParams: {},
implicitTags,
renderResumeDataCache: null,
resumeDataCache: null,
previewProps,
isHmrRefresh: false,
serverComponentsHmrCache: undefined,
......@@ -215,7 +215,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
url,
rootParams,
implicitTags,
renderResumeDataCache,
resumeDataCache,
previewProps,
isHmrRefresh,
serverComponentsHmrCache,
......@@ -296,7 +296,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
return cache.draftMode
},
renderResumeDataCache: renderResumeDataCache ?? null,
resumeDataCache: resumeDataCache ?? null,
isHmrRefresh,
serverComponentsHmrCache:
serverComponentsHmrCache ||
......
......@@ -159,7 +159,7 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> {
url: { pathname: msg.request.urlPathname, search: msg.request.urlSearch },
rootParams: msg.request.rootParams,
implicitTags: { tags: [], expirationsByCacheKind: new Map() },
renderResumeDataCache: null,
resumeDataCache: null,
previewProps: undefined,
isHmrRefresh: msg.request.isHmrRefresh,
serverComponentsHmrCache: undefined,
......
......@@ -26,8 +26,7 @@ import {
import { toRoute } from '../to-route'
import { SharedCacheControls } from './shared-cache-controls.external'
import {
getPrerenderResumeDataCache,
getRenderResumeDataCache,
getResumeDataCache,
workUnitAsyncStorage,
} from '../../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../../shared/lib/invariant-error'
......@@ -436,7 +435,7 @@ export class IncrementalCache implements IncrementalCacheType {
if (ctx.kind === IncrementalCacheKind.FETCH) {
const workUnitStore = workUnitAsyncStorage.getStore()
const resumeDataCache = workUnitStore
? getRenderResumeDataCache(workUnitStore)
? getResumeDataCache(workUnitStore)
: null
if (resumeDataCache) {
const memoryCacheData = resumeDataCache.fetch.get(cacheKey)
......@@ -532,14 +531,13 @@ export class IncrementalCache implements IncrementalCacheType {
// and it won't have to reach into the fetch cache implementation.
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
const prerenderResumeDataCache =
getPrerenderResumeDataCache(workUnitStore)
if (prerenderResumeDataCache) {
const resumeDataCache = getResumeDataCache(workUnitStore)
if (resumeDataCache?.mutable) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:set', cacheKey)
}
prerenderResumeDataCache.fetch.set(cacheKey, cacheData.value)
resumeDataCache.fetch.set(cacheKey, cacheData.value)
}
}
......@@ -682,15 +680,15 @@ export class IncrementalCache implements IncrementalCacheType {
// debug info to have the right environment associated to it.
if (data?.kind === CachedRouteKind.FETCH) {
const workUnitStore = workUnitAsyncStorage.getStore()
const prerenderResumeDataCache = workUnitStore
? getPrerenderResumeDataCache(workUnitStore)
const resumeDataCache = workUnitStore
? getResumeDataCache(workUnitStore)
: null
if (prerenderResumeDataCache) {
if (resumeDataCache?.mutable) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:set', pathname)
}
prerenderResumeDataCache.fetch.set(pathname, data)
resumeDataCache.fetch.set(pathname, data)
}
}
......
......@@ -14,6 +14,14 @@ import {
* This cache is read-only and cannot be modified once created.
*/
export interface RenderResumeDataCache {
/**
* Discriminator. `false` means this cache is read-only and cannot be filled
* with new entries. Used by `ResumeDataCache` consumers to narrow the union
* via standard discriminated-union narrowing (e.g. `if
* (resumeDataCache.mutable)`).
*/
readonly mutable: false
/**
* A read-only Map store for values cached by the 'use cache' React hook.
* The 'set' operation is omitted to enforce immutability.
......@@ -56,6 +64,14 @@ export interface RenderResumeDataCache {
* This cache allows both reading and writing of cached values.
*/
export interface PrerenderResumeDataCache {
/**
* Discriminator. `true` means this cache is mutable and can be filled with
* new entries during this prerender. Used by `ResumeDataCache` consumers to
* narrow the union via standard discriminated-union narrowing (e.g.
* `if (resumeDataCache.mutable)`).
*/
readonly mutable: true
/**
* A mutable Map store for values cached by the 'use cache' React hook.
* Supports both 'get' and 'set' operations to build the cache during
......@@ -100,6 +116,13 @@ export interface PrerenderResumeDataCache {
readonly dynamicCacheKeys: Set<string>
}
/**
* Discriminated union of the two resume data cache flavors. Consumers should
* narrow via `resumeDataCache.mutable` to access the mutable Map API (only
* available on `PrerenderResumeDataCache`).
*/
export type ResumeDataCache = RenderResumeDataCache | PrerenderResumeDataCache
type ResumeStoreSerialized = {
store: {
cache: {
......@@ -124,7 +147,7 @@ type ResumeStoreSerialized = {
* 'null' if empty
*/
export async function stringifyResumeDataCache(
resumeDataCache: RenderResumeDataCache | PrerenderResumeDataCache,
resumeDataCache: ResumeDataCache,
isCacheComponentsEnabled: boolean
): Promise<string> {
if (process.env.NEXT_RUNTIME === 'edge') {
......@@ -172,10 +195,11 @@ export async function stringifyResumeDataCache(
* @returns A new empty PrerenderResumeDataCache instance
*/
export function createPrerenderResumeDataCache(
source?: PrerenderResumeDataCache | RenderResumeDataCache
source?: ResumeDataCache
): PrerenderResumeDataCache {
if (source) {
return {
mutable: true,
cache: new Map(source.cache),
fetch: new Map(source.fetch),
encryptedBoundArgs: new Map(source.encryptedBoundArgs),
......@@ -186,6 +210,7 @@ export function createPrerenderResumeDataCache(
}
} else {
return {
mutable: true,
cache: new Map(),
fetch: new Map(),
encryptedBoundArgs: new Map(),
......@@ -207,20 +232,14 @@ export function createPrerenderResumeDataCache(
* @returns An immutable RenderResumeDataCache instance
*/
export function createRenderResumeDataCache(
renderResumeDataCache: RenderResumeDataCache
): RenderResumeDataCache
export function createRenderResumeDataCache(
prerenderResumeDataCache: PrerenderResumeDataCache
resumeDataCache: ResumeDataCache
): RenderResumeDataCache
export function createRenderResumeDataCache(
persistedCache: string,
maxPostponedStateSizeBytes: number | undefined
): RenderResumeDataCache
export function createRenderResumeDataCache(
resumeDataCacheOrPersistedCache:
| RenderResumeDataCache
| PrerenderResumeDataCache
| string,
resumeDataCacheOrPersistedCache: ResumeDataCache | string,
maxPostponedStateSizeBytes?: number | undefined
): RenderResumeDataCache {
if (process.env.NEXT_RUNTIME === 'edge') {
......@@ -229,13 +248,19 @@ export function createRenderResumeDataCache(
)
} else {
if (typeof resumeDataCacheOrPersistedCache !== 'string') {
// If the cache is already a prerender or render cache, we can return it
// directly. For the former, we're just performing a type change.
return resumeDataCacheOrPersistedCache
// If the cache is already read-only, return it directly. Otherwise we
// perform a type change by overriding the discriminator — the underlying
// Map references are still shared, but callers should treat the result
// as immutable.
if (!resumeDataCacheOrPersistedCache.mutable) {
return resumeDataCacheOrPersistedCache
}
return { ...resumeDataCacheOrPersistedCache, mutable: false }
}
if (resumeDataCacheOrPersistedCache === 'null') {
return {
mutable: false,
cache: new Map(),
fetch: new Map(),
encryptedBoundArgs: new Map(),
......@@ -276,6 +301,7 @@ export function createRenderResumeDataCache(
}
return {
mutable: false,
cache: parseUseCacheCacheStore(Object.entries(json.store.cache)),
fetch: new Map(Object.entries(json.store.fetch)),
encryptedBoundArgs: new Map(
......
......@@ -496,10 +496,6 @@ export class AppRouteRouteModule extends RouteModule<
// can be retrieved during the final prerender within microtasks. This
// is crucial when doing revalidations of a deployed route handler,
// where the default cache handler does not do any in-memory caching.
// We should replace the `prerenderResumeDataCache` and
// `renderResumeDataCache` with a single `dataCache` property that is
// conceptually not tied to resuming, and also avoids the unnecessary
// complexity of using a mutable and an immutable resume data cache.
const prerenderResumeDataCache = createPrerenderResumeDataCache()
const prospectiveRoutePrerenderStore: PrerenderStore =
......@@ -522,8 +518,7 @@ export class AppRouteRouteModule extends RouteModule<
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache: null,
resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined,
varyParamsAccumulator: null,
})
......@@ -619,8 +614,7 @@ export class AppRouteRouteModule extends RouteModule<
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache: null,
resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined,
varyParamsAccumulator: null,
})
......
......@@ -28,8 +28,7 @@ import type {
} from '../app-render/work-unit-async-storage.external'
import {
getHmrRefreshHash,
getRenderResumeDataCache,
getPrerenderResumeDataCache,
getResumeDataCache,
workUnitAsyncStorage,
getDraftModeProviderForCacheScope,
getCacheSignal,
......@@ -74,7 +73,7 @@ import {
type SearchParams,
} from '../request/search-params'
import type { Params } from '../request/params'
import type { PrerenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { ResumeDataCache } from '../resume-data-cache/resume-data-cache'
import { createLazyResult, isResolvedLazyResult } from '../lib/lazy-result'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
import type { CacheLife } from './cache-life'
......@@ -333,11 +332,11 @@ function computeRootParamsCacheKeySuffix(
}
function saveToResumeDataCache(
prerenderResumeDataCache: PrerenderResumeDataCache | null,
resumeDataCache: ResumeDataCache | null,
serializedCacheKey: string,
pendingCacheResult: Promise<CollectedCacheResult>
): Promise<CollectedCacheResult> {
if (!prerenderResumeDataCache) {
if (!resumeDataCache?.mutable) {
return pendingCacheResult
}
......@@ -348,7 +347,7 @@ function saveToResumeDataCache(
// The RDC is per-page and root params are fixed within a page, so we always
// 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)
resumeDataCache.cache.set(serializedCacheKey, rdcResult)
debug?.('Resume Data Cache entry saved', serializedCacheKey)
return savedCacheResult
......@@ -373,11 +372,11 @@ function saveToResumeDataCache(
function saveSharedCacheEntryToResumeDataCache(
serializedCacheKey: string,
sharedCacheEntry: SharedCacheEntry,
prerenderResumeDataCache: PrerenderResumeDataCache | null
resumeDataCache: ResumeDataCache | null
): void {
if (
!prerenderResumeDataCache ||
prerenderResumeDataCache.cache.has(serializedCacheKey)
!resumeDataCache?.mutable ||
resumeDataCache.cache.has(serializedCacheKey)
) {
return
}
......@@ -398,7 +397,7 @@ function saveSharedCacheEntryToResumeDataCache(
dynamicNestedCacheError: metadata.dynamicNestedCacheError,
}))
prerenderResumeDataCache.cache.set(serializedCacheKey, rdcResult)
resumeDataCache.cache.set(serializedCacheKey, rdcResult)
debug?.('Resume Data Cache entry saved by joiner', serializedCacheKey)
}
......@@ -1982,18 +1981,16 @@ export async function cache(
let stream: undefined | ReadableStream = undefined
// Get an immutable and mutable versions of the resume data cache.
const prerenderResumeDataCache = getPrerenderResumeDataCache(workUnitStore)
const renderResumeDataCache = getRenderResumeDataCache(workUnitStore)
const resumeDataCache = getResumeDataCache(workUnitStore)
const implicitTags = workUnitStore.implicitTags?.tags ?? []
if (renderResumeDataCache) {
if (resumeDataCache) {
// If this cache key was already determined to be dynamic during the
// prospective prerender (e.g. because it accessed fallback params), we
// return a hanging promise early to avoid trying to regenerate the entry,
// which would be aborted anyway.
if (renderResumeDataCache.dynamicCacheKeys?.has(serializedCacheKey)) {
if (resumeDataCache.dynamicCacheKeys?.has(serializedCacheKey)) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
......@@ -2020,7 +2017,7 @@ export async function cache(
if (cacheSignal) {
cacheSignal.beginRead()
}
const rdcEntry = renderResumeDataCache.cache.get(serializedCacheKey)
const rdcEntry = resumeDataCache.cache.get(serializedCacheKey)
if (rdcEntry !== undefined) {
let rdcResult: CollectedCacheResult | undefined = await rdcEntry
......@@ -2209,10 +2206,6 @@ export async function cache(
if (rdcResult !== undefined) {
debug?.('Resume Data Cache entry found', serializedCacheKey)
if (prerenderResumeDataCache) {
prerenderResumeDataCache.cache.set(serializedCacheKey, rdcEntry)
}
if (
rdcResult.readRootParamNames &&
rdcResult.readRootParamNames.size > 0
......@@ -2277,8 +2270,8 @@ export async function cache(
// an async function, before being passed into the "use cache"
// function, which escapes the instrumentation.
if (workUnitStore.allowEmptyStaticShell) {
if (prerenderResumeDataCache) {
prerenderResumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
if (resumeDataCache?.mutable) {
resumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
}
return makeHangingPromise(
workUnitStore.renderSignal,
......@@ -2360,7 +2353,7 @@ export async function cache(
saveSharedCacheEntryToResumeDataCache(
serializedCacheKey,
sharedCacheResult.entry,
prerenderResumeDataCache
resumeDataCache
)
// End the cache signal read when the result is fully collected, not when
......@@ -2465,7 +2458,7 @@ export async function cache(
saveSharedCacheEntryToResumeDataCache(
serializedCacheKey,
sharedCacheResult.entry,
prerenderResumeDataCache
resumeDataCache
)
// Resolve for intra-request joiners in this request. They get
......@@ -2500,8 +2493,8 @@ export async function cache(
'cross-request invocation is prerender-dynamic',
cacheHandlerKey
)
if (prerenderResumeDataCache) {
prerenderResumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
if (resumeDataCache?.mutable) {
resumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
}
cacheSignal?.endRead()
resolvableSharedCacheResult.resolve(sharedCacheResult)
......@@ -2723,8 +2716,8 @@ export async function cache(
'leader resolved as prerender-dynamic (generation)',
cacheHandlerKey
)
if (prerenderResumeDataCache) {
prerenderResumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
if (resumeDataCache?.mutable) {
resumeDataCache.dynamicCacheKeys.add(serializedCacheKey)
}
resolvableSharedCacheResult.resolve(result)
return result.hangingPromise
......@@ -2735,7 +2728,7 @@ export async function cache(
// When draft mode is enabled, we must not save the cache entry.
if (!workStore.isDraftMode) {
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
resumeDataCache,
serializedCacheKey,
pendingCacheResult
)
......@@ -2809,9 +2802,9 @@ export async function cache(
// We want to return this stream, even if it's stale.
stream = entry.value
// If we have a resume data cache, we need to clone the entry and add
// it to the resume data cache.
if (prerenderResumeDataCache) {
// If we have a mutable resume data cache, we need to clone the entry
// and add it to the resume data cache.
if (resumeDataCache?.mutable) {
const [entryLeft, entryRight] = cloneCacheEntry(entry)
if (cacheSignal) {
stream = createTrackedReadableStream(entryLeft.value, cacheSignal)
......@@ -2821,7 +2814,7 @@ export async function cache(
// 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(
resumeDataCache.cache.set(
serializedCacheKey,
Promise.resolve({
entry: entryRight,
......@@ -2875,7 +2868,7 @@ export async function cache(
const { stream: ignoredStream, pendingCacheResult } = result
const savedCacheResult = saveToResumeDataCache(
prerenderResumeDataCache,
resumeDataCache,
serializedCacheKey,
pendingCacheResult
)
......
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