Unverified Commit 7958c79b authored by Sebastian Markbåge's avatar Sebastian Markbåge Committed by GitHub

Rename StaticGenerationStore to WorkStore (#70721)

This has long been a misnomer since it's not just used for static
generation but it's the outer context of all the "Work" we're currently
doing.

A follow up will merge the other contexts into a "WorkUnitStore".
parent 39e06c75
......@@ -34,14 +34,14 @@ const routeModule = new AppRouteRouteModule({
// are used to hook into the route.
const {
requestAsyncStorage,
staticGenerationAsyncStorage,
workAsyncStorage,
prerenderAsyncStorage,
serverHooks,
} = routeModule
function patchFetch() {
return _patchFetch({
staticGenerationAsyncStorage,
workAsyncStorage,
requestAsyncStorage,
prerenderAsyncStorage,
})
......@@ -50,7 +50,7 @@ function patchFetch() {
export {
routeModule,
requestAsyncStorage,
staticGenerationAsyncStorage,
workAsyncStorage,
serverHooks,
patchFetch,
}
......@@ -75,7 +75,7 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { getRuntimeContext } from '../server/web/sandbox'
import { isClientReference } from '../lib/client-reference'
import { withStaticGenerationStore } from '../server/async-storage/with-static-generation-store'
import { withWorkStore } from '../server/async-storage/with-work-store'
import type { CacheHandler } from '../server/lib/incremental-cache'
import { IncrementalCache } from '../server/lib/incremental-cache'
import { nodeFs } from '../server/lib/node-fs-methods'
......@@ -1294,8 +1294,8 @@ export async function buildAppStaticPaths({
}
}
const routeParams = await withStaticGenerationStore(
ComponentMod.staticGenerationAsyncStorage,
const routeParams = await withWorkStore(
ComponentMod.workAsyncStorage,
{
page,
// We're discovering the parameters here, so we don't have any unknown
......
......@@ -130,7 +130,7 @@ const browserNonTranspileModules = [
const precompileRegex = /[\\/]next[\\/]dist[\\/]compiled[\\/]/
const asyncStoragesRegex =
/next[\\/]dist[\\/](esm[\\/])?client[\\/]components[\\/](static-generation-async-storage|action-async-storage|request-async-storage)/
/next[\\/]dist[\\/](esm[\\/])?client[\\/]components[\\/](work-async-storage|action-async-storage|request-async-storage)/
// Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '')
......
import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { staticGenerationAsyncStorage } from './static-generation-async-storage.external'
import { workAsyncStorage } from './work-async-storage.external'
export function bailoutToClientRendering(reason: string): void | never {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
if (staticGenerationStore?.forceStatic) return
if (workStore?.forceStatic) return
if (staticGenerationStore?.isStaticGeneration)
throw new BailoutToCSRError(reason)
if (workStore?.isStaticGeneration) throw new BailoutToCSRError(reason)
}
......@@ -26,17 +26,17 @@ export function ClientPageRoot({
promises?: Array<Promise<any>>
}) {
if (typeof window === 'undefined') {
const { staticGenerationAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external')
const { workAsyncStorage } =
require('./work-async-storage.external') as typeof import('./work-async-storage.external')
let clientSearchParams: Promise<ParsedUrlQuery>
let clientParams: Promise<Params>
// We are going to instrument the searchParams prop with tracking for the
// appropriate context. We wrap differently in prerendering vs rendering
const store = staticGenerationAsyncStorage.getStore()
const store = workAsyncStorage.getStore()
if (!store) {
throw new InvariantError(
'Expected staticGenerationStore to exist when handling searchParams in a client Page.'
'Expected workStore to exist when handling searchParams in a client Page.'
)
}
......
......@@ -25,16 +25,16 @@ export function ClientSegmentRoot({
promise?: Promise<any>
}) {
if (typeof window === 'undefined') {
const { staticGenerationAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external')
const { workAsyncStorage } =
require('./work-async-storage.external') as typeof import('./work-async-storage.external')
let clientParams: Promise<Params>
// We are going to instrument the searchParams prop with tracking for the
// appropriate context. We wrap differently in prerendering vs rendering
const store = staticGenerationAsyncStorage.getStore()
const store = workAsyncStorage.getStore()
if (!store) {
throw new InvariantError(
'Expected staticGenerationStore to exist when handling params in a client segment such as a Layout or Template.'
'Expected workStore to exist when handling params in a client segment such as a Layout or Template.'
)
}
......
......@@ -4,7 +4,7 @@ import React, { type JSX } from 'react'
import { useUntrackedPathname } from './navigation-untracked'
import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler'
import { staticGenerationAsyncStorage } from './static-generation-async-storage.external'
import { workAsyncStorage } from './work-async-storage.external'
const styles = {
error: {
......@@ -52,7 +52,7 @@ interface ErrorBoundaryHandlerState {
// function crashes so we can maintain our previous cache
// instead of caching the error page
function HandleISRError({ error }: { error: any }) {
const store = staticGenerationAsyncStorage.getStore()
const store = workAsyncStorage.getStore()
if (store?.isRevalidate || store?.isStaticGeneration) {
console.error(error)
throw error
......
......@@ -10,13 +10,13 @@ import { PathnameContext } from '../../shared/lib/hooks-client-context.shared-ru
function hasFallbackRouteParams() {
if (typeof window === 'undefined') {
// AsyncLocalStorage should not be included in the client bundle.
const { staticGenerationAsyncStorage } =
require('./static-generation-async-storage.external') as typeof import('./static-generation-async-storage.external')
const { workAsyncStorage } =
require('./work-async-storage.external') as typeof import('./work-async-storage.external')
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (!staticGenerationStore) return false
const workStore = workAsyncStorage.getStore()
if (!workStore) return false
const { fallbackRouteParams } = staticGenerationStore
const { fallbackRouteParams } = workStore
if (!fallbackRouteParams || fallbackRouteParams.size === 0) return false
return true
......
import type { StaticGenerationAsyncStorage } from './static-generation-async-storage.external'
import { createAsyncLocalStorage } from './async-local-storage'
export const staticGenerationAsyncStorage: StaticGenerationAsyncStorage =
createAsyncLocalStorage()
import type { WorkAsyncStorage } from './work-async-storage.external'
import { createAsyncLocalStorage } from './async-local-storage'
export const workAsyncStorage: WorkAsyncStorage = createAsyncLocalStorage()
......@@ -6,10 +6,10 @@ import type { Revalidate } from '../../server/lib/revalidate'
import type { FallbackRouteParams } from '../../server/request/fallback-params'
// Share the instance module in the next-shared layer
import { staticGenerationAsyncStorage } from './static-generation-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
import { workAsyncStorage } from './work-async-storage-instance' with { 'turbopack-transition': 'next-shared' }
import type { AppSegmentConfig } from '../../build/app-segments/app-segment-config'
export interface StaticGenerationStore {
export interface WorkStore {
readonly isStaticGeneration: boolean
/**
......@@ -65,7 +65,6 @@ export interface StaticGenerationStore {
buildId: string
}
export type StaticGenerationAsyncStorage =
AsyncLocalStorage<StaticGenerationStore>
export type WorkAsyncStorage = AsyncLocalStorage<WorkStore>
export { staticGenerationAsyncStorage }
export { workAsyncStorage }
......@@ -21,7 +21,7 @@ import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-cs
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { NEXT_IS_PRERENDER_HEADER } from '../../client/components/app-router-headers'
import type { FetchMetrics } from '../../server/base-http'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { FallbackRouteParams } from '../../server/request/fallback-params'
export const enum ExportedAppPageFiles {
......@@ -205,7 +205,7 @@ export async function exportAppPage(
let fetchMetrics: FetchMetrics | undefined
if (debugOutput) {
const store = (renderOpts as any).store as StaticGenerationStore
const store = (renderOpts as any).store as WorkStore
const { dynamicUsageDescription, dynamicUsageStack } = store
fetchMetrics = store.fetchMetrics
......
import type { AppRenderContext } from '../../server/app-render/app-render'
import type { MetadataContext } from './types/resolvers'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import { trackFallbackParamAccessed } from '../../server/app-render/dynamic-rendering'
export function createMetadataContext(
......@@ -17,7 +17,7 @@ export function createMetadataContext(
export function createTrackedMetadataContext(
pathname: string,
renderOpts: AppRenderContext['renderOpts'],
staticGenerationStore: StaticGenerationStore | null
workStore: WorkStore | null
): MetadataContext {
return {
// Use the regular metadata context, but we trap the pathname access.
......@@ -29,15 +29,12 @@ export function createTrackedMetadataContext(
// to provide it, and instead we should error.
get pathname() {
if (
staticGenerationStore &&
staticGenerationStore.isStaticGeneration &&
staticGenerationStore.fallbackRouteParams &&
staticGenerationStore.fallbackRouteParams.size > 0
workStore &&
workStore.isStaticGeneration &&
workStore.fallbackRouteParams &&
workStore.fallbackRouteParams.size > 0
) {
trackFallbackParamAccessed(
staticGenerationStore,
'metadata relative url resolving'
)
trackFallbackParamAccessed(workStore, 'metadata relative url resolving')
}
return pathname
......
......@@ -32,7 +32,7 @@ import type {
} from './types/metadata-interface'
import { isNotFoundError } from '../../client/components/not-found'
import type { MetadataContext } from './types/resolvers'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
// Use a promise to share the status of the metadata resolving,
// returning two components `MetadataTree` and `MetadataOutlet`
......@@ -48,7 +48,7 @@ export function createMetadataComponents({
appUsingSizeAdjustment,
errorType,
createServerParamsForMetadata,
staticGenerationStore,
workStore,
}: {
tree: LoaderTree
searchParams: Promise<ParsedUrlQuery>
......@@ -57,7 +57,7 @@ export function createMetadataComponents({
appUsingSizeAdjustment: boolean
errorType?: 'not-found' | 'redirect'
createServerParamsForMetadata: CreateServerParamsForMetadata
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
}): [React.ComponentType, () => Promise<void>] {
function MetadataRoot() {
return (
......@@ -75,7 +75,7 @@ export function createMetadataComponents({
searchParams,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore,
workStore,
errorType
)
}
......@@ -91,7 +91,7 @@ export function createMetadataComponents({
searchParams,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
} catch {}
}
......@@ -110,7 +110,7 @@ export function createMetadataComponents({
getDynamicParamFromSegment,
metadataContext,
createServerParamsForMetadata,
staticGenerationStore,
workStore,
errorType
)
}
......@@ -127,7 +127,7 @@ export function createMetadataComponents({
getDynamicParamFromSegment,
metadataContext,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
} catch {}
}
......@@ -155,7 +155,7 @@ async function getResolvedMetadataImpl(
getDynamicParamFromSegment: GetDynamicParamFromSegment,
metadataContext: MetadataContext,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
errorType?: 'not-found' | 'redirect'
): Promise<React.ReactNode> {
const errorConvention = errorType === 'redirect' ? undefined : errorType
......@@ -166,7 +166,7 @@ async function getResolvedMetadataImpl(
errorConvention,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
const elements: Array<React.ReactNode> = createMetadataElements(
await accumulateMetadata(metadataItems, metadataContext)
......@@ -187,7 +187,7 @@ async function getNotFoundMetadataImpl(
getDynamicParamFromSegment: GetDynamicParamFromSegment,
metadataContext: MetadataContext,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<React.ReactNode> {
const notFoundErrorConvention = 'not-found'
const notFoundMetadataItems = await resolveMetadataItems(
......@@ -196,7 +196,7 @@ async function getNotFoundMetadataImpl(
notFoundErrorConvention,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
const elements: Array<React.ReactNode> = createMetadataElements(
......@@ -217,7 +217,7 @@ async function getResolvedViewportImpl(
searchParams: Promise<ParsedUrlQuery>,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
errorType?: 'not-found' | 'redirect'
): Promise<React.ReactNode> {
const errorConvention = errorType === 'redirect' ? undefined : errorType
......@@ -228,7 +228,7 @@ async function getResolvedViewportImpl(
errorConvention,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
const elements: Array<React.ReactNode> = createViewportElements(
await accumulateViewport(metadataItems)
......@@ -248,7 +248,7 @@ async function getNotFoundViewportImpl(
searchParams: Promise<ParsedUrlQuery>,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<React.ReactNode> {
const notFoundErrorConvention = 'not-found'
const notFoundMetadataItems = await resolveMetadataItems(
......@@ -257,7 +257,7 @@ async function getNotFoundViewportImpl(
notFoundErrorConvention,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
const elements: Array<React.ReactNode> = createViewportElements(
......
......@@ -53,7 +53,7 @@ import { getTracer } from '../../server/lib/trace/tracer'
import { ResolveMetadataSpan } from '../../server/lib/trace/constants'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import * as Log from '../../build/output/log'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import type {
Params,
CreateServerParamsForMetadata,
......@@ -489,7 +489,7 @@ async function resolveMetadataItems(
errorConvention: 'not-found' | undefined,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
) {
const parentParams = {}
const metadataItems: MetadataItems = []
......@@ -505,7 +505,7 @@ async function resolveMetadataItems(
errorMetadataItem,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
}
......@@ -520,7 +520,7 @@ async function resolveMetadataItemsImpl(
errorMetadataItem: MetadataItems[number],
getDynamicParamFromSegment: GetDynamicParamFromSegment,
createServerParamsForMetadata: CreateServerParamsForMetadata,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<MetadataItems> {
const [segment, parallelRoutes, { page }] = tree
const currentTreePrefix =
......@@ -540,10 +540,7 @@ async function resolveMetadataItemsImpl(
}
}
const params = createServerParamsForMetadata(
currentParams,
staticGenerationStore
)
const params = createServerParamsForMetadata(currentParams, workStore)
let layerProps: LayoutProps | PageProps
if (isPage) {
......@@ -581,7 +578,7 @@ async function resolveMetadataItemsImpl(
errorMetadataItem,
getDynamicParamFromSegment,
createServerParamsForMetadata,
staticGenerationStore
workStore
)
}
......
......@@ -8,7 +8,7 @@ import type { RequestLifecycleOpts } from '../base-server'
import type { AfterCallback, AfterTask } from './after'
import { InvariantError } from '../../shared/lib/invariant-error'
import { isThenable } from '../../shared/lib/is-thenable'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { withExecuteRevalidates } from './revalidation-utils'
export type AfterContextOpts = {
......@@ -107,9 +107,9 @@ export class AfterContext {
const readonlyRequestStore: RequestStore =
wrapRequestStoreForAfterCallbacks(requestStore)
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
return withExecuteRevalidates(staticGenerationStore, () =>
return withExecuteRevalidates(workStore, () =>
requestAsyncStorage.run(readonlyRequestStore, async () => {
this.callbackQueue.start()
await this.callbackQueue.onIdle()
......
import { getExpectedRequestStore } from '../../client/components/request-async-storage.external'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'
......@@ -22,15 +22,15 @@ export function unstable_after<T>(task: AfterTask<T>) {
)
}
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
if (staticGenerationStore) {
if (staticGenerationStore.forceStatic) {
if (workStore) {
if (workStore.forceStatic) {
throw new StaticGenBailoutError(
`Route ${staticGenerationStore.route} with \`dynamic = "force-static"\` couldn't be rendered statically because it used \`${callingExpression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
`Route ${workStore.route} with \`dynamic = "force-static"\` couldn't be rendered statically because it used \`${callingExpression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
} else {
markCurrentScopeAsDynamic(staticGenerationStore, callingExpression)
markCurrentScopeAsDynamic(workStore, callingExpression)
}
}
......
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
/** Run a callback, and execute any *new* revalidations added during its runtime. */
export async function withExecuteRevalidates<T>(
store: StaticGenerationStore | undefined,
store: WorkStore | undefined,
callback: () => Promise<T>
): Promise<T> {
if (!store) {
......@@ -25,14 +25,12 @@ export async function withExecuteRevalidates<T>(
type RevalidationState = Required<
Pick<
StaticGenerationStore,
WorkStore,
'revalidatedTags' | 'pendingRevalidates' | 'pendingRevalidateWrites'
>
>
function cloneRevalidationState(
store: StaticGenerationStore
): RevalidationState {
function cloneRevalidationState(store: WorkStore): RevalidationState {
return {
revalidatedTags: store.revalidatedTags ? [...store.revalidatedTags] : [],
pendingRevalidates: { ...store.pendingRevalidates },
......@@ -62,7 +60,7 @@ function diffRevalidationState(
}
async function executeRevalidates(
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
{
revalidatedTags,
pendingRevalidates,
......@@ -70,7 +68,7 @@ async function executeRevalidates(
}: RevalidationState
) {
return Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(revalidatedTags),
workStore.incrementalCache?.revalidateTag(revalidatedTags),
...Object.values(pendingRevalidates),
...pendingRevalidateWrites,
])
......
......@@ -20,7 +20,7 @@ import {
type RedirectType,
} from '../../client/components/redirect'
import RenderResult from '../render-result'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import { FlightRenderResult } from './flight-render-result'
import {
filterReqHeaders,
......@@ -110,19 +110,17 @@ function getForwardedHeaders(
async function addRevalidationHeader(
res: BaseNextResponse,
{
staticGenerationStore,
workStore,
requestStore,
}: {
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
requestStore: RequestStore
}
) {
await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
...(staticGenerationStore.pendingRevalidateWrites || []),
workStore.incrementalCache?.revalidateTag(workStore.revalidatedTags || []),
...Object.values(workStore.pendingRevalidates || {}),
...(workStore.pendingRevalidateWrites || []),
])
// If a tag was revalidated, the client router needs to invalidate all the
......@@ -138,7 +136,7 @@ async function addRevalidationHeader(
// TODO-APP: Currently paths are treated as tags, so the second element of the tuple
// is always empty.
const isTagRevalidated = staticGenerationStore.revalidatedTags?.length ? 1 : 0
const isTagRevalidated = workStore.revalidatedTags?.length ? 1 : 0
const isCookieRevalidated = getModifiedCookieValues(
requestStore.mutableCookies
).length
......@@ -160,7 +158,7 @@ async function createForwardedActionResponse(
host: Host,
workerPathname: string,
basePath: string,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
) {
if (!host) {
throw new Error(
......@@ -175,8 +173,7 @@ async function createForwardedActionResponse(
// with the response from the forwarded worker
forwardedHeaders.set('x-action-forwarded', '1')
const proto =
staticGenerationStore.incrementalCache?.requestProtocol || 'https'
const proto = workStore.incrementalCache?.requestProtocol || 'https'
// For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request.
......@@ -281,7 +278,7 @@ async function createRedirectRenderResult(
redirectUrl: string,
redirectType: RedirectType,
basePath: string,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
) {
res.setHeader('x-action-redirect', `${redirectUrl};${redirectType}`)
......@@ -306,8 +303,7 @@ async function createRedirectRenderResult(
const forwardedHeaders = getForwardedHeaders(req, res)
forwardedHeaders.set(RSC_HEADER, '1')
const proto =
staticGenerationStore.incrementalCache?.requestProtocol || 'https'
const proto = workStore.incrementalCache?.requestProtocol || 'https'
// For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request.
......@@ -318,15 +314,15 @@ async function createRedirectRenderResult(
`${origin}${appRelativeRedirectUrl.pathname}${appRelativeRedirectUrl.search}`
)
if (staticGenerationStore.revalidatedTags) {
if (workStore.revalidatedTags) {
forwardedHeaders.set(
NEXT_CACHE_REVALIDATED_TAGS_HEADER,
staticGenerationStore.revalidatedTags.join(',')
workStore.revalidatedTags.join(',')
)
forwardedHeaders.set(
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
staticGenerationStore.incrementalCache?.prerenderManifest?.preview
?.previewModeId || ''
workStore.incrementalCache?.prerenderManifest?.preview?.previewModeId ||
''
)
}
......@@ -416,7 +412,7 @@ export async function handleAction({
ComponentMod,
serverModuleMap,
generateFlight,
staticGenerationStore,
workStore,
requestStore,
serverActions,
ctx,
......@@ -426,7 +422,7 @@ export async function handleAction({
ComponentMod: AppPageModule
serverModuleMap: ServerModuleMap
generateFlight: GenerateFlight
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
requestStore: RequestStore
serverActions?: ServerActionsConfig
ctx: AppRenderContext
......@@ -457,14 +453,14 @@ export async function handleAction({
return
}
if (staticGenerationStore.isStaticGeneration) {
if (workStore.isStaticGeneration) {
throw new Error(
"Invariant: server actions can't be handled during static rendering"
)
}
// When running actions the default is no-store, you can still `cache: 'force-cache'`
staticGenerationStore.fetchCache = 'default-no-store'
workStore.fetchCache = 'default-no-store'
const originDomain =
typeof req.headers['origin'] === 'string'
......@@ -530,11 +526,11 @@ export async function handleAction({
if (isFetchAction) {
res.statusCode = 500
await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || []
workStore.incrementalCache?.revalidateTag(
workStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
...(staticGenerationStore.pendingRevalidateWrites || []),
...Object.values(workStore.pendingRevalidates || {}),
...(workStore.pendingRevalidateWrites || []),
])
const promise = Promise.reject(error)
......@@ -553,7 +549,7 @@ export async function handleAction({
result: await generateFlight(req, ctx, {
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
skipFlight: !workStore.pathWasRevalidated,
}),
}
}
......@@ -595,7 +591,7 @@ export async function handleAction({
host,
forwardedWorker,
ctx.renderOpts.basePath,
staticGenerationStore
workStore
),
}
}
......@@ -839,15 +835,14 @@ export async function handleAction({
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
await addRevalidationHeader(res, {
staticGenerationStore,
workStore,
requestStore,
})
actionResult = await generateFlight(req, ctx, {
actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight:
!staticGenerationStore.pathWasRevalidated || actionWasForwarded,
skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,
})
}
})
......@@ -864,7 +859,7 @@ export async function handleAction({
const redirectType = getRedirectTypeFromError(err)
await addRevalidationHeader(res, {
staticGenerationStore,
workStore,
requestStore,
})
......@@ -882,7 +877,7 @@ export async function handleAction({
redirectUrl,
redirectType,
ctx.renderOpts.basePath,
staticGenerationStore
workStore
),
}
}
......@@ -906,7 +901,7 @@ export async function handleAction({
res.statusCode = 404
await addRevalidationHeader(res, {
staticGenerationStore,
workStore,
requestStore,
})
......@@ -937,11 +932,11 @@ export async function handleAction({
if (isFetchAction) {
res.statusCode = 500
await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || []
workStore.incrementalCache?.revalidateTag(
workStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
...(staticGenerationStore.pendingRevalidateWrites || []),
...Object.values(workStore.pendingRevalidates || {}),
...(workStore.pendingRevalidateWrites || []),
])
const promise = Promise.reject(err)
try {
......@@ -959,8 +954,7 @@ export async function handleAction({
result: await generateFlight(req, ctx, {
actionResult: promise,
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight:
!staticGenerationStore.pathWasRevalidated || actionWasForwarded,
skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,
}),
}
}
......
......@@ -87,7 +87,7 @@ async function createComponentTreeInternal({
}): Promise<CacheNodeSeedData> {
const {
renderOpts: { nextConfigOutput, experimental },
staticGenerationStore,
workStore,
componentMod: {
NotFoundBoundary,
LayoutRouter,
......@@ -209,69 +209,66 @@ async function createComponentTreeInternal({
// if it's configured above any parent that configured
// otherwise
if (dynamic === 'error') {
staticGenerationStore.dynamicShouldError = true
workStore.dynamicShouldError = true
} else if (dynamic === 'force-dynamic') {
staticGenerationStore.forceDynamic = true
workStore.forceDynamic = true
// TODO: (PPR) remove this bailout once PPR is the default
if (
staticGenerationStore.isStaticGeneration &&
!experimental.isRoutePPREnabled
) {
if (workStore.isStaticGeneration && !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(
`Page with \`dynamic = "force-dynamic"\` won't be rendered statically.`
)
staticGenerationStore.dynamicUsageDescription = err.message
staticGenerationStore.dynamicUsageStack = err.stack
workStore.dynamicUsageDescription = err.message
workStore.dynamicUsageStack = err.stack
throw err
}
} else {
staticGenerationStore.dynamicShouldError = false
staticGenerationStore.forceStatic = dynamic === 'force-static'
workStore.dynamicShouldError = false
workStore.forceStatic = dynamic === 'force-static'
}
}
if (typeof layoutOrPageMod?.fetchCache === 'string') {
staticGenerationStore.fetchCache = layoutOrPageMod?.fetchCache
workStore.fetchCache = layoutOrPageMod?.fetchCache
}
if (typeof layoutOrPageMod?.revalidate !== 'undefined') {
validateRevalidate(layoutOrPageMod?.revalidate, staticGenerationStore.route)
validateRevalidate(layoutOrPageMod?.revalidate, workStore.route)
}
if (typeof layoutOrPageMod?.revalidate === 'number') {
ctx.defaultRevalidate = layoutOrPageMod.revalidate as number
if (
typeof staticGenerationStore.revalidate === 'undefined' ||
(typeof staticGenerationStore.revalidate === 'number' &&
staticGenerationStore.revalidate > ctx.defaultRevalidate)
typeof workStore.revalidate === 'undefined' ||
(typeof workStore.revalidate === 'number' &&
workStore.revalidate > ctx.defaultRevalidate)
) {
staticGenerationStore.revalidate = ctx.defaultRevalidate
workStore.revalidate = ctx.defaultRevalidate
}
if (
!staticGenerationStore.forceStatic &&
staticGenerationStore.isStaticGeneration &&
!workStore.forceStatic &&
workStore.isStaticGeneration &&
ctx.defaultRevalidate === 0 &&
// If the postpone API isn't available, we can't postpone the render and
// therefore we can't use the dynamic API.
!experimental.isRoutePPREnabled
) {
const dynamicUsageDescription = `revalidate: 0 configured ${segment}`
staticGenerationStore.dynamicUsageDescription = dynamicUsageDescription
workStore.dynamicUsageDescription = dynamicUsageDescription
throw new DynamicServerError(dynamicUsageDescription)
}
}
const isStaticGeneration = staticGenerationStore.isStaticGeneration
const isStaticGeneration = workStore.isStaticGeneration
// If there's a dynamic usage error attached to the store, throw it.
if (staticGenerationStore.dynamicUsageErr) {
throw staticGenerationStore.dynamicUsageErr
if (workStore.dynamicUsageErr) {
throw workStore.dynamicUsageErr
}
const LayoutOrPage: React.ComponentType<any> | undefined = layoutOrPageMod
......@@ -491,8 +488,8 @@ async function createComponentTreeInternal({
// render force-dynamic. We should refactor this function so that we can correctly track which segments
// need to be dynamic
if (
staticGenerationStore.isStaticGeneration &&
staticGenerationStore.forceDynamic &&
workStore.isStaticGeneration &&
workStore.forceDynamic &&
experimental.isRoutePPREnabled
) {
return [
......@@ -505,7 +502,7 @@ async function createComponentTreeInternal({
>
<Postpone
reason='dynamic = "force-dynamic" was used'
route={staticGenerationStore.route}
route={workStore.route}
/>
{layerAssets}
</Segment>,
......@@ -534,11 +531,10 @@ async function createComponentTreeInternal({
if (isStaticGeneration) {
const promiseOfParams = createPrerenderParamsForClientSegment(
currentParams,
staticGenerationStore
)
const promiseOfSearchParams = createPrerenderSearchParamsForClientPage(
staticGenerationStore
workStore
)
const promiseOfSearchParams =
createPrerenderSearchParamsForClientPage(workStore)
pageElement = (
<ClientPageRoot
Component={PageComponent}
......@@ -561,11 +557,11 @@ async function createComponentTreeInternal({
// the current render mode tracks dynamic API usage.
const params = createServerParamsForServerSegment(
currentParams,
staticGenerationStore
workStore
)
const searchParams = createServerSearchParamsForServerPage(
query,
staticGenerationStore
workStore
)
pageElement = (
<PageComponent params={params} searchParams={searchParams} />
......@@ -603,7 +599,7 @@ async function createComponentTreeInternal({
if (isStaticGeneration) {
const promiseOfParams = createPrerenderParamsForClientSegment(
currentParams,
staticGenerationStore
workStore
)
clientSegment = (
......@@ -696,7 +692,7 @@ async function createComponentTreeInternal({
} else {
const params = createServerParamsForServerSegment(
currentParams,
staticGenerationStore
workStore
)
let serverSegment = (
......
......@@ -20,7 +20,7 @@
* read that data outside the cache and pass it in as an argument to the cached function.
*/
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly
import React from 'react'
......@@ -32,7 +32,7 @@ import {
prerenderAsyncStorage,
type PrerenderStore,
} from './prerender-async-storage.external'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
const hasPostpone = typeof React.unstable_postpone === 'function'
......@@ -87,7 +87,7 @@ export function getFirstDynamicReason(
* it during a normal prerender will cause the entire prerender to abort
*/
export function markCurrentScopeAsDynamic(
store: StaticGenerationStore,
store: WorkStore,
expression: string
): void {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
......@@ -152,7 +152,7 @@ export function markCurrentScopeAsDynamic(
* @param expression The expression that was accessed dynamically
*/
export function trackFallbackParamAccessed(
store: StaticGenerationStore,
store: WorkStore,
expression: string
): void {
const prerenderStore = prerenderAsyncStorage.getStore()
......@@ -171,7 +171,7 @@ export function trackFallbackParamAccessed(
* Also during a PPR Prerender we postpone
*/
export function trackDynamicDataAccessed(
store: StaticGenerationStore,
store: WorkStore,
expression: string
): void {
if (store.isUnstableCacheCallback) {
......@@ -229,7 +229,7 @@ export function trackDynamicDataAccessed(
*/
export function throwToInterruptStaticGeneration(
expression: string,
store: StaticGenerationStore
store: WorkStore
): never {
store.revalidate = 0
......@@ -250,7 +250,7 @@ export function throwToInterruptStaticGeneration(
*
* @internal
*/
export function trackDynamicDataInDynamicRender(store: StaticGenerationStore) {
export function trackDynamicDataInDynamicRender(store: WorkStore) {
store.revalidate = 0
}
......@@ -523,13 +523,13 @@ export function annotateDynamicAccess(
export function useDynamicRouteParams(expression: string) {
if (typeof window === 'undefined') {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
if (
staticGenerationStore &&
staticGenerationStore.isStaticGeneration &&
staticGenerationStore.fallbackRouteParams &&
staticGenerationStore.fallbackRouteParams.size > 0
workStore &&
workStore.isStaticGeneration &&
workStore.fallbackRouteParams &&
workStore.fallbackRouteParams.size > 0
) {
// There are fallback route params, we should track these as dynamic
// accesses.
......@@ -544,14 +544,14 @@ export function useDynamicRouteParams(expression: string) {
} else {
// We're prerendering with PPR
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
}
} else {
// We're prerendering in legacy mode
throwToInterruptStaticGeneration(expression, staticGenerationStore)
throwToInterruptStaticGeneration(expression, workStore)
}
}
}
......
......@@ -11,7 +11,7 @@ export { prerender } from 'react-server-dom-webpack/static.edge'
import LayoutRouter from '../../client/components/layout-router'
import RenderFromTemplateContext from '../../client/components/render-from-template-context'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { requestAsyncStorage } from '../../client/components/request-async-storage.external'
import { prerenderAsyncStorage } from './prerender-async-storage.external'
import { actionAsyncStorage } from '../../client/components/action-async-storage.external'
......@@ -42,7 +42,7 @@ import { taintObjectReference } from './rsc/taint'
// in the experimental channel of React, so export it from here so that it comes from the bundled runtime
function patchFetch() {
return _patchFetch({
staticGenerationAsyncStorage,
workAsyncStorage,
requestAsyncStorage,
prerenderAsyncStorage,
})
......@@ -51,7 +51,7 @@ function patchFetch() {
export {
LayoutRouter,
RenderFromTemplateContext,
staticGenerationAsyncStorage,
workAsyncStorage,
requestAsyncStorage,
actionAsyncStorage,
createServerSearchParamsForServerPage,
......
import type { WithStore } from './with-store'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { AsyncLocalStorage } from 'async_hooks'
import type { IncrementalCache } from '../lib/incremental-cache'
import type { RenderOptsPartial } from '../app-render/types'
import type { FetchMetric } from '../base-http'
import type { RequestLifecycleOpts } from '../base-server'
import type { FallbackRouteParams } from '../../server/request/fallback-params'
import type { FallbackRouteParams } from '../request/fallback-params'
import type { AppSegmentConfig } from '../../build/app-segments/app-segment-config'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
export type StaticGenerationContext = {
export type WorkStoreContext = {
/**
* The page that is being rendered. This relates to the path to the page file.
*/
......@@ -47,7 +47,7 @@ export type StaticGenerationContext = {
* @deprecated should only be used as a temporary workaround
*/
// TODO: remove this when we resolve accessing the store outside the execution context
store?: StaticGenerationStore
store?: WorkStore
} & Pick<
// Pull some properties from RenderOptsPartial so that the docs are also
// mirrored.
......@@ -62,19 +62,16 @@ export type StaticGenerationContext = {
Partial<RequestLifecycleOpts>
}
export const withStaticGenerationStore: WithStore<
StaticGenerationStore,
StaticGenerationContext
> = <Result>(
storage: AsyncLocalStorage<StaticGenerationStore>,
export const withWorkStore: WithStore<WorkStore, WorkStoreContext> = <Result>(
storage: AsyncLocalStorage<WorkStore>,
{
page,
fallbackRouteParams,
renderOpts,
requestEndedState,
isPrefetchRequest,
}: StaticGenerationContext,
callback: (store: StaticGenerationStore) => Result
}: WorkStoreContext,
callback: (store: WorkStore) => Result
): Result => {
/**
* Rules of Static & Dynamic HTML:
......@@ -98,7 +95,7 @@ export const withStaticGenerationStore: WithStore<
!renderOpts.isDraftMode &&
!renderOpts.isServerAction
const store: StaticGenerationStore = {
const store: WorkStore = {
isStaticGeneration,
page,
fallbackRouteParams,
......
import { AsyncLocalStorage } from 'node:async_hooks'
import type { RequestStore } from '../../client/components/request-async-storage.external'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { IncrementalCache } from './incremental-cache'
import { createPatchedFetcher } from './patch-fetch'
import type { PrerenderStore } from '../app-render/prerender-async-storage.external'
......@@ -22,15 +22,14 @@ describe('createPatchedFetcher', () => {
mockFetch.mockResolvedValue(new Response(readableStream))
const staticGenerationAsyncStorage =
new AsyncLocalStorage<StaticGenerationStore>()
const workAsyncStorage = new AsyncLocalStorage<WorkStore>()
const prerenderAsyncStorage = new AsyncLocalStorage<PrerenderStore>()
const patchedFetch = createPatchedFetcher(mockFetch, {
// requestAsyncStorage does not need to provide a store for this test.
requestAsyncStorage: new AsyncLocalStorage<RequestStore>(),
staticGenerationAsyncStorage,
workAsyncStorage,
prerenderAsyncStorage,
})
......@@ -47,56 +46,53 @@ describe('createPatchedFetcher', () => {
lock: jest.fn(() => resolveIncrementalCacheSet),
} as unknown as IncrementalCache
// We only need to provide a few of the StaticGenerationStore properties.
const staticGenerationStore: Partial<StaticGenerationStore> = {
// We only need to provide a few of the WorkStore properties.
const workStore: Partial<WorkStore> = {
page: '/',
route: '/',
incrementalCache,
}
await staticGenerationAsyncStorage.run(
staticGenerationStore as StaticGenerationStore,
async () => {
const response = await patchedFetch('https://example.com', {
cache: 'force-cache',
})
await workAsyncStorage.run(workStore as WorkStore, async () => {
const response = await patchedFetch('https://example.com', {
cache: 'force-cache',
})
if (!response.body) {
throw new Error(`Response body is ${JSON.stringify(response.body)}.`)
}
if (!response.body) {
throw new Error(`Response body is ${JSON.stringify(response.body)}.`)
}
const reader = response.body.getReader()
let result = await reader.read()
const textDecoder = new TextDecoder()
expect(textDecoder.decode(result.value)).toBe('stream start')
streamChunk()
result = await reader.read()
expect(textDecoder.decode(result.value)).toBe('stream end')
const reader = response.body.getReader()
let result = await reader.read()
const textDecoder = new TextDecoder()
expect(textDecoder.decode(result.value)).toBe('stream start')
streamChunk()
result = await reader.read()
expect(textDecoder.decode(result.value)).toBe('stream end')
await incrementalCacheSetPromise
await incrementalCacheSetPromise
expect(incrementalCache.set).toHaveBeenCalledWith(
'test-cache-key',
{
data: {
body: btoa('stream startstream end'),
headers: {},
status: 200,
url: '', // the mocked response does not have a URL
},
kind: 'FETCH',
revalidate: 31536000, // default of one year
expect(incrementalCache.set).toHaveBeenCalledWith(
'test-cache-key',
{
data: {
body: btoa('stream startstream end'),
headers: {},
status: 200,
url: '', // the mocked response does not have a URL
},
{
fetchCache: true,
fetchIdx: 1,
fetchUrl: 'https://example.com/',
revalidate: false,
tags: [],
}
)
}
)
kind: 'FETCH',
revalidate: 31536000, // default of one year
},
{
fetchCache: true,
fetchIdx: 1,
fetchUrl: 'https://example.com/',
revalidate: false,
tags: [],
}
)
})
// Setting a lower timeout than default, because the test will fail with a
// timeout when we regress and buffer the response.
}, 1000)
......
This diff is collapsed.
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import {
isDynamicIOPrerender,
prerenderAsyncStorage,
......@@ -17,23 +17,23 @@ import { makeHangingPromise } from '../dynamic-rendering-utils'
* During prerendering it will never resolve and during rendering it resolves immediately.
*/
export function connection(): Promise<void> {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore()
if (staticGenerationStore) {
if (staticGenerationStore.forceStatic) {
if (workStore) {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
// headers object without tracking
return Promise.resolve(undefined)
}
if (staticGenerationStore.isUnstableCacheCallback) {
if (workStore.isUnstableCacheCallback) {
throw new Error(
`Route ${staticGenerationStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
`Route ${workStore.route} used "connection" inside a function cached with "unstable_cache(...)". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
} else if (staticGenerationStore.dynamicShouldError) {
} else if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError(
`Route ${staticGenerationStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`connection\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
......@@ -53,19 +53,19 @@ export function connection(): Promise<void> {
// to keep continuity with how headers has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access intead
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
'connection',
prerenderStore.dynamicTracking
)
}
} else if (staticGenerationStore.isStaticGeneration) {
} else if (workStore.isStaticGeneration) {
// We are in a legacy static generation mode while prerendering
// We treat this function call as a bailout of static generation
throwToInterruptStaticGeneration('connection', staticGenerationStore)
throwToInterruptStaticGeneration('connection', workStore)
}
// We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(staticGenerationStore)
trackDynamicDataInDynamicRender(workStore)
}
return Promise.resolve(undefined)
......
......@@ -4,7 +4,7 @@ import {
RequestCookiesAdapter,
} from '../../server/web/spec-extension/adapters/request-cookies'
import { RequestCookies } from '../../server/web/spec-extension/cookies'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import {
isDynamicIOPrerender,
prerenderAsyncStorage,
......@@ -51,24 +51,24 @@ export type UnsafeUnwrappedCookies = ReadonlyRequestCookies
export function cookies(): Promise<ReadonlyRequestCookies> {
const callingExpression = 'cookies'
const requestStore = getExpectedRequestStore(callingExpression)
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore()
if (staticGenerationStore) {
if (staticGenerationStore.forceStatic) {
if (workStore) {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
// cookies object without tracking
const underlyingCookies = createEmptyCookies()
return makeUntrackedExoticCookies(underlyingCookies)
}
if (staticGenerationStore.isUnstableCacheCallback) {
if (workStore.isUnstableCacheCallback) {
throw new Error(
`Route ${staticGenerationStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
`Route ${workStore.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
} else if (staticGenerationStore.dynamicShouldError) {
} else if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError(
`Route ${staticGenerationStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
......@@ -83,7 +83,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
// We don't track dynamic access here because access will be tracked when you access
// one of the properties of the cookies object.
return makeDynamicallyTrackedExoticCookies(
staticGenerationStore.route,
workStore.route,
prerenderStore
)
} else {
......@@ -91,20 +91,20 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
// to keep continuity with how cookies has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access instead
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
callingExpression,
prerenderStore.dynamicTracking
)
}
} else if (staticGenerationStore.isStaticGeneration) {
} else if (workStore.isStaticGeneration) {
// We are in a legacy static generation mode while prerendering
// We track dynamic access here so we don't need to wrap the cookies in
// individual property access tracking.
throwToInterruptStaticGeneration(callingExpression, staticGenerationStore)
throwToInterruptStaticGeneration(callingExpression, workStore)
}
// We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using cookies inside a cache context
trackDynamicDataInDynamicRender(staticGenerationStore)
trackDynamicDataInDynamicRender(workStore)
}
// cookies is being called in a dynamic context
......@@ -126,13 +126,10 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
underlyingCookies = requestStore.cookies
}
if (
process.env.NODE_ENV === 'development' &&
!staticGenerationStore?.isPrefetchRequest
) {
if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
return makeUntrackedExoticCookiesWithDevWarnings(
underlyingCookies,
staticGenerationStore?.route
workStore?.route
)
} else {
return makeUntrackedExoticCookies(underlyingCookies)
......
......@@ -2,7 +2,7 @@ import { getExpectedRequestStore } from '../../client/components/request-async-s
import type { DraftModeProvider } from '../../server/async-storage/draft-mode-provider'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { trackDynamicDataAccessed } from '../app-render/dynamic-rendering'
/**
......@@ -34,13 +34,10 @@ export type UnsafeUnwrappedDraftMode = DraftMode
export function draftMode(): Promise<DraftMode> {
const callingExpression = 'draftMode'
const requestStore = getExpectedRequestStore(callingExpression)
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
if (
process.env.NODE_ENV === 'development' &&
!staticGenerationStore?.isPrefetchRequest
) {
const route = staticGenerationStore?.route
if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
const route = workStore?.route
return createExoticDraftModeWithDevWarnings(requestStore.draftMode, route)
} else {
return createExoticDraftMode(requestStore.draftMode)
......@@ -144,7 +141,7 @@ class DraftMode {
return this._provider.isEnabled
}
public enable() {
const store = staticGenerationAsyncStorage.getStore()
const store = workAsyncStorage.getStore()
if (store) {
// We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
......@@ -153,7 +150,7 @@ class DraftMode {
return this._provider.enable()
}
public disable() {
const store = staticGenerationAsyncStorage.getStore()
const store = workAsyncStorage.getStore()
if (store) {
// We we have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
......
......@@ -2,7 +2,7 @@ import {
HeadersAdapter,
type ReadonlyHeaders,
} from '../../server/web/spec-extension/adapters/headers'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import { getExpectedRequestStore } from '../../client/components/request-async-storage.external'
import {
isDynamicIOPrerender,
......@@ -56,24 +56,24 @@ export type UnsafeUnwrappedHeaders = ReadonlyHeaders
*/
export function headers(): Promise<ReadonlyHeaders> {
const requestStore = getExpectedRequestStore('headers')
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore()
const prerenderStore = prerenderAsyncStorage.getStore()
if (staticGenerationStore) {
if (staticGenerationStore.forceStatic) {
if (workStore) {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
// headers object without tracking
const underlyingHeaders = HeadersAdapter.seal(new Headers({}))
return makeUntrackedExoticHeaders(underlyingHeaders)
}
if (staticGenerationStore.isUnstableCacheCallback) {
if (workStore.isUnstableCacheCallback) {
throw new Error(
`Route ${staticGenerationStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
`Route ${workStore.route} used "headers" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "headers" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
} else if (staticGenerationStore.dynamicShouldError) {
} else if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError(
`Route ${staticGenerationStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
`Route ${workStore.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`headers\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
......@@ -88,7 +88,7 @@ export function headers(): Promise<ReadonlyHeaders> {
// We don't track dynamic access here because access will be tracked when you access
// one of the properties of the headers object.
return makeDynamicallyTrackedExoticHeaders(
staticGenerationStore.route,
workStore.route,
prerenderStore
)
} else {
......@@ -96,29 +96,26 @@ export function headers(): Promise<ReadonlyHeaders> {
// to keep continuity with how headers has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access instead
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
'headers',
prerenderStore.dynamicTracking
)
}
} else if (staticGenerationStore.isStaticGeneration) {
} else if (workStore.isStaticGeneration) {
// We are in a legacy static generation mode while prerendering
// We track dynamic access here so we don't need to wrap the headers in
// individual property access tracking.
throwToInterruptStaticGeneration('headers', staticGenerationStore)
throwToInterruptStaticGeneration('headers', workStore)
}
// We fall through to the dynamic context below but we still track dynamic access
// because in dev we can still error for things like using headers inside a cache context
trackDynamicDataInDynamicRender(staticGenerationStore)
trackDynamicDataInDynamicRender(workStore)
}
if (
process.env.NODE_ENV === 'development' &&
!staticGenerationStore?.isPrefetchRequest
) {
if (process.env.NODE_ENV === 'development' && !workStore?.isPrefetchRequest) {
return makeUntrackedExoticHeadersWithDevWarnings(
requestStore.headers,
staticGenerationStore?.route
workStore?.route
)
} else {
return makeUntrackedExoticHeaders(requestStore.headers)
......
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import type { FallbackRouteParams } from './fallback-params'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
......@@ -49,16 +49,16 @@ export type UnsafeUnwrappedParams<P> =
export function createPrerenderParamsFromClient(
underlyingParams: Params,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
) {
return createPrerenderParams(underlyingParams, staticGenerationStore)
return createPrerenderParams(underlyingParams, workStore)
}
export function createRenderParamsFromClient(
underlyingParams: Params,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
) {
return createRenderParams(underlyingParams, staticGenerationStore)
return createRenderParams(underlyingParams, workStore)
}
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
......@@ -68,34 +68,34 @@ export const createServerParamsForMetadata = createServerParamsForServerSegment
// routes always runs in RSC context so it is equivalent to a Server Page Component
export function createServerParamsForRoute(
underlyingParams: Params,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
) {
if (staticGenerationStore.isStaticGeneration) {
return createPrerenderParams(underlyingParams, staticGenerationStore)
if (workStore.isStaticGeneration) {
return createPrerenderParams(underlyingParams, workStore)
} else {
return createRenderParams(underlyingParams, staticGenerationStore)
return createRenderParams(underlyingParams, workStore)
}
}
export function createServerParamsForServerSegment(
underlyingParams: Params,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<Params> {
if (staticGenerationStore.isStaticGeneration) {
return createPrerenderParams(underlyingParams, staticGenerationStore)
if (workStore.isStaticGeneration) {
return createPrerenderParams(underlyingParams, workStore)
} else {
return createRenderParams(underlyingParams, staticGenerationStore)
return createRenderParams(underlyingParams, workStore)
}
}
export function createPrerenderParamsForClientSegment(
underlyingParams: Params,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<Params> {
const prerenderStore = prerenderAsyncStorage.getStore()
if (prerenderStore) {
if (isDynamicIOPrerender(prerenderStore)) {
const fallbackParams = staticGenerationStore.fallbackRouteParams
const fallbackParams = workStore.fallbackRouteParams
if (fallbackParams) {
for (let key in underlyingParams) {
if (fallbackParams.has(key)) {
......@@ -116,9 +116,9 @@ export function createPrerenderParamsForClientSegment(
function createPrerenderParams(
underlyingParams: Params,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<Params> {
const fallbackParams = staticGenerationStore.fallbackRouteParams
const fallbackParams = workStore.fallbackRouteParams
if (fallbackParams) {
let hasSomeFallbackParams = false
for (const key in underlyingParams) {
......@@ -136,7 +136,7 @@ function createPrerenderParams(
// We are in a dynamicIO (PPR or otherwise) prerender
return makeAbortingExoticParams(
underlyingParams,
staticGenerationStore.route,
workStore.route,
prerenderStore
)
}
......@@ -147,7 +147,7 @@ function createPrerenderParams(
return makeErroringExoticParams(
underlyingParams,
fallbackParams,
staticGenerationStore,
workStore,
prerenderStore
)
}
......@@ -159,15 +159,12 @@ function createPrerenderParams(
function createRenderParams(
underlyingParams: Params,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<Params> {
if (
process.env.NODE_ENV === 'development' &&
!staticGenerationStore.isPrefetchRequest
) {
if (process.env.NODE_ENV === 'development' && !workStore.isPrefetchRequest) {
return makeDynamicallyTrackedExoticParamsWithDevWarnings(
underlyingParams,
staticGenerationStore
workStore
)
} else {
return makeUntrackedExoticParams(underlyingParams)
......@@ -249,7 +246,7 @@ function makeAbortingExoticParams(
function makeErroringExoticParams(
underlyingParams: Params,
fallbackParams: FallbackRouteParams,
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
prerenderStore: undefined | PrerenderStore
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
......@@ -307,15 +304,12 @@ function makeErroringExoticParams(
// will be no `dynamic = "error"`
if (prerenderStore) {
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
throwToInterruptStaticGeneration(
expression,
staticGenerationStore
)
throwToInterruptStaticGeneration(expression, workStore)
}
},
enumerable: true,
......@@ -331,15 +325,12 @@ function makeErroringExoticParams(
// will be no `dynamic = "error"`
if (prerenderStore) {
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
throwToInterruptStaticGeneration(
expression,
staticGenerationStore
)
throwToInterruptStaticGeneration(expression, workStore)
}
},
set(newValue) {
......@@ -414,7 +405,7 @@ function makeUntrackedExoticParams(underlyingParams: Params): Promise<Params> {
function makeDynamicallyTrackedExoticParamsWithDevWarnings(
underlyingParams: Params,
store: StaticGenerationStore
store: WorkStore
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
......
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
......@@ -52,17 +52,15 @@ export type SearchParams = { [key: string]: string | string[] | undefined }
export type UnsafeUnwrappedSearchParams<P> =
P extends Promise<infer U> ? Omit<U, 'then' | 'status' | 'value'> : never
export function createPrerenderSearchParamsFromClient(
staticGenerationStore: StaticGenerationStore
) {
return createPrerenderSearchParams(staticGenerationStore)
export function createPrerenderSearchParamsFromClient(workStore: WorkStore) {
return createPrerenderSearchParams(workStore)
}
export function createRenderSearchParamsFromClient(
underlyingSearchParams: SearchParams,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
) {
return createRenderSearchParams(underlyingSearchParams, staticGenerationStore)
return createRenderSearchParams(underlyingSearchParams, workStore)
}
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
......@@ -71,22 +69,19 @@ export const createServerSearchParamsForMetadata =
export function createServerSearchParamsForServerPage(
underlyingSearchParams: SearchParams,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<SearchParams> {
if (staticGenerationStore.isStaticGeneration) {
return createPrerenderSearchParams(staticGenerationStore)
if (workStore.isStaticGeneration) {
return createPrerenderSearchParams(workStore)
} else {
return createRenderSearchParams(
underlyingSearchParams,
staticGenerationStore
)
return createRenderSearchParams(underlyingSearchParams, workStore)
}
}
export function createPrerenderSearchParamsForClientPage(
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<SearchParams> {
if (staticGenerationStore.forceStatic) {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
// dictionary object.
return Promise.resolve({})
......@@ -107,9 +102,9 @@ export function createPrerenderSearchParamsForClientPage(
}
function createPrerenderSearchParams(
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<SearchParams> {
if (staticGenerationStore.forceStatic) {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
// dictionary object.
return Promise.resolve({})
......@@ -119,40 +114,34 @@ function createPrerenderSearchParams(
if (prerenderStore) {
if (prerenderStore.controller || prerenderStore.cacheSignal) {
// We are in a dynamicIO (PPR or otherwise) prerender
return makeAbortingExoticSearchParams(
staticGenerationStore.route,
prerenderStore
)
return makeAbortingExoticSearchParams(workStore.route, prerenderStore)
}
}
// We are in a legacy static generation and need to interrupt the prerender
// when search params are accessed.
return makeErroringExoticSearchParams(staticGenerationStore, prerenderStore)
return makeErroringExoticSearchParams(workStore, prerenderStore)
}
function createRenderSearchParams(
underlyingSearchParams: SearchParams,
staticGenerationStore: StaticGenerationStore
workStore: WorkStore
): Promise<SearchParams> {
if (staticGenerationStore.forceStatic) {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
// dictionary object.
return Promise.resolve({})
} else {
if (
process.env.NODE_ENV === 'development' &&
!staticGenerationStore.isPrefetchRequest
!workStore.isPrefetchRequest
) {
return makeDynamicallyTrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams,
staticGenerationStore
workStore
)
} else {
return makeUntrackedExoticSearchParams(
underlyingSearchParams,
staticGenerationStore
)
return makeUntrackedExoticSearchParams(underlyingSearchParams, workStore)
}
}
}
......@@ -266,10 +255,10 @@ function makeAbortingExoticSearchParams(
}
function makeErroringExoticSearchParams(
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
prerenderStore: undefined | PrerenderStore
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(staticGenerationStore)
const cachedSearchParams = CachedSearchParams.get(workStore)
if (cachedSearchParams) {
return cachedSearchParams
}
......@@ -315,38 +304,38 @@ function makeErroringExoticSearchParams(
case 'then': {
const expression =
'`await searchParams`, `searchParams.then`, or similar'
if (staticGenerationStore.dynamicShouldError) {
if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route,
workStore.route,
expression
)
} else if (prerenderStore) {
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
throwToInterruptStaticGeneration(expression, staticGenerationStore)
throwToInterruptStaticGeneration(expression, workStore)
}
return
}
case 'status': {
const expression =
'`use(searchParams)`, `searchParams.status`, or similar'
if (staticGenerationStore.dynamicShouldError) {
if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route,
workStore.route,
expression
)
} else if (prerenderStore) {
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
throwToInterruptStaticGeneration(expression, staticGenerationStore)
throwToInterruptStaticGeneration(expression, workStore)
}
return
}
......@@ -356,22 +345,19 @@ function makeErroringExoticSearchParams(
'searchParams',
prop
)
if (staticGenerationStore.dynamicShouldError) {
if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route,
workStore.route,
expression
)
} else if (prerenderStore) {
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
throwToInterruptStaticGeneration(
expression,
staticGenerationStore
)
throwToInterruptStaticGeneration(expression, workStore)
}
}
return ReflectAdapter.get(target, prop, receiver)
......@@ -388,19 +374,19 @@ function makeErroringExoticSearchParams(
'searchParams',
prop
)
if (staticGenerationStore.dynamicShouldError) {
if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route,
workStore.route,
expression
)
} else if (prerenderStore) {
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
throwToInterruptStaticGeneration(expression, staticGenerationStore)
throwToInterruptStaticGeneration(expression, workStore)
}
return false
}
......@@ -409,30 +395,30 @@ function makeErroringExoticSearchParams(
ownKeys() {
const expression =
'`{...searchParams}`, `Object.keys(searchParams)`, or similar'
if (staticGenerationStore.dynamicShouldError) {
if (workStore.dynamicShouldError) {
throwWithStaticGenerationBailoutErrorWithDynamicError(
staticGenerationStore.route,
workStore.route,
expression
)
} else if (prerenderStore) {
postponeWithTracking(
staticGenerationStore.route,
workStore.route,
expression,
prerenderStore.dynamicTracking
)
} else {
throwToInterruptStaticGeneration(expression, staticGenerationStore)
throwToInterruptStaticGeneration(expression, workStore)
}
},
})
CachedSearchParams.set(staticGenerationStore, proxiedPromise)
CachedSearchParams.set(workStore, proxiedPromise)
return proxiedPromise
}
function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams,
store: StaticGenerationStore
store: WorkStore
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
......@@ -499,7 +485,7 @@ function makeUntrackedExoticSearchParams(
function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams,
store: StaticGenerationStore
store: WorkStore
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
......
......@@ -12,8 +12,8 @@ import {
createTemporaryReferenceSet as createClientTemporaryReferenceSet,
} from 'react-server-dom-webpack/client.edge'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import type { WorkStore } from '../../client/components/work-async-storage.external'
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import type { CacheStore } from '../app-render/cache-async-storage.external'
import { cacheAsyncStorage } from '../app-render/cache-async-storage.external'
import { runInCleanSnapshot } from '../app-render/clean-async-snapshot.external'
......@@ -76,7 +76,7 @@ cacheHandlerMap.set('default', {
})
function generateCacheEntry(
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer,
......@@ -89,8 +89,8 @@ function generateCacheEntry(
// Note: It is important that we await at least once before this because it lets us
// pop out of any stack specific contexts as well - aka "Sync" Local Storage.
return runInCleanSnapshot(
generateCacheEntryWithRestoredStaticGenerationStore,
staticGenerationStore,
generateCacheEntryWithRestoredWorkStore,
workStore,
clientReferenceManifest,
cacheHandler,
serializedCacheKey,
......@@ -99,25 +99,25 @@ function generateCacheEntry(
)
}
function generateCacheEntryWithRestoredStaticGenerationStore(
staticGenerationStore: StaticGenerationStore,
function generateCacheEntryWithRestoredWorkStore(
workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer,
encodedArguments: FormData | string,
fn: any
) {
// Since we cleared the AsyncLocalStorage we need to restore the staticGenerationStore.
// Since we cleared the AsyncLocalStorage we need to restore the workStore.
// Note: We explicitly don't restore the RequestStore nor the PrerenderStore.
// We don't want any request specific information leaking an we don't want to create a
// bloated fake request mock for every cache call. So any feature that currently lives
// in RequestStore but should be available to Caches need to move to StaticGenerationStore.
// in RequestStore but should be available to Caches need to move to WorkStore.
// PrerenderStore is not needed inside the cache scope because the outer most one will
// be the one to report its result to the outer Prerender.
return staticGenerationAsyncStorage.run(
staticGenerationStore,
return workAsyncStorage.run(
workStore,
generateCacheEntryWithCacheContext,
staticGenerationStore,
workStore,
clientReferenceManifest,
cacheHandler,
serializedCacheKey,
......@@ -127,7 +127,7 @@ function generateCacheEntryWithRestoredStaticGenerationStore(
}
function generateCacheEntryWithCacheContext(
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer,
......@@ -139,7 +139,7 @@ function generateCacheEntryWithCacheContext(
return cacheAsyncStorage.run(
cacheStore,
generateCacheEntryImpl,
staticGenerationStore,
workStore,
clientReferenceManifest,
cacheHandler,
serializedCacheKey,
......@@ -149,7 +149,7 @@ function generateCacheEntryWithCacheContext(
}
async function generateCacheEntryImpl(
staticGenerationStore: StaticGenerationStore,
workStore: WorkStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
cacheHandler: CacheHandler,
serializedCacheKey: string | ArrayBuffer,
......@@ -219,13 +219,13 @@ async function generateCacheEntryImpl(
},
})
if (!staticGenerationStore.pendingRevalidateWrites) {
staticGenerationStore.pendingRevalidateWrites = []
if (!workStore.pendingRevalidateWrites) {
workStore.pendingRevalidateWrites = []
}
const promise = cacheHandler.set(serializedCacheKey, erroringSavedStream)
staticGenerationStore.pendingRevalidateWrites.push(promise)
workStore.pendingRevalidateWrites.push(promise)
// Return the stream as we're creating it. This means that if it ends up
// erroring we cannot return a stale-while-error version but it allows
......@@ -246,10 +246,10 @@ export function cache(kind: string, id: string, fn: any) {
const name = fn.name
const cachedFn = {
[name]: async function (...args: any[]) {
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (staticGenerationStore === undefined) {
const workStore = workAsyncStorage.getStore()
if (workStore === undefined) {
throw new Error(
'"use cache" cannot be used outside of App Router. Expected a StaticGenerationStore.'
'"use cache" cannot be used outside of App Router. Expected a WorkStore.'
)
}
......@@ -257,7 +257,7 @@ export function cache(kind: string, id: string, fn: any) {
// safely reuse the results across builds yet. In the meantime we add the buildId to the
// arguments as a seed to ensure they're not reused. Remove this once Action IDs hash
// the implementation.
const buildId = staticGenerationStore.buildId
const buildId = workStore.buildId
const temporaryReferences = createClientTemporaryReferenceSet()
const encodedArguments: FormData | string = await encodeReply(
......@@ -283,7 +283,7 @@ export function cache(kind: string, id: string, fn: any) {
let stream
if (
entry === undefined ||
(entry.stale && staticGenerationStore.isStaticGeneration)
(entry.stale && workStore.isStaticGeneration)
) {
// Miss. Generate a new result.
......@@ -303,7 +303,7 @@ export function cache(kind: string, id: string, fn: any) {
getClientReferenceManifestSingleton()
stream = await generateCacheEntry(
staticGenerationStore,
workStore,
clientReferenceManifestSingleton,
cacheHandler,
serializedCacheKey,
......@@ -318,7 +318,7 @@ export function cache(kind: string, id: string, fn: any) {
const clientReferenceManifestSingleton =
getClientReferenceManifestSingleton()
const ignoredStream = await generateCacheEntry(
staticGenerationStore,
workStore,
clientReferenceManifestSingleton,
cacheHandler,
serializedCacheKey,
......
......@@ -2,7 +2,7 @@ import type { RequestCookies } from '../cookies'
import { ResponseCookies } from '../cookies'
import { ReflectAdapter } from './reflect'
import { staticGenerationAsyncStorage } from '../../../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../../../client/components/work-async-storage.external'
/**
* @internal
......@@ -108,10 +108,10 @@ export class MutableRequestCookiesAdapter {
let modifiedValues: ResponseCookie[] = []
const modifiedCookies = new Set<string>()
const updateResponseCookies = () => {
// TODO-APP: change method of getting staticGenerationAsyncStore
const staticGenerationAsyncStore = staticGenerationAsyncStorage.getStore()
if (staticGenerationAsyncStore) {
staticGenerationAsyncStore.pathWasRevalidated = true
// TODO-APP: change method of getting workStore
const workStore = workAsyncStorage.getStore()
if (workStore) {
workStore.pathWasRevalidated = true
}
const allCookies = responseCookies.getAll()
......
......@@ -4,7 +4,7 @@ import {
NEXT_CACHE_IMPLICIT_TAG_ID,
NEXT_CACHE_SOFT_TAG_MAX_LENGTH,
} from '../../../lib/constants'
import { staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../../client/components/work-async-storage.external'
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
......@@ -41,7 +41,7 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
}
function revalidate(tag: string, expression: string) {
const store = staticGenerationAsyncStorage.getStore()
const store = workAsyncStorage.getStore()
if (!store || !store.incrementalCache) {
throw new Error(
`Invariant: static generation store missing in ${expression}`
......
import { staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external'
import { workAsyncStorage } from '../../../client/components/work-async-storage.external'
import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'
/**
......@@ -18,7 +18,7 @@ import { markCurrentScopeAsDynamic } from '../../app-render/dynamic-rendering'
*/
export function unstable_noStore() {
const callingExpression = 'unstable_noStore()'
const store = staticGenerationAsyncStorage.getStore()
const store = workAsyncStorage.getStore()
if (!store) {
// This generally implies we are being called in Pages router. We should probably not support
// unstable_noStore in contexts outside of `react-server` condition but since we historically
......
......@@ -20,12 +20,12 @@ const routeModule = new AppRouteRouteModule({
// Pull out the exports that we need to expose from the module. This should
// be eliminated when we've moved the other routes to the new format. These
// are used to hook into the route.
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule;
const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
const originalPathname = 'VAR_ORIGINAL_PATHNAME';
function patchFetch() {
return _patchFetch({
serverHooks,
staticGenerationAsyncStorage
workAsyncStorage
});
}
export { routeModule, requestAsyncStorage, staticGenerationAsyncStorage, serverHooks, originalPathname, patchFetch, };
export { routeModule, requestAsyncStorage, workAsyncStorage, serverHooks, originalPathname, patchFetch, };
......@@ -108,13 +108,13 @@ const routeModule = new AppRouteRouteModule({
## Item 10: Stmt 5, `VarDeclarator(0)`
```js
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule;
const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
```
- Declares: `requestAsyncStorage`, `staticGenerationAsyncStorage`, `serverHooks`
- Declares: `requestAsyncStorage`, `workAsyncStorage`, `serverHooks`
- Reads: `routeModule`
- Write: `requestAsyncStorage`, `staticGenerationAsyncStorage`, `serverHooks`
- Write: `requestAsyncStorage`, `workAsyncStorage`, `serverHooks`
## Item 11: Stmt 6, `VarDeclarator(0)`
......@@ -132,7 +132,7 @@ const originalPathname = 'VAR_ORIGINAL_PATHNAME';
function patchFetch() {
return _patchFetch({
serverHooks,
staticGenerationAsyncStorage
workAsyncStorage
});
}
......@@ -140,9 +140,9 @@ function patchFetch() {
- Hoisted
- Declares: `patchFetch`
- Reads (eventual): `_patchFetch`, `serverHooks`, `staticGenerationAsyncStorage`
- Reads (eventual): `_patchFetch`, `serverHooks`, `workAsyncStorage`
- Write: `patchFetch`
- Write (eventual): `serverHooks`, `staticGenerationAsyncStorage`
- Write (eventual): `serverHooks`, `workAsyncStorage`
# Phase 1
```mermaid
......@@ -166,7 +166,7 @@ graph TD
Item15;
Item15["export requestAsyncStorage"];
Item16;
Item16["export staticGenerationAsyncStorage"];
Item16["export workAsyncStorage"];
Item17;
Item17["export serverHooks"];
Item18;
......@@ -202,7 +202,7 @@ graph TD
Item15;
Item15["export requestAsyncStorage"];
Item16;
Item16["export staticGenerationAsyncStorage"];
Item16["export workAsyncStorage"];
Item17;
Item17["export serverHooks"];
Item18;
......@@ -253,7 +253,7 @@ graph TD
Item15;
Item15["export requestAsyncStorage"];
Item16;
Item16["export staticGenerationAsyncStorage"];
Item16["export workAsyncStorage"];
Item17;
Item17["export serverHooks"];
Item18;
......@@ -308,7 +308,7 @@ graph TD
Item15;
Item15["export requestAsyncStorage"];
Item16;
Item16["export staticGenerationAsyncStorage"];
Item16["export workAsyncStorage"];
Item17;
Item17["export serverHooks"];
Item18;
......@@ -364,7 +364,7 @@ graph TD
N12["Items: [ItemId(Export((&quot;routeModule&quot;, #2), &quot;routeModule&quot;))]"];
N13["Items: [ItemId(5, VarDeclarator(0))]"];
N14["Items: [ItemId(Export((&quot;serverHooks&quot;, #2), &quot;serverHooks&quot;))]"];
N15["Items: [ItemId(Export((&quot;staticGenerationAsyncStorage&quot;, #2), &quot;staticGenerationAsyncStorage&quot;))]"];
N15["Items: [ItemId(Export((&quot;workAsyncStorage&quot;, #2), &quot;workAsyncStorage&quot;))]"];
N16["Items: [ItemId(7, Normal)]"];
N17["Items: [ItemId(Export((&quot;patchFetch&quot;, #2), &quot;patchFetch&quot;))]"];
N18["Items: [ItemId(Export((&quot;requestAsyncStorage&quot;, #2), &quot;requestAsyncStorage&quot;))]"];
......@@ -410,9 +410,6 @@ graph TD
Export(
"patchFetch",
): 17,
Export(
"staticGenerationAsyncStorage",
): 15,
Export(
"requestAsyncStorage",
): 18,
......@@ -420,6 +417,9 @@ graph TD
"routeModule",
): 12,
Exports: 19,
Export(
"workAsyncStorage",
): 15,
Export(
"originalPathname",
): 1,
......@@ -608,11 +608,11 @@ import "__TURBOPACK_PART__" assert {
import { f as routeModule } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 10
};
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule;
const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
export { requestAsyncStorage as g } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true
};
export { staticGenerationAsyncStorage as h } from "__TURBOPACK_VAR__" assert {
export { workAsyncStorage as h } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true
};
export { serverHooks as i } from "__TURBOPACK_VAR__" assert {
......@@ -636,10 +636,10 @@ export { serverHooks };
import "__TURBOPACK_PART__" assert {
__turbopack_part__: 13
};
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert {
import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 13
};
export { staticGenerationAsyncStorage };
export { workAsyncStorage };
```
## Part 16
......@@ -656,7 +656,7 @@ import "__TURBOPACK_PART__" assert {
import "__TURBOPACK_PART__" assert {
__turbopack_part__: 15
};
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert {
import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 13
};
import { b as _patchFetch } from "__TURBOPACK_PART__" assert {
......@@ -668,7 +668,7 @@ import { i as serverHooks } from "__TURBOPACK_PART__" assert {
function patchFetch() {
return _patchFetch({
serverHooks,
staticGenerationAsyncStorage
workAsyncStorage
});
}
export { patchFetch as j } from "__TURBOPACK_VAR__" assert {
......@@ -709,8 +709,8 @@ export { routeModule } from "__TURBOPACK_PART__" assert {
export { serverHooks } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export serverHooks"
};
export { staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export staticGenerationAsyncStorage"
export { workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export workAsyncStorage"
};
export { patchFetch } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export patchFetch"
......@@ -751,9 +751,6 @@ import "__TURBOPACK_PART__" assert {
Export(
"serverHooks",
): 15,
Export(
"staticGenerationAsyncStorage",
): 16,
Export(
"requestAsyncStorage",
): 17,
......@@ -761,6 +758,9 @@ import "__TURBOPACK_PART__" assert {
"routeModule",
): 11,
Exports: 19,
Export(
"workAsyncStorage",
): 16,
Export(
"originalPathname",
): 1,
......@@ -926,11 +926,11 @@ import "__TURBOPACK_PART__" assert {
import { f as routeModule } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 10
};
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } = routeModule;
const { requestAsyncStorage, workAsyncStorage, serverHooks } = routeModule;
export { requestAsyncStorage as g } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true
};
export { staticGenerationAsyncStorage as h } from "__TURBOPACK_VAR__" assert {
export { workAsyncStorage as h } from "__TURBOPACK_VAR__" assert {
__turbopack_var__: true
};
export { serverHooks as i } from "__TURBOPACK_VAR__" assert {
......@@ -946,7 +946,7 @@ import "__TURBOPACK_PART__" assert {
import "__TURBOPACK_PART__" assert {
__turbopack_part__: 12
};
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert {
import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 12
};
import { b as _patchFetch } from "__TURBOPACK_PART__" assert {
......@@ -958,7 +958,7 @@ import { i as serverHooks } from "__TURBOPACK_PART__" assert {
function patchFetch() {
return _patchFetch({
serverHooks,
staticGenerationAsyncStorage
workAsyncStorage
});
}
export { patchFetch as j } from "__TURBOPACK_VAR__" assert {
......@@ -993,10 +993,10 @@ export { serverHooks };
import "__TURBOPACK_PART__" assert {
__turbopack_part__: 12
};
import { h as staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert {
import { h as workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: 12
};
export { staticGenerationAsyncStorage };
export { workAsyncStorage };
```
## Part 17
......@@ -1044,8 +1044,8 @@ export { patchFetch } from "__TURBOPACK_PART__" assert {
export { serverHooks } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export serverHooks"
};
export { staticGenerationAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export staticGenerationAsyncStorage"
export { workAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export workAsyncStorage"
};
export { requestAsyncStorage } from "__TURBOPACK_PART__" assert {
__turbopack_part__: "export requestAsyncStorage"
......
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