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