Unverified Commit d50d2ce8 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Prefer non-partial entries regardless of FetchStrategy (#99705)

If an entry is not partial, it means nothing was omittted during
rendering. Regardless of the strategy used to fetch it — static vs
dynamic, shell vs prefetch vs navigation, etc — it's the most complete
possible representation of the data. No other fetch strategy could
return a more complete version.

This PR updates the precedence logic to take `isPartial` into account. I
discovered this while working on the next PR, which replaces `isPartial`
with a new "completeness" concept. I extracted it into this earlier PR
to show how it would be expressed in the current model, so the next one
is easier to review.
parent 06136c4a
...@@ -45,6 +45,7 @@ import { ...@@ -45,6 +45,7 @@ import {
getFulfilledRouteVaryPath, getFulfilledRouteVaryPath,
getFulfilledSegmentVaryPath, getFulfilledSegmentVaryPath,
getSegmentVaryPathForRequest, getSegmentVaryPathForRequest,
getStaticSegmentVaryPathForRequest,
getShellSegmentVaryPath, getShellSegmentVaryPath,
cloneVaryPathWithNewSearchParams, cloneVaryPathWithNewSearchParams,
getPartialVaryPath, getPartialVaryPath,
...@@ -931,36 +932,40 @@ export function readOrCreateSegmentCacheEntry( ...@@ -931,36 +932,40 @@ export function readOrCreateSegmentCacheEntry(
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`, // The map the calling task operates in (`PrefetchTask.segmentCacheMap`,
// captured when the task was scheduled). // captured when the task was scheduled).
map: CacheMap<SegmentCacheEntry>, map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy, // The vary path to read from (see getSegmentVaryPathForRequest). A shell
tree: RouteTree<RSCSegmentData | null> // prefetch reads from the shell vary path, because that's where its request
// writes. If it read from the concrete path, it might find a deeper entry
// for this URL and check the wrong one. Everything else reads from the
// concrete path, which still finds entries stored under a more generic key.
varyPath: VaryPath,
// The vary path to store a new entry under, which is the request's own.
varyPathForRequest: VaryPath
): SegmentCacheEntry { ): SegmentCacheEntry {
const existingEntry = getFromCacheMap( const existingEntry = getFromCacheMap(
now, now,
getCurrentSegmentCacheVersion(), getCurrentSegmentCacheVersion(),
map, map,
tree.varyPath, varyPath,
false, false,
false false
) )
if (existingEntry !== null) { if (existingEntry !== null) {
return existingEntry return existingEntry
} }
return insertEmptySegmentCacheEntry(now, map, fetchStrategy, tree) return insertEmptySegmentCacheEntry(now, map, varyPathForRequest)
} }
/** /**
* Creates an empty segment cache entry and inserts it into the cache, keyed * Creates an empty segment cache entry and inserts it into the cache, keyed
* at the vary path a request made with the given fetch strategy is stored * at the vary path the request's pending entry is stored under. The stale time
* under. The stale time is set to a default value; the actual stale time will * is set to a default value; the actual stale time will be set when the entry
* be set when the entry is fulfilled with data from the server response. * is fulfilled with data from the server response.
*/ */
function insertEmptySegmentCacheEntry( function insertEmptySegmentCacheEntry(
now: number, now: number,
map: CacheMap<SegmentCacheEntry>, map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy, varyPathForRequest: VaryPath
tree: RouteTree<RSCSegmentData | null>
): EmptySegmentCacheEntry { ): EmptySegmentCacheEntry {
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const emptyEntry = createDetachedSegmentCacheEntry(now) const emptyEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = false const isRevalidation = false
setInCacheMap(map, varyPathForRequest, emptyEntry, isRevalidation) setInCacheMap(map, varyPathForRequest, emptyEntry, isRevalidation)
...@@ -971,8 +976,10 @@ export function readOrCreateRevalidatingSegmentEntry( ...@@ -971,8 +976,10 @@ export function readOrCreateRevalidatingSegmentEntry(
now: number, now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`). // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).
map: CacheMap<SegmentCacheEntry>, map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy, // The vary path to read from; see readOrCreateSegmentCacheEntry.
tree: RouteTree<RSCSegmentData | null> varyPath: VaryPath,
// Where to store the revalidation: the request's own vary path.
varyPathForRequest: VaryPath
): SegmentCacheEntry { ): SegmentCacheEntry {
// This function is called when we've already confirmed that a particular // This function is called when we've already confirmed that a particular
// segment is cached, but we want to perform another request anyway in case it // segment is cached, but we want to perform another request anyway in case it
...@@ -1001,18 +1008,13 @@ export function readOrCreateRevalidatingSegmentEntry( ...@@ -1001,18 +1008,13 @@ export function readOrCreateRevalidatingSegmentEntry(
// return a less generic entry upon revalidation. For now, though, this isn't // return a less generic entry upon revalidation. For now, though, this isn't
// a concern because the keypath is based solely on the prefetch strategy, // a concern because the keypath is based solely on the prefetch strategy,
// not on data contained in the response. // not on data contained in the response.
const existingEntry = readRevalidatingSegmentCacheEntry( const existingEntry = readRevalidatingSegmentCacheEntry(now, map, varyPath)
now,
map,
tree.varyPath
)
if (existingEntry !== null) { if (existingEntry !== null) {
return existingEntry return existingEntry
} }
// Create a pending entry and add it to the cache. The stale time is set to a // Create a pending entry and add it to the cache. The stale time is set to a
// default value; the actual stale time will be set when the entry is // default value; the actual stale time will be set when the entry is
// fulfilled with data from the server response. // fulfilled with data from the server response.
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const pendingEntry = createDetachedSegmentCacheEntry(now) const pendingEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = true const isRevalidation = true
setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation) setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)
...@@ -1023,15 +1025,14 @@ export function overwriteRevalidatingSegmentCacheEntry( ...@@ -1023,15 +1025,14 @@ export function overwriteRevalidatingSegmentCacheEntry(
now: number, now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`). // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).
map: CacheMap<SegmentCacheEntry>, map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy, // Where to store the revalidation: the request's own vary path.
tree: RouteTree<RSCSegmentData | null> varyPathForRequest: VaryPath
) { ) {
// This function is called when we've already decided to replace an existing // This function is called when we've already decided to replace an existing
// revalidation entry. Create a new entry and write it into the cache, // revalidation entry. Create a new entry and write it into the cache,
// overwriting the previous value. The stale time is set to a default value; // overwriting the previous value. The stale time is set to a default value;
// the actual stale time will be set when the entry is fulfilled with data // the actual stale time will be set when the entry is fulfilled with data
// from the server response. // from the server response.
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const pendingEntry = createDetachedSegmentCacheEntry(now) const pendingEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = true const isRevalidation = true
setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation) setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)
...@@ -1047,6 +1048,10 @@ export function overwriteRevalidatingSegmentCacheEntry( ...@@ -1047,6 +1048,10 @@ export function overwriteRevalidatingSegmentCacheEntry(
* deciding whether an entry at a more specific keypath may be evicted because * deciding whether an entry at a more specific keypath may be evicted because
* it shadows a just-inserted candidate (see `evictShadowingSegmentEntries`). * it shadows a just-inserted candidate (see `evictShadowingSegmentEntries`).
* *
* When exactly one of the two entries is non-partial, it wins, whatever
* strategy fetched it: it has nothing left to fetch. Otherwise the entry
* fetched with the more specific strategy wins.
*
* Note that "less/more specific" in the comments below refers to fetch * Note that "less/more specific" in the comments below refers to fetch
* strategy content tiers (how much content a strategy can produce), not the * strategy content tiers (how much content a strategy can produce), not the
* vary-path specificity the eviction docs are concerned with. * vary-path specificity the eviction docs are concerned with.
...@@ -1063,18 +1068,18 @@ function isExistingSegmentEntryPreferred( ...@@ -1063,18 +1068,18 @@ function isExistingSegmentEntryPreferred(
// in favor of an entry with nothing in it.) // in favor of an entry with nothing in it.)
return false return false
} }
if (existingEntry.isPartial !== candidateEntry.isPartial) {
return !existingEntry.isPartial
}
// We fetched the new segment using a different, less specific fetch
// strategy than the segment we already have in the cache, so it can't have
// more content.
return ( return (
// We fetched the new segment using a different, less specific fetch candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&
// strategy than the segment we already have in the cache, so it can't !canNewFetchStrategyProvideMoreContent(
// have more content. existingEntry.fetchStrategy,
(candidateEntry.fetchStrategy !== existingEntry.fetchStrategy && candidateEntry.fetchStrategy
!canNewFetchStrategyProvideMoreContent( )
existingEntry.fetchStrategy,
candidateEntry.fetchStrategy
)) ||
// The existing entry isn't partial, but the new one is.
// (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)
(!existingEntry.isPartial && candidateEntry.isPartial)
) )
} }
...@@ -3563,16 +3568,22 @@ function writeSegmentDataIntoCache( ...@@ -3563,16 +3568,22 @@ function writeSegmentDataIntoCache(
// keying (this is load-bearing for entries spawned as revalidations: // keying (this is load-bearing for entries spawned as revalidations:
// without the re-key they'd stay in their Revalidation slot forever, // without the re-key they'd stay in their Revalidation slot forever,
// invisible to canonical reads, and the partial entry that prompted the // invisible to canonical reads, and the partial entry that prompted the
// revalidation would keep serving navigations). Full responses are // revalidation would keep serving navigations). Only a Full or PPRRuntime
// excluded, matching the varyParams re-key: they're spawned as canonical // response can vary on search params.
// entries at their final path, and their vary tracking can't be trusted let canonicalVaryPath: VaryPath
// for re-keying (see the fulfilledVaryPath derivation above). if (fulfilledVaryPath !== null) {
const canonicalVaryPath = canonicalVaryPath = fulfilledVaryPath
fulfilledVaryPath !== null } else if (
? fulfilledVaryPath payloadStrategy === FetchStrategy.Full ||
: payloadStrategy !== FetchStrategy.Full payloadStrategy === FetchStrategy.PPRRuntime
? getSegmentVaryPathForRequest(payloadStrategy, tree) ) {
: null canonicalVaryPath = getSegmentVaryPathForRequest(payloadStrategy, tree)
} else {
canonicalVaryPath = getStaticSegmentVaryPathForRequest(
payloadStrategy,
tree
)
}
// We should only write into cache entries that are owned by us. Or create // We should only write into cache entries that are owned by us. Or create
// a new one and write into that. We must never write over an entry that was // a new one and write into that. We must never write over an entry that was
...@@ -3586,7 +3597,6 @@ function writeSegmentDataIntoCache( ...@@ -3586,7 +3597,6 @@ function writeSegmentDataIntoCache(
const isOwned = const isOwned =
ownedEntry !== undefined && ownedEntry.status === EntryStatus.Pending ownedEntry !== undefined && ownedEntry.status === EntryStatus.Pending
let fulfilledEntry: FulfilledSegmentCacheEntry let fulfilledEntry: FulfilledSegmentCacheEntry
let insertVaryPath: VaryPath | null
if (isOwned) { if (isOwned) {
// We own this entry — fulfill it directly. // We own this entry — fulfill it directly.
fulfilledEntry = fulfillSegmentCacheEntry( fulfilledEntry = fulfillSegmentCacheEntry(
...@@ -3598,14 +3608,9 @@ function writeSegmentDataIntoCache( ...@@ -3598,14 +3608,9 @@ function writeSegmentDataIntoCache(
isUpgradeableISRFallback, isUpgradeableISRFallback,
recordedFetchStrategy recordedFetchStrategy
) )
// Re-key the fulfilled entry at its canonical path. Owned Full entries
// are the exception (canonicalVaryPath is null): they were spawned as
// canonical entries at their final path, so no re-key happens.
insertVaryPath = canonicalVaryPath
} else { } else {
// We don't own an entry for this segment. Create a detached one and // We don't own an entry for this segment. Create a detached one and
// attempt to insert it at the canonical path — or, for a Full response // attempt to insert it at the canonical path.
// (which has no canonical re-key), at the request's own path.
fulfilledEntry = fulfillSegmentCacheEntry( fulfilledEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment( upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now), createDetachedSegmentCacheEntry(now),
...@@ -3618,46 +3623,40 @@ function writeSegmentDataIntoCache( ...@@ -3618,46 +3623,40 @@ function writeSegmentDataIntoCache(
isUpgradeableISRFallback, isUpgradeableISRFallback,
recordedFetchStrategy recordedFetchStrategy
) )
insertVaryPath = }
canonicalVaryPath !== null // Insert through the upsert so the usual precedence rules apply — an
? canonicalVaryPath // existing entry with more complete content is never downgraded, and a
: getSegmentVaryPathForRequest(fetchStrategy, tree) // shadowed Empty/Pending entry's blocked tasks are pinged. (In the
} // common case the slot already holds the entry we just fulfilled, which
if (insertVaryPath !== null) { // the upsert replaces in place; but the re-key is load-bearing for
// Insert through the upsert so the usual precedence rules apply — an // entries whose spawn path differs from the canonical path — e.g.
// existing entry with more complete content is never downgraded, and a // spawned revalidations, which would otherwise stay in their
// shadowed Empty/Pending entry's blocked tasks are pinged. (In the // Revalidation slot forever, invisible to canonical reads, while the
// common case the slot already holds the entry we just fulfilled, which // partial entry that prompted the revalidation kept serving
// the upsert replaces in place; but the re-key is load-bearing for // navigations.)
// entries whose spawn path differs from the canonical path — e.g. //
// spawned revalidations, which would otherwise stay in their // The concrete lookup path (tree.varyPath) is passed so that when the
// Revalidation slot forever, invisible to canonical reads, while the // canonical path is more generic, any stale settled entry — or unclaimed
// partial entry that prompted the revalidation kept serving // Empty placeholder — at a more specific path that would shadow the
// navigations.) // fulfilled entry is evicted. Without this, a shadowed re-keyed entry is
// // unreachable at the concrete read path: the scheduler would keep
// The concrete lookup path (tree.varyPath) is passed so that when the // re-reading the stale entry and, for a revalidation, respawn it
// canonical path is more generic, any stale settled entry — or unclaimed // forever. See evictShadowingSegmentEntries.
// Empty placeholder — at a more specific path that would shadow the const installedEntry = upsertSegmentEntry(
// fulfilled entry is evicted. Without this, a shadowed re-keyed entry is now,
// unreachable at the concrete read path: the scheduler would keep map,
// re-reading the stale entry and, for a revalidation, respawn it canonicalVaryPath,
// forever. See evictShadowingSegmentEntries. fulfilledEntry,
const installedEntry = upsertSegmentEntry( tree.varyPath
now, )
map, if (installedEntry === null && !isOwned) {
insertVaryPath, // The upsert declined the detached candidate (an existing entry took
fulfilledEntry, // precedence, or the candidate was already expired), so no cache slot
tree.varyPath // holds this write's content — nothing for the caller to charge to
) // the LRU. (An owned entry is returned regardless: it was fulfilled
if (installedEntry === null && !isOwned) { // above and stays live for waiters that hold it, whether or not the
// The upsert declined the detached candidate (an existing entry took // re-key installed it.)
// precedence, or the candidate was already expired), so no cache slot return null
// holds this write's content — nothing for the caller to charge to
// the LRU. (An owned entry is returned regardless: it was fulfilled
// above and stays live for waiters that hold it, whether or not the
// re-key installed it.)
return null
}
} }
return fulfilledEntry return fulfilledEntry
} }
......
import { compareParams, ParamsChange } from './vary-path' import {
compareParams,
ParamsChange,
getSegmentVaryPathForRequest,
getStaticSegmentVaryPathForRequest,
} from './vary-path'
import type { import type {
FlightRouterState, FlightRouterState,
CacheNode, CacheNode,
...@@ -855,9 +860,9 @@ function pingRootRouteTree( ...@@ -855,9 +860,9 @@ function pingRootRouteTree(
// A task's fetch strategy gets set to `PPR` for any "auto" prefetch. // A task's fetch strategy gets set to `PPR` for any "auto" prefetch.
// If it turned out that the route isn't PPR-enabled, we need to use `LoadingBoundary` instead. // If it turned out that the route isn't PPR-enabled, we need to use `LoadingBoundary` instead.
// We don't need to do this for runtime prefetches, because those are only available in let fetchStrategy:
// `cacheComponents`, where every route is PPR. | PrefetchTaskFetchStrategy
let fetchStrategy: FetchStrategy | FetchStrategy.LoadingBoundary
if (tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) { if (tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) {
// If Partial Prefetching is enabled anywhere on the target route, // If Partial Prefetching is enabled anywhere on the target route,
// ignore the fetch strategy and switch to unified strategy used by // ignore the fetch strategy and switch to unified strategy used by
...@@ -1022,7 +1027,6 @@ function pingRootRouteTree( ...@@ -1022,7 +1027,6 @@ function pingRootRouteTree(
return PrefetchTaskExitStatus.Done return PrefetchTaskExitStatus.Done
} }
case FetchStrategy.Full: case FetchStrategy.Full:
case FetchStrategy.PPRRuntime:
case FetchStrategy.LoadingBoundary: { case FetchStrategy.LoadingBoundary: {
if (task.phase === PrefetchPhase.Shell) { if (task.phase === PrefetchPhase.Shell) {
// Shell phase only does work on routes that use the PPR strategy // Shell phase only does work on routes that use the PPR strategy
...@@ -1171,52 +1175,47 @@ function shouldSegmentAttemptStaticRequest( ...@@ -1171,52 +1175,47 @@ function shouldSegmentAttemptStaticRequest(
} }
} }
/**
* The runtime counterpart of a pass's static walk strategy: the strategy the
* batched runtime request uses if this walk deopts. Each phase has exactly one
* — the Shell phase escalates to a shell-scoped runtime request
* (RuntimeShell), the Speculative phase to a per-link concrete
* runtime prefetch.
*/
function getRuntimeStrategyForWalk(
staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): FetchStrategy.RuntimeShell | FetchStrategy.PPRRuntime {
return staticWalkStrategy === FetchStrategy.StaticShell
? FetchStrategy.RuntimeShell
: FetchStrategy.PPRRuntime
}
/** /**
* Whether this phase's runtime request would return more content for a * Whether this phase's runtime request would return more content for a
* fulfilled entry than the entry already holds. * fulfilled entry than the entry already holds. The Shell phase escalates to
* a shell-scoped runtime request (RuntimeShell), the Speculative phase to a
* per-link concrete runtime prefetch (PPRRuntime).
* *
* An entry records the tier its CONTENT achieved, not the one it was requested * An entry records the tier its CONTENT achieved, not the one it was requested
* at, and that tier spans both axes — so a static response that needed no * at, and that tier spans both axes — so a static response that needed no
* runtime data records the runtime counterpart of its own variant (see * runtime data records the runtime counterpart of its own variant (see
* `recordedFetchStrategy` in cache.ts). That makes this a pure tier * `recordedFetchStrategy` in cache.ts). That makes this a pure tier
* comparison: an entry at or above the phase's runtime tier has nothing to * comparison: an entry at or above the phase's runtime tier has nothing to
* gain from it. * gain from it. Neither does a non-partial entry, whatever its tier.
*/ */
function wouldRuntimeRequestProvideMore( function wouldRuntimeRequestProvideMore(
entry: SegmentCacheEntry, entry: SegmentCacheEntry,
staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): boolean { ): boolean {
if (!entry.isPartial) {
return false
}
return canNewFetchStrategyProvideMoreContent( return canNewFetchStrategyProvideMoreContent(
entry.fetchStrategy, entry.fetchStrategy,
getRuntimeStrategyForWalk(staticWalkStrategy) staticWalkStrategy === FetchStrategy.StaticShell
? FetchStrategy.RuntimeShell
: FetchStrategy.PPRRuntime
) )
} }
/** /**
* Whether a fulfilled shell-tier entry should take a static attempt (a * Whether a fulfilled shell-tier entry should take a static attempt (a
* spawned revalidation at the walk's static tier) before its position deopts * spawned revalidation at the walk's static tier) before its position deopts
* to a runtime request. A shell-tier recorded entry (StaticShell or * to a runtime request. A RuntimeShell entry is not evidence that a static
* RuntimeShell) is not evidence that a static attempt would be pointless — * attempt would be pointless — unlike a concrete static (PPR) entry, where a
* unlike a concrete static (PPR) entry, where a static re-fetch would return * static re-fetch would return the same bytes — so when the segment's hint
* the same bytes — so when the segment's hint says a static attempt is * says a static attempt is worthwhile (the build-time prerender accessed no
* worthwhile (the build-time prerender accessed no runtime data), the * runtime data), the attempt is taken and its response's own verdict decides
* attempt is taken and its response's own verdict decides whether to * whether to escalate afterward. A StaticShell entry is not eligible: its
* escalate afterward. * verdict says the shell read runtime data, so the later stages read it too
* and a static prefetch can't make the entry cache complete. Only a runtime
* request can, so it goes straight there. A non-partial entry is not eligible
* either: it has nothing more to fetch.
* *
* Consults the revalidation slot so an attempt that already ran and settled * Consults the revalidation slot so an attempt that already ran and settled
* without healing the entry (a rejected attempt: server miss or network * without healing the entry (a rejected attempt: server miss or network
...@@ -1235,8 +1234,8 @@ function isShellEntryEligibleForStaticAttempt( ...@@ -1235,8 +1234,8 @@ function isShellEntryEligibleForStaticAttempt(
): boolean { ): boolean {
if ( if (
!( !(
(entry.fetchStrategy === FetchStrategy.StaticShell || entry.isPartial &&
entry.fetchStrategy === FetchStrategy.RuntimeShell) && entry.fetchStrategy === FetchStrategy.RuntimeShell &&
shouldSegmentAttemptStaticRequest(fetchStrategy, tree) && shouldSegmentAttemptStaticRequest(fetchStrategy, tree) &&
// if the `fetchStrategy` is `FetchStrategy.PPR`, it might provide more content // if the `fetchStrategy` is `FetchStrategy.PPR`, it might provide more content
// (e.g. static params that this shell doesn't have) // (e.g. static params that this shell doesn't have)
...@@ -1248,8 +1247,8 @@ function isShellEntryEligibleForStaticAttempt( ...@@ -1248,8 +1247,8 @@ function isShellEntryEligibleForStaticAttempt(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry( const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now, now,
map, map,
fetchStrategy, getSegmentVaryPathForRequest(fetchStrategy, tree),
tree getStaticSegmentVaryPathForRequest(fetchStrategy, tree)
) )
return ( return (
revalidatingEntry.status === EntryStatus.Empty || revalidatingEntry.status === EntryStatus.Empty ||
...@@ -1513,10 +1512,9 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1513,10 +1512,9 @@ function pingNewPartOfCacheComponentsTree(
* The static hints and `needsRuntimeRequest` have no effect if runtime requests * The static hints and `needsRuntimeRequest` have no effect if runtime requests
* are not allowed (i.e. outside of Partial Prefetching). * are not allowed (i.e. outside of Partial Prefetching).
* *
* Returns the segment's bundle accumulation when the walk should continue * Returns the segment's bundle if we should keep going into its children.
* into its children, and null when the walk stops at this segment: the link * Returns null if we stop at this segment, because it needs a runtime
* needs no speculative prefetch, or the segment deopted and the batched * request, and that request covers the whole subtree.
* runtime request covers the whole subtree.
*/ */
function pingSegmentInCacheComponentsTree( function pingSegmentInCacheComponentsTree(
now: number, now: number,
...@@ -1528,14 +1526,6 @@ function pingSegmentInCacheComponentsTree( ...@@ -1528,14 +1526,6 @@ function pingSegmentInCacheComponentsTree(
// it's derived. // it's derived.
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): { bundle: SegmentBundle | null; needsRuntimeRequest: boolean } | null { ): { 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 null
}
// Constant for the whole pass; recomputed here only because the walk is // Constant for the whole pass; recomputed here only because the walk is
// recursive and the check is cheap. // recursive and the check is cheap.
const canUseRuntimeRequests = walkCanUseRuntimeRequests(fetchStrategy, route) const canUseRuntimeRequests = walkCanUseRuntimeRequests(fetchStrategy, route)
...@@ -1601,10 +1591,7 @@ function diffRouteTreeAgainstCurrent( ...@@ -1601,10 +1591,7 @@ function diffRouteTreeAgainstCurrent(
oldTree: RouteTree<CacheNode>, oldTree: RouteTree<CacheNode>,
newTree: RouteTree<null>, newTree: RouteTree<null>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>, spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
fetchStrategy: fetchStrategy: FetchStrategy.Full | FetchStrategy.LoadingBoundary
| FetchStrategy.Full
| FetchStrategy.PPRRuntime
| FetchStrategy.LoadingBoundary
): FlightRouterState { ): FlightRouterState {
// This is a single recursive traversal that does multiple things: // This is a single recursive traversal that does multiple things:
// - Finds the segments that differ from the current route, comparing each // - Finds the segments that differ from the current route, comparing each
...@@ -1662,10 +1649,7 @@ function diffSegmentAgainstCurrent( ...@@ -1662,10 +1649,7 @@ function diffSegmentAgainstCurrent(
oldTree: RouteTree<CacheNode> | undefined, oldTree: RouteTree<CacheNode> | undefined,
newTree: RouteTree<null>, newTree: RouteTree<null>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>, spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
fetchStrategy: fetchStrategy: FetchStrategy.Full | FetchStrategy.LoadingBoundary
| FetchStrategy.Full
| FetchStrategy.PPRRuntime
| FetchStrategy.LoadingBoundary
): FlightRouterState { ): FlightRouterState {
if (oldTree !== undefined && doesRouteStructureMatch(oldTree, newTree)) { if (oldTree !== undefined && doesRouteStructureMatch(oldTree, newTree)) {
// This segment is already part of the current route. // This segment is already part of the current route.
...@@ -1719,19 +1703,6 @@ function diffSegmentAgainstCurrent( ...@@ -1719,19 +1703,6 @@ function diffSegmentAgainstCurrent(
// There's no loading boundary within this tree. Bail out. // There's no loading boundary within this tree. Bail out.
return convertRouteTreeToFlightRouterState(newTree) return convertRouteTreeToFlightRouterState(newTree)
} }
case FetchStrategy.PPRRuntime: {
// This is a runtime prefetch. Fetch all cacheable data in the tree,
// not just the static PPR shell.
return pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
newTree,
false,
spawnedEntries,
fetchStrategy
)
}
case FetchStrategy.Full: { case FetchStrategy.Full: {
// This is a "full" prefetch. Fetch all the data in the tree, both // This is a "full" prefetch. Fetch all the data in the tree, both
// static and dynamic. We issue roughly the same request that we // static and dynamic. We issue roughly the same request that we
...@@ -1788,8 +1759,8 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary( ...@@ -1788,8 +1759,8 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
const segment = readOrCreateSegmentCacheEntry( const segment = readOrCreateSegmentCacheEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
task.fetchStrategy, getSegmentVaryPathForRequest(FetchStrategy.LoadingBoundary, tree),
tree getStaticSegmentVaryPathForRequest(FetchStrategy.LoadingBoundary, tree)
) )
switch (segment.status) { switch (segment.status) {
case EntryStatus.Empty: { case EntryStatus.Empty: {
...@@ -1937,16 +1908,17 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -1937,16 +1908,17 @@ function pingRouteTreeAndIncludeDynamicData(
// explicit "refetch" marker so the server knows where to start rendering. // explicit "refetch" marker so the server knows where to start rendering.
// Once the server starts rendering along a path, it keeps rendering the // Once the server starts rendering along a path, it keeps rendering the
// entire subtree. // entire subtree.
// Note that `fetchStrategy` might be different from `task.fetchStrategy`,
// and we have to use the former here.
// We can have a task with `FetchStrategy.PPR` where some of its segments are configured to
// always use runtime prefetching (via `export const prefetch`), and those should check for
// entries that include search params.
const varyPath = getSegmentVaryPathForRequest(fetchStrategy, tree)
const segment = readOrCreateSegmentCacheEntry( const segment = readOrCreateSegmentCacheEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
// Note that `fetchStrategy` might be different from `task.fetchStrategy`, varyPath,
// and we have to use the former here. varyPath
// We can have a task with `FetchStrategy.PPR` where some of its segments are configured to
// always use runtime prefetching (via `export const prefetch`), and those should check for
// entries that include search params.
fetchStrategy,
tree
) )
let spawnedSegment: PendingSegmentCacheEntry | null = null let spawnedSegment: PendingSegmentCacheEntry | null = null
...@@ -2158,7 +2130,7 @@ function pingRuntimePrefetches( ...@@ -2158,7 +2130,7 @@ function pingRuntimePrefetches(
* produced the entry). The callers surface this signal to the per-segment * produced the entry). The callers surface this signal to the per-segment
* decision point in pingSegmentInCacheComponentsTree, which uses it during * decision point in pingSegmentInCacheComponentsTree, which uses it during
* a static attempt to decide whether to fall back to a runtime prefetch. One * 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 * exception withholds the signal: a RuntimeShell entry whose segment carries
* the static-attempt hint spawns a concrete static attempt first — see the * the static-attempt hint spawns a concrete static attempt first — see the
* Fulfilled case. * Fulfilled case.
*/ */
...@@ -2224,8 +2196,8 @@ function pingSegmentBundle( ...@@ -2224,8 +2196,8 @@ function pingSegmentBundle(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry( const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
fetchStrategy, getSegmentVaryPathForRequest(fetchStrategy, nodeTree),
nodeTree getStaticSegmentVaryPathForRequest(fetchStrategy, nodeTree)
) )
if (revalidatingEntry.status === EntryStatus.Empty) { if (revalidatingEntry.status === EntryStatus.Empty) {
const pendingEntry = upgradeToPendingSegment( const pendingEntry = upgradeToPendingSegment(
...@@ -2264,8 +2236,8 @@ function pingSegmentBundle( ...@@ -2264,8 +2236,8 @@ function pingSegmentBundle(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry( const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
fetchStrategy, getSegmentVaryPathForRequest(fetchStrategy, nodeTree),
nodeTree getStaticSegmentVaryPathForRequest(fetchStrategy, nodeTree)
) )
if (revalidatingEntry.status === EntryStatus.Empty) { if (revalidatingEntry.status === EntryStatus.Empty) {
const pendingEntry = upgradeToPendingSegment( const pendingEntry = upgradeToPendingSegment(
...@@ -2374,8 +2346,8 @@ function pingSegmentBundle( ...@@ -2374,8 +2346,8 @@ function pingSegmentBundle(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry( const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
fetchStrategy, getSegmentVaryPathForRequest(fetchStrategy, nodeTree),
nodeTree getStaticSegmentVaryPathForRequest(fetchStrategy, nodeTree)
) )
if (revalidatingEntry.status === EntryStatus.Empty) { if (revalidatingEntry.status === EntryStatus.Empty) {
const pendingEntry = upgradeToPendingSegment( const pendingEntry = upgradeToPendingSegment(
...@@ -2471,8 +2443,8 @@ function accumulateSegmentBundle( ...@@ -2471,8 +2443,8 @@ function accumulateSegmentBundle(
const segment = readOrCreateSegmentCacheEntry( const segment = readOrCreateSegmentCacheEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
fetchStrategy, getSegmentVaryPathForRequest(fetchStrategy, tree),
tree getStaticSegmentVaryPathForRequest(fetchStrategy, tree)
) )
if ( if (
...@@ -2526,8 +2498,8 @@ function accumulateSegmentBundle( ...@@ -2526,8 +2498,8 @@ function accumulateSegmentBundle(
entry: readOrCreateSegmentCacheEntry( entry: readOrCreateSegmentCacheEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
fetchStrategy, getSegmentVaryPathForRequest(fetchStrategy, route.root.head),
route.root.head getStaticSegmentVaryPathForRequest(fetchStrategy, route.root.head)
), ),
parent: parentBundle, parent: parentBundle,
} }
...@@ -2604,11 +2576,12 @@ function pingFullSegmentRevalidation( ...@@ -2604,11 +2576,12 @@ function pingFullSegmentRevalidation(
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
| FetchStrategy.RuntimeShell | FetchStrategy.RuntimeShell
): PendingSegmentCacheEntry | null { ): PendingSegmentCacheEntry | null {
const varyPath = getSegmentVaryPathForRequest(fetchStrategy, tree)
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry( const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
fetchStrategy, varyPath,
tree varyPath
) )
if (revalidatingSegment.status === EntryStatus.Empty) { if (revalidatingSegment.status === EntryStatus.Empty) {
// During a Full/PPRRuntime prefetch, a single runtime request is made for // During a Full/PPRRuntime prefetch, a single runtime request is made for
...@@ -2637,8 +2610,7 @@ function pingFullSegmentRevalidation( ...@@ -2637,8 +2610,7 @@ function pingFullSegmentRevalidation(
const emptySegment = overwriteRevalidatingSegmentCacheEntry( const emptySegment = overwriteRevalidatingSegmentCacheEntry(
now, now,
task.segmentCacheMap, task.segmentCacheMap,
fetchStrategy, varyPath
tree
) )
const pendingSegment = upgradeToPendingSegment( const pendingSegment = upgradeToPendingSegment(
emptySegment, emptySegment,
......
...@@ -71,7 +71,4 @@ export const enum FetchStrategy { ...@@ -71,7 +71,4 @@ export const enum FetchStrategy {
* until we complete the initial tree prefetch request, so we use `PPR` to signal both cases * until we complete the initial tree prefetch request, so we use `PPR` to signal both cases
* and adjust it based on the route when actually fetching. * and adjust it based on the route when actually fetching.
* */ * */
export type PrefetchTaskFetchStrategy = export type PrefetchTaskFetchStrategy = FetchStrategy.PPR | FetchStrategy.Full
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.Full
...@@ -214,19 +214,16 @@ export function getSegmentVaryPathForRequest<TData>( ...@@ -214,19 +214,16 @@ export function getSegmentVaryPathForRequest<TData>(
tree: RouteTree<TData> tree: RouteTree<TData>
): VaryPath { ): VaryPath {
// This is used for storing pending requests in the cache. We want to choose // This is used for storing pending requests in the cache. We want to choose
// the most generic vary path based on the strategy used to fetch it, i.e. // the most generic vary path based on the strategy used to fetch it, so
// static/PPR versus runtime prefetching, so that it can be reused as much // that it can be reused as much as possible.
// as possible.
// //
// We may be able to re-key the response to something even more generic once // We may be able to re-key the response to something even more generic once
// we receive it — for example, if the server tells us that the response // we receive it — for example, if the server tells us that the response
// doesn't vary on a particular param — but even before we send the request, // doesn't vary on a particular param — but even before we send the request,
// we know some params are reusable based on the fetch strategy alone. For // we know some params are reusable based on the fetch strategy alone.
// example, a static prefetch will never vary on search params.
// //
// The original vary path with all the params filled in is stored on the // The original vary path with all the params filled in is stored on the
// route tree object. We will clone this one to create a new vary path // route tree object. The shell vary path is precomputed there too.
// where certain params are replaced with Fallback.
// //
// This result of this function is not stored anywhere. It's only used to // This result of this function is not stored anywhere. It's only used to
// access the cache a single time. // access the cache a single time.
...@@ -234,8 +231,6 @@ export function getSegmentVaryPathForRequest<TData>( ...@@ -234,8 +231,6 @@ export function getSegmentVaryPathForRequest<TData>(
// TODO: Rather than create a new list object just to access the cache, the // TODO: Rather than create a new list object just to access the cache, the
// plan is to add the concept of a "vary mask". This will represent all the // plan is to add the concept of a "vary mask". This will represent all the
// params that can be treated as Fallback. (Or perhaps the inverse.) // params that can be treated as Fallback. (Or perhaps the inverse.)
const originalVaryPath = tree.varyPath
if ( if (
fetchStrategy === FetchStrategy.RuntimeShell || fetchStrategy === FetchStrategy.RuntimeShell ||
fetchStrategy === FetchStrategy.StaticShell fetchStrategy === FetchStrategy.StaticShell
...@@ -249,36 +244,43 @@ export function getSegmentVaryPathForRequest<TData>( ...@@ -249,36 +244,43 @@ export function getSegmentVaryPathForRequest<TData>(
// params keep their concrete value). // params keep their concrete value).
return tree.shellVaryPath return tree.shellVaryPath
} }
return tree.varyPath
}
/**
* The vary path a pending entry is stored under when its response never
* varies on search params: every strategy except Full and PPRRuntime. Like
* getSegmentVaryPathForRequest, except that the entry can be reused across
* all possible search param values.
*/
export function getStaticSegmentVaryPathForRequest<TData>(
fetchStrategy: FetchStrategy,
tree: RouteTree<TData>
): VaryPath {
if (
fetchStrategy === FetchStrategy.RuntimeShell ||
fetchStrategy === FetchStrategy.StaticShell
) {
return tree.shellVaryPath
}
// The vary path includes a search params entry only when the segment varies // The vary path includes a search params entry only when the segment varies
// on search params. // on search params.
const originalVaryPath = tree.varyPath
const searchParamsVaryPath = originalVaryPath.parent const searchParamsVaryPath = originalVaryPath.parent
if ( if (
searchParamsVaryPath !== null && searchParamsVaryPath !== null &&
searchParamsVaryPath.id === SEARCH_PARAMS_VARY_ID searchParamsVaryPath.id === SEARCH_PARAMS_VARY_ID
) { ) {
// Only a runtime prefetch will include search params in the vary path. // Rebuild the vary path with the search params replaced by Fallback.
// Static prefetches never include search params, so they can be reused //
// across all possible search param values. // requestKey -> searchParams -> pathParams
const doesVaryOnSearchParams = // ^ This part gets replaced with Fallback
fetchStrategy === FetchStrategy.Full || return finalizeVaryPath(
fetchStrategy === FetchStrategy.PPRRuntime originalVaryPath.value,
Fallback,
if (!doesVaryOnSearchParams) { getPartialVaryPath(originalVaryPath)
// The response from the the server will not vary on search params. )
// Rebuild the vary path with the search params replaced by Fallback.
//
// requestKey -> searchParams -> pathParams
// ^ This part gets replaced with Fallback
return finalizeVaryPath(
originalVaryPath.value,
Fallback,
getPartialVaryPath(originalVaryPath)
)
}
} }
// The request does vary on search params. We don't need to modify anything.
return originalVaryPath return originalVaryPath
} }
......
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