Unverified Commit 380f0946 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refine development validation signal handling (#95998)

## Summary

This follow-up addresses the remaining review comments from #95939.

Pass the complete development validation generation through the
background-validation lifecycle so cleanup invokes its finish method on
the owning object.

Make validation signals required throughout the development-only call
chain and remove redundant optional checks, while preserving optional
signals in helpers shared with build-time validation.

## Verification

- pnpm exec jest --runTestsByPath
packages/next/src/server/app-render/dev-validation-scheduler.test.ts
packages/next/src/server/app-render/wait-for-response.test.ts
- NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-turbo
test/development/app-dir/instant-validation-scheduling/instant-validation-scheduling.test.ts
- NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-webpack
test/development/app-dir/instant-validation-scheduling/instant-validation-scheduling.test.ts

<!-- NEXT_JS_LLM -->
parent 3b7946d0
...@@ -181,6 +181,7 @@ import { isNodeNextRequest, isNodeNextResponse } from '../base-http/helpers' ...@@ -181,6 +181,7 @@ import { isNodeNextRequest, isNodeNextResponse } from '../base-http/helpers'
import { waitForResponseToFinish } from './wait-for-response' import { waitForResponseToFinish } from './wait-for-response'
import { import {
beginDevValidation, beginDevValidation,
type DevValidationGeneration,
yieldToForegroundRequest, yieldToForegroundRequest,
} from './dev-validation-scheduler' } from './dev-validation-scheduler'
import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request' import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'
...@@ -4433,9 +4434,10 @@ function runDevValidationInBackground( ...@@ -4433,9 +4434,10 @@ function runDevValidationInBackground(
createRequestStore: () => RequestStore, createRequestStore: () => RequestStore,
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>, getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void, onError: (error: unknown) => void,
validationAbortSignal: AbortSignal, validationGeneration: DevValidationGeneration
onSettled: () => void
): void { ): void {
const validationAbortSignal = validationGeneration.signal
void consoleAsyncStorage void consoleAsyncStorage
.run({ dim: true }, async () => { .run({ dim: true }, async () => {
const result = await resultPromise const result = await resultPromise
...@@ -4444,7 +4446,7 @@ function runDevValidationInBackground( ...@@ -4444,7 +4446,7 @@ function runDevValidationInBackground(
// validation, re-rendering and analyzing it would only waste server // validation, re-rendering and analyzing it would only waste server
// work. In-flight `'use cache'` fills are left running (we don't await // work. In-flight `'use cache'` fills are left running (we don't await
// `cacheReady` below). // `cacheReady` below).
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
logValidationAborted(ctx) logValidationAborted(ctx)
return return
} }
...@@ -4478,7 +4480,7 @@ function runDevValidationInBackground( ...@@ -4478,7 +4480,7 @@ function runDevValidationInBackground(
await cacheSignal.cacheReady() await cacheSignal.cacheReady()
} }
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
logValidationAborted(ctx) logValidationAborted(ctx)
return return
} }
...@@ -4529,7 +4531,7 @@ function runDevValidationInBackground( ...@@ -4529,7 +4531,7 @@ function runDevValidationInBackground(
// A newer render may have superseded this work while we prepared the // A newer render may have superseded this work while we prepared the
// validation inputs above (which can itself render). // validation inputs above (which can itself render).
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
logValidationAborted(ctx) logValidationAborted(ctx)
return return
} }
...@@ -4549,7 +4551,7 @@ function runDevValidationInBackground( ...@@ -4549,7 +4551,7 @@ function runDevValidationInBackground(
.catch((err) => { .catch((err) => {
// Superseded validation is intentionally torn down. Don't log errors // Superseded validation is intentionally torn down. Don't log errors
// caused by its abort signal. // caused by its abort signal.
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
return return
} }
console.error( console.error(
...@@ -4558,7 +4560,7 @@ function runDevValidationInBackground( ...@@ -4558,7 +4560,7 @@ function runDevValidationInBackground(
}) })
) )
}) })
.finally(onSettled) .finally(() => validationGeneration.finish())
} }
/** /**
...@@ -4617,7 +4619,7 @@ async function prepareValidationInputs( ...@@ -4617,7 +4619,7 @@ async function prepareValidationInputs(
createRequestStore: () => RequestStore, createRequestStore: () => RequestStore,
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>, getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void, onError: (error: unknown) => void,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<PrepareValidationInputsResult> { ): Promise<PrepareValidationInputsResult> {
// Check if we can re-use the main render for validation. // Check if we can re-use the main render for validation.
let inputsFromNavigation: DevValidationInputs | null let inputsFromNavigation: DevValidationInputs | null
...@@ -4671,7 +4673,7 @@ async function prepareValidationInputsInPartialPrefetching( ...@@ -4671,7 +4673,7 @@ async function prepareValidationInputsInPartialPrefetching(
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>, getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void, onError: (error: unknown) => void,
inputsFromNavigation: DevValidationInputs | null, inputsFromNavigation: DevValidationInputs | null,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<PrepareValidationInputsResult> { ): Promise<PrepareValidationInputsResult> {
const loaderTree = ctx.componentMod.routeModule.userland.loaderTree const loaderTree = ctx.componentMod.routeModule.userland.loaderTree
const needsInstantValidation = const needsInstantValidation =
...@@ -4765,7 +4767,7 @@ async function prepareValidationInputsInLegacyPrefetching( ...@@ -4765,7 +4767,7 @@ async function prepareValidationInputsInLegacyPrefetching(
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>, getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void, onError: (error: unknown) => void,
inputsFromNavigation: DevValidationInputs | null, inputsFromNavigation: DevValidationInputs | null,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<PrepareValidationInputsResult> { ): Promise<PrepareValidationInputsResult> {
const loaderTree = ctx.componentMod.routeModule.userland.loaderTree const loaderTree = ctx.componentMod.routeModule.userland.loaderTree
const needsInstantValidation = const needsInstantValidation =
...@@ -5268,7 +5270,7 @@ async function renderWithWarmCachesForValidationInDev( ...@@ -5268,7 +5270,7 @@ async function renderWithWarmCachesForValidationInDev(
prerenderResumeDataCache: ReturnType<typeof createPrerenderResumeDataCache>, prerenderResumeDataCache: ReturnType<typeof createPrerenderResumeDataCache>,
prefetchMode: PrefetchingMode, prefetchMode: PrefetchingMode,
shouldRenderWithAppShell: boolean, shouldRenderWithAppShell: boolean,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<DevValidationInputs> { ): Promise<DevValidationInputs> {
const { ComponentMod, setReactDebugChannel } = ctx.renderOpts const { ComponentMod, setReactDebugChannel } = ctx.renderOpts
const { clientModules } = getClientReferenceManifest() const { clientModules } = getClientReferenceManifest()
...@@ -5325,7 +5327,7 @@ async function renderWithWarmCachesForValidationInDev( ...@@ -5325,7 +5327,7 @@ async function renderWithWarmCachesForValidationInDev(
return accumulateStreamChunks( return accumulateStreamChunks(
sourceStream, sourceStream,
stageController, stageController,
validationAbortSignal ?? null validationAbortSignal
) )
}, },
() => stageController.advanceStage(RenderStage.Static), () => stageController.advanceStage(RenderStage.Static),
...@@ -5359,7 +5361,7 @@ async function prerenderWithWarmCachesForStaticValidationInDev( ...@@ -5359,7 +5361,7 @@ async function prerenderWithWarmCachesForStaticValidationInDev(
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>, getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void, onError: (error: unknown) => void,
prerenderResumeDataCache: ReturnType<typeof createPrerenderResumeDataCache>, prerenderResumeDataCache: ReturnType<typeof createPrerenderResumeDataCache>,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<DevValidationInputs> { ): Promise<DevValidationInputs> {
// This function is currently only used in partialPrefetching. // This function is currently only used in partialPrefetching.
const prefetchMode = PrefetchingMode.Partial const prefetchMode = PrefetchingMode.Partial
...@@ -5373,9 +5375,7 @@ async function prerenderWithWarmCachesForStaticValidationInDev( ...@@ -5373,9 +5375,7 @@ async function prerenderWithWarmCachesForStaticValidationInDev(
const finalReactController = new AbortController() const finalReactController = new AbortController()
const finalDataController = new AbortController() const finalDataController = new AbortController()
if (validationAbortSignal) { abortWhenSignalAborts(validationAbortSignal, finalReactController)
abortWhenSignalAborts(validationAbortSignal, finalReactController)
}
const stageController = new StagedRenderingController({ const stageController = new StagedRenderingController({
abortSignal: finalDataController.signal, abortSignal: finalDataController.signal,
...@@ -5596,8 +5596,7 @@ async function stagedRenderWithCachesInDev({ ...@@ -5596,8 +5596,7 @@ async function stagedRenderWithCachesInDev({
createRequestStore, createRequestStore,
getPayload, getPayload,
onError, onError,
validationGeneration.signal, validationGeneration
validationGeneration.finish
) )
validationWasScheduled = true validationWasScheduled = true
} else { } else {
...@@ -6001,14 +6000,13 @@ async function runValidationInDev( ...@@ -6001,14 +6000,13 @@ async function runValidationInDev(
'</VALIDATION_MESSAGE>' '</VALIDATION_MESSAGE>'
) )
try { try {
const validationAbortSignal: AbortSignal | undefined = args[6] const validationAbortSignal: AbortSignal = args[6]
// Keep validation in flight for scheduler E2E tests without relying on // Keep validation in flight for scheduler E2E tests without relying on
// timing-sensitive user code. Aborts end the delay immediately. // timing-sensitive user code. Aborts end the delay immediately.
const validationDelay = Number( const validationDelay = Number(
process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS
) )
if ( if (
validationAbortSignal !== undefined &&
Number.isFinite(validationDelay) && Number.isFinite(validationDelay) &&
validationDelay > 0 && validationDelay > 0 &&
!validationAbortSignal.aborted !validationAbortSignal.aborted
...@@ -6027,13 +6025,13 @@ async function runValidationInDev( ...@@ -6027,13 +6025,13 @@ async function runValidationInDev(
}) })
} }
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
return return
} }
return await runValidationInDevImpl(...args) return await runValidationInDevImpl(...args)
} finally { } finally {
const validationAbortSignal: AbortSignal | undefined = args[6] const validationAbortSignal: AbortSignal = args[6]
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
logValidationAborted(ctx) logValidationAborted(ctx)
} else { } else {
console.log( console.log(
...@@ -6061,7 +6059,7 @@ async function runValidationInDevImpl( ...@@ -6061,7 +6059,7 @@ async function runValidationInDevImpl(
ctx: AppRenderContext, ctx: AppRenderContext,
fallbackRouteParams: OpaqueFallbackRouteParams | null, fallbackRouteParams: OpaqueFallbackRouteParams | null,
devRenderDidError: boolean, devRenderDidError: boolean,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<void> { ): Promise<void> {
const { componentMod: ComponentMod, getDynamicParamFromSegment } = ctx const { componentMod: ComponentMod, getDynamicParamFromSegment } = ctx
const loaderTree = ComponentMod.routeModule.userland.loaderTree const loaderTree = ComponentMod.routeModule.userland.loaderTree
...@@ -6130,7 +6128,7 @@ async function runValidationInDevImpl( ...@@ -6130,7 +6128,7 @@ async function runValidationInDevImpl(
//================================ //================================
{ {
// The request may have been aborted during the client module warmup above. // The request may have been aborted during the client module warmup above.
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
return return
} }
...@@ -6152,7 +6150,7 @@ async function runValidationInDevImpl( ...@@ -6152,7 +6150,7 @@ async function runValidationInDevImpl(
) )
// A newer render superseded this validation while its render ran, so its // A newer render superseded this validation while its render ran, so its
// result is stale. Don't surface errors for a page the user left. // result is stale. Don't surface errors for a page the user left.
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
return return
} }
if (result.length > 0) { if (result.length > 0) {
...@@ -6194,7 +6192,7 @@ async function runValidationInDevImpl( ...@@ -6194,7 +6192,7 @@ async function runValidationInDevImpl(
// A newer render superseded this work. Don't surface stale validation // A newer render superseded this work. Don't surface stale validation
// errors for a page the user left. // errors for a page the user left.
if (validationAbortSignal?.aborted) { if (validationAbortSignal.aborted) {
return return
} }
if (result.length > 0) { if (result.length > 0) {
...@@ -6221,7 +6219,7 @@ async function validateStaticShell( ...@@ -6221,7 +6219,7 @@ async function validateStaticShell(
fallbackRouteParams: OpaqueFallbackRouteParams | null, fallbackRouteParams: OpaqueFallbackRouteParams | null,
debugChunks: Uint8Array[] | null, debugChunks: Uint8Array[] | null,
hmrRefreshHash: string | undefined, hmrRefreshHash: string | undefined,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<unknown[]> { ): Promise<unknown[]> {
const debug = const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
...@@ -6479,7 +6477,7 @@ async function validateStagedShell( ...@@ -6479,7 +6477,7 @@ async function validateStagedShell(
trackDynamicHole: trackDynamicHole:
| typeof trackDynamicHoleInStaticShell | typeof trackDynamicHoleInStaticShell
| typeof trackDynamicHoleInRuntimeShell, | typeof trackDynamicHoleInRuntimeShell,
validationAbortSignal: AbortSignal | undefined validationAbortSignal: AbortSignal
): Promise<Array<unknown>> { ): Promise<Array<unknown>> {
const { implicitTags, nonce, workStore } = ctx const { implicitTags, nonce, workStore } = ctx
...@@ -6488,10 +6486,10 @@ async function validateStagedShell( ...@@ -6488,10 +6486,10 @@ async function validateStagedShell(
) )
const clientReactController = new AbortController() const clientReactController = new AbortController()
const clientRenderController = new AbortController() const clientRenderController = new AbortController()
const clientReactSignal = const clientReactSignal = AbortSignal.any([
validationAbortSignal === undefined clientReactController.signal,
? clientReactController.signal validationAbortSignal,
: AbortSignal.any([clientReactController.signal, validationAbortSignal]) ])
const preinitScripts = () => {} const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML() const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
......
...@@ -84,12 +84,12 @@ export function beginDevValidation( ...@@ -84,12 +84,12 @@ export function beginDevValidation(
* actually pass through the event-loop poll phase where HTTP requests arrive. * actually pass through the event-loop poll phase where HTTP requests arrive.
*/ */
export async function yieldToForegroundRequest( export async function yieldToForegroundRequest(
validationSignal: AbortSignal | undefined validationSignal: AbortSignal
): Promise<boolean> { ): Promise<boolean> {
if (validationSignal?.aborted) { if (validationSignal.aborted) {
return false return false
} }
await new Promise<void>((resolve) => unpatchedSetImmediate(resolve)) await new Promise<void>((resolve) => unpatchedSetImmediate(resolve))
return validationSignal?.aborted !== true return !validationSignal.aborted
} }
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