Unverified Commit 5af7af5f authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add lazy initialize of router cache nodes (#42629)

parent 601e964e
...@@ -7,6 +7,7 @@ import { ...@@ -7,6 +7,7 @@ import {
AppRouterContext, AppRouterContext,
LayoutRouterContext, LayoutRouterContext,
GlobalLayoutRouterContext, GlobalLayoutRouterContext,
CacheStates,
} from '../../shared/lib/app-router-context' } from '../../shared/lib/app-router-context'
import type { import type {
CacheNode, CacheNode,
...@@ -121,11 +122,12 @@ function Router({ ...@@ -121,11 +122,12 @@ function Router({
return { return {
tree: initialTree, tree: initialTree,
cache: { cache: {
status: CacheStates.READY,
data: null, data: null,
subTreeData: children, subTreeData: children,
parallelRoutes: parallelRoutes:
typeof window === 'undefined' ? new Map() : initialParallelRoutes, typeof window === 'undefined' ? new Map() : initialParallelRoutes,
}, } as CacheNode,
prefetchCache: new Map(), prefetchCache: new Map(),
pushRef: { pendingPush: false, mpaNavigation: false }, pushRef: { pendingPush: false, mpaNavigation: false },
focusAndScrollRef: { apply: false }, focusAndScrollRef: { apply: false },
...@@ -176,6 +178,7 @@ function Router({ ...@@ -176,6 +178,7 @@ function Router({
previousTree, previousTree,
overrideCanonicalUrl, overrideCanonicalUrl,
cache: { cache: {
status: CacheStates.LAZYINITIALIZED,
data: null, data: null,
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
...@@ -201,6 +204,7 @@ function Router({ ...@@ -201,6 +204,7 @@ function Router({
forceOptimisticNavigation, forceOptimisticNavigation,
navigateType, navigateType,
cache: { cache: {
status: CacheStates.LAZYINITIALIZED,
data: null, data: null,
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
...@@ -262,6 +266,7 @@ function Router({ ...@@ -262,6 +266,7 @@ function Router({
// TODO-APP: revisit if this needs to be passed. // TODO-APP: revisit if this needs to be passed.
cache: { cache: {
status: CacheStates.LAZYINITIALIZED,
data: null, data: null,
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
......
...@@ -16,6 +16,7 @@ import type { ...@@ -16,6 +16,7 @@ import type {
} from '../../server/app-render' } from '../../server/app-render'
import type { ErrorComponent } from './error-boundary' import type { ErrorComponent } from './error-boundary'
import { import {
CacheStates,
LayoutRouterContext, LayoutRouterContext,
GlobalLayoutRouterContext, GlobalLayoutRouterContext,
TemplateContext, TemplateContext,
...@@ -143,21 +144,29 @@ export function InnerLayoutRouter({ ...@@ -143,21 +144,29 @@ export function InnerLayoutRouter({
if ( if (
childProp && childProp &&
// TODO-APP: verify if this can be null based on user code // TODO-APP: verify if this can be null based on user code
childProp.current !== null && childProp.current !== null
!childNode /*&&
!childProp.partial*/
) { ) {
// Add the segment's subTreeData to the cache. if (childNode && childNode.status === CacheStates.LAZYINITIALIZED) {
// This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode. // @ts-expect-error TODO-APP: handle changing of the type
childNodes.set(path, { childNode.status = CacheStates.READY
data: null, // @ts-expect-error TODO-APP: handle changing of the type
subTreeData: childProp.current, childNode.subTreeData = childProp.current
parallelRoutes: new Map(), // Mutates the prop in order to clean up the memory associated with the subTreeData as it is now part of the cache.
}) childProp.current = null
// Mutates the prop in order to clean up the memory associated with the subTreeData as it is now part of the cache. } else {
childProp.current = null // Add the segment's subTreeData to the cache.
// In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again. // This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode.
childNode = childNodes.get(path) childNodes.set(path, {
status: CacheStates.READY,
data: null,
subTreeData: childProp.current,
parallelRoutes: new Map(),
})
// Mutates the prop in order to clean up the memory associated with the subTreeData as it is now part of the cache.
childProp.current = null
// In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again.
childNode = childNodes.get(path)
}
} }
// When childNode is not available during rendering client-side we need to fetch it from the server. // When childNode is not available during rendering client-side we need to fetch it from the server.
...@@ -172,6 +181,7 @@ export function InnerLayoutRouter({ ...@@ -172,6 +181,7 @@ export function InnerLayoutRouter({
* Flight data fetch kicked off during render and put into the cache. * Flight data fetch kicked off during render and put into the cache.
*/ */
childNodes.set(path, { childNodes.set(path, {
status: CacheStates.DATAFETCH,
data: fetchServerResponse(new URL(url, location.origin), refetchTree), data: fetchServerResponse(new URL(url, location.origin), refetchTree),
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
......
import type { CacheNode } from '../../shared/lib/app-router-context' import { CacheNode, CacheStates } from '../../shared/lib/app-router-context'
import type { import type {
FlightRouterState, FlightRouterState,
FlightData, FlightData,
...@@ -55,7 +55,7 @@ function invalidateCacheByRouterState( ...@@ -55,7 +55,7 @@ function invalidateCacheByRouterState(
newCache: CacheNode, newCache: CacheNode,
existingCache: CacheNode, existingCache: CacheNode,
routerState: FlightRouterState routerState: FlightRouterState
) { ): void {
// Remove segment that we got data for so that it is filled in during rendering of subTreeData. // Remove segment that we got data for so that it is filled in during rendering of subTreeData.
for (const key in routerState[1]) { for (const key in routerState[1]) {
const segmentForParallelRoute = routerState[1][key][0] const segmentForParallelRoute = routerState[1][key][0]
...@@ -72,6 +72,65 @@ function invalidateCacheByRouterState( ...@@ -72,6 +72,65 @@ function invalidateCacheByRouterState(
} }
} }
function fillLazyItemsTillLeafWithHead(
newCache: CacheNode,
existingCache: CacheNode | undefined,
routerState: FlightRouterState,
head: React.ReactNode
): void {
const isLastSegment = Object.keys(routerState[1]).length === 0
if (isLastSegment) {
newCache.head = head
return
}
// Remove segment that we got data for so that it is filled in during rendering of subTreeData.
for (const key in routerState[1]) {
const parallelRouteState = routerState[1][key]
const segmentForParallelRoute = parallelRouteState[0]
const cacheKey = Array.isArray(segmentForParallelRoute)
? segmentForParallelRoute[1]
: segmentForParallelRoute
if (existingCache) {
const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
parallelRouteCacheNode.delete(cacheKey)
const newCacheNode: CacheNode = {
status: CacheStates.LAZYINITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
}
parallelRouteCacheNode.set(cacheKey, newCacheNode)
fillLazyItemsTillLeafWithHead(
newCacheNode,
undefined,
parallelRouteState,
head
)
newCache.parallelRoutes.set(key, parallelRouteCacheNode)
continue
}
}
const newCacheNode: CacheNode = {
status: CacheStates.LAZYINITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
}
newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))
fillLazyItemsTillLeafWithHead(
newCacheNode,
undefined,
parallelRouteState,
head
)
}
}
/** /**
* Fill cache with subTreeData based on flightDataPath * Fill cache with subTreeData based on flightDataPath
*/ */
...@@ -111,6 +170,7 @@ function fillCacheWithNewSubTreeData( ...@@ -111,6 +170,7 @@ function fillCacheWithNewSubTreeData(
childCacheNode === existingChildCacheNode childCacheNode === existingChildCacheNode
) { ) {
childCacheNode = { childCacheNode = {
status: CacheStates.READY,
data: null, data: null,
subTreeData: flightDataPath[3], subTreeData: flightDataPath[3],
// Ensure segments other than the one we got data for are preserved. // Ensure segments other than the one we got data for are preserved.
...@@ -127,6 +187,13 @@ function fillCacheWithNewSubTreeData( ...@@ -127,6 +187,13 @@ function fillCacheWithNewSubTreeData(
) )
} }
fillLazyItemsTillLeafWithHead(
childCacheNode,
existingChildCacheNode,
flightDataPath[2],
/* flightDataPath[4] */ undefined
)
childSegmentMap.set(segmentForCache, childCacheNode) childSegmentMap.set(segmentForCache, childCacheNode)
} }
return return
...@@ -140,10 +207,11 @@ function fillCacheWithNewSubTreeData( ...@@ -140,10 +207,11 @@ function fillCacheWithNewSubTreeData(
if (childCacheNode === existingChildCacheNode) { if (childCacheNode === existingChildCacheNode) {
childCacheNode = { childCacheNode = {
status: childCacheNode.status,
data: childCacheNode.data, data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData, subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes), parallelRoutes: new Map(childCacheNode.parallelRoutes),
} } as CacheNode
childSegmentMap.set(segmentForCache, childCacheNode) childSegmentMap.set(segmentForCache, childCacheNode)
} }
...@@ -199,10 +267,11 @@ function invalidateCacheBelowFlightSegmentPath( ...@@ -199,10 +267,11 @@ function invalidateCacheBelowFlightSegmentPath(
if (childCacheNode === existingChildCacheNode) { if (childCacheNode === existingChildCacheNode) {
childCacheNode = { childCacheNode = {
status: childCacheNode.status,
data: childCacheNode.data, data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData, subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes), parallelRoutes: new Map(childCacheNode.parallelRoutes),
} } as CacheNode
childSegmentMap.set(segmentForCache, childCacheNode) childSegmentMap.set(segmentForCache, childCacheNode)
} }
...@@ -239,6 +308,7 @@ function fillCacheWithPrefetchedSubTreeData( ...@@ -239,6 +308,7 @@ function fillCacheWithPrefetchedSubTreeData(
if (isLastEntry) { if (isLastEntry) {
if (!existingChildCacheNode) { if (!existingChildCacheNode) {
existingChildSegmentMap.set(segmentForCache, { existingChildSegmentMap.set(segmentForCache, {
status: CacheStates.READY,
data: null, data: null,
subTreeData: flightDataPath[3], subTreeData: flightDataPath[3],
parallelRoutes: new Map(), parallelRoutes: new Map(),
...@@ -300,6 +370,7 @@ function fillCacheWithDataProperty( ...@@ -300,6 +370,7 @@ function fillCacheWithDataProperty(
childCacheNode === existingChildCacheNode childCacheNode === existingChildCacheNode
) { ) {
childSegmentMap.set(segment, { childSegmentMap.set(segment, {
status: CacheStates.DATAFETCH,
data: fetchResponse(), data: fetchResponse(),
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
...@@ -312,6 +383,7 @@ function fillCacheWithDataProperty( ...@@ -312,6 +383,7 @@ function fillCacheWithDataProperty(
// Start fetch in the place where the existing cache doesn't have the data yet. // Start fetch in the place where the existing cache doesn't have the data yet.
if (!childCacheNode) { if (!childCacheNode) {
childSegmentMap.set(segment, { childSegmentMap.set(segment, {
status: CacheStates.DATAFETCH,
data: fetchResponse(), data: fetchResponse(),
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
...@@ -322,10 +394,11 @@ function fillCacheWithDataProperty( ...@@ -322,10 +394,11 @@ function fillCacheWithDataProperty(
if (childCacheNode === existingChildCacheNode) { if (childCacheNode === existingChildCacheNode) {
childCacheNode = { childCacheNode = {
status: childCacheNode.status,
data: childCacheNode.data, data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData, subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes), parallelRoutes: new Map(childCacheNode.parallelRoutes),
} } as CacheNode
childSegmentMap.set(segment, childCacheNode) childSegmentMap.set(segment, childCacheNode)
} }
......
...@@ -6,26 +6,61 @@ import type { FlightRouterState, FlightData } from '../../server/app-render' ...@@ -6,26 +6,61 @@ import type { FlightRouterState, FlightData } from '../../server/app-render'
export type ChildSegmentMap = Map<string, CacheNode> export type ChildSegmentMap = Map<string, CacheNode>
// eslint-disable-next-line no-shadow
export enum CacheStates {
LAZYINITIALIZED = 'LAZYINITIALIZED',
DATAFETCH = 'DATAFETCH',
READY = 'READY',
}
/** /**
* Cache node used in app-router / layout-router. * Cache node used in app-router / layout-router.
*/ */
export type CacheNode = { export type CacheNode =
/** | {
* In-flight request for this node. status: CacheStates.DATAFETCH
*/ /**
data: ReturnType< * In-flight request for this node.
typeof import('../../client/components/app-router').fetchServerResponse */
> | null data: ReturnType<
/** typeof import('../../client/components/app-router').fetchServerResponse
* React Component for this node. > | null
*/ head?: React.ReactNode
subTreeData: React.ReactNode | null /**
/** * React Component for this node.
* Child parallel routes. */
*/ subTreeData: null
parallelRoutes: Map<string, ChildSegmentMap> /**
} * Child parallel routes.
*/
parallelRoutes: Map<string, ChildSegmentMap>
}
| {
status: CacheStates.READY
/**
* In-flight request for this node.
*/
data: null
head?: React.ReactNode
/**
* React Component for this node.
*/
subTreeData: React.ReactNode
/**
* Child parallel routes.
*/
parallelRoutes: Map<string, ChildSegmentMap>
}
| {
status: CacheStates.LAZYINITIALIZED
data: null
head?: React.ReactNode
subTreeData: null
/**
* Child parallel routes.
*/
parallelRoutes: Map<string, ChildSegmentMap>
}
interface NavigateOptions { interface NavigateOptions {
forceOptimisticNavigation?: boolean forceOptimisticNavigation?: boolean
} }
......
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