Unverified Commit 34fdbdcc authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Prefetch scheduler mirrors the navigation's tree walk (#98975)

The prefetch scheduler's static walk decided at the parent which child
was still part of the current page and which began the new part of the
route, and it fetched the head through two functions of its own that
copied the per-segment decision (a static attempt, then a runtime deopt
if that wasn't enough) for a node that hangs off the route root instead
of sitting in the tree.

Give the walk the same shape as the navigation's. The walk over the part
of the route the current page also has owns the comparison for its own
node — first whether the route position still matches, then whether any
of its params changed — and hands off to the walk over the new part of
the route when either fails, so the root enters the shared walk like
every other node. The per-segment decision, a static attempt or a
runtime deopt, lives in one function that the new-part walk calls for
every segment, and the runtime request's walk gets the same split
between iterating the children and deciding for one node.

The head is a one-node route tree like any other segment now, so it goes
through the same functions: the new-part static walk and the direct
runtime fetch it already had.

This is a pure restructuring and issues the same requests as before: a
segment the navigation keeps is still prefetched at the ordinary static
tier without a runtime deopt, the head is still fetched whenever
anything is, and a chain of inlined segments is still dropped where a
Shell-phase walk crosses from a kept node into the new part. A later
change uses the shape to prefetch only what the navigation would fetch.
parent b3512c2e
......@@ -3242,8 +3242,9 @@ function writeServerResponseIntoCache(
? now + getStaleTimeMs(headData.staleTimeSeconds)
: staleAt
// A head has no loading boundary. Match pingRuntimeHead, which spawns
// LoadingBoundary head entries using the concrete Full strategy.
// A head has no loading boundary. Match the scheduler, which spawns
// LoadingBoundary head entries using the concrete Full strategy (see the
// head's runtime fetch in pingRootRouteTree).
const headFetchStrategy =
fetchStrategy === FetchStrategy.LoadingBoundary
? FetchStrategy.Full
......
......@@ -44,10 +44,7 @@ import {
} from './cache'
import type { CacheMap } from './cache-map'
import type { NavigationLockPrefetch } from './navigation-testing-lock'
import {
HEAD_REQUEST_KEY,
type SegmentRequestKey,
} from '../../../shared/lib/segment-cache/segment-value-encoding'
import type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'
import { cleanup } from './lru'
const scheduleMicrotask =
......@@ -917,7 +914,36 @@ function pingRootRouteTree(
return PrefetchTaskExitStatus.Done
}
pingStaticHead(now, task, route, staticWalkStrategy)
// The head is a one-node tree beside the route tree (see
// createMetadataRouteTree in cache.ts); it takes the same walk as
// a segment the current page doesn't have. If the head was inlined
// into a page's bundle (HeadOutlined is NOT set on the root), skip
// the standalone walk — the head data will arrive as part of that
// page's response, and its runtime-completeness signal is carried
// by that page's own entries.
const head = route.root.head
if (
!process.env.__NEXT_PREFETCH_INLINING ||
(route.root.tree.prefetchHints & PrefetchHint.HeadOutlined) !== 0 ||
// An inlined head that can't attempt a static fetch still deopts
// to the runtime request (the first check of the decision point
// in pingSegmentInCacheComponentsTree); only the static fetch
// itself is skipped for an inlined head.
(walkCanUseRuntimeRequests(staticWalkStrategy, route) &&
!shouldSegmentAttemptStaticRequest(staticWalkStrategy, head))
) {
const headExitStatus = pingNewPartOfCacheComponentsTree(
now,
task,
route,
head,
null,
staticWalkStrategy
)
if (headExitStatus === PrefetchTaskExitStatus.InProgress) {
return PrefetchTaskExitStatus.InProgress
}
}
const exitStatus = pingSharedPartOfCacheComponentsTree(
now,
......@@ -933,7 +959,7 @@ function pingRootRouteTree(
return PrefetchTaskExitStatus.InProgress
}
// `pingNewPartOfCacheComponentsTree` may have determined that
// `pingSegmentInCacheComponentsTree` may have determined that
// we need to do a runtime prefetch for one or more segments.
// Bail out early if runtime prefetches are not permitted for this route.
if (walkCanUseRuntimeRequests(staticWalkStrategy, route)) {
......@@ -944,19 +970,32 @@ function pingRootRouteTree(
// spawnedRuntimePrefetches was populated during the traversal
// above: every subtree in the new part of the tree that needs a
// runtime prefetch — plus, during the Shell phase, the head, if
// its static attempt was insufficient (see above).
// runtime prefetch, the head included — it registers under its
// own request key, like any segment, when its own static attempt
// was insufficient or never happened.
//
// If it's null, nothing in the new part of the tree is a candidate
// for runtime prefetching, and we don't fetch the head, either —
// the head is runtime prefetched only if one of the segments is.
// the head is runtime prefetched only if something is.
const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches
if (spawnedRuntimePrefetches !== null) {
const spawnedEntries = new Map<
SegmentRequestKey,
PendingSegmentCacheEntry
>()
pingRuntimeHead(now, task, route, spawnedEntries, runtimeStrategy)
// The head has no position in the request tree — a runtime
// response carries it beside the segments (see
// writeServerResponseIntoCache in cache.ts) — so the head's
// own request tree is discarded.
pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
head,
false,
spawnedEntries,
runtimeStrategy
)
const requestTree = pingRuntimePrefetches(
now,
task,
......@@ -1002,7 +1041,24 @@ function pingRootRouteTree(
SegmentRequestKey,
PendingSegmentCacheEntry
>()
pingRuntimeHead(now, task, route, spawnedEntries, fetchStrategy)
// The head has no position in the request tree — a runtime response
// carries it beside the segments (see writeServerResponseIntoCache
// in cache.ts) — so the head's own request tree is discarded.
const head = route.root.head
pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
head,
false,
spawnedEntries,
// When prefetching the head, there's no difference between Full
// and LoadingBoundary: the head has no loading boundary, so a
// LoadingBoundary request would skip it.
fetchStrategy === FetchStrategy.LoadingBoundary
? FetchStrategy.Full
: fetchStrategy
)
const dynamicRequestTree = diffRouteTreeAgainstCurrent(
now,
task,
......@@ -1059,84 +1115,6 @@ type SegmentBundle = {
parent: SegmentBundle | null
}
/**
* Prefetches the Head data for a page (metadata, viewport). The Head is not
* really a route segment, in the sense that it doesn't appear in the route
* tree, but we store it in the cache as if it were, using a special key.
*
* Symmetric with the per-segment decision point in
* pingNewPartOfCacheComponentsTree: the head deopts to the runtime prefetch
* path either when it requires runtime completeness and no static attempt is
* happening, or when a fulfilled static head entry reported that a runtime
* request would return more content than the entry contains. Deopting
* registers the head under its wire request key, which makes the runtime
* gate in pingRootRouteTree fire even when every tree segment was
* sufficient; pingRuntimeHead performs the actual head work.
*/
function pingStaticHead(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
// The per-pass static walk strategy; see pingRootRouteTree where
// it's derived.
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): void {
const headCanUseRuntimeRequests = walkCanUseRuntimeRequests(
fetchStrategy,
route
)
if (
headCanUseRuntimeRequests &&
// The head is not a tree node — it hangs off the route root — so the
// static-attempt hints are read from the root's node. (Segments read the
// hints from their own node; see `pingNewPartOfCacheComponentsTree.`)
!shouldSegmentAttemptStaticRequest(fetchStrategy, route.root.tree)
) {
// No static attempt: the head arrives via the runtime request instead.
addSpawnedRuntimePrefetch(task, HEAD_REQUEST_KEY)
return
}
if (
// If the head was inlined into a page's bundle (HeadOutlined is NOT set
// on the root), skip the standalone fetch — the head data will arrive
// as part of that page's response, and its runtime-completeness signal
// is carried by that page's own entries.
process.env.__NEXT_PREFETCH_INLINING &&
!(route.root.tree.prefetchHints & PrefetchHint.HeadOutlined)
) {
return
}
const segments: SegmentBundle = {
tree: route.root.head,
entry: readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
route.root.head
),
parent: null,
}
const needsRuntimeRequest = pingSegmentBundle(
now,
task,
route,
task.key,
route.root.head,
segments,
fetchStrategy,
true
)
if (headCanUseRuntimeRequests && needsRuntimeRequest) {
// The static attempt was insufficient for the head. Deopt to a
// runtime prefetch. (Outside of runtime-completeness contexts the
// head's signal is unused — a partial static head is filled in by the
// navigation-time request, as with any other static segment.)
addSpawnedRuntimePrefetch(task, HEAD_REQUEST_KEY)
}
}
/**
* Whether the task can use runtime requests to prefetch the content.
*
......@@ -1280,8 +1258,9 @@ function isShellEntryEligibleForStaticAttempt(
}
/**
* Register a subtree root (or the head's wire key) for the batched
* runtime request issued by the gate at the end of pingRootRouteTree.
* Register a subtree root (the head is one, under its own request key) for
* the batched runtime request issued by the gate at the end of
* pingRootRouteTree.
*/
function addSpawnedRuntimePrefetch(
task: PrefetchTask,
......@@ -1294,62 +1273,85 @@ function addSpawnedRuntimePrefetch(
}
}
function pingRuntimeHead(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.Full
| FetchStrategy.PPRRuntime
| FetchStrategy.RuntimeShell
| FetchStrategy.LoadingBoundary
): void {
pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
route.root.head,
false,
spawnedEntries,
// When prefetching the head, there's no difference between Full
// and LoadingBoundary
fetchStrategy === FetchStrategy.LoadingBoundary
? FetchStrategy.Full
: fetchStrategy
)
}
// TODO: Rename dynamic -> runtime throughout this module
/**
* The static walk over the part of the target route that also exists on the
* current page: the current page's node and the target route's node at the
* same position in the tree. It mirrors the navigation's traversal order (see
* updateRenderTreeOnNavigation in render-tree.ts): first whether the route
* position still matches — if not, this node begins the new part of the route
* (pingNewPartOfCacheComponentsTree) — and then whether any of the node's
* param values changed — if so, the node and everything below it begin the
* new part of the route too. The walk does not consult which params a
* segment read, so it prefetches more than the navigation replaces: the
* navigation keeps data whose read params did not change and decides each
* descendant on its own. A node the walk keeps is prefetched at the ordinary
* static tier.
* Its children continue here wherever the current page has a child in the
* same slot; a child in a slot the current page doesn't have enters the new
* part of the route directly.
*
* Bundle chains must not cross the strategy boundary: a kept node walks at
* PPR while a Shell-phase new part walks at StaticShell, and a chain spanning
* both would fulfill the kept node's concrete-path entry with shell-variant
* data. Nor may the chain be finished by fetching the new-part node at PPR
* — that would prefetch new-part segments at the concrete tier during the
* Shell phase, which only the Speculative phase is allowed to do. So the
* chain is dropped wherever the walk hands off to the new part during a
* StaticShell walk, exactly like the drop sites in
* pingSegmentInCacheComponentsTree: nothing in a dropped chain was upgraded
* to Pending, so no entry is stranded, and the inlined kept data is fetched
* by the Speculative pass whenever its walk of the new part permits the
* child fetch.
*/
function pingSharedPartOfCacheComponentsTree(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
oldTree: RouteTree<CacheNode>,
currentTree: RouteTree<CacheNode>,
newTree: RouteTree<null>,
parentBundle: SegmentBundle | null,
// The per-pass static walk strategy; see pingRootRouteTree where
// it's derived.
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
// When Cache Components is enabled (or PPR, or a fully static route when PPR
// is disabled; those cases are treated equivalently to Cache Components), we
// start by prefetching each segment individually. Once we reach the "new"
// part of the tree — the part that doesn't exist on the current page — we
// may choose to switch to a runtime prefetch instead, based on the
// information sent by the server in the route tree.
//
// The traversal starts in the "shared" part of the tree. Once we reach the
// "new" part of the tree, we switch to a different traversal,
// pingNewPartOfCacheComponentsTree.
// The shared part of the tree always performs the ordinary static (PPR)
// prefetch, regardless of phase. Phase-specific strategies — the runtime
// shell request and the Shell phase's StaticShell walk — apply only to the
// new part of the tree, so the per-pass walk strategy is irrelevant here.
// (The needs-runtime signal is ignored: shared segments are already
// rendered on the current page, so a runtime prefetch has nothing to add.)
if (!doesRouteStructureMatch(currentTree, newTree)) {
// We're entering the part of the target route that doesn't exist on the
// current page.
return pingNewPartOfCacheComponentsTree(
now,
task,
route,
newTree,
fetchStrategy === FetchStrategy.StaticShell ? null : parentBundle,
fetchStrategy
)
}
if (
compareParams(currentTree.varyPath, newTree.varyPath) !== ParamsChange.None
) {
// A param changed. The navigation replaces only the data that read it and
// decides each descendant on its own (see updateRenderTreeOnNavigation in
// render-tree.ts); this walk doesn't know what each segment read, so it
// prefetches the whole subtree.
return pingNewPartOfCacheComponentsTree(
now,
task,
route,
newTree,
fetchStrategy === FetchStrategy.StaticShell ? null : parentBundle,
fetchStrategy
)
}
// The navigation keeps this segment's current data. A kept segment always
// performs the ordinary static (PPR) prefetch, regardless of phase.
// Phase-specific strategies — the runtime shell request and the Shell
// phase's StaticShell walk — apply only to the new part of the tree, so the
// per-pass walk strategy is irrelevant here. (The needs-runtime signal is
// ignored: kept segments are already rendered on the current page, so a
// runtime prefetch has nothing to add.)
const bundleInProgress = accumulateSegmentBundle(
now,
task,
......@@ -1360,16 +1362,16 @@ function pingSharedPartOfCacheComponentsTree(
true
).bundle
// Recursively ping the children.
const oldSlots = oldTree.slots
// Recursively ping the children, continuing in lockstep with the current
// page wherever it has a child in the same slot.
const newTreeChildren = newTree.slots
if (newTreeChildren !== null) {
const currentSlots = currentTree.slots
for (const [parallelRouteKey, newTreeChild] of newTreeChildren) {
if (!hasNetworkBandwidth(task)) {
// Stop prefetching segments until there's more bandwidth.
return PrefetchTaskExitStatus.InProgress
}
const oldTreeChild = oldSlots?.get(parallelRouteKey)
// Only pass the bundle to the child that accepts it. A parent is
// only ever bundled into one child.
const bundleForChild =
......@@ -1378,48 +1380,30 @@ function pingSharedPartOfCacheComponentsTree(
newTreeChild.prefetchHints & PrefetchHint.ParentInlinedIntoSelf
? bundleInProgress
: null
let childExitStatus
if (
oldTreeChild !== undefined &&
doesRouteStructureMatch(oldTreeChild, newTreeChild) &&
compareParams(oldTreeChild.varyPath, newTreeChild.varyPath) ===
ParamsChange.None
) {
// We're still in the "shared" part of the tree.
let currentTreeChild: RouteTree<CacheNode> | undefined = undefined
if (currentSlots !== null) {
currentTreeChild = currentSlots.get(parallelRouteKey)
}
let childExitStatus:
| PrefetchTaskExitStatus.InProgress
| PrefetchTaskExitStatus.Done
if (currentTreeChild !== undefined) {
childExitStatus = pingSharedPartOfCacheComponentsTree(
now,
task,
route,
oldTreeChild,
currentTreeChild,
newTreeChild,
bundleForChild,
fetchStrategy
)
} else {
// We've entered the "new" part of the tree. Switch
// traversal functions.
//
// Bundle chains must not cross the strategy boundary: the shared
// part walks at PPR while a Shell-phase new part walks at
// StaticShell, and a chain spanning both would fulfill the shared
// parent's concrete-path entry with shell-variant data. Nor may we
// finish the chain by fetching the new-part child at PPR here —
// that would prefetch new-part segments at the concrete tier
// during the Shell phase, which only the Speculative phase is
// allowed to do. So drop the bundle instead, exactly like the
// Speculative walk's subtree bail does when a chain crosses into a
// subtree it skips: nothing in a dropped chain was upgraded to
// Pending, so no entry is stranded, and the inlined shared data is
// fetched by the Speculative pass whenever its walk of the new
// part permits the child fetch.
const bundleForNewPart =
fetchStrategy === FetchStrategy.StaticShell ? null : bundleForChild
childExitStatus = pingNewPartOfCacheComponentsTree(
now,
task,
route,
newTreeChild,
bundleForNewPart,
fetchStrategy === FetchStrategy.StaticShell ? null : bundleForChild,
fetchStrategy
)
}
......@@ -1430,9 +1414,18 @@ function pingSharedPartOfCacheComponentsTree(
}
}
// The static attempt was sufficient for this segment (each child is its
// own decision point) — or parts of it are still in flight, in which case
// the task is blocked and the decision re-runs against the received
// responses.
return PrefetchTaskExitStatus.Done
}
/**
* The static walk over the part of the target route that doesn't exist on
* the current page. Nothing here is compared against the current tree: every
* segment goes through the per-segment decision point.
*/
function pingNewPartOfCacheComponentsTree(
now: number,
task: PrefetchTask,
......@@ -1443,33 +1436,104 @@ function pingNewPartOfCacheComponentsTree(
// it's derived.
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
// We're now prefetching in the "new" part of the tree, the part that
// doesn't exist on the current page. (In other words, we're deeper than
// the shared layouts.) Segments in here default to being prefetched
// statically, at the per-pass strategy derived in pingRootRouteTree.
//
// This is where we decide whether we should use runtime requests, if the walk
// is allowed to do so (see `walkCanUseRuntimeRequests`).
//
// If runtime requests are allowed, but the segment's node has one of the
// `ShouldAttemptStatic{Shell,Prefetch}` hints set (either because the build-time
// prerender accessed no runtime data, or because of `ensureStatic`), then its
// subtree should be prefetched statically first.
// However, the hint may be stale after a revalidation, so we'll also check the
// `needsRuntimeRequest` promise on the static response, and will follow up with
// a runtime request if needed.
// Pending responses block the task, so the attempt is serial, never raced:
// static attempt → observe → runtime (if needed).
//
// The static hints and `needsRuntimeRequest` have no effect if runtime requests
// are not allowed (i.e. outside of Partial Prefetching).
const accumulation = pingSegmentInCacheComponentsTree(
now,
task,
route,
tree,
parentBundle,
fetchStrategy
)
if (accumulation === null) {
return PrefetchTaskExitStatus.Done
}
const bundleInProgress = accumulation.bundle
// Recursively ping the children.
const treeChildren = tree.slots
if (treeChildren !== null) {
for (const treeChild of treeChildren.values()) {
if (!hasNetworkBandwidth(task)) {
// Stop prefetching segments until there's more bandwidth.
return PrefetchTaskExitStatus.InProgress
}
// Only pass the bundle to the child that accepts it. A parent is
// only ever bundled into one child.
const bundleForChild =
process.env.__NEXT_PREFETCH_INLINING &&
bundleInProgress !== null &&
treeChild.prefetchHints & PrefetchHint.ParentInlinedIntoSelf
? bundleInProgress
: null
const childExitStatus = pingNewPartOfCacheComponentsTree(
now,
task,
route,
treeChild,
bundleForChild,
fetchStrategy
)
if (childExitStatus === PrefetchTaskExitStatus.InProgress) {
// Child yielded without finishing.
return PrefetchTaskExitStatus.InProgress
}
}
}
// The static attempt was sufficient for this segment (each child is its
// own decision point) — or parts of it are still in flight, in which case
// the task is blocked and the decision re-runs against the received
// responses.
return PrefetchTaskExitStatus.Done
}
/**
* The per-segment decision point of the static walk: the one place that
* decides how a segment in the new part of the route — one the navigation
* won't keep — is prefetched (pingNewPartOfCacheComponentsTree).
*
* When Cache Components is enabled (or PPR, or a fully static route when PPR
* is disabled; those cases are treated equivalently to Cache Components), we
* prefetch each segment individually, statically, at the per-pass strategy
* derived in pingRootRouteTree.
*
* This is where we decide whether we should use runtime requests, if the walk
* is allowed to do so (see `walkCanUseRuntimeRequests`).
*
* If runtime requests are allowed, but the segment's node has one of the
* `ShouldAttemptStatic{Shell,Prefetch}` hints set (either because the build-time
* prerender accessed no runtime data, or because of `ensureStatic`), then its
* subtree should be prefetched statically first.
* However, the hint may be stale after a revalidation, so we'll also check the
* `needsRuntimeRequest` promise on the static response, and will follow up with
* a runtime request if needed.
* Pending responses block the task, so the attempt is serial, never raced:
* static attempt → observe → runtime (if needed).
*
* The static hints and `needsRuntimeRequest` have no effect if runtime requests
* are not allowed (i.e. outside of Partial Prefetching).
*
* Returns the segment's bundle accumulation when the walk should continue
* into its children, and null when the walk stops at this segment: the link
* needs no speculative prefetch, or the segment deopted and the batched
* runtime request covers the whole subtree.
*/
function pingSegmentInCacheComponentsTree(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
tree: RouteTree<null>,
parentBundle: SegmentBundle | null,
// The per-pass static walk strategy; see pingRootRouteTree where
// it's derived.
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): { bundle: SegmentBundle | null; needsRuntimeRequest: boolean } | null {
// In PPF, links may skip speculative prefetching if they only need a shell.
if (
fetchStrategy === FetchStrategy.PPR &&
!needsSpeculativePrefetch(task.fetchStrategy, route.root.tree.prefetchHints)
) {
return PrefetchTaskExitStatus.Done
return null
}
// Constant for the whole pass; recomputed here only because the walk is
......@@ -1500,7 +1564,7 @@ function pingNewPartOfCacheComponentsTree(
fetchStrategy
)
}
return PrefetchTaskExitStatus.Done
return null
}
// Prefetch this segment and its subtree statically, using the normal
......@@ -1514,7 +1578,6 @@ function pingNewPartOfCacheComponentsTree(
fetchStrategy,
true
)
const bundleInProgress = accumulation.bundle
if (canUseRuntimeRequests && accumulation.needsRuntimeRequest) {
// The static attempt for this segment was insufficient. Stop the walk
......@@ -1525,44 +1588,10 @@ function pingNewPartOfCacheComponentsTree(
// upgraded to Pending, so no entry is stranded blocking the task, and
// Empty entries in the dropped chain are re-fetched by a later pass.)
addSpawnedRuntimePrefetch(task, tree.requestKey)
return PrefetchTaskExitStatus.Done
}
if (tree.slots !== null) {
if (!hasNetworkBandwidth(task)) {
// Stop prefetching segments until there's more bandwidth.
return PrefetchTaskExitStatus.InProgress
}
// Recursively ping the children.
for (const childTree of tree.slots.values()) {
// Only pass the bundle to the child that accepts it. A parent is
// only ever bundled into one child.
const bundleForChild =
process.env.__NEXT_PREFETCH_INLINING &&
bundleInProgress !== null &&
childTree.prefetchHints & PrefetchHint.ParentInlinedIntoSelf
? bundleInProgress
: null
const childResult = pingNewPartOfCacheComponentsTree(
now,
task,
route,
childTree,
bundleForChild,
fetchStrategy
)
if (childResult === PrefetchTaskExitStatus.InProgress) {
// Child yielded without finishing.
return PrefetchTaskExitStatus.InProgress
}
}
return null
}
// The static attempt was sufficient for this segment (each child is its
// own decision point) — or parts of it are still in flight, in which case
// the task is blocked and the decision re-runs against the received
// responses.
return PrefetchTaskExitStatus.Done
return accumulation
}
function diffRouteTreeAgainstCurrent(
......@@ -1579,7 +1608,9 @@ function diffRouteTreeAgainstCurrent(
): FlightRouterState {
// This is a single recursive traversal that does multiple things:
// - Finds the segments that differ from the current route, comparing each
// segment's identity as we traverse.
// segment the same way the navigation will (see
// updateRenderTreeOnNavigation in render-tree.ts): its route position,
// then whether any of its param values changed.
// - Constructs a request tree (FlightRouterState) that describes which
// segments need to be prefetched and which ones are already cached.
// - Creates a set of pending cache entries for the segments that need to
......@@ -1591,14 +1622,7 @@ function diffRouteTreeAgainstCurrent(
if (newTreeChildren !== null) {
for (const [parallelRouteKey, newTreeChild] of newTreeChildren) {
const oldTreeChild = oldSlots?.get(parallelRouteKey)
if (
oldTreeChild !== undefined &&
doesRouteStructureMatch(oldTreeChild, newTreeChild) &&
compareParams(oldTreeChild.varyPath, newTreeChild.varyPath) ===
ParamsChange.None
) {
// This segment is already part of the current route. Keep traversing.
const requestTreeChild = diffRouteTreeAgainstCurrent(
requestTreeChildren[parallelRouteKey] = diffSegmentAgainstCurrent(
now,
task,
route,
......@@ -1607,11 +1631,62 @@ function diffRouteTreeAgainstCurrent(
spawnedEntries,
fetchStrategy
)
requestTreeChildren[parallelRouteKey] = requestTreeChild
} else {
// This segment is not part of the current route. We're entering a
// part of the tree that we need to prefetch (unless everything is
// already cached).
}
}
const requestTree: FlightRouterState = [
newTree.segment,
requestTreeChildren,
null,
null,
]
if (newTree.prefetchHints !== 0) {
requestTree[4] = newTree.prefetchHints
}
return requestTree
}
/**
* The per-segment decision of a runtime request's tree walk
* (diffRouteTreeAgainstCurrent): the segment at this position of the target
* route, and the current page's segment at the same position, if it has one.
* A segment the navigation keeps — same route position, and none of its param
* values changed — is omitted from the request and the walk continues into
* its children. Otherwise this segment begins a part of the tree that needs
* to be prefetched (unless everything is already cached), requested according
* to the strategy.
*/
function diffSegmentAgainstCurrent(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
oldTree: RouteTree<CacheNode> | undefined,
newTree: RouteTree<null>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.Full
| FetchStrategy.PPRRuntime
| FetchStrategy.LoadingBoundary
): FlightRouterState {
if (oldTree !== undefined && doesRouteStructureMatch(oldTree, newTree)) {
// This segment is already part of the current route.
if (
compareParams(oldTree.varyPath, newTree.varyPath) === ParamsChange.None
) {
// The navigation keeps its data. Keep traversing.
return diffRouteTreeAgainstCurrent(
now,
task,
route,
oldTree,
newTree,
spawnedEntries,
fetchStrategy
)
}
}
// This segment is not part of the current route, or the navigation
// replaces its data. We're entering a part of the tree that we need to
// prefetch (unless everything is already cached).
switch (fetchStrategy) {
case FetchStrategy.LoadingBoundary: {
// When PPR is disabled, we can't prefetch per segment. We must
......@@ -1627,38 +1702,35 @@ function diffRouteTreeAgainstCurrent(
// anywhere in the tree, the server will never return any data, so
// we can skip the request.
const subtreeHasLoadingBoundary =
(newTreeChild.prefetchHints &
(newTree.prefetchHints &
(PrefetchHint.SegmentHasLoadingBoundary |
PrefetchHint.SubtreeHasLoadingBoundary)) !==
0
const requestTreeChild = subtreeHasLoadingBoundary
? pingPPRDisabledRouteTreeUpToLoadingBoundary(
if (subtreeHasLoadingBoundary) {
return pingPPRDisabledRouteTreeUpToLoadingBoundary(
now,
task,
route,
newTreeChild,
newTree,
null,
spawnedEntries
)
: // There's no loading boundary within this tree. Bail out.
convertRouteTreeToFlightRouterState(newTreeChild)
requestTreeChildren[parallelRouteKey] = requestTreeChild
break
}
// There's no loading boundary within this tree. Bail out.
return convertRouteTreeToFlightRouterState(newTree)
}
case FetchStrategy.PPRRuntime: {
// This is a runtime prefetch. Fetch all cacheable data in the tree,
// not just the static PPR shell.
const requestTreeChild = pingRouteTreeAndIncludeDynamicData(
return pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
newTreeChild,
newTree,
false,
spawnedEntries,
fetchStrategy
)
requestTreeChildren[parallelRouteKey] = requestTreeChild
break
}
case FetchStrategy.Full: {
// This is a "full" prefetch. Fetch all the data in the tree, both
......@@ -1678,34 +1750,17 @@ function diffRouteTreeAgainstCurrent(
// cached. If the tree is empty, then we can exit. Otherwise, we'll
// send the request tree to the server and use the response to
// populate the segment cache.
const requestTreeChild = pingRouteTreeAndIncludeDynamicData(
return pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
newTreeChild,
newTree,
false,
spawnedEntries,
fetchStrategy
)
requestTreeChildren[parallelRouteKey] = requestTreeChild
break
}
default:
fetchStrategy satisfies never
}
}
}
}
const requestTree: FlightRouterState = [
newTree.segment,
requestTreeChildren,
null,
null,
]
if (newTree.prefetchHints !== 0) {
requestTree[4] = newTree.prefetchHints
}
return requestTree
}
function pingPPRDisabledRouteTreeUpToLoadingBoundary(
......@@ -2101,11 +2156,11 @@ function pingRuntimePrefetches(
* request would return more content than the entry contains
* (needsRuntimeRequest, derived at write time from the response that
* produced the entry). The callers surface this signal to the per-segment
* decision point in pingNewPartOfCacheComponentsTree (and its analog for
* the head in pingStaticHead), which uses it during a static attempt to
* decide whether to fall back to a runtime prefetch. One exception withholds
* the signal: a shell-tier entry whose segment carries the static-attempt
* hint spawns a concrete static attempt first — see the Fulfilled case.
* decision point in pingSegmentInCacheComponentsTree, which uses it during
* a static attempt to decide whether to fall back to a runtime prefetch. One
* exception withholds the signal: a shell-tier entry whose segment carries
* the static-attempt hint spawns a concrete static attempt first — see the
* Fulfilled case.
*/
function pingSegmentBundle(
now: number,
......@@ -2426,7 +2481,7 @@ function accumulateSegmentBundle(
) {
if (segment.status === EntryStatus.Pending) {
// The chain this entry joins may be dropped before it's ever pinged
// (see the drop sites in pingNewPartOfCacheComponentsTree), and only
// (see the drop sites in pingSegmentInCacheComponentsTree), and only
// the ping blocks on Pending entries. Register on the in-flight
// response at read time instead, so the pass observes it before the
// phase can complete even if the chain is dropped. When the chain does
......
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