Unverified Commit 2d895935 authored by Josh Story's avatar Josh Story Committed by GitHub

Keep cached root parameters out of generic fallback shells (#98950)

## Summary

Replace #98892 with a fix for both ways root-dependent content can enter
a generic fallback shell: reusing an existing Resume Data Cache entry
and executing a fresh cache fill.

For example, cached English content produced for `/en/items/one` remains
reusable in `/en/items/[slug]`, but must be absent from
`/[lang]/items/[slug]`. When reusing that concrete prerender as a seed,
clone its cache map and replace entries whose recorded
`readRootParamNames` intersect the unknown roots with omission markers.
The original seed is unchanged.

Keep those markers in the cache map itself, not a separate collection
that must stay synchronized. They carry the reason for a hole between
prerender passes and are never serialized into the persisted RDC.
Preserve canary's distinction between URL data and session data when
computing shell and prefetch hints.

For fresh fills, an unknown root read suspends the entire cache
invocation, including cached components with an internal Suspense
boundary. Affected nested caches use independently cancellable
prerenders. Dependencies propagate through consumers without cancelling
independent sibling fills or saving aborted partial results.

A top-level caller joining a nested cache fill must also record the
omission marker: the nested leader has no RDC of its own. Otherwise the
final prerender sees an unexplained miss and loses the fallback's
prefetch hint. This applies to intra-request joins as well as
cross-request joins.

This is prerequisite work for configurable root fallbacks in #97393.
Without the new API, ordinary misses for root parameters still block.
The prerequisite fixture inspects ordinary build artifacts and document
requests; the API fixtures exercise fresh fills through real fallback
requests and tag invalidation. Neither uses forced rendering or
shell-debugging hooks.

## Verification

- Prerequisite root-cache fixture: five production tests pass with both
Webpack and freshly built Turbopack.
- API root-cache isolation and root-parameter fixtures: eleven
production tests pass with each bundler. Fourteen closed-route
revalidation tests also pass with Webpack after restacking.
- The new nested-leader/top-level-join regression fails without the
marker write with the reported unexpected-cache-miss warning, and passes
with the write. Data-service barriers determine the ordering; no timing
sleeps or framework test hooks are used.
- Existing runtime prerender cache-warming coverage: eight Webpack tests
pass, including cached pages that await params/searchParams.
- The three focused unit suites pass together: 114 tests on this
prerequisite and 128 on the API layer, with four snapshots each. The
postponed-state assertion no longer snapshots Node's incidental
async-hooks fields on promises.
- Full workspace/native builds and package/repository type checks pass.
- Deployment tests were not run locally for this update.

<!-- NEXT_JS_LLM -->
parent ec0abf41
...@@ -32,6 +32,7 @@ import type { NextParsedUrlQuery } from '../request-meta' ...@@ -32,6 +32,7 @@ import type { NextParsedUrlQuery } from '../request-meta'
import { getTurbopackChunkGroupBootstrap } from '../get-page-files' import { getTurbopackChunkGroupBootstrap } from '../get-page-files'
import { UNDERSCORE_NOT_FOUND_ROUTE_ENTRY } from '../../shared/lib/entry-constants' import { UNDERSCORE_NOT_FOUND_ROUTE_ENTRY } from '../../shared/lib/entry-constants'
import type { LoaderTree } from '../lib/app-dir-module' import type { LoaderTree } from '../lib/app-dir-module'
import { MIN_PRERENDERABLE_EXPIRE } from '../use-cache/constants'
import type { AppPageModule } from '../route-modules/app-page/module' import type { AppPageModule } from '../route-modules/app-page/module'
import type { BaseNextRequest, BaseNextResponse } from '../base-http' import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { IncomingHttpHeaders } from 'http' import type { IncomingHttpHeaders } from 'http'
...@@ -279,6 +280,11 @@ import { ...@@ -279,6 +280,11 @@ import {
type RenderResumeDataCache, type RenderResumeDataCache,
type ResumeDataCache, type ResumeDataCache,
} from '../resume-data-cache/resume-data-cache' } from '../resume-data-cache/resume-data-cache'
import {
FALLBACK_PARAMS,
RUNTIME_DATA,
SESSION_DATA,
} from '../resume-data-cache/cache-store'
import type { MetadataErrorType } from '../../lib/metadata/resolve-metadata' import type { MetadataErrorType } from '../../lib/metadata/resolve-metadata'
import isError from '../../lib/is-error' import isError from '../../lib/is-error'
import { createServerInsertedMetadata } from './metadata-insertion/create-server-inserted-metadata' import { createServerInsertedMetadata } from './metadata-insertion/create-server-inserted-metadata'
...@@ -8958,8 +8964,51 @@ async function prerenderToStream( ...@@ -8958,8 +8964,51 @@ async function prerenderToStream(
// when prerendering an optional fallback shell after having prerendered // when prerendering an optional fallback shell after having prerendered
// pages with defined params, we use this instead of a mutable prerender // pages with defined params, we use this instead of a mutable prerender
// resume data cache. // resume data cache.
const resumeDataCache: ResumeDataCache = let resumeDataCache: ResumeDataCache =
renderOpts.renderResumeDataCache ?? createPrerenderResumeDataCache() renderOpts.renderResumeDataCache ?? createPrerenderResumeDataCache()
if (
renderOpts.renderResumeDataCache &&
fallbackRouteParams &&
Object.keys(rootParams).some((name) => fallbackRouteParams.has(name))
) {
// This seed came from a more specific prerender. Its cache keys don't
// include root params, so replace entries that read roots this shell
// doesn't know with markers explaining why they must become holes.
// Keep the original seed intact for shells where those roots are known.
const cache = new Map(resumeDataCache.cache)
for (const [key, pendingEntry] of cache) {
if (
pendingEntry === FALLBACK_PARAMS ||
pendingEntry === RUNTIME_DATA ||
pendingEntry === SESSION_DATA
) {
continue
}
const {
readRootParamNames,
entry: { revalidate, expire },
} = await pendingEntry
if (readRootParamNames) {
for (const name of readRootParamNames) {
if (fallbackRouteParams.has(name)) {
// Unlike an unexplained miss, this entry can become static
// once its root params are known. Preserve that distinction
// for the final pass's static-prefetch hint. Short-lived
// entries still need runtime data even with concrete params.
if (revalidate === 0 || expire < MIN_PRERENDERABLE_EXPIRE) {
cache.set(key, SESSION_DATA)
} else {
cache.set(key, FALLBACK_PARAMS)
}
break
}
}
}
}
resumeDataCache = { ...resumeDataCache, cache }
}
reactServerPrerenderResultIsDynamic = null reactServerPrerenderResultIsDynamic = null
reactServerResumeDataCache = resumeDataCache reactServerResumeDataCache = resumeDataCache
reactServerPrerenderStore = null reactServerPrerenderStore = null
......
...@@ -5,7 +5,25 @@ import { dynamicAccessAsyncStorageInstance } from './dynamic-access-async-storag ...@@ -5,7 +5,25 @@ import { dynamicAccessAsyncStorageInstance } from './dynamic-access-async-storag
export interface DynamicAccessAsyncStore { export interface DynamicAccessAsyncStore {
readonly abortController: AbortController readonly abortController: AbortController
reason: DynamicAccessReason | null
} }
export type DynamicAccessReason = 'fallback-params' | 'runtime'
export type DynamicAccessStorage = AsyncLocalStorage<DynamicAccessAsyncStore> export type DynamicAccessStorage = AsyncLocalStorage<DynamicAccessAsyncStore>
export { dynamicAccessAsyncStorageInstance as dynamicAccessAsyncStorage } export { dynamicAccessAsyncStorageInstance as dynamicAccessAsyncStorage }
export function abortOnDynamicAccess(
reason: DynamicAccessReason,
error: Error
) {
const store = dynamicAccessAsyncStorageInstance.getStore()
if (store !== undefined) {
// A cache may read both kinds of data before cancellation finishes. Only
// fallback-only dependencies can become static when the params are known.
if (store.reason !== 'runtime') {
store.reason = reason
}
store.abortController.abort(error)
}
}
import assert from 'node:assert/strict'
import { import {
createPrerenderResumeDataCache, createPrerenderResumeDataCache,
deflateResumeDataCache, deflateResumeDataCache,
...@@ -64,7 +65,12 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -64,7 +65,12 @@ describe('getDynamicHTMLPostponedState', () => {
const parsed = parsePostponedState(state, undefined) const parsed = parsePostponedState(state, undefined)
expect(state).not.toContain(key) expect(state).not.toContain(key)
expect(parsed).toMatchInlineSnapshot(` // Other suites may enable async hooks, which attach internal symbols to
// promises. Check the entry below rather than snapshotting those fields.
expect(parsed.renderResumeDataCache.cache.size).toBe(1)
expect(parsed).toMatchInlineSnapshot(
{ renderResumeDataCache: { cache: expect.any(Map) } },
`
{ {
"data": [ "data": [
1, 1,
...@@ -76,9 +82,7 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -76,9 +82,7 @@ describe('getDynamicHTMLPostponedState', () => {
}, },
], ],
"renderResumeDataCache": { "renderResumeDataCache": {
"cache": Map { "cache": Any<Map>,
"1" => Promise {},
},
"decryptedBoundArgs": Map {}, "decryptedBoundArgs": Map {},
"encryptedBoundArgs": Map {}, "encryptedBoundArgs": Map {},
"fetch": Map {}, "fetch": Map {},
...@@ -90,13 +94,14 @@ describe('getDynamicHTMLPostponedState', () => { ...@@ -90,13 +94,14 @@ describe('getDynamicHTMLPostponedState', () => {
}, },
"type": 2, "type": 2,
} }
`) `
)
const value = await parsed.renderResumeDataCache.cache.get('1') const value = await parsed.renderResumeDataCache.cache.get('1')
expect(value).toBeDefined() assert(value !== undefined && typeof value !== 'symbol')
await expect(streamToString(value!.entry.value)).resolves.toEqual('hello') await expect(streamToString(value.entry.value)).resolves.toEqual('hello')
}) })
it('serializes a HTML postponed state without fallback params', async () => { it('serializes a HTML postponed state without fallback params', async () => {
...@@ -349,8 +354,8 @@ describe('parseResumeDataCacheFromPostponedState', () => { ...@@ -349,8 +354,8 @@ describe('parseResumeDataCacheFromPostponedState', () => {
) )
const value = await resumeDataCache.cache.get('cache-key') const value = await resumeDataCache.cache.get('cache-key')
expect(value).toBeDefined() assert(value !== undefined && typeof value !== 'symbol')
await expect(streamToString(value!.entry.value)).resolves.toBe( await expect(streamToString(value.entry.value)).resolves.toBe(
'cached value' 'cached value'
) )
}) })
......
...@@ -348,6 +348,13 @@ export interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore { ...@@ -348,6 +348,13 @@ export interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {
export interface PublicUseCacheStore extends CommonUseCacheStore { export interface PublicUseCacheStore extends CommonUseCacheStore {
readonly type: 'cache' readonly type: 'cache'
/**
* The enclosing prerender when root params are unknown. Nested caches need
* the same root availability and render lifetime, but their fills are
* cancelled independently.
*/
readonly fallbackRootParamsPrerender: PrerenderStoreModernServer | null
/** /**
* The root params for the current route. `undefined` when nested inside * The root params for the current route. `undefined` when nested inside
* `unstable_cache`, which doesn't carry root params. Currently, `"use cache"` * `unstable_cache`, which doesn't carry root params. Currently, `"use cache"`
......
...@@ -33,7 +33,7 @@ import { ...@@ -33,7 +33,7 @@ import {
trackIncompatibleShellContent, trackIncompatibleShellContent,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger' import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external' import { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external'
import { import {
isEmptyParams, isEmptyParams,
hasFallbackRouteParams, hasFallbackRouteParams,
...@@ -694,13 +694,10 @@ const fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = { ...@@ -694,13 +694,10 @@ const fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {
trackFallbackParamsAccessed(workUnitStore, '`params`') trackFallbackParamsAccessed(workUnitStore, '`params`')
} }
const store = dynamicAccessAsyncStorage.getStore() abortOnDynamicAccess(
'fallback-params',
if (store) { new Error(`Accessed fallback \`params\` during prerendering.`)
store.abortController.abort( )
new Error(`Accessed fallback \`params\` during prerendering.`)
)
}
return new Proxy( return new Proxy(
originalMethod.apply(target, args), originalMethod.apply(target, args),
......
...@@ -8,7 +8,12 @@ import { ...@@ -8,7 +8,12 @@ import {
type PrerenderStoreLegacy, type PrerenderStoreLegacy,
type PrerenderStoreModernServer, type PrerenderStoreModernServer,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils' import {
makeFallbackParamsHangingPromise,
trackFallbackParamsAccessed,
trackPromiseUsed,
} from '../dynamic-rendering-utils'
import { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external'
import type { ParamValue } from './params' import type { ParamValue } from './params'
import { actionAsyncStorage } from '../app-render/action-async-storage.external' import { actionAsyncStorage } from '../app-render/action-async-storage.external'
import { accumulateRootVaryParam } from '../app-render/vary-params' import { accumulateRootVaryParam } from '../app-render/vary-params'
...@@ -64,6 +69,33 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -64,6 +69,33 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
) )
} }
workUnitStore.readRootParamNames.add(paramName) workUnitStore.readRootParamNames.add(paramName)
const prerenderStore = workUnitStore.fallbackRootParamsPrerender
if (
prerenderStore !== null &&
prerenderStore.fallbackRouteParams !== null &&
prerenderStore.fallbackRouteParams.has(paramName)
) {
return trackPromiseUsed(
makeFallbackParamsHangingPromise<ParamValue>(
prerenderStore.renderSignal,
workStore.route,
apiName,
// Track access and cancel the cache together when consumed below.
null
),
() => {
trackFallbackParamsAccessed(prerenderStore, apiName)
// Like fallback `params`, an unknown root makes the whole cache
// invocation dynamic, even if it contains its own Suspense.
abortOnDynamicAccess(
'fallback-params',
new Error(
`Accessed fallback root parameter "${paramName}" during prerendering.`
)
)
}
)
}
return Promise.resolve(workUnitStore.rootParams[paramName]) return Promise.resolve(workUnitStore.rootParams[paramName])
} }
case 'prerender': case 'prerender':
......
...@@ -13,7 +13,7 @@ import { ...@@ -13,7 +13,7 @@ import {
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
annotateDynamicAccess, annotateDynamicAccess,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external' import { abortOnDynamicAccess } from '../app-render/dynamic-access-async-storage.external'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
...@@ -429,12 +429,10 @@ function makeHangingSearchParams( ...@@ -429,12 +429,10 @@ function makeHangingSearchParams(
// stall the App Shell cache-warming render. Re-wrapping the // stall the App Shell cache-warming render. Re-wrapping the
// result propagates the same behavior to promises derived via // result propagates the same behavior to promises derived via
// `.then`/`.catch`/`.finally` that are then passed into a cache. // `.then`/`.catch`/`.finally` that are then passed into a cache.
const dynamicAccessStore = dynamicAccessAsyncStorage.getStore() abortOnDynamicAccess(
if (dynamicAccessStore) { 'runtime',
dynamicAccessStore.abortController.abort( new Error('Accessed `searchParams` during prerendering.')
new Error('Accessed `searchParams` during prerendering.') )
)
}
return new Proxy(originalMethod.apply(target, args), proxyHandler) return new Proxy(originalMethod.apply(target, args), proxyHandler)
}, },
}[prop] }[prop]
......
...@@ -57,11 +57,27 @@ export interface UseCacheCacheStoreSerialized { ...@@ -57,11 +57,27 @@ export interface UseCacheCacheStoreSerialized {
readRootParamNames: string[] | undefined readRootParamNames: string[] | undefined
} }
// These markers carry holes from the prospective prerender to the final pass.
// They are never serialized: a request resuming the shell must be able to fill
// them. Symbol.for keeps their identity across separately bundled runtime code.
export const FALLBACK_PARAMS = Symbol.for(
'next.resume-data-cache.fallback-params'
)
export const RUNTIME_DATA = Symbol.for('next.resume-data-cache.runtime-data')
// Unlike params/searchParams, short-lived data also prevents a static shell.
export const SESSION_DATA = Symbol.for('next.resume-data-cache.session-data')
type UseCacheCacheStoreValue =
| Promise<CollectedCacheResult>
| typeof FALLBACK_PARAMS
| typeof RUNTIME_DATA
| typeof SESSION_DATA
/** /**
* A cache store specifically for "use cache" values that stores promises of * A cache store for "use cache" results, or markers explaining why an entry
* collected cache results (entry + metadata). * could not be included in this prerender.
*/ */
export type UseCacheCacheStore = CacheStore<Promise<CollectedCacheResult>> export type UseCacheCacheStore = CacheStore<UseCacheCacheStoreValue>
/** /**
* Parses serialized cache entries into a UseCacheCacheStore * Parses serialized cache entries into a UseCacheCacheStore
...@@ -120,11 +136,19 @@ export function parseUseCacheCacheStore( ...@@ -120,11 +136,19 @@ export function parseUseCacheCacheStore(
* @returns A promise that resolves to an array of key-value pairs with serialized values * @returns A promise that resolves to an array of key-value pairs with serialized values
*/ */
export async function serializeUseCacheCacheStore( export async function serializeUseCacheCacheStore(
entries: IterableIterator<[string, Promise<CollectedCacheResult>]>, entries: IterableIterator<[string, UseCacheCacheStoreValue]>,
isCacheComponentsEnabled: boolean isCacheComponentsEnabled: boolean
): Promise<Array<[string, UseCacheCacheStoreSerialized] | null>> { ): Promise<Array<[string, UseCacheCacheStoreSerialized] | null>> {
return Promise.all( return Promise.all(
Array.from(entries).map(([key, value]) => { Array.from(entries).map(([key, value]) => {
if (
value === FALLBACK_PARAMS ||
value === RUNTIME_DATA ||
value === SESSION_DATA
) {
return null
}
return value return value
.then( .then(
async ({ async ({
......
...@@ -4,12 +4,18 @@ import { ...@@ -4,12 +4,18 @@ import {
createRenderResumeDataCache, createRenderResumeDataCache,
} from './resume-data-cache' } from './resume-data-cache'
import { createPrerenderResumeDataCache } from './resume-data-cache' import { createPrerenderResumeDataCache } from './resume-data-cache'
import { FALLBACK_PARAMS, RUNTIME_DATA, SESSION_DATA } from './cache-store'
import { streamFromString } from '../stream-utils/node-web-streams-helper' import { streamFromString } from '../stream-utils/node-web-streams-helper'
const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true' const isCacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
function createMockedCache() { function createMockedCache() {
const cache = createPrerenderResumeDataCache() const cache = createPrerenderResumeDataCache()
// Omission reasons are only carried between passes of this prerender, never
// into the persisted cache used by a later request.
cache.cache.set('fallback-hole', FALLBACK_PARAMS)
cache.cache.set('runtime-hole', RUNTIME_DATA)
cache.cache.set('session-hole', SESSION_DATA)
// Should be included during serialization. // Should be included during serialization.
cache.cache.set( cache.cache.set(
...@@ -78,6 +84,32 @@ function createMockedCacheWithEntryThatFails() { ...@@ -78,6 +84,32 @@ function createMockedCacheWithEntryThatFails() {
return cache return cache
} }
describe('createPrerenderResumeDataCache', () => {
it('copies entries and hole markers without changing the seed', () => {
const seed = createMockedCache()
const clone = createPrerenderResumeDataCache(seed)
expect(clone.cache).not.toBe(seed.cache)
expect(clone.cache).toEqual(seed.cache)
clone.cache.set('success', FALLBACK_PARAMS)
clone.cache.set('fallback-hole', RUNTIME_DATA)
expect(seed.cache.get('success')).toBeInstanceOf(Promise)
expect(seed.cache.get('fallback-hole')).toBe(FALLBACK_PARAMS)
expect(clone.cache.get('runtime-hole')).toBe(RUNTIME_DATA)
expect(clone.cache.get('session-hole')).toBe(SESSION_DATA)
})
it('keeps hole markers when converting to a read-only in-memory cache', () => {
const cache = createMockedCache()
const renderCache = createRenderResumeDataCache(cache)
expect(renderCache.mutable).toBe(false)
expect(renderCache.cache.get('fallback-hole')).toBe(FALLBACK_PARAMS)
expect(renderCache.cache.get('runtime-hole')).toBe(RUNTIME_DATA)
expect(renderCache.cache.get('session-hole')).toBe(SESSION_DATA)
})
})
describe('stringifyResumeDataCache', () => { describe('stringifyResumeDataCache', () => {
it('throws in the edge runtime before serializing an empty cache', async () => { it('throws in the edge runtime before serializing an empty cache', async () => {
const nextRuntime = process.env.NEXT_RUNTIME const nextRuntime = process.env.NEXT_RUNTIME
...@@ -108,6 +140,22 @@ describe('stringifyResumeDataCache', () => { ...@@ -108,6 +140,22 @@ describe('stringifyResumeDataCache', () => {
).toBe('null') ).toBe('null')
}) })
it('serializes a successful fill that replaced a hole marker', async () => {
const cache = createMockedCache()
const successfulEntry = cache.cache.get('success')!
cache.cache.set('fallback-hole', successfulEntry)
cache.cache.set('runtime-hole', successfulEntry)
const serialized = await stringifyResumeDataCache(
cache,
isCacheComponentsEnabled
)
const parsed = createRenderResumeDataCache(serialized, undefined, true)
expect(parsed.cache.get('fallback-hole')).toBeInstanceOf(Promise)
expect(parsed.cache.get('runtime-hole')).toBeInstanceOf(Promise)
})
it('only serializes cache entries that were not excluded from the prerender result', async () => { it('only serializes cache entries that were not excluded from the prerender result', async () => {
const cache = createMockedCache() const cache = createMockedCache()
...@@ -175,7 +223,6 @@ describe('parseResumeDataCache', () => { ...@@ -175,7 +223,6 @@ describe('parseResumeDataCache', () => {
expect(parsed.fetch).toEqual(new Map()) expect(parsed.fetch).toEqual(new Map())
expect(parsed.encryptedBoundArgs).toEqual(new Map()) expect(parsed.encryptedBoundArgs).toEqual(new Map())
expect(parsed.decryptedBoundArgs).toEqual(new Map()) expect(parsed.decryptedBoundArgs).toEqual(new Map())
expect(parsed.dynamicCacheKeys).toBeUndefined()
}) })
it.each([false, true])( it.each([false, true])(
...@@ -198,6 +245,37 @@ describe('parseResumeDataCache', () => { ...@@ -198,6 +245,37 @@ describe('parseResumeDataCache', () => {
expect(parsed.cache.size).toBe(isCacheComponentsEnabled ? 1 : 3) expect(parsed.cache.size).toBe(isCacheComponentsEnabled ? 1 : 3)
expect(parsed.fetch.size).toBe(0) expect(parsed.fetch.size).toBe(0)
expect(parsed.cache.has('fallback-hole')).toBe(false)
expect(parsed.cache.has('runtime-hole')).toBe(false)
expect(parsed.cache.has('session-hole')).toBe(false)
}
)
it.each([false, true])(
'omits all hole markers with compression disabled: %s',
async (disableResumeDataCacheCompression) => {
const cache = createPrerenderResumeDataCache()
cache.cache.set('fallback-hole', FALLBACK_PARAMS)
cache.cache.set('runtime-hole', RUNTIME_DATA)
cache.cache.set('session-hole', SESSION_DATA)
const serialized = await stringifyResumeDataCache(
cache,
isCacheComponentsEnabled
)
const persisted = disableResumeDataCacheCompression
? serialized
: deflateResumeDataCache(serialized)
const parsed = createRenderResumeDataCache(
persisted,
undefined,
disableResumeDataCacheCompression
)
expect(parsed.cache.size).toBe(0)
expect(cache.cache.get('fallback-hole')).toBe(FALLBACK_PARAMS)
expect(cache.cache.get('runtime-hole')).toBe(RUNTIME_DATA)
expect(cache.cache.get('session-hole')).toBe(SESSION_DATA)
} }
) )
}) })
...@@ -56,16 +56,6 @@ export interface RenderResumeDataCache { ...@@ -56,16 +56,6 @@ export interface RenderResumeDataCache {
* enforce immutability. * enforce immutability.
*/ */
readonly imageResponses: Omit<ImageResponseCacheStore, 'set'> readonly imageResponses: Omit<ImageResponseCacheStore, 'set'>
/**
* Serialized cache keys that were intentionally skipped during the
* prospective prerender (e.g. because the cached function accessed fallback
* params or other dynamic data). During the final prerender, a key in this
* set is returned as a hanging promise early, without attempting to look up
* or generate a cache entry. Optional because this field is intentionally not
* serialized and won't be present in deserialized caches.
*/
readonly dynamicCacheKeys?: ReadonlySet<string>
} }
/** /**
...@@ -116,20 +106,6 @@ export interface PrerenderResumeDataCache { ...@@ -116,20 +106,6 @@ export interface PrerenderResumeDataCache {
* prerender. Never persisted in the resume store. * prerender. Never persisted in the resume store.
*/ */
readonly imageResponses: ImageResponseCacheStore readonly imageResponses: ImageResponseCacheStore
/**
* Tracks serialized cache keys that were intentionally skipped during the
* prospective prerender (e.g. because the cached function accessed fallback
* params or other dynamic data). During the final prerender, a key in this
* set is returned as a hanging promise early, without attempting to look up
* or generate a cache entry.
*
* This is intentionally not serialized. It is only used in-memory within a
* single prerender cycle (prospective to final). During the resume at request
* time, a cache miss for a dynamic key should generate a fresh entry rather
* than being short-circuited.
*/
readonly dynamicCacheKeys: Set<string>
} }
/** /**
...@@ -236,9 +212,6 @@ export function createPrerenderResumeDataCache( ...@@ -236,9 +212,6 @@ export function createPrerenderResumeDataCache(
encryptedBoundArgs: new Map(source.encryptedBoundArgs), encryptedBoundArgs: new Map(source.encryptedBoundArgs),
decryptedBoundArgs: new Map(source.decryptedBoundArgs), decryptedBoundArgs: new Map(source.decryptedBoundArgs),
imageResponses: new Map(source.imageResponses), imageResponses: new Map(source.imageResponses),
dynamicCacheKeys: source.dynamicCacheKeys
? new Set(source.dynamicCacheKeys)
: new Set(),
} }
} else { } else {
return { return {
...@@ -248,7 +221,6 @@ export function createPrerenderResumeDataCache( ...@@ -248,7 +221,6 @@ export function createPrerenderResumeDataCache(
encryptedBoundArgs: new Map(), encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(), decryptedBoundArgs: new Map(),
imageResponses: new Map(), imageResponses: new Map(),
dynamicCacheKeys: new Set(),
} }
} }
} }
......
import { Suspense } from 'react'
import { DirectLanguage } from '../cached'
async function CachedUI() {
'use cache'
return (
<>
<p id="cache-prefix">This belongs to the cached result</p>
<Suspense fallback={<p id="inner-pending">Loading inside cache</p>}>
<DirectLanguage />
</Suspense>
</>
)
}
export default function Page() {
return (
<Suspense fallback={<p id="outer-pending">Loading entire cache</p>}>
<CachedUI />
</Suspense>
)
}
import { lang } from 'next/root-params'
async function getLanguage() {
'use cache'
return (await lang()).toUpperCase()
}
async function getSharedContent() {
'use cache'
return 'shared content'
}
async function getNestedLanguage() {
'use cache'
const [language] = await Promise.all([getLanguage(), getSharedContent()])
return language
}
async function getDeepLanguage() {
'use cache'
return getNestedLanguage()
}
export async function CachedLanguage() {
return <p id="cached-lang">{await getLanguage()}</p>
}
export async function NestedLanguage() {
return <p id="nested-lang">{await getDeepLanguage()}</p>
}
export async function Independent() {
return <p id="independent">{await getSharedContent()}</p>
}
export async function DirectLanguage() {
return <p id="direct-lang">{await lang()}</p>
}
import { Suspense } from 'react'
import { CachedLanguage } from '../../cached'
export function generateStaticParams() {
return [{ slug: 'one' }]
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<>
<Suspense fallback={<p id="cached-pending">Loading language</p>}>
<CachedLanguage />
</Suspense>
<Suspense fallback={<p id="slug-pending">Loading item</p>}>
<Item params={params} />
</Suspense>
</>
)
}
async function Item({ params }: { params: Promise<{ slug: string }> }) {
return <p>{(await params).slug}</p>
}
export function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'es' }]
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<h1>Language-independent shell</h1>
{children}
</body>
</html>
)
}
import { Suspense } from 'react'
import { CachedLanguage, Independent, NestedLanguage } from '../cached'
export default function Page() {
return (
<>
<Suspense fallback={<p id="cached-pending">Loading cached language</p>}>
<CachedLanguage />
</Suspense>
<Suspense fallback={<p id="nested-pending">Loading nested language</p>}>
<NestedLanguage />
</Suspense>
<Suspense fallback={<p id="independent-pending">Loading content</p>}>
<Independent />
</Suspense>
</>
)
}
import { Suspense } from 'react'
import { CachedLanguage, DirectLanguage, Independent } from './cached'
export default function Page() {
return (
<>
<Suspense fallback={<p id="direct-pending">Loading language</p>}>
<DirectLanguage />
</Suspense>
<Suspense fallback={<p id="cached-pending">Loading cached language</p>}>
<CachedLanguage />
</Suspense>
<Suspense fallback={<p id="independent-pending">Loading content</p>}>
<Independent />
</Suspense>
</>
)
}
import { Suspense } from 'react'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<Suspense fallback={<p>Loading search results</p>}>{children}</Suspense>
)
}
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ query?: string }>
}) {
'use cache: private'
return <p>Search: {(await searchParams).query}</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import { load } from 'cheerio'
import { PrefetchHint } from 'next/src/shared/lib/app-router-types'
describe('use-cache-fallback-root-params', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// The build seeds generic shells with the RDC from a concrete prerender.
// Root-dependent entries must become holes when that root is unknown.
// @force-gate !dev && !deploy
it('omits root-dependent entries from the RDC used to build generic shells', async () => {
const $ = load(await next.readFile('.next/server/app/[lang].html'))
expect($('#cached-pending').length).toBe(1)
expect($('#cached-lang').length).toBe(0)
expect($('#independent').text()).toBe('shared content')
const $nested = load(
await next.readFile('.next/server/app/[lang]/nested.html')
)
expect($nested('#nested-pending').length).toBe(1)
expect($nested('#nested-lang').length).toBe(0)
expect($nested('#independent').text()).toBe('shared content')
const $boundary = load(
await next.readFile('.next/server/app/[lang]/boundary.html')
)
expect($boundary('#outer-pending').length).toBe(1)
expect(
$boundary('#cache-prefix, #inner-pending, #direct-lang').length
).toBe(0)
})
// @force-gate !dev && !deploy
it('keeps cached root content in shells whose root is known', async () => {
for (const language of ['en', 'es']) {
const $ = load(
await next.readFile(`.next/server/app/${language}/items/[slug].html`)
)
expect($('#cached-lang').text()).toBe(language.toUpperCase())
expect($('#cached-pending').length).toBe(0)
expect($('#slug-pending').length).toBe(1)
}
})
// These are per-shell build measurements, not the route-level manifest:
// a concrete prerender can supply that manifest's hints before the generic
// shell is rendered. Inspect the generic shell to exercise RDC pruning.
// @force-gate !dev && !deploy
it('preserves static-prefetch hints when only fallback roots are missing', async () => {
for (const pathname of ['[lang]', '[lang]/nested', '[lang]/boundary']) {
const meta = JSON.parse(
await next.readFile(`.next/server/app/${pathname}.meta`)
)
expect(
(meta.prefetchHints?.hints ?? 0) &
PrefetchHint.ShouldAttemptStaticPrefetch
).toBe(PrefetchHint.ShouldAttemptStaticPrefetch)
}
})
// @force-gate !dev && !deploy
it('does not mistake searchParams in a cached page for a fallback root read', async () => {
const meta = JSON.parse(
await next.readFile('.next/server/app/[lang]/search.meta')
)
expect(
(meta.prefetchHints?.hints ?? 0) &
PrefetchHint.ShouldAttemptStaticPrefetch
).toBe(0)
})
it('resolves cached and uncached roots on ordinary requests', async () => {
await Promise.all(
['en', 'fr', 'de'].map(async (language) => {
const $ = await next.render$(`/${language}`)
expect($('#cached-lang').text()).toBe(language.toUpperCase())
expect($('#direct-lang').text()).toBe(language)
expect($('#independent').text()).toBe('shared content')
const $nested = await next.render$(`/${language}/nested`)
expect($nested('#nested-lang').text()).toBe(language.toUpperCase())
expect($nested('#independent').text()).toBe('shared content')
const $boundary = await next.render$(`/${language}/boundary`)
expect($boundary('#direct-lang').text()).toBe(language)
})
)
})
})
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