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 {
getFulfilledRouteVaryPath,
getFulfilledSegmentVaryPath,
getSegmentVaryPathForRequest,
getStaticSegmentVaryPathForRequest,
getShellSegmentVaryPath,
cloneVaryPathWithNewSearchParams,
getPartialVaryPath,
......@@ -931,36 +932,40 @@ export function readOrCreateSegmentCacheEntry(
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`,
// captured when the task was scheduled).
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
// The vary path to read from (see getSegmentVaryPathForRequest). A shell
// 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 {
const existingEntry = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
map,
tree.varyPath,
varyPath,
false,
false
)
if (existingEntry !== null) {
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
* at the vary path a request made with the given fetch strategy is stored
* under. The stale time is set to a default value; the actual stale time will
* be set when the entry is fulfilled with data from the server response.
* at the vary path the request's pending entry is stored under. The stale time
* is set to a default value; the actual stale time will be set when the entry
* is fulfilled with data from the server response.
*/
function insertEmptySegmentCacheEntry(
now: number,
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
varyPathForRequest: VaryPath
): EmptySegmentCacheEntry {
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const emptyEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = false
setInCacheMap(map, varyPathForRequest, emptyEntry, isRevalidation)
......@@ -971,8 +976,10 @@ export function readOrCreateRevalidatingSegmentEntry(
now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`).
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
// The vary path to read from; see readOrCreateSegmentCacheEntry.
varyPath: VaryPath,
// Where to store the revalidation: the request's own vary path.
varyPathForRequest: VaryPath
): SegmentCacheEntry {
// 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
......@@ -1001,18 +1008,13 @@ export function readOrCreateRevalidatingSegmentEntry(
// 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,
// not on data contained in the response.
const existingEntry = readRevalidatingSegmentCacheEntry(
now,
map,
tree.varyPath
)
const existingEntry = readRevalidatingSegmentCacheEntry(now, map, varyPath)
if (existingEntry !== null) {
return existingEntry
}
// 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
// fulfilled with data from the server response.
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const pendingEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = true
setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)
......@@ -1023,15 +1025,14 @@ export function overwriteRevalidatingSegmentCacheEntry(
now: number,
// The map the calling task operates in (`PrefetchTask.segmentCacheMap`).
map: CacheMap<SegmentCacheEntry>,
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
// Where to store the revalidation: the request's own vary path.
varyPathForRequest: VaryPath
) {
// 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,
// 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
// from the server response.
const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)
const pendingEntry = createDetachedSegmentCacheEntry(now)
const isRevalidation = true
setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)
......@@ -1047,6 +1048,10 @@ export function overwriteRevalidatingSegmentCacheEntry(
* deciding whether an entry at a more specific keypath may be evicted because
* 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
* strategy content tiers (how much content a strategy can produce), not the
* vary-path specificity the eviction docs are concerned with.
......@@ -1063,18 +1068,18 @@ function isExistingSegmentEntryPreferred(
// in favor of an entry with nothing in it.)
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 (
// 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.
(candidateEntry.fetchStrategy !== existingEntry.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)
candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&
!canNewFetchStrategyProvideMoreContent(
existingEntry.fetchStrategy,
candidateEntry.fetchStrategy
)
)
}
......@@ -3563,16 +3568,22 @@ function writeSegmentDataIntoCache(
// keying (this is load-bearing for entries spawned as revalidations:
// without the re-key they'd stay in their Revalidation slot forever,
// invisible to canonical reads, and the partial entry that prompted the
// revalidation would keep serving navigations). Full responses are
// excluded, matching the varyParams re-key: they're spawned as canonical
// entries at their final path, and their vary tracking can't be trusted
// for re-keying (see the fulfilledVaryPath derivation above).
const canonicalVaryPath =
fulfilledVaryPath !== null
? fulfilledVaryPath
: payloadStrategy !== FetchStrategy.Full
? getSegmentVaryPathForRequest(payloadStrategy, tree)
: null
// revalidation would keep serving navigations). Only a Full or PPRRuntime
// response can vary on search params.
let canonicalVaryPath: VaryPath
if (fulfilledVaryPath !== null) {
canonicalVaryPath = fulfilledVaryPath
} else if (
payloadStrategy === FetchStrategy.Full ||
payloadStrategy === FetchStrategy.PPRRuntime
) {
canonicalVaryPath = getSegmentVaryPathForRequest(payloadStrategy, tree)
} else {
canonicalVaryPath = getStaticSegmentVaryPathForRequest(
payloadStrategy,
tree
)
}
// 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
......@@ -3586,7 +3597,6 @@ function writeSegmentDataIntoCache(
const isOwned =
ownedEntry !== undefined && ownedEntry.status === EntryStatus.Pending
let fulfilledEntry: FulfilledSegmentCacheEntry
let insertVaryPath: VaryPath | null
if (isOwned) {
// We own this entry — fulfill it directly.
fulfilledEntry = fulfillSegmentCacheEntry(
......@@ -3598,14 +3608,9 @@ function writeSegmentDataIntoCache(
isUpgradeableISRFallback,
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 {
// 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
// (which has no canonical re-key), at the request's own path.
// attempt to insert it at the canonical path.
fulfilledEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now),
......@@ -3618,46 +3623,40 @@ function writeSegmentDataIntoCache(
isUpgradeableISRFallback,
recordedFetchStrategy
)
insertVaryPath =
canonicalVaryPath !== null
? canonicalVaryPath
: getSegmentVaryPathForRequest(fetchStrategy, tree)
}
if (insertVaryPath !== null) {
// Insert through the upsert so the usual precedence rules apply — an
// existing entry with more complete content is never downgraded, and a
// shadowed Empty/Pending entry's blocked tasks are pinged. (In the
// common case the slot already holds the entry we just fulfilled, which
// the upsert replaces in place; but the re-key is load-bearing for
// entries whose spawn path differs from the canonical path — e.g.
// spawned revalidations, which would otherwise stay in their
// Revalidation slot forever, invisible to canonical reads, while the
// partial entry that prompted the revalidation kept serving
// navigations.)
//
// The concrete lookup path (tree.varyPath) is passed so that when the
// canonical path is more generic, any stale settled entry — or unclaimed
// Empty placeholder — at a more specific path that would shadow the
// fulfilled entry is evicted. Without this, a shadowed re-keyed entry is
// unreachable at the concrete read path: the scheduler would keep
// re-reading the stale entry and, for a revalidation, respawn it
// forever. See evictShadowingSegmentEntries.
const installedEntry = upsertSegmentEntry(
now,
map,
insertVaryPath,
fulfilledEntry,
tree.varyPath
)
if (installedEntry === null && !isOwned) {
// The upsert declined the detached candidate (an existing entry took
// precedence, or the candidate was already expired), so no cache slot
// 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
}
}
// Insert through the upsert so the usual precedence rules apply — an
// existing entry with more complete content is never downgraded, and a
// shadowed Empty/Pending entry's blocked tasks are pinged. (In the
// common case the slot already holds the entry we just fulfilled, which
// the upsert replaces in place; but the re-key is load-bearing for
// entries whose spawn path differs from the canonical path — e.g.
// spawned revalidations, which would otherwise stay in their
// Revalidation slot forever, invisible to canonical reads, while the
// partial entry that prompted the revalidation kept serving
// navigations.)
//
// The concrete lookup path (tree.varyPath) is passed so that when the
// canonical path is more generic, any stale settled entry — or unclaimed
// Empty placeholder — at a more specific path that would shadow the
// fulfilled entry is evicted. Without this, a shadowed re-keyed entry is
// unreachable at the concrete read path: the scheduler would keep
// re-reading the stale entry and, for a revalidation, respawn it
// forever. See evictShadowingSegmentEntries.
const installedEntry = upsertSegmentEntry(
now,
map,
canonicalVaryPath,
fulfilledEntry,
tree.varyPath
)
if (installedEntry === null && !isOwned) {
// The upsert declined the detached candidate (an existing entry took
// precedence, or the candidate was already expired), so no cache slot
// 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
}
......
import { compareParams, ParamsChange } from './vary-path'
import {
compareParams,
ParamsChange,
getSegmentVaryPathForRequest,
getStaticSegmentVaryPathForRequest,
} from './vary-path'
import type {
FlightRouterState,
CacheNode,
......@@ -855,9 +860,9 @@ function pingRootRouteTree(
// 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.
// We don't need to do this for runtime prefetches, because those are only available in
// `cacheComponents`, where every route is PPR.
let fetchStrategy: FetchStrategy
let fetchStrategy:
| PrefetchTaskFetchStrategy
| FetchStrategy.LoadingBoundary
if (tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) {
// If Partial Prefetching is enabled anywhere on the target route,
// ignore the fetch strategy and switch to unified strategy used by
......@@ -1022,7 +1027,6 @@ function pingRootRouteTree(
return PrefetchTaskExitStatus.Done
}
case FetchStrategy.Full:
case FetchStrategy.PPRRuntime:
case FetchStrategy.LoadingBoundary: {
if (task.phase === PrefetchPhase.Shell) {
// Shell phase only does work on routes that use the PPR strategy
......@@ -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
* 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
* 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
* `recordedFetchStrategy` in cache.ts). That makes this a pure tier
* 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(
entry: SegmentCacheEntry,
staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): boolean {
if (!entry.isPartial) {
return false
}
return canNewFetchStrategyProvideMoreContent(
entry.fetchStrategy,
getRuntimeStrategyForWalk(staticWalkStrategy)
staticWalkStrategy === FetchStrategy.StaticShell
? FetchStrategy.RuntimeShell
: FetchStrategy.PPRRuntime
)
}
/**
* Whether a fulfilled shell-tier entry should take a static attempt (a
* spawned revalidation at the walk's static tier) before its position deopts
* to a runtime request. A shell-tier recorded entry (StaticShell or
* RuntimeShell) is not evidence that a static attempt would be pointless —
* unlike a concrete static (PPR) entry, where a static re-fetch would return
* the same bytes — so when the segment's hint says a static attempt is
* worthwhile (the build-time prerender accessed no runtime data), the
* attempt is taken and its response's own verdict decides whether to
* escalate afterward.
* to a runtime request. A RuntimeShell entry is not evidence that a static
* attempt would be pointless — unlike a concrete static (PPR) entry, where a
* static re-fetch would return the same bytes — so when the segment's hint
* says a static attempt is worthwhile (the build-time prerender accessed no
* runtime data), the attempt is taken and its response's own verdict decides
* whether to escalate afterward. A StaticShell entry is not eligible: its
* 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
* without healing the entry (a rejected attempt: server miss or network
......@@ -1235,8 +1234,8 @@ function isShellEntryEligibleForStaticAttempt(
): boolean {
if (
!(
(entry.fetchStrategy === FetchStrategy.StaticShell ||
entry.fetchStrategy === FetchStrategy.RuntimeShell) &&
entry.isPartial &&
entry.fetchStrategy === FetchStrategy.RuntimeShell &&
shouldSegmentAttemptStaticRequest(fetchStrategy, tree) &&
// if the `fetchStrategy` is `FetchStrategy.PPR`, it might provide more content
// (e.g. static params that this shell doesn't have)
......@@ -1248,8 +1247,8 @@ function isShellEntryEligibleForStaticAttempt(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now,
map,
fetchStrategy,
tree
getSegmentVaryPathForRequest(fetchStrategy, tree),
getStaticSegmentVaryPathForRequest(fetchStrategy, tree)
)
return (
revalidatingEntry.status === EntryStatus.Empty ||
......@@ -1513,10 +1512,9 @@ function pingNewPartOfCacheComponentsTree(
* 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.
* Returns the segment's bundle if we should keep going into its children.
* Returns null if we stop at this segment, because it needs a runtime
* request, and that request covers the whole subtree.
*/
function pingSegmentInCacheComponentsTree(
now: number,
......@@ -1528,14 +1526,6 @@ function pingSegmentInCacheComponentsTree(
// 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 null
}
// Constant for the whole pass; recomputed here only because the walk is
// recursive and the check is cheap.
const canUseRuntimeRequests = walkCanUseRuntimeRequests(fetchStrategy, route)
......@@ -1601,10 +1591,7 @@ function diffRouteTreeAgainstCurrent(
oldTree: RouteTree<CacheNode>,
newTree: RouteTree<null>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.Full
| FetchStrategy.PPRRuntime
| FetchStrategy.LoadingBoundary
fetchStrategy: FetchStrategy.Full | FetchStrategy.LoadingBoundary
): FlightRouterState {
// This is a single recursive traversal that does multiple things:
// - Finds the segments that differ from the current route, comparing each
......@@ -1662,10 +1649,7 @@ function diffSegmentAgainstCurrent(
oldTree: RouteTree<CacheNode> | undefined,
newTree: RouteTree<null>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
fetchStrategy:
| FetchStrategy.Full
| FetchStrategy.PPRRuntime
| FetchStrategy.LoadingBoundary
fetchStrategy: FetchStrategy.Full | FetchStrategy.LoadingBoundary
): FlightRouterState {
if (oldTree !== undefined && doesRouteStructureMatch(oldTree, newTree)) {
// This segment is already part of the current route.
......@@ -1719,19 +1703,6 @@ function diffSegmentAgainstCurrent(
// 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.
return pingRouteTreeAndIncludeDynamicData(
now,
task,
route,
newTree,
false,
spawnedEntries,
fetchStrategy
)
}
case FetchStrategy.Full: {
// This is a "full" prefetch. Fetch all the data in the tree, both
// static and dynamic. We issue roughly the same request that we
......@@ -1788,8 +1759,8 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
const segment = readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
task.fetchStrategy,
tree
getSegmentVaryPathForRequest(FetchStrategy.LoadingBoundary, tree),
getStaticSegmentVaryPathForRequest(FetchStrategy.LoadingBoundary, tree)
)
switch (segment.status) {
case EntryStatus.Empty: {
......@@ -1937,16 +1908,17 @@ function pingRouteTreeAndIncludeDynamicData(
// explicit "refetch" marker so the server knows where to start rendering.
// Once the server starts rendering along a path, it keeps rendering the
// 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(
now,
task.segmentCacheMap,
// 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.
fetchStrategy,
tree
varyPath,
varyPath
)
let spawnedSegment: PendingSegmentCacheEntry | null = null
......@@ -2158,7 +2130,7 @@ function pingRuntimePrefetches(
* produced the entry). The callers surface this signal to the per-segment
* 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
* exception withholds the signal: a RuntimeShell entry whose segment carries
* the static-attempt hint spawns a concrete static attempt first — see the
* Fulfilled case.
*/
......@@ -2224,8 +2196,8 @@ function pingSegmentBundle(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
nodeTree
getSegmentVaryPathForRequest(fetchStrategy, nodeTree),
getStaticSegmentVaryPathForRequest(fetchStrategy, nodeTree)
)
if (revalidatingEntry.status === EntryStatus.Empty) {
const pendingEntry = upgradeToPendingSegment(
......@@ -2264,8 +2236,8 @@ function pingSegmentBundle(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
nodeTree
getSegmentVaryPathForRequest(fetchStrategy, nodeTree),
getStaticSegmentVaryPathForRequest(fetchStrategy, nodeTree)
)
if (revalidatingEntry.status === EntryStatus.Empty) {
const pendingEntry = upgradeToPendingSegment(
......@@ -2374,8 +2346,8 @@ function pingSegmentBundle(
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
nodeTree
getSegmentVaryPathForRequest(fetchStrategy, nodeTree),
getStaticSegmentVaryPathForRequest(fetchStrategy, nodeTree)
)
if (revalidatingEntry.status === EntryStatus.Empty) {
const pendingEntry = upgradeToPendingSegment(
......@@ -2471,8 +2443,8 @@ function accumulateSegmentBundle(
const segment = readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
tree
getSegmentVaryPathForRequest(fetchStrategy, tree),
getStaticSegmentVaryPathForRequest(fetchStrategy, tree)
)
if (
......@@ -2526,8 +2498,8 @@ function accumulateSegmentBundle(
entry: readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
route.root.head
getSegmentVaryPathForRequest(fetchStrategy, route.root.head),
getStaticSegmentVaryPathForRequest(fetchStrategy, route.root.head)
),
parent: parentBundle,
}
......@@ -2604,11 +2576,12 @@ function pingFullSegmentRevalidation(
| FetchStrategy.PPRRuntime
| FetchStrategy.RuntimeShell
): PendingSegmentCacheEntry | null {
const varyPath = getSegmentVaryPathForRequest(fetchStrategy, tree)
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
now,
task.segmentCacheMap,
fetchStrategy,
tree
varyPath,
varyPath
)
if (revalidatingSegment.status === EntryStatus.Empty) {
// During a Full/PPRRuntime prefetch, a single runtime request is made for
......@@ -2637,8 +2610,7 @@ function pingFullSegmentRevalidation(
const emptySegment = overwriteRevalidatingSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
tree
varyPath
)
const pendingSegment = upgradeToPendingSegment(
emptySegment,
......
......@@ -71,7 +71,4 @@ export const enum FetchStrategy {
* 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.
* */
export type PrefetchTaskFetchStrategy =
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.Full
export type PrefetchTaskFetchStrategy = FetchStrategy.PPR | FetchStrategy.Full
......@@ -214,19 +214,16 @@ export function getSegmentVaryPathForRequest<TData>(
tree: RouteTree<TData>
): VaryPath {
// 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.
// static/PPR versus runtime prefetching, so that it can be reused as much
// as possible.
// the most generic vary path based on the strategy used to fetch it, so
// that it can be reused as much as possible.
//
// 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
// 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
// example, a static prefetch will never vary on search params.
// we know some params are reusable based on the fetch strategy alone.
//
// 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
// where certain params are replaced with Fallback.
// route tree object. The shell vary path is precomputed there too.
//
// This result of this function is not stored anywhere. It's only used to
// access the cache a single time.
......@@ -234,8 +231,6 @@ export function getSegmentVaryPathForRequest<TData>(
// 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
// params that can be treated as Fallback. (Or perhaps the inverse.)
const originalVaryPath = tree.varyPath
if (
fetchStrategy === FetchStrategy.RuntimeShell ||
fetchStrategy === FetchStrategy.StaticShell
......@@ -249,36 +244,43 @@ export function getSegmentVaryPathForRequest<TData>(
// params keep their concrete value).
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
// on search params.
const originalVaryPath = tree.varyPath
const searchParamsVaryPath = originalVaryPath.parent
if (
searchParamsVaryPath !== null &&
searchParamsVaryPath.id === SEARCH_PARAMS_VARY_ID
) {
// Only a runtime prefetch will include search params in the vary path.
// Static prefetches never include search params, so they can be reused
// across all possible search param values.
const doesVaryOnSearchParams =
fetchStrategy === FetchStrategy.Full ||
fetchStrategy === FetchStrategy.PPRRuntime
if (!doesVaryOnSearchParams) {
// 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)
)
}
// 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
}
......
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