Unverified Commit cbb9a85b authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[App Shells] App shells in runtime prefetches (#93801)

Reimplements app shells in runtime prefetches in terms of a staged
render.

when `appShells` is on:
- a `next-router-prefetch: 2` request (i.e. "including link data") will
have a shell stage that only includes session data. we communicate the
byte offset to the client so it can rewind the response to a session
fallback
- a `next-router-prefetch: 3` request (i.e. "session shell") stops
rendering after the shell stages, i.e. link data is never resolved. this
replaces the previous `forceOmitParams` implementation.
 
Note that In order to produce a session shell, we have to resolve static
`params` and rootParams in the Runtime stage (previously, they'd resolve
in the static stage). This is because params are link data and cannot be
part of the session shell. We don't really need to rewind a runtime
prefetch to a static stage, so this divergence in behavior shouldn't be
meaningfully observable.

Notable call-out: root params getters can also be called inside caches.
if a cache accesses root params, then the cache depends on link data and
must be excluded from the shell. We rely on existing mechanisms for
tracking root param access and delay the cache appropriately in the
final render.
parent 7644b7e5
...@@ -899,6 +899,7 @@ export async function handler( ...@@ -899,6 +899,7 @@ export async function handler(
cachedNavigations: Boolean( cachedNavigations: Boolean(
nextConfig.experimental.cachedNavigations nextConfig.experimental.cachedNavigations
), ),
appShells: nextConfig.experimental.appShells,
clientTraceMetadata: clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any), nextConfig.experimental.clientTraceMetadata || ([] as any),
clientParamParsingOrigins: clientParamParsingOrigins:
......
...@@ -171,6 +171,7 @@ async function requestHandler( ...@@ -171,6 +171,7 @@ async function requestHandler(
authInterrupts: Boolean(nextConfig.experimental.authInterrupts), authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
useCacheTimeout: nextConfig.experimental.useCacheTimeout, useCacheTimeout: nextConfig.experimental.useCacheTimeout,
cachedNavigations: Boolean(nextConfig.experimental.cachedNavigations), cachedNavigations: Boolean(nextConfig.experimental.cachedNavigations),
appShells: nextConfig.experimental.appShells,
clientTraceMetadata: clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any), nextConfig.experimental.clientTraceMetadata || ([] as any),
clientParamParsingOrigins: clientParamParsingOrigins:
......
...@@ -518,6 +518,7 @@ async function exportAppImpl( ...@@ -518,6 +518,7 @@ async function exportAppImpl(
authInterrupts: !!nextConfig.experimental.authInterrupts, authInterrupts: !!nextConfig.experimental.authInterrupts,
useCacheTimeout: nextConfig.experimental.useCacheTimeout, useCacheTimeout: nextConfig.experimental.useCacheTimeout,
cachedNavigations: nextConfig.experimental.cachedNavigations ?? false, cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,
appShells: nextConfig.experimental.appShells,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
nextConfig.experimental.maxPostponedStateSize nextConfig.experimental.maxPostponedStateSize
), ),
......
...@@ -170,6 +170,7 @@ export interface RenderOptsPartial { ...@@ -170,6 +170,7 @@ export interface RenderOptsPartial {
authInterrupts: boolean authInterrupts: boolean
useCacheTimeout: number useCacheTimeout: number
cachedNavigations: boolean cachedNavigations: boolean
appShells: ExperimentalConfig['appShells']
/** /**
* The maximum size (in bytes) of the postponed state body for PPR resume * The maximum size (in bytes) of the postponed state body for PPR resume
......
...@@ -198,14 +198,6 @@ export interface PrerenderStoreModernRuntime ...@@ -198,14 +198,6 @@ export interface PrerenderStoreModernRuntime
readonly headers: RequestStore['headers'] readonly headers: RequestStore['headers']
readonly cookies: RequestStore['cookies'] readonly cookies: RequestStore['cookies']
readonly draftMode: RequestStore['draftMode'] readonly draftMode: RequestStore['draftMode']
/**
* When true, `await params` and `await searchParams` both return hanging
* promises — segments that depend on either suspend, producing the App
* Shell of the route. Set by an App Shell prefetch request
* (NEXT_ROUTER_PREFETCH_HEADER === '3').
*/
readonly forceOmitParams: boolean
} }
export interface RevalidateStore { export interface RevalidateStore {
......
...@@ -586,6 +586,7 @@ export default abstract class Server< ...@@ -586,6 +586,7 @@ export default abstract class Server<
useCacheTimeout: this.nextConfig.experimental.useCacheTimeout, useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,
cachedNavigations: cachedNavigations:
this.nextConfig.experimental.cachedNavigations ?? false, this.nextConfig.experimental.cachedNavigations ?? false,
appShells: this.nextConfig.experimental.appShells,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize( maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
this.nextConfig.experimental.maxPostponedStateSize this.nextConfig.experimental.maxPostponedStateSize
), ),
......
import { InvariantError } from '../shared/lib/invariant-error' import { InvariantError } from '../shared/lib/invariant-error'
import { import {
isEarlyRenderStage,
RenderStage, RenderStage,
type AdvanceableRenderStage, type AdvanceableRenderStage,
type StagedRenderingController, type StagedRenderingController,
isEarlyRenderStage,
} from './app-render/staged-rendering' } from './app-render/staged-rendering'
import type { RequestStore } from './app-render/work-unit-async-storage.external' import type { RequestStore } from './app-render/work-unit-async-storage.external'
import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external' import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'
...@@ -107,21 +107,64 @@ export function makeDevtoolsIOAwarePromise<T>( ...@@ -107,21 +107,64 @@ export function makeDevtoolsIOAwarePromise<T>(
}) })
} }
/** export const RENDER_STAGES_BY_DATA_KIND = {
* Returns the appropriate runtime stage for the current point in the render. // NOTE: keep in sync with getSessionDataStage
* Runtime-prefetchable segments render in the early stages and should wait sessionData: {
* for EarlyRuntime. Non-prefetchable segments render in the later stages early: RenderStage.ShellEarlyRuntime as const,
* and should wait for Runtime. late: RenderStage.ShellRuntime as const,
*/ },
export function getRuntimeStage( // NOTE: keep in sync with getStaticLinkDataStage
staticLinkData: {
early: RenderStage.EarlyStatic as const,
late: RenderStage.Static as const,
},
// NOTE: keep in sync with getRuntimeLinkDataStage
runtimeLinkData: {
early: RenderStage.EarlyRuntime as const,
late: RenderStage.Runtime as const,
},
}
export function getSessionDataStage(
stagedRendering: StagedRenderingController
) {
const { currentStage } = stagedRendering
if (currentStage === RenderStage.Before) {
throw new InvariantError(
'Cannot determine late/early stage before starting the render'
)
}
// NOTE: keep in sync with RENDER_STAGES_BY_DATA_KIND
return isEarlyRenderStage(currentStage)
? RenderStage.ShellEarlyRuntime
: RenderStage.ShellRuntime
}
export function getStaticLinkDataStage(
stagedRendering: StagedRenderingController
) {
const { currentStage } = stagedRendering
if (currentStage === RenderStage.Before) {
throw new InvariantError(
'Cannot determine late/early stage before starting the render'
)
}
// NOTE: keep in sync with RENDER_STAGES_BY_DATA_KIND
return isEarlyRenderStage(currentStage)
? RenderStage.EarlyStatic
: RenderStage.Static
}
export function getRuntimeLinkDataStage(
stagedRendering: StagedRenderingController stagedRendering: StagedRenderingController
): RenderStage.EarlyRuntime | RenderStage.Runtime { ) {
const { currentStage } = stagedRendering const { currentStage } = stagedRendering
if (currentStage === RenderStage.Before) { if (currentStage === RenderStage.Before) {
throw new InvariantError( throw new InvariantError(
'Cannot determine late/early stage before starting the render' 'Cannot determine late/early stage before starting the render'
) )
} }
// NOTE: keep in sync with RENDER_STAGES_BY_DATA_KIND
return isEarlyRenderStage(currentStage) return isEarlyRenderStage(currentStage)
? RenderStage.EarlyRuntime ? RenderStage.EarlyRuntime
: RenderStage.Runtime : RenderStage.Runtime
......
...@@ -24,7 +24,7 @@ import { StaticGenBailoutError } from '../../client/components/static-generation ...@@ -24,7 +24,7 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import { import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
getRuntimeStage, getSessionDataStage,
} 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 { isRequestAPICallableInsideAfter } from './utils' import { isRequestAPICallableInsideAfter } from './utils'
...@@ -108,7 +108,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -108,7 +108,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (stagedRendering) { if (stagedRendering) {
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
getRuntimeStage(stagedRendering), getSessionDataStage(stagedRendering),
'cookies', 'cookies',
workUnitStore.cookies workUnitStore.cookies
) )
...@@ -242,7 +242,7 @@ function makeUntrackedCookiesWithDevWarnings( ...@@ -242,7 +242,7 @@ function makeUntrackedCookiesWithDevWarnings(
const promise = makeDevtoolsIOAwarePromise( const promise = makeDevtoolsIOAwarePromise(
underlyingCookies, underlyingCookies,
requestStore, requestStore,
RenderStage.Runtime RenderStage.ShellRuntime
) )
const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route) const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)
......
...@@ -20,7 +20,10 @@ import { StaticGenBailoutError } from '../../client/components/static-generation ...@@ -20,7 +20,10 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import { DynamicServerError } from '../../client/components/hooks-server-context' import { DynamicServerError } from '../../client/components/hooks-server-context'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { applyOwnerStack, getRuntimeStage } from '../dynamic-rendering-utils' import {
applyOwnerStack,
getSessionDataStage,
} from '../dynamic-rendering-utils'
export function draftMode(): Promise<DraftMode> { export function draftMode(): Promise<DraftMode> {
const callingExpression = 'draftMode' const callingExpression = 'draftMode'
...@@ -37,7 +40,7 @@ export function draftMode(): Promise<DraftMode> { ...@@ -37,7 +40,7 @@ export function draftMode(): Promise<DraftMode> {
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (stagedRendering) { if (stagedRendering) {
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
getRuntimeStage(stagedRendering), getSessionDataStage(stagedRendering),
'draftMode', 'draftMode',
new DraftMode(workUnitStore.draftMode) new DraftMode(workUnitStore.draftMode)
) )
......
...@@ -22,7 +22,7 @@ import { StaticGenBailoutError } from '../../client/components/static-generation ...@@ -22,7 +22,7 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import { import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
getRuntimeStage, getSessionDataStage,
} 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 { isRequestAPICallableInsideAfter } from './utils' import { isRequestAPICallableInsideAfter } from './utils'
...@@ -134,9 +134,8 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -134,9 +134,8 @@ export function headers(): Promise<ReadonlyHeaders> {
case 'prerender-runtime': { case 'prerender-runtime': {
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (stagedRendering) { if (stagedRendering) {
// TODO(app-shells): headers should be dynamic instead.
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
getRuntimeStage(stagedRendering), getSessionDataStage(stagedRendering),
'headers', 'headers',
workUnitStore.headers workUnitStore.headers
) )
......
...@@ -34,6 +34,7 @@ import { ...@@ -34,6 +34,7 @@ import {
import { import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} 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 { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
...@@ -177,7 +178,6 @@ export function createServerParamsForRoute( ...@@ -177,7 +178,6 @@ export function createServerParamsForRoute(
return createRuntimePrerenderParams( return createRuntimePrerenderParams(
underlyingParams, underlyingParams,
null, null,
workStore,
workUnitStore, workUnitStore,
varyParamsAccumulator, varyParamsAccumulator,
isRuntimePrefetchable isRuntimePrefetchable
...@@ -250,7 +250,6 @@ export function createServerParamsForServerSegment( ...@@ -250,7 +250,6 @@ export function createServerParamsForServerSegment(
return createRuntimePrerenderParams( return createRuntimePrerenderParams(
underlyingParams, underlyingParams,
optionalCatchAllParamName, optionalCatchAllParamName,
workStore,
workUnitStore, workUnitStore,
varyParamsAccumulator, varyParamsAccumulator,
isRuntimePrefetchable isRuntimePrefetchable
...@@ -346,17 +345,6 @@ export function createPrerenderParamsForClientSegment( ...@@ -346,17 +345,6 @@ export function createPrerenderParamsForClientSegment(
'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.' 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'
) )
case 'prerender-runtime': case 'prerender-runtime':
if (workUnitStore.forceOmitParams) {
// App Shell prefetch: hang on params so the client segment doesn't
// receive a resolved value and render. Matches the server-side
// behavior in createRuntimePrerenderParams.
return makeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`params`'
)
}
break
case 'prerender-ppr': case 'prerender-ppr':
case 'prerender-legacy': case 'prerender-legacy':
case 'request': case 'request':
...@@ -436,21 +424,10 @@ function createStaticPrerenderParams( ...@@ -436,21 +424,10 @@ function createStaticPrerenderParams(
function createRuntimePrerenderParams( function createRuntimePrerenderParams(
underlyingParams: Params, underlyingParams: Params,
optionalCatchAllParamName: string | null, optionalCatchAllParamName: string | null,
workStore: WorkStore,
workUnitStore: PrerenderStoreModernRuntime, workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null, varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean isRuntimePrefetchable: boolean
): Promise<Params> { ): Promise<Params> {
if (workUnitStore.forceOmitParams) {
// App Shell prefetch: any `await params` suspends. Segments that depend
// on params render as holes, leaving the param-independent shell.
return makeHangingPromise<Params>(
workUnitStore.renderSignal,
workStore.route,
'`params`'
)
}
const underlyingParamsWithVarying = const underlyingParamsWithVarying =
varyParamsAccumulator !== null varyParamsAccumulator !== null
? createVaryingParams( ? createVaryingParams(
...@@ -463,14 +440,31 @@ function createRuntimePrerenderParams( ...@@ -463,14 +440,31 @@ function createRuntimePrerenderParams(
const result = makeUntrackedParams(underlyingParamsWithVarying) const result = makeUntrackedParams(underlyingParamsWithVarying)
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
// If there's no staging, we're in a prospective runtime prerender,
// and it doesn't matter when params resolve.
return result
}
// if the params are empty, there's nothing to delay
if (isEmptyParams(underlyingParams)) {
return result return result
} }
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime // Semantically, we should resolve static params in the static stage.
: RenderStage.Runtime // But params are link data, and we need to recover a param-less session shell,
// so we delay all params until the runtime stage instead.
const paramsStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable ? paramsStages.early : paramsStages.late
return stagedRendering.waitForStage(stage).then(() => result) return stagedRendering.waitForStage(stage).then(() => result)
} }
function isEmptyParams(params: Params): boolean {
for (const _paramKey in params) {
return false
}
return true
}
function hasFallbackRouteParams( function hasFallbackRouteParams(
underlyingParams: Params, underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined fallbackParams: OpaqueFallbackRouteParams | null | undefined
......
...@@ -15,9 +15,11 @@ import { ...@@ -15,9 +15,11 @@ import {
type PrerenderStoreModernServer, type PrerenderStoreModernServer,
type PrerenderStorePPR, type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import {
makeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
export function createServerPathnameForMetadata( export function createServerPathnameForMetadata(
underlyingPathname: string, underlyingPathname: string,
...@@ -55,11 +57,18 @@ export function createServerPathnameForMetadata( ...@@ -55,11 +57,18 @@ export function createServerPathnameForMetadata(
'createServerPathnameForMetadata should not be called inside generateStaticParams.' 'createServerPathnameForMetadata should not be called inside generateStaticParams.'
) )
case 'prerender-runtime': { case 'prerender-runtime': {
// TODO(app-shells): whether or not this is included in the shell
// should depend on whether this route has params.
// if there's no params, it can be included.
// for now, we defensively exclude it to match the earlier pessimistic
// behavior of always resolving in the runtime stage
// (i.e. assuming that we have non-static params in the pathname)
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (stagedRendering) { if (stagedRendering) {
const pathnameStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime ? pathnameStages.early
: RenderStage.Runtime : pathnameStages.late
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
stage, stage,
undefined, undefined,
......
...@@ -13,11 +13,18 @@ import { ...@@ -13,11 +13,18 @@ import {
type PrerenderStoreModernServer, type PrerenderStoreModernServer,
type PrerenderStorePPR, type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import {
getRuntimeLinkDataStage,
makeHangingPromise,
} from '../dynamic-rendering-utils'
import type { ParamValue } from './params' import type { ParamValue } from './params'
import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils' import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'
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'
import type {
RenderStage,
StagedRenderingController,
} from '../app-render/staged-rendering'
/** /**
* Used for the compiler-generated `next/root-params` module. * Used for the compiler-generated `next/root-params` module.
...@@ -64,6 +71,9 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -64,6 +71,9 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
) )
} }
case 'cache': { case 'cache': {
// NOTE: In shell prerenders, we delay caches that used root params
// in use-cache-wrapper, during the final prerender, so we don't
// need to do anything here
if (!workUnitStore.rootParams) { if (!workUnitStore.rootParams) {
throw new Error( throw new Error(
`Route ${workStore.route} used ${apiName} inside \`"use cache"\` nested within \`unstable_cache\`. Root params are not available in this context.` `Route ${workStore.route} used ${apiName} inside \`"use cache"\` nested within \`unstable_cache\`. Root params are not available in this context.`
...@@ -108,8 +118,28 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -108,8 +118,28 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
} }
break break
} }
case 'private-cache': case 'private-cache': {
// NOTE: In shell prerenders, we delay caches that used root params
// in use-cache-wrapper, during the final prerender, so we don't
// need to do anything here
break
}
case 'prerender-runtime': { case 'prerender-runtime': {
const { stagedRendering } = workUnitStore
if (stagedRendering && process.env.__NEXT_APP_SHELLS) {
return createRootParamPromiseForShellRender(
stagedRendering,
// A runtime prerender with shells means that we want to recover a session shell.
// Root params are link data, so we have to omit them from the shell.
// Tihs means we must delay them until the runtime stage even though
// semantically they're considered static.
getRuntimeLinkDataStage(stagedRendering),
apiName,
paramName,
workUnitStore.rootParams[paramName]
)
}
break break
} }
case 'generate-static-params': { case 'generate-static-params': {
...@@ -129,6 +159,23 @@ export function getRootParam(paramName: string): Promise<ParamValue> { ...@@ -129,6 +159,23 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
return Promise.resolve(workUnitStore.rootParams[paramName]) return Promise.resolve(workUnitStore.rootParams[paramName])
} }
type LinkDataStage =
| RenderStage.EarlyStatic
| RenderStage.Static
| RenderStage.EarlyRuntime
| RenderStage.Runtime
function createRootParamPromiseForShellRender(
stagedRendering: StagedRenderingController,
stage: LinkDataStage,
apiName: string,
paramName: string,
paramValue: ParamValue
): Promise<ParamValue> {
accumulateRootVaryParam(paramName)
return stagedRendering.delayUntilStage(stage, apiName, paramValue)
}
function createPrerenderRootParamPromise( function createPrerenderRootParamPromise(
paramName: string, paramName: string,
workStore: WorkStore, workStore: WorkStore,
......
...@@ -30,6 +30,7 @@ import { InvariantError } from '../../shared/lib/invariant-error' ...@@ -30,6 +30,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} 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 { import {
...@@ -144,7 +145,6 @@ export function createServerSearchParamsForServerPage( ...@@ -144,7 +145,6 @@ export function createServerSearchParamsForServerPage(
case 'prerender-runtime': case 'prerender-runtime':
return createRuntimePrerenderSearchParams( return createRuntimePrerenderSearchParams(
underlyingSearchParams, underlyingSearchParams,
workStore,
workUnitStore, workUnitStore,
varyParamsAccumulator, varyParamsAccumulator,
isRuntimePrefetchable isRuntimePrefetchable
...@@ -242,23 +242,10 @@ function createStaticPrerenderSearchParams( ...@@ -242,23 +242,10 @@ function createStaticPrerenderSearchParams(
function createRuntimePrerenderSearchParams( function createRuntimePrerenderSearchParams(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workStore: WorkStore,
workUnitStore: PrerenderStoreModernRuntime, workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null, varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean isRuntimePrefetchable: boolean
): Promise<SearchParams> { ): Promise<SearchParams> {
if (workUnitStore.forceOmitParams) {
// App Shell prefetch: any `await searchParams` suspends. Segments that
// depend on search params render as holes, leaving the
// search-param-independent shell. Matches the behavior in
// createRuntimePrerenderParams for path params.
return makeHangingPromise<SearchParams>(
workUnitStore.renderSignal,
workStore.route,
'`searchParams`'
)
}
const underlyingSearchParamsWithVarying = const underlyingSearchParamsWithVarying =
varyParamsAccumulator !== null varyParamsAccumulator !== null
? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams) ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)
...@@ -269,9 +256,10 @@ function createRuntimePrerenderSearchParams( ...@@ -269,9 +256,10 @@ function createRuntimePrerenderSearchParams(
if (!stagedRendering) { if (!stagedRendering) {
return result return result
} }
const searchParamsStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime ? searchParamsStages.early
: RenderStage.Runtime : searchParamsStages.late
return stagedRendering.waitForStage(stage).then(() => result) return stagedRendering.waitForStage(stage).then(() => result)
} }
......
...@@ -34,13 +34,15 @@ import { ...@@ -34,13 +34,15 @@ import {
getCacheSignal, getCacheSignal,
isHmrRefresh, isHmrRefresh,
getServerComponentsHmrCache, getServerComponentsHmrCache,
getStagedRenderingController,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
applyOwnerStack, applyOwnerStack,
getRuntimeStage,
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
getSessionDataStage,
getRuntimeLinkDataStage,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
...@@ -1686,7 +1688,10 @@ export async function cache( ...@@ -1686,7 +1688,10 @@ export async function cache(
// while runtime-prefetchable segments resolve at Runtime. // while runtime-prefetchable segments resolve at Runtime.
const stagedRendering = outerWorkUnitStore.stagedRendering const stagedRendering = outerWorkUnitStore.stagedRendering
if (stagedRendering) { if (stagedRendering) {
await stagedRendering.waitForStage(getRuntimeStage(stagedRendering)) await stagedRendering.waitForStage(
// TODO(app-shells): exclude private caches with a short staletime from shells
getSessionDataStage(stagedRendering)
)
} }
break break
} }
...@@ -1697,7 +1702,7 @@ export async function cache( ...@@ -1697,7 +1702,7 @@ export async function cache(
// whether we're in the early or late stages. // whether we're in the early or late stages.
const stagedRendering = outerWorkUnitStore.stagedRendering const stagedRendering = outerWorkUnitStore.stagedRendering
const stage = stagedRendering const stage = stagedRendering
? getRuntimeStage(stagedRendering) ? getSessionDataStage(stagedRendering)
: RenderStage.Runtime : RenderStage.Runtime
await makeDevtoolsIOAwarePromise(undefined, outerWorkUnitStore, stage) await makeDevtoolsIOAwarePromise(undefined, outerWorkUnitStore, stage)
} }
...@@ -2095,7 +2100,8 @@ export async function cache( ...@@ -2095,7 +2100,8 @@ export async function cache(
const stagedRendering = workUnitStore.stagedRendering const stagedRendering = workUnitStore.stagedRendering
if (stagedRendering) { if (stagedRendering) {
await stagedRendering.waitForStage( await stagedRendering.waitForStage(
getRuntimeStage(stagedRendering) // TODO(app-shells): exclude caches with a short staletime
getSessionDataStage(stagedRendering)
) )
} }
break break
...@@ -2128,9 +2134,10 @@ export async function cache( ...@@ -2128,9 +2134,10 @@ export async function cache(
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts. // TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts.
// We don't end the cache read here, so this will always appear as a cache miss in the static stage, // We don't end the cache read here, so this will always appear as a cache miss in the static stage,
// and thus will cause a restart even if all caches are filled. // and thus will cause a restart even if all caches are filled.
const stagedRendering = workUnitStore.stagedRendering const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering const stage = stagedRendering
? getRuntimeStage(stagedRendering) ? getSessionDataStage(stagedRendering)
: RenderStage.Runtime : RenderStage.Runtime
await makeDevtoolsIOAwarePromise( await makeDevtoolsIOAwarePromise(
undefined, undefined,
...@@ -2201,6 +2208,39 @@ export async function cache( ...@@ -2201,6 +2208,39 @@ export async function cache(
workUnitStore satisfies never workUnitStore satisfies never
} }
} }
// If we're doing staged rendering with shells and the cache accessed root params,
// we should exclude it from the shell, because root params are also excluded.
const stagedRendering = getStagedRenderingController(workUnitStore)
if (
process.env.__NEXT_APP_SHELLS &&
stagedRendering &&
rootParams &&
rdcResult.readRootParamNames &&
rdcResult.readRootParamNames.size > 0
) {
switch (workUnitStore.type) {
case 'prerender-runtime': {
// If we're rendering with shells, this is when params should resolve
await stagedRendering.waitForStage(
getRuntimeLinkDataStage(stagedRendering)
)
break
}
case 'request':
case 'prerender':
case 'cache':
case 'private-cache':
case 'prerender-legacy':
case 'prerender-ppr':
case 'generate-static-params': {
break
}
default: {
workUnitStore satisfies never
}
}
}
} }
if (rdcResult !== undefined) { if (rdcResult !== undefined) {
...@@ -2638,7 +2678,7 @@ export async function cache( ...@@ -2638,7 +2678,7 @@ export async function cache(
// and thus will cause a restart even if all caches are filled. // and thus will cause a restart even if all caches are filled.
const stagedRendering = workUnitStore.stagedRendering const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering const stage = stagedRendering
? getRuntimeStage(stagedRendering) ? getSessionDataStage(stagedRendering)
: RenderStage.Runtime : RenderStage.Runtime
await makeDevtoolsIOAwarePromise( await makeDevtoolsIOAwarePromise(
undefined, undefined,
......
...@@ -378,6 +378,11 @@ export type NavigationFlightResponse = { ...@@ -378,6 +378,11 @@ export type NavigationFlightResponse = {
s?: AsyncIterable<number> s?: AsyncIterable<number>
/** staticStageByteLength - Resolves when the static stage ends. */ /** staticStageByteLength - Resolves when the static stage ends. */
l?: Promise<number> l?: Promise<number>
/**
* shellByteLength - Resolves when the shell stage ends.
* If it resolves to null, then the shell is the same as the main response.
* */
a?: Promise<number | null>
/** headVaryParams */ /** headVaryParams */
h: VaryParamsThenable | null h: VaryParamsThenable | null
/** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */ /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */
......
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