Commit b1ab3408 authored by Janka Uryga's avatar Janka Uryga

abort and report on sync IO errors in dev

parent 31f18201
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
} from '../app-render/work-async-storage.external' } from '../app-render/work-async-storage.external'
import type { import type {
DevStoreModernPartial, DevStoreModernPartial,
DevRequestStoreModern,
PrerenderStoreModernRuntime, PrerenderStoreModernRuntime,
RequestStore, RequestStore,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
...@@ -2789,6 +2790,7 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2789,6 +2790,7 @@ async function renderWithRestartOnCacheMissInDev(
htmlRequestId, htmlRequestId,
renderOpts, renderOpts,
requestId, requestId,
workStore,
componentMod: { componentMod: {
routeModule: { routeModule: {
userland: { loaderTree }, userland: { loaderTree },
...@@ -2803,6 +2805,13 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2803,6 +2805,13 @@ async function renderWithRestartOnCacheMissInDev(
} = renderOpts } = renderOpts
assertClientReferenceManifest(clientReferenceManifest) assertClientReferenceManifest(clientReferenceManifest)
const captureOwnerStack = ComponentMod.captureOwnerStack
// Check if any segment of the current page has runtime prefetching enabled.
// Note that if we're in a client navigation, this config might come from
// a shared layout parent that won't actually be rendered here.
// However, if the parent is runtime prefetchable, then all of its children
// can potentially run as part of a runtime prefetch, so it makes sense to validate them.
const hasRuntimePrefetch = const hasRuntimePrefetch =
await anySegmentHasRuntimePrefetchEnabled(loaderTree) await anySegmentHasRuntimePrefetchEnabled(loaderTree)
...@@ -2810,7 +2819,8 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2810,7 +2819,8 @@ async function renderWithRestartOnCacheMissInDev(
let requestStore: RequestStore = initialRequestStore let requestStore: RequestStore = initialRequestStore
const environmentName = () => { const environmentName = () => {
const currentStage = requestStore.stagedRendering!.currentStage const { stagedRendering } = requestStore as DevRequestStoreModern
const currentStage = stagedRendering.currentStage
switch (currentStage) { switch (currentStage) {
case RenderStage.Static: case RenderStage.Static:
return 'Prerender' return 'Prerender'
...@@ -2824,6 +2834,25 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2824,6 +2834,25 @@ async function renderWithRestartOnCacheMissInDev(
} }
} }
const throwIfInvalidDynamic = (expectedStage: RenderStage) => {
const { stagedRendering, dynamicTracking } =
requestStore as DevRequestStoreModern
if (
expectedStage !== RenderStage.Dynamic &&
// Sync IO errors advance us to the dynamic stage.
stagedRendering.currentStage === RenderStage.Dynamic
) {
// We should always have an error set, but be defensive
if (dynamicTracking.syncDynamicErrorWithStack) {
throw dynamicTracking.syncDynamicErrorWithStack
}
}
if (workStore.invalidDynamicUsageError) {
throw workStore.invalidDynamicUsageError
}
}
//=============================================== //===============================================
// Initial render // Initial render
//=============================================== //===============================================
...@@ -2861,6 +2890,10 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2861,6 +2890,10 @@ async function renderWithRestartOnCacheMissInDev(
), ),
prerenderResumeDataCache, prerenderResumeDataCache,
cacheSignal, cacheSignal,
dynamicTracking: createDynamicTrackingState(
false // isDebugDynamicAccesses
),
captureOwnerStack,
} satisfies DevStoreModernPartial) } satisfies DevStoreModernPartial)
let debugChannel = setReactDebugChannel && createDebugChannel() let debugChannel = setReactDebugChannel && createDebugChannel()
...@@ -2899,6 +2932,8 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2899,6 +2932,8 @@ async function renderWithRestartOnCacheMissInDev(
return stream return stream
}, },
(stream) => { (stream) => {
throwIfInvalidDynamic(/* expected stage */ RenderStage.Static)
// Runtime stage // Runtime stage
initialStageController.advanceStage(RenderStage.Runtime) initialStageController.advanceStage(RenderStage.Runtime)
...@@ -2912,7 +2947,9 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2912,7 +2947,9 @@ async function renderWithRestartOnCacheMissInDev(
// and see if there's any cache misses in the runtime stage. // and see if there's any cache misses in the runtime stage.
return stream return stream
}, },
async (maybeStream) => { (maybeStream) => {
throwIfInvalidDynamic(/* expected stage */ RenderStage.Runtime)
// Dynamic stage // Dynamic stage
// If we had cache misses in either of the previous stages, // If we had cache misses in either of the previous stages,
...@@ -2954,6 +2991,10 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2954,6 +2991,10 @@ async function renderWithRestartOnCacheMissInDev(
await cacheSignal.cacheReady() await cacheSignal.cacheReady()
initialReactController.abort() initialReactController.abort()
throwIfInvalidDynamic(
// If we're warming caches, we shouldn't have advanced past the runtime stage.
RenderStage.Runtime
)
//=============================================== //===============================================
// Final render (restarted) // Final render (restarted)
...@@ -2979,6 +3020,10 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -2979,6 +3020,10 @@ async function renderWithRestartOnCacheMissInDev(
), ),
prerenderResumeDataCache: null, prerenderResumeDataCache: null,
cacheSignal: null, cacheSignal: null,
dynamicTracking: createDynamicTrackingState(
false // isDebugDynamicAccesses
),
captureOwnerStack: ComponentMod.captureOwnerStack,
} satisfies DevStoreModernPartial) } satisfies DevStoreModernPartial)
// The initial render already wrote to its debug channel. // The initial render already wrote to its debug channel.
...@@ -3002,11 +3047,15 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -3002,11 +3047,15 @@ async function renderWithRestartOnCacheMissInDev(
) )
}, },
(stream) => { (stream) => {
throwIfInvalidDynamic(/* expected stage */ RenderStage.Static)
// Runtime stage // Runtime stage
finalStageController.advanceStage(RenderStage.Runtime) finalStageController.advanceStage(RenderStage.Runtime)
return stream return stream
}, },
(stream) => { (stream) => {
throwIfInvalidDynamic(/* expected stage */ RenderStage.Runtime)
// Dynamic stage // Dynamic stage
finalStageController.advanceStage(RenderStage.Dynamic) finalStageController.advanceStage(RenderStage.Dynamic)
return stream return stream
......
...@@ -23,10 +23,10 @@ ...@@ -23,10 +23,10 @@
import type { WorkStore } from '../app-render/work-async-storage.external' import type { WorkStore } from '../app-render/work-async-storage.external'
import type { import type {
WorkUnitStore, WorkUnitStore,
RequestStore,
PrerenderStoreLegacy, PrerenderStoreLegacy,
PrerenderStoreModern, PrerenderStoreModern,
PrerenderStoreModernRuntime, PrerenderStoreModernRuntime,
DevRequestStoreModern,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly // Once postpone is in stable we should switch to importing the postpone export directly
...@@ -296,14 +296,18 @@ export function abortOnSynchronousPlatformIOAccess( ...@@ -296,14 +296,18 @@ export function abortOnSynchronousPlatformIOAccess(
} }
export function trackSynchronousPlatformIOAccessInDev( export function trackSynchronousPlatformIOAccessInDev(
requestStore: RequestStore requestStore: DevRequestStoreModern,
errorWithStack: Error
): void { ): void {
const { stagedRendering, dynamicTracking } = requestStore
// We don't actually have a controller to abort but we do the semantic equivalent by // We don't actually have a controller to abort but we do the semantic equivalent by
// advancing the request store out of the prerender stage // advancing the request store out of the prerender stage
if (requestStore.stagedRendering) {
// TODO: error for sync IO in the runtime stage // TODO: error for sync IO in the runtime stage
// (which is not currently covered by the validation render in `spawnDynamicValidationInDev`) // (which is not currently covered by the validation render in `spawnDynamicValidationInDev`)
requestStore.stagedRendering.advanceStage(RenderStage.Dynamic) stagedRendering.advanceStage(RenderStage.Dynamic)
if (dynamicTracking.syncDynamicErrorWithStack === null) {
dynamicTracking.syncDynamicErrorWithStack = errorWithStack
} }
} }
......
...@@ -71,6 +71,7 @@ export type RequestStore = ProdRequestStore | DevRequestStore ...@@ -71,6 +71,7 @@ export type RequestStore = ProdRequestStore | DevRequestStore
export type ProdRequestStore = BaseRequestStore & AllMissing<DevStore> export type ProdRequestStore = BaseRequestStore & AllMissing<DevStore>
export type DevRequestStore = BaseRequestStore & DevStore export type DevRequestStore = BaseRequestStore & DevStore
export type DevRequestStoreModern = BaseRequestStore & DevStoreModern
// If `cacheComponents` is enabled, we add multiple extra properties on the store. // If `cacheComponents` is enabled, we add multiple extra properties on the store.
// We either want all of them to be present, or all of them to be undefined. // We either want all of them to be present, or all of them to be undefined.
...@@ -90,6 +91,8 @@ type DevStoreCommon = { ...@@ -90,6 +91,8 @@ type DevStoreCommon = {
export type DevStoreModernPartial = { export type DevStoreModernPartial = {
readonly stagedRendering: StagedRenderingController readonly stagedRendering: StagedRenderingController
readonly asyncApiPromises: DevAsyncApiPromises readonly asyncApiPromises: DevAsyncApiPromises
readonly captureOwnerStack: () => string | null
readonly dynamicTracking: DynamicTrackingState
} & ( } & (
| { | {
// In the initial render, we track and fill caches // In the initial render, we track and fill caches
......
...@@ -263,7 +263,7 @@ function createRequestStoreImpl( ...@@ -263,7 +263,7 @@ function createRequestStoreImpl(
serverComponentsHmrCache: serverComponentsHmrCache:
serverComponentsHmrCache || serverComponentsHmrCache ||
(globalThis as any).__serverComponentsHmrCache, (globalThis as any).__serverComponentsHmrCache,
devFallbackParams, devFallbackParams: devFallbackParams ?? null,
} }
} }
......
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { import {
workUnitAsyncStorage, workUnitAsyncStorage,
type DevRequestStoreModern,
type PrerenderStoreModern, type PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
...@@ -87,7 +88,31 @@ export function io(expression: string, type: ApiType) { ...@@ -87,7 +88,31 @@ export function io(expression: string, type: ApiType) {
} }
case 'request': case 'request':
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
trackSynchronousPlatformIOAccessInDev(workUnitStore) if (workUnitStore.stagedRendering) {
// If the prerender signal is already aborted we don't need to construct
// any stacks because something else actually terminated the prerender.
let message: string
switch (type) {
case 'time':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or \`connection()\`. 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`
break
case 'random':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or \`connection()\`. Accessing random values synchronously 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-random`
break
case 'crypto':
message = `Route "${workStore.route}" used ${expression} before accessing either uncached data (e.g. \`fetch()\`) or \`connection()\`. Accessing random cryptographic values synchronously 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-crypto`
break
default:
throw new InvariantError(
'Unknown expression type in abortOnSynchronousPlatformIOAccess.'
)
}
trackSynchronousPlatformIOAccessInDev(
workUnitStore,
applyOwnerStack(new Error(message), workUnitStore)
)
}
} }
break break
case 'prerender-ppr': case 'prerender-ppr':
...@@ -101,7 +126,10 @@ export function io(expression: string, type: ApiType) { ...@@ -101,7 +126,10 @@ export function io(expression: string, type: ApiType) {
} }
} }
function applyOwnerStack(error: Error, workUnitStore: PrerenderStoreModern) { function applyOwnerStack(
error: Error,
workUnitStore: PrerenderStoreModern | DevRequestStoreModern
) {
// TODO: Instead of stitching the stacks here, we should log the original // TODO: Instead of stitching the stacks here, we should log the original
// error as-is when it occurs, and let `patchErrorInspect` handle adding the // error as-is when it occurs, and let `patchErrorInspect` handle adding the
// owner stack, instead of logging it deferred in the `LogSafely` component // owner stack, instead of logging it deferred in the `LogSafely` component
......
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