Unverified Commit 4580da17 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Replace WorkStore isStaticGeneration with executionMode (#96570)

## Summary

- replace `WorkStore.isStaticGeneration` with an explicit `'prerender' |
'request'` execution mode
- preserve the existing derivation and behavior while making the
render/prerender distinction explicit
- document that prerendering includes both build-time generation and
runtime revalidation
- establish groundwork for moving the render decision higher in the
stack and replacing downstream mode checks with purpose-specific state

Stacked on #96564.
parent da0529d6
......@@ -6,7 +6,7 @@ import { workAsyncStorage } from './server-async-storage'
export function handleISRError({ error }: { error: any }) {
if (workAsyncStorage) {
const store = workAsyncStorage.getStore()
if (store?.isStaticGeneration) {
if (store?.executionMode === 'prerender') {
if (error) {
console.error(error)
}
......
......@@ -706,7 +706,7 @@ const createMockWorkStore = (afterContext: AfterContext): WorkStore => {
forceStatic: false,
forceDynamic: false,
dynamicShouldError: false,
isStaticGeneration: false,
executionMode: 'request',
pendingRevalidatedTags: [],
pendingRevalidates: undefined,
pendingRevalidateWrites: undefined,
......
......@@ -644,7 +644,7 @@ export async function handleAction({
return handleUnrecognizedFetchAction(error)
}
if (workStore.isStaticGeneration) {
if (workStore.executionMode === 'prerender') {
throw new Error(
"Invariant: server actions can't be handled during static rendering"
)
......
......@@ -791,7 +791,9 @@ async function generateDynamicRSCPayload(
// With Cache Components, all routes support it. Without it, only fully
// static pages do, because their per-segment prefetch responses are
// generated during static generation (build or ISR).
S: workStore.isStaticGeneration || ctx.renderOpts.cacheComponents,
S:
workStore.executionMode === 'prerender' ||
ctx.renderOpts.cacheComponents,
h: getMetadataVaryParamsAccumulator(),
r: getRootParamsVaryParamsAccumulator() ?? undefined,
}
......@@ -820,7 +822,7 @@ async function generateDynamicRSCPayload(
// its presence as authoritative.
// TODO: Move this to the prefetch hints file so we don't have to walk the
// tree on every render.
if (!workStore.isStaticGeneration) {
if (workStore.executionMode !== 'prerender') {
const dynamicStaleTime = await getDynamicStaleTime(
ctx.componentMod.routeModule.userland.loaderTree
)
......@@ -842,7 +844,10 @@ function createErrorContext(
// TODO: is this correct if `isPossibleServerAction` is a false positive?
routeType: ctx.isPossibleServerAction ? 'action' : 'render',
renderSource,
revalidateReason: getRevalidateReason(ctx.workStore),
revalidateReason: getRevalidateReason({
isOnDemandRevalidate: ctx.workStore.isOnDemandRevalidate,
isStaticGeneration: ctx.workStore.executionMode === 'prerender',
}),
}
}
......@@ -2095,7 +2100,7 @@ async function getRSCPayload(
prefetchInliningEnabled,
ctx.renderOpts.cacheComponents,
ctx.renderOpts.partialPrefetching,
workStore.isStaticGeneration,
workStore.executionMode === 'prerender',
ctx.renderOpts.isBuildTimePrerendering ?? false,
getDynamicParamFromSegment,
query
......@@ -2180,7 +2185,7 @@ async function getRSCPayload(
//
// See similar comment in create-component-tree.tsx for more context.
const isPossiblyPartialHead =
workStore.isStaticGeneration &&
workStore.executionMode === 'prerender' &&
ctx.renderOpts.experimental.isRoutePPREnabled === true
return maybeAppendBuildIdToRSCPayload(ctx, {
......@@ -2205,7 +2210,8 @@ async function getRSCPayload(
// With Cache Components, all routes support it. Without it, only fully
// static pages do, because their per-segment prefetch responses are
// generated during static generation (build or ISR).
S: workStore.isStaticGeneration || ctx.renderOpts.cacheComponents,
S:
workStore.executionMode === 'prerender' || ctx.renderOpts.cacheComponents,
h: getMetadataVaryParamsAccumulator(),
r: getRootParamsVaryParamsAccumulator() ?? undefined,
s: staleTimeIterable,
......@@ -2217,7 +2223,8 @@ async function getRSCPayload(
// authoritative.
// TODO: Move this to the prefetch hints file so we don't have to walk
// the tree on every render.
d: !workStore.isStaticGeneration
d:
workStore.executionMode !== 'prerender'
? ((await getDynamicStaleTime(tree)) ?? undefined)
: undefined,
} satisfies InitialRSCPayload & { P: ReactNode })
......@@ -2297,7 +2304,7 @@ async function getErrorRSCPayload(
errorPrefetchInliningEnabled,
ctx.renderOpts.cacheComponents,
ctx.renderOpts.partialPrefetching,
workStore.isStaticGeneration,
workStore.executionMode === 'prerender',
ctx.renderOpts.isBuildTimePrerendering ?? false,
getDynamicParamFromSegment,
query
......@@ -2341,7 +2348,7 @@ async function getErrorRSCPayload(
)
const isPossiblyPartialHead =
workStore.isStaticGeneration &&
workStore.executionMode === 'prerender' &&
ctx.renderOpts.experimental.isRoutePPREnabled === true
return maybeAppendBuildIdToRSCPayload(ctx, {
......@@ -2362,7 +2369,8 @@ async function getErrorRSCPayload(
// With Cache Components, all routes support it. Without it, only fully
// static pages do, because their per-segment prefetch responses are
// generated during static generation (build or ISR).
S: workStore.isStaticGeneration || ctx.renderOpts.cacheComponents,
S:
workStore.executionMode === 'prerender' || ctx.renderOpts.cacheComponents,
h: getMetadataVaryParamsAccumulator(),
r: getRootParamsVaryParamsAccumulator() ?? undefined,
} satisfies InitialRSCPayload)
......@@ -2687,7 +2695,7 @@ async function renderToHTMLOrFlightImpl(
query = { ...query }
stripInternalQueries(query)
const { isStaticGeneration } = workStore
const isStaticGeneration = workStore.executionMode === 'prerender'
let requestId: string
let htmlRequestId: string
......@@ -6325,7 +6333,7 @@ function buildDevValidationWorkStore(
})
return {
isStaticGeneration: false,
executionMode: 'request',
page: message.page,
route: message.route,
forceStatic: message.forceStatic,
......@@ -7908,7 +7916,7 @@ async function validateInstantConfigInBuildWithSample(
// NOTE: Matching the field order in `createWorkStore` to avoid deopting.
const workStore: WorkStore = {
isStaticGeneration: false,
executionMode: 'request',
page: outerWorkStore.page,
route: outerWorkStore.route,
incrementalCache: outerWorkStore.incrementalCache,
......
......@@ -273,7 +273,10 @@ async function createComponentTreeInternal(
workStore.forceDynamic = true
// TODO: (PPR) remove this bailout once PPR is the default
if (workStore.isStaticGeneration && !experimental.isRoutePPREnabled) {
if (
workStore.executionMode === 'prerender' &&
!experimental.isRoutePPREnabled
) {
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
const err = new DynamicServerError(
......@@ -330,7 +333,7 @@ async function createComponentTreeInternal(
if (
!workStore.forceStatic &&
workStore.isStaticGeneration &&
workStore.executionMode === 'prerender' &&
defaultRevalidate === 0 &&
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
......@@ -385,7 +388,7 @@ async function createComponentTreeInternal(
}
}
const isStaticGeneration = workStore.isStaticGeneration
const isStaticGeneration = workStore.executionMode === 'prerender'
// Assume the segment we're rendering contains only partial data if PPR is
// enabled and this is a statically generated response. This is used by the
......@@ -768,7 +771,7 @@ async function createComponentTreeInternal(
// render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic
if (
workStore.isStaticGeneration &&
workStore.executionMode === 'prerender' &&
workStore.forceDynamic &&
experimental.isRoutePPREnabled
) {
......
......@@ -65,7 +65,7 @@ export async function walkTreeWithFlightRouterState({
const prefetchInliningEnabled = Boolean(experimental.prefetchInlining)
const cacheComponents = ctx.renderOpts.cacheComponents
const partialPrefetching = ctx.renderOpts.partialPrefetching
const isStaticGeneration = workStore.isStaticGeneration
const isStaticGeneration = workStore.executionMode === 'prerender'
const isBuildTimePrerendering =
ctx.renderOpts.isBuildTimePrerendering ?? false
......@@ -387,7 +387,7 @@ export async function createFullTreeFlightDataForNavigation({
Boolean(experimental.prefetchInlining),
ctx.renderOpts.cacheComponents,
ctx.renderOpts.partialPrefetching,
workStoreForInitialRender.isStaticGeneration,
workStoreForInitialRender.executionMode === 'prerender',
ctx.renderOpts.isBuildTimePrerendering ?? false,
getDynamicParamFromSegment,
query
......
......@@ -15,7 +15,12 @@ import type { DigestedError } from './create-error-handler'
import type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind'
export interface WorkStore {
readonly isStaticGeneration: boolean
/**
* Whether this invocation produces reusable prerender output or renders a
* response for the current request. Prerendering includes both build-time
* generation and runtime revalidation.
*/
readonly executionMode: 'prerender' | 'request'
/**
* The page that is being rendered. This relates to the path to the page file.
......
......@@ -113,22 +113,24 @@ export function createWorkStore({
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const isStaticGeneration =
const executionMode =
!renderOpts.supportsDynamicResponse &&
!renderOpts.isDraftMode &&
!renderOpts.isPossibleServerAction
? 'prerender'
: 'request'
const shouldTrackFetchMetrics =
!!process.env.__NEXT_DEV_SERVER ||
// The only times we want to track fetch metrics outside of development is
// when we are performing a static generation and we either are in debug
// mode, or tracking fetch metrics was specifically opted into.
(isStaticGeneration &&
(executionMode === 'prerender' &&
(!!process.env.NEXT_DEBUG_BUILD ||
process.env.NEXT_SSG_FETCH_METRICS === '1'))
const store: WorkStore = {
isStaticGeneration,
executionMode,
page,
route: normalizeAppPath(page),
incrementalCache:
......
......@@ -197,7 +197,7 @@ function buildProbeWorkStore(msg: ProbeMessage): WorkStore {
})
return {
isStaticGeneration: false,
executionMode: 'request',
page: msg.page,
route: msg.route,
useCacheProbeMode: { timeoutMs: msg.timeoutMs },
......
......@@ -1082,7 +1082,7 @@ export function createPatchedFetcher(
if (entry?.value && entry.value.kind === CachedRouteKind.FETCH) {
// when stale and is revalidating we wait for fresh data
// so the revalidated entry has the updated data
if (workStore.isStaticGeneration && entry.isStale) {
if (workStore.executionMode === 'prerender' && entry.isStale) {
isForegroundRevalidate = true
} else {
if (entry.isStale) {
......@@ -1143,7 +1143,7 @@ export function createPatchedFetcher(
}
if (
(workStore.isStaticGeneration ||
(workStore.executionMode === 'prerender' ||
(process.env.NODE_ENV === 'development' &&
process.env.__NEXT_CACHE_COMPONENTS &&
workUnitStore &&
......
......@@ -703,7 +703,7 @@ describe('local span recording', () => {
require('./tracer') as typeof import('./tracer')
const workStore = {
isStaticGeneration: false,
executionMode: 'request',
page: '/products/[id]/page',
route: '/products/[id]',
cacheComponentsEnabled: true,
......
......@@ -378,7 +378,7 @@ export class AppRouteRouteModule extends RouteModule<
request: NextRequest,
context: AppRouteRouteHandlerContext
) {
const isStaticGeneration = workStore.isStaticGeneration
const isStaticGeneration = workStore.executionMode === 'prerender'
const cacheComponentsEnabled = !!context.renderOpts.cacheComponents
// Patch the global fetch.
......@@ -832,7 +832,7 @@ export class AppRouteRouteModule extends RouteModule<
? hasNonStaticMethods(liveUserland)
: this._hasNonStaticMethods
if (hasNonStatic) {
if (workStore.isStaticGeneration) {
if (workStore.executionMode === 'prerender') {
const err = new DynamicServerError(
'Route is configured with methods that cannot be statically generated.'
)
......@@ -855,7 +855,7 @@ export class AppRouteRouteModule extends RouteModule<
case 'force-dynamic': {
// Routes of generated paths should be dynamic
workStore.forceDynamic = true
if (workStore.isStaticGeneration) {
if (workStore.executionMode === 'prerender') {
const err = new DynamicServerError(
'Route is configured with dynamic = error which cannot be statically generated.'
)
......@@ -877,7 +877,7 @@ export class AppRouteRouteModule extends RouteModule<
// The dynamic property is set to error, so we should throw an
// error if the page is being statically generated.
workStore.dynamicShouldError = true
if (workStore.isStaticGeneration)
if (workStore.executionMode === 'prerender')
request = new Proxy(req, requireStaticRequestHandlers)
break
case undefined:
......
......@@ -3120,7 +3120,7 @@ export async function cache(
? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)
: entry.expire) *
1000 ||
(workStore.isStaticGeneration &&
(workStore.executionMode === 'prerender' &&
currentTime > entry.timestamp + entry.revalidate * 1000)
) {
// Miss. Generate a new result.
......@@ -3144,7 +3144,7 @@ export async function cache(
}
if (
workStore.isStaticGeneration &&
workStore.executionMode === 'prerender' &&
currentTime > entry.timestamp + entry.revalidate * 1000
) {
debug?.('static generation, entry is stale', cacheHandlerKey)
......
......@@ -280,7 +280,7 @@ export function unstable_cache<T extends Callback>(
// Attach the empty catch here so we don't get a "unhandled promise
// rejection" warning. (Behavior is matched with patch-fetch)
if (workStore.isStaticGeneration) {
if (workStore.executionMode === 'prerender') {
revalidationPromise.catch(() => {})
}
......@@ -289,7 +289,7 @@ export function unstable_cache<T extends Callback>(
}
// Check if we need to do foreground revalidation
if (workStore.isStaticGeneration) {
if (workStore.executionMode === 'prerender') {
// When the page is revalidating and the cache entry is stale,
// we need to wait for fresh data (blocking revalidate). The
// `await` here keeps `cacheSignal.endRead` (in the outer
......
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