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
),
......
......@@ -255,8 +255,11 @@ import { ImageConfigContext } from '../../shared/lib/image-config-context.shared
import { imageConfigDefault } from '../../shared/lib/image-config'
import {
getNextStage,
isAdvanceableRenderStage,
RENDER_STAGE_ADVANCE_ORDER,
RenderStage,
StagedRenderingController,
type AdvanceableRenderStage,
} from './staged-rendering'
import {
anySegmentHasRuntimePrefetchEnabled,
......@@ -283,6 +286,7 @@ import type {
} from '../../build/segment-config/app/app-segment-config'
import { ResponseCookies } from '../web/spec-extension/cookies'
import { isInstantValidationError } from './instant-validation/instant-validation-error'
import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'
export type GetDynamicParamFromSegment = (
// The LoaderTree to extract the dynamic param from
......@@ -397,7 +401,7 @@ function parseRequestHeaders(
const isAppShellPrefetchRequest = headers[NEXT_ROUTER_PREFETCH_HEADER] === '3'
// App Shell prefetches are a subtype of runtime prefetch — same code path,
// with `forceOmitParams` set on the prerender store.
// but with less resolved content (omitting link data)
const isRuntimePrefetchRequest =
headers[NEXT_ROUTER_PREFETCH_HEADER] === '2' || isAppShellPrefetchRequest
......@@ -597,6 +601,7 @@ async function generateDynamicRSCPayload(
skipPageRendering?: boolean
staleTimeIterable?: AsyncIterable<number>
staticStageByteLengthPromise?: Promise<number>
shellByteLengthPromise?: Promise<number | null>
runtimePrefetchStream?: ReadableStream<Uint8Array>
}
): Promise<RSCPayload> {
......@@ -742,6 +747,9 @@ async function generateDynamicRSCPayload(
if (options?.staticStageByteLengthPromise !== undefined) {
baseResponse.l = options.staticStageByteLengthPromise
}
if (options?.shellByteLengthPromise !== undefined) {
baseResponse.a = options.shellByteLengthPromise
}
if (options?.runtimePrefetchStream !== undefined) {
baseResponse.p = options.runtimePrefetchStream
......@@ -1234,22 +1242,39 @@ async function spawnRuntimePrefetchWithFilledCaches(
onError: (err: unknown) => string | undefined
): Promise<void> {
try {
const { componentMod, getDynamicParamFromSegment } = ctx
const { componentMod, getDynamicParamFromSegment, renderOpts } = ctx
const { loaderTree } = componentMod.routeModule.userland
const { appShells } = renderOpts.experimental
const rootParams = getRootParams(loaderTree, getDynamicParamFromSegment)
const staleTimeIterable = new StaleTimeIterable()
const mode: RuntimePrerenderMode = appShells
? // If appShells is on, we want to be able to rewind the result to a session shell.
{
type: 'rewindable-session-shell',
shellByteLengthDeferred: createPromiseWithResolvers(),
}
: // Otherwise, render everything without considering shells.
{ type: 'runtime-only' }
const { result } = await finalRuntimeServerPrerender(
mode,
ctx,
generateDynamicRSCPayload.bind(null, ctx, { staleTimeIterable }),
generateDynamicRSCPayload.bind(null, ctx, {
staleTimeIterable,
shellByteLengthPromise:
mode.type === 'rewindable-session-shell'
? mode.shellByteLengthDeferred.promise
: undefined,
}),
prerenderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode,
onError,
staleTimeIterable,
false // forceOmitParams — server-initiated background prefetch, not a shell request
staleTimeIterable
)
await result.prelude.pipeTo(writable)
......@@ -1644,11 +1669,12 @@ async function generateRuntimePrefetchResult(
req: BaseNextRequest,
ctx: AppRenderContext,
requestStore: RequestStore,
forceOmitParams: boolean
isShellPrefetch: boolean
): Promise<RenderResult> {
const { workStore, renderOpts } = ctx
const { isBuildTimePrerendering = false, onInstrumentationRequestError } =
renderOpts
const { appShells } = renderOpts.experimental
function onFlightDataRenderError(err: DigestedError, silenceLog: boolean) {
return onInstrumentationRequestError?.(
......@@ -1691,21 +1717,35 @@ async function generateRuntimePrefetchResult(
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode,
forceOmitParams
requestStore.draftMode
)
const mode: RuntimePrerenderMode = appShells
? isShellPrefetch
? { type: 'session-shell-only' }
: {
type: 'rewindable-session-shell',
shellByteLengthDeferred: createPromiseWithResolvers(),
}
: { type: 'runtime-only' }
const response = await finalRuntimeServerPrerender(
mode,
ctx,
generateDynamicRSCPayload.bind(null, ctx, { staleTimeIterable }),
generateDynamicRSCPayload.bind(null, ctx, {
staleTimeIterable,
shellByteLengthPromise:
mode.type === 'rewindable-session-shell'
? mode.shellByteLengthDeferred.promise
: undefined,
}),
prerenderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode,
onError,
staleTimeIterable,
forceOmitParams
staleTimeIterable
)
applyMetadataFromPrerenderResult(response, metadata, workStore)
......@@ -1716,13 +1756,12 @@ async function generateRuntimePrefetchResult(
async function prospectiveRuntimeServerPrerender(
ctx: AppRenderContext,
getPayload: () => any,
getPayload: () => Promise<RSCPayload>,
resumeDataCache: PrerenderResumeDataCache | null,
rootParams: Params,
headers: PrerenderStoreModernRuntime['headers'],
cookies: PrerenderStoreModernRuntime['cookies'],
draftMode: PrerenderStoreModernRuntime['draftMode'],
forceOmitParams: boolean
draftMode: PrerenderStoreModernRuntime['draftMode']
) {
const { implicitTags, renderOpts, workStore } = ctx
const { ComponentMod } = renderOpts
......@@ -1771,7 +1810,6 @@ async function prospectiveRuntimeServerPrerender(
headers,
cookies,
draftMode,
forceOmitParams,
}
const { clientModules } = getClientReferenceManifest()
......@@ -1871,23 +1909,31 @@ function prependIsPartialByteToChunks(
return [new Uint8Array([markerByte]), ...chunks]
}
type RuntimePrerenderMode =
| { type: 'runtime-only' }
| { type: 'session-shell-only' }
| {
type: 'rewindable-session-shell'
shellByteLengthDeferred: PromiseWithResolvers<number | null>
}
async function finalRuntimeServerPrerender(
mode: RuntimePrerenderMode,
ctx: AppRenderContext,
getPayload: () => any,
getPayload: () => Promise<RSCPayload>,
resumeDataCache: PrerenderResumeDataCache | null,
rootParams: Params,
headers: PrerenderStoreModernRuntime['headers'],
cookies: PrerenderStoreModernRuntime['cookies'],
draftMode: PrerenderStoreModernRuntime['draftMode'],
onError: (err: unknown) => string | undefined,
staleTimeIterable: StaleTimeIterable,
forceOmitParams: boolean
staleTimeIterable: StaleTimeIterable
) {
const { implicitTags, renderOpts } = ctx
const { ComponentMod, experimental, isDebugDynamicAccesses } = renderOpts
const selectStaleTime = createSelectStaleTime(experimental)
let serverIsDynamic = false
let resultIsPartial = false
const finalServerController = new AbortController()
const serverDynamicTracking = createDynamicTrackingState(
......@@ -1898,7 +1944,11 @@ async function finalRuntimeServerPrerender(
abortSignal: finalServerController.signal,
abandonController: null,
shouldTrackSyncIO: true,
finalStage: RenderStage.Runtime,
// we only reach the runtime stage if we're doing a rewindable render
finalStage:
mode.type === 'session-shell-only'
? RenderStage.ShellRuntime
: RenderStage.Runtime,
})
const varyParamsAccumulator = createResponseVaryParamsAccumulator()
......@@ -1928,7 +1978,6 @@ async function finalRuntimeServerPrerender(
headers,
cookies,
draftMode,
forceOmitParams,
}
trackStaleTime(finalServerPrerenderStore, staleTimeIterable, selectStaleTime)
......@@ -1942,6 +1991,8 @@ async function finalRuntimeServerPrerender(
const streamState = createStreamPendingState()
const collectedChunks = createPrerenderChunksAccumulator()
const stageByteLengths =
mode.type === 'rewindable-session-shell' ? createStageByteLengths() : null
await runInSequentialTasks(
async () => {
......@@ -1949,7 +2000,7 @@ async function finalRuntimeServerPrerender(
// Non-prefetchable segments are gated until the first late stage.
finalStageController.advanceStage(RenderStage.ShellEarlyStatic)
const stream = workUnitAsyncStorage.run(
let stream = workUnitAsyncStorage.run(
finalServerPrerenderStore,
ComponentMod.renderToReadableStream,
finalRSCPayload,
......@@ -1961,6 +2012,17 @@ async function finalRuntimeServerPrerender(
}
)
if (stageByteLengths) {
let countStream: typeof stream
;[stream, countStream] = stream.tee()
void countStageBytesUntilAbortWeb(
stageByteLengths,
countStream,
finalStageController,
finalServerController.signal
).catch(() => {})
}
// Note: this await will only resolve after the last task (unless sync IO aborts the render earlier)
// We await it here so that if the stream errors, it's not an unhandled rejection.
await collectPrerenderChunksWeb(
......@@ -1981,25 +2043,32 @@ async function finalRuntimeServerPrerender(
finalStageController.advanceStage(RenderStage.Static)
},
() => {
// TODO(app-shells): resolve session data for runtime-prefetchable segments here
// Resolve session data for runtime-prefetchable segments.
// Sync IO is NOT allowed here.
finalStageController.advanceStage(RenderStage.ShellEarlyRuntime)
},
() => {
// TODO(app-shells): resolve session data here for non-prefetchable segments here
// Resolve session data for non-prefetchable segments.
// Sync IO is allowed here.
finalStageController.advanceStage(RenderStage.ShellRuntime)
},
() => {
// TODO(app-shells): resolve link data for runtime-prefetchable segments here
// Resolve runtime data for runtime-prefetchable segments.
if (mode.type === 'session-shell-only') {
// We're only rendering a shell, so we do not advance to stages where link data is resolved.
return
}
// Resolve link data for runtime-prefetchable segments.
// Sync IO is NOT allowed here.
finalStageController.advanceStage(RenderStage.EarlyRuntime)
},
() => {
// TODO(app-shells): resolve link data for runtime-prefetchable segments here
// Resolve runtime data for non-prefetchable segments.
if (mode.type === 'session-shell-only') {
// We're only rendering a shell, so we do not advance to stages where link data is resolved.
return
}
// Resolve link data for non-prefetchable segments.
// Sync IO is allowed here.
// TODO(app-shells): This is strange: we allow sync IO here, but we don't want sync IO in a fallback.
finalStageController.advanceStage(RenderStage.Runtime)
},
async () => {
......@@ -2007,7 +2076,7 @@ async function finalRuntimeServerPrerender(
// If the server controller is already aborted we must have called
// something that required aborting the prerender synchronously such
// as with new Date()
serverIsDynamic = true
resultIsPartial = true
// FIXME(NAR-810): If we're already aborted due to Sync IO, there should be no need to
// finish the accumulators. However, it seems like in `--debug-prerender`
......@@ -2022,15 +2091,31 @@ async function finalRuntimeServerPrerender(
return
}
if (mode.type === 'rewindable-session-shell' && stageByteLengths) {
// If advancing to the runtime stage didn't unblock new content,
// then the result does not depend on link data and can be used as a shell (indicated via `null`).
// Otherwise, send a byte length to indicate where the shell content ends.
const didLinkDataUnblockNewContent =
stageByteLengths[RenderStage.Runtime] >
stageByteLengths[RenderStage.ShellRuntime]
mode.shellByteLengthDeferred.resolve(
didLinkDataUnblockNewContent
? stageByteLengths[RenderStage.ShellRuntime]
: null
)
}
staleTimeIterable.close()
finishAccumulatingVaryParams(varyParamsAccumulator)
// We're using a render, not a prerender, so React schedules rendering work in fast immediates,
// and we need to wait a fast immediate for the stale time/vary params chunks to flush.
await waitAtLeastOneReactRenderTask()
if (streamState.isPending) {
// If the prerender is still pending then it must depend on dynamic data.
serverIsDynamic = true
// If the prerender is still pending then it must depend on dynamic data
// (or, if this is a shell prefetch, link data)
resultIsPartial = true
}
workUnitAsyncStorage.run(
finalServerPrerenderStore,
......@@ -2043,7 +2128,7 @@ async function finalRuntimeServerPrerender(
prelude: new ReactServerPrerenderResult(
prependIsPartialByteToChunks(
collectedChunks.prerenderChunks,
serverIsDynamic
resultIsPartial
)
).consumeAsStream(),
}
......@@ -2053,7 +2138,7 @@ async function finalRuntimeServerPrerender(
// TODO(runtime-ppr): do we need to produce a digest map here?
// digestErrorsMap: ...,
dynamicAccess: serverDynamicTracking,
isPartial: serverIsDynamic,
isPartial: resultIsPartial,
collectedRevalidate: finalServerPrerenderStore.revalidate,
collectedExpire: finalServerPrerenderStore.expire,
collectedStale: staleTimeIterable.currentValue,
......@@ -5460,6 +5545,60 @@ async function countStaticStageBytesNode(
return byteLength
}
type StageByteLengths = Record<AdvanceableRenderStage, number>
function createStageByteLengths(): StageByteLengths {
const result: Partial<StageByteLengths> = {}
for (const stage of RENDER_STAGE_ADVANCE_ORDER) {
result[stage] = 0
}
return result as StageByteLengths
}
async function countStageBytesUntilAbortWeb(
byteLengths: StageByteLengths,
stream: ReadableStream<Uint8Array>,
stageController: StagedRenderingController,
abortSignal: AbortSignal
): Promise<void> {
const reader = stream.getReader()
abortSignal.addEventListener('abort', reader.cancel.bind(reader), {
once: true,
})
while (true) {
const { done, value } = await reader.read()
if (done || abortSignal.aborted) {
break
}
increaseChunkByteLengths(
byteLengths,
stageController.currentStage,
value.byteLength
)
}
}
function increaseChunkByteLengths(
byteLengths: StageByteLengths,
currentStage: RenderStage,
length: number
) {
if (!isAdvanceableRenderStage(currentStage)) {
return
}
// Later stages include earlier stages, so we increment
// the byte count for all that are `>= currentStage`.
// Iterate in reverse so we don't have to skip the earlier ones.
for (let i = RENDER_STAGE_ADVANCE_ORDER.length - 1; i >= 0; i--) {
const stage = RENDER_STAGE_ADVANCE_ORDER[i]
if (stage < currentStage) {
break
}
byteLengths[stage] += length
}
}
function createAsyncApiPromises(
stagedRendering: StagedRenderingController,
cookies: RequestStore['cookies'],
......
......@@ -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