Unverified Commit 3cd6d4dd authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Track whether runtime data is accessed during prefetch (#95964)

Adds a server-computed signal to static per-segment prefetch responses
that tells the client whether a runtime prefetch request would return
more content than the static response already contains.

The signal is computed by tracking whether the prerender accessed any
data source that hangs during a static prerender but would resolve
during a runtime prerender. For example: cookies, headers, fallback
params, and search params.

The information is encoded two places:

- As a prefetch hint called ShouldAttemptStaticPrefetch. This tells the
client that it's worth attempting to do a static prefetch instead of a
runtime one. It's only an optimization, though: if the static response
ends up being insufficient, the client will follow it up with a runtime
request. It's semantically OK if there are false positives.
- Embedded in the static segment response. This tells the client whether
the static response is missing data that would have been included in a
runtime response. Unlike the prefetch hint, this value must never
falsely claim that no runtime request is needed.

A follow-up will update the client to skip the runtime request using
this information. This commit only encodes the signal into the response.
parent 31b78bbe
......@@ -855,10 +855,15 @@ function pingRootRouteTree(
// opt-in because the Shell for a given route is reusable across
// all given params, by definition. So it does not lead to an
// explosion in prefetching costs.
// TODO: In the future, the server could emit a hint to tell us
// *not* to prefetch via a runtime request, via build-time
// heuristics, like if no `cookies()` call was detected. We'll
// leave this optimization for later.
// TODO: The server now emits signals for skipping unnecessary
// runtime prefetch requests: an advisory
// PrefetchHint.ShouldAttemptStaticPrefetch bit on the route
// tree, and a load-bearing response-level `needsRuntimeRequest`
// promise on the static segment responses (fulfilled `true`
// visible in the decode means a runtime request would return
// more; rewindable at the shell boundary; combined with each
// segment's `isPartial`). They aren't consumed yet; wiring them
// up is left for a follow-up.
task.phase === PrefetchPhase.Shell
) {
const runtimeStrategy =
......@@ -1139,6 +1144,10 @@ function pingNewPartOfCacheComponentsTree(
// runtime shell request. For fully static pages, it doesn't matter since
// server will respond to even a runtime request with a static response. For
// a partially static page, we can send down a hint from the server.
// The server-side hints for this now exist
// (PrefetchHint.ShouldAttemptStaticPrefetch on the route tree, the
// `needsRuntimeRequest` promise + per-segment `isPartial` on static
// segment responses) but aren't consumed yet.
if (
task.phase === PrefetchPhase.Speculative &&
......
......@@ -44,6 +44,7 @@ import {
ClientHookDynamicError,
isClientHookDynamicError,
makeClientHookHangingPromise,
trackRuntimeDataAccessed,
} from '../dynamic-rendering-utils'
import {
METADATA_BOUNDARY_NAME,
......@@ -361,6 +362,15 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
errorWithStack: Error,
prerenderStore: PrerenderStoreModern
): never {
// The synchronously accessed request data would have been available during
// a runtime prerender, which would have rendered past this point instead of
// aborting — so a runtime prefetch would produce more content than this
// render. Record that, same as when request data access creates a hanging
// promise (see makeRuntimeHangingPromise). Unlike
// `abortOnSynchronousPlatformIOAccess`, which aborts a runtime prerender
// all the same and therefore must not record anything.
trackRuntimeDataAccessed(prerenderStore)
const prerenderSignal = prerenderStore.controller.signal
if (prerenderSignal.aborted === false) {
// TODO it would be better to move this aborted check into the callsite so we can avoid making
......
......@@ -307,7 +307,7 @@ export class StagedRenderingController {
)
: stagePromise.then(() => resolvedValue)
// Analogously to `makeHangingPromise`, we might reject this promise if the signal is invoked.
// Analogously to `makeDynamicHangingPromise`, we might reject this promise if the signal is invoked.
// (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).
// We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.
if (this.abortSignal) {
......
......@@ -152,6 +152,56 @@ export interface PrerenderStoreModernServer
readonly type: 'prerender'
readonly stagedRendering: StagedRenderingController | null
/**
* When not null, records whether the render has accessed a data source
* that hangs during a static prerender but would resolve during a runtime
* prerender — cookies, headers, fallback params, searchParams, and cache
* entries excluded only from static prerenders. Call sites go through
* `trackRuntimeDataAccessed`, which resolves the promise `true` on the
* first access; it's resolved `false` when the prerender completes without
* one. Promise resolution is idempotent, so the flag is monotonic with no
* extra state.
*
* The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)
* so the fulfillment row's stream position records the stage the access
* happened in; the per-segment prefetch encoding (`collectSegmentData`)
* extracts it from the page data to tell the client whether a runtime
* prefetch request could be skipped. Tracking is page-global: an access
* anywhere in the page poisons all segments (per-segment granularity is
* recovered downstream for segments whose content is provably complete).
* Shared between the payload prerender store and the render store because
* request-data props are created during payload construction, before the
* render store exists. Null for warmup, route-handler, and error prerender
* stores.
*/
readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null
/**
* Mutable single-boolean companion to `runtimeDataAccessed`, holding this
* prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement
* directly — the value that becomes the route's build-constant hint:
* starts `true`, and a disqualifying runtime-data access flips it to
* `false`. Not every access that resolves the promise disqualifies —
* fallback-param accesses on a fallback-upgradeable route are transient
* and leave the hint intact (see `trackRuntimeDataAccessed`, which applies
* the rule at access time using `isFallbackUpgradeable` below). A plain
* boolean suffices because the hint needs no stream positioning: unlike
* `runtimeDataAccessed`, whose fulfillment position encodes which stage
* the access happened in, this is read once after the prerender settles.
* Held in a cell so it can be shared. Same sharing and null rules as
* `runtimeDataAccessed`.
*/
readonly shouldAttemptStaticPrefetch: { current: boolean } | null
/**
* Whether a fallback shell produced by this prerender could later be
* upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:
* at least one fallback param is a `generateStaticParams` candidate).
* Consulted by `trackRuntimeDataAccessed` to decide whether a
* fallback-param access disqualifies the static-prefetch hint.
*/
readonly isFallbackUpgradeable: boolean
}
export interface PrerenderStoreModernRuntime
......
......@@ -2,7 +2,10 @@ import {
RenderStage,
type AdvanceableRenderStage,
} from './app-render/staged-rendering'
import type { RequestStore } from './app-render/work-unit-async-storage.external'
import type {
RequestStore,
WorkUnitStore,
} from './app-render/work-unit-async-storage.external'
import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'
import { getServerReact, getClientReact } from './runtime-reacts.external'
......@@ -62,13 +65,22 @@ type AbortListeners = Array<() => void>
const abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()
/**
* This function constructs a promise that will never resolve. This is primarily
* useful for cacheComponents where we use promise resolution timing to determine which
* parts of a render can be included in a prerender.
* Constructs a promise that never resolves, standing in for *dynamic* data:
* data that is only available during a real dynamic request and hangs in
* every kind of prerender — `io()`, `connection()`, uncached `fetch()`.
*
* This is primarily useful for cacheComponents where we use promise
* resolution timing to determine which parts of a render can be included in a
* prerender.
*
* Records nothing on the prerender store: the promise's holes are only ever
* filled by a real dynamic request, so a runtime prefetch response would have
* the same holes as the static one. If the data source would resolve during a
* runtime prerender, use `makeRuntimeHangingPromise` instead.
*
* @internal
*/
export function makeHangingPromise<T>(
export function makeDynamicHangingPromise<T>(
signal: AbortSignal,
route: string,
expression: string
......@@ -79,6 +91,195 @@ export function makeHangingPromise<T>(
)
}
/**
* Constructs a promise that never resolves, standing in for *runtime* data:
* data that hangs during a static prerender but is available during a runtime
* prerender (the kind that backs a runtime prefetch request: request data
* like cookies and headers is available, but the render is still not a real
* dynamic request). Examples: cookies, headers, fallback params,
* searchParams, and cache entries that are excluded only from static
* prerenders.
*
* Creating one of these during a static prerender records on the prerender
* store that a runtime prefetch would produce more content than the static
* response (`runtimeDataAccessed`), which the segment prefetch encoding uses
* to tell the client whether a runtime prefetch request could be skipped.
*
* When unsure whether data is dynamic or runtime, prefer this method — the
* cost of over-recording is a redundant runtime prefetch request; the cost of
* under-recording is a permanently missing one.
*
* `workUnitStore` may be null ONLY when the caller tracks the access itself
* at observation time instead of creation time. This is for promises the
* framework creates eagerly whether or not anything reads them (e.g. the
* `searchParams` prop constructed for every page): recording at creation
* would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`
* from every path that observes the promise (e.g. the proxy traps for
* `then`/`status`), against the work unit store active at access time.
*
* For fallback-param data — data a concrete (ISR-upgraded) prerender would
* resolve — use `makeFallbackParamsHangingPromise` instead, so the access
* is recorded with the right effect on the static-prefetch hint.
*
* @internal
*/
export function makeRuntimeHangingPromise<T>(
signal: AbortSignal,
route: string,
expression: string,
workUnitStore: WorkUnitStore | null
): Promise<T> {
if (workUnitStore !== null) {
trackRuntimeDataAccessed(workUnitStore)
}
return makeHangingPromiseWithError(
signal,
new HangingPromiseRejectionError(route, expression)
)
}
/**
* Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback
* route params and values derived solely from them (`params`, `rootParams`,
* `pathname` during a fallback prerender). Like every runtime data access it
* records the access on the prerender store's response-level flag, but its
* effect on the build-time static-prefetch hint differs — on a
* fallback-upgradeable route the access is transient (a concrete prerender
* resolves it), so it leaves the hint intact. See
* `trackFallbackParamsAccessed`.
*
* As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when
* the caller tracks the access itself at observation time instead of creation
* time, by calling `trackFallbackParamsAccessed` from every path that
* observes the promise.
*
* @internal
*/
export function makeFallbackParamsHangingPromise<T>(
signal: AbortSignal,
route: string,
expression: string,
workUnitStore: WorkUnitStore | null
): Promise<T> {
if (workUnitStore !== null) {
trackFallbackParamsAccessed(workUnitStore)
}
return makeHangingPromiseWithError(
signal,
new HangingPromiseRejectionError(route, expression)
)
}
/**
* Constructs a promise that never resolves, standing in for data that is only
* accessible in a later *stage* of rendering than this render reaches — e.g.
* a prefetchable short-stale cache entry that's excluded from shells when the
* render ends at the shell stage, or params during a runtime-prefetch render
* that stops before the stage where params resolve.
*
* A render that runs through the later stage would include the data; in
* particular a runtime prefetch renders through its later stages, so on a
* static prerender store this records `runtimeDataAccessed`, same as
* `makeRuntimeHangingPromise`.
*
* @internal
*/
export function makeStageHangingPromise<T>(
signal: AbortSignal,
route: string,
expression: string,
workUnitStore: WorkUnitStore
): Promise<T> {
trackRuntimeDataAccessed(workUnitStore)
return makeHangingPromiseWithError(
signal,
new HangingPromiseRejectionError(route, expression)
)
}
/**
* Records on a static prerender store that the render accessed a data source
* which would have resolved during a runtime prerender. No-op for all other
* store types.
*
* `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this
* automatically; call it directly only where the access is observed
* separately from the promise's creation (see the null `workUnitStore` case
* of `makeRuntimeHangingPromise`), or where the prerender is aborted
* synchronously instead of hanging.
*
* For fallback-param data, use `trackFallbackParamsAccessed` instead. When
* unsure, this is the conservative choice: it unconditionally clears the
* static-prefetch hint.
*/
export function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {
trackRuntimeDataAccessedImpl(workUnitStore, false)
}
/**
* Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of
* fallback route params and values derived solely from them. It records the
* response-level flag all the same, but only clears the build-time
* static-prefetch hint when the route is not fallback-upgradeable — on an
* upgradeable route the access is transient, since ISR later produces a
* concrete prerender that resolves it.
*/
export function trackFallbackParamsAccessed(
workUnitStore: WorkUnitStore
): void {
trackRuntimeDataAccessedImpl(workUnitStore, true)
}
function trackRuntimeDataAccessedImpl(
workUnitStore: WorkUnitStore,
isFallbackParamAccess: boolean
): void {
switch (workUnitStore.type) {
case 'prerender': {
// Response-level flag (the payload's `u`, forwarded to segment
// responses as `needsRuntimeRequest`): resolved for every kind of
// access — a pre-upgrade fallback response must keep reporting that
// a runtime request would return more. The fulfillment row lands at
// the current position in the Flight stream, which is what makes the
// value rewindable per stage. Promise resolution is idempotent, so
// repeated accesses are free.
workUnitStore.runtimeDataAccessed?.resolve(true)
// Hint cell (holds the build-constant
// PrefetchHint.ShouldAttemptStaticPrefetch value directly): a
// fallback-param access is transient when the route is
// fallback-upgradeable — ISR later produces the concrete prerender a
// static prefetch attempt would hit — so it leaves the hint intact.
// (Until that upgrade, the response-level flag above keeps directing
// the client to a runtime fallback; the hint only costs a wasted
// static attempt in the interim.) Every other access clears it.
const hintCell = workUnitStore.shouldAttemptStaticPrefetch
if (
hintCell !== null &&
(!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)
) {
hintCell.current = false
}
break
}
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'validation-client':
case 'request':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
// Only the modern server prerender tracks this; see the field docs on
// PrerenderStoreModernServer.
break
default:
workUnitStore satisfies never
}
}
export function makeClientHookHangingPromise<T>(
signal: AbortSignal,
error: ClientHookDynamicError
......
......@@ -17,7 +17,7 @@ import {
NEXT_CACHE_TAG_MAX_LENGTH,
} from '../../lib/constants'
import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { makeDynamicHangingPromise } from '../dynamic-rendering-utils'
import type { FetchMetric } from '../base-http'
import { createDedupeFetch } from './dedupe-fetch'
import {
......@@ -621,7 +621,7 @@ export function createPatchedFetcher(
cacheSignal = null
}
return makeHangingPromise<Response>(
return makeDynamicHangingPromise<Response>(
workUnitStore.renderSignal,
workStore.route,
'fetch()'
......@@ -756,7 +756,7 @@ export function createPatchedFetcher(
cacheSignal.endRead()
cacheSignal = null
}
return makeHangingPromise<Response>(
return makeDynamicHangingPromise<Response>(
workUnitStore.renderSignal,
workStore.route,
'fetch()'
......@@ -1170,7 +1170,7 @@ export function createPatchedFetcher(
cacheSignal.endRead()
cacheSignal = null
}
return makeHangingPromise<Response>(
return makeDynamicHangingPromise<Response>(
workUnitStore.renderSignal,
workStore.route,
'fetch()'
......@@ -1222,7 +1222,7 @@ export function createPatchedFetcher(
case 'prerender-client':
case 'prerender-runtime':
case 'validation-client':
return makeHangingPromise<Response>(
return makeDynamicHangingPromise<Response>(
workUnitStore.renderSignal,
workStore.route,
'fetch()'
......
......@@ -5,7 +5,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { makeDynamicHangingPromise } from '../dynamic-rendering-utils'
import {
getClientReferenceManifest,
getServerModuleMap,
......@@ -192,7 +192,12 @@ async function getCachedImageResponseArrayBuffer(
// `fetch`), so the image can't be produced statically. Return a hanging
// promise: the body never resolves, and the final prerender's macrotask
// budget then classifies the route as dynamic.
return makeHangingPromise<ArrayBuffer>(
// Whatever dynamic input made the element partial already classified
// itself when it created its own hanging promise (cookies() creates a
// runtime hanging promise, an uncached fetch creates a dynamic one,
// ...), so this wrapper adds no new information and can use the
// non-recording dynamic variant.
return makeDynamicHangingPromise<ArrayBuffer>(
renderSignal,
workStore.route,
'dynamic `ImageResponse`'
......
......@@ -10,7 +10,7 @@ import {
} from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
makeHangingPromise,
makeDynamicHangingPromise,
makeDevtoolsIOAwarePromise,
} from '../dynamic-rendering-utils'
import { isRequestApiAllowedInCurrentPhase } from './utils'
......@@ -83,7 +83,7 @@ export function connection(): Promise<void> {
case 'prerender-runtime':
// We return a promise that never resolves to allow the prerender to
// stall at this point.
return makeHangingPromise(
return makeDynamicHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`connection()`'
......
......@@ -22,7 +22,7 @@ import {
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
makeRuntimeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
......@@ -174,10 +174,11 @@ function makeHangingCookies(
return cachedPromise
}
const promise = makeHangingPromise<ReadonlyRequestCookies>(
const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>(
prerenderStore.renderSignal,
workStore.route,
'`cookies()`'
'`cookies()`',
prerenderStore
)
CachedCookies.set(prerenderStore, promise)
......
......@@ -20,7 +20,7 @@ import {
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
makeRuntimeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
......@@ -181,10 +181,11 @@ function makeHangingHeaders(
return cachedHeaders
}
const promise = makeHangingPromise<ReadonlyHeaders>(
const promise = makeRuntimeHangingPromise<ReadonlyHeaders>(
prerenderStore.renderSignal,
workStore.route,
'`headers()`'
'`headers()`',
prerenderStore
)
CachedHeaders.set(prerenderStore, promise)
......
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import {
makeHangingPromise,
makeDynamicHangingPromise,
makeDevtoolsIOAwarePromise,
} from '../dynamic-rendering-utils'
import { RenderStage } from '../app-render/staged-rendering'
......@@ -62,7 +62,7 @@ export function io(): Promise<void> {
// When prerendering with Cache Components we consider `io()` to be
// actual IO if not in a cache scope and we can avoid actually executing
// anything after it by making it return a hanging promise.
return makeHangingPromise(
return makeDynamicHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`io()`'
......
......@@ -33,8 +33,9 @@ import {
} from '../../shared/lib/utils/reflect-utils'
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
makeFallbackParamsHangingPromise,
makePromiseFromTrigger,
trackFallbackParamsAccessed,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
......@@ -287,10 +288,11 @@ export function createPrerenderParamsForClientSegment(
// to consider the awaiting of this params object "dynamic". Since
// we are in cacheComponents mode we encode this as a promise that never
// resolves.
return makeHangingPromise(
return makeFallbackParamsHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`params`'
'`params`',
workUnitStore
)
}
}
......@@ -693,6 +695,15 @@ const fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {
return {
[prop]: (...args: unknown[]) => {
// Record against the store that's active at access time: the
// hanging promise is cached by params object across prerender
// stores, so the store that created it may not be the one that's
// rendering when it's finally awaited.
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore !== undefined) {
trackFallbackParamsAccessed(workUnitStore)
}
const store = dynamicAccessAsyncStorage.getStore()
if (store) {
......@@ -724,10 +735,14 @@ function makeHangingParams(
}
const promise = new Proxy(
makeHangingPromise<Params>(
makeFallbackParamsHangingPromise<Params>(
prerenderStore.renderSignal,
workStore.route,
'`params`'
'`params`',
// This promise is created for every segment on a fallback route whether
// or not it reads params, so recording the access at creation would mark
// every render. The access is tracked in the proxy traps instead.
null
),
fallbackParamsProxyHandler
)
......
......@@ -16,7 +16,8 @@ import {
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import {
makeHangingPromise,
makeDynamicHangingPromise,
makeFallbackParamsHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
......@@ -72,7 +73,7 @@ export function createServerPathnameForMetadata(
)
} else {
if (workUnitStore.isSessionShell) {
return makeHangingPromise<string>(
return makeDynamicHangingPromise<string>(
workUnitStore.renderSignal,
workStore.route,
'`pathname`'
......@@ -104,10 +105,14 @@ function createPrerenderPathname(
case 'prerender': {
const fallbackParams = prerenderStore.fallbackRouteParams
if (fallbackParams && fallbackParams.size > 0) {
return makeHangingPromise<string>(
// The pathname only hangs when there are fallback params, and a
// concrete (ISR-upgraded) prerender resolves it — so this access is
// fallback-param data for the static-prefetch hint.
return makeFallbackParamsHangingPromise<string>(
prerenderStore.renderSignal,
workStore.route,
'`pathname`'
'`pathname`',
prerenderStore
)
}
break
......
......@@ -13,7 +13,7 @@ import {
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { makeFallbackParamsHangingPromise } 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'
......@@ -162,10 +162,11 @@ function createPrerenderRootParamPromise(
prerenderStore.fallbackRouteParams &&
prerenderStore.fallbackRouteParams.has(paramName)
) {
return makeHangingPromise<ParamValue>(
return makeFallbackParamsHangingPromise<ParamValue>(
prerenderStore.renderSignal,
workStore.route,
apiName
apiName,
prerenderStore
)
}
break
......
......@@ -30,8 +30,9 @@ import {
import { InvariantError } from '../../shared/lib/invariant-error'
import {
makeDevtoolsIOAwarePromise,
makeHangingPromise,
makeRuntimeHangingPromise,
makePromiseFromTrigger,
trackRuntimeDataAccessed,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
......@@ -178,10 +179,11 @@ export function createPrerenderSearchParamsForClientPage(): Promise<SearchParams
case 'prerender-client':
// We're prerendering in a mode that aborts (cacheComponents) and should stall
// the promise to ensure the RSC side is considered dynamic
return makeHangingPromise(
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`searchParams`'
'`searchParams`',
workUnitStore
)
case 'validation-client':
throw new InvariantError(
......@@ -382,12 +384,24 @@ function makeHangingSearchParams(
return cachedSearchParams
}
const promise = makeHangingPromise<SearchParams>(
const promise = makeRuntimeHangingPromise<SearchParams>(
prerenderStore.renderSignal,
workStore.route,
'`searchParams`'
'`searchParams`',
// This promise is created for every page whether or not it reads search
// params, so recording the access at creation would mark every render.
// The access is tracked in the proxy traps below instead.
null
)
const trackSearchParamsAccessed = () => {
// Record against the store that's active at access time: the promise is
// created while the RSC payload is constructed, but typically accessed
// later, during the render, under a different store.
const workUnitStore = workUnitAsyncStorage.getStore()
trackRuntimeDataAccessed(workUnitStore ?? prerenderStore)
}
const proxyHandler: ProxyHandler<Promise<SearchParams>> = {
get(target, prop, receiver) {
if (Object.hasOwn(target, prop)) {
......@@ -406,6 +420,7 @@ function makeHangingSearchParams(
[prop]: (...args: unknown[]) => {
const expression =
'`await searchParams`, `searchParams.then`, or similar'
trackSearchParamsAccessed()
annotateDynamicAccess(expression, prerenderStore)
// Mirror `makeHangingParams`: when this never-resolving promise
// is awaited while a `use cache` key is being encoded
......@@ -428,6 +443,7 @@ function makeHangingSearchParams(
case 'status': {
const expression =
'`use(searchParams)`, `searchParams.status`, or similar'
trackSearchParamsAccessed()
annotateDynamicAccess(expression, prerenderStore)
return ReflectAdapter.get(target, prop, receiver)
}
......
......@@ -479,6 +479,9 @@ export class AppRouteRouteModule extends RouteModule<
resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined,
varyParamsAccumulator: null,
runtimeDataAccessed: null,
shouldAttemptStaticPrefetch: null,
isFallbackUpgradeable: false,
})
let prospectiveResult
......@@ -575,6 +578,9 @@ export class AppRouteRouteModule extends RouteModule<
resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined,
varyParamsAccumulator: null,
runtimeDataAccessed: null,
shouldAttemptStaticPrefetch: null,
isFallbackUpgradeable: false,
})
let responseHandled = false
......
......@@ -39,7 +39,9 @@ import {
import {
applyOwnerStack,
makeDevtoolsIOAwarePromise,
makeHangingPromise,
makeDynamicHangingPromise,
makeRuntimeHangingPromise,
makeStageHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils'
......@@ -1329,10 +1331,12 @@ async function generateCacheEntryImpl(
// If the prerender is aborted because of dynamic access (e.g. reading
// fallback params), we return a hanging promise. This essentially makes
// the "use cache" function dynamic.
const hangingPromise = makeHangingPromise<never>(
// The dynamic access is a fallback params read, which is runtime data.
const hangingPromise = makeRuntimeHangingPromise<never>(
outerWorkUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
'dynamic "use cache"',
outerWorkUnitStore
)
if (outerWorkUnitStore.cacheSignal) {
......@@ -1714,10 +1718,12 @@ export async function cache(
switch (workUnitStore.type) {
// "use cache: private" is dynamic in prerendering contexts.
case 'prerender':
return makeHangingPromise(
// Private caches can read request data, which is runtime data.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
expression
expression,
workUnitStore
)
case 'prerender-ppr':
return postponeWithTracking(
......@@ -2054,10 +2060,13 @@ export async function cache(
)
if (dynamicAccessAbortController.signal.aborted) {
return makeHangingPromise(
// The dynamic access is a fallback params read, which is runtime
// data.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
'dynamic "use cache"',
workUnitStore
)
}
break
......@@ -2197,10 +2206,13 @@ export async function cache(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
return makeHangingPromise(
// The cache key was marked dynamic because it depends on fallback
// params, which are runtime data.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
'dynamic "use cache"',
workUnitStore
)
case 'prerender-ppr':
case 'prerender-legacy':
......@@ -2308,10 +2320,14 @@ export async function cache(
if (cacheSignal) {
cacheSignal.endRead()
}
return makeHangingPromise(
// The entry is only excluded from *static* prerenders — the
// 'prerender-runtime' case below serves it — so a runtime
// prefetch would include this content.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
'dynamic "use cache"',
workUnitStore
)
case 'prerender-runtime': {
// In the final phase of a runtime prerender, we have to make
......@@ -2426,7 +2442,20 @@ export async function cache(
if (cacheSignal) {
cacheSignal.endRead()
}
return makeHangingPromise(
if (isPrefetchable) {
// The entry was omitted only because this render ends
// before the post-shell stage; a render that reaches its
// post-shell stage would serve it.
return makeStageHangingPromise(
prerenderStore.renderSignal,
workStore.route,
'dynamic "use cache"',
prerenderStore
)
}
// An unprefetchable entry (stale < MIN_PREFETCHABLE_STALE) is
// excluded from runtime prerenders too.
return makeDynamicHangingPromise(
prerenderStore.renderSignal,
workStore.route,
'dynamic "use cache"'
......@@ -2558,10 +2587,13 @@ export async function cache(
// also do here, this covers the case where params are transformed
// with an async function before being passed into the "use cache"
// function, which escapes the instrumentation.
return makeHangingPromise(
// The cache key depends on fallback params, which are runtime
// data.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
'dynamic "use cache"',
workUnitStore
)
}
// fallthrough
......@@ -2580,10 +2612,15 @@ export async function cache(
`Unexpected cache miss after cache warming phase during prerendering. This is likely caused by non-deterministic arguments that differ between the cache warming phase and the final prerender phase (e.g. unstable array order). Ensure that arguments passed to cached functions are deterministic.`
)
)
return makeHangingPromise(
// This is an anomaly (non-deterministic cache key), so we can't
// know whether a runtime prerender would resolve it. Treat it as
// runtime data, conservatively: the cost is at most a redundant
// runtime prefetch request.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
'dynamic "use cache"',
workUnitStore
)
}
break
......@@ -2913,10 +2950,14 @@ export async function cache(
cacheSignal.endRead()
}
const hangingPromise = makeHangingPromise<never>(
// The entry is only excluded from *static* prerenders — the
// 'prerender-runtime' case below serves it — so a runtime
// prefetch would include this content.
const hangingPromise = makeRuntimeHangingPromise<never>(
workUnitStore.renderSignal,
workStore.route,
'dynamic "use cache"'
'dynamic "use cache"',
workUnitStore
)
debug?.('leader resolved as prerender-dynamic', cacheHandlerKey)
resolvableSharedCacheResult.resolve({
......
......@@ -237,6 +237,28 @@ export const enum PrefetchHint {
// `<Link prefetch={true}>` warning — unlike PrefetchDisabled, it has no effect
// on the actual prefetch behavior.
SubtreeHasInstantFalse = 0b10000000000000,
// The client should attempt a static prefetch for this route: the
// build-time prerender did not access any runtime data (cookies, headers,
// searchParams, ...), so a static prefetch is expected to be as complete
// as a runtime one. A fallback-param access only unsets the bit when the
// route can never be upgraded from a fallback to a concrete prerender —
// on an upgradeable route, ISR later produces the concrete prerender a
// static attempt would hit (until then, the static responses' own
// signal reports the insufficiency per response). Purely advisory, and
// both error directions are safe: if set when a runtime request is
// actually needed, that same response-level signal (the load-bearing
// `needsRuntimeRequest` promise combined with each segment's `isPartial`)
// directs the client to follow up — the cost is a wasted static attempt.
// If unset when static would have sufficed, the client goes straight to a
// runtime prefetch, which is a superset of the static response — the cost
// is only reduced cacheability. Like the other bits, this one is computed
// once per build and stays constant for the build's lifetime; it rides
// the prefetch-hints manifest into every response that carries hints —
// `/_tree` prefetch responses and the FlightRouterState of dynamic
// navigations alike. (Routes missing from the manifest — see the #91407
// fallbacks — simply never carry it.) Set on every node of the tree, but
// does not propagate.
ShouldAttemptStaticPrefetch = 0b100000000000000,
}
/**
......@@ -434,6 +456,27 @@ export type InitialRSCPayload = {
r?: VaryParamsIterable
/** staleTime in seconds - Only present when Cache Components is enabled. */
s?: AsyncIterable<number>
/**
* runtimeDataAccessed — whether the render has accessed a data source that
* hangs during a static prerender but would resolve during a runtime
* prerender (cookies, headers, fallback params, searchParams, ...). The
* flag is monotonic (false → true, at most once), so it's encoded as a
* promise: resolved `true` at the moment of first access — the fulfillment
* row's position in the stream records the stage the access happened in —
* or resolved `false` when the prerender completes without one, a row that
* lands past every stage boundary. A truncated (shell) decode therefore
* reads the answer as of the shell stage: fulfilled `true` iff the access
* happened during a stage it includes, pending (⇒ no access) otherwise.
* Unlike an async iterable, a pending promise costs Flight no abort
* listener on the render. Used when generating per-segment prefetch
* responses (forwarded as the response-level `needsRuntimeRequest`).
* The build-constant `PrefetchHint.ShouldAttemptStaticPrefetch` is
* tracked directly on the prerender store instead (its
* `shouldAttemptStaticPrefetch` cell) — it needs neither stream
* positioning nor this flag's param/non-param blindness. Only present
* for static prerenders when Cache Components is enabled.
*/
u?: Promise<boolean>
/** staticStageByteLength - Resolves when the static stage ends. */
l?: Promise<number>
/**
......
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