Unverified Commit ea3cad28 authored by Josh Story's avatar Josh Story Committed by GitHub

Only error for sync IO after runtime in segments that would be runtime prefetched (#89979)

Stacked on #89984

When we initially implemented runtime prefetching we decided to make
sync IO that happens after runtime but before async IO an error. This is
similar to but more aggressive than the error for sync IO before runtime
data but is important because if you have sync IO before uncached IO and
we are runtime prefetching the page then we aren't going to get anything
useful from that prefetch but it might be very expensive.

The problem with the current implementation is that if you turn on
runtime prefetching for a Page segment then in practice the router will
only ever runtime prefetch that page segment but the sync IO validator
will error for sync IO before uncached IO anywhere in the route. This
makes adding runtime prefetching to leaf Segments much harder b/c you
have to address sync IO in the entire Segment stack.

This change updates the sync IO heuristic to only error in segments that
would be runtime prefetched and below. This way when you add runtime
prefetching to a segment you only have to true up the sync IO for the
part of the tree that has the changed behavior.

This PR only partially implements the intended semantics for runtime
prefetching validation of sync IO. One thing that will need to be done
in a follow up is handling sync IO in generateMetadata. In this case
while the functions are defined in layouts and pages they are
semantically always "owned" by the page itself. This means that while
the layout might not be runtime prefetchable and thus allow sync IO
after runtime data access the generateMetadata in that same layout might
not allow sync IO after runtime if there is a runtime prefetch config at
the page level or some layout higher. This will be done in a follow up
parent da445e89
......@@ -41,13 +41,17 @@ import {
getConventionPathByType,
isNextjsBuiltinFilePath,
} from './segment-explorer-path'
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import { RenderStage, type StagedRenderingController } from './staged-rendering'
/**
* Use the provided loader tree to create the React Component tree.
*/
// TODO convert these arguments to non-object form. the entrypoint doesn't need most of them
export function createComponentTree(props: {
loaderTree: LoaderTree
parentParams: Params
parentRuntimePrefetchable: false
rootLayoutIncluded: boolean
injectedCSS: Set<string>
injectedJS: Set<string>
......@@ -83,6 +87,7 @@ async function createComponentTreeInternal(
{
loaderTree: tree,
parentParams,
parentRuntimePrefetchable,
rootLayoutIncluded,
injectedCSS,
injectedJS,
......@@ -95,6 +100,7 @@ async function createComponentTreeInternal(
}: {
loaderTree: LoaderTree
parentParams: Params
parentRuntimePrefetchable: boolean
rootLayoutIncluded: boolean
injectedCSS: Set<string>
injectedJS: Set<string>
......@@ -224,6 +230,15 @@ async function createComponentTreeInternal(
})
: []
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
const hasRuntimePrefetch =
instantConfig && typeof instantConfig === 'object'
? instantConfig.prefetch === 'runtime'
: false
const isRuntimePrefetchable = hasRuntimePrefetch || parentRuntimePrefetchable
const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden
? await createComponentStylesAndScripts({
......@@ -526,6 +541,7 @@ async function createComponentTreeInternal(
{
loaderTree: parallelRoute,
parentParams: currentParams,
parentRuntimePrefetchable: isRuntimePrefetchable,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
......@@ -685,6 +701,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
isRuntimePrefetchable,
// No user-provided component, so no params will be accessed. Use the
// pre-resolved empty tracker.
emptyVaryParamsAccumulator
......@@ -724,6 +742,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
true,
isRuntimePrefetchable,
// force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty.
emptyVaryParamsAccumulator
......@@ -790,7 +810,8 @@ async function createComponentTreeInternal(
const params = createServerParamsForServerSegment(
currentParams,
workStore,
varyParamsAccumulator
varyParamsAccumulator,
isRuntimePrefetchable
)
// If we are passing searchParams to a server component Page we need to
......@@ -799,7 +820,8 @@ async function createComponentTreeInternal(
let searchParams = createServerSearchParamsForServerPage(
query,
workStore,
varyParamsAccumulator
varyParamsAccumulator,
isRuntimePrefetchable
)
if (isUseCacheFunction(PageComponent)) {
......@@ -851,6 +873,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
isRuntimePrefetchable,
varyParamsAccumulator
)
} else {
......@@ -970,7 +994,8 @@ async function createComponentTreeInternal(
const params = createServerParamsForServerSegment(
currentParams,
workStore,
varyParamsAccumulator
varyParamsAccumulator,
isRuntimePrefetchable
)
let serverSegment: React.ReactNode
......@@ -1065,6 +1090,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
isRuntimePrefetchable,
varyParamsAccumulator
)
}
......@@ -1216,8 +1243,46 @@ function createSeedData(
parallelRoutes: Record<string, CacheNodeSeedData | null>,
loading: LoadingModuleData | null,
isPossiblyPartialResponse: boolean,
isRuntimePrefetchable: boolean,
varyParamsAccumulator: VaryParamsAccumulator | null
): CacheNodeSeedData {
const createElement = ctx.componentMod.createElement
// When this segment is NOT runtime-prefetchable, delay it until the Static
// stage by wrapping the node in a promise. This allows runtime-prefetchable
// segments (the lower tree) to render first during EarlyStatic, so their
// runtime data resolves in EarlyRuntime where sync IO can be checked.
// React will suspend on the thenable and resume when the stage advances.
if (!isRuntimePrefetchable) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
let stagedRendering: StagedRenderingController | null | undefined
switch (workUnitStore.type) {
case 'request':
case 'prerender-runtime':
stagedRendering = workUnitStore.stagedRendering
if (stagedRendering) {
const deferredRsc = rsc
rsc = stagedRendering
.waitForStage(RenderStage.Static)
.then(() => deferredRsc)
}
break
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
}
if (loading !== null) {
// If a loading.tsx boundary is present, wrap the component data in an
// additional context provider to pass the loading data to the next
......@@ -1225,7 +1290,6 @@ function createSeedData(
// NOTE: The reason this is a separate wrapper from LayoutRouter is because
// not all segments render a LayoutRouter component, e.g. the root segment.
const LoadingBoundaryProvider = ctx.componentMod.LoadingBoundaryProvider
const createElement = ctx.componentMod.createElement
rsc = createElement(LoadingBoundaryProvider, {
loading: loading,
children: rsc,
......
......@@ -25,7 +25,6 @@ import type {
WorkUnitStore,
PrerenderStoreLegacy,
PrerenderStoreModern,
PrerenderStoreModernRuntime,
ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external'
......@@ -38,9 +37,8 @@ import {
throwForMissingRequestStore,
workUnitAsyncStorage,
} from './work-unit-async-storage.external'
import { RenderStage } from './staged-rendering'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { makeHangingPromise, getRuntimeStage } from '../dynamic-rendering-utils'
import {
METADATA_BOUNDARY_NAME,
VIEWPORT_BOUNDARY_NAME,
......@@ -547,8 +545,9 @@ export function createHangingInputAbortSignal(
workUnitStore.type === 'prerender-runtime' &&
workUnitStore.stagedRendering
) {
workUnitStore.stagedRendering
.waitForStage(RenderStage.Runtime)
const { stagedRendering } = workUnitStore
stagedRendering
.waitForStage(getRuntimeStage(stagedRendering))
.then(() => scheduleOnNextTick(() => controller.abort()))
} else {
scheduleOnNextTick(() => controller.abort())
......@@ -1259,15 +1258,3 @@ export function getNavigationDisallowedDynamicReasons(
// We had a non-empty prelude and there are no dynamic holes
return []
}
export function delayUntilRuntimeStage<T>(
prerenderStore: PrerenderStoreModernRuntime,
result: Promise<T>
): Promise<T> {
if (prerenderStore.stagedRendering) {
return prerenderStore.stagedRendering
.waitForStage(RenderStage.Runtime)
.then(() => result)
}
return result
}
......@@ -3,31 +3,39 @@ import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolv
export enum RenderStage {
Before = 1,
Static = 2,
Runtime = 3,
Dynamic = 4,
Abandoned = 5,
EarlyStatic = 2,
Static = 3,
EarlyRuntime = 4,
Runtime = 5,
Dynamic = 6,
Abandoned = 7,
}
export type NonStaticRenderStage = RenderStage.Runtime | RenderStage.Dynamic
export type AdvanceableRenderStage =
| RenderStage.Static
| RenderStage.EarlyRuntime
| RenderStage.Runtime
| RenderStage.Dynamic
export class StagedRenderingController {
currentStage: RenderStage = RenderStage.Before
staticInterruptReason: Error | null = null
runtimeInterruptReason: Error | null = null
syncInterruptReason: Error | null = null
staticStageEndTime: number = Infinity
runtimeStageEndTime: number = Infinity
private staticStageListeners: Array<() => void> = []
private earlyRuntimeStageListeners: Array<() => void> = []
private runtimeStageListeners: Array<() => void> = []
private dynamicStageListeners: Array<() => void> = []
private staticStagePromise = createPromiseWithResolvers<void>()
private earlyRuntimeStagePromise = createPromiseWithResolvers<void>()
private runtimeStagePromise = createPromiseWithResolvers<void>()
private dynamicStagePromise = createPromiseWithResolvers<void>()
constructor(
private abortSignal: AbortSignal | null = null,
private hasRuntimePrefetch: boolean,
private abandonController: AbortController | null = null
) {
if (abortSignal) {
......@@ -39,6 +47,10 @@ export class StagedRenderingController {
// is a no-op. The ignoreReject handler suppresses unhandled
// rejection warnings for promises that no one is awaiting.
const { reason } = abortSignal
this.staticStagePromise.promise.catch(ignoreReject)
this.staticStagePromise.reject(reason)
this.earlyRuntimeStagePromise.promise.catch(ignoreReject)
this.earlyRuntimeStagePromise.reject(reason)
this.runtimeStagePromise.promise.catch(ignoreReject)
this.runtimeStagePromise.reject(reason)
this.dynamicStagePromise.promise.catch(ignoreReject)
......@@ -59,9 +71,13 @@ export class StagedRenderingController {
}
}
onStage(stage: NonStaticRenderStage, callback: () => void) {
onStage(stage: AdvanceableRenderStage, callback: () => void) {
if (this.currentStage >= stage) {
callback()
} else if (stage === RenderStage.Static) {
this.staticStageListeners.push(callback)
} else if (stage === RenderStage.EarlyRuntime) {
this.earlyRuntimeStageListeners.push(callback)
} else if (stage === RenderStage.Runtime) {
this.runtimeStageListeners.push(callback)
} else if (stage === RenderStage.Dynamic) {
......@@ -78,10 +94,24 @@ export class StagedRenderingController {
return false
}
const boundaryStage = this.hasRuntimePrefetch
? RenderStage.Dynamic
: RenderStage.Runtime
return this.currentStage < boundaryStage
switch (this.currentStage) {
case RenderStage.EarlyStatic:
case RenderStage.Static:
return true
case RenderStage.EarlyRuntime:
// EarlyRuntime is for runtime-prefetchable segments. Sync IO
// should error because it would abort a runtime prefetch.
return true
case RenderStage.Runtime:
// Runtime is for non-prefetchable segments. Sync IO is fine there
// because in practice this segment will never be runtime prefetched
return false
case RenderStage.Dynamic:
case RenderStage.Abandoned:
return false
default:
return false
}
}
syncInterruptCurrentStageWithReason(reason: Error) {
......@@ -105,22 +135,18 @@ export class StagedRenderingController {
// If we're in the final render, we cannot abandon it. We need to advance to the Dynamic stage
// and capture the interruption reason.
switch (this.currentStage) {
case RenderStage.Static: {
this.staticInterruptReason = reason
case RenderStage.EarlyStatic:
case RenderStage.Static:
case RenderStage.EarlyRuntime: {
// EarlyRuntime is for runtime-prefetchable segments. Sync IO here
// means the prefetch would be aborted too early.
this.syncInterruptReason = reason
this.advanceStage(RenderStage.Dynamic)
return
}
case RenderStage.Runtime: {
// We only error for Sync IO in the runtime stage if the route
// is configured to use runtime prefetching.
// We do this to reflect the fact that during a runtime prefetch,
// Sync IO aborts aborts the render.
// Note that `canSyncInterrupt` should prevent us from getting here at all
// if runtime prefetching isn't enabled.
if (this.hasRuntimePrefetch) {
this.runtimeInterruptReason = reason
this.advanceStage(RenderStage.Dynamic)
}
// canSyncInterrupt returns false for Runtime, so we should
// never get here. Defensive no-op.
return
}
case RenderStage.Dynamic:
......@@ -128,12 +154,8 @@ export class StagedRenderingController {
}
}
getStaticInterruptReason() {
return this.staticInterruptReason
}
getRuntimeInterruptReason() {
return this.runtimeInterruptReason
getSyncInterruptReason() {
return this.syncInterruptReason
}
getStaticStageEndTime() {
......@@ -152,15 +174,22 @@ export class StagedRenderingController {
// (this might be a lazy intitialization of a module,
// so we still want to restart in this case and see if it still occurs)
// In either case, we'll be doing another render after this one,
// so we only want to unblock the Runtime stage, not Dynamic, because
// so we only want to unblock the next stage, not Dynamic, because
// unblocking the dynamic stage would likely lead to wasted (uncached) IO.
const { currentStage } = this
switch (currentStage) {
case RenderStage.EarlyStatic: {
this.resolveStaticStage()
}
// intentional fallthrough
case RenderStage.Static: {
this.currentStage = RenderStage.Abandoned
this.resolveEarlyRuntimeStage()
}
// intentional fallthrough
case RenderStage.EarlyRuntime: {
this.resolveRuntimeStage()
return
}
// intentional fallthrough
case RenderStage.Runtime: {
this.currentStage = RenderStage.Abandoned
return
......@@ -176,7 +205,12 @@ export class StagedRenderingController {
}
advanceStage(
stage: RenderStage.Static | RenderStage.Runtime | RenderStage.Dynamic
stage:
| RenderStage.EarlyStatic
| RenderStage.Static
| RenderStage.EarlyRuntime
| RenderStage.Runtime
| RenderStage.Dynamic
) {
// If we're already at the target stage or beyond, do nothing.
// (this can happen e.g. if sync IO advanced us to the dynamic stage)
......@@ -187,6 +221,15 @@ export class StagedRenderingController {
let currentStage = this.currentStage
this.currentStage = stage
if (currentStage < RenderStage.Static && stage >= RenderStage.Static) {
this.resolveStaticStage()
}
if (
currentStage < RenderStage.EarlyRuntime &&
stage >= RenderStage.EarlyRuntime
) {
this.resolveEarlyRuntimeStage()
}
if (currentStage < RenderStage.Runtime && stage >= RenderStage.Runtime) {
this.staticStageEndTime = performance.now() + performance.timeOrigin
this.resolveRuntimeStage()
......@@ -198,6 +241,26 @@ export class StagedRenderingController {
}
}
/** Fire the `onStage` listeners for the static stage and unblock any promises waiting for it. */
private resolveStaticStage() {
const staticListeners = this.staticStageListeners
for (let i = 0; i < staticListeners.length; i++) {
staticListeners[i]()
}
staticListeners.length = 0
this.staticStagePromise.resolve()
}
/** Fire the `onStage` listeners for the early runtime stage and unblock any promises waiting for it. */
private resolveEarlyRuntimeStage() {
const earlyRuntimeListeners = this.earlyRuntimeStageListeners
for (let i = 0; i < earlyRuntimeListeners.length; i++) {
earlyRuntimeListeners[i]()
}
earlyRuntimeListeners.length = 0
this.earlyRuntimeStagePromise.resolve()
}
/** Fire the `onStage` listeners for the runtime stage and unblock any promises waiting for it. */
private resolveRuntimeStage() {
const runtimeListeners = this.runtimeStageListeners
......@@ -218,8 +281,14 @@ export class StagedRenderingController {
this.dynamicStagePromise.resolve()
}
private getStagePromise(stage: NonStaticRenderStage): Promise<void> {
private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {
switch (stage) {
case RenderStage.Static: {
return this.staticStagePromise.promise
}
case RenderStage.EarlyRuntime: {
return this.earlyRuntimeStagePromise.promise
}
case RenderStage.Runtime: {
return this.runtimeStagePromise.promise
}
......@@ -233,12 +302,12 @@ export class StagedRenderingController {
}
}
waitForStage(stage: NonStaticRenderStage) {
waitForStage(stage: AdvanceableRenderStage) {
return this.getStagePromise(stage)
}
delayUntilStage<T>(
stage: NonStaticRenderStage,
stage: AdvanceableRenderStage,
displayName: string | undefined,
resolvedValue: T
) {
......
......@@ -225,6 +225,7 @@ export async function walkTreeWithFlightRouterState({
ctx,
loaderTree: loaderTreeToFilter,
parentParams: currentParams,
parentRuntimePrefetchable: false,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
......@@ -342,6 +343,7 @@ export async function createFullTreeFlightDataForNavigation({
ctx,
loaderTree,
parentParams: {},
parentRuntimePrefetchable: false,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
......
......@@ -21,6 +21,7 @@ import type { WorkStore } from './work-async-storage.external'
import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../client/components/app-router-headers'
import { InvariantError } from '../../shared/lib/invariant-error'
import type { StagedRenderingController } from './staged-rendering'
import { RenderStage } from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
export type WorkUnitPhase = 'action' | 'render' | 'after'
......@@ -79,15 +80,42 @@ export interface RequestStore extends CommonWorkUnitStore {
type DevAsyncApiPromises = {
cookies: Promise<ReadonlyRequestCookies>
earlyCookies: Promise<ReadonlyRequestCookies>
mutableCookies: Promise<ReadonlyRequestCookies>
earlyMutableCookies: Promise<ReadonlyRequestCookies>
headers: Promise<ReadonlyHeaders>
earlyHeaders: Promise<ReadonlyHeaders>
sharedParamsParent: Promise<string>
earlySharedParamsParent: Promise<string>
sharedSearchParamsParent: Promise<string>
earlySharedSearchParamsParent: Promise<string>
// Connection is not a runtime promise and doesn't
// need to distinguish between early and late
connection: Promise<undefined>
}
/**
* Returns true if the current render stage is an early stage (EarlyStatic or
* EarlyRuntime). The early stages are for runtime-prefetchable segments. When
* true, runtime APIs should use the early promise variant that resolves at
* EarlyRuntime rather than Runtime.
*/
export function isInEarlyRenderStage(requestStore: RequestStore): boolean {
const stagedRendering = requestStore.stagedRendering
if (stagedRendering) {
return (
stagedRendering.currentStage === RenderStage.EarlyStatic ||
stagedRendering.currentStage === RenderStage.EarlyRuntime
)
}
return false
}
/**
* The Prerender store is for tracking information related to prerenders.
*
......
import type { NonStaticRenderStage } from './app-render/staged-rendering'
import type { RequestStore } from './app-render/work-unit-async-storage.external'
import {
RenderStage,
type AdvanceableRenderStage,
type StagedRenderingController,
} from './app-render/staged-rendering'
import type {
PrerenderStoreModernRuntime,
RequestStore,
} from './app-render/work-unit-async-storage.external'
export function isHangingPromiseRejectionError(
err: unknown
......@@ -79,7 +86,7 @@ function ignoreReject() {}
export function makeDevtoolsIOAwarePromise<T>(
underlying: T,
requestStore: RequestStore,
stage: NonStaticRenderStage
stage: AdvanceableRenderStage
): Promise<T> {
if (requestStore.stagedRendering) {
// We resolve each stage in a timeout, so React DevTools will pick this up as IO.
......@@ -98,3 +105,46 @@ export function makeDevtoolsIOAwarePromise<T>(
}, 0)
})
}
/**
* Returns the appropriate runtime stage for the current point in the render.
* Runtime-prefetchable segments render in the early stages and should wait
* for EarlyRuntime. Non-prefetchable segments render in the later stages
* and should wait for Runtime.
*/
export function getRuntimeStage(
stagedRendering: StagedRenderingController
): RenderStage.EarlyRuntime | RenderStage.Runtime {
if (
stagedRendering.currentStage === RenderStage.EarlyStatic ||
stagedRendering.currentStage === RenderStage.EarlyRuntime
) {
return RenderStage.EarlyRuntime
}
return RenderStage.Runtime
}
/**
* Delays until the appropriate runtime stage based on the current stage of
* the rendering pipeline:
*
* - Early stages → wait for EarlyRuntime
* (for runtime-prefetchable segments)
* - Later stages → wait for Runtime
* (for segments not using runtime prefetch)
*
* This ensures that cookies()/headers()/etc. resolve at the right time for
* each segment type.
*/
export function delayUntilRuntimeStage<T>(
prerenderStore: PrerenderStoreModernRuntime,
result: Promise<T>
): Promise<T> {
const { stagedRendering } = prerenderStore
if (!stagedRendering) {
return result
}
return stagedRendering
.waitForStage(getRuntimeStage(stagedRendering))
.then(() => result)
}
......@@ -87,7 +87,10 @@ export function io(expression: string, type: ApiType) {
const stageController = workUnitStore.stagedRendering
if (stageController && stageController.canSyncInterrupt()) {
let message: string
if (stageController.currentStage === RenderStage.Static) {
if (
stageController.currentStage === RenderStage.Static ||
stageController.currentStage === RenderStage.EarlyStatic
) {
switch (type) {
case 'time':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time`
......
......@@ -13,15 +13,16 @@ import {
workUnitAsyncStorage,
type PrerenderStoreModern,
type RequestStore,
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external'
import {
delayUntilRuntimeStage,
postponeWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
delayUntilRuntimeStage,
makeDevtoolsIOAwarePromise,
makeHangingPromise,
} from '../dynamic-rendering-utils'
......@@ -191,11 +192,16 @@ function makeUntrackedCookiesWithDevWarnings(
route?: string
): Promise<ReadonlyRequestCookies> {
if (requestStore.asyncApiPromises) {
const early = isInEarlyRenderStage(requestStore)
let promise: Promise<ReadonlyRequestCookies>
if (underlyingCookies === requestStore.mutableCookies) {
promise = requestStore.asyncApiPromises.mutableCookies
promise = early
? requestStore.asyncApiPromises.earlyMutableCookies
: requestStore.asyncApiPromises.mutableCookies
} else if (underlyingCookies === requestStore.cookies) {
promise = requestStore.asyncApiPromises.cookies
promise = early
? requestStore.asyncApiPromises.earlyCookies
: requestStore.asyncApiPromises.cookies
} else {
throw new InvariantError(
'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'
......
......@@ -12,7 +12,6 @@ import {
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import {
abortAndThrowOnSynchronousRequestDataAccess,
delayUntilRuntimeStage,
postponeWithTracking,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
......@@ -20,6 +19,7 @@ import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-b
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { DynamicServerError } from '../../client/components/hooks-server-context'
import { InvariantError } from '../../shared/lib/invariant-error'
import { delayUntilRuntimeStage } from '../dynamic-rendering-utils'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
export function draftMode(): Promise<DraftMode> {
......
......@@ -11,15 +11,16 @@ import {
workUnitAsyncStorage,
type PrerenderStoreModern,
type RequestStore,
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external'
import {
delayUntilRuntimeStage,
postponeWithTracking,
throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
delayUntilRuntimeStage,
makeDevtoolsIOAwarePromise,
makeHangingPromise,
} from '../dynamic-rendering-utils'
......@@ -201,7 +202,9 @@ function makeUntrackedHeadersWithDevWarnings(
requestStore: RequestStore
): Promise<ReadonlyHeaders> {
if (requestStore.asyncApiPromises) {
const promise = requestStore.asyncApiPromises.headers
const promise = isInEarlyRenderStage(requestStore)
? requestStore.asyncApiPromises.earlyHeaders
: requestStore.asyncApiPromises.headers
return instrumentHeadersPromiseWithDevWarnings(promise, route)
}
......
......@@ -13,7 +13,6 @@ import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import {
throwToInterruptStaticGeneration,
postponeWithTracking,
delayUntilRuntimeStage,
} from '../app-render/dynamic-rendering'
import {
......@@ -82,11 +81,14 @@ export function createParamsFromClient(
// but since you would never use next dev with production NODE_ENV we use this
// as a proxy so we can statically exclude this code from production builds.
const devFallbackParams = workUnitStore.devFallbackParams
// Client params are not runtime prefetchable
const isRuntimePrefetchable = false
return createRenderParamsInDev(
underlyingParams,
devFallbackParams,
workStore,
workUnitStore
workUnitStore,
isRuntimePrefetchable
)
} else {
return createRenderParamsInProd(underlyingParams)
......@@ -99,6 +101,8 @@ export function createParamsFromClient(
}
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
// TODO: metadata should inherit the runtime prefetchability of the page segment
const metadataIsRuntimePrefetchable = false
export type CreateServerParamsForMetadata = typeof createServerParamsForMetadata
export function createServerParamsForMetadata(
underlyingParams: Params,
......@@ -108,7 +112,8 @@ export function createServerParamsForMetadata(
return createServerParamsForServerSegment(
underlyingParams,
workStore,
metadataVaryParamsAccumulator
metadataVaryParamsAccumulator,
metadataIsRuntimePrefetchable
)
}
......@@ -141,23 +146,30 @@ export function createServerParamsForRoute(
throw new InvariantError(
'createServerParamsForRoute should not be called in cache contexts.'
)
case 'prerender-runtime':
case 'prerender-runtime': {
// Route params are not runtime prefetchable
const isRuntimePrefetchable = false
return createRuntimePrerenderParams(
underlyingParams,
workUnitStore,
varyParamsAccumulator
varyParamsAccumulator,
isRuntimePrefetchable
)
}
case 'request':
if (process.env.NODE_ENV === 'development') {
// Semantically we only need the dev tracking when running in `next dev`
// but since you would never use next dev with production NODE_ENV we use this
// as a proxy so we can statically exclude this code from production builds.
const devFallbackParams = workUnitStore.devFallbackParams
// Route params are not runtime prefetchable
const isRuntimePrefetchable = false
return createRenderParamsInDev(
underlyingParams,
devFallbackParams,
workStore,
workUnitStore
workUnitStore,
isRuntimePrefetchable
)
} else {
return createRenderParamsInProd(underlyingParams)
......@@ -172,7 +184,8 @@ export function createServerParamsForRoute(
export function createServerParamsForServerSegment(
underlyingParams: Params,
workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<Params> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
......@@ -200,7 +213,8 @@ export function createServerParamsForServerSegment(
return createRuntimePrerenderParams(
underlyingParams,
workUnitStore,
varyParamsAccumulator
varyParamsAccumulator,
isRuntimePrefetchable
)
case 'request':
if (process.env.NODE_ENV === 'development') {
......@@ -212,7 +226,8 @@ export function createServerParamsForServerSegment(
underlyingParams,
devFallbackParams,
workStore,
workUnitStore
workUnitStore,
isRuntimePrefetchable
)
} else {
return createRenderParamsInProd(underlyingParams)
......@@ -340,17 +355,23 @@ function createStaticPrerenderParams(
function createRuntimePrerenderParams(
underlyingParams: Params,
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<Params> {
const underlyingParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingParams(varyParamsAccumulator, underlyingParams)
: underlyingParams
return delayUntilRuntimeStage(
workUnitStore,
makeUntrackedParams(underlyingParamsWithVarying)
)
const result = makeUntrackedParams(underlyingParamsWithVarying)
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
return result
}
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime
: RenderStage.Runtime
return stagedRendering.waitForStage(stage).then(() => result)
}
function createRenderParamsInProd(underlyingParams: Params): Promise<Params> {
......@@ -361,7 +382,8 @@ function createRenderParamsInDev(
underlyingParams: Params,
devFallbackParams: OpaqueFallbackRouteParams | null | undefined,
workStore: WorkStore,
requestStore: RequestStore
requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<Params> {
let hasFallbackParams = false
if (devFallbackParams) {
......@@ -377,7 +399,8 @@ function createRenderParamsInDev(
underlyingParams,
hasFallbackParams,
workStore,
requestStore
requestStore,
isRuntimePrefetchable
)
}
......@@ -510,7 +533,8 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
underlyingParams: Params,
hasFallbackParams: boolean,
workStore: WorkStore,
requestStore: RequestStore
requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<Params> {
if (requestStore.asyncApiPromises && hasFallbackParams) {
// We wrap each instance of params in a `new Promise()`, because deduping
......@@ -518,7 +542,9 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
// await a different set of values. This is important when all awaits
// are in third party which would otherwise track all the way to the
// internal params.
const sharedParamsParent = requestStore.asyncApiPromises.sharedParamsParent
const sharedParamsParent = isRuntimePrefetchable
? requestStore.asyncApiPromises.earlySharedParamsParent
: requestStore.asyncApiPromises.sharedParamsParent
const promise: Promise<Params> = new Promise((resolve, reject) => {
sharedParamsParent.then(() => resolve(underlyingParams), reject)
})
......
import type { WorkStore } from '../app-render/work-async-storage.external'
import {
delayUntilRuntimeStage,
postponeWithTracking,
type DynamicTrackingState,
} from '../app-render/dynamic-rendering'
......@@ -13,7 +12,10 @@ import {
type PrerenderStoreModernServer,
type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import {
delayUntilRuntimeStage,
makeHangingPromise,
} from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
export function createServerPathnameForMetadata(
......
......@@ -10,7 +10,6 @@ import {
throwToInterruptStaticGeneration,
postponeWithTracking,
annotateDynamicAccess,
delayUntilRuntimeStage,
} from '../app-render/dynamic-rendering'
import {
......@@ -68,10 +67,13 @@ export function createSearchParamsFromClient(
'createSearchParamsFromClient should not be called in cache contexts.'
)
case 'request':
// Client searchParams are not runtime prefetchable
const isRuntimePrefetchable = false
return createRenderSearchParams(
underlyingSearchParams,
workStore,
workUnitStore
workUnitStore,
isRuntimePrefetchable
)
default:
workUnitStore satisfies never
......@@ -81,6 +83,8 @@ export function createSearchParamsFromClient(
}
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component
// TODO: metadata should inherit the runtime prefetchability of the page segment
const metadataIsRuntimePrefetchable = false
export function createServerSearchParamsForMetadata(
underlyingSearchParams: SearchParams,
workStore: WorkStore
......@@ -89,14 +93,16 @@ export function createServerSearchParamsForMetadata(
return createServerSearchParamsForServerPage(
underlyingSearchParams,
workStore,
metadataVaryParamsAccumulator
metadataVaryParamsAccumulator,
metadataIsRuntimePrefetchable
)
}
export function createServerSearchParamsForServerPage(
underlyingSearchParams: SearchParams,
workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<SearchParams> {
const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) {
......@@ -120,13 +126,15 @@ export function createServerSearchParamsForServerPage(
return createRuntimePrerenderSearchParams(
underlyingSearchParams,
workUnitStore,
varyParamsAccumulator
varyParamsAccumulator,
isRuntimePrefetchable
)
case 'request':
return createRenderSearchParams(
underlyingSearchParams,
workStore,
workUnitStore
workUnitStore,
isRuntimePrefetchable
)
default:
workUnitStore satisfies never
......@@ -209,22 +217,30 @@ function createStaticPrerenderSearchParams(
function createRuntimePrerenderSearchParams(
underlyingSearchParams: SearchParams,
workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null
varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<SearchParams> {
const underlyingSearchParamsWithVarying =
varyParamsAccumulator !== null
? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)
: underlyingSearchParams
return delayUntilRuntimeStage(
workUnitStore,
makeUntrackedSearchParams(underlyingSearchParamsWithVarying)
)
const result = makeUntrackedSearchParams(underlyingSearchParamsWithVarying)
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
return result
}
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime
: RenderStage.Runtime
return stagedRendering.waitForStage(stage).then(() => result)
}
function createRenderSearchParams(
underlyingSearchParams: SearchParams,
workStore: WorkStore,
requestStore: RequestStore
requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<SearchParams> {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
......@@ -238,7 +254,8 @@ function createRenderSearchParams(
return makeUntrackedSearchParamsWithDevWarnings(
underlyingSearchParams,
workStore,
requestStore
requestStore,
isRuntimePrefetchable
)
} else {
return makeUntrackedSearchParams(underlyingSearchParams)
......@@ -416,7 +433,8 @@ function makeUntrackedSearchParams(
function makeUntrackedSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams,
workStore: WorkStore,
requestStore: RequestStore
requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<SearchParams> {
if (requestStore.asyncApiPromises) {
// Do not cache the resulting promise. If we do, we'll only show the first "awaited at"
......@@ -424,7 +442,8 @@ function makeUntrackedSearchParamsWithDevWarnings(
return makeUntrackedSearchParamsWithDevWarningsImpl(
underlyingSearchParams,
workStore,
requestStore
requestStore,
isRuntimePrefetchable
)
} else {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
......@@ -434,7 +453,8 @@ function makeUntrackedSearchParamsWithDevWarnings(
const promise = makeUntrackedSearchParamsWithDevWarningsImpl(
underlyingSearchParams,
workStore,
requestStore
requestStore,
isRuntimePrefetchable
)
CachedSearchParams.set(requestStore, promise)
return promise
......@@ -444,7 +464,8 @@ function makeUntrackedSearchParamsWithDevWarnings(
function makeUntrackedSearchParamsWithDevWarningsImpl(
underlyingSearchParams: SearchParams,
workStore: WorkStore,
requestStore: RequestStore
requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<SearchParams> {
const promiseInitialized = { current: false }
const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(
......@@ -458,8 +479,9 @@ function makeUntrackedSearchParamsWithDevWarningsImpl(
// We wrap each instance of searchParams in a `new Promise()`.
// This is important when all awaits are in third party which would otherwise
// track all the way to the internal params.
const sharedSearchParamsParent =
requestStore.asyncApiPromises.sharedSearchParamsParent
const sharedSearchParamsParent = isRuntimePrefetchable
? requestStore.asyncApiPromises.earlySharedSearchParamsParent
: requestStore.asyncApiPromises.sharedSearchParamsParent
promise = new Promise((resolve, reject) => {
sharedSearchParamsParent.then(() => resolve(proxiedUnderlying), reject)
})
......
......@@ -38,6 +38,7 @@ import {
} from '../app-render/work-unit-async-storage.external'
import {
getRuntimeStage,
makeDevtoolsIOAwarePromise,
makeHangingPromise,
} from '../dynamic-rendering-utils'
......@@ -1055,22 +1056,25 @@ export async function cache(
switch (outerWorkUnitStore.type) {
case 'prerender-runtime': {
// In a runtime prerender, we have to make sure that APIs that would hang during a static prerender
// are resolved with a delay, in the runtime stage. Private caches are one of these.
// are resolved with a delay, in the appropriate runtime stage. Private caches read from
// Segments not using runtime prefetch resolve at EarlyRuntime,
// while runtime-prefetchable segments resolve at Runtime.
const stagedRendering = outerWorkUnitStore.stagedRendering
if (stagedRendering) {
await stagedRendering.waitForStage(RenderStage.Runtime)
await stagedRendering.waitForStage(getRuntimeStage(stagedRendering))
}
break
}
case 'request': {
if (process.env.NODE_ENV === 'development') {
// Similar to runtime prerenders, private caches should not resolve in the static stage
// of a dev request, so we delay them.
await makeDevtoolsIOAwarePromise(
undefined,
outerWorkUnitStore,
RenderStage.Runtime
)
// of a dev request, so we delay them. We pick the appropriate runtime stage based on
// whether we're in the early or late stages.
const stagedRendering = outerWorkUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(undefined, outerWorkUnitStore, stage)
}
break
}
......@@ -1366,10 +1370,12 @@ export async function cache(
case 'prerender-runtime': {
// In the final phase of a runtime prerender, we have to make
// sure that APIs that would hang during a static prerender
// are resolved with a delay, in the runtime stage.
// are resolved with a delay, in the appropriate runtime stage.
const stagedRendering = workUnitStore.stagedRendering
if (stagedRendering) {
await stagedRendering.waitForStage(RenderStage.Runtime)
await stagedRendering.waitForStage(
getRuntimeStage(stagedRendering)
)
}
break
}
......@@ -1399,10 +1405,14 @@ export async function cache(
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts.
// We don't end the cache read here, so this will always appear as a cache miss in the static stage,
// and thus will cause a restart even if all caches are filled.
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(
undefined,
workUnitStore,
RenderStage.Runtime
stage
)
}
break
......@@ -1652,11 +1662,11 @@ export async function cache(
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts.
// We don't end the cache read here, so this will always appear as a cache miss in the static stage,
// and thus will cause a restart even if all caches are filled.
await makeDevtoolsIOAwarePromise(
undefined,
workUnitStore,
RenderStage.Runtime
)
const stagedRendering = workUnitStore.stagedRendering
const stage = stagedRendering
? getRuntimeStage(stagedRendering)
: RenderStage.Runtime
await makeDevtoolsIOAwarePromise(undefined, workUnitStore, stage)
}
break
}
......
......@@ -110,8 +110,26 @@ describe('react-performance-track', () => {
})
const track = await browser.eval('window.reactServerRequests.getSnapshot()')
// TODO: Should include "draftMode [Prefetchable]".
expect(track).toEqual([])
// TODO the addition of a promise to delay some Segments from rendering until the later Static
// stage has caused the draftMode snapshot to include an empty-named entry. This is probably
// a bug in React and should be fixed there but
// expect(track).toEqual([])
expect(track).toEqual(
expect.arrayContaining([
{
name: '\u200b [Prerender]',
properties: [],
},
])
)
let didThrow = false
try {
// including this anti-assertion here so we can restore the test when the bug in React is fixed
expect(track).toEqual([])
} catch (e) {
didThrow = true
}
expect(didThrow).toBe(true)
})
it('should show headers', async () => {
......
......@@ -38,6 +38,15 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-blocking-inside-runtime" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-sync-io-in-static-parent" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-in-runtime-with-valid-static-parent" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input" />
</li>
</ul>
<h2>Static</h2>
......
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
// This page HAS runtime prefetch enabled. cookies() is passed as a promise
// input to a public "use cache" function. The cache doesn't read the cookies
// in its body — they're only part of the cache key. After the cache resolves,
// Date.now() is sync IO that should error because we're in a
// runtime-prefetchable segment where cookies() has resolved at EarlyRuntime.
//
// This test validates that the cache input encoding resolves in the correct
// runtime stage (EarlyRuntime for prefetchable segments). If the cache input
// abort signal incorrectly waited for the Runtime stage, the cache would
// resolve later, and Date.now() would happen at the Runtime stage where
// canSyncInterrupt returns false — missing the error.
async function cachedFn(cookiePromise: Promise<string>) {
'use cache'
// Intentionally not reading the cookie promise in the body.
// It's only used as part of the cache key via input encoding.
return 'cached result'
}
export default async function Page() {
const cookiePromise = cookies().then((c) => c.get('testCookie')?.value ?? '')
await cachedFn(cookiePromise)
const now = Date.now()
return (
<main>
<p>Runtime page with sync IO after cache with cookie input: {now}</p>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
// This layout does NOT have runtime prefetch — it's a static segment.
// The sync IO after cookies() is valid here because this segment won't
// be runtime prefetched.
async function RuntimeContent() {
await cookies()
const now = Date.now()
return <p>Static layout with sync IO after cookies: {now}</p>
}
export default function StaticLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
<Suspense fallback={<p>Loading...</p>}>
<RuntimeContent />
</Suspense>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
// This page HAS runtime prefetch enabled. The sync IO (Date.now()) after
// cookies() is invalid here because during a runtime prefetch, cookies()
// resolves and then Date.now() would abort the prerender too early.
export default async function Page() {
await cookies()
const now = Date.now()
return (
<main>
<p>Runtime page with sync IO after cookies: {now}</p>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
// This layout does NOT have runtime prefetch — it's a static segment.
// The RuntimeContent component accesses cookies() then Date.now().
// In a static prefetch the render would never get past cookies() so the
// sync IO is unreachable. In a runtime prefetch, cookies() would resolve
// but this layout is not runtime-prefetchable — only the child page is.
// So the sync IO here should not error.
async function RuntimeContent() {
await cookies()
const now = Date.now()
return <p>Static layout with sync IO after cookies: {now}</p>
}
export default function StaticLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
<Suspense fallback={<p>Loading...</p>}>
<RuntimeContent />
</Suspense>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export const unstable_instant = {
prefetch: 'runtime',
samples: [{}],
}
async function Runtime() {
await cookies()
return <p>Runtime content</p>
}
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Runtime />
</Suspense>
</main>
)
}
......@@ -417,6 +417,71 @@ describe('instant validation', () => {
`)
})
it('invalid - runtime prefetch - sync IO in runtime segment with valid static parent', async () => {
// The static parent layout has sync IO after cookies() which is fine
// because it's not runtime-prefetchable. But the page itself has
// runtime prefetch enabled and also has sync IO after cookies(),
// which should error.
const browser = await navigateTo(
'/suspense-in-root/runtime/invalid-sync-io-in-runtime-with-valid-static-parent'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route "/suspense-in-root/runtime/invalid-sync-io-in-runtime-with-valid-static-parent" used \`Date.now()\` before accessing either uncached data (e.g. \`fetch()\`) or awaiting \`connection()\`. When configured for Runtime prefetching, accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-runtime-current-time",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/runtime/invalid-sync-io-in-runtime-with-valid-static-parent/page.tsx (14:20) @ Page
> 14 | const now = Date.now()
| ^",
"stack": [
"Page app/suspense-in-root/runtime/invalid-sync-io-in-runtime-with-valid-static-parent/page.tsx (14:20)",
"Page <anonymous>",
],
}
`)
})
it('invalid - runtime prefetch - sync IO after public cache with cookie input', async () => {
// A public "use cache" function receives cookies() as a promise
// input (for cache keying). The cache body doesn't read the cookies.
// After the cache resolves, Date.now() is sync IO that should error
// because the cookies input causes the cache to resolve during the
// EarlyRuntime stage where canSyncInterrupt returns true.
//
// If the stage discrimination for cache inputs were broken (always
// using Runtime instead of getRuntimeStage), the cookies would
// resolve at Runtime where canSyncInterrupt returns false, and the
// sync IO would be silently allowed.
const browser = await navigateTo(
'/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route "/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input" used \`Date.now()\` before accessing either uncached data (e.g. \`fetch()\`) or awaiting \`connection()\`. When configured for Runtime prefetching, accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-runtime-current-time",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input/page.tsx (30:20) @ Page
> 30 | const now = Date.now()
| ^",
"stack": [
"Page app/suspense-in-root/runtime/invalid-sync-io-after-cache-with-cookie-input/page.tsx (30:20)",
"Page <anonymous>",
],
}
`)
})
it('valid - runtime prefetch - sync IO in a static parent layout is allowed', async () => {
// Sync IO (Date.now()) in a layout that is NOT runtime-prefetchable
// should not error, even though the child page has runtime prefetch
// enabled. Only segments that are runtime-prefetchable should be
// validated for sync IO after runtime APIs.
const browser = await navigateTo(
'/suspense-in-root/runtime/valid-sync-io-in-static-parent'
)
await waitForNoErrorToast(browser)
})
it('invalid - missing suspense around dynamic (with loading.js)', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/invalid-only-loading-around-dynamic'
......
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