Unverified Commit ab7fc5fb authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Remove WorkStore execution mode (#96674)

## Summary

This removes the intermediate `executionMode` from `WorkStore` now that
App Page and App Route select their render or prerender pipeline before
constructing the store.

- Derive ISR error handling from the active `WorkUnitStore`
- Derive fetch configuration processing from the active `WorkUnitStore`,
including treating cache scopes as owners of their cache policy
regardless of the outer render operation
- Use explicit render and prerender WorkStore constructors where
fetch-metric behavior differs
- Keep the App Page render/prerender operation local to the top-level
route-module dispatch

This completes the migration away from global render-mode state on
`WorkStore`, allowing downstream behavior to depend on the more precise
work-unit scope instead.

<!-- NEXT_JS_LLM -->
parent f226166c
...@@ -897,7 +897,6 @@ export async function buildAppStaticPaths({ ...@@ -897,7 +897,6 @@ export async function buildAppStaticPaths({
const store = createWorkStore({ const store = createWorkStore({
page, page,
executionMode: 'request',
renderOpts: { renderOpts: {
incrementalCache, incrementalCache,
cacheLifeProfiles, cacheLifeProfiles,
......
import type { LoaderTree } from '../../server/lib/app-dir-module' import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { IncomingMessage, ServerResponse } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http'
import type { FallbackRouteParam } from '../static-paths/types' import type { FallbackRouteParam } from '../static-paths/types'
import type { WorkStoreExecutionMode } from '../../server/app-render/work-async-storage.external'
import { import {
AppPageRouteModule, AppPageRouteModule,
...@@ -94,6 +93,8 @@ import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-trans ...@@ -94,6 +93,8 @@ import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-trans
import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes' with { 'turbopack-transition': 'next-server-utility' } import { isInterceptionRouteAppPath } from '../../shared/lib/router/utils/interception-routes' with { 'turbopack-transition': 'next-server-utility' }
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' } import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' }
type AppPageRenderOperation = 'render' | 'prerender'
/** /**
* Builds the cache key for the most complete prerenderable shell we can derive * Builds the cache key for the most complete prerenderable shell we can derive
* from the shell that matched this request. Only params that can still be * from the shell that matched this request. Only params that can still be
...@@ -743,13 +744,13 @@ export function createAppPageEntrypoint({ ...@@ -743,13 +744,13 @@ export function createAppPageEntrypoint({
const invokeRouteModule = async ( const invokeRouteModule = async (
span: Span | undefined, span: Span | undefined,
context: AppPageRouteHandlerContext, context: AppPageRouteHandlerContext,
executionMode: WorkStoreExecutionMode renderOperation: AppPageRenderOperation
) => { ) => {
const nextReq = new NodeNextRequest(req) const nextReq = new NodeNextRequest(req)
const nextRes = new NodeNextResponse(res) const nextRes = new NodeNextResponse(res)
const result = const result =
executionMode === 'prerender' renderOperation === 'prerender'
? routeModule.prerender(nextReq, nextRes, context) ? routeModule.prerender(nextReq, nextRes, context)
: routeModule.render(nextReq, nextRes, context) : routeModule.render(nextReq, nextRes, context)
...@@ -827,7 +828,7 @@ export function createAppPageEntrypoint({ ...@@ -827,7 +828,7 @@ export function createAppPageEntrypoint({
span, span,
postponed, postponed,
fallbackRouteParams, fallbackRouteParams,
executionMode, renderOperation,
allowEmptyStaticShell, allowEmptyStaticShell,
}: { }: {
span?: Span span?: Span
...@@ -844,7 +845,7 @@ export function createAppPageEntrypoint({ ...@@ -844,7 +845,7 @@ export function createAppPageEntrypoint({
*/ */
fallbackRouteParams: OpaqueFallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
executionMode: WorkStoreExecutionMode renderOperation: AppPageRenderOperation
}): Promise<ResponseCacheEntry> => { }): Promise<ResponseCacheEntry> => {
const context: AppPageRouteHandlerContext = { const context: AppPageRouteHandlerContext = {
query, query,
...@@ -874,7 +875,7 @@ export function createAppPageEntrypoint({ ...@@ -874,7 +875,7 @@ export function createAppPageEntrypoint({
allowEmptyStaticShell, allowEmptyStaticShell,
serveStreamingMetadata, serveStreamingMetadata,
supportsDynamicResponse: supportsDynamicResponse:
executionMode === 'request' && renderOperation === 'render' &&
(typeof postponed === 'string' || supportsDynamicResponse), (typeof postponed === 'string' || supportsDynamicResponse),
buildManifest, buildManifest,
nextFontManifest, nextFontManifest,
...@@ -991,7 +992,7 @@ export function createAppPageEntrypoint({ ...@@ -991,7 +992,7 @@ export function createAppPageEntrypoint({
}, },
} }
const result = await invokeRouteModule(span, context, executionMode) const result = await invokeRouteModule(span, context, renderOperation)
const { metadata } = result const { metadata } = result
...@@ -1263,7 +1264,7 @@ export function createAppPageEntrypoint({ ...@@ -1263,7 +1264,7 @@ export function createAppPageEntrypoint({
// the background path below will complete the shell into a // the background path below will complete the shell into a
// more specific cache entry for later requests. // more specific cache entry for later requests.
fallbackRouteParams, fallbackRouteParams,
executionMode: 'prerender', renderOperation: 'prerender',
allowEmptyStaticShell: isInstantNavigationTest || undefined, allowEmptyStaticShell: isInstantNavigationTest || undefined,
}), }),
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
...@@ -1321,7 +1322,7 @@ export function createAppPageEntrypoint({ ...@@ -1321,7 +1322,7 @@ export function createAppPageEntrypoint({
remainingFallbackRouteParams remainingFallbackRouteParams
) )
: null, : null,
executionMode: 'prerender', renderOperation: 'prerender',
}) })
}, },
// We don't have a prior entry for this param-specific shell. // We don't have a prior entry for this param-specific shell.
...@@ -1579,7 +1580,7 @@ export function createAppPageEntrypoint({ ...@@ -1579,7 +1580,7 @@ export function createAppPageEntrypoint({
span, span,
postponed, postponed,
fallbackRouteParams, fallbackRouteParams,
executionMode: isRequestSpecificRender ? 'request' : 'prerender', renderOperation: isRequestSpecificRender ? 'render' : 'prerender',
allowEmptyStaticShell: isInstantNavigationTest || undefined, allowEmptyStaticShell: isInstantNavigationTest || undefined,
}) })
} catch (err) { } catch (err) {
...@@ -2122,7 +2123,7 @@ export function createAppPageEntrypoint({ ...@@ -2122,7 +2123,7 @@ export function createAppPageEntrypoint({
// This is a resume render, not a fallback render. Fallback params // This is a resume render, not a fallback render. Fallback params
// (for cacheComponents routes) are plumbed via request meta above. // (for cacheComponents routes) are plumbed via request meta above.
fallbackRouteParams: null, fallbackRouteParams: null,
executionMode: 'request', renderOperation: 'render',
}) })
.then(async (result) => { .then(async (result) => {
if (!result) { if (!result) {
......
import { workAsyncStorage } from './server-async-storage' import { workUnitAsyncStorage } from './server-async-storage'
// if we are revalidating we want to re-throw the error so the // if we are revalidating we want to re-throw the error so the
// function crashes so we can maintain our previous cache // function crashes so we can maintain our previous cache
// instead of caching the error page // instead of caching the error page
export function handleISRError({ error }: { error: any }) { export function handleISRError({ error }: { error: any }) {
if (workAsyncStorage) { if (!workUnitAsyncStorage) {
const store = workAsyncStorage.getStore() return
if (store?.executionMode === 'prerender') { }
const store = workUnitAsyncStorage.getStore()
switch (store?.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
if (error) { if (error) {
console.error(error) console.error(error)
} }
throw error throw error
} case 'request':
case 'prerender-runtime':
case 'validation-client':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
return
default:
store satisfies never
} }
} }
...@@ -706,7 +706,6 @@ const createMockWorkStore = (afterContext: AfterContext): WorkStore => { ...@@ -706,7 +706,6 @@ const createMockWorkStore = (afterContext: AfterContext): WorkStore => {
forceStatic: false, forceStatic: false,
forceDynamic: false, forceDynamic: false,
dynamicShouldError: false, dynamicShouldError: false,
executionMode: 'request',
pendingRevalidatedTags: [], pendingRevalidatedTags: [],
pendingRevalidates: undefined, pendingRevalidates: undefined,
pendingRevalidateWrites: undefined, pendingRevalidateWrites: undefined,
......
...@@ -87,7 +87,10 @@ import { ...@@ -87,7 +87,10 @@ import {
createRequestStoreForRender, createRequestStoreForRender,
} from '../async-storage/request-store' } from '../async-storage/request-store'
import { isRSCRequestHeader } from '../lib/is-rsc-request' import { isRSCRequestHeader } from '../lib/is-rsc-request'
import { createWorkStore } from '../async-storage/work-store' import {
createPrerenderWorkStore,
createWorkStore,
} from '../async-storage/work-store'
import { formatValidationEvent } from './dev-validation-events' import { formatValidationEvent } from './dev-validation-events'
import { createSnapshot } from './async-local-storage' import { createSnapshot } from './async-local-storage'
import { import {
...@@ -3354,7 +3357,6 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -3354,7 +3357,6 @@ export const renderToHTMLOrFlight: AppPageRender = (
parsedRequestHeaders parsedRequestHeaders
const workStore = createWorkStore({ const workStore = createWorkStore({
page: renderOpts.routeModule.definition.page, page: renderOpts.routeModule.definition.page,
executionMode: 'request',
renderOpts, renderOpts,
// @TODO move to workUnitStore of type Request // @TODO move to workUnitStore of type Request
isPrefetchRequest, isPrefetchRequest,
...@@ -3401,9 +3403,8 @@ export const prerenderToHTMLOrFlight: AppPageRender = ( ...@@ -3401,9 +3403,8 @@ export const prerenderToHTMLOrFlight: AppPageRender = (
) )
const { isPrefetchRequest, previouslyRevalidatedTags, nonce } = const { isPrefetchRequest, previouslyRevalidatedTags, nonce } =
parsedRequestHeaders parsedRequestHeaders
const workStore = createWorkStore({ const workStore = createPrerenderWorkStore({
page: renderOpts.routeModule.definition.page, page: renderOpts.routeModule.definition.page,
executionMode: 'prerender',
renderOpts, renderOpts,
// @TODO move to workUnitStore of type Request // @TODO move to workUnitStore of type Request
isPrefetchRequest, isPrefetchRequest,
...@@ -6554,7 +6555,6 @@ function buildDevValidationWorkStore( ...@@ -6554,7 +6555,6 @@ function buildDevValidationWorkStore(
}) })
return { return {
executionMode: 'request',
page: message.page, page: message.page,
route: message.route, route: message.route,
forceStatic: message.forceStatic, forceStatic: message.forceStatic,
...@@ -8137,7 +8137,6 @@ async function validateInstantConfigInBuildWithSample( ...@@ -8137,7 +8137,6 @@ async function validateInstantConfigInBuildWithSample(
// NOTE: Matching the field order in `createWorkStore` to avoid deopting. // NOTE: Matching the field order in `createWorkStore` to avoid deopting.
const workStore: WorkStore = { const workStore: WorkStore = {
executionMode: 'request',
page: outerWorkStore.page, page: outerWorkStore.page,
route: outerWorkStore.route, route: outerWorkStore.route,
incrementalCache: outerWorkStore.incrementalCache, incrementalCache: outerWorkStore.incrementalCache,
......
...@@ -14,16 +14,7 @@ import type { LazyResult } from '../lib/lazy-result' ...@@ -14,16 +14,7 @@ import type { LazyResult } from '../lib/lazy-result'
import type { DigestedError } from './create-error-handler' import type { DigestedError } from './create-error-handler'
import type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind' import type { ActionRevalidationKind } from '../../shared/lib/action-revalidation-kind'
export type WorkStoreExecutionMode = 'prerender' | 'request'
export interface WorkStore { export interface WorkStore {
/**
* 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: WorkStoreExecutionMode
/** /**
* The page that is being rendered. This relates to the path to the page file. * The page that is being rendered. This relates to the path to the page file.
*/ */
......
import type { import type { WorkStore } from '../app-render/work-async-storage.external'
WorkStore,
WorkStoreExecutionMode,
} from '../app-render/work-async-storage.external'
import type { IncrementalCache } from '../lib/incremental-cache' import type { IncrementalCache } from '../lib/incremental-cache'
import type { RenderOpts } from '../app-render/types' import type { RenderOpts } from '../app-render/types'
import type { FetchMetric } from '../base-http' import type { FetchMetric } from '../base-http'
...@@ -25,12 +22,6 @@ export type WorkStoreContext = { ...@@ -25,12 +22,6 @@ export type WorkStoreContext = {
*/ */
page: string page: string
/**
* Whether this invocation produces reusable prerender output or renders a
* response for the current request.
*/
executionMode: WorkStoreExecutionMode
isPrefetchRequest?: boolean isPrefetchRequest?: boolean
nonce?: string nonce?: string
renderOpts: { renderOpts: {
...@@ -94,27 +85,32 @@ export type WorkStoreContext = { ...@@ -94,27 +85,32 @@ export type WorkStoreContext = {
previouslyRevalidatedTags: string[] previouslyRevalidatedTags: string[]
} }
export function createWorkStore({ export function createWorkStore(context: WorkStoreContext): WorkStore {
page, return createWorkStoreImpl(context, !!process.env.__NEXT_DEV_SERVER)
executionMode, }
renderOpts,
isPrefetchRequest, export function createPrerenderWorkStore(context: WorkStoreContext): WorkStore {
buildId, return createWorkStoreImpl(
deploymentId, context,
previouslyRevalidatedTags,
nonce,
}: WorkStoreContext): WorkStore {
const shouldTrackFetchMetrics =
!!process.env.__NEXT_DEV_SERVER || !!process.env.__NEXT_DEV_SERVER ||
// The only times we want to track fetch metrics outside of development is !!process.env.NEXT_DEBUG_BUILD ||
// when we are performing a static generation and we either are in debug process.env.NEXT_SSG_FETCH_METRICS === '1'
// mode, or tracking fetch metrics was specifically opted into. )
(executionMode === 'prerender' && }
(!!process.env.NEXT_DEBUG_BUILD ||
process.env.NEXT_SSG_FETCH_METRICS === '1'))
function createWorkStoreImpl(
{
page,
renderOpts,
isPrefetchRequest,
buildId,
deploymentId,
previouslyRevalidatedTags,
nonce,
}: WorkStoreContext,
shouldTrackFetchMetrics: boolean
): WorkStore {
const store: WorkStore = { const store: WorkStore = {
executionMode,
page, page,
route: normalizeAppPath(page), route: normalizeAppPath(page),
incrementalCache: incrementalCache:
......
...@@ -197,7 +197,6 @@ function buildProbeWorkStore(msg: ProbeMessage): WorkStore { ...@@ -197,7 +197,6 @@ function buildProbeWorkStore(msg: ProbeMessage): WorkStore {
}) })
return { return {
executionMode: 'request',
page: msg.page, page: msg.page,
route: msg.route, route: msg.route,
useCacheProbeMode: { timeoutMs: msg.timeoutMs }, useCacheProbeMode: { timeoutMs: msg.timeoutMs },
......
...@@ -25,6 +25,7 @@ import { ...@@ -25,6 +25,7 @@ import {
shouldRevalidateStaleCacheEntryInForeground, shouldRevalidateStaleCacheEntryInForeground,
type RevalidateStore, type RevalidateStore,
type WorkUnitAsyncStorage, type WorkUnitAsyncStorage,
type WorkUnitStore,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
CachedRouteKind, CachedRouteKind,
...@@ -41,6 +42,44 @@ import type { Span } from './trace/tracer' ...@@ -41,6 +42,44 @@ import type { Span } from './trace/tracer'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
/**
* Whether fetch cache configuration needs to be processed for the current work
* unit before an origin fetch. Static prerender stores use it for dynamic
* access tracking. Cache scopes apply it to their own cache policy, regardless
* of which outer work unit created them. Development staged renders additionally
* coordinate dynamic fetches with the dynamic render stage.
*/
function shouldProcessFetchConfigForWorkUnit(
workUnitStore: WorkUnitStore | undefined
): boolean {
if (!workUnitStore) {
return false
}
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
return true
case 'request':
return Boolean(
process.env.NODE_ENV === 'development' &&
process.env.__NEXT_CACHE_COMPONENTS &&
workUnitStore.stagedRendering
)
case 'prerender-runtime':
case 'validation-client':
case 'generate-static-params':
return false
default:
return workUnitStore satisfies never
}
}
type Fetcher = typeof fetch type Fetcher = typeof fetch
type PatchedFetcher = Fetcher & { type PatchedFetcher = Fetcher & {
...@@ -1147,15 +1186,9 @@ export function createPatchedFetcher( ...@@ -1147,15 +1186,9 @@ export function createPatchedFetcher(
} }
if ( if (
(workStore.executionMode === 'prerender' ||
(process.env.NODE_ENV === 'development' &&
process.env.__NEXT_CACHE_COMPONENTS &&
workUnitStore &&
// eslint-disable-next-line no-restricted-syntax
workUnitStore.type === 'request' &&
workUnitStore.stagedRendering)) &&
init && init &&
typeof init === 'object' typeof init === 'object' &&
shouldProcessFetchConfigForWorkUnit(workUnitStore)
) { ) {
const { cache } = init const { cache } = init
......
...@@ -703,7 +703,6 @@ describe('local span recording', () => { ...@@ -703,7 +703,6 @@ describe('local span recording', () => {
require('./tracer') as typeof import('./tracer') require('./tracer') as typeof import('./tracer')
const workStore = { const workStore = {
executionMode: 'request',
page: '/products/[id]/page', page: '/products/[id]/page',
route: '/products/[id]', route: '/products/[id]',
cacheComponentsEnabled: true, cacheComponentsEnabled: true,
......
...@@ -14,6 +14,7 @@ import { ...@@ -14,6 +14,7 @@ import {
} from '../route-module' } from '../route-module'
import { createRequestStoreForAPI } from '../../async-storage/request-store' import { createRequestStoreForAPI } from '../../async-storage/request-store'
import { import {
createPrerenderWorkStore,
createWorkStore, createWorkStore,
type WorkStoreContext, type WorkStoreContext,
} from '../../async-storage/work-store' } from '../../async-storage/work-store'
...@@ -1074,7 +1075,6 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -1074,7 +1075,6 @@ export class AppRouteRouteModule extends RouteModule<
const prepared = await this.prepareExecution(req, context) const prepared = await this.prepareExecution(req, context)
const workStore = createWorkStore({ const workStore = createWorkStore({
page: this.definition.page, page: this.definition.page,
executionMode: 'request',
renderOpts: context.renderOpts, renderOpts: context.renderOpts,
buildId: context.sharedContext.buildId, buildId: context.sharedContext.buildId,
deploymentId: context.sharedContext.deploymentId, deploymentId: context.sharedContext.deploymentId,
...@@ -1089,9 +1089,8 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -1089,9 +1089,8 @@ export class AppRouteRouteModule extends RouteModule<
context: AppRouteRouteHandlerContext context: AppRouteRouteHandlerContext
): Promise<Response> { ): Promise<Response> {
const prepared = await this.prepareExecution(req, context) const prepared = await this.prepareExecution(req, context)
const workStore = createWorkStore({ const workStore = createPrerenderWorkStore({
page: this.definition.page, page: this.definition.page,
executionMode: 'prerender',
renderOpts: context.renderOpts, renderOpts: context.renderOpts,
buildId: context.sharedContext.buildId, buildId: context.sharedContext.buildId,
deploymentId: context.sharedContext.deploymentId, deploymentId: context.sharedContext.deploymentId,
......
...@@ -321,7 +321,6 @@ export async function adapter( ...@@ -321,7 +321,6 @@ export async function adapter(
const workStore = createWorkStore({ const workStore = createWorkStore({
page, page,
executionMode: 'request',
renderOpts: { renderOpts: {
cacheLifeProfiles: proxyCacheLifeProfiles, cacheLifeProfiles: proxyCacheLifeProfiles,
// Proxy doesn't do static generation, so this value does not // Proxy doesn't do static generation, so this value does not
......
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