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(
cachedNavigations: Boolean(
nextConfig.experimental.cachedNavigations
),
appShells: nextConfig.experimental.appShells,
clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any),
clientParamParsingOrigins:
......
......@@ -171,6 +171,7 @@ async function requestHandler(
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
useCacheTimeout: nextConfig.experimental.useCacheTimeout,
cachedNavigations: Boolean(nextConfig.experimental.cachedNavigations),
appShells: nextConfig.experimental.appShells,
clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any),
clientParamParsingOrigins:
......
......@@ -518,6 +518,7 @@ async function exportAppImpl(
authInterrupts: !!nextConfig.experimental.authInterrupts,
useCacheTimeout: nextConfig.experimental.useCacheTimeout,
cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,
appShells: nextConfig.experimental.appShells,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
nextConfig.experimental.maxPostponedStateSize
),
......
......@@ -170,6 +170,7 @@ export interface RenderOptsPartial {
authInterrupts: boolean
useCacheTimeout: number
cachedNavigations: boolean
appShells: ExperimentalConfig['appShells']
/**
* The maximum size (in bytes) of the postponed state body for PPR resume
......
......@@ -198,14 +198,6 @@ export interface PrerenderStoreModernRuntime
readonly headers: RequestStore['headers']
readonly cookies: RequestStore['cookies']
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 {
......
......@@ -586,6 +586,7 @@ export default abstract class Server<
useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,
cachedNavigations:
this.nextConfig.experimental.cachedNavigations ?? false,
appShells: this.nextConfig.experimental.appShells,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
this.nextConfig.experimental.maxPostponedStateSize
),
......
import { InvariantError } from '../shared/lib/invariant-error'
import {
isEarlyRenderStage,
RenderStage,
type AdvanceableRenderStage,
type StagedRenderingController,
isEarlyRenderStage,
} from './app-render/staged-rendering'
import type { RequestStore } 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>(
})
}
/**
* Returns the appropriate runtime stage for the current point in the render.
* Runtime-prefetchable segments render in the early stages and should wait
* for EarlyRuntime. Non-prefetchable segments render in the later stages
* and should wait for Runtime.
*/
export function getRuntimeStage(
export const RENDER_STAGES_BY_DATA_KIND = {
// NOTE: keep in sync with getSessionDataStage
sessionData: {
early: RenderStage.ShellEarlyRuntime as const,
late: RenderStage.ShellRuntime as const,
},
// 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
): RenderStage.EarlyRuntime | RenderStage.Runtime {
) {
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.EarlyRuntime
: RenderStage.Runtime
......
......@@ -24,7 +24,7 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
getRuntimeStage,
getSessionDataStage,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestAPICallableInsideAfter } from './utils'
......@@ -108,7 +108,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
return stagedRendering.delayUntilStage(
getRuntimeStage(stagedRendering),
getSessionDataStage(stagedRendering),
'cookies',
workUnitStore.cookies
)
......@@ -242,7 +242,7 @@ function makeUntrackedCookiesWithDevWarnings(
const promise = makeDevtoolsIOAwarePromise(
underlyingCookies,
requestStore,
RenderStage.Runtime
RenderStage.ShellRuntime
)
const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)
......
......@@ -20,7 +20,10 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import { DynamicServerError } from '../../client/components/hooks-server-context'
import { InvariantError } from '../../shared/lib/invariant-error'
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> {
const callingExpression = 'draftMode'
......@@ -37,7 +40,7 @@ export function draftMode(): Promise<DraftMode> {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
return stagedRendering.delayUntilStage(
getRuntimeStage(stagedRendering),
getSessionDataStage(stagedRendering),
'draftMode',
new DraftMode(workUnitStore.draftMode)
)
......
......@@ -22,7 +22,7 @@ import { StaticGenBailoutError } from '../../client/components/static-generation
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
getRuntimeStage,
getSessionDataStage,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { isRequestAPICallableInsideAfter } from './utils'
......@@ -134,9 +134,8 @@ export function headers(): Promise<ReadonlyHeaders> {
case 'prerender-runtime': {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
// TODO(app-shells): headers should be dynamic instead.
return stagedRendering.delayUntilStage(
getRuntimeStage(stagedRendering),
getSessionDataStage(stagedRendering),
'headers',
workUnitStore.headers
)
......
......@@ -34,6 +34,7 @@ import {
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
......@@ -177,7 +178,6 @@ export function createServerParamsForRoute(
return createRuntimePrerenderParams(
underlyingParams,
null,
workStore,
workUnitStore,
varyParamsAccumulator,
isRuntimePrefetchable
......@@ -250,7 +250,6 @@ export function createServerParamsForServerSegment(
return createRuntimePrerenderParams(
underlyingParams,
optionalCatchAllParamName,
workStore,
workUnitStore,
varyParamsAccumulator,
isRuntimePrefetchable
......@@ -346,17 +345,6 @@ export function createPrerenderParamsForClientSegment(
'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'
)
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-legacy':
case 'request':
......@@ -436,21 +424,10 @@ function createStaticPrerenderParams(
function createRuntimePrerenderParams(
underlyingParams: Params,
optionalCatchAllParamName: string | null,
workStore: WorkStore,
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): 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 =
varyParamsAccumulator !== null
? createVaryingParams(
......@@ -463,14 +440,31 @@ function createRuntimePrerenderParams(
const result = makeUntrackedParams(underlyingParamsWithVarying)
const { stagedRendering } = workUnitStore
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
}
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime
: RenderStage.Runtime
// Semantically, we should resolve static params in the static stage.
// 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)
}
function isEmptyParams(params: Params): boolean {
for (const _paramKey in params) {
return false
}
return true
}
function hasFallbackRouteParams(
underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined
......
......@@ -15,9 +15,11 @@ import {
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} 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 { RenderStage } from '../app-render/staged-rendering'
export function createServerPathnameForMetadata(
underlyingPathname: string,
......@@ -55,11 +57,18 @@ export function createServerPathnameForMetadata(
'createServerPathnameForMetadata should not be called inside generateStaticParams.'
)
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
if (stagedRendering) {
const pathnameStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime
: RenderStage.Runtime
? pathnameStages.early
: pathnameStages.late
return stagedRendering.delayUntilStage(
stage,
undefined,
......
......@@ -13,11 +13,18 @@ import {
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} 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 { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'
import { actionAsyncStorage } from '../app-render/action-async-storage.external'
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.
......@@ -64,6 +71,9 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
)
}
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) {
throw new Error(
`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> {
}
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': {
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
}
case 'generate-static-params': {
......@@ -129,6 +159,23 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
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(
paramName: string,
workStore: WorkStore,
......
......@@ -30,6 +30,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
import {
......@@ -144,7 +145,6 @@ export function createServerSearchParamsForServerPage(
case 'prerender-runtime':
return createRuntimePrerenderSearchParams(
underlyingSearchParams,
workStore,
workUnitStore,
varyParamsAccumulator,
isRuntimePrefetchable
......@@ -242,23 +242,10 @@ function createStaticPrerenderSearchParams(
function createRuntimePrerenderSearchParams(
underlyingSearchParams: SearchParams,
workStore: WorkStore,
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): 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 =
varyParamsAccumulator !== null
? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)
......@@ -269,9 +256,10 @@ function createRuntimePrerenderSearchParams(
if (!stagedRendering) {
return result
}
const searchParamsStages = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime
: RenderStage.Runtime
? searchParamsStages.early
: searchParamsStages.late
return stagedRendering.waitForStage(stage).then(() => result)
}
......
......@@ -34,13 +34,15 @@ import {
getCacheSignal,
isHmrRefresh,
getServerComponentsHmrCache,
getStagedRenderingController,
} from '../app-render/work-unit-async-storage.external'
import {
applyOwnerStack,
getRuntimeStage,
makeDevtoolsIOAwarePromise,
makeHangingPromise,
getSessionDataStage,
getRuntimeLinkDataStage,
} from '../dynamic-rendering-utils'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
......@@ -1686,7 +1688,10 @@ export async function cache(
// while runtime-prefetchable segments resolve at Runtime.
const stagedRendering = outerWorkUnitStore.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
}
......@@ -1697,7 +1702,7 @@ export async function cache(
// whether we're in the early or late stages.
const stagedRendering = outerWorkUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
? getSessionDataStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(undefined, outerWorkUnitStore, stage)
}
......@@ -2095,7 +2100,8 @@ export async function cache(
const stagedRendering = workUnitStore.stagedRendering
if (stagedRendering) {
await stagedRendering.waitForStage(
getRuntimeStage(stagedRendering)
// TODO(app-shells): exclude caches with a short staletime
getSessionDataStage(stagedRendering)
)
}
break
......@@ -2128,9 +2134,10 @@ export async function cache(
// 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,
// and thus will cause a restart even if all caches are filled.
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
? getSessionDataStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(
undefined,
......@@ -2201,6 +2208,39 @@ export async function cache(
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) {
......@@ -2638,7 +2678,7 @@ export async function cache(
// and thus will cause a restart even if all caches are filled.
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
? getSessionDataStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(
undefined,
......
......@@ -378,6 +378,11 @@ export type NavigationFlightResponse = {
s?: AsyncIterable<number>
/** staticStageByteLength - Resolves when the static stage ends. */
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 */
h: VaryParamsThenable | null
/** 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