Unverified Commit 2c95fefd authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[dynamicIO] Use filled Resume Data Cache for final-phase prerenders (#79743)

When a route with dynamic params is prerendered using defined params
from `generateStaticParams`, the filled Resume Data Cache is now used
for the final-phase prerender of the matching optional fallback shell.

This ensures that the fallback shell can reuse existing cache entries,
which partially mitigates the performance hit we accepted by splitting
up the prerendering into two phases.

Furthermore, it will allow us to short-circuit fallback params access in
`"use cache"` functions. Instead of having to wait for the timeout
error, we will be able to regard cache misses (excluding cached pages
and layouts, whose params access is already handled swiftly) to be
caused by including the params in the cache key, if
`allowEmptyFallbackShell` is `true`.
parent c6775aef
...@@ -365,9 +365,9 @@ export async function handler( ...@@ -365,9 +365,9 @@ export async function handler(
// If the warmup is successful, we should use the resume data // If the warmup is successful, we should use the resume data
// cache from the warmup. // cache from the warmup.
if (warmup.metadata.devRenderResumeDataCache) { if (warmup.metadata.renderResumeDataCache) {
context.renderOpts.devRenderResumeDataCache = context.renderOpts.renderResumeDataCache =
warmup.metadata.devRenderResumeDataCache warmup.metadata.renderResumeDataCache
} }
} }
} }
......
...@@ -560,7 +560,8 @@ async function exportAppImpl( ...@@ -560,7 +560,8 @@ async function exportAppImpl(
const exportPagesInBatches = async ( const exportPagesInBatches = async (
worker: StaticWorker, worker: StaticWorker,
exportPaths: ExportPathEntry[] exportPaths: ExportPathEntry[],
renderResumeDataCachesByPage?: Record<string, string>
): Promise<ExportPagesResult> => { ): Promise<ExportPagesResult> => {
// Batch filtered pages into smaller batches, and call the export worker on // Batch filtered pages into smaller batches, and call the export worker on
// each batch. We've set a default minimum of 25 pages per batch to ensure // each batch. We've set a default minimum of 25 pages per batch to ensure
...@@ -607,6 +608,7 @@ async function exportAppImpl( ...@@ -607,6 +608,7 @@ async function exportAppImpl(
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize, cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
fetchCache: true, fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix, fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
renderResumeDataCachesByPage,
}) })
) )
) )
...@@ -641,7 +643,31 @@ async function exportAppImpl( ...@@ -641,7 +643,31 @@ async function exportAppImpl(
const results = await exportPagesInBatches(worker, initialPhaseExportPaths) const results = await exportPagesInBatches(worker, initialPhaseExportPaths)
if (finalPhaseExportPaths.length > 0) { if (finalPhaseExportPaths.length > 0) {
results.push(...(await exportPagesInBatches(worker, finalPhaseExportPaths))) const renderResumeDataCachesByPage: Record<string, string> = {}
for (const { page, result } of results) {
if (!result) {
continue
}
if ('renderResumeDataCache' in result && result.renderResumeDataCache) {
// The last RDC for each page is used. We only need one. It should have
// all the entries that the fallback shell also needs. We don't need to
// merge them per page.
renderResumeDataCachesByPage[page] = result.renderResumeDataCache
// Remove the RDC string from the result so that it can be garbage
// collected, when there are more results for the same page.
result.renderResumeDataCache = undefined
}
}
const finalPhaseResults = await exportPagesInBatches(
worker,
finalPhaseExportPaths,
renderResumeDataCachesByPage
)
results.push(...finalPhaseResults)
} }
let hadValidationError = false let hadValidationError = false
......
...@@ -29,6 +29,7 @@ import { AfterRunner } from '../../server/after/run-with-after' ...@@ -29,6 +29,7 @@ import { AfterRunner } from '../../server/after/run-with-after'
import type { RequestLifecycleOpts } from '../../server/base-server' import type { RequestLifecycleOpts } from '../../server/base-server'
import type { AppSharedContext } from '../../server/app-render/app-render' import type { AppSharedContext } from '../../server/app-render/app-render'
import type { MultiFileWriter } from '../../lib/multi-file-writer' import type { MultiFileWriter } from '../../lib/multi-file-writer'
import { stringifyResumeDataCache } from '../../server/resume-data-cache/resume-data-cache'
/** /**
* Renders & exports a page associated with the /app directory * Renders & exports a page associated with the /app directory
...@@ -92,6 +93,7 @@ export async function exportAppPage( ...@@ -92,6 +93,7 @@ export async function exportAppPage(
fetchTags, fetchTags,
fetchMetrics, fetchMetrics,
segmentData, segmentData,
renderResumeDataCache,
} = metadata } = metadata
// Ensure we don't postpone without having PPR enabled. // Ensure we don't postpone without having PPR enabled.
...@@ -220,6 +222,9 @@ export async function exportAppPage( ...@@ -220,6 +222,9 @@ export async function exportAppPage(
hasPostponed: Boolean(postponed), hasPostponed: Boolean(postponed),
cacheControl, cacheControl,
fetchMetrics, fetchMetrics,
renderResumeDataCache: renderResumeDataCache
? await stringifyResumeDataCache(renderResumeDataCache)
: undefined,
} }
} catch (err) { } catch (err) {
if (!isDynamicUsageError(err)) { if (!isDynamicUsageError(err)) {
......
...@@ -12,6 +12,7 @@ import type { ...@@ -12,6 +12,7 @@ import type {
} from '../build/turborepo-access-trace' } from '../build/turborepo-access-trace'
import type { FetchMetrics } from '../server/base-http' import type { FetchMetrics } from '../server/base-http'
import type { RouteMetadata } from './routes/types' import type { RouteMetadata } from './routes/types'
import type { RenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
export interface AmpValidation { export interface AmpValidation {
page: string page: string
...@@ -40,6 +41,7 @@ export interface ExportPagesInput { ...@@ -40,6 +41,7 @@ export interface ExportPagesInput {
cacheHandler: string | undefined cacheHandler: string | undefined
fetchCacheKeyPrefix: string | undefined fetchCacheKeyPrefix: string | undefined
options: ExportAppOptions options: ExportAppOptions
renderResumeDataCachesByPage: Record<string, string> | undefined
} }
export interface ExportPageInput { export interface ExportPageInput {
...@@ -62,6 +64,7 @@ export interface ExportPageInput { ...@@ -62,6 +64,7 @@ export interface ExportPageInput {
nextConfigOutput?: NextConfigComplete['output'] nextConfigOutput?: NextConfigComplete['output']
enableExperimentalReact?: boolean enableExperimentalReact?: boolean
sriEnabled: boolean sriEnabled: boolean
renderResumeDataCache: RenderResumeDataCache | undefined
} }
export type ExportRouteResult = export type ExportRouteResult =
...@@ -73,6 +76,7 @@ export type ExportRouteResult = ...@@ -73,6 +76,7 @@ export type ExportRouteResult =
hasEmptyStaticShell?: boolean hasEmptyStaticShell?: boolean
hasPostponed?: boolean hasPostponed?: boolean
fetchMetrics?: FetchMetrics fetchMetrics?: FetchMetrics
renderResumeDataCache?: string
} }
| { | {
error: boolean error: boolean
......
...@@ -49,6 +49,7 @@ import { isStaticGenBailoutError } from '../client/components/static-generation- ...@@ -49,6 +49,7 @@ import { isStaticGenBailoutError } from '../client/components/static-generation-
import type { PagesRenderContext, PagesSharedContext } from '../server/render' import type { PagesRenderContext, PagesSharedContext } from '../server/render'
import type { AppSharedContext } from '../server/app-render/app-render' import type { AppSharedContext } from '../server/app-render/app-render'
import { MultiFileWriter } from '../lib/multi-file-writer' import { MultiFileWriter } from '../lib/multi-file-writer'
import { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
const envConfig = const envConfig =
require('../shared/lib/runtime-config.external') as typeof import('../shared/lib/runtime-config.external') require('../shared/lib/runtime-config.external') as typeof import('../shared/lib/runtime-config.external')
...@@ -86,6 +87,7 @@ async function exportPageImpl( ...@@ -86,6 +87,7 @@ async function exportPageImpl(
renderOpts: commonRenderOpts, renderOpts: commonRenderOpts,
outDir: commonOutDir, outDir: commonOutDir,
buildId, buildId,
renderResumeDataCache,
} = input } = input
if (enableExperimentalReact) { if (enableExperimentalReact) {
...@@ -276,6 +278,7 @@ async function exportPageImpl( ...@@ -276,6 +278,7 @@ async function exportPageImpl(
...commonRenderOpts.experimental, ...commonRenderOpts.experimental,
isRoutePPREnabled, isRoutePPREnabled,
}, },
renderResumeDataCache,
} }
if (hasNextSupport) { if (hasNextSupport) {
...@@ -355,6 +358,7 @@ export async function exportPages( ...@@ -355,6 +358,7 @@ export async function exportPages(
renderOpts, renderOpts,
nextConfig, nextConfig,
options, options,
renderResumeDataCachesByPage = {},
} = input } = input
if (nextConfig.experimental.enablePrerenderSourceMaps) { if (nextConfig.experimental.enablePrerenderSourceMaps) {
...@@ -399,6 +403,10 @@ export async function exportPages( ...@@ -399,6 +403,10 @@ export async function exportPages(
// Also tests for `inspect-brk` // Also tests for `inspect-brk`
process.env.NODE_OPTIONS?.includes('--inspect') process.env.NODE_OPTIONS?.includes('--inspect')
const renderResumeDataCache = renderResumeDataCachesByPage[page]
? createRenderResumeDataCache(renderResumeDataCachesByPage[page])
: undefined
while (attempt < maxAttempts) { while (attempt < maxAttempts) {
try { try {
result = await Promise.race<ExportPageResult | undefined>([ result = await Promise.race<ExportPageResult | undefined>([
...@@ -423,6 +431,7 @@ export async function exportPages( ...@@ -423,6 +431,7 @@ export async function exportPages(
enableExperimentalReact: needsExperimentalReact(nextConfig), enableExperimentalReact: needsExperimentalReact(nextConfig),
sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm), sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),
buildId: input.buildId, buildId: input.buildId,
renderResumeDataCache,
}), }),
hasDebuggerAttached hasDebuggerAttached
? // With a debugger attached, exporting can take infinitely if we paused script execution. ? // With a debugger attached, exporting can take infinitely if we paused script execution.
...@@ -591,15 +600,9 @@ async function exportPage( ...@@ -591,15 +600,9 @@ async function exportPage(
// Otherwise we can return the result. // Otherwise we can return the result.
return { return {
...result,
duration: Date.now() - start, duration: Date.now() - start,
ampValidations: result.ampValidations,
cacheControl: result.cacheControl,
metadata: result.metadata,
ssgNotFound: result.ssgNotFound,
hasEmptyStaticShell: result.hasEmptyStaticShell,
hasPostponed: result.hasPostponed,
turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(), turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),
fetchMetrics: result.fetchMetrics,
} }
} }
......
...@@ -181,6 +181,8 @@ import { parseLoaderTree } from './parse-loader-tree' ...@@ -181,6 +181,8 @@ import { parseLoaderTree } from './parse-loader-tree'
import { import {
createPrerenderResumeDataCache, createPrerenderResumeDataCache,
createRenderResumeDataCache, createRenderResumeDataCache,
type PrerenderResumeDataCache,
type RenderResumeDataCache,
} from '../resume-data-cache/resume-data-cache' } from '../resume-data-cache/resume-data-cache'
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'
...@@ -714,6 +716,7 @@ async function warmupDevRender( ...@@ -714,6 +716,7 @@ async function warmupDevRender(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [], tags: [],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash: req.cookies[NEXT_HMR_REFRESH_HASH_COOKIE], hmrRefreshHash: req.cookies[NEXT_HMR_REFRESH_HASH_COOKIE],
} }
...@@ -750,7 +753,7 @@ async function warmupDevRender( ...@@ -750,7 +753,7 @@ async function warmupDevRender(
// lift the warmup pathway outside of renderToHTML... but for now this suffices // lift the warmup pathway outside of renderToHTML... but for now this suffices
return new FlightRenderResult('', { return new FlightRenderResult('', {
fetchMetrics: workStore.fetchMetrics, fetchMetrics: workStore.fetchMetrics,
devRenderResumeDataCache: createRenderResumeDataCache( renderResumeDataCache: createRenderResumeDataCache(
prerenderResumeDataCache prerenderResumeDataCache
), ),
}) })
...@@ -1493,12 +1496,15 @@ async function renderToHTMLOrFlightImpl( ...@@ -1493,12 +1496,15 @@ async function renderToHTMLOrFlightImpl(
} }
} }
if (response.renderResumeDataCache) {
metadata.renderResumeDataCache = response.renderResumeDataCache
}
return new RenderResult(await streamToString(response.stream), options) return new RenderResult(await streamToString(response.stream), options)
} else { } else {
// We're rendering dynamically // We're rendering dynamically
const renderResumeDataCache = const renderResumeDataCache =
renderOpts.devRenderResumeDataCache ?? renderOpts.renderResumeDataCache ?? postponedState?.renderResumeDataCache
postponedState?.renderResumeDataCache
const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment) const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment)
const requestStore = createRequestStoreForRender( const requestStore = createRequestStoreForRender(
...@@ -1696,7 +1702,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -1696,7 +1702,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
if ( if (
postponedState?.renderResumeDataCache && postponedState?.renderResumeDataCache &&
renderOpts.devRenderResumeDataCache renderOpts.renderResumeDataCache
) { ) {
throw new InvariantError( throw new InvariantError(
'postponed state and dev warmup immutable resume data cache should not be provided together' 'postponed state and dev warmup immutable resume data cache should not be provided together'
...@@ -2310,6 +2316,7 @@ async function spawnDynamicValidationInDev( ...@@ -2310,6 +2316,7 @@ async function spawnDynamicValidationInDev(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
} }
...@@ -2416,6 +2423,7 @@ async function spawnDynamicValidationInDev( ...@@ -2416,6 +2423,7 @@ async function spawnDynamicValidationInDev(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
} }
...@@ -2501,6 +2509,7 @@ async function spawnDynamicValidationInDev( ...@@ -2501,6 +2509,7 @@ async function spawnDynamicValidationInDev(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
} }
...@@ -2563,6 +2572,7 @@ async function spawnDynamicValidationInDev( ...@@ -2563,6 +2572,7 @@ async function spawnDynamicValidationInDev(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
} }
...@@ -2673,6 +2683,7 @@ type PrerenderToStreamResult = { ...@@ -2673,6 +2683,7 @@ type PrerenderToStreamResult = {
collectedExpire: number collectedExpire: number
collectedStale: number collectedStale: number
collectedTags: null | string[] collectedTags: null | string[]
renderResumeDataCache?: RenderResumeDataCache
} }
/** /**
...@@ -2866,11 +2877,22 @@ async function prerenderToStream( ...@@ -2866,11 +2877,22 @@ async function prerenderToStream(
// to cut the render off. // to cut the render off.
const cacheSignal = new CacheSignal() const cacheSignal = new CacheSignal()
// The resume data cache here should use a fresh instance as it's let resumeDataCache: RenderResumeDataCache | PrerenderResumeDataCache
// performing a fresh prerender. If we get to implementing the let renderResumeDataCache: RenderResumeDataCache | null = null
// prerendering of an already prerendered page, we should use the passed let prerenderResumeDataCache: PrerenderResumeDataCache | null = null
// resume data cache instead.
const prerenderResumeDataCache = createPrerenderResumeDataCache() if (renderOpts.renderResumeDataCache) {
// If a prefilled immutable render resume data cache is provided, e.g.
// when prerendering an optional fallback shell after having prerendered
// pages with defined params, we use this instead of a prerender resume
// data cache.
resumeDataCache = renderResumeDataCache =
renderOpts.renderResumeDataCache
} else {
// Otherwise we create a new mutable prerender resume data cache.
resumeDataCache = prerenderResumeDataCache =
createPrerenderResumeDataCache()
}
const initialServerPrerenderStore: PrerenderStore = (prerenderStore = { const initialServerPrerenderStore: PrerenderStore = (prerenderStore = {
type: 'prerender', type: 'prerender',
...@@ -2889,6 +2911,7 @@ async function prerenderToStream( ...@@ -2889,6 +2911,7 @@ async function prerenderToStream(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
}) })
...@@ -3011,6 +3034,7 @@ async function prerenderToStream( ...@@ -3011,6 +3034,7 @@ async function prerenderToStream(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
} }
...@@ -3096,6 +3120,7 @@ async function prerenderToStream( ...@@ -3096,6 +3120,7 @@ async function prerenderToStream(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
}) })
...@@ -3166,6 +3191,7 @@ async function prerenderToStream( ...@@ -3166,6 +3191,7 @@ async function prerenderToStream(
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
} }
...@@ -3267,13 +3293,12 @@ async function prerenderToStream( ...@@ -3267,13 +3293,12 @@ async function prerenderToStream(
metadata.postponed = await getDynamicHTMLPostponedState( metadata.postponed = await getDynamicHTMLPostponedState(
postponed, postponed,
fallbackRouteParams, fallbackRouteParams,
prerenderResumeDataCache resumeDataCache
) )
} else { } else {
// Dynamic Data case // Dynamic Data case
metadata.postponed = await getDynamicDataPostponedState( metadata.postponed =
prerenderResumeDataCache await getDynamicDataPostponedState(resumeDataCache)
)
} }
reactServerResult.consume() reactServerResult.consume()
return { return {
...@@ -3292,6 +3317,7 @@ async function prerenderToStream( ...@@ -3292,6 +3317,7 @@ async function prerenderToStream(
collectedExpire: finalServerPrerenderStore.expire, collectedExpire: finalServerPrerenderStore.expire,
collectedStale: selectStaleTime(finalServerPrerenderStore.stale), collectedStale: selectStaleTime(finalServerPrerenderStore.stale),
collectedTags: finalServerPrerenderStore.tags, collectedTags: finalServerPrerenderStore.tags,
renderResumeDataCache: createRenderResumeDataCache(resumeDataCache),
} }
} else { } else {
// Static case // Static case
...@@ -3355,6 +3381,7 @@ async function prerenderToStream( ...@@ -3355,6 +3381,7 @@ async function prerenderToStream(
collectedExpire: finalServerPrerenderStore.expire, collectedExpire: finalServerPrerenderStore.expire,
collectedStale: selectStaleTime(finalServerPrerenderStore.stale), collectedStale: selectStaleTime(finalServerPrerenderStore.stale),
collectedTags: finalServerPrerenderStore.tags, collectedTags: finalServerPrerenderStore.tags,
renderResumeDataCache: createRenderResumeDataCache(resumeDataCache),
} }
} }
} else if (experimental.isRoutePPREnabled) { } else if (experimental.isRoutePPREnabled) {
......
...@@ -62,14 +62,14 @@ export type PostponedState = ...@@ -62,14 +62,14 @@ export type PostponedState =
export async function getDynamicHTMLPostponedState( export async function getDynamicHTMLPostponedState(
data: object, data: object,
fallbackRouteParams: FallbackRouteParams | null, fallbackRouteParams: FallbackRouteParams | null,
prerenderResumeDataCache: PrerenderResumeDataCache resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache
): Promise<string> { ): Promise<string> {
if (!fallbackRouteParams || fallbackRouteParams.size === 0) { if (!fallbackRouteParams || fallbackRouteParams.size === 0) {
const postponedString = JSON.stringify(data) const postponedString = JSON.stringify(data)
// Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>` // Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>`
return `${postponedString.length}:${postponedString}${await stringifyResumeDataCache( return `${postponedString.length}:${postponedString}${await stringifyResumeDataCache(
createRenderResumeDataCache(prerenderResumeDataCache) createRenderResumeDataCache(resumeDataCache)
)}` )}`
} }
...@@ -81,13 +81,13 @@ export async function getDynamicHTMLPostponedState( ...@@ -81,13 +81,13 @@ export async function getDynamicHTMLPostponedState(
const postponedString = `${replacementsString.length}${replacementsString}${dataString}` const postponedString = `${replacementsString.length}${replacementsString}${dataString}`
// Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>` // Serialized as `<postponedString.length>:<postponedString><renderResumeDataCache>`
return `${postponedString.length}:${postponedString}${await stringifyResumeDataCache(prerenderResumeDataCache)}` return `${postponedString.length}:${postponedString}${await stringifyResumeDataCache(resumeDataCache)}`
} }
export async function getDynamicDataPostponedState( export async function getDynamicDataPostponedState(
prerenderResumeDataCache: PrerenderResumeDataCache resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache
): Promise<string> { ): Promise<string> {
return `4:null${await stringifyResumeDataCache(createRenderResumeDataCache(prerenderResumeDataCache))}` return `4:null${await stringifyResumeDataCache(createRenderResumeDataCache(resumeDataCache))}`
} }
export function parsePostponedState( export function parsePostponedState(
......
...@@ -250,10 +250,11 @@ export interface RenderOptsPartial { ...@@ -250,10 +250,11 @@ export interface RenderOptsPartial {
shouldWaitOnAllReady?: boolean shouldWaitOnAllReady?: boolean
/** /**
* The resume data cache that was generated for this partially prerendered * A prefilled resume data cache. This was either generated for this page
* page during dev warmup. * during dev warmup, or when a page with defined params was previously
* prerendered, and now its matching optional fallback shell is prerendered.
*/ */
devRenderResumeDataCache?: RenderResumeDataCache renderResumeDataCache?: RenderResumeDataCache
/** /**
* When true, the page will be rendered using the static rendering to detect * When true, the page will be rendered using the static rendering to detect
......
...@@ -116,10 +116,18 @@ export interface PrerenderStoreModern extends CommonWorkUnitStore { ...@@ -116,10 +116,18 @@ export interface PrerenderStoreModern extends CommonWorkUnitStore {
tags: null | string[] tags: null | string[]
/** /**
* The resume data cache for this prerender. * A mutable resume data cache for this prerender.
*/ */
prerenderResumeDataCache: PrerenderResumeDataCache | null 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
/** /**
* The HMR refresh hash is only provided in dev mode. It is needed for the dev * The HMR refresh hash is only provided in dev mode. It is needed for the dev
* warmup render to ensure that the cache keys will be identical for the * warmup render to ensure that the cache keys will be identical for the
...@@ -272,21 +280,24 @@ export function getPrerenderResumeDataCache( ...@@ -272,21 +280,24 @@ export function getPrerenderResumeDataCache(
export function getRenderResumeDataCache( export function getRenderResumeDataCache(
workUnitStore: WorkUnitStore workUnitStore: WorkUnitStore
): RenderResumeDataCache | null { ): RenderResumeDataCache | null {
if ( switch (workUnitStore.type) {
workUnitStore.type !== 'prerender-legacy' && case 'request':
workUnitStore.type !== 'cache' &&
workUnitStore.type !== 'unstable-cache'
) {
if (workUnitStore.type === 'request') {
return workUnitStore.renderResumeDataCache return workUnitStore.renderResumeDataCache
} case 'prerender':
case 'prerender-client':
// We return the mutable resume data cache here as an immutable version of if (workUnitStore.renderResumeDataCache) {
// the cache as it can also be used for reading. // If we are in a prerender, we might have a render resume data cache
return workUnitStore.prerenderResumeDataCache // 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
default:
return null
} }
return null
} }
export function getHmrRefreshHash( export function getHmrRefreshHash(
......
...@@ -2774,9 +2774,9 @@ export default abstract class Server< ...@@ -2774,9 +2774,9 @@ export default abstract class Server<
// If the warmup is successful, we should use the resume data // If the warmup is successful, we should use the resume data
// cache from the warmup. // cache from the warmup.
if (warmup.metadata.devRenderResumeDataCache) { if (warmup.metadata.renderResumeDataCache) {
renderOpts.devRenderResumeDataCache = renderOpts.renderResumeDataCache =
warmup.metadata.devRenderResumeDataCache warmup.metadata.renderResumeDataCache
} }
} }
......
...@@ -38,10 +38,12 @@ export type AppPageRenderResultMetadata = { ...@@ -38,10 +38,12 @@ export type AppPageRenderResultMetadata = {
segmentData?: Map<string, Buffer> segmentData?: Map<string, Buffer>
/** /**
* In development, the cache is warmed up before the render. This is attached * In development, the resume data cache is warmed up before the render. This
* to the metadata so that it can be used during the render. * is attached to the metadata so that it can be used during the render. When
* prerendering, the filled resume data cache is also attached to the metadata
* so that it can be used when prerendering matching fallback shells.
*/ */
devRenderResumeDataCache?: RenderResumeDataCache renderResumeDataCache?: RenderResumeDataCache
} }
export type PagesRenderResultMetadata = { export type PagesRenderResultMetadata = {
......
...@@ -157,10 +157,14 @@ export function createPrerenderResumeDataCache(): PrerenderResumeDataCache { ...@@ -157,10 +157,14 @@ export function createPrerenderResumeDataCache(): PrerenderResumeDataCache {
* 1. An existing prerender cache instance * 1. An existing prerender cache instance
* 2. A serialized cache string * 2. A serialized cache string
* *
* @param renderResumeDataCache - A RenderResumeDataCache instance to be used directly
* @param prerenderResumeDataCache - A PrerenderResumeDataCache instance to convert to immutable * @param prerenderResumeDataCache - A PrerenderResumeDataCache instance to convert to immutable
* @param persistedCache - A serialized cache string to parse * @param persistedCache - A serialized cache string to parse
* @returns An immutable RenderResumeDataCache instance * @returns An immutable RenderResumeDataCache instance
*/ */
export function createRenderResumeDataCache(
renderResumeDataCache: RenderResumeDataCache
): RenderResumeDataCache
export function createRenderResumeDataCache( export function createRenderResumeDataCache(
prerenderResumeDataCache: PrerenderResumeDataCache prerenderResumeDataCache: PrerenderResumeDataCache
): RenderResumeDataCache ): RenderResumeDataCache
...@@ -168,20 +172,23 @@ export function createRenderResumeDataCache( ...@@ -168,20 +172,23 @@ export function createRenderResumeDataCache(
persistedCache: string persistedCache: string
): RenderResumeDataCache ): RenderResumeDataCache
export function createRenderResumeDataCache( export function createRenderResumeDataCache(
prerenderResumeDataCacheOrPersistedCache: PrerenderResumeDataCache | string resumeDataCacheOrPersistedCache:
| RenderResumeDataCache
| PrerenderResumeDataCache
| string
): RenderResumeDataCache { ): RenderResumeDataCache {
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError( throw new InvariantError(
'`createRenderResumeDataCache` should not be called in edge runtime.' '`createRenderResumeDataCache` should not be called in edge runtime.'
) )
} else { } else {
if (typeof prerenderResumeDataCacheOrPersistedCache !== 'string') { if (typeof resumeDataCacheOrPersistedCache !== 'string') {
// If the cache is already a prerender cache, we can return it directly, // If the cache is already a prerender or render cache, we can return it
// we're just performing a type change. // directly. For the former, we're just performing a type change.
return prerenderResumeDataCacheOrPersistedCache return resumeDataCacheOrPersistedCache
} }
if (prerenderResumeDataCacheOrPersistedCache === 'null') { if (resumeDataCacheOrPersistedCache === 'null') {
return { return {
cache: new Map(), cache: new Map(),
fetch: new Map(), fetch: new Map(),
...@@ -197,7 +204,7 @@ export function createRenderResumeDataCache( ...@@ -197,7 +204,7 @@ export function createRenderResumeDataCache(
const json: ResumeStoreSerialized = JSON.parse( const json: ResumeStoreSerialized = JSON.parse(
inflateSync( inflateSync(
Buffer.from(prerenderResumeDataCacheOrPersistedCache, 'base64') Buffer.from(resumeDataCacheOrPersistedCache, 'base64')
).toString('utf-8') ).toString('utf-8')
) )
......
...@@ -395,7 +395,9 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -395,7 +395,9 @@ export class AppRouteRouteModule extends RouteModule<
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
// TODO: Shouldn't we provide an RDC here?
prerenderResumeDataCache: null, prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
}) })
...@@ -483,7 +485,9 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -483,7 +485,9 @@ export class AppRouteRouteModule extends RouteModule<
expire: INFINITE_CACHE, expire: INFINITE_CACHE,
stale: INFINITE_CACHE, stale: INFINITE_CACHE,
tags: [...implicitTags.tags], tags: [...implicitTags.tags],
// TODO: Shouldn't we provide an RDC here?
prerenderResumeDataCache: null, prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
}) })
......
...@@ -7,8 +7,8 @@ export default async function Layout({ children }) { ...@@ -7,8 +7,8 @@ export default async function Layout({ children }) {
return ( return (
<html> <html>
<body> <body>
<div id="layout"> <div id="root-layout">
Layout: {new Date().toISOString()} ({getSentinelValue()}) Root Layout: {new Date().toISOString()} ({getSentinelValue()})
</div> </div>
<Suspense fallback={<p>Loading...</p>}>{children}</Suspense> <Suspense fallback={<p>Loading...</p>}>{children}</Suspense>
</body> </body>
......
'use cache'
import { getSentinelValue } from '../../../sentinel'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
<p>This layout is explicitly not reading params.</p>
<div id="layout">
Layout: {new Date().toISOString()} ({getSentinelValue()})
</div>
<div>{children}</div>
</div>
)
}
...@@ -6,8 +6,8 @@ export default async function Layout({ children }) { ...@@ -6,8 +6,8 @@ export default async function Layout({ children }) {
return ( return (
<html> <html>
<body> <body>
<div id="layout"> <div id="root-layout">
Layout: {new Date().toISOString()} ({getSentinelValue()}) Root Layout: {new Date().toISOString()} ({getSentinelValue()})
</div> </div>
{children} {children}
</body> </body>
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { assertNoConsoleErrors } from 'next-test-utils'
describe('fallback-shells', () => { describe('fallback-shells', () => {
const { next, isNextDev, isNextDeploy, isNextStart } = nextTestSetup({ const { next, isNextDev, isNextDeploy, isNextStart } = nextTestSetup({
...@@ -28,14 +29,15 @@ describe('fallback-shells', () => { ...@@ -28,14 +29,15 @@ describe('fallback-shells', () => {
describe('and the params accessed in the cached page', () => { describe('and the params accessed in the cached page', () => {
it('resumes a postponed fallback shell', async () => { it('resumes a postponed fallback shell', async () => {
const { browser, response } = await next.browserWithResponse( const { browser, response } = await next.browserWithResponse(
'/with-cached-io/with-suspense/params-in-page/bar' '/with-cached-io/with-suspense/params-in-page/bar',
{ pushErrorAsConsoleLog: true }
) )
const lastModified = await browser.elementById('last-modified').text() const lastModified = await browser.elementById('last-modified').text()
expect(lastModified).toInclude('Page /bar') expect(lastModified).toInclude('Page /bar')
expect(lastModified).toInclude('runtime') expect(lastModified).toInclude('runtime')
const layout = await browser.elementById('layout').text() const layout = await browser.elementById('root-layout').text()
expect(layout).toInclude(isNextDev ? 'runtime' : 'buildtime') expect(layout).toInclude(isNextDev ? 'runtime' : 'buildtime')
const headers = response.headers() const headers = response.headers()
...@@ -48,6 +50,96 @@ describe('fallback-shells', () => { ...@@ -48,6 +50,96 @@ describe('fallback-shells', () => {
expect(headers['x-nextjs-postponed']).toBe('1') expect(headers['x-nextjs-postponed']).toBe('1')
} }
}) })
// TODO: To be implemented in NAR-136.
it.skip('does not produce hydration errors when resuming a fallback shell containing a layout with unused params', async () => {
const browser = await next.browser(
'/with-cached-io/with-suspense/params-in-page/bar',
{ pushErrorAsConsoleLog: true }
)
const layout = await browser.elementById('layout').text()
// When prerendered, this should be restored from the RDC during the
// resume of the fallback shell, so it should be "buildtime". If the
// layout is unexpectedly a cache miss, then it will be "runtime".
expect(layout).toInclude(isNextDev ? 'runtime' : 'buildtime')
// There should also be no hydration errors due to a buildtime date
// being replaced by a new runtime date.
await assertNoConsoleErrors(browser)
})
// TODO: Activate for deploy tests once background revalidation for
// prerendered pages is not triggered anymore on the first visit.
if (!isNextDeploy) {
it('shares a cached parent layout between a prerendered route shell and the fallback shell', async () => {
// `/foo` was prerendered
const browser = await next.browser(
'/with-cached-io/with-suspense/params-in-page/foo'
)
const layoutDateRouteShell = await browser
.elementById('root-layout')
.text()
expect(layoutDateRouteShell).toInclude(
isNextDev ? 'runtime' : 'buildtime'
)
// `/bar` was not prerendered, and thus resumes the fallback shell.
await browser.loadPage(
new URL(
'/with-cached-io/with-suspense/params-in-page/bar',
next.url
).href
)
const layoutDateFallbackShell = await browser
.elementById('root-layout')
.text()
expect(layoutDateRouteShell).toInclude(
isNextDev ? 'runtime' : 'buildtime'
)
expect(layoutDateFallbackShell).toBe(layoutDateRouteShell)
})
// TODO: To be implemented in NAR-136.
it.skip('shares a cached layout with unused params between a prerendered route shell and the fallback shell', async () => {
// `/foo` was prerendered
const browser = await next.browser(
'/with-cached-io/with-suspense/params-in-page/foo'
)
const layoutDateRouteShell = await browser
.elementById('layout')
.text()
expect(layoutDateRouteShell).toInclude(
isNextDev ? 'runtime' : 'buildtime'
)
// `/bar` was not prerendered, and thus resumes the fallback shell.
await browser.loadPage(
new URL(
'/with-cached-io/with-suspense/params-in-page/bar',
next.url
).href
)
const layoutDateFallbackShell = await browser
.elementById('layout')
.text()
expect(layoutDateRouteShell).toInclude(
isNextDev ? 'runtime' : 'buildtime'
)
expect(layoutDateFallbackShell).toBe(layoutDateRouteShell)
})
}
}) })
describe('and the params accessed in cached non-page function', () => { describe('and the params accessed in cached non-page function', () => {
...@@ -60,7 +152,7 @@ describe('fallback-shells', () => { ...@@ -60,7 +152,7 @@ describe('fallback-shells', () => {
expect(lastModified).toInclude('Page /bar') expect(lastModified).toInclude('Page /bar')
expect(lastModified).toInclude('runtime') expect(lastModified).toInclude('runtime')
const layout = await browser.elementById('layout').text() const layout = await browser.elementById('root-layout').text()
expect(layout).toInclude(isNextDev ? 'runtime' : 'buildtime') expect(layout).toInclude(isNextDev ? 'runtime' : 'buildtime')
const headers = response.headers() const headers = response.headers()
...@@ -85,7 +177,7 @@ describe('fallback-shells', () => { ...@@ -85,7 +177,7 @@ describe('fallback-shells', () => {
expect(lastModified).toInclude('Page /bar') expect(lastModified).toInclude('Page /bar')
expect(lastModified).toInclude('runtime') expect(lastModified).toInclude('runtime')
const layout = await browser.elementById('layout').text() const layout = await browser.elementById('root-layout').text()
expect(layout).toInclude(isNextDev ? 'runtime' : 'buildtime') expect(layout).toInclude(isNextDev ? 'runtime' : 'buildtime')
const headers = response.headers() const headers = response.headers()
...@@ -112,7 +204,7 @@ describe('fallback-shells', () => { ...@@ -112,7 +204,7 @@ describe('fallback-shells', () => {
expect(lastModified).toInclude('Page /bar') expect(lastModified).toInclude('Page /bar')
expect(lastModified).toInclude('runtime') expect(lastModified).toInclude('runtime')
const layout = await browser.elementById('layout').text() const layout = await browser.elementById('root-layout').text()
expect(layout).toInclude('runtime') expect(layout).toInclude('runtime')
const headers = response.headers() const headers = response.headers()
...@@ -154,7 +246,7 @@ describe('fallback-shells', () => { ...@@ -154,7 +246,7 @@ describe('fallback-shells', () => {
expect(lastModified).toInclude('Page /bar') expect(lastModified).toInclude('Page /bar')
expect(lastModified).toInclude('runtime') expect(lastModified).toInclude('runtime')
const layout = await browser.elementById('layout').text() const layout = await browser.elementById('root-layout').text()
expect(layout).toInclude('runtime') expect(layout).toInclude('runtime')
const headers = response.headers() const headers = response.headers()
...@@ -179,7 +271,7 @@ describe('fallback-shells', () => { ...@@ -179,7 +271,7 @@ describe('fallback-shells', () => {
expect(lastModified).toInclude('Page /bar') expect(lastModified).toInclude('Page /bar')
expect(lastModified).toInclude('runtime') expect(lastModified).toInclude('runtime')
const layout = await browser.elementById('layout').text() const layout = await browser.elementById('root-layout').text()
expect(layout).toInclude('runtime') expect(layout).toInclude('runtime')
const headers = response.headers() const headers = response.headers()
......
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