Unverified Commit 5bf4f831 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

refactor: clean up places that needlessly list all RenderStages (#96907)

pure refactor, no behavioral changes are expected. removes a couple of
places that we had to touch when we add/remove stages:

- `AccumulatedStreamChunks` unnecessarily used names like
`staticChunks`/`runtimeChunks`/... instead of just using
`RenderStage.Static`/`RenderStage.Runtime`/... like we do elsewhere
- `collectStageChunk` had to do a switch over stages to map
`RenderStage.Static` to `staticChunks` etc. after removing this, we can
replace the switch with a loop over `RENDER_STAGE_ADVANCE_ORDER`
- in `StagedRenderingController`, we were unnecessarily listing out all
the stages when initializing `triggers`. replaced with a loop over
`RENDER_STAGE_ADVANCE_ORDER`
- in `StagedRenderingController.shouldTrackSyncInterrupt`, using a range
of stages is a better way to express intent than a `switch`
parent 116eb73c
...@@ -6057,22 +6057,14 @@ async function stagedRenderWithCachesInDev({ ...@@ -6057,22 +6057,14 @@ async function stagedRenderWithCachesInDev({
} }
} }
interface AccumulatedStreamChunks { type AccumulatedStreamChunks = Record<AdvanceableRenderStage, Array<Uint8Array>>
readonly shellStaticChunks: Array<Uint8Array>
readonly staticChunks: Array<Uint8Array>
readonly shellRuntimeChunks: Array<Uint8Array>
readonly runtimeChunks: Array<Uint8Array>
readonly dynamicChunks: Array<Uint8Array>
}
function createStageChunksAccumulator(): AccumulatedStreamChunks { function createStageChunksAccumulator(): AccumulatedStreamChunks {
return { const result: Partial<AccumulatedStreamChunks> = {}
shellStaticChunks: [], for (const stage of RENDER_STAGE_ADVANCE_ORDER) {
staticChunks: [], result[stage] = []
shellRuntimeChunks: [],
runtimeChunks: [],
dynamicChunks: [],
} }
return result as AccumulatedStreamChunks
} }
async function accumulateStreamChunks( async function accumulateStreamChunks(
...@@ -6152,33 +6144,22 @@ async function accumulateStreamChunksInto( ...@@ -6152,33 +6144,22 @@ async function accumulateStreamChunksInto(
function collectStageChunk( function collectStageChunk(
accumulator: AccumulatedStreamChunks, accumulator: AccumulatedStreamChunks,
stage: RenderStage, currentStage: RenderStage,
value: Uint8Array value: Uint8Array
): void { ): void {
switch (stage) { if (currentStage === RenderStage.Before) {
case RenderStage.Before:
throw new InvariantError('Unexpected stream chunk while in Before stage') throw new InvariantError('Unexpected stream chunk while in Before stage')
case RenderStage.ShellStatic: }
accumulator.shellStaticChunks.push(value) // Stage N+1 contains all the chunks of the stages 1..N,
// fall through // so add the chunk to the array for the current stage and all the stages that follow it.
case RenderStage.Static: // Starting at the end saves us from having to find the current stage in the order array.
accumulator.staticChunks.push(value) for (let i = RENDER_STAGE_ADVANCE_ORDER.length - 1; i >= 0; i--) {
// fall through const stage = RENDER_STAGE_ADVANCE_ORDER[i]
case RenderStage.ShellRuntime: if (stage < currentStage) {
accumulator.shellRuntimeChunks.push(value)
// fall through
case RenderStage.Runtime:
accumulator.runtimeChunks.push(value)
// fall through
case RenderStage.Dynamic:
accumulator.dynamicChunks.push(value)
break
case RenderStage.Abandoned:
break
default:
stage satisfies never
break break
} }
accumulator[stage].push(value)
}
} }
async function countShellAndStaticStageBytes( async function countShellAndStaticStageBytes(
...@@ -6717,8 +6698,7 @@ async function runValidationInDev( ...@@ -6717,8 +6698,7 @@ async function runValidationInDev(
{ {
// For warmup, we have to use the shared inputs if present -- the static inputs // For warmup, we have to use the shared inputs if present -- the static inputs
// may not have a proper dynamic stage. // may not have a proper dynamic stage.
const { runtimeChunks, dynamicChunks } = (instantInputs ?? staticInputs) const { accumulatedChunks } = instantInputs ?? staticInputs
.accumulatedChunks
// First we warmup SSR with the runtime chunks. This ensures that when we do // First we warmup SSR with the runtime chunks. This ensures that when we do
// the full prerender pass with dynamic tracking module loading won't // the full prerender pass with dynamic tracking module loading won't
...@@ -6728,8 +6708,10 @@ async function runValidationInDev( ...@@ -6728,8 +6708,10 @@ async function runValidationInDev(
// otherwise, for static shell validation, we only need to warm up to the runtime stage. // otherwise, for static shell validation, we only need to warm up to the runtime stage.
// we also need to use a different store type, because instant validation allows more APIs to resolve. // we also need to use a different store type, because instant validation allows more APIs to resolve.
needsInstantValidation ? 'validation-client' : 'prerender-client', needsInstantValidation ? 'validation-client' : 'prerender-client',
needsInstantValidation ? dynamicChunks : runtimeChunks, needsInstantValidation
dynamicChunks, ? accumulatedChunks[RenderStage.Dynamic]
: accumulatedChunks[RenderStage.Runtime],
accumulatedChunks[RenderStage.Dynamic],
rootParams, rootParams,
fallbackRouteParams, fallbackRouteParams,
ctx, ctx,
...@@ -6871,15 +6853,14 @@ async function validateStaticShell( ...@@ -6871,15 +6853,14 @@ async function validateStaticShell(
const loaderTree = ComponentMod.routeModule.userland.loaderTree const loaderTree = ComponentMod.routeModule.userland.loaderTree
const { accumulatedChunks, stageEndTimes } = inputs const { accumulatedChunks, stageEndTimes } = inputs
const { staticChunks, runtimeChunks, dynamicChunks } = accumulatedChunks
const allowEmptyStaticShell = const allowEmptyStaticShell =
(renderOpts.allowEmptyStaticShell ?? false) || (renderOpts.allowEmptyStaticShell ?? false) ||
(await isPageAllowedToBlock(loaderTree)) (await isPageAllowedToBlock(loaderTree))
const runtimeResult = await validateStagedShell( const runtimeResult = await validateStagedShell(
runtimeChunks, accumulatedChunks[RenderStage.Runtime],
dynamicChunks, accumulatedChunks[RenderStage.Dynamic],
debugChunks, debugChunks,
stageEndTimes[RenderStage.Runtime], stageEndTimes[RenderStage.Runtime],
rootParams, rootParams,
...@@ -6903,8 +6884,8 @@ async function validateStaticShell( ...@@ -6903,8 +6884,8 @@ async function validateStaticShell(
} }
const staticResult = await validateStagedShell( const staticResult = await validateStagedShell(
staticChunks, accumulatedChunks[RenderStage.Static],
dynamicChunks, accumulatedChunks[RenderStage.Dynamic],
debugChunks, debugChunks,
stageEndTimes[RenderStage.Static], stageEndTimes[RenderStage.Static],
rootParams, rootParams,
...@@ -7328,12 +7309,7 @@ async function validateInstantConfigs( ...@@ -7328,12 +7309,7 @@ async function validateInstantConfigs(
prefetchKind, prefetchKind,
ctx.componentMod, ctx.componentMod,
renderFlightStream, renderFlightStream,
{ accumulatedChunks,
[RenderStage.Static]: accumulatedChunks.staticChunks,
[RenderStage.ShellRuntime]: accumulatedChunks.shellRuntimeChunks,
[RenderStage.Runtime]: accumulatedChunks.runtimeChunks,
[RenderStage.Dynamic]: accumulatedChunks.dynamicChunks,
},
debugChunks, debugChunks,
startTime, startTime,
stageEndTimes, stageEndTimes,
...@@ -8334,8 +8310,8 @@ async function validateInstantConfigInBuildWithSample( ...@@ -8334,8 +8310,8 @@ async function validateInstantConfigInBuildWithSample(
const validationRenderCtx = toValidationRenderContext(validationCtx) const validationRenderCtx = toValidationRenderContext(validationCtx)
await warmupClientModulesForStagedValidation( await warmupClientModulesForStagedValidation(
'validation-client', 'validation-client',
accumulatedChunks.dynamicChunks, accumulatedChunks[RenderStage.Dynamic],
accumulatedChunks.dynamicChunks, accumulatedChunks[RenderStage.Dynamic],
sampleRootParams, sampleRootParams,
fallbackRouteParams, fallbackRouteParams,
validationRenderCtx, validationRenderCtx,
...@@ -9218,8 +9194,8 @@ async function prerenderToStream( ...@@ -9218,8 +9194,8 @@ async function prerenderToStream(
// NOTE: we must capture this *before* resolving staleTime/varyParams, // NOTE: we must capture this *before* resolving staleTime/varyParams,
// which always emit new static chunks. // which always emit new static chunks.
didLinkDataUnblockNewContent = didLinkDataUnblockNewContent =
collectedChunksByStage.staticChunks.length > collectedChunksByStage[RenderStage.Static].length >
collectedChunksByStage.shellStaticChunks.length collectedChunksByStage[RenderStage.ShellStatic].length
// Now that the prerendering is complete, we know the final stale // Now that the prerendering is complete, we know the final stale
// time and vary params. Close the stale time iterable and resolve // time and vary params. Close the stale time iterable and resolve
...@@ -9237,7 +9213,7 @@ async function prerenderToStream( ...@@ -9237,7 +9213,7 @@ async function prerenderToStream(
shellByteLengthDeferred.resolve( shellByteLengthDeferred.resolve(
didLinkDataUnblockNewContent didLinkDataUnblockNewContent
? collectedChunksByStage.shellStaticChunks.reduce( ? collectedChunksByStage[RenderStage.ShellStatic].reduce(
(acc, chunk) => acc + chunk.byteLength, (acc, chunk) => acc + chunk.byteLength,
0 0
) )
......
...@@ -5,6 +5,7 @@ import type { PrefetchingMode } from './app-render' ...@@ -5,6 +5,7 @@ import type { PrefetchingMode } from './app-render'
import type { NextConfigComplete, ValidationLevel } from '../config-shared' import type { NextConfigComplete, ValidationLevel } from '../config-shared'
import type { ImageConfigComplete } from '../../shared/lib/image-config' import type { ImageConfigComplete } from '../../shared/lib/image-config'
import type { StageEndTimes } from './instant-validation/instant-validation' import type { StageEndTimes } from './instant-validation/instant-validation'
import type { AdvanceableRenderStage } from './staged-rendering'
/** /**
* Cross-module handoff for the dev validation worker (client-module warmup, * Cross-module handoff for the dev validation worker (client-module warmup,
...@@ -22,13 +23,10 @@ const SYMBOL: unique symbol = Symbol.for('next.dev.validationWorker') ...@@ -22,13 +23,10 @@ const SYMBOL: unique symbol = Symbol.for('next.dev.validationWorker')
* Per-stage RSC chunks, the serializable form of `AccumulatedStreamChunks` that * Per-stage RSC chunks, the serializable form of `AccumulatedStreamChunks` that
* the worker replays. No live streams cross the boundary. * the worker replays. No live streams cross the boundary.
*/ */
export interface SerializedAccumulatedChunks { export type SerializedAccumulatedChunks = Record<
shellStaticChunks: Uint8Array[] AdvanceableRenderStage,
staticChunks: Uint8Array[] Uint8Array[]
shellRuntimeChunks: Uint8Array[] >
runtimeChunks: Uint8Array[]
dynamicChunks: Uint8Array[]
}
/** /**
* Serializable view of one validation input (the shape `DevValidationInputs` * Serializable view of one validation input (the shape `DevValidationInputs`
......
...@@ -63,15 +63,8 @@ export class StagedRenderingController { ...@@ -63,15 +63,8 @@ export class StagedRenderingController {
syncInterruptReason: Error | null = null syncInterruptReason: Error | null = null
triggers: Record<AdvanceableRenderStage, StageTrigger> = { triggers: Record<AdvanceableRenderStage, StageTrigger> =
[RenderStage.ShellStatic]: createStageTrigger(), createAdvanceableStageTriggers()
[RenderStage.Static]: createStageTrigger(),
//
[RenderStage.ShellRuntime]: createStageTrigger(),
[RenderStage.Runtime]: createStageTrigger(),
//
[RenderStage.Dynamic]: createStageTrigger(),
}
constructor({ constructor({
abortSignal, abortSignal,
...@@ -120,36 +113,29 @@ export class StagedRenderingController { ...@@ -120,36 +113,29 @@ export class StagedRenderingController {
} }
shouldTrackSyncInterrupt(): boolean { shouldTrackSyncInterrupt(): boolean {
if (this.syncIOMode === SyncIOMode.Untracked) { const { syncIOMode, currentStage } = this
switch (syncIOMode) {
case SyncIOMode.Untracked: {
return false return false
} }
switch (this.currentStage) {
case RenderStage.Before:
// If we haven't started the render yet, it can't be interrupted.
return false
case RenderStage.ShellStatic:
case RenderStage.Static:
return true
case RenderStage.ShellRuntime:
case RenderStage.Runtime: {
switch (this.syncIOMode) {
case SyncIOMode.AllowedInRuntimeOrDynamic: { case SyncIOMode.AllowedInRuntimeOrDynamic: {
// Before `partialPrefetching`: Sync IO only errors in static stages. // Legacy: track Sync IO only in static stages.
return false // Do not track it before the render, or in runtime/dynamic stages.
return (
currentStage > RenderStage.Before &&
currentStage <= RenderStage.Static
)
} }
case SyncIOMode.AllowedInDynamic: { case SyncIOMode.AllowedInDynamic: {
return true // Track sync IO in all cacheable stages.
} // This means all stages except:
} // - before the render
// NOT a fallthrough, but eslint doesn't understand that // - in the dynamic stage
return (
currentStage > RenderStage.Before &&
currentStage < RenderStage.Dynamic
)
} }
case RenderStage.Dynamic:
case RenderStage.Abandoned:
return false
default:
this.currentStage satisfies never
return false
} }
} }
...@@ -307,6 +293,17 @@ export class StagedRenderingController { ...@@ -307,6 +293,17 @@ export class StagedRenderingController {
} }
} }
function createAdvanceableStageTriggers(): Record<
AdvanceableRenderStage,
StageTrigger
> {
const triggers: Partial<Record<AdvanceableRenderStage, StageTrigger>> = {}
for (const stage of RENDER_STAGE_ADVANCE_ORDER) {
triggers[stage] = createStageTrigger()
}
return triggers as Record<AdvanceableRenderStage, StageTrigger>
}
function ignoreReject() {} function ignoreReject() {}
// TODO(restart-on-cache-miss): the layering of `delayUntilStage`, // TODO(restart-on-cache-miss): the layering of `delayUntilStage`,
......
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