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

[Segment Cache] Background segment revalidation (#74057)

This implements background revalidation of partial segment entries in
the client Segment Cache.

Until this PR, entries were never replaced in the Segment Cache, they
were only evicted upon becoming stale, or if the LRU overflowed. But
there are cases where we'll want to replace an existing entry with a new
one; for example, if the current segment has more dynamic holes than the
new one.

Most commonly this happens when multiple fetching strategies are mixed
within the same app. For example: when a shared layout belongs to both a
PPR-enabled route and a non-PPR enabled route, the layout data might be
omitted when prefetching the non-PPR enabled route, if it's wrapped in a
loading boundary. But that shouldn't prevent it from being included when
prefetching the route that has PPR enabled.

(*Another example is when a shared layout is prefetched both on viewport
entry and also via `<Link prefetch={true}>`. A viewport prefetch will
only include the static data, but `prefetch={true}` includes both the
static and the dynamic.*

*`<Link prefetch={true}>` is not yet implemented by the Segment Cache
but it will use a similar background revalidation strategy as the one
implemented in this PR.*)
parent 7b614701
......@@ -145,8 +145,15 @@ export type RouteCacheEntry =
| FulfilledRouteCacheEntry
| RejectedRouteCacheEntry
export const enum FetchStrategy {
PPR,
LoadingBoundary,
}
type SegmentCacheEntryShared = {
staleAt: number
fetchStrategy: FetchStrategy
revalidating: SegmentCacheEntry | null
// LRU-related fields
key: null | string
......@@ -155,8 +162,16 @@ type SegmentCacheEntryShared = {
size: number
}
export type EmptySegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Empty
rsc: null
loading: null
isPartial: true
promise: null
}
export type PendingSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Empty | EntryStatus.Pending
status: EntryStatus.Pending
rsc: null
loading: null
isPartial: true
......@@ -171,7 +186,7 @@ type RejectedSegmentCacheEntry = SegmentCacheEntryShared & {
promise: null
}
type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {
export type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Fulfilled
rsc: React.ReactNode | null
loading: LoadingModuleData | Promise<LoadingModuleData>
......@@ -180,10 +195,16 @@ type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {
}
export type SegmentCacheEntry =
| EmptySegmentCacheEntry
| PendingSegmentCacheEntry
| RejectedSegmentCacheEntry
| FulfilledSegmentCacheEntry
export type NonEmptySegmentCacheEntry = Exclude<
SegmentCacheEntry,
EmptySegmentCacheEntry
>
// Route cache entries vary on multiple keys: the href and the Next-Url. Each of
// these parts needs to be included in the internal cache key. Rather than
// concatenate the keys into a single key, we use a multi-level map, where the
......@@ -272,8 +293,37 @@ export function readSegmentCacheEntry(
return existingEntry
} else {
// Evict the stale entry from the cache.
deleteSegmentFromCache(existingEntry, path)
// This is a stale entry.
const revalidatingEntry = existingEntry.revalidating
if (revalidatingEntry !== null) {
// There's a revalidation in progress. Upsert it.
const upsertedEntry = upsertSegmentEntry(now, path, revalidatingEntry)
if (upsertedEntry !== null && upsertedEntry.staleAt > now) {
// We can use the upserted revalidation entry.
return upsertedEntry
}
} else {
// Evict the stale entry from the cache.
deleteSegmentFromCache(existingEntry, path)
}
}
}
return null
}
function readRevalidatingSegmentCacheEntry(
now: number,
owner: SegmentCacheEntry
): SegmentCacheEntry | null {
const existingRevalidation = owner.revalidating
if (existingRevalidation !== null) {
if (existingRevalidation.staleAt > now) {
// There's already a revalidation in progress. Or a previous revalidation
// failed and it has not yet expired.
return existingRevalidation
} else {
// Clear the stale revalidation from its owner.
clearRevalidatingSegmentFromOwner(owner)
}
}
return null
......@@ -356,11 +406,89 @@ export function readOrCreateSegmentCacheEntry(
return existingEntry
}
// Create a pending entry and add it to the cache.
const pendingEntry: PendingSegmentCacheEntry = {
const pendingEntry = createDetachedSegmentCacheEntry(route.staleAt)
segmentCacheMap.set(path, pendingEntry)
// Stash the keypath on the entry so we know how to remove it from the map
// if it gets evicted from the LRU.
pendingEntry.key = path
segmentCacheLru.put(pendingEntry)
return pendingEntry
}
export function readOrCreateRevalidatingSegmentEntry(
now: number,
prevEntry: SegmentCacheEntry
): SegmentCacheEntry {
const existingRevalidation = readRevalidatingSegmentCacheEntry(now, prevEntry)
if (existingRevalidation !== null) {
return existingRevalidation
}
const pendingEntry = createDetachedSegmentCacheEntry(prevEntry.staleAt)
// Background revalidations are not stored directly in the cache map or LRU;
// they're stashed on the entry that they will (potentially) replace.
//
// Note that we don't actually ever clear this field, except when the entry
// expires. When the revalidation finishes, one of two things will happen:
//
// 1) the revalidation is successful, `prevEntry` is removed from the cache
// and garbage collected (so there's no point clearing any of its fields)
// 2) the revalidation fails, and we'll use the `revalidating` field to
// prevent subsequent revalidation attempts, until it expires.
prevEntry.revalidating = pendingEntry
return pendingEntry
}
export function upsertSegmentEntry(
now: number,
segmentKeyPath: string,
candidateEntry: SegmentCacheEntry
): SegmentCacheEntry | null {
// We have a new entry that has not yet been inserted into the cache. Before
// we do so, we need to confirm whether it takes precedence over the existing
// entry (if one exists).
const existingEntry = readSegmentCacheEntry(now, segmentKeyPath)
if (existingEntry !== null) {
if (candidateEntry.isPartial && !existingEntry.isPartial) {
// Don't replace a full segment with a partial one. A case where this
// might happen is if the existing segment was fetched via
// <Link prefetch={true}>.
// We're going to leave the entry on the owner's `revalidating` field
// so that it doesn't get revalidated again unnecessarily. Downgrade the
// Fulfilled entry to Rejected and null out the data so it can be garbage
// collected. We leave `staleAt` intact to prevent subsequent revalidation
// attempts only until the entry expires.
const rejectedEntry: RejectedSegmentCacheEntry = candidateEntry as any
rejectedEntry.status = EntryStatus.Rejected
rejectedEntry.loading = null
rejectedEntry.rsc = null
return null
}
// Evict the existing entry from the cache.
deleteSegmentFromCache(existingEntry, segmentKeyPath)
}
segmentCacheMap.set(segmentKeyPath, candidateEntry)
// Stash the keypath on the entry so we know how to remove it from the map
// if it gets evicted from the LRU.
candidateEntry.key = segmentKeyPath
segmentCacheLru.put(candidateEntry)
return candidateEntry
}
export function createDetachedSegmentCacheEntry(
staleAt: number
): EmptySegmentCacheEntry {
const emptyEntry: EmptySegmentCacheEntry = {
status: EntryStatus.Empty,
// Default to assuming the fetch strategy will be PPR. This will be updated
// when a fetch is actually initiated.
fetchStrategy: FetchStrategy.PPR,
revalidating: null,
rsc: null,
loading: null,
staleAt: route.staleAt,
staleAt,
isPartial: true,
promise: null,
......@@ -370,11 +498,16 @@ export function readOrCreateSegmentCacheEntry(
prev: null,
size: 0,
}
segmentCacheMap.set(path, pendingEntry)
// Stash the keypath on the entry so we know how to remove it from the map
// if it gets evicted from the LRU.
pendingEntry.key = path
segmentCacheLru.put(pendingEntry)
return emptyEntry
}
export function upgradeToPendingSegment(
emptyEntry: EmptySegmentCacheEntry,
fetchStrategy: FetchStrategy
): PendingSegmentCacheEntry {
const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any
pendingEntry.status = EntryStatus.Pending
pendingEntry.fetchStrategy = fetchStrategy
return pendingEntry
}
......@@ -391,6 +524,28 @@ function deleteSegmentFromCache(entry: SegmentCacheEntry, key: string): void {
cancelEntryListeners(entry)
segmentCacheMap.delete(key)
segmentCacheLru.delete(entry)
clearRevalidatingSegmentFromOwner(entry)
}
function clearRevalidatingSegmentFromOwner(owner: SegmentCacheEntry): void {
// Revalidating segments are not stored in the cache directly; they're
// stored as a field on the entry that they will (potentially) replace. So
// to dispose of an existing revalidation, we just need to null out the field
// on the owner.
const revalidatingSegment = owner.revalidating
if (revalidatingSegment !== null) {
cancelEntryListeners(revalidatingSegment)
owner.revalidating = null
}
}
export function resetRevalidatingSegmentEntry(
owner: SegmentCacheEntry
): EmptySegmentCacheEntry {
clearRevalidatingSegmentFromOwner(owner)
const emptyEntry = createDetachedSegmentCacheEntry(owner.staleAt)
owner.revalidating = emptyEntry
return emptyEntry
}
function onRouteLRUEviction(entry: RouteCacheEntry): void {
......@@ -461,12 +616,12 @@ function fulfillRouteCacheEntry(
}
function fulfillSegmentCacheEntry(
segmentCacheEntry: PendingSegmentCacheEntry,
segmentCacheEntry: EmptySegmentCacheEntry | PendingSegmentCacheEntry,
rsc: React.ReactNode,
loading: LoadingModuleData | Promise<LoadingModuleData>,
staleAt: number,
isPartial: boolean
) {
): FulfilledSegmentCacheEntry {
const fulfilledEntry: FulfilledSegmentCacheEntry = segmentCacheEntry as any
fulfilledEntry.status = EntryStatus.Fulfilled
fulfilledEntry.rsc = rsc
......@@ -479,6 +634,7 @@ function fulfillSegmentCacheEntry(
// Free the promise for garbage collection.
fulfilledEntry.promise = null
}
return fulfilledEntry
}
function rejectRouteCacheEntry(
......@@ -625,11 +781,11 @@ export function convertRouteTreeToFlightRouterState(
export async function fetchRouteOnCacheMiss(
entry: PendingRouteCacheEntry,
task: PrefetchTask
): Promise<PrefetchSubtaskResult | null> {
): Promise<PrefetchSubtaskResult<null> | null> {
// This function is allowed to use async/await because it contains the actual
// fetch that gets issued on a cache miss. Notice though that it does not
// return anything; it writes the result to the cache entry directly, then
// pings the scheduler to unblock the corresponding prefetch task.
// fetch that gets issued on a cache miss. Notice it writes the result to the
// cache entry directly, rather than return data that is then written by
// the caller.
const key = task.key
const href = key.href
const nextUrl = key.nextUrl
......@@ -754,7 +910,7 @@ export async function fetchRouteOnCacheMiss(
}
// Return a promise that resolves when the network connection closes, so
// the scheduler can track the number of concurrent network connections.
return { closed: closed.promise }
return { value: null, closed: closed.promise }
} catch (error) {
// Either the connection itself failed, or something bad happened while
// decoding the response.
......@@ -769,10 +925,11 @@ export async function fetchSegmentOnCacheMiss(
routeKey: RouteCacheKey,
segmentKeyPath: string,
accessToken: string | null
): Promise<PrefetchSubtaskResult | null> {
): Promise<PrefetchSubtaskResult<FulfilledSegmentCacheEntry> | null> {
// This function is allowed to use async/await because it contains the actual
// fetch that gets issued on a cache miss. Notice though that it does not
// return anything; it writes the result to the cache entry directly.
// fetch that gets issued on a cache miss. Notice it writes the result to the
// cache entry directly, rather than return data that is then written by
// the caller.
//
// Segment fetches are non-blocking so we don't need to ping the scheduler
// on completion.
......@@ -825,19 +982,20 @@ export async function fetchSegmentOnCacheMiss(
rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)
return null
}
fulfillSegmentCacheEntry(
segmentCacheEntry,
serverData.rsc,
serverData.loading,
// TODO: The server does not currently provide per-segment stale time.
// So we use the stale time of the route.
route.staleAt,
serverData.isPartial
)
// Return a promise that resolves when the network connection closes, so
// the scheduler can track the number of concurrent network connections.
return { closed: closed.promise }
return {
value: fulfillSegmentCacheEntry(
segmentCacheEntry,
serverData.rsc,
serverData.loading,
// TODO: The server does not currently provide per-segment stale time.
// So we use the stale time of the route.
route.staleAt,
serverData.isPartial
),
// Return a promise that resolves when the network connection closes, so
// the scheduler can track the number of concurrent network connections.
closed: closed.promise,
}
} catch (error) {
// Either the connection itself failed, or something bad happened while
// decoding the response.
......@@ -851,7 +1009,7 @@ export async function fetchSegmentPrefetchesForPPRDisabledRoute(
route: FulfilledRouteCacheEntry,
dynamicRequestTree: FlightRouterState,
spawnedEntries: Map<string, PendingSegmentCacheEntry>
): Promise<PrefetchSubtaskResult | null> {
): Promise<PrefetchSubtaskResult<null> | null> {
const href = task.key.href
const nextUrl = task.key.nextUrl
const headers: RequestHeaders = {
......@@ -912,7 +1070,7 @@ export async function fetchSegmentPrefetchesForPPRDisabledRoute(
// Return a promise that resolves when the network connection closes, so
// the scheduler can track the number of concurrent network connections.
return { closed: closed.promise }
return { value: null, closed: closed.promise }
} catch (error) {
rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)
return null
......@@ -1094,7 +1252,16 @@ function writeSeedDataIntoCache(
const newEntry = possiblyNewEntry
fulfillSegmentCacheEntry(newEntry, rsc, loading, staleAt, isPartial)
} else {
// There was already an entry in the cache. We must not write over it.
// There was already an entry in the cache. But we may be able to
// replace it with the new one from the server.
const newEntry = fulfillSegmentCacheEntry(
createDetachedSegmentCacheEntry(staleAt),
rsc,
loading,
staleAt,
isPartial
)
upsertSegmentEntry(now, key, newEntry)
}
}
// Recursively write the child data into the cache.
......
......@@ -64,14 +64,15 @@ export function createLRU<T extends LRUNode>(
}
function updateSize(node: T, newNodeSize: number) {
// This is a separate function so that we can resize the entry after it's
// already been inserted.
// This is a separate function from `put` so that we can resize the entry
// regardless of whether it's currently being tracked by the LRU.
const prevNodeSize = node.size
node.size = newNodeSize
if (node.next === null) {
// No longer part of LRU.
// This entry is not currently being tracked by the LRU.
return
}
const prevNodeSize = node.size
node.size = newNodeSize
// Update the total LRU size
lruSize = lruSize - prevNodeSize + newNodeSize
ensureCleanupIsScheduled()
}
......
......@@ -213,7 +213,6 @@ function readRenderSnapshotFromCache(
isPartial = segmentEntry.isPartial
break
}
case EntryStatus.Empty:
case EntryStatus.Pending: {
// We haven't received data for this segment yet, but there's already
// an in-progress request. Since it's extremely likely to arrive
......@@ -231,12 +230,11 @@ function readRenderSnapshotFromCache(
isPartial = true
break
}
case EntryStatus.Empty:
case EntryStatus.Rejected:
break
default: {
const _exhaustiveCheck: never = segmentEntry
break
}
default:
segmentEntry satisfies never
}
}
......
......@@ -16,6 +16,11 @@ import {
fetchSegmentPrefetchesForPPRDisabledRoute,
type PendingSegmentCacheEntry,
convertRouteTreeToFlightRouterState,
FetchStrategy,
readOrCreateRevalidatingSegmentEntry,
upsertSegmentEntry,
type FulfilledSegmentCacheEntry,
upgradeToPendingSegment,
} from './cache'
import type { RouteCacheKey } from './cache-key'
......@@ -50,7 +55,7 @@ export type PrefetchTask = {
* heuristics, like removing prefetches once a link leaves the viewport.
*
* The sortId is assigned when the prefetch is initiated, and reassigned if
* the same URL is prefetched again (effectively bumping it to the top of
* the same task is prefetched again (effectively bumping it to the top of
* the queue).
*
* TODO: We can add additional fields here to indicate what kind of prefetch
......@@ -64,6 +69,19 @@ export type PrefetchTask = {
*/
sortId: number
/**
* The priority of the task. Like sortId, this affects the task's position in
* the queue, so it must never be updated without resifting the heap.
*/
priority: PrefetchPriority
/**
* Temporary state for tracking the currently running task. This is currently
* used to track whether a task deferred some work to run background at
* priority, but we might need it for additional state in the future.
*/
hasBackgroundWork: boolean
/**
* True if the prefetch is blocked by network data. We remove tasks from the
* queue once they are blocked, and add them back when they receive data.
......@@ -105,11 +123,20 @@ const enum PrefetchTaskExitStatus {
Done,
}
export type PrefetchSubtaskResult = {
/**
* The priority of the prefetch task. Higher numbers are higher priority.
*/
const enum PrefetchPriority {
Default = 1,
Background = 0,
}
export type PrefetchSubtaskResult<T> = {
/**
* A promise that resolves when the network connection is closed.
*/
closed: Promise<void>
value: T
}
const taskHeap: Array<PrefetchTask> = []
......@@ -140,6 +167,8 @@ export function schedulePrefetchTask(
const task: PrefetchTask = {
key,
treeAtTimeOfPrefetch,
priority: PrefetchPriority.Default,
hasBackgroundWork: false,
sortId: sortIdCounter++,
isBlocked: false,
_heapIndex: -1,
......@@ -181,9 +210,9 @@ function hasNetworkBandwidth(): boolean {
return inProgressRequests < MAX_CONCURRENT_PREFETCH_REQUESTS
}
function spawnPrefetchSubtask(
prefetchSubtask: Promise<PrefetchSubtaskResult | null>
): void {
function spawnPrefetchSubtask<T>(
prefetchSubtask: Promise<PrefetchSubtaskResult<T> | null>
): Promise<T | null> {
// When the scheduler spawns an async task, we don't await its result.
// Instead, the async task writes its result directly into the cache, then
// pings the scheduler to continue.
......@@ -194,17 +223,17 @@ function spawnPrefetchSubtask(
// closed. The scheduler uses this to control network bandwidth by tracking
// and limiting the number of concurrent requests.
inProgressRequests++
prefetchSubtask
.then((result) => {
if (result === null) {
// The prefetch task errored before it could start processing the
// network stream. Assume the connection is closed.
return
}
// Wait for the connection to close before freeing up more bandwidth.
return result.closed
})
.then(onPrefetchConnectionClosed, onPrefetchConnectionClosed)
return prefetchSubtask.then((result) => {
if (result === null) {
// The prefetch task errored before it could start processing the
// network stream. Assume the connection is closed.
onPrefetchConnectionClosed()
return null
}
// Wait for the connection to close before freeing up more bandwidth.
result.closed.then(onPrefetchConnectionClosed)
return result.value
})
}
function onPrefetchConnectionClosed(): void {
......@@ -245,6 +274,12 @@ function processQueueInMicrotask() {
while (task !== null && hasNetworkBandwidth()) {
const route = readOrCreateRouteCacheEntry(now, task)
const exitStatus = pingRootRouteTree(now, task, route)
// The `hasBackgroundWork` field is only valid for a single attempt. Reset
// it immediately upon exit.
const hasBackgroundWork = task.hasBackgroundWork
task.hasBackgroundWork = false
switch (exitStatus) {
case PrefetchTaskExitStatus.InProgress:
// The task yielded because there are too many requests in progress.
......@@ -260,18 +295,41 @@ function processQueueInMicrotask() {
task = heapPeek(taskHeap)
continue
case PrefetchTaskExitStatus.Done:
// The prefetch is complete. Continue to the next task.
heapPop(taskHeap)
if (hasBackgroundWork) {
// The task spawned additional background work. Reschedule the task
// at background priority.
task.priority = PrefetchPriority.Background
heapResift(taskHeap, task)
} else {
// The prefetch is complete. Continue to the next task.
heapPop(taskHeap)
}
task = heapPeek(taskHeap)
continue
default: {
const _exhaustiveCheck: never = exitStatus
return
}
default:
exitStatus satisfies never
}
}
}
/**
* Check this during a prefetch task to determine if background work can be
* performed. If so, it evaluates to `true`. Otherwise, it returns `false`,
* while also scheduling a background task to run later. Usage:
*
* @example
* if (background(task)) {
* // Perform background-pri work
* }
*/
function background(task: PrefetchTask): boolean {
if (task.priority === PrefetchPriority.Background) {
return true
}
task.hasBackgroundWork = true
return false
}
function pingRootRouteTree(
now: number,
task: PrefetchTask,
......@@ -387,7 +445,7 @@ function pingRouteTree(
tree: RouteTree
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
const segment = readOrCreateSegmentCacheEntry(now, route, tree.key)
pingSegment(route, segment, task.key, tree.key, tree.token)
pingSegment(now, task, route, segment, task.key, tree.key, tree.token)
if (tree.slots !== null) {
if (!hasNetworkBandwidth()) {
// Stop prefetching segments until there's more bandwidth.
......@@ -503,9 +561,18 @@ function createDynamicRequestTreeForPartiallyCachedSegments(
// already work even without any updates to the server. For consistency,
// though, I'll send the full tree and we'll look into this later as part
// of a larger redesign of the request protocol.
// Add the pending cache entry to the result map.
segment.status = EntryStatus.Pending
spawnedEntries.set(tree.key, segment)
spawnedEntries.set(
tree.key,
upgradeToPendingSegment(
segment,
// Set the fetch strategy to LoadingBoundary to indicate that the server
// might not include it in the pending response. If another route is able
// to issue a per-segment request, we'll do that in the background.
FetchStrategy.LoadingBoundary
)
)
if (refetchMarkerContext !== 'refetch') {
refetchMarker = refetchMarkerContext = 'refetch'
} else {
......@@ -524,6 +591,12 @@ function createDynamicRequestTreeForPartiallyCachedSegments(
// path. We can bail out.
return convertRouteTreeToFlightRouterState(tree)
}
// NOTE: If the cached segment were fetched using PPR, then it might be
// partial. We could get a more complete version of the segment by
// including it in this non-PPR request.
//
// We're intentionally choosing not to, though, because it's generally
// better to avoid doing a dynamic prefetch whenever possible.
break
}
case EntryStatus.Pending: {
......@@ -564,34 +637,102 @@ function createDynamicRequestTreeForPartiallyCachedSegments(
}
function pingSegment(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
segment: SegmentCacheEntry,
routeKey: RouteCacheKey,
segmentKey: string,
accessToken: string | null
): void {
if (segment.status === EntryStatus.Empty) {
if (accessToken === null) {
// We don't have an access token for this segment, which means we can't
// do a per-segment prefetch. This happens when the route tree was
// returned by a dynamic server response. Or if the server has decided
// not to grant access to this segment.
} else {
// Segment is not yet cached, and there's no request already in progress.
// Spawn a task to request the segment and load it into the cache.
if (accessToken === null) {
// We don't have an access token for this segment, which means we can't
// do a per-segment prefetch. This happens when the route tree was
// returned by a dynamic server response. Or if the server has decided
// not to grant access to this segment.
return
}
switch (segment.status) {
case EntryStatus.Empty:
// Upgrade to Pending so we know there's already a request in progress
segment.status = EntryStatus.Pending
spawnPrefetchSubtask(
fetchSegmentOnCacheMiss(
route,
segment,
upgradeToPendingSegment(segment, FetchStrategy.PPR),
routeKey,
segmentKey,
accessToken
)
)
break
case EntryStatus.Pending: {
// There's already a request in progress. Depending on what kind of
// request it is, we may want to
switch (segment.fetchStrategy) {
case FetchStrategy.PPR:
// There's already a request in progress. Don't do anything.
break
case FetchStrategy.LoadingBoundary:
// There's a pending request, but because it's using the old
// prefetching strategy, we can't be sure if it will be fulfilled by
// the response — it might be inside the loading boundary. Perform
// a revalidation, but because it's speculative, wait to do it at
// background priority.
if (background(task)) {
// TODO: Instead of speculatively revalidating, consider including
// `hasLoading` in the route tree prefetch response.
pingPPRSegmentRevalidation(
now,
segment,
route,
routeKey,
segmentKey,
accessToken
)
}
break
default:
segment.fetchStrategy satisfies never
}
break
}
case EntryStatus.Rejected: {
// The existing entry in the cache was rejected. Depending on how it
// was originally fetched, we may or may not want to revalidate it.
switch (segment.fetchStrategy) {
case FetchStrategy.PPR:
// The previous attempt to fetch this entry failed. Don't attempt to
// fetch it again until the entry expires.
break
case FetchStrategy.LoadingBoundary:
// There's a rejected entry, but it was fetched using the loading
// boundary strategy. So the reason it wasn't returned by the server
// might just be because it was inside a loading boundary. Or because
// there was a dynamic rewrite. Revalidate it using the per-
// segment strategy.
//
// Because a rejected segment will definitely prevent the segment (and
// all of its children) from rendering, we perform this revalidation
// immediately instead of deferring it to a background task.
pingPPRSegmentRevalidation(
now,
segment,
route,
routeKey,
segmentKey,
accessToken
)
break
default:
segment.fetchStrategy satisfies never
}
break
}
case EntryStatus.Fulfilled:
// Segment is already cached. There's nothing left to prefetch.
break
default:
segment satisfies never
}
// Segments do not have dependent tasks, so once the prefetch is initiated,
......@@ -599,8 +740,66 @@ function pingSegment(
// entry, which is handled by `fetchSegmentOnCacheMiss`).
}
function pingPPRSegmentRevalidation(
now: number,
currentSegment: SegmentCacheEntry,
route: FulfilledRouteCacheEntry,
routeKey: RouteCacheKey,
segmentKey: string,
accessToken: string | null
): void {
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
now,
currentSegment
)
switch (revalidatingSegment.status) {
case EntryStatus.Empty:
// Spawn a prefetch request and upsert the segment into the cache
// upon completion.
upsertSegmentOnCompletion(
segmentKey,
spawnPrefetchSubtask(
fetchSegmentOnCacheMiss(
route,
upgradeToPendingSegment(revalidatingSegment, FetchStrategy.PPR),
routeKey,
segmentKey,
accessToken
)
)
)
break
case EntryStatus.Pending:
// There's already a revalidation in progress.
break
case EntryStatus.Fulfilled:
case EntryStatus.Rejected:
// A previous revalidation attempt finished, but we chose not to replace
// the existing entry in the cache. Don't try again until or unless the
// revalidation entry expires.
break
default:
revalidatingSegment satisfies never
}
}
const noop = () => {}
function upsertSegmentOnCompletion(
key: string,
promise: Promise<FulfilledSegmentCacheEntry | null>
) {
// Wait for a segment to finish loading, then upsert it into the cache
promise.then((fulfilled) => {
if (fulfilled !== null) {
// Received new data. Attempt to replace the existing entry in the cache.
upsertSegmentEntry(Date.now(), key, fulfilled)
}
}, noop)
}
// -----------------------------------------------------------------------------
// The remainider of the module is a MinHeap implementation. Try not to put any
// The remainder of the module is a MinHeap implementation. Try not to put any
// logic below here unless it's related to the heap algorithm. We can extract
// this to a separate module if/when we need multiple kinds of heaps.
// -----------------------------------------------------------------------------
......@@ -609,7 +808,13 @@ function compareQueuePriority(a: PrefetchTask, b: PrefetchTask) {
// Since the queue is a MinHeap, this should return a positive number if b is
// higher priority than a, and a negative number if a is higher priority
// than b.
//
// `priority` is an integer, where higher numbers are higher priority.
const priorityDiff = b.priority - a.priority
if (priorityDiff !== 0) {
return priorityDiff
}
// sortId is an incrementing counter assigned to prefetches. We want to
// process the newest prefetches first.
return b.sortId - a.sortId
......@@ -641,22 +846,24 @@ function heapPop(heap: Array<PrefetchTask>): PrefetchTask | null {
return first
}
// Not currently used, but will be once we add the ability to update a
// task's priority.
// function heapSift(heap: Array<PrefetchTask>, node: PrefetchTask) {
// const index = node._heapIndex
// if (index !== -1) {
// const parentIndex = (index - 1) >>> 1
// const parent = heap[parentIndex]
// if (compareQueuePriority(parent, node) > 0) {
// // The parent is larger. Sift up.
// heapSiftUp(heap, node, index)
// } else {
// // The parent is smaller (or equal). Sift down.
// heapSiftDown(heap, node, index)
// }
// }
// }
function heapResift(heap: Array<PrefetchTask>, node: PrefetchTask): void {
const index = node._heapIndex
if (index !== -1) {
if (index === 0) {
heapSiftDown(heap, node, 0)
} else {
const parentIndex = (index - 1) >>> 1
const parent = heap[parentIndex]
if (compareQueuePriority(parent, node) > 0) {
// The parent is larger. Sift up.
heapSiftUp(heap, node, index)
} else {
// The parent is smaller (or equal). Sift down.
heapSiftDown(heap, node, index)
}
}
}
}
function heapSiftUp(
heap: Array<PrefetchTask>,
......
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
id,
}: {
href: string
children: string
prefetch?: boolean
id?: string
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
id={id}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
async function DynamicContentInSharedLayout() {
await connection()
return (
<div id="dynamic-content-in-shared-layout">
Dynamic content in shared layout
</div>
)
}
export default function SharedLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div id="shared-layout">
<Suspense
fallback={
<div id="shared-layout-ppr-boundary">
Loading (PPR shell of shared-layout)...
</div>
}
>
<DynamicContentInSharedLayout />
</Suspense>
{children}
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
async function Content() {
await connection()
return <div id="page-content">Dynamic page content</div>
}
export default async function Page() {
return (
<Suspense fallback={<div id="page-loading-boundary">Loading page...</div>}>
<Content />
</Suspense>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export const experimental_ppr = true
async function Content() {
await connection()
return <div id="page-content">Dynamic page content</div>
}
export default async function Page() {
return (
<Suspense fallback={<div id="page-loading-boundary">Loading page...</div>}>
<Content />
</Suspense>
)
}
export default function SharedLayout({
children,
}: {
children: React.ReactNode
}) {
return <div id="has-loading-boundary">{children}</div>
}
export default function Loading() {
return (
<div id="loading-boundary">
Loading (has-loading-boundary/loading.tsx)...
</div>
)
}
import { LinkAccordion } from '../link-accordion'
export default function MixedFetchStrategies() {
return (
<>
<p>
This page tests what happens when a shared layout belongs to both a
PPR-enabled route and a non-PPR enabled route. The layout data should be
omitted when prefetching the non-PPR enabled route, because it's inside
another layout that has a loading boundary. But it should be included
when prefetching the route that has PPR enabled.
</p>
<ul>
<li>
<LinkAccordion
id="ppr-enabled"
href="/mixed-fetch-strategies/has-loading-boundary/a/b/shared-layout/ppr-enabled"
>
Link to PPR enabled page
</LinkAccordion>
</li>
<li>
<LinkAccordion
id="ppr-disabled"
href="/mixed-fetch-strategies/has-loading-boundary/a/b/shared-layout/ppr-disabled"
>
Link to PPR disabled page
</LinkAccordion>
</li>
</ul>
</>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
function LinkAccordion({ href, children }) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { LinkAccordion } from './link-accordion'
export default function Page() {
return (
......
......@@ -92,4 +92,43 @@ describe('segment cache (incremental opt in)', () => {
it('page with PPR disabled, and has a loading boundary', () =>
testPrefetchDeduping('/ppr-disabled-with-loading-boundary'))
})
it(
'prefetches a shared layout on a PPR-enabled route that was previously ' +
'omitted from a non-PPR-enabled route',
async () => {
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Initiate a prefetch for the PPR-disabled route first. This will not
// include the /shared-layout/ segment, because it's inside the
// loading boundary.
await act(async () => {
const checkbox = await browser.elementById('ppr-disabled')
await checkbox.click()
})
// Then initiate a prefetch for the PPR-enabled route. This prefetch
// should include the /shared-layout/ segment despite the presence of
// the loading boundary, and despite the earlier non-PPR attempt
await act(async () => {
const checkbox = await browser.elementById('ppr-enabled')
await checkbox.click()
})
// Navigate to the PPR-enabled route
await act(async () => {
const link = await browser.elementByCss('#ppr-enabled + a')
await link.click()
// If we prefetched all the segments correctly, we should be able to
// reveal the page's loading state, before the server responds.
await browser.elementById('page-loading-boundary')
})
}
)
})
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