Unverified Commit 1c1d9b5f authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Use and enforce exhaustive switch statements for work unit store (#81577)

This allows us to introduce more work unit store types with confidence.

closes NAR-203
parent 079c06d3
......@@ -316,6 +316,16 @@
{
"message": "substr() is deprecated, use slice() or substring() instead",
"selector": "MemberExpression > Identifier[name='substr']"
},
// ban plain workUnitStore.type if statements and ternaries
{
"selector": "BinaryExpression[left.object.name='workUnitStore'][left.property.name='type'][operator=/^(?:===|!==)$/]",
"message": "Use an exhaustive switch on `workUnitStore.type` (with a `never`-based default) instead of using if statements or ternaries."
},
// ban optional-chained workUnitStore?.type if statements and ternaries
{
"selector": "BinaryExpression[left.type='ChainExpression'][left.expression.object.name='workUnitStore'][left.expression.property.name='type'][operator=/^(?:===|!==)$/]",
"message": "Use an exhaustive switch on `workUnitStore.type` (with a `never`-based default) instead of using if statements or ternaries."
}
],
"no-script-url": "error",
......
......@@ -717,5 +717,6 @@
"716": "NEXT_DEVTOOLS_SIMULATED_ERROR",
"717": "Unsupported environment condition \"%s\" and react condition \"%s\". This is a bug in Next.js.",
"718": "Invariant: projectDir is required for node runtime",
"719": "Failed to get source map for '%s'. This is a bug in Next.js"
"719": "Failed to get source map for '%s'. This is a bug in Next.js",
"720": "A client prerender store should not be used for a route handler."
}
......@@ -16,7 +16,12 @@ export function bailoutToClientRendering(reason: string): void | never {
case 'prerender-ppr':
case 'prerender-legacy':
throw new BailoutToCSRError(reason)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
}
......@@ -1233,12 +1233,24 @@ async function renderToHTMLOrFlightImpl(
return true
}
const workUnitStore = workUnitAsyncStorage.getStore()
return !!(
workUnitStore &&
(workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-client' ||
workUnitStore.type === 'cache')
)
if (!workUnitStore) {
return false
}
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'cache':
return true
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
return false
default:
workUnitStore satisfies never
}
}
const __next_require__: typeof instrumented.require = (...args) => {
......
......@@ -293,15 +293,21 @@ async function createComponentTreeInternal({
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
if (
workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-legacy' ||
workUnitStore.type === 'prerender-ppr' ||
workUnitStore.type === 'cache'
) {
if (workUnitStore.revalidate > defaultRevalidate) {
workUnitStore.revalidate = defaultRevalidate
}
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-legacy':
case 'prerender-ppr':
case 'cache':
if (workUnitStore.revalidate > defaultRevalidate) {
workUnitStore.revalidate = defaultRevalidate
}
break
case 'prerender-client':
case 'request':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
......
......@@ -122,14 +122,20 @@ export function markCurrentScopeAsDynamic(
expression: string
): void {
if (workUnitStore) {
if (
workUnitStore.type === 'cache' ||
workUnitStore.type === 'unstable-cache'
) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is
// forbidden inside a cache scope.
return
switch (workUnitStore.type) {
case 'cache':
case 'unstable-cache':
// Inside cache scopes, marking a scope as dynamic has no effect,
// because the outer cache scope creates a cache boundary. This is
// subtly different from reading a dynamic data source, which is
// forbidden inside a cache scope.
return
case 'prerender-legacy':
case 'prerender-ppr':
case 'request':
break
default:
workUnitStore satisfies never
}
}
......@@ -145,51 +151,36 @@ export function markCurrentScopeAsDynamic(
}
if (workUnitStore) {
if (workUnitStore.type === 'prerender-ppr') {
postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
workUnitStore.revalidate = 0
switch (workUnitStore.type) {
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
workUnitStore.revalidate = 0
// We aren't prerendering but we are generating a static page. We need to bail out of static generation
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
throw err
} else if (
process.env.NODE_ENV === 'development' &&
workUnitStore &&
workUnitStore.type === 'request'
) {
workUnitStore.usedDynamic = true
// We aren't prerendering, but we are generating a static page. We need
// to bail out of static generation.
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
throw err
case 'request':
if (process.env.NODE_ENV !== 'production') {
workUnitStore.usedDynamic = true
}
break
default:
workUnitStore satisfies never
}
}
}
/**
* This function communicates that some dynamic path parameter was read. This
* differs from the more general `trackDynamicDataAccessed` in that it is will
* not error when `dynamic = "error"` is set.
*
* @param store The static generation store
* @param expression The expression that was accessed dynamically
*/
export function trackFallbackParamAccessed(
store: WorkStore,
expression: string
): void {
const prerenderStore = workUnitAsyncStorage.getStore()
if (!prerenderStore || prerenderStore.type !== 'prerender-ppr') return
postponeWithTracking(store.route, expression, prerenderStore.dynamicTracking)
}
/**
* This function is meant to be used when prerendering without dynamicIO or PPR.
* When called during a build it will cause Next.js to consider the route as dynamic.
......@@ -221,34 +212,27 @@ export function throwToInterruptStaticGeneration(
*
* @internal
*/
export function trackDynamicDataInDynamicRender(
_store: WorkStore,
workUnitStore: void | WorkUnitStore
) {
if (workUnitStore) {
if (
workUnitStore.type === 'cache' ||
workUnitStore.type === 'unstable-cache'
) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is
export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
switch (workUnitStore.type) {
case 'cache':
case 'unstable-cache':
// Inside cache scopes, marking a scope as dynamic has no effect,
// because the outer cache scope creates a cache boundary. This is
// subtly different from reading a dynamic data source, which is
// forbidden inside a cache scope.
return
}
// TODO: it makes no sense to have these work unit store types during a dev render.
if (
workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-client' ||
workUnitStore.type === 'prerender-legacy'
) {
workUnitStore.revalidate = 0
}
if (
process.env.NODE_ENV === 'development' &&
workUnitStore.type === 'request'
) {
workUnitStore.usedDynamic = true
}
case 'prerender':
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':
break
case 'request':
if (process.env.NODE_ENV !== 'production') {
workUnitStore.usedDynamic = true
}
break
default:
workUnitStore satisfies never
}
}
......@@ -529,27 +513,40 @@ export function createPostponedAbortSignal(reason: string): AbortSignal {
* case we need to abort the encoding of arguments since they'll never complete.
*/
export function createHangingInputAbortSignal(
workUnitStore: PrerenderStoreModern
): AbortSignal {
const controller = new AbortController()
workUnitStore: WorkUnitStore
): AbortSignal | undefined {
switch (workUnitStore.type) {
case 'prerender':
const controller = new AbortController()
if (workUnitStore.cacheSignal) {
// If we have a cacheSignal it means we're in a prospective render. If
// the input we're waiting on is coming from another cache, we do want
// to wait for it so that we can resolve this cache entry too.
workUnitStore.cacheSignal.inputReady().then(() => {
controller.abort()
})
} else {
// Otherwise we're in the final render and we should already have all
// our caches filled. We might still be waiting on some microtasks so we
// wait one tick before giving up. When we give up, we still want to
// render the content of this cache as deeply as we can so that we can
// suspend as deeply as possible in the tree or not at all if we don't
// end up waiting for the input.
scheduleOnNextTick(() => controller.abort())
}
if (workUnitStore.cacheSignal) {
// If we have a cacheSignal it means we're in a prospective render. If the input
// we're waiting on is coming from another cache, we do want to wait for it so that
// we can resolve this cache entry too.
workUnitStore.cacheSignal.inputReady().then(() => {
controller.abort()
})
} else {
// Otherwise we're in the final render and we should already have all our caches
// filled. We might still be waiting on some microtasks so we wait one tick before
// giving up. When we give up, we still want to render the content of this cache
// as deeply as we can so that we can suspend as deeply as possible in the tree
// or not at all if we don't end up waiting for the input.
scheduleOnNextTick(() => controller.abort())
return controller.signal
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
return undefined
default:
workUnitStore satisfies never
}
return controller.signal
}
export function annotateDynamicAccess(
......@@ -580,21 +577,32 @@ export function useDynamicRouteParams(expression: string) {
// accesses.
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
// We're prerendering with dynamicIO or PPR or both
if (workUnitStore.type === 'prerender-client') {
// We are in a prerender with dynamicIO semantics
// We are going to hang here and never resolve. This will cause the currently
// rendering component to effectively be a dynamic hole
React.use(makeHangingPromise(workUnitStore.renderSignal, expression))
} else if (workUnitStore.type === 'prerender-ppr') {
// We're prerendering with PPR
postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
throwToInterruptStaticGeneration(expression, workStore, workUnitStore)
switch (workUnitStore.type) {
case 'prerender-client':
// We are in a prerender with dynamicIO semantics. We are going to
// hang here and never resolve. This will cause the currently
// rendering component to effectively be a dynamic hole.
React.use(makeHangingPromise(workUnitStore.renderSignal, expression))
break
case 'prerender':
case 'prerender-ppr':
return postponeWithTracking(
workStore.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
return throwToInterruptStaticGeneration(
expression,
workStore,
workUnitStore
)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
}
......
......@@ -17,6 +17,7 @@ import {
stringToUint8Array,
} from './encryption-utils'
import {
getCacheSignal,
getPrerenderResumeDataCache,
getRenderResumeDataCache,
workUnitAsyncStorage,
......@@ -95,10 +96,9 @@ enum ReadStatus {
export const encryptActionBoundArgs = React.cache(
async function encryptActionBoundArgs(actionId: string, ...args: any[]) {
const workUnitStore = workUnitAsyncStorage.getStore()
const cacheSignal =
workUnitStore?.type === 'prerender'
? workUnitStore.cacheSignal
: undefined
const cacheSignal = workUnitStore
? getCacheSignal(workUnitStore)
: undefined
const { clientModules } = getClientReferenceManifestForRsc()
......@@ -109,10 +109,9 @@ export const encryptActionBoundArgs = React.cache(
let didCatchError = false
const hangingInputAbortSignal =
workUnitStore?.type === 'prerender'
? createHangingInputAbortSignal(workUnitStore)
: undefined
const hangingInputAbortSignal = workUnitStore
? createHangingInputAbortSignal(workUnitStore)
: undefined
let readStatus = ReadStatus.Ready
function startReadOnce() {
......@@ -227,9 +226,7 @@ export async function decryptActionBoundArgs(
let decrypted: string | undefined
if (workUnitStore) {
const cacheSignal =
workUnitStore.type === 'prerender' ? workUnitStore.cacheSignal : undefined
const cacheSignal = getCacheSignal(workUnitStore)
const prerenderResumeDataCache = getPrerenderResumeDataCache(workUnitStore)
const renderResumeDataCache = getRenderResumeDataCache(workUnitStore)
......@@ -256,20 +253,30 @@ export async function decryptActionBoundArgs(
start(controller) {
controller.enqueue(textEncoder.encode(decrypted))
if (workUnitStore?.type === 'prerender') {
// Explicitly don't close the stream here (until prerendering is
// complete) so that hanging promises are not rejected.
if (workUnitStore.renderSignal.aborted) {
controller.close()
} else {
workUnitStore.renderSignal.addEventListener(
'abort',
() => controller.close(),
{ once: true }
)
}
} else {
controller.close()
switch (workUnitStore?.type) {
case 'prerender':
// Explicitly don't close the stream here (until prerendering is
// complete) so that hanging promises are not rejected.
if (workUnitStore.renderSignal.aborted) {
controller.close()
} else {
workUnitStore.renderSignal.addEventListener(
'abort',
() => controller.close(),
{ once: true }
)
}
break
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
case undefined:
return controller.close()
default:
workUnitStore satisfies never
}
},
}),
......
......@@ -51,17 +51,27 @@ export function useFlightStream<T>(
// that requires the nextTick behavior. This is why it is safe to access a node only API here
if (process.env.NEXT_RUNTIME !== 'edge') {
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore) {
throw new InvariantError('Expected workUnitAsyncStorage to have a store.')
}
if (workUnitStore.type === 'prerender-client') {
const responseOnNextTick = new Promise<T>((r) => {
process.nextTick(() => {
r(newResponse)
switch (workUnitStore.type) {
case 'prerender-client':
const responseOnNextTick = new Promise<T>((resolve) => {
process.nextTick(() => resolve(newResponse))
})
})
flightResponses.set(flightStream, responseOnNextTick)
return responseOnNextTick
flightResponses.set(flightStream, responseOnNextTick)
return responseOnNextTick
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
......
......@@ -264,8 +264,7 @@ export function getExpectedRequestStore(
)
default:
const _exhaustiveCheck: never = workUnitStore
return _exhaustiveCheck
return workUnitStore satisfies never
}
}
......@@ -278,16 +277,22 @@ export function throwForMissingRequestStore(callingExpression: string): never {
export function getPrerenderResumeDataCache(
workUnitStore: WorkUnitStore
): PrerenderResumeDataCache | null {
if (
workUnitStore.type === 'prerender' ||
// TODO eliminate fetch caching in client scope and stop exposing this data cache during SSR
workUnitStore.type === 'prerender-client' ||
workUnitStore.type === 'prerender-ppr'
) {
return workUnitStore.prerenderResumeDataCache
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-ppr':
return workUnitStore.prerenderResumeDataCache
case 'prerender-client':
// TODO eliminate fetch caching in client scope and stop exposing this data
// cache during SSR.
return workUnitStore.prerenderResumeDataCache
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
return null
default:
return workUnitStore satisfies never
}
return null
}
export function getRenderResumeDataCache(
......@@ -308,8 +313,12 @@ export function getRenderResumeDataCache(
// Otherwise we return the mutable resume data cache here as an immutable
// version of the cache as it can also be used for reading.
return workUnitStore.prerenderResumeDataCache
default:
case 'cache':
case 'unstable-cache':
case 'prerender-legacy':
return null
default:
return workUnitStore satisfies never
}
}
......@@ -317,15 +326,24 @@ export function getHmrRefreshHash(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): string | undefined {
if (!workStore.dev) {
return undefined
if (workStore.dev) {
switch (workUnitStore.type) {
case 'cache':
case 'prerender':
return workUnitStore.hmrRefreshHash
case 'request':
return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
return workUnitStore.type === 'cache' || workUnitStore.type === 'prerender'
? workUnitStore.hmrRefreshHash
: workUnitStore.type === 'request'
? workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
: undefined
return undefined
}
/**
......@@ -341,10 +359,33 @@ export function getDraftModeProviderForCacheScope(
case 'unstable-cache':
case 'request':
return workUnitStore.draftMode
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
break
default:
return undefined
workUnitStore satisfies never
}
}
return undefined
}
export function getCacheSignal(
workUnitStore: WorkUnitStore
): CacheSignal | null {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
return workUnitStore.cacheSignal
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
return null
default:
return workUnitStore satisfies never
}
}
This diff is collapsed.
......@@ -128,15 +128,22 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')
const wrapperMethod = function (this: typeof console, ...args: any[]) {
const workUnitStore = workUnitAsyncStorage.getStore()
const isPrerenderValidation =
workUnitStore !== undefined &&
(workUnitStore.type === 'prerender-client' ||
workUnitStore.type === 'prerender')
if (isPrerenderValidation) {
originalMethod.apply(this, dimConsoleCall(methodName, args))
} else {
originalMethod.apply(this, args)
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
originalMethod.apply(this, dimConsoleCall(methodName, args))
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
case undefined:
originalMethod.apply(this, args)
break
default:
workUnitStore satisfies never
}
}
if (originalName) {
......
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import {
workUnitAsyncStorage,
type PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
import {
abortOnSynchronousPlatformIOAccess,
trackSynchronousPlatformIOAccessInDev,
......@@ -10,93 +13,123 @@ type ApiType = 'time' | 'random' | 'crypto'
export function io(expression: string, type: ApiType) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
let isClient = false
if (
workUnitStore.type === 'prerender' ||
(isClient = workUnitStore.type === 'prerender-client')
) {
const workStore = workAsyncStorage.getStore()
if (!workUnitStore || !workStore) {
return
}
switch (workUnitStore.type) {
case 'prerender': {
const prerenderSignal = workUnitStore.controller.signal
if (prerenderSignal.aborted === false) {
// If the prerender signal is already aborted we don't need to construct any stacks
// because something else actually terminated the prerender.
const workStore = workAsyncStorage.getStore()
if (workStore) {
let message: string
switch (type) {
case 'time':
message = isClient
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client`
: `Route "${workStore.route}" used ${expression} instead of using \`performance\` or without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
break
case 'random':
message = isClient
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-random-client`
: `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random`
break
case 'crypto':
message = isClient
? `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto-client`
: `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
// If the prerender signal is already aborted we don't need to construct
// any stacks because something else actually terminated the prerender.
let message: string
switch (type) {
case 'time':
message = `Route "${workStore.route}" used ${expression} instead of using \`performance\` or without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
break
case 'random':
message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random`
break
case 'crypto':
message = `Route "${workStore.route}" used ${expression} outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
const errorWithStack = new Error(message)
if (
process.env.NODE_ENV !== 'production' &&
workUnitStore.captureOwnerStack
) {
const ownerStack = workUnitStore.captureOwnerStack()
if (ownerStack) {
// TODO: Instead of stitching the stacks here, we should log the
// original error as-is when it occurs (i.e. here), and let
// `patchErrorInspect` handle adding the owner stack, instead of
// logging it deferred in the `LogSafely` component via
// `throwIfDisallowedDynamic`.
applyOwnerStack(errorWithStack, ownerStack)
}
}
abortOnSynchronousPlatformIOAccess(
workStore.route,
expression,
applyOwnerStack(new Error(message), workUnitStore),
workUnitStore
)
}
break
}
case 'prerender-client': {
const prerenderSignal = workUnitStore.controller.signal
abortOnSynchronousPlatformIOAccess(
workStore.route,
expression,
errorWithStack,
workUnitStore
)
if (prerenderSignal.aborted === false) {
// If the prerender signal is already aborted we don't need to construct
// any stacks because something else actually terminated the prerender.
let message: string
switch (type) {
case 'time':
message = `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client`
break
case 'random':
message = `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-random-client`
break
case 'crypto':
message = `Route "${workStore.route}" used ${expression} inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-crypto-client`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
abortOnSynchronousPlatformIOAccess(
workStore.route,
expression,
applyOwnerStack(new Error(message), workUnitStore),
workUnitStore
)
}
} else if (
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
const requestStore = workUnitStore
trackSynchronousPlatformIOAccessInDev(requestStore)
break
}
case 'request':
if (workUnitStore.prerenderPhase === true) {
trackSynchronousPlatformIOAccessInDev(workUnitStore)
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
function applyOwnerStack(error: Error, ownerStack: string) {
let stack = ownerStack
function applyOwnerStack(error: Error, workUnitStore: PrerenderStoreModern) {
// TODO: Instead of stitching the stacks here, we should log the original
// error as-is when it occurs, and let `patchErrorInspect` handle adding the
// owner stack, instead of logging it deferred in the `LogSafely` component
// via `throwIfDisallowedDynamic`.
if (
process.env.NODE_ENV !== 'production' &&
workUnitStore.captureOwnerStack
) {
const ownerStack = workUnitStore.captureOwnerStack()
if (ownerStack) {
let stack = ownerStack
if (error.stack) {
const frames: string[] = []
if (error.stack) {
const frames: string[] = []
for (const frame of error.stack.split('\n').slice(1)) {
if (frame.includes('react_stack_bottom_frame')) {
break
for (const frame of error.stack.split('\n').slice(1)) {
if (frame.includes('react_stack_bottom_frame')) {
break
}
frames.push(frame)
}
stack = '\n' + frames.join('\n') + stack
}
frames.push(frame)
error.stack = error.name + ': ' + error.message + stack
}
stack = '\n' + frames.join('\n') + stack
}
error.stack = error.name + ': ' + error.message + stack
return error
}
......@@ -30,22 +30,11 @@ export function connection(): Promise<void> {
}
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
// headers object without tracking
// When using forceStatic, we override all other logic and always just
// return a resolving promise without tracking.
return Promise.resolve(undefined)
}
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${workStore.route} used "connection" inside "use 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/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`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`
)
}
}
if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError(
`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,30 +42,46 @@ export function connection(): Promise<void> {
}
if (workUnitStore) {
if (
workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-client'
) {
// dynamicIO Prerender
// We return a promise that never resolves to allow the prender to stall at this point
return makeHangingPromise(workUnitStore.renderSignal, '`connection()`')
} else if (workUnitStore.type === 'prerender-ppr') {
// PPR Prerender (no dynamicIO)
// We use React's postpone API to interrupt rendering here to create a dynamic hole
postponeWithTracking(
workStore.route,
'connection',
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
// Legacy Prerender
// We throw an error here to interrupt prerendering to mark the route as dynamic
throwToInterruptStaticGeneration('connection', workStore, workUnitStore)
switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${workStore.route} used "connection" inside "use 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/messages/next-request-in-use-cache`
)
case 'unstable-cache':
throw new Error(
`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`
)
case 'prerender':
case 'prerender-client':
// We return a promise that never resolves to allow the prerender to
// stall at this point.
return makeHangingPromise(
workUnitStore.renderSignal,
'`connection()`'
)
case 'prerender-ppr':
// We use React's postpone API to interrupt rendering here to create a
// dynamic hole
return postponeWithTracking(
workStore.route,
'connection',
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
// We throw an error here to interrupt prerendering to mark the route
// as dynamic
return throwToInterruptStaticGeneration(
'connection',
workStore,
workUnitStore
)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
break
default:
workUnitStore satisfies never
}
}
// 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(workStore, workUnitStore)
}
return Promise.resolve(undefined)
......
......@@ -72,17 +72,6 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
return makeUntrackedExoticCookies(underlyingCookies)
}
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${workStore.route} used "cookies" inside "use 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/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`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`
)
}
}
if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError(
`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`
......@@ -91,6 +80,14 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${workStore.route} used "cookies" inside "use 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/messages/next-request-in-use-cache`
)
case 'unstable-cache':
throw new Error(
`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`
)
case 'prerender':
return makeHangingCookies(workUnitStore)
case 'prerender-client':
......@@ -99,32 +96,28 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
)
case 'prerender-ppr':
// PPR Prerender (no dynamicIO)
// We are prerendering with PPR. We need track dynamic access here eagerly
// to keep continuity with how cookies has worked in PPR without dynamicIO.
postponeWithTracking(
// We need track dynamic access here eagerly to keep continuity with
// how cookies has worked in PPR without dynamicIO.
return postponeWithTracking(
workStore.route,
callingExpression,
workUnitStore.dynamicTracking
)
break
case 'prerender-legacy':
// Legacy Prerender
// We track dynamic access here so we don't need to wrap the cookies in
// individual property access tracking.
throwToInterruptStaticGeneration(
// We track dynamic access here so we don't need to wrap the cookies
// in individual property access tracking.
return throwToInterruptStaticGeneration(
callingExpression,
workStore,
workUnitStore
)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
break
default:
// fallthrough
workUnitStore satisfies never
}
}
// 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(workStore, workUnitStore)
}
// cookies is being called in a dynamic context
......@@ -459,16 +452,28 @@ function describeNameArg(arg: unknown) {
function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
// When we're rendering dynamically in dev we need to advance out of the
// Prerender environment when we read Request data synchronously
const requestStore = workUnitStore
trackSynchronousRequestDataAccessInDev(requestStore)
if (workUnitStore) {
switch (workUnitStore.type) {
case 'request':
if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev, we need to advance out of
// the Prerender environment when we read Request data synchronously.
trackSynchronousRequestDataAccessInDev(workUnitStore)
}
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
// In all cases we warn normally
warnForSyncAccess(route, expression)
}
......
......@@ -13,6 +13,7 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
trackDynamicDataInDynamicRender,
trackSynchronousRequestDataAccessInDev,
} from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'
......@@ -81,8 +82,7 @@ export function draftMode(): Promise<DraftMode> {
return createOrGetCachedDraftMode(null, workStore)
default:
const _exhaustiveCheck: never = workUnitStore
return _exhaustiveCheck
return workUnitStore satisfies never
}
}
......@@ -244,16 +244,28 @@ class DraftMode {
function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
// When we're rendering dynamically in dev we need to advance out of the
// Prerender environment when we read Request data synchronously
const requestStore = workUnitStore
trackSynchronousRequestDataAccessInDev(requestStore)
if (workUnitStore) {
switch (workUnitStore.type) {
case 'request':
if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev, we need to advance out of
// the Prerender environment when we read Request data synchronously.
trackSynchronousRequestDataAccessInDev(workUnitStore)
}
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
// In all cases we warn normally
warnForSyncAccess(route, expression)
}
......@@ -280,20 +292,10 @@ function trackDynamicDraftMode(expression: string) {
if (store) {
// We have a store we want to track dynamic data access to ensure we
// don't statically generate routes that manipulate draft mode.
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
} else if (workUnitStore.phase === 'after') {
throw new Error(
`Route ${store.route} used "${expression}" inside \`after\`. The enabled status of draftMode can be read inside \`after\` but you cannot enable or disable draftMode. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
if (workUnitStore?.phase === 'after') {
throw new Error(
`Route ${store.route} used "${expression}" inside \`after\`. The enabled status of draftMode can be read inside \`after\` but you cannot enable or disable draftMode. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
if (store.dynamicShouldError) {
......@@ -304,33 +306,36 @@ function trackDynamicDraftMode(expression: string) {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'prerender':
// dynamicIO Prerender
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
)
abortAndThrowOnSynchronousRequestDataAccess(
return abortAndThrowOnSynchronousRequestDataAccess(
store.route,
expression,
error,
workUnitStore
)
break
case 'prerender-client':
const exportName = '`draftMode`'
throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
)
case 'prerender-ppr':
// PPR Prerender
postponeWithTracking(
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
break
case 'prerender-legacy':
// legacy Prerender
workUnitStore.revalidate = 0
const err = new DynamicServerError(
......@@ -341,12 +346,10 @@ function trackDynamicDraftMode(expression: string) {
throw err
case 'request':
if (process.env.NODE_ENV === 'development') {
workUnitStore.usedDynamic = true
}
trackDynamicDataInDynamicRender(workUnitStore)
break
default:
// fallthrough
workUnitStore satisfies never
}
}
}
......
......@@ -77,16 +77,26 @@ export function headers(): Promise<ReadonlyHeaders> {
}
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${workStore.route} used "headers" inside "use 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/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`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`
)
switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${workStore.route} used "headers" inside "use 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/messages/next-request-in-use-cache`
)
case 'unstable-cache':
throw new Error(
`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`
)
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
break
default:
workUnitStore satisfies never
}
}
if (workStore.dynamicShouldError) {
throw new StaticGenBailoutError(
`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`
......@@ -107,26 +117,28 @@ export function headers(): Promise<ReadonlyHeaders> {
// We are prerendering with PPR. We need track dynamic access here eagerly
// to keep continuity with how headers has worked in PPR without dynamicIO.
// TODO consider switching the semantic to throw on property access instead
postponeWithTracking(
return postponeWithTracking(
workStore.route,
'headers',
workUnitStore.dynamicTracking
)
break
case 'prerender-legacy':
// Legacy Prerender
// 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', workStore, workUnitStore)
return throwToInterruptStaticGeneration(
'headers',
workStore,
workUnitStore
)
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
break
default:
// fallthrough
workUnitStore satisfies never
}
}
// 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(workStore, workUnitStore)
}
const requestStore = getExpectedRequestStore('headers')
......@@ -391,16 +403,28 @@ function describeNameArg(arg: unknown) {
function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
// When we're rendering dynamically in dev we need to advance out of the
// Prerender environment when we read Request data synchronously
const requestStore = workUnitStore
trackSynchronousRequestDataAccessInDev(requestStore)
if (workUnitStore) {
switch (workUnitStore.type) {
case 'request':
if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev, we need to advance out of
// the Prerender environment when we read Request data synchronously.
trackSynchronousRequestDataAccessInDev(workUnitStore)
}
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
// In all cases we warn normally
warnForSyncAccess(route, expression)
}
......
......@@ -68,8 +68,12 @@ export function createParamsFromClient(
case 'prerender-ppr':
case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
// fallthrough
workUnitStore satisfies never
}
}
return createRenderParams(underlyingParams, workStore)
......@@ -92,8 +96,12 @@ export function createServerParamsForRoute(
case 'prerender-ppr':
case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
// fallthrough
workUnitStore satisfies never
}
}
return createRenderParams(underlyingParams, workStore)
......@@ -111,8 +119,12 @@ export function createServerParamsForServerSegment(
case 'prerender-ppr':
case 'prerender-legacy':
return createPrerenderParams(underlyingParams, workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
// fallthrough
workUnitStore satisfies never
}
}
return createRenderParams(underlyingParams, workStore)
......@@ -122,22 +134,32 @@ export function createPrerenderParamsForClientSegment(
underlyingParams: Params,
workStore: WorkStore
): Promise<Params> {
const prerenderStore = workUnitAsyncStorage.getStore()
if (
prerenderStore &&
(prerenderStore.type === 'prerender' ||
prerenderStore.type === 'prerender-client')
) {
const fallbackParams = workStore.fallbackRouteParams
if (fallbackParams) {
for (let key in underlyingParams) {
if (fallbackParams.has(key)) {
// This params object has one of more fallback params so we need to consider
// the awaiting of this params object "dynamic". Since we are in dynamicIO mode
// we encode this as a promise that never resolves
return makeHangingPromise(prerenderStore.renderSignal, '`params`')
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
const fallbackParams = workStore.fallbackRouteParams
if (fallbackParams) {
for (let key in underlyingParams) {
if (fallbackParams.has(key)) {
// This params object has one or more fallback params, so we need
// to consider the awaiting of this params object "dynamic". Since
// we are in dynamicIO mode we encode this as a promise that never
// resolves.
return makeHangingPromise(workUnitStore.renderSignal, '`params`')
}
}
}
}
break
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
// We're prerendering in a mode that does not abort. We resolve the promise without
......@@ -168,13 +190,16 @@ function createPrerenderParams(
case 'prerender-client':
// We are in a dynamicIO prerender
return makeHangingParams(underlyingParams, prerenderStore)
default:
case 'prerender-ppr':
case 'prerender-legacy':
return makeErroringExoticParams(
underlyingParams,
fallbackParams,
workStore,
prerenderStore
)
default:
prerenderStore satisfies never
}
}
}
......@@ -516,15 +541,25 @@ function syncIODev(
missingProperties?: Array<string>
) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
// When we're rendering dynamically in dev we need to advance out of the
// Prerender environment when we read Request data synchronously
const requestStore = workUnitStore
trackSynchronousRequestDataAccessInDev(requestStore)
if (workUnitStore) {
switch (workUnitStore.type) {
case 'request':
if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev, we need to advance out of
// the Prerender environment when we read Request data synchronously.
trackSynchronousRequestDataAccessInDev(workUnitStore)
}
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
// In all cases we warn normally
if (missingProperties && missingProperties.length > 0) {
......
......@@ -29,8 +29,12 @@ export function createServerPathnameForMetadata(
workUnitStore
)
}
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
// fallthrough
workUnitStore satisfies never
}
}
return createRenderPathname(underlyingPathname)
......@@ -55,9 +59,10 @@ function createPrerenderPathname(
)
case 'prerender-ppr':
return makeErroringPathname(workStore, prerenderStore.dynamicTracking)
break
default:
case 'prerender-legacy':
return makeErroringPathname(workStore, null)
default:
prerenderStore satisfies never
}
}
......
......@@ -54,8 +54,10 @@ export async function unstable_rootParams(): Promise<Params> {
workStore,
workUnitStore
)
default:
case 'request':
return Promise.resolve(workUnitStore.rootParams)
default:
return workUnitStore satisfies never
}
}
......@@ -96,8 +98,8 @@ function createPrerenderRootParams(
throw new InvariantError(
`${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`
)
default:
// remaining cases are prerender-ppr and prerender-legacy
case 'prerender-ppr':
case 'prerender-legacy':
// We aren't in a dynamicIO prerender but we do have fallback params at this
// level so we need to make an erroring params object which will postpone
// if you access the fallback params
......@@ -107,6 +109,8 @@ function createPrerenderRootParams(
workStore,
prerenderStore
)
default:
prerenderStore satisfies never
}
}
}
......
......@@ -72,8 +72,12 @@ export function createSearchParamsFromClient(
case 'prerender-ppr':
case 'prerender-legacy':
return createPrerenderSearchParams(workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
// fallthrough
workUnitStore satisfies never
}
}
return createRenderSearchParams(underlyingSearchParams, workStore)
......@@ -95,8 +99,12 @@ export function createServerSearchParamsForServerPage(
case 'prerender-ppr':
case 'prerender-legacy':
return createPrerenderSearchParams(workStore, workUnitStore)
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
// fallthrough
workUnitStore satisfies never
}
}
return createRenderSearchParams(underlyingSearchParams, workStore)
......@@ -111,20 +119,27 @@ export function createPrerenderSearchParamsForClientPage(
return Promise.resolve({})
}
const prerenderStore = workUnitAsyncStorage.getStore()
if (
prerenderStore &&
(prerenderStore.type === 'prerender' ||
prerenderStore.type === 'prerender-client')
) {
// dynamicIO Prerender
// We're prerendering in a mode that aborts (dynamicIO) and should stall
// the promise to ensure the RSC side is considered dynamic
return makeHangingPromise(prerenderStore.renderSignal, '`searchParams`')
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
// We're prerendering in a mode that aborts (dynamicIO) and should stall
// the promise to ensure the RSC side is considered dynamic
return makeHangingPromise(workUnitStore.renderSignal, '`searchParams`')
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
// We're prerendering in a mode that does not aborts. We resolve the promise without
// any tracking because we're just transporting a value from server to client where the tracking
// will be applied.
// We're prerendering in a mode that does not abort. We resolve the promise
// without any tracking because we're just transporting a value from server to
// client where the tracking will be applied.
return Promise.resolve({})
}
......@@ -143,11 +158,13 @@ function createPrerenderSearchParams(
case 'prerender-client':
// We are in a dynamicIO (PPR or otherwise) prerender
return makeHangingSearchParams(prerenderStore)
default:
// The remaining cases are prerender-ppr and prerender-legacy
// We are in a legacy static generation and need to interrupt the prerender
// when search params are accessed.
case 'prerender-ppr':
case 'prerender-legacy':
// We are in a legacy static generation and need to interrupt the
// prerender when search params are accessed.
return makeErroringExoticSearchParams(workStore, prerenderStore)
default:
return prerenderStore satisfies never
}
}
......@@ -180,7 +197,7 @@ function createRenderSearchParams(
return makeUntrackedSearchParams(underlyingSearchParams)
}
return makeUntrackedExoticSearchParams(underlyingSearchParams, workStore)
return makeUntrackedExoticSearchParams(underlyingSearchParams)
}
}
}
......@@ -464,8 +481,7 @@ export function makeErroringExoticSearchParamsForUseCache(
}
function makeUntrackedExoticSearchParams(
underlyingSearchParams: SearchParams,
store: WorkStore
underlyingSearchParams: SearchParams
): Promise<SearchParams> {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
if (cachedSearchParams) {
......@@ -483,7 +499,9 @@ function makeUntrackedExoticSearchParams(
Object.defineProperty(promise, prop, {
get() {
const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataInDynamicRender(store, workUnitStore)
if (workUnitStore) {
trackDynamicDataInDynamicRender(workUnitStore)
}
return underlyingSearchParams[prop]
},
set(value) {
......@@ -546,7 +564,9 @@ function makeDynamicallyTrackedExoticSearchParamsWithDevWarnings(
)
}
const workUnitStore = workUnitAsyncStorage.getStore()
trackDynamicDataInDynamicRender(store, workUnitStore)
if (workUnitStore) {
trackDynamicDataInDynamicRender(workUnitStore)
}
}
return ReflectAdapter.get(target, prop, receiver)
},
......@@ -760,15 +780,25 @@ function syncIODev(
}
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
// When we're rendering dynamically in dev we need to advance out of the
// Prerender environment when we read Request data synchronously
const requestStore = workUnitStore
trackSynchronousRequestDataAccessInDev(requestStore)
if (workUnitStore) {
switch (workUnitStore.type) {
case 'request':
if (workUnitStore.prerenderPhase === true) {
// When we're rendering dynamically in dev, we need to advance out of
// the Prerender environment when we read Request data synchronously.
trackSynchronousRequestDataAccessInDev(workUnitStore)
}
break
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
}
......
......@@ -84,6 +84,7 @@ import { RedirectStatusCode } from '../../../client/components/redirect-status-c
import { INFINITE_CACHE } from '../../../lib/constants'
import { executeRevalidates } from '../../revalidation-utils'
import { trackPendingModules } from '../../app-render/module-loading/track-module-loading.external'
import { InvariantError } from '../../../shared/lib/invariant-error'
export class WrappedNextRouterError {
constructor(
......@@ -601,9 +602,7 @@ export class AppRouteRouteModule extends RouteModule<
// cookie API.
// TODO leaving the gate here b/c it indicates that we might not actually want to do this
// on every `do` call. During prerender there should be no mutableCookies because
if (requestStore.type === 'request') {
appendMutableCookies(headers, requestStore.mutableCookies)
}
appendMutableCookies(headers, requestStore.mutableCookies)
resolvePendingRevalidations()
......@@ -647,10 +646,7 @@ export class AppRouteRouteModule extends RouteModule<
// to merge the modified cookies and the returned response
// here.
const headers = new Headers(res.headers)
if (
requestStore.type === 'request' &&
appendMutableCookies(headers, requestStore.mutableCookies)
) {
if (appendMutableCookies(headers, requestStore.mutableCookies)) {
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
......@@ -1154,18 +1150,6 @@ function trackDynamic(
workUnitStore: undefined | WorkUnitStore,
expression: string
): void {
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" 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 "${expression}" 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`
)
}
}
if (store.dynamicShouldError) {
throw new StaticGenBailoutError(
`Route ${store.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
......@@ -1173,41 +1157,54 @@ function trackDynamic(
}
if (workUnitStore) {
if (workUnitStore.type === 'prerender') {
// dynamicIO Prerender
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request`
)
abortAndThrowOnSynchronousRequestDataAccess(
store.route,
expression,
error,
workUnitStore
)
} else if (workUnitStore.type === 'prerender-ppr') {
// PPR Prerender
postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
} else if (workUnitStore.type === 'prerender-legacy') {
// legacy Prerender
workUnitStore.revalidate = 0
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${store.route} used "${expression}" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" 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 "${expression}" 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`
)
case 'prerender':
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-request`
)
return abortAndThrowOnSynchronousRequestDataAccess(
store.route,
expression,
error,
workUnitStore
)
case 'prerender-client':
throw new InvariantError(
'A client prerender store should not be used for a route handler.'
)
case 'prerender-ppr':
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
case 'prerender-legacy':
workUnitStore.revalidate = 0
throw err
} else if (
process.env.NODE_ENV === 'development' &&
workUnitStore &&
workUnitStore.type === 'request'
) {
workUnitStore.usedDynamic = true
const err = new DynamicServerError(
`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`
)
store.dynamicUsageDescription = expression
store.dynamicUsageStack = err.stack
throw err
case 'request':
if (process.env.NODE_ENV !== 'production') {
// TODO: This is currently not really needed for route handlers, as it
// only controls the ISR status that's shown for pages.
workUnitStore.usedDynamic = true
}
break
default:
workUnitStore satisfies never
}
}
}
......@@ -92,10 +92,22 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
}
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore || workUnitStore.type !== 'cache') {
throw new Error(
'cacheLife() can only be called inside a "use cache" function.'
)
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case undefined:
throw new Error(
'cacheLife() can only be called inside a "use cache" function.'
)
case 'cache':
break
default:
workUnitStore satisfies never
}
if (typeof profile === 'string') {
......
......@@ -9,10 +9,22 @@ export function cacheTag(...tags: string[]): void {
}
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore || workUnitStore.type !== 'cache') {
throw new Error(
'cacheTag() can only be called inside a "use cache" function.'
)
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case undefined:
throw new Error(
'cacheTag() can only be called inside a "use cache" function.'
)
case 'cache':
break
default:
workUnitStore satisfies never
}
const validTags = validateTags(tags, 'cacheTag()')
......
......@@ -93,15 +93,6 @@ function revalidate(tags: string[], expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
if (workUnitStore.type === 'cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
} else if (workUnitStore.type === 'unstable-cache') {
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
}
if (workUnitStore.phase === 'render') {
throw new Error(
`Route ${store.route} used "${expression}" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
......@@ -109,32 +100,35 @@ function revalidate(tags: string[], expression: string) {
}
switch (workUnitStore.type) {
case 'cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
case 'unstable-cache':
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
case 'prerender':
// dynamicIO Prerender
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`.`
)
abortAndThrowOnSynchronousRequestDataAccess(
return abortAndThrowOnSynchronousRequestDataAccess(
store.route,
expression,
error,
workUnitStore
)
break
case 'prerender-client':
throw new InvariantError(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`
)
case 'prerender-ppr':
// PPR Prerender
postponeWithTracking(
return postponeWithTracking(
store.route,
expression,
workUnitStore.dynamicTracking
)
break
case 'prerender-legacy':
// legacy Prerender
workUnitStore.revalidate = 0
const err = new DynamicServerError(
......@@ -145,12 +139,15 @@ function revalidate(tags: string[], expression: string) {
throw err
case 'request':
if (process.env.NODE_ENV === 'development') {
if (process.env.NODE_ENV !== 'production') {
// TODO: This is most likely incorrect. It would lead to the ISR
// status being flipped when revalidating a static page with a server
// action.
workUnitStore.usedDynamic = true
}
break
default:
// fallthrough
workUnitStore satisfies never
}
}
......
......@@ -2,8 +2,12 @@ import type { IncrementalCache } from '../../lib/incremental-cache'
import { CACHE_ONE_YEAR } from '../../../lib/constants'
import { validateRevalidate, validateTags } from '../../lib/patch-fetch'
import { workAsyncStorage } from '../../app-render/work-async-storage.external'
import {
workAsyncStorage,
type WorkStore,
} from '../../app-render/work-async-storage.external'
import {
getCacheSignal,
getDraftModeProviderForCacheScope,
workUnitAsyncStorage,
} from '../../app-render/work-unit-async-storage.external'
......@@ -12,7 +16,10 @@ import {
IncrementalCacheKind,
type CachedFetchData,
} from '../../response-cache'
import type { UnstableCacheStore } from '../../app-render/work-unit-async-storage.external'
import type {
UnstableCacheStore,
WorkUnitStore,
} from '../../app-render/work-unit-async-storage.external'
type Callback = (...args: any[]) => Promise<any>
......@@ -106,31 +113,19 @@ export function unstable_cache<T extends Callback>(
}
const incrementalCache = maybeIncrementalCache
const cacheSignal =
workUnitStore && workUnitStore.type === 'prerender'
? workUnitStore.cacheSignal
: null
const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null
if (cacheSignal) {
cacheSignal.beginRead()
}
try {
// If there's no request store, we aren't in a request (or we're not in app
// router) and if there's no static generation store, we aren't in app
// If there's no request store, we aren't in a request (or we're not in
// app router) and if there's no static generation store, we aren't in app
// router. Default to an empty pathname and search params when there's no
// request store or static generation store available.
const requestStore =
workUnitStore && workUnitStore.type === 'request'
? workUnitStore
: undefined
const pathname = requestStore?.url.pathname ?? workStore?.route ?? ''
const searchParams = new URLSearchParams(requestStore?.url.search ?? '')
const sortedSearchKeys = [...searchParams.keys()].sort((a, b) => {
return a.localeCompare(b)
})
const sortedSearch = sortedSearchKeys
.map((key) => `${key}=${searchParams.get(key)}`)
.join('&')
const fetchUrlPrefix =
workStore && workUnitStore
? getFetchUrlPrefix(workStore, workUnitStore)
: ''
// Construct the complete cache key for this function invocation
// @TODO stringify is likely not safe here. We will coerce undefined to null which will make
......@@ -138,7 +133,7 @@ export function unstable_cache<T extends Callback>(
const invocationKey = `${fixedKey}-${JSON.stringify(args)}`
const cacheKey = await incrementalCache.generateCacheKey(invocationKey)
// $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse
const fetchUrl = `unstable_cache ${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch} ${cb.name ? ` ${cb.name}` : cacheKey}`
const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`
const fetchIdx =
(workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1
......@@ -161,40 +156,49 @@ export function unstable_cache<T extends Callback>(
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
// the background. If the entry is missing or invalid we generate a new entry and return it.
// We update the store's revalidate property if the option.revalidate is a higher precedence
if (
workUnitStore &&
(workUnitStore.type === 'cache' ||
workUnitStore.type === 'prerender' ||
workUnitStore.type === 'prerender-ppr' ||
workUnitStore.type === 'prerender-legacy')
) {
// options.revalidate === undefined doesn't affect timing.
// options.revalidate === false doesn't shrink timing. it stays at the maximum.
if (typeof options.revalidate === 'number') {
if (workUnitStore.revalidate < options.revalidate) {
// The store is already revalidating on a shorter time interval, leave it alone
} else {
workUnitStore.revalidate = options.revalidate
}
}
let isNestedUnstableCache = false
if (workUnitStore) {
switch (workUnitStore.type) {
case 'cache':
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
// We update the store's revalidate property if the option.revalidate is a higher precedence
// options.revalidate === undefined doesn't affect timing.
// options.revalidate === false doesn't shrink timing. it stays at the maximum.
if (typeof options.revalidate === 'number') {
if (workUnitStore.revalidate < options.revalidate) {
// The store is already revalidating on a shorter time interval, leave it alone
} else {
workUnitStore.revalidate = options.revalidate
}
}
// We need to accumulate the tags for this invocation within the store
const collectedTags = workUnitStore.tags
if (collectedTags === null) {
workUnitStore.tags = tags.slice()
} else {
for (const tag of tags) {
// @TODO refactor tags to be a set to avoid this O(n) lookup
if (!collectedTags.includes(tag)) {
collectedTags.push(tag)
// We need to accumulate the tags for this invocation within the store
const collectedTags = workUnitStore.tags
if (collectedTags === null) {
workUnitStore.tags = tags.slice()
} else {
for (const tag of tags) {
// @TODO refactor tags to be a set to avoid this O(n) lookup
if (!collectedTags.includes(tag)) {
collectedTags.push(tag)
}
}
}
}
break
case 'unstable-cache':
isNestedUnstableCache = true
break
case 'prerender-client':
case 'request':
break
default:
workUnitStore satisfies never
}
}
const isNestedUnstableCache =
workUnitStore && workUnitStore.type === 'unstable-cache'
if (
// when we are nested inside of other unstable_cache's
// we should bypass cache similar to fetches
......@@ -361,3 +365,30 @@ export function unstable_cache<T extends Callback>(
// TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary
return cachedCb as unknown as T
}
function getFetchUrlPrefix(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): string {
switch (workUnitStore.type) {
case 'request':
const pathname = workUnitStore.url.pathname
const searchParams = new URLSearchParams(workUnitStore.url.search)
const sortedSearch = [...searchParams.keys()]
.sort((a, b) => a.localeCompare(b))
.map((key) => `${key}=${searchParams.get(key)}`)
.join('&')
return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'unstable-cache':
return workStore.route
default:
return workUnitStore satisfies never
}
}
......@@ -36,8 +36,14 @@ export function unstable_noStore() {
case 'prerender-client':
// unstable_noStore() is a noop in Dynamic I/O.
return
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'unstable-cache':
break
default:
// fallthrough
workUnitStore satisfies never
}
}
markCurrentScopeAsDynamic(store, workUnitStore, callingExpression)
......
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