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 { ...@@ -41,13 +41,17 @@ import {
getConventionPathByType, getConventionPathByType,
isNextjsBuiltinFilePath, isNextjsBuiltinFilePath,
} from './segment-explorer-path' } 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. * 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: { export function createComponentTree(props: {
loaderTree: LoaderTree loaderTree: LoaderTree
parentParams: Params parentParams: Params
parentRuntimePrefetchable: false
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
injectedCSS: Set<string> injectedCSS: Set<string>
injectedJS: Set<string> injectedJS: Set<string>
...@@ -83,6 +87,7 @@ async function createComponentTreeInternal( ...@@ -83,6 +87,7 @@ async function createComponentTreeInternal(
{ {
loaderTree: tree, loaderTree: tree,
parentParams, parentParams,
parentRuntimePrefetchable,
rootLayoutIncluded, rootLayoutIncluded,
injectedCSS, injectedCSS,
injectedJS, injectedJS,
...@@ -95,6 +100,7 @@ async function createComponentTreeInternal( ...@@ -95,6 +100,7 @@ async function createComponentTreeInternal(
}: { }: {
loaderTree: LoaderTree loaderTree: LoaderTree
parentParams: Params parentParams: Params
parentRuntimePrefetchable: boolean
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
injectedCSS: Set<string> injectedCSS: Set<string>
injectedJS: Set<string> injectedJS: Set<string>
...@@ -224,6 +230,15 @@ async function createComponentTreeInternal( ...@@ -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] = const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden authInterrupts && forbidden
? await createComponentStylesAndScripts({ ? await createComponentStylesAndScripts({
...@@ -526,6 +541,7 @@ async function createComponentTreeInternal( ...@@ -526,6 +541,7 @@ async function createComponentTreeInternal(
{ {
loaderTree: parallelRoute, loaderTree: parallelRoute,
parentParams: currentParams, parentParams: currentParams,
parentRuntimePrefetchable: isRuntimePrefetchable,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout, injectedJS: injectedJSWithCurrentLayout,
...@@ -685,6 +701,8 @@ async function createComponentTreeInternal( ...@@ -685,6 +701,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
isRuntimePrefetchable,
// No user-provided component, so no params will be accessed. Use the // No user-provided component, so no params will be accessed. Use the
// pre-resolved empty tracker. // pre-resolved empty tracker.
emptyVaryParamsAccumulator emptyVaryParamsAccumulator
...@@ -724,6 +742,8 @@ async function createComponentTreeInternal( ...@@ -724,6 +742,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
true, true,
isRuntimePrefetchable,
// force-dynamic postpones without rendering the component, so no params // force-dynamic postpones without rendering the component, so no params
// are accessed. The vary params are empty. // are accessed. The vary params are empty.
emptyVaryParamsAccumulator emptyVaryParamsAccumulator
...@@ -790,7 +810,8 @@ async function createComponentTreeInternal( ...@@ -790,7 +810,8 @@ async function createComponentTreeInternal(
const params = createServerParamsForServerSegment( const params = createServerParamsForServerSegment(
currentParams, currentParams,
workStore, workStore,
varyParamsAccumulator varyParamsAccumulator,
isRuntimePrefetchable
) )
// If we are passing searchParams to a server component Page we need to // If we are passing searchParams to a server component Page we need to
...@@ -799,7 +820,8 @@ async function createComponentTreeInternal( ...@@ -799,7 +820,8 @@ async function createComponentTreeInternal(
let searchParams = createServerSearchParamsForServerPage( let searchParams = createServerSearchParamsForServerPage(
query, query,
workStore, workStore,
varyParamsAccumulator varyParamsAccumulator,
isRuntimePrefetchable
) )
if (isUseCacheFunction(PageComponent)) { if (isUseCacheFunction(PageComponent)) {
...@@ -851,6 +873,8 @@ async function createComponentTreeInternal( ...@@ -851,6 +873,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
isRuntimePrefetchable,
varyParamsAccumulator varyParamsAccumulator
) )
} else { } else {
...@@ -970,7 +994,8 @@ async function createComponentTreeInternal( ...@@ -970,7 +994,8 @@ async function createComponentTreeInternal(
const params = createServerParamsForServerSegment( const params = createServerParamsForServerSegment(
currentParams, currentParams,
workStore, workStore,
varyParamsAccumulator varyParamsAccumulator,
isRuntimePrefetchable
) )
let serverSegment: React.ReactNode let serverSegment: React.ReactNode
...@@ -1065,6 +1090,8 @@ async function createComponentTreeInternal( ...@@ -1065,6 +1090,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
isRuntimePrefetchable,
varyParamsAccumulator varyParamsAccumulator
) )
} }
...@@ -1216,8 +1243,46 @@ function createSeedData( ...@@ -1216,8 +1243,46 @@ function createSeedData(
parallelRoutes: Record<string, CacheNodeSeedData | null>, parallelRoutes: Record<string, CacheNodeSeedData | null>,
loading: LoadingModuleData | null, loading: LoadingModuleData | null,
isPossiblyPartialResponse: boolean, isPossiblyPartialResponse: boolean,
isRuntimePrefetchable: boolean,
varyParamsAccumulator: VaryParamsAccumulator | null varyParamsAccumulator: VaryParamsAccumulator | null
): CacheNodeSeedData { ): 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 (loading !== null) {
// If a loading.tsx boundary is present, wrap the component data in an // If a loading.tsx boundary is present, wrap the component data in an
// additional context provider to pass the loading data to the next // additional context provider to pass the loading data to the next
...@@ -1225,7 +1290,6 @@ function createSeedData( ...@@ -1225,7 +1290,6 @@ function createSeedData(
// NOTE: The reason this is a separate wrapper from LayoutRouter is because // NOTE: The reason this is a separate wrapper from LayoutRouter is because
// not all segments render a LayoutRouter component, e.g. the root segment. // not all segments render a LayoutRouter component, e.g. the root segment.
const LoadingBoundaryProvider = ctx.componentMod.LoadingBoundaryProvider const LoadingBoundaryProvider = ctx.componentMod.LoadingBoundaryProvider
const createElement = ctx.componentMod.createElement
rsc = createElement(LoadingBoundaryProvider, { rsc = createElement(LoadingBoundaryProvider, {
loading: loading, loading: loading,
children: rsc, children: rsc,
......
...@@ -25,7 +25,6 @@ import type { ...@@ -25,7 +25,6 @@ import type {
WorkUnitStore, WorkUnitStore,
PrerenderStoreLegacy, PrerenderStoreLegacy,
PrerenderStoreModern, PrerenderStoreModern,
PrerenderStoreModernRuntime,
ValidationStoreClient, ValidationStoreClient,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
...@@ -38,9 +37,8 @@ import { ...@@ -38,9 +37,8 @@ import {
throwForMissingRequestStore, throwForMissingRequestStore,
workUnitAsyncStorage, workUnitAsyncStorage,
} from './work-unit-async-storage.external' } from './work-unit-async-storage.external'
import { RenderStage } from './staged-rendering'
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise, getRuntimeStage } from '../dynamic-rendering-utils'
import { import {
METADATA_BOUNDARY_NAME, METADATA_BOUNDARY_NAME,
VIEWPORT_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME,
...@@ -547,8 +545,9 @@ export function createHangingInputAbortSignal( ...@@ -547,8 +545,9 @@ export function createHangingInputAbortSignal(
workUnitStore.type === 'prerender-runtime' && workUnitStore.type === 'prerender-runtime' &&
workUnitStore.stagedRendering workUnitStore.stagedRendering
) { ) {
workUnitStore.stagedRendering const { stagedRendering } = workUnitStore
.waitForStage(RenderStage.Runtime) stagedRendering
.waitForStage(getRuntimeStage(stagedRendering))
.then(() => scheduleOnNextTick(() => controller.abort())) .then(() => scheduleOnNextTick(() => controller.abort()))
} else { } else {
scheduleOnNextTick(() => controller.abort()) scheduleOnNextTick(() => controller.abort())
...@@ -1259,15 +1258,3 @@ export function getNavigationDisallowedDynamicReasons( ...@@ -1259,15 +1258,3 @@ export function getNavigationDisallowedDynamicReasons(
// We had a non-empty prelude and there are no dynamic holes // We had a non-empty prelude and there are no dynamic holes
return [] 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 ...@@ -3,31 +3,39 @@ import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolv
export enum RenderStage { export enum RenderStage {
Before = 1, Before = 1,
Static = 2, EarlyStatic = 2,
Runtime = 3, Static = 3,
Dynamic = 4, EarlyRuntime = 4,
Abandoned = 5, 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 { export class StagedRenderingController {
currentStage: RenderStage = RenderStage.Before currentStage: RenderStage = RenderStage.Before
staticInterruptReason: Error | null = null syncInterruptReason: Error | null = null
runtimeInterruptReason: Error | null = null
staticStageEndTime: number = Infinity staticStageEndTime: number = Infinity
runtimeStageEndTime: number = Infinity runtimeStageEndTime: number = Infinity
private staticStageListeners: Array<() => void> = []
private earlyRuntimeStageListeners: Array<() => void> = []
private runtimeStageListeners: Array<() => void> = [] private runtimeStageListeners: Array<() => void> = []
private dynamicStageListeners: Array<() => void> = [] private dynamicStageListeners: Array<() => void> = []
private staticStagePromise = createPromiseWithResolvers<void>()
private earlyRuntimeStagePromise = createPromiseWithResolvers<void>()
private runtimeStagePromise = createPromiseWithResolvers<void>() private runtimeStagePromise = createPromiseWithResolvers<void>()
private dynamicStagePromise = createPromiseWithResolvers<void>() private dynamicStagePromise = createPromiseWithResolvers<void>()
constructor( constructor(
private abortSignal: AbortSignal | null = null, private abortSignal: AbortSignal | null = null,
private hasRuntimePrefetch: boolean,
private abandonController: AbortController | null = null private abandonController: AbortController | null = null
) { ) {
if (abortSignal) { if (abortSignal) {
...@@ -39,6 +47,10 @@ export class StagedRenderingController { ...@@ -39,6 +47,10 @@ export class StagedRenderingController {
// is a no-op. The ignoreReject handler suppresses unhandled // is a no-op. The ignoreReject handler suppresses unhandled
// rejection warnings for promises that no one is awaiting. // rejection warnings for promises that no one is awaiting.
const { reason } = abortSignal 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.promise.catch(ignoreReject)
this.runtimeStagePromise.reject(reason) this.runtimeStagePromise.reject(reason)
this.dynamicStagePromise.promise.catch(ignoreReject) this.dynamicStagePromise.promise.catch(ignoreReject)
...@@ -59,9 +71,13 @@ export class StagedRenderingController { ...@@ -59,9 +71,13 @@ export class StagedRenderingController {
} }
} }
onStage(stage: NonStaticRenderStage, callback: () => void) { onStage(stage: AdvanceableRenderStage, callback: () => void) {
if (this.currentStage >= stage) { if (this.currentStage >= stage) {
callback() callback()
} else if (stage === RenderStage.Static) {
this.staticStageListeners.push(callback)
} else if (stage === RenderStage.EarlyRuntime) {
this.earlyRuntimeStageListeners.push(callback)
} else if (stage === RenderStage.Runtime) { } else if (stage === RenderStage.Runtime) {
this.runtimeStageListeners.push(callback) this.runtimeStageListeners.push(callback)
} else if (stage === RenderStage.Dynamic) { } else if (stage === RenderStage.Dynamic) {
...@@ -78,10 +94,24 @@ export class StagedRenderingController { ...@@ -78,10 +94,24 @@ export class StagedRenderingController {
return false return false
} }
const boundaryStage = this.hasRuntimePrefetch switch (this.currentStage) {
? RenderStage.Dynamic case RenderStage.EarlyStatic:
: RenderStage.Runtime case RenderStage.Static:
return this.currentStage < boundaryStage 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) { syncInterruptCurrentStageWithReason(reason: Error) {
...@@ -105,22 +135,18 @@ export class StagedRenderingController { ...@@ -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 // If we're in the final render, we cannot abandon it. We need to advance to the Dynamic stage
// and capture the interruption reason. // and capture the interruption reason.
switch (this.currentStage) { switch (this.currentStage) {
case RenderStage.Static: { case RenderStage.EarlyStatic:
this.staticInterruptReason = reason 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) this.advanceStage(RenderStage.Dynamic)
return return
} }
case RenderStage.Runtime: { case RenderStage.Runtime: {
// We only error for Sync IO in the runtime stage if the route // canSyncInterrupt returns false for Runtime, so we should
// is configured to use runtime prefetching. // never get here. Defensive no-op.
// 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)
}
return return
} }
case RenderStage.Dynamic: case RenderStage.Dynamic:
...@@ -128,12 +154,8 @@ export class StagedRenderingController { ...@@ -128,12 +154,8 @@ export class StagedRenderingController {
} }
} }
getStaticInterruptReason() { getSyncInterruptReason() {
return this.staticInterruptReason return this.syncInterruptReason
}
getRuntimeInterruptReason() {
return this.runtimeInterruptReason
} }
getStaticStageEndTime() { getStaticStageEndTime() {
...@@ -152,15 +174,22 @@ export class StagedRenderingController { ...@@ -152,15 +174,22 @@ export class StagedRenderingController {
// (this might be a lazy intitialization of a module, // (this might be a lazy intitialization of a module,
// so we still want to restart in this case and see if it still occurs) // 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, // 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. // unblocking the dynamic stage would likely lead to wasted (uncached) IO.
const { currentStage } = this const { currentStage } = this
switch (currentStage) { switch (currentStage) {
case RenderStage.EarlyStatic: {
this.resolveStaticStage()
}
// intentional fallthrough
case RenderStage.Static: { case RenderStage.Static: {
this.currentStage = RenderStage.Abandoned this.resolveEarlyRuntimeStage()
}
// intentional fallthrough
case RenderStage.EarlyRuntime: {
this.resolveRuntimeStage() this.resolveRuntimeStage()
return
} }
// intentional fallthrough
case RenderStage.Runtime: { case RenderStage.Runtime: {
this.currentStage = RenderStage.Abandoned this.currentStage = RenderStage.Abandoned
return return
...@@ -176,7 +205,12 @@ export class StagedRenderingController { ...@@ -176,7 +205,12 @@ export class StagedRenderingController {
} }
advanceStage( 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. // 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) // (this can happen e.g. if sync IO advanced us to the dynamic stage)
...@@ -187,6 +221,15 @@ export class StagedRenderingController { ...@@ -187,6 +221,15 @@ export class StagedRenderingController {
let currentStage = this.currentStage let currentStage = this.currentStage
this.currentStage = stage 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) { if (currentStage < RenderStage.Runtime && stage >= RenderStage.Runtime) {
this.staticStageEndTime = performance.now() + performance.timeOrigin this.staticStageEndTime = performance.now() + performance.timeOrigin
this.resolveRuntimeStage() this.resolveRuntimeStage()
...@@ -198,6 +241,26 @@ export class StagedRenderingController { ...@@ -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. */ /** Fire the `onStage` listeners for the runtime stage and unblock any promises waiting for it. */
private resolveRuntimeStage() { private resolveRuntimeStage() {
const runtimeListeners = this.runtimeStageListeners const runtimeListeners = this.runtimeStageListeners
...@@ -218,8 +281,14 @@ export class StagedRenderingController { ...@@ -218,8 +281,14 @@ export class StagedRenderingController {
this.dynamicStagePromise.resolve() this.dynamicStagePromise.resolve()
} }
private getStagePromise(stage: NonStaticRenderStage): Promise<void> { private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {
switch (stage) { switch (stage) {
case RenderStage.Static: {
return this.staticStagePromise.promise
}
case RenderStage.EarlyRuntime: {
return this.earlyRuntimeStagePromise.promise
}
case RenderStage.Runtime: { case RenderStage.Runtime: {
return this.runtimeStagePromise.promise return this.runtimeStagePromise.promise
} }
...@@ -233,12 +302,12 @@ export class StagedRenderingController { ...@@ -233,12 +302,12 @@ export class StagedRenderingController {
} }
} }
waitForStage(stage: NonStaticRenderStage) { waitForStage(stage: AdvanceableRenderStage) {
return this.getStagePromise(stage) return this.getStagePromise(stage)
} }
delayUntilStage<T>( delayUntilStage<T>(
stage: NonStaticRenderStage, stage: AdvanceableRenderStage,
displayName: string | undefined, displayName: string | undefined,
resolvedValue: T resolvedValue: T
) { ) {
......
...@@ -225,6 +225,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -225,6 +225,7 @@ export async function walkTreeWithFlightRouterState({
ctx, ctx,
loaderTree: loaderTreeToFilter, loaderTree: loaderTreeToFilter,
parentParams: currentParams, parentParams: currentParams,
parentRuntimePrefetchable: false,
injectedCSS, injectedCSS,
injectedJS, injectedJS,
injectedFontPreloadTags, injectedFontPreloadTags,
...@@ -342,6 +343,7 @@ export async function createFullTreeFlightDataForNavigation({ ...@@ -342,6 +343,7 @@ export async function createFullTreeFlightDataForNavigation({
ctx, ctx,
loaderTree, loaderTree,
parentParams: {}, parentParams: {},
parentRuntimePrefetchable: false,
injectedCSS, injectedCSS,
injectedJS, injectedJS,
injectedFontPreloadTags, injectedFontPreloadTags,
......
...@@ -21,6 +21,7 @@ import type { WorkStore } from './work-async-storage.external' ...@@ -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 { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../client/components/app-router-headers'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import type { StagedRenderingController } from './staged-rendering' import type { StagedRenderingController } from './staged-rendering'
import { RenderStage } from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking' import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
export type WorkUnitPhase = 'action' | 'render' | 'after' export type WorkUnitPhase = 'action' | 'render' | 'after'
...@@ -79,15 +80,42 @@ export interface RequestStore extends CommonWorkUnitStore { ...@@ -79,15 +80,42 @@ export interface RequestStore extends CommonWorkUnitStore {
type DevAsyncApiPromises = { type DevAsyncApiPromises = {
cookies: Promise<ReadonlyRequestCookies> cookies: Promise<ReadonlyRequestCookies>
earlyCookies: Promise<ReadonlyRequestCookies>
mutableCookies: Promise<ReadonlyRequestCookies> mutableCookies: Promise<ReadonlyRequestCookies>
earlyMutableCookies: Promise<ReadonlyRequestCookies>
headers: Promise<ReadonlyHeaders> headers: Promise<ReadonlyHeaders>
earlyHeaders: Promise<ReadonlyHeaders>
sharedParamsParent: Promise<string> sharedParamsParent: Promise<string>
earlySharedParamsParent: Promise<string>
sharedSearchParamsParent: 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> 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. * The Prerender store is for tracking information related to prerenders.
* *
......
import type { NonStaticRenderStage } from './app-render/staged-rendering' import {
import type { RequestStore } from './app-render/work-unit-async-storage.external' 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( export function isHangingPromiseRejectionError(
err: unknown err: unknown
...@@ -79,7 +86,7 @@ function ignoreReject() {} ...@@ -79,7 +86,7 @@ function ignoreReject() {}
export function makeDevtoolsIOAwarePromise<T>( export function makeDevtoolsIOAwarePromise<T>(
underlying: T, underlying: T,
requestStore: RequestStore, requestStore: RequestStore,
stage: NonStaticRenderStage stage: AdvanceableRenderStage
): Promise<T> { ): Promise<T> {
if (requestStore.stagedRendering) { if (requestStore.stagedRendering) {
// We resolve each stage in a timeout, so React DevTools will pick this up as IO. // We resolve each stage in a timeout, so React DevTools will pick this up as IO.
...@@ -98,3 +105,46 @@ export function makeDevtoolsIOAwarePromise<T>( ...@@ -98,3 +105,46 @@ export function makeDevtoolsIOAwarePromise<T>(
}, 0) }, 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) { ...@@ -87,7 +87,10 @@ export function io(expression: string, type: ApiType) {
const stageController = workUnitStore.stagedRendering const stageController = workUnitStore.stagedRendering
if (stageController && stageController.canSyncInterrupt()) { if (stageController && stageController.canSyncInterrupt()) {
let message: string let message: string
if (stageController.currentStage === RenderStage.Static) { if (
stageController.currentStage === RenderStage.Static ||
stageController.currentStage === RenderStage.EarlyStatic
) {
switch (type) { switch (type) {
case 'time': 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` 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 { ...@@ -13,15 +13,16 @@ import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreModern, type PrerenderStoreModern,
type RequestStore, type RequestStore,
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
delayUntilRuntimeStage,
postponeWithTracking, postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { import {
delayUntilRuntimeStage,
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
...@@ -191,11 +192,16 @@ function makeUntrackedCookiesWithDevWarnings( ...@@ -191,11 +192,16 @@ function makeUntrackedCookiesWithDevWarnings(
route?: string route?: string
): Promise<ReadonlyRequestCookies> { ): Promise<ReadonlyRequestCookies> {
if (requestStore.asyncApiPromises) { if (requestStore.asyncApiPromises) {
const early = isInEarlyRenderStage(requestStore)
let promise: Promise<ReadonlyRequestCookies> let promise: Promise<ReadonlyRequestCookies>
if (underlyingCookies === requestStore.mutableCookies) { if (underlyingCookies === requestStore.mutableCookies) {
promise = requestStore.asyncApiPromises.mutableCookies promise = early
? requestStore.asyncApiPromises.earlyMutableCookies
: requestStore.asyncApiPromises.mutableCookies
} else if (underlyingCookies === requestStore.cookies) { } else if (underlyingCookies === requestStore.cookies) {
promise = requestStore.asyncApiPromises.cookies promise = early
? requestStore.asyncApiPromises.earlyCookies
: requestStore.asyncApiPromises.cookies
} else { } else {
throw new InvariantError( throw new InvariantError(
'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`' 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'
......
...@@ -12,7 +12,6 @@ import { ...@@ -12,7 +12,6 @@ import {
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { import {
abortAndThrowOnSynchronousRequestDataAccess, abortAndThrowOnSynchronousRequestDataAccess,
delayUntilRuntimeStage,
postponeWithTracking, postponeWithTracking,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -20,6 +19,7 @@ import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-b ...@@ -20,6 +19,7 @@ import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-b
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { DynamicServerError } from '../../client/components/hooks-server-context' import { DynamicServerError } from '../../client/components/hooks-server-context'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { delayUntilRuntimeStage } from '../dynamic-rendering-utils'
import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
export function draftMode(): Promise<DraftMode> { export function draftMode(): Promise<DraftMode> {
......
...@@ -11,15 +11,16 @@ import { ...@@ -11,15 +11,16 @@ import {
workUnitAsyncStorage, workUnitAsyncStorage,
type PrerenderStoreModern, type PrerenderStoreModern,
type RequestStore, type RequestStore,
isInEarlyRenderStage,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
delayUntilRuntimeStage,
postponeWithTracking, postponeWithTracking,
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
trackDynamicDataInDynamicRender, trackDynamicDataInDynamicRender,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout' import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { import {
delayUntilRuntimeStage,
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
...@@ -201,7 +202,9 @@ function makeUntrackedHeadersWithDevWarnings( ...@@ -201,7 +202,9 @@ function makeUntrackedHeadersWithDevWarnings(
requestStore: RequestStore requestStore: RequestStore
): Promise<ReadonlyHeaders> { ): Promise<ReadonlyHeaders> {
if (requestStore.asyncApiPromises) { if (requestStore.asyncApiPromises) {
const promise = requestStore.asyncApiPromises.headers const promise = isInEarlyRenderStage(requestStore)
? requestStore.asyncApiPromises.earlyHeaders
: requestStore.asyncApiPromises.headers
return instrumentHeadersPromiseWithDevWarnings(promise, route) return instrumentHeadersPromiseWithDevWarnings(promise, route)
} }
......
...@@ -13,7 +13,6 @@ import { ReflectAdapter } from '../web/spec-extension/adapters/reflect' ...@@ -13,7 +13,6 @@ import { ReflectAdapter } from '../web/spec-extension/adapters/reflect'
import { import {
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
postponeWithTracking, postponeWithTracking,
delayUntilRuntimeStage,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { import {
...@@ -82,11 +81,14 @@ export function createParamsFromClient( ...@@ -82,11 +81,14 @@ export function createParamsFromClient(
// but since you would never use next dev with production NODE_ENV we use this // 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. // as a proxy so we can statically exclude this code from production builds.
const devFallbackParams = workUnitStore.devFallbackParams const devFallbackParams = workUnitStore.devFallbackParams
// Client params are not runtime prefetchable
const isRuntimePrefetchable = false
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
devFallbackParams, devFallbackParams,
workStore, workStore,
workUnitStore workUnitStore,
isRuntimePrefetchable
) )
} else { } else {
return createRenderParamsInProd(underlyingParams) return createRenderParamsInProd(underlyingParams)
...@@ -99,6 +101,8 @@ export function createParamsFromClient( ...@@ -99,6 +101,8 @@ export function createParamsFromClient(
} }
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component // 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 type CreateServerParamsForMetadata = typeof createServerParamsForMetadata
export function createServerParamsForMetadata( export function createServerParamsForMetadata(
underlyingParams: Params, underlyingParams: Params,
...@@ -108,7 +112,8 @@ export function createServerParamsForMetadata( ...@@ -108,7 +112,8 @@ export function createServerParamsForMetadata(
return createServerParamsForServerSegment( return createServerParamsForServerSegment(
underlyingParams, underlyingParams,
workStore, workStore,
metadataVaryParamsAccumulator metadataVaryParamsAccumulator,
metadataIsRuntimePrefetchable
) )
} }
...@@ -141,23 +146,30 @@ export function createServerParamsForRoute( ...@@ -141,23 +146,30 @@ export function createServerParamsForRoute(
throw new InvariantError( throw new InvariantError(
'createServerParamsForRoute should not be called in cache contexts.' '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( return createRuntimePrerenderParams(
underlyingParams, underlyingParams,
workUnitStore, workUnitStore,
varyParamsAccumulator varyParamsAccumulator,
isRuntimePrefetchable
) )
}
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// Semantically we only need the dev tracking when running in `next dev` // 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 // 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. // as a proxy so we can statically exclude this code from production builds.
const devFallbackParams = workUnitStore.devFallbackParams const devFallbackParams = workUnitStore.devFallbackParams
// Route params are not runtime prefetchable
const isRuntimePrefetchable = false
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
devFallbackParams, devFallbackParams,
workStore, workStore,
workUnitStore workUnitStore,
isRuntimePrefetchable
) )
} else { } else {
return createRenderParamsInProd(underlyingParams) return createRenderParamsInProd(underlyingParams)
...@@ -172,7 +184,8 @@ export function createServerParamsForRoute( ...@@ -172,7 +184,8 @@ export function createServerParamsForRoute(
export function createServerParamsForServerSegment( export function createServerParamsForServerSegment(
underlyingParams: Params, underlyingParams: Params,
workStore: WorkStore, workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<Params> { ): Promise<Params> {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
...@@ -200,7 +213,8 @@ export function createServerParamsForServerSegment( ...@@ -200,7 +213,8 @@ export function createServerParamsForServerSegment(
return createRuntimePrerenderParams( return createRuntimePrerenderParams(
underlyingParams, underlyingParams,
workUnitStore, workUnitStore,
varyParamsAccumulator varyParamsAccumulator,
isRuntimePrefetchable
) )
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
...@@ -212,7 +226,8 @@ export function createServerParamsForServerSegment( ...@@ -212,7 +226,8 @@ export function createServerParamsForServerSegment(
underlyingParams, underlyingParams,
devFallbackParams, devFallbackParams,
workStore, workStore,
workUnitStore workUnitStore,
isRuntimePrefetchable
) )
} else { } else {
return createRenderParamsInProd(underlyingParams) return createRenderParamsInProd(underlyingParams)
...@@ -340,17 +355,23 @@ function createStaticPrerenderParams( ...@@ -340,17 +355,23 @@ function createStaticPrerenderParams(
function createRuntimePrerenderParams( function createRuntimePrerenderParams(
underlyingParams: Params, underlyingParams: Params,
workUnitStore: PrerenderStoreModernRuntime, workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<Params> { ): Promise<Params> {
const underlyingParamsWithVarying = const underlyingParamsWithVarying =
varyParamsAccumulator !== null varyParamsAccumulator !== null
? createVaryingParams(varyParamsAccumulator, underlyingParams) ? createVaryingParams(varyParamsAccumulator, underlyingParams)
: underlyingParams : underlyingParams
return delayUntilRuntimeStage( const result = makeUntrackedParams(underlyingParamsWithVarying)
workUnitStore, const { stagedRendering } = workUnitStore
makeUntrackedParams(underlyingParamsWithVarying) if (!stagedRendering) {
) return result
}
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime
: RenderStage.Runtime
return stagedRendering.waitForStage(stage).then(() => result)
} }
function createRenderParamsInProd(underlyingParams: Params): Promise<Params> { function createRenderParamsInProd(underlyingParams: Params): Promise<Params> {
...@@ -361,7 +382,8 @@ function createRenderParamsInDev( ...@@ -361,7 +382,8 @@ function createRenderParamsInDev(
underlyingParams: Params, underlyingParams: Params,
devFallbackParams: OpaqueFallbackRouteParams | null | undefined, devFallbackParams: OpaqueFallbackRouteParams | null | undefined,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<Params> { ): Promise<Params> {
let hasFallbackParams = false let hasFallbackParams = false
if (devFallbackParams) { if (devFallbackParams) {
...@@ -377,7 +399,8 @@ function createRenderParamsInDev( ...@@ -377,7 +399,8 @@ function createRenderParamsInDev(
underlyingParams, underlyingParams,
hasFallbackParams, hasFallbackParams,
workStore, workStore,
requestStore requestStore,
isRuntimePrefetchable
) )
} }
...@@ -510,7 +533,8 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -510,7 +533,8 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
underlyingParams: Params, underlyingParams: Params,
hasFallbackParams: boolean, hasFallbackParams: boolean,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<Params> { ): Promise<Params> {
if (requestStore.asyncApiPromises && hasFallbackParams) { if (requestStore.asyncApiPromises && hasFallbackParams) {
// We wrap each instance of params in a `new Promise()`, because deduping // We wrap each instance of params in a `new Promise()`, because deduping
...@@ -518,7 +542,9 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -518,7 +542,9 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
// await a different set of values. This is important when all awaits // 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 // are in third party which would otherwise track all the way to the
// internal params. // internal params.
const sharedParamsParent = requestStore.asyncApiPromises.sharedParamsParent const sharedParamsParent = isRuntimePrefetchable
? requestStore.asyncApiPromises.earlySharedParamsParent
: requestStore.asyncApiPromises.sharedParamsParent
const promise: Promise<Params> = new Promise((resolve, reject) => { const promise: Promise<Params> = new Promise((resolve, reject) => {
sharedParamsParent.then(() => resolve(underlyingParams), reject) sharedParamsParent.then(() => resolve(underlyingParams), reject)
}) })
......
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from '../app-render/work-async-storage.external'
import { import {
delayUntilRuntimeStage,
postponeWithTracking, postponeWithTracking,
type DynamicTrackingState, type DynamicTrackingState,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
...@@ -13,7 +12,10 @@ import { ...@@ -13,7 +12,10 @@ import {
type PrerenderStoreModernServer, type PrerenderStoreModernServer,
type PrerenderStorePPR, type PrerenderStorePPR,
} from '../app-render/work-unit-async-storage.external' } 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' import { InvariantError } from '../../shared/lib/invariant-error'
export function createServerPathnameForMetadata( export function createServerPathnameForMetadata(
......
...@@ -10,7 +10,6 @@ import { ...@@ -10,7 +10,6 @@ import {
throwToInterruptStaticGeneration, throwToInterruptStaticGeneration,
postponeWithTracking, postponeWithTracking,
annotateDynamicAccess, annotateDynamicAccess,
delayUntilRuntimeStage,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { import {
...@@ -68,10 +67,13 @@ export function createSearchParamsFromClient( ...@@ -68,10 +67,13 @@ export function createSearchParamsFromClient(
'createSearchParamsFromClient should not be called in cache contexts.' 'createSearchParamsFromClient should not be called in cache contexts.'
) )
case 'request': case 'request':
// Client searchParams are not runtime prefetchable
const isRuntimePrefetchable = false
return createRenderSearchParams( return createRenderSearchParams(
underlyingSearchParams, underlyingSearchParams,
workStore, workStore,
workUnitStore workUnitStore,
isRuntimePrefetchable
) )
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -81,6 +83,8 @@ export function createSearchParamsFromClient( ...@@ -81,6 +83,8 @@ export function createSearchParamsFromClient(
} }
// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component // 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( export function createServerSearchParamsForMetadata(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workStore: WorkStore workStore: WorkStore
...@@ -89,14 +93,16 @@ export function createServerSearchParamsForMetadata( ...@@ -89,14 +93,16 @@ export function createServerSearchParamsForMetadata(
return createServerSearchParamsForServerPage( return createServerSearchParamsForServerPage(
underlyingSearchParams, underlyingSearchParams,
workStore, workStore,
metadataVaryParamsAccumulator metadataVaryParamsAccumulator,
metadataIsRuntimePrefetchable
) )
} }
export function createServerSearchParamsForServerPage( export function createServerSearchParamsForServerPage(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workStore: WorkStore, workStore: WorkStore,
varyParamsAccumulator: VaryParamsAccumulator | null = null varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<SearchParams> { ): Promise<SearchParams> {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
if (workUnitStore) { if (workUnitStore) {
...@@ -120,13 +126,15 @@ export function createServerSearchParamsForServerPage( ...@@ -120,13 +126,15 @@ export function createServerSearchParamsForServerPage(
return createRuntimePrerenderSearchParams( return createRuntimePrerenderSearchParams(
underlyingSearchParams, underlyingSearchParams,
workUnitStore, workUnitStore,
varyParamsAccumulator varyParamsAccumulator,
isRuntimePrefetchable
) )
case 'request': case 'request':
return createRenderSearchParams( return createRenderSearchParams(
underlyingSearchParams, underlyingSearchParams,
workStore, workStore,
workUnitStore workUnitStore,
isRuntimePrefetchable
) )
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -209,22 +217,30 @@ function createStaticPrerenderSearchParams( ...@@ -209,22 +217,30 @@ function createStaticPrerenderSearchParams(
function createRuntimePrerenderSearchParams( function createRuntimePrerenderSearchParams(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workUnitStore: PrerenderStoreModernRuntime, workUnitStore: PrerenderStoreModernRuntime,
varyParamsAccumulator: VaryParamsAccumulator | null varyParamsAccumulator: VaryParamsAccumulator | null,
isRuntimePrefetchable: boolean
): Promise<SearchParams> { ): Promise<SearchParams> {
const underlyingSearchParamsWithVarying = const underlyingSearchParamsWithVarying =
varyParamsAccumulator !== null varyParamsAccumulator !== null
? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams) ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)
: underlyingSearchParams : underlyingSearchParams
return delayUntilRuntimeStage(
workUnitStore, const result = makeUntrackedSearchParams(underlyingSearchParamsWithVarying)
makeUntrackedSearchParams(underlyingSearchParamsWithVarying) const { stagedRendering } = workUnitStore
) if (!stagedRendering) {
return result
}
const stage = isRuntimePrefetchable
? RenderStage.EarlyRuntime
: RenderStage.Runtime
return stagedRendering.waitForStage(stage).then(() => result)
} }
function createRenderSearchParams( function createRenderSearchParams(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<SearchParams> { ): Promise<SearchParams> {
if (workStore.forceStatic) { if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty // When using forceStatic we override all other logic and always just return an empty
...@@ -238,7 +254,8 @@ function createRenderSearchParams( ...@@ -238,7 +254,8 @@ function createRenderSearchParams(
return makeUntrackedSearchParamsWithDevWarnings( return makeUntrackedSearchParamsWithDevWarnings(
underlyingSearchParams, underlyingSearchParams,
workStore, workStore,
requestStore requestStore,
isRuntimePrefetchable
) )
} else { } else {
return makeUntrackedSearchParams(underlyingSearchParams) return makeUntrackedSearchParams(underlyingSearchParams)
...@@ -416,7 +433,8 @@ function makeUntrackedSearchParams( ...@@ -416,7 +433,8 @@ function makeUntrackedSearchParams(
function makeUntrackedSearchParamsWithDevWarnings( function makeUntrackedSearchParamsWithDevWarnings(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<SearchParams> { ): Promise<SearchParams> {
if (requestStore.asyncApiPromises) { if (requestStore.asyncApiPromises) {
// Do not cache the resulting promise. If we do, we'll only show the first "awaited at" // Do not cache the resulting promise. If we do, we'll only show the first "awaited at"
...@@ -424,7 +442,8 @@ function makeUntrackedSearchParamsWithDevWarnings( ...@@ -424,7 +442,8 @@ function makeUntrackedSearchParamsWithDevWarnings(
return makeUntrackedSearchParamsWithDevWarningsImpl( return makeUntrackedSearchParamsWithDevWarningsImpl(
underlyingSearchParams, underlyingSearchParams,
workStore, workStore,
requestStore requestStore,
isRuntimePrefetchable
) )
} else { } else {
const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams) const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)
...@@ -434,7 +453,8 @@ function makeUntrackedSearchParamsWithDevWarnings( ...@@ -434,7 +453,8 @@ function makeUntrackedSearchParamsWithDevWarnings(
const promise = makeUntrackedSearchParamsWithDevWarningsImpl( const promise = makeUntrackedSearchParamsWithDevWarningsImpl(
underlyingSearchParams, underlyingSearchParams,
workStore, workStore,
requestStore requestStore,
isRuntimePrefetchable
) )
CachedSearchParams.set(requestStore, promise) CachedSearchParams.set(requestStore, promise)
return promise return promise
...@@ -444,7 +464,8 @@ function makeUntrackedSearchParamsWithDevWarnings( ...@@ -444,7 +464,8 @@ function makeUntrackedSearchParamsWithDevWarnings(
function makeUntrackedSearchParamsWithDevWarningsImpl( function makeUntrackedSearchParamsWithDevWarningsImpl(
underlyingSearchParams: SearchParams, underlyingSearchParams: SearchParams,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore requestStore: RequestStore,
isRuntimePrefetchable: boolean
): Promise<SearchParams> { ): Promise<SearchParams> {
const promiseInitialized = { current: false } const promiseInitialized = { current: false }
const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings( const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(
...@@ -458,8 +479,9 @@ function makeUntrackedSearchParamsWithDevWarningsImpl( ...@@ -458,8 +479,9 @@ function makeUntrackedSearchParamsWithDevWarningsImpl(
// We wrap each instance of searchParams in a `new Promise()`. // We wrap each instance of searchParams in a `new Promise()`.
// This is important when all awaits are in third party which would otherwise // This is important when all awaits are in third party which would otherwise
// track all the way to the internal params. // track all the way to the internal params.
const sharedSearchParamsParent = const sharedSearchParamsParent = isRuntimePrefetchable
requestStore.asyncApiPromises.sharedSearchParamsParent ? requestStore.asyncApiPromises.earlySharedSearchParamsParent
: requestStore.asyncApiPromises.sharedSearchParamsParent
promise = new Promise((resolve, reject) => { promise = new Promise((resolve, reject) => {
sharedSearchParamsParent.then(() => resolve(proxiedUnderlying), reject) sharedSearchParamsParent.then(() => resolve(proxiedUnderlying), reject)
}) })
......
...@@ -38,6 +38,7 @@ import { ...@@ -38,6 +38,7 @@ import {
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
getRuntimeStage,
makeDevtoolsIOAwarePromise, makeDevtoolsIOAwarePromise,
makeHangingPromise, makeHangingPromise,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
...@@ -1055,22 +1056,25 @@ export async function cache( ...@@ -1055,22 +1056,25 @@ export async function cache(
switch (outerWorkUnitStore.type) { switch (outerWorkUnitStore.type) {
case 'prerender-runtime': { case 'prerender-runtime': {
// In a runtime prerender, we have to make sure that APIs that would hang during a static prerender // 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 const stagedRendering = outerWorkUnitStore.stagedRendering
if (stagedRendering) { if (stagedRendering) {
await stagedRendering.waitForStage(RenderStage.Runtime) await stagedRendering.waitForStage(getRuntimeStage(stagedRendering))
} }
break break
} }
case 'request': { case 'request': {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// Similar to runtime prerenders, private caches should not resolve in the static stage // Similar to runtime prerenders, private caches should not resolve in the static stage
// of a dev request, so we delay them. // of a dev request, so we delay them. We pick the appropriate runtime stage based on
await makeDevtoolsIOAwarePromise( // whether we're in the early or late stages.
undefined, const stagedRendering = outerWorkUnitStore.stagedRendering
outerWorkUnitStore, const stage = stagedRendering
RenderStage.Runtime ? getRuntimeStage(stagedRendering)
) : RenderStage.Runtime
await makeDevtoolsIOAwarePromise(undefined, outerWorkUnitStore, stage)
} }
break break
} }
...@@ -1366,10 +1370,12 @@ export async function cache( ...@@ -1366,10 +1370,12 @@ export async function cache(
case 'prerender-runtime': { case 'prerender-runtime': {
// In the final phase of a runtime prerender, we have to make // In the final phase of a runtime prerender, we have to make
// sure that APIs that would hang during a static prerender // 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 const stagedRendering = workUnitStore.stagedRendering
if (stagedRendering) { if (stagedRendering) {
await stagedRendering.waitForStage(RenderStage.Runtime) await stagedRendering.waitForStage(
getRuntimeStage(stagedRendering)
)
} }
break break
} }
...@@ -1399,10 +1405,14 @@ export async function cache( ...@@ -1399,10 +1405,14 @@ export async function cache(
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts. // 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, // 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. // 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( await makeDevtoolsIOAwarePromise(
undefined, undefined,
workUnitStore, workUnitStore,
RenderStage.Runtime stage
) )
} }
break break
...@@ -1652,11 +1662,11 @@ export async function cache( ...@@ -1652,11 +1662,11 @@ export async function cache(
// TODO(restart-on-cache-miss): Optimize this to avoid unnecessary restarts. // 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, // 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. // and thus will cause a restart even if all caches are filled.
await makeDevtoolsIOAwarePromise( const stagedRendering = workUnitStore.stagedRendering
undefined, const stage = stagedRendering
workUnitStore, ? getRuntimeStage(stagedRendering)
RenderStage.Runtime : RenderStage.Runtime
) await makeDevtoolsIOAwarePromise(undefined, workUnitStore, stage)
} }
break break
} }
......
...@@ -110,8 +110,26 @@ describe('react-performance-track', () => { ...@@ -110,8 +110,26 @@ describe('react-performance-track', () => {
}) })
const track = await browser.eval('window.reactServerRequests.getSnapshot()') const track = await browser.eval('window.reactServerRequests.getSnapshot()')
// TODO: Should include "draftMode [Prefetchable]". // TODO the addition of a promise to delay some Segments from rendering until the later Static
expect(track).toEqual([]) // 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 () => { it('should show headers', async () => {
......
...@@ -38,6 +38,15 @@ export default async function Page() { ...@@ -38,6 +38,15 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/runtime/valid-blocking-inside-runtime" /> <DebugLinks href="/suspense-in-root/runtime/valid-blocking-inside-runtime" />
</li> </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> </ul>
<h2>Static</h2> <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', () => { ...@@ -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 () => { it('invalid - missing suspense around dynamic (with loading.js)', async () => {
const browser = await navigateTo( const browser = await navigateTo(
'/suspense-in-root/static/invalid-only-loading-around-dynamic' '/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