Unverified Commit 50edb744 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

[ppr] RDC for RSCs (redo) (#80853)

## What?

This PR introduces the Resume Data Cache (RDC) functionality to improve
handling of dynamic React Server Component (RSC) requests when Partial
Pre-rendering (PPR) is enabled. This enhancement enables dynamic RSC
responses to utilize the Resume Data Cache, significantly reducing
waterfalls and preventing content shearing.

## Why?

Previously, dynamic RSC requests with PPR enabled experienced several
issues:

**Waterfall Reduction:** Dynamic RSC responses required multiple
waterfalls to hydrate a given cache, leading to slower response times
and unnecessary network round-trips.

**Content Shearing Prevention:** There were mismatches between static
cached parts of the page and the dynamic response, causing visual
inconsistencies and potential hydration errors. By ensuring the RDC
generated for static responses is also used for dynamic RSC responses,
we maintain consistency even when the dynamic response interacts with
caches directly and potentially receives newer, non-stale values.

**Additional Issues Addressed:**
- Stale content revalidation not triggering correctly
- Background revalidation producing dynamic responses instead of static
ones
- Inconsistent cache tag staleness evaluation
- Missing support for resumable rendering in dynamic contexts

## How?

**Core Implementation:**
- Added Resume Data Cache layer that stores resumable render data for
dynamic RSC requests
- Ensures the same RDC used by static responses is reused for dynamic
RSC responses
- Introduced `forceStaticRender` flag to ensure background revalidation
generates static responses
- Refactored response cache internals to separate cache entry creation
from response handling
- Enhanced error handling with try-catch blocks for server actions in
app-render

**Revalidation Improvements:**
- Fixed cache tag staleness evaluation for consistent behavior
- Improved triggering logic for background revalidation of stale dynamic
content
- Better handling of cache misses and "no-resume-data" scenarios with
debug logging

---------
Co-authored-by: 's avatargraphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>
parent 11762a78
......@@ -795,5 +795,8 @@
"794": "Invalid <Link> with <a> child. Please remove <a>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor",
"795": "\\`%s\\` was called from a Server Component. Next.js should be preventing %s from being included in server components statically, but did not in this case.",
"796": "Page \"%s\" cannot use \\`export const unstable_prefetch = ...\\` without enabling \\`experimental.cacheComponents\\` and \\`experimental.clientSegmentCache\\`.",
"797": "Failed to transpile \"%s\"."
"797": "Failed to transpile \"%s\".",
"798": "expected a result to be returned",
"799": "expected a page response, got %s",
"800": "`experimental.rdcForNavigations` is enabled, but `experimental.ppr` is not."
}
......@@ -172,7 +172,12 @@ module.exports = ({ dev, turbo, bundleType, experimental, ...rest }) => {
return {
entry: bundleTypes[bundleType],
target: 'node',
mode: dev ? 'development' : 'production',
mode:
process.env.NEXT_DEBUG_INTERNALS === 'true'
? 'development'
: dev
? 'development'
: 'production',
output: {
path: path.join(__dirname, 'dist/compiled/next-server'),
filename: `[name]${turbo ? '-turbo' : ''}${
......@@ -181,18 +186,22 @@ module.exports = ({ dev, turbo, bundleType, experimental, ...rest }) => {
libraryTarget: 'commonjs2',
},
devtool: 'source-map',
optimization: {
moduleIds: 'named',
minimize: true,
concatenateModules: true,
minimizer: [
new webpack.SwcJsMinimizerRspackPlugin({
minimizerOptions: {
mangle: dev || process.env.NEXT_SERVER_NO_MANGLE ? false : true,
optimization:
process.env.NEXT_DEBUG_INTERNALS === 'true'
? undefined
: {
moduleIds: 'named',
minimize: true,
concatenateModules: true,
minimizer: [
new webpack.SwcJsMinimizerRspackPlugin({
minimizerOptions: {
mangle:
dev || process.env.NEXT_SERVER_NO_MANGLE ? false : true,
},
}),
],
},
}),
],
},
plugins: [
new DevToolsIgnoreListPlugin({ shouldIgnorePath }),
new webpack.DefinePlugin({
......
......@@ -480,6 +480,7 @@ export type RoutesManifest = {
* rewrites will get the rewrite headers.
*/
clientParamParsingOrigins: string[] | undefined
dynamicRSCPrerender: boolean
}
rewriteHeaders: {
pathHeader: typeof NEXT_REWRITTEN_PATH_HEADER
......@@ -1567,6 +1568,17 @@ export default async function build(
clientParamParsingOrigins: config.experimental.clientParamParsing
? config.experimental.clientParamParsingOrigins
: undefined,
dynamicRSCPrerender:
// Only enable RDC for Navigations if the feature is enabled.
// Once we've made RDC for Navigations the default for PPR, we
// can remove the check for `config.experimental.rdcForNavigations`.
isAppPPREnabled &&
config.experimental.rdcForNavigations === true &&
// Temporarily we require that clientParamParsing is enabled for
// RDC for Navigations. This is due to a builder configuration
// bug that manifests as invalid query params being passed to
// the resume lambdas.
config.experimental.clientParamParsing === true,
},
rewriteHeaders: {
pathHeader: NEXT_REWRITTEN_PATH_HEADER,
......
......@@ -32,7 +32,7 @@ describe('Batcher', () => {
it('should not batch calls to different keys', async () => {
const batcher = Batcher.create<string, string>()
const workFn = jest.fn((key) => key)
const workFn = jest.fn(({ key }) => Promise.resolve(key))
const result1 = batcher.batch('key1', workFn)
const result2 = batcher.batch('key2', workFn)
......
......@@ -11,10 +11,12 @@ type BatcherOptions<K, C extends string | number | null> = {
schedulerFn?: SchedulerFn<void>
}
type WorkFn<V, C> = (
key: C,
type WorkFnContext<V, K> = {
resolve: (value: V | PromiseLike<V>) => void
) => Promise<V>
key: K
}
type WorkFn<V, K> = (context: WorkFnContext<V, K>) => Promise<V>
/**
* A wrapper for a function that will only allow one call to the function to
......@@ -61,10 +63,10 @@ export class Batcher<K, V, C extends string | number | null> {
* @param fn the function to wrap
* @returns a promise that resolves to the result of the function
*/
public async batch(key: K, fn: WorkFn<V, C>): Promise<V> {
public async batch(key: K, fn: WorkFn<V, K>): Promise<V> {
const cacheKey = (this.cacheKeyFn ? await this.cacheKeyFn(key) : key) as C
if (cacheKey === null) {
return fn(cacheKey, Promise.resolve)
return fn({ resolve: (value) => Promise.resolve(value), key })
}
const pending = this.pending.get(cacheKey)
......@@ -75,7 +77,7 @@ export class Batcher<K, V, C extends string | number | null> {
this.schedulerFn(async () => {
try {
const result = await fn(cacheKey, resolve)
const result = await fn({ resolve, key })
// Resolving a promise multiple times is a no-op, so we can safely
// resolve all pending promises with the same result.
......
......@@ -1782,7 +1782,9 @@ async function renderToHTMLOrFlightImpl(
} else {
// We're rendering dynamically
const renderResumeDataCache =
renderOpts.renderResumeDataCache ?? postponedState?.renderResumeDataCache
renderOpts.renderResumeDataCache ??
postponedState?.renderResumeDataCache ??
null
const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment)
const devValidatingFallbackParams =
......@@ -1843,6 +1845,9 @@ async function renderToHTMLOrFlightImpl(
let formState: null | any = null
if (isPossibleActionRequest) {
// For action requests, we don't want to use the resume data cache.
requestStore.renderResumeDataCache = null
// For action requests, we handle them differently with a special render result.
const actionRequestResult = await handleAction({
req,
......@@ -1887,6 +1892,9 @@ async function renderToHTMLOrFlightImpl(
}
}
}
// Restore the resume data cache
requestStore.renderResumeDataCache = renderResumeDataCache
}
const options: RenderResultOptions = {
......@@ -2071,7 +2079,7 @@ function applyMetadataFromPrerenderResult(
}
// provide bailout info for debugging
if (metadata.cacheControl?.revalidate === 0) {
if (metadata.cacheControl.revalidate === 0) {
metadata.staticBailoutInfo = {
description: workStore.dynamicUsageDescription,
stack: workStore.dynamicUsageStack,
......@@ -3516,6 +3524,7 @@ async function prerenderToStream(
'abort',
() => {
initialServerRenderController.abort()
initialServerPrerenderController.abort()
},
{ once: true }
)
......
......@@ -115,7 +115,7 @@ export function createRequestStoreForRender(
previewProps: WrapperRenderOpts['previewProps'],
isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
renderResumeDataCache: RenderResumeDataCache | undefined,
renderResumeDataCache: RenderResumeDataCache | null,
devFallbackParams: OpaqueFallbackRouteParams | null
): RequestStore {
return createRequestStoreImpl(
......@@ -151,7 +151,7 @@ export function createRequestStoreForAPI(
{},
implicitTags,
onUpdateCookies,
undefined,
null,
previewProps,
false,
undefined,
......@@ -167,7 +167,7 @@ function createRequestStoreImpl(
rootParams: Params,
implicitTags: RequestContext['implicitTags'],
onUpdateCookies: RenderOpts['onUpdateCookies'],
renderResumeDataCache: RenderResumeDataCache | undefined,
renderResumeDataCache: RenderResumeDataCache | null,
previewProps: WrapperRenderOpts['previewProps'],
isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
......
......@@ -374,6 +374,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
clientSegmentCache: z
.union([z.boolean(), z.literal('client-only')])
.optional(),
rdcForNavigations: z.boolean().optional(),
clientParamParsing: z.boolean().optional(),
clientParamParsingOrigins: z.array(z.string()).optional(),
dynamicOnHover: z.boolean().optional(),
......
......@@ -466,6 +466,13 @@ export interface ExperimentalConfig {
linkNoTouchStart?: boolean
caseSensitiveRoutes?: boolean
clientSegmentCache?: boolean | 'client-only'
/**
* Enables RDC for Dynamic Navigations. This is only supported for App Router
* when Partial Prerendering is also enabled. This is enabled by default when
* Partial Prerendering is enabled.
*/
rdcForNavigations?: boolean
clientParamParsing?: boolean
/**
......@@ -1573,6 +1580,7 @@ export const defaultConfig = Object.freeze({
linkNoTouchStart: false,
caseSensitiveRoutes: false,
clientSegmentCache: false,
rdcForNavigations: false,
clientParamParsing: false,
clientParamParsingOrigins: undefined,
dynamicOnHover: false,
......
......@@ -170,6 +170,46 @@ describe('loadConfig', () => {
)
})
it('errors when rdcForNavigations is enabled but ppr is disabled', async () => {
await expect(
loadConfig('', __dirname, {
customConfig: {
experimental: {
rdcForNavigations: true,
ppr: false,
},
},
})
).rejects.toThrow(
'`experimental.rdcForNavigations` is enabled, but `experimental.ppr` is not.'
)
})
it('defaults rdcForNavigations to true when ppr is enabled', async () => {
const result = await loadConfig('', __dirname, {
customConfig: {
experimental: {
ppr: true,
},
},
})
expect(result.experimental.rdcForNavigations).toBe(true)
})
it('allows explicitly disabling rdcForNavigations when ppr is enabled', async () => {
const result = await loadConfig('', __dirname, {
customConfig: {
experimental: {
ppr: true,
rdcForNavigations: false,
},
},
})
expect(result.experimental.rdcForNavigations).toBe(false)
})
it('errors when cacheComponents is enabled but PPR set to "incremental"', async () => {
await expect(
loadConfig('', __dirname, {
......
......@@ -214,7 +214,8 @@ function warnCustomizedOption(
function assignDefaultsAndValidate(
dir: string,
userConfig: NextConfig & { configFileName: string },
silent: boolean
silent: boolean,
configuredExperimentalFeatures: ConfiguredExperimentalFeature[]
): NextConfigComplete {
const configFileName = userConfig.configFileName
if (typeof userConfig.exportTrailingSlash !== 'undefined') {
......@@ -1143,6 +1144,46 @@ function assignDefaultsAndValidate(
}
result.experimental.ppr = true
if (
configuredExperimentalFeatures &&
// If we've already noted that the `process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS`
// has enabled the feature, we don't need to note it again.
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS !== 'true' &&
process.env.__NEXT_EXPERIMENTAL_PPR !== 'true'
) {
addConfiguredExperimentalFeature(
configuredExperimentalFeatures,
'ppr',
true,
'enabled by `experimental.cacheComponents`'
)
}
}
// If ppr is enabled and the user hasn't configured rdcForNavigations, we
// enable it by default.
if (
result.experimental.ppr &&
userConfig.experimental?.rdcForNavigations === undefined
) {
result.experimental.rdcForNavigations = true
if (configuredExperimentalFeatures) {
addConfiguredExperimentalFeature(
configuredExperimentalFeatures,
'rdcForNavigations',
true,
'enabled by `experimental.ppr`'
)
}
}
// If rdcForNavigations is enabled, but ppr is not, we throw an error.
if (result.experimental.rdcForNavigations && !result.experimental.ppr) {
throw new Error(
'`experimental.rdcForNavigations` is enabled, but `experimental.ppr` is not.'
)
}
// We require clientSegmentCache to be enabled if clientParamParsing is
......@@ -1320,7 +1361,8 @@ export default async function loadConfig(
configFileName,
...customConfig,
},
silent
silent,
configuredExperimentalFeatures
) as NextConfigComplete,
phase,
silent
......@@ -1526,7 +1568,8 @@ export default async function loadConfig(
configFileName,
...userConfig,
},
silent
silent,
configuredExperimentalFeatures
) as NextConfigComplete
const finalConfig = await applyModifyConfig(completeConfig, phase, silent)
......@@ -1579,7 +1622,8 @@ export default async function loadConfig(
const completeConfig = assignDefaultsAndValidate(
dir,
{ ...clonedDefaultConfig, configFileName },
silent
silent,
configuredExperimentalFeatures
) as NextConfigComplete
setHttpClientAndAgentOptions(completeConfig)
......@@ -1752,6 +1796,44 @@ function enforceExperimentalFeatures(
}
}
// TODO: Remove this once we've made RDC for Navigations the default for PPR.
if (
process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS === 'true' &&
// We do respect an explicit value in the user config.
(config.experimental.rdcForNavigations === undefined ||
(isDefaultConfig && !config.experimental.rdcForNavigations))
) {
config.experimental.rdcForNavigations = true
if (configuredExperimentalFeatures) {
addConfiguredExperimentalFeature(
configuredExperimentalFeatures,
'rdcForNavigations',
true,
'enabled by `__NEXT_EXPERIMENTAL_CACHE_COMPONENTS`'
)
}
}
// TODO: Remove this once we've made RDC for Navigations the default for PPR.
if (
process.env.__NEXT_EXPERIMENTAL_PPR === 'true' &&
// We do respect an explicit value in the user config.
(config.experimental.rdcForNavigations === undefined ||
(isDefaultConfig && !config.experimental.rdcForNavigations))
) {
config.experimental.rdcForNavigations = true
if (configuredExperimentalFeatures) {
addConfiguredExperimentalFeature(
configuredExperimentalFeatures,
'rdcForNavigations',
true,
'enabled by `__NEXT_EXPERIMENTAL_PPR`'
)
}
}
if (
config.experimental.enablePrerenderSourceMaps === undefined &&
config.experimental.cacheComponents === true
......
......@@ -12,13 +12,11 @@ export function logStartInfo({
appUrl,
envInfo,
experimentalFeatures,
maxExperimentalFeatures = Infinity,
}: {
networkUrl: string | null
appUrl: string | null
envInfo?: string[]
experimentalFeatures?: ConfiguredExperimentalFeature[]
maxExperimentalFeatures?: number
}) {
let bundlerSuffix
if (process.env.TURBOPACK) {
......@@ -44,8 +42,7 @@ export function logStartInfo({
if (experimentalFeatures?.length) {
Log.bootstrap(`- Experiments (use with caution):`)
// only show a maximum number of flags
for (const exp of experimentalFeatures.slice(0, maxExperimentalFeatures)) {
for (const exp of experimentalFeatures) {
const symbol =
typeof exp.value === 'boolean'
? exp.value === true
......@@ -62,10 +59,6 @@ export function logStartInfo({
Log.bootstrap(` ${symbol} ${exp.key}${suffix}${reason}`)
}
/* indicate if there are more than the maximum shown no. flags */
if (experimentalFeatures.length > maxExperimentalFeatures) {
Log.bootstrap(` · ...`)
}
}
// New line after the bootstrap info
......@@ -90,8 +83,8 @@ export async function getStartServerInfo({
dir,
{
reportExperimentalFeatures(features) {
experimentalFeatures = features.sort(
({ key: a }, { key: b }) => a.length - b.length
experimentalFeatures = features.sort(({ key: a }, { key: b }) =>
a.localeCompare(b)
)
},
debugPrerender,
......
......@@ -50,15 +50,15 @@ export default class FileSystemCache implements CacheHandler {
if (ctx.maxMemoryCacheSize) {
if (!FileSystemCache.memoryCache) {
if (FileSystemCache.debug) {
console.log('using memory store for fetch cache')
console.log('FileSystemCache: using memory store for fetch cache')
}
FileSystemCache.memoryCache = getMemoryCache(ctx.maxMemoryCacheSize)
} else if (FileSystemCache.debug) {
console.log('memory store already initialized')
console.log('FileSystemCache: memory store already initialized')
}
} else if (FileSystemCache.debug) {
console.log('not using memory store for fetch cache')
console.log('FileSystemCache: not using memory store for fetch cache')
}
}
......@@ -71,7 +71,7 @@ export default class FileSystemCache implements CacheHandler {
tags = typeof tags === 'string' ? [tags] : tags
if (FileSystemCache.debug) {
console.log('revalidateTag', tags)
console.log('FileSystemCache: revalidateTag', tags)
}
if (tags.length === 0) {
......@@ -93,9 +93,9 @@ export default class FileSystemCache implements CacheHandler {
if (FileSystemCache.debug) {
if (kind === IncrementalCacheKind.FETCH) {
console.log('get', key, ctx.tags, kind, !!data)
console.log('FileSystemCache: get', key, ctx.tags, kind, !!data)
} else {
console.log('get', key, kind, !!data)
console.log('FileSystemCache: get', key, kind, !!data)
}
}
......@@ -155,7 +155,11 @@ export default class FileSystemCache implements CacheHandler {
// via header on GET same as SET
if (!tags?.every((tag) => storedTags?.includes(tag))) {
if (FileSystemCache.debug) {
console.log('tags vs storedTags mismatch', tags, storedTags)
console.log(
'FileSystemCache: tags vs storedTags mismatch',
tags,
storedTags
)
}
await this.set(key, data.value, {
fetchCache: true,
......@@ -271,23 +275,33 @@ export default class FileSystemCache implements CacheHandler {
}
}
// If enabled, this will return the possibly stale data without validating
// that the tags have expired or not yet been revalidated.
if ('allowStale' in ctx && ctx.allowStale) {
if (FileSystemCache.debug) {
console.log('FileSystemCache: allow stale', ctx.allowStale)
}
return data ?? null
}
if (
data?.value?.kind === CachedRouteKind.APP_PAGE ||
data?.value?.kind === CachedRouteKind.APP_ROUTE ||
data?.value?.kind === CachedRouteKind.PAGES
) {
let cacheTags: undefined | string[]
const tagsHeader = data.value.headers?.[NEXT_CACHE_TAGS_HEADER]
if (typeof tagsHeader === 'string') {
cacheTags = tagsHeader.split(',')
}
const cacheTags = tagsHeader.split(',')
if (cacheTags?.length) {
// we trigger a blocking validation if an ISR page
// had a tag revalidated, if we want to be a background
// revalidation instead we return data.lastModified = -1
if (isStale(cacheTags, data?.lastModified || Date.now())) {
if (cacheTags.length > 0 && isStale(cacheTags, data.lastModified)) {
if (FileSystemCache.debug) {
console.log('FileSystemCache: stale tags', cacheTags)
}
return null
}
}
......@@ -297,17 +311,22 @@ export default class FileSystemCache implements CacheHandler {
? [...(ctx.tags || []), ...(ctx.softTags || [])]
: []
const wasRevalidated = combinedTags.some((tag) => {
if (this.revalidatedTags.includes(tag)) {
return true
// When revalidate tag is called we don't return stale data so it's
// updated right away.
if (combinedTags.some((tag) => this.revalidatedTags.includes(tag))) {
if (FileSystemCache.debug) {
console.log('FileSystemCache: was revalidated', combinedTags)
}
return null
}
if (isStale(combinedTags, data.lastModified)) {
if (FileSystemCache.debug) {
console.log('FileSystemCache: stale tags', combinedTags)
}
return isStale([tag], data?.lastModified || Date.now())
})
// When revalidate tag is called we don't return
// stale data so it's updated right away
if (wasRevalidated) {
data = undefined
return null
}
}
......@@ -325,7 +344,7 @@ export default class FileSystemCache implements CacheHandler {
})
if (FileSystemCache.debug) {
console.log('set', key)
console.log('FileSystemCache: set', key)
}
if (!this.flushToDisk || !data) return
......
......@@ -15,12 +15,12 @@ import {
type SetIncrementalResponseCacheContext,
} from '../../response-cache'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import FileSystemCache from './file-system-cache'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import {
CACHE_ONE_YEAR,
NEXT_CACHE_TAGS_HEADER,
PRERENDER_REVALIDATE_HEADER,
} from '../../../lib/constants'
import { toRoute } from '../to-route'
......@@ -35,6 +35,7 @@ import type { Revalidate } from '../cache-control'
import { getPreviouslyRevalidatedTags } from '../../server-utils'
import { workAsyncStorage } from '../../app-render/work-async-storage.external'
import { DetachedPromise } from '../../../lib/detached-promise'
import { isStale as isTagsStale } from './tags-manifest.external'
export interface CacheHandlerContext {
fs?: CacheFs
......@@ -49,7 +50,7 @@ export interface CacheHandlerContext {
}
export interface CacheHandlerValue {
lastModified?: number
lastModified: number
age?: number
cacheState?: string
value: IncrementalCacheValue | null
......@@ -89,8 +90,8 @@ export class IncrementalCache implements IncrementalCacheType {
readonly allowedRevalidateHeaderKeys?: string[]
readonly minimalMode?: boolean
readonly fetchCacheKeyPrefix?: string
readonly revalidatedTags?: string[]
readonly isOnDemandRevalidate?: boolean
readonly revalidatedTags?: readonly string[]
private static readonly debug: boolean =
!!process.env.NEXT_PRIVATE_DEBUG_CACHE
......@@ -145,13 +146,16 @@ export class IncrementalCache implements IncrementalCacheType {
} else {
if (fs && serverDistDir) {
if (IncrementalCache.debug) {
console.log('using filesystem cache handler')
console.log('IncrementalCache: using filesystem cache handler')
}
CurCacheHandler = FileSystemCache
}
}
} else if (IncrementalCache.debug) {
console.log('using custom cache handler', CurCacheHandler.name)
console.log(
'IncrementalCache: using custom cache handler',
CurCacheHandler.name
)
}
if (process.env.__NEXT_TEST_MAX_ISR_CACHE) {
......@@ -179,7 +183,7 @@ export class IncrementalCache implements IncrementalCacheType {
}
if (minimalMode) {
revalidatedTags = getPreviouslyRevalidatedTags(
revalidatedTags = this.revalidatedTags = getPreviouslyRevalidatedTags(
requestHeaders,
this.prerenderManifest?.preview?.previewModeId
)
......@@ -243,7 +247,7 @@ export class IncrementalCache implements IncrementalCacheType {
const lock = this.locks.get(cacheKey)
if (IncrementalCache.debug) {
console.log('lock get', cacheKey, !!lock)
console.log('IncrementalCache: lock get', cacheKey, !!lock)
}
// If no lock exists, we can proceed to acquire it
......@@ -258,7 +262,7 @@ export class IncrementalCache implements IncrementalCacheType {
const { resolve, promise } = new DetachedPromise<void>()
if (IncrementalCache.debug) {
console.log('successfully locked', cacheKey)
console.log('IncrementalCache: successfully locked', cacheKey)
}
// Store the lock promise in the locks map
......@@ -430,7 +434,17 @@ export class IncrementalCache implements IncrementalCacheType {
if (resumeDataCache) {
const memoryCacheData = resumeDataCache.fetch.get(cacheKey)
if (memoryCacheData?.kind === CachedRouteKind.FETCH) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:hit', cacheKey)
}
return { isStale: false, value: memoryCacheData }
} else if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:miss', cacheKey)
}
} else {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:no-resume-data')
}
}
}
......@@ -474,9 +488,34 @@ export class IncrementalCache implements IncrementalCacheType {
workStore?.pendingRevalidatedTags?.includes(tag)
)
) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: stale tag', cacheKey)
}
return null
}
// As we're able to get the cache entry for this fetch, and the prerender
// resume data cache (RDC) is available, it must have been populated by a
// previous fetch, but was not yet present in the in-memory cache. This
// could be the case when performing multiple renders in parallel during
// build time where we de-duplicate the fetch calls.
//
// We add it to the RDC so that the next fetch call will be able to use it
// and it won't have to reach into the fetch cache implementation.
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
const prerenderResumeDataCache =
getPrerenderResumeDataCache(workUnitStore)
if (prerenderResumeDataCache) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:set', cacheKey)
}
prerenderResumeDataCache.fetch.set(cacheKey, cacheData.value)
}
}
const revalidate = ctx.revalidate || cacheData.value.revalidate
const age =
(performance.timeOrigin +
......@@ -507,17 +546,35 @@ export class IncrementalCache implements IncrementalCacheType {
isStale = -1
revalidateAfter = -1 * CACHE_ONE_YEAR
} else {
const now = performance.timeOrigin + performance.now()
const lastModified = cacheData?.lastModified || now
revalidateAfter = this.calculateRevalidate(
cacheKey,
cacheData?.lastModified || performance.timeOrigin + performance.now(),
lastModified,
this.dev ?? false,
ctx.isFallback
)
isStale =
revalidateAfter !== false &&
revalidateAfter < performance.timeOrigin + performance.now()
? true
: undefined
revalidateAfter !== false && revalidateAfter < now ? true : undefined
// If the stale time couldn't be determined based on the revalidation
// time, we check if the tags are stale.
if (
isStale === undefined &&
(cacheData?.value?.kind === CachedRouteKind.APP_PAGE ||
cacheData?.value?.kind === CachedRouteKind.APP_ROUTE)
) {
const tagsHeader = cacheData.value.headers?.[NEXT_CACHE_TAGS_HEADER]
if (typeof tagsHeader === 'string') {
const cacheTags = tagsHeader.split(',')
if (cacheTags.length > 0 && isTagsStale(cacheTags, lastModified)) {
isStale = -1
}
}
}
}
if (cacheData) {
......@@ -575,6 +632,10 @@ export class IncrementalCache implements IncrementalCacheType {
? getPrerenderResumeDataCache(workUnitStore)
: null
if (prerenderResumeDataCache) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: rdc:set', pathname)
}
prerenderResumeDataCache.fetch.set(pathname, data)
}
}
......
......@@ -377,7 +377,6 @@ export async function startServer(
appUrl,
envInfo,
experimentalFeatures,
maxExperimentalFeatures: 3,
})
Log.event(`Starting...`)
......
......@@ -6,9 +6,13 @@ import type { BaseNextRequest } from './base-http'
import type { CloneableBody } from './body-streams'
import type { RouteMatch } from './route-matches/route-match'
import type { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
import type { ServerComponentsHmrCache } from './response-cache'
import type {
ResponseCacheEntry,
ServerComponentsHmrCache,
} from './response-cache'
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'
import type { OpaqueFallbackRouteParams } from './request/fallback-params'
import type { IncrementalCache } from './lib/incremental-cache'
// FIXME: (wyattjoh) this is a temporary solution to allow us to pass data between bundled modules
export const NEXT_REQUEST_META = Symbol.for('NextInternalRequestMeta')
......@@ -69,7 +73,7 @@ export interface RequestMeta {
/**
* The incremental cache to use for the request.
*/
incrementalCache?: any
incrementalCache?: IncrementalCache
/**
* The server components HMR cache, only for dev.
......@@ -119,10 +123,25 @@ export interface RequestMeta {
/**
* If provided, this will be called when a response cache entry was generated
* or looked up in the cache.
*
* @deprecated Use `onCacheEntryV2` instead.
*/
onCacheEntry?: (
cacheEntry: any,
requestMeta: any
cacheEntry: ResponseCacheEntry,
requestMeta: {
url: string | undefined
}
) => Promise<boolean | void> | boolean | void
/**
* If provided, this will be called when a response cache entry was generated
* or looked up in the cache.
*/
onCacheEntryV2?: (
cacheEntry: ResponseCacheEntry,
requestMeta: {
url: string | undefined
}
) => Promise<boolean | void> | boolean | void
/**
......
......@@ -188,6 +188,15 @@ export type ResponseGenerator = (state: {
previousCacheEntry?: IncrementalResponseCacheEntry | null
isRevalidating?: boolean
span?: any
/**
* When true, this indicates that the response generator is being called in a
* context where the response must be generated statically.
*
* CRITICAL: This should only currently be used when revalidating due to a
* dynamic RSC request.
*/
forceStaticRender?: boolean
}) => Promise<ResponseCacheEntry | null>
export const enum IncrementalCacheKind {
......@@ -219,6 +228,11 @@ export interface GetIncrementalResponseCacheContext {
* True if this is a fallback request.
*/
isFallback: boolean
/**
* True if stale data is allowed to be returned.
*/
allowStale?: boolean
}
export interface SetIncrementalFetchCacheContext {
......
......@@ -67,6 +67,21 @@ const addCacheBustingSearchParam = (
return url.pathname + url.search
}
/**
* Expects that the cache-control header contains the given directives in any
* order.
*
* @param header The cache-control header to check.
* @param directives The directives to expect.
*/
const expectDirectives = (header: string, directives: string[]) => {
const split = header.split(',').map((directive) => directive.trim())
for (const directive of directives) {
expect(split).toContain(directive)
}
expect(split.length).toEqual(directives.length)
}
describe('ppr-full', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
......@@ -107,6 +122,32 @@ describe('ppr-full', () => {
await res.text()
})
it('should allow soft navigations to and from the / page', async () => {
const browser = await next.browser('/')
await browser.waitForElementByCss(`[data-pathname="/"]`)
// Add a window var so we can detect if there was a full navigation.
const now = Date.now()
await browser.eval(`window.beforeNav = ${now}`)
// Navigate to the page and wait for the page to load.
await browser.elementByCss(`a[href="${pathname}"]`).click()
await browser.waitForElementByCss(`[data-pathname="${pathname}"]`)
// Ensure we did a client navigation and not a full page navigation.
let beforeNav = await browser.eval('window.beforeNav')
expect(beforeNav).toBe(now)
// Navigate back to the home page and wait for the page to load.
await browser.elementByCss(`a[href="/"]`).click()
await browser.waitForElementByCss(`[data-pathname="/"]`)
// Ensure we did a client navigation and not a full page navigation.
beforeNav = await browser.eval('window.beforeNav')
expect(beforeNav).toBe(now)
})
it('should allow navigations to and from a pages/ page', async () => {
const browser = await next.browser(pathname)
......@@ -491,9 +532,11 @@ describe('ppr-full', () => {
}
if (isNextDeploy) {
expect(res.headers.get('cache-control')).toEqual(
'public, max-age=0, must-revalidate'
)
expectDirectives(res.headers.get('cache-control') || '', [
'public',
'max-age=0',
'must-revalidate',
])
}
if (signal === 'redirect()') {
......@@ -551,9 +594,11 @@ describe('ppr-full', () => {
expect(res.headers.get('content-type')).toEqual('text/x-component')
if (isNextDeploy) {
expect(res.headers.get('cache-control')).toEqual(
'public, max-age=0, must-revalidate'
)
expectDirectives(res.headers.get('cache-control') || '', [
'public',
'max-age=0',
'must-revalidate',
])
} else {
expect(res.headers.get('cache-control')).toEqual(
revalidate === undefined
......@@ -602,16 +647,23 @@ describe('ppr-full', () => {
headers
)
const res = await next.fetch(urlWithCacheBusting, {
let res = await next.fetch(urlWithCacheBusting, {
headers,
})
expect(res.status).toEqual(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
expect(res.headers.get('cache-control')).toEqual(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
expectDirectives(res.headers.get('cache-control') || '', [
'private',
'no-store',
'no-cache',
'max-age=0',
'must-revalidate',
])
if (isNextDeploy) {
expect(res.headers.get('x-vercel-cache')).toBe('MISS')
expect(res.headers.get('x-vercel-cache')).toMatch(
/MISS|HIT|PRERENDER/
)
} else {
expect(res.headers.get('x-nextjs-cache')).toEqual(null)
}
......
......@@ -351,7 +351,8 @@
"test/production/app-dir/subresource-integrity/subresource-integrity.test.ts",
"test/production/app-dir/typed-routes-with-webpack-worker/typed-routes-with-webpack-worker.test.ts",
"test/production/app-dir/unexpected-error/unexpected-error.test.ts",
"test/production/app-dir/worker-restart/worker-restart.test.ts"
"test/production/app-dir/worker-restart/worker-restart.test.ts",
"test/production/app-dir/resume-data-cache/resume-data-cache.test.ts"
]
}
}
......@@ -2431,6 +2431,7 @@ const runTests = (isDev = false) => {
"clientParamParsing": false,
"contentTypeHeader": "text/x-component",
"didPostponeHeader": "x-nextjs-postponed",
"dynamicRSCPrerender": false,
"header": "rsc",
"prefetchHeader": "next-router-prefetch",
"prefetchSegmentDirSuffix": ".segments",
......
......@@ -1474,6 +1474,7 @@ function runTests({ dev }) {
"clientParamParsing": false,
"contentTypeHeader": "text/x-component",
"didPostponeHeader": "x-nextjs-postponed",
"dynamicRSCPrerender": false,
"header": "rsc",
"prefetchHeader": "next-router-prefetch",
"prefetchSegmentDirSuffix": ".segments",
......
......@@ -175,7 +175,8 @@
"test/e2e/app-dir/use-cache-with-server-function-props/use-cache-with-server-function-props.test.ts",
"test/integration/app-dir-export/**/*",
"test/production/app-dir/build-output-tree-view/build-output-tree-view.test.ts",
"test/production/app-dir/global-default-cache-handler/global-default-cache-handler.test.ts"
"test/production/app-dir/global-default-cache-handler/global-default-cache-handler.test.ts",
"test/production/app-dir/resume-data-cache/resume-data-cache.test.ts"
]
}
}
import React, { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import React, { Suspense } from 'react'
import { connection } from 'next/server'
import { unstable_cacheTag } from 'next/cache'
async function getRandomNumber() {
'use cache'
unstable_cacheTag('test')
return Math.random()
}
async function DynamicComponent() {
await connection()
return null
}
export default async function Page() {
const randomNumber = await getRandomNumber()
const anotherRandomNumber = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache', next: { tags: ['test'] } }
).then((res) => res.text())
return (
<>
<p id="random-number">{randomNumber}</p>
<p id="another-random-number">{anotherRandomNumber}</p>
<Suspense>
<DynamicComponent />
</Suspense>
</>
)
}
import { revalidateTag } from 'next/cache'
export function POST() {
revalidateTag('test')
return new Response(null, { status: 200 })
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
cacheComponents: true,
clientSegmentCache: true,
clientParamParsing: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { computeCacheBustingSearchParam } from 'next/dist/shared/lib/router/utils/cache-busting-search-param'
describe('resume-data-cache', () => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it.each([
{ name: 'use cache', id: 'random-number' },
{ name: 'fetch cache', id: 'another-random-number' },
])(
'should have consistent data between static and dynamic renders with $name',
async ({ id }) => {
// First render the page statically, getting the random number from the
// HTML.
let $ = await next.render$('/')
const first = $(`p#${id}`).text()
// Then get the Prefetch RSC and validate that it also contains the same
// random number.
await retry(async () => {
const url = new URL('/', 'http://localhost')
url.searchParams.set(
'_rsc',
computeCacheBustingSearchParam('1', '/__PAGE__', undefined, undefined)
)
const rsc = await next
.fetch(url.toString(), {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
'Next-Router-Segment-Prefetch': '/__PAGE__',
},
})
.then((res) => res.text())
expect(rsc).toContain(first)
})
// Then get the dynamic RSC and validate that it also contains the same
// random number.
await retry(async () => {
const rsc = await next
.fetch('/', {
headers: {
RSC: '1',
},
})
.then((res) => res.text())
expect(rsc).toContain(first)
})
// Then revalidate the page. Note: Dynamic RSC requests don't trigger
// actual revalidation - they only mark tags as needing revalidation.
// The actual revalidation only occurs when accessing a static resource again.
await next.fetch('/revalidate', { method: 'POST' })
// Then get the dynamic RSC again and validate that it still contains the
// same random number. The first request will get the stale data, but the
// second request will get the fresh data as it'll eventually have
// revalidated.
// NOTE: this current doesn't work on Next.js Deploy, as the dynamic RSC
// requests are not able to revalidate the page.
if (!isNextDeploy) {
const rsc = await next
.fetch('/', {
headers: {
RSC: '1',
},
})
.then((res) => res.text())
expect(rsc).toContain(first)
}
// We then expect after the background revalidation has been completed,
// the dynamic RSC to get the fresh data.
await retry(async () => {
const rsc = await next
.fetch('/', {
headers: {
RSC: '1',
},
})
.then((res) => res.text())
expect(rsc).not.toContain(first)
})
// This proves that the dynamic RSC was able to use the resume data cache
// (RDC) from the static render to ensure that the data is consistent
// between the static and dynamic renders. Let's now try to render the
// page statically and see that the random number changes.
$ = await next.render$('/')
const random2 = $(`p#${id}`).text()
expect(random2).not.toBe(first)
// Then get the Prefetch RSC and validate that it also contains the new
// random number.
await retry(async () => {
const rsc = await next
.fetch('/', {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
},
})
.then((res) => res.text())
expect(rsc).toContain(random2)
})
// Then get the dynamic RSC again and validate that it also contains the
// new random number.
await retry(async () => {
const rsc = await next
.fetch('/', {
headers: {
RSC: '1',
},
})
.then((res) => res.text())
expect(rsc).toContain(random2)
})
// This proves that the dynamic RSC was able to use the resume data cache
// (RDC) from the static render to ensure that the data is consistent
// between the static and dynamic renders.
}
)
})
import { headers } from 'next/headers'
export default async function Page({ params }) {
const data = headers()
const data = await headers()
return (
<>
......
import { Suspense } from 'react'
import { unstable_noStore } from 'next/cache'
import { connection } from 'next/server'
export function generateStaticParams() {
return [{ slug: 'first-cookie' }]
return [{ slug: 'first-cookie' }, { slug: 'second-cookie' }]
}
function Postpone({ children }) {
unstable_noStore()
async function Postpone({ children }) {
await connection()
return children
}
export default async function Page({ params }) {
const random = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{ cache: 'force-cache' }
).then((res) => res.text())
return (
<>
<p id="random">{random}</p>
<Suspense>
<Postpone>
<p id="page">/rewrite/[slug]</p>
......
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