Unverified Commit 61b285e5 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Generalize Segment Cache fallback implementation (#84652)

This is a stack of refactors related to the internal map type used to
store Segment Cache entries on the client. Refer to each commit message
for full details.

The main motivation is to generalize the "fallback entry" mechanism used
for interception routes to more kinds of params. Currently this is only
used for interception routes and search params, but in the future we
will use it for route params, too.
parent a99aaa9c
...@@ -2,14 +2,14 @@ ...@@ -2,14 +2,14 @@
type Opaque<K, T> = T & { __brand: K } type Opaque<K, T> = T & { __brand: K }
// Only functions in this module should be allowed to create CacheKeys. // Only functions in this module should be allowed to create CacheKeys.
export type NormalizedHref = Opaque<'NormalizedHref', string> export type NormalizedPathname = Opaque<'NormalizedPathname', string>
export type NormalizedSearch = Opaque<'NormalizedSearch', string> export type NormalizedSearch = Opaque<'NormalizedSearch', string>
export type NormalizedNextUrl = Opaque<'NormalizedNextUrl', string> export type NormalizedNextUrl = Opaque<'NormalizedNextUrl', string>
export type RouteCacheKey = Opaque< export type RouteCacheKey = Opaque<
'RouteCacheKey', 'RouteCacheKey',
{ {
href: NormalizedHref pathname: NormalizedPathname
search: NormalizedSearch search: NormalizedSearch
nextUrl: NormalizedNextUrl | null nextUrl: NormalizedNextUrl | null
...@@ -21,11 +21,9 @@ export function createCacheKey( ...@@ -21,11 +21,9 @@ export function createCacheKey(
originalHref: string, originalHref: string,
nextUrl: string | null nextUrl: string | null
): RouteCacheKey { ): RouteCacheKey {
// TODO: We should remove the hash from the href and track that separately.
// There's no reason to vary route entries by hash.
const originalUrl = new URL(originalHref) const originalUrl = new URL(originalHref)
const cacheKey = { const cacheKey = {
href: originalHref as NormalizedHref, pathname: originalUrl.pathname as NormalizedPathname,
search: originalUrl.search as NormalizedSearch, search: originalUrl.search as NormalizedSearch,
nextUrl: nextUrl as NormalizedNextUrl | null, nextUrl: nextUrl as NormalizedNextUrl | null,
} as RouteCacheKey } as RouteCacheKey
......
export type LRU<T extends LRUNode> = { import type { MapEntry } from './cache-map'
put(node: T): void import { deleteFromCacheMap } from './cache-map'
delete(node: T): void
updateSize(node: T, size: number): void
}
// Doubly-linked list // We use an LRU for memory management. We must update this whenever we add or
type LRUNode<T = any> = { // remove a new cache entry, or when an entry changes size.
// Although it's not encoded in the type, these are both null if the node is
// not in the LRU; both non-null if it is.
prev: T | null
next: T | null
size: number
}
// Rather than create an internal LRU node, the passed-in type must conform // The MapEntry type is used as an LRU node, too. We choose this one instead of
// the LRUNode interface. This is just a memory optimization to avoid creating // the inner cache entry type (RouteCacheEntry, SegmentCacheEntry) because it's
// another object; we only use this for Segment Cache entries so it doesn't need // monomorphic and can be optimized by the VM.
// to be general purpose. type LRUNode = MapEntry<any, any>
export function createLRU<T extends LRUNode>(
// From the LRU's perspective, the size unit is arbitrary, but for our
// purposes this is the byte size.
maxLruSize: number,
onEviction: (node: T) => void
): LRU<T> {
let head: T | null = null
let didScheduleCleanup: boolean = false
let lruSize: number = 0
function put(node: T) { let head: LRUNode | null = null
if (head === node) { let didScheduleCleanup: boolean = false
// Already at the head let lruSize: number = 0
return
}
const prev = node.prev
const next = node.next
if (next === null || prev === null) {
// This is an insertion
lruSize += node.size
// Whenever we add an entry, we need to check if we've exceeded the
// max size. We don't evict entries immediately; they're evicted later in
// an asynchronous task.
ensureCleanupIsScheduled()
} else {
// This is a move. Remove from its current position.
prev.next = next
next.prev = prev
}
// Move to the front of the list // TODO: I chose the max size somewhat arbitrarily. Consider setting this based
if (head === null) { // on navigator.deviceMemory, or some other heuristic. We should make this
// This is the first entry // customizable via the Next.js config, too.
node.prev = node const maxLruSize = 50 * 1024 * 1024 // 50 MB
node.next = node
} else { export function lruPut(node: LRUNode) {
// Add to the front of the list if (head === node) {
const tail = head.prev // Already at the head
node.prev = tail return
}
const prev = node.prev
const next = node.next
if (next === null || prev === null) {
// This is an insertion
lruSize += node.size
// Whenever we add an entry, we need to check if we've exceeded the
// max size. We don't evict entries immediately; they're evicted later in
// an asynchronous task.
ensureCleanupIsScheduled()
} else {
// This is a move. Remove from its current position.
prev.next = next
next.prev = prev
}
// Move to the front of the list
if (head === null) {
// This is the first entry
node.prev = node
node.next = node
} else {
// Add to the front of the list
const tail = head.prev
node.prev = tail
// In practice, this is never null, but that isn't encoded in the type
if (tail !== null) {
tail.next = node tail.next = node
node.next = head
head.prev = node
} }
head = node node.next = head
head.prev = node
} }
head = node
}
function updateSize(node: T, newNodeSize: number) { export function updateLruSize(node: LRUNode, newNodeSize: number) {
// This is a separate function from `put` so that we can resize the entry // 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. // regardless of whether it's currently being tracked by the LRU.
const prevNodeSize = node.size const prevNodeSize = node.size
node.size = newNodeSize node.size = newNodeSize
if (node.next === null) { if (node.next === null) {
// This entry is not currently being tracked by the LRU. // This entry is not currently being tracked by the LRU.
return return
}
// Update the total LRU size
lruSize = lruSize - prevNodeSize + newNodeSize
ensureCleanupIsScheduled()
} }
// Update the total LRU size
lruSize = lruSize - prevNodeSize + newNodeSize
ensureCleanupIsScheduled()
}
function deleteNode(deleted: T) { export function deleteFromLru(deleted: LRUNode) {
const next = deleted.next const next = deleted.next
const prev = deleted.prev const prev = deleted.prev
if (next !== null && prev !== null) { if (next !== null && prev !== null) {
lruSize -= deleted.size lruSize -= deleted.size
deleted.next = null deleted.next = null
deleted.prev = null deleted.prev = null
// Remove from the list // Remove from the list
if (head === deleted) { if (head === deleted) {
// Update the head // Update the head
if (next === head) { if (next === head) {
// This was the last entry // This was the last entry
head = null head = null
} else {
head = next
}
} else { } else {
prev.next = next head = next
next.prev = prev
} }
} else { } else {
// Already deleted prev.next = next
next.prev = prev
} }
} else {
// Already deleted
} }
}
function ensureCleanupIsScheduled() { function ensureCleanupIsScheduled() {
if (didScheduleCleanup || lruSize <= maxLruSize) { if (didScheduleCleanup || lruSize <= maxLruSize) {
return return
}
didScheduleCleanup = true
requestCleanupCallback(cleanup)
} }
didScheduleCleanup = true
requestCleanupCallback(cleanup)
}
function cleanup() { function cleanup() {
didScheduleCleanup = false didScheduleCleanup = false
// Evict entries until we're at 90% capacity. We can assume this won't // Evict entries until we're at 90% capacity. We can assume this won't
// infinite loop because even if `maxLruSize` were 0, eventually // infinite loop because even if `maxLruSize` were 0, eventually
// `deleteNode` sets `head` to `null` when we run out entries. // `deleteFromLru` sets `head` to `null` when we run out entries.
const ninetyPercentMax = maxLruSize * 0.9 const ninetyPercentMax = maxLruSize * 0.9
while (lruSize > ninetyPercentMax && head !== null) { while (lruSize > ninetyPercentMax && head !== null) {
const tail = head.prev const tail = head.prev
deleteNode(tail) // In practice, this is never null, but that isn't encoded in the type
onEviction(tail) if (tail !== null) {
// Delete the entry from the map. In turn, this will remove it from
// the LRU.
deleteFromCacheMap(tail.value)
} }
} }
return {
put,
delete: deleteNode,
updateSize,
}
} }
const requestCleanupCallback = const requestCleanupCallback =
......
...@@ -19,6 +19,7 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url' ...@@ -19,6 +19,7 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import { import {
EntryStatus, EntryStatus,
readRouteCacheEntry, readRouteCacheEntry,
getCanonicalSegmentKeypath,
readSegmentCacheEntry, readSegmentCacheEntry,
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
requestOptimisticRouteCacheEntry, requestOptimisticRouteCacheEntry,
...@@ -123,7 +124,13 @@ export function navigate( ...@@ -123,7 +124,13 @@ export function navigate(
const prefetchSeedData = snapshot.seedData const prefetchSeedData = snapshot.seedData
const prefetchHead = route.head const prefetchHead = route.head
const isPrefetchHeadPartial = route.isHeadPartial const isPrefetchHeadPartial = route.isHeadPartial
const newCanonicalUrl = route.canonicalUrl // TODO: The "canonicalUrl" stored in the cache doesn't include the hash,
// because hash entries do not vary by hash fragment. However, the one
// we set in the router state *does* include the hash, and it's used to
// sync with the actual browser location. To make this less of a refactor
// hazard, we should always track the hash separately from the rest of
// the URL.
const newCanonicalUrl = route.canonicalUrl + url.hash
const renderedSearch = route.renderedSearch const renderedSearch = route.renderedSearch
return navigateUsingPrefetchedRouteTree( return navigateUsingPrefetchedRouteTree(
now, now,
...@@ -166,7 +173,7 @@ export function navigate( ...@@ -166,7 +173,7 @@ export function navigate(
const prefetchSeedData = snapshot.seedData const prefetchSeedData = snapshot.seedData
const prefetchHead = optimisticRoute.head const prefetchHead = optimisticRoute.head
const isPrefetchHeadPartial = optimisticRoute.isHeadPartial const isPrefetchHeadPartial = optimisticRoute.isHeadPartial
const newCanonicalUrl = optimisticRoute.canonicalUrl const newCanonicalUrl = optimisticRoute.canonicalUrl + url.hash
const newRenderedSearch = optimisticRoute.renderedSearch const newRenderedSearch = optimisticRoute.renderedSearch
return navigateUsingPrefetchedRouteTree( return navigateUsingPrefetchedRouteTree(
now, now,
...@@ -338,7 +345,11 @@ function readRenderSnapshotFromCache( ...@@ -338,7 +345,11 @@ function readRenderSnapshotFromCache(
let loading: LoadingModuleData | Promise<LoadingModuleData> = null let loading: LoadingModuleData | Promise<LoadingModuleData> = null
let isPartial: boolean = true let isPartial: boolean = true
const segmentEntry = readSegmentCacheEntry(now, route, tree.cacheKey) const canonicalSegmentKeypath = getCanonicalSegmentKeypath(
route,
tree.cacheKey
)
const segmentEntry = readSegmentCacheEntry(now, canonicalSegmentKeypath)
if (segmentEntry !== null) { if (segmentEntry !== null) {
switch (segmentEntry.status) { switch (segmentEntry.status) {
case EntryStatus.Fulfilled: { case EntryStatus.Fulfilled: {
......
...@@ -23,9 +23,10 @@ import { ...@@ -23,9 +23,10 @@ import {
type FulfilledSegmentCacheEntry, type FulfilledSegmentCacheEntry,
upgradeToPendingSegment, upgradeToPendingSegment,
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
resetRevalidatingSegmentEntry, overwriteRevalidatingSegmentCacheEntry,
getSegmentKeypath, getGenericSegmentKeypathFromFetchStrategy,
canNewFetchStrategyProvideMoreContent, canNewFetchStrategyProvideMoreContent,
type SegmentCacheKeypath,
} from './cache' } from './cache'
import type { RouteCacheKey } from './cache-key' import type { RouteCacheKey } from './cache-key'
import { createCacheKey } from './cache-key' import { createCacheKey } from './cache-key'
...@@ -556,8 +557,7 @@ function pingRoute(now: number, task: PrefetchTask): PrefetchTaskExitStatus { ...@@ -556,8 +557,7 @@ function pingRoute(now: number, task: PrefetchTask): PrefetchTaskExitStatus {
// a wildcard lookup method to the TupleMap implementation. This is // a wildcard lookup method to the TupleMap implementation. This is
// non-trivial to implement because it needs to account for things like // non-trivial to implement because it needs to account for things like
// fallback route entries, hence this temporary workaround. // fallback route entries, hence this temporary workaround.
const url = new URL(key.href) const url = new URL(key.pathname, location.origin)
url.search = ''
const keyWithoutSearch = createCacheKey(url.href, key.nextUrl) const keyWithoutSearch = createCacheKey(url.href, key.nextUrl)
const routeWithoutSearch = readOrCreateRouteCacheEntry( const routeWithoutSearch = readOrCreateRouteCacheEntry(
now, now,
...@@ -1265,7 +1265,6 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -1265,7 +1265,6 @@ function pingRouteTreeAndIncludeDynamicData(
spawnedSegment = pingFullSegmentRevalidation( spawnedSegment = pingFullSegmentRevalidation(
now, now,
route, route,
segment,
tree, tree,
fetchStrategy fetchStrategy
) )
...@@ -1285,7 +1284,6 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -1285,7 +1284,6 @@ function pingRouteTreeAndIncludeDynamicData(
spawnedSegment = pingFullSegmentRevalidation( spawnedSegment = pingFullSegmentRevalidation(
now, now,
route, route,
segment,
tree, tree,
fetchStrategy fetchStrategy
) )
...@@ -1421,14 +1419,7 @@ function pingStaticSegmentData( ...@@ -1421,14 +1419,7 @@ function pingStaticSegmentData(
if (background(task)) { if (background(task)) {
// TODO: Instead of speculatively revalidating, consider including // TODO: Instead of speculatively revalidating, consider including
// `hasLoading` in the route tree prefetch response. // `hasLoading` in the route tree prefetch response.
pingPPRSegmentRevalidation( pingPPRSegmentRevalidation(now, route, routeKey, tree)
now,
task,
segment,
route,
routeKey,
tree
)
} }
break break
default: default:
...@@ -1456,7 +1447,7 @@ function pingStaticSegmentData( ...@@ -1456,7 +1447,7 @@ function pingStaticSegmentData(
// Because a rejected segment will definitely prevent the segment (and // Because a rejected segment will definitely prevent the segment (and
// all of its children) from rendering, we perform this revalidation // all of its children) from rendering, we perform this revalidation
// immediately instead of deferring it to a background task. // immediately instead of deferring it to a background task.
pingPPRSegmentRevalidation(now, task, segment, route, routeKey, tree) pingPPRSegmentRevalidation(now, route, routeKey, tree)
break break
default: default:
segment.fetchStrategy satisfies never segment.fetchStrategy satisfies never
...@@ -1477,24 +1468,21 @@ function pingStaticSegmentData( ...@@ -1477,24 +1468,21 @@ function pingStaticSegmentData(
function pingPPRSegmentRevalidation( function pingPPRSegmentRevalidation(
now: number, now: number,
task: PrefetchTask,
currentSegment: SegmentCacheEntry,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
routeKey: RouteCacheKey, routeKey: RouteCacheKey,
tree: RouteTree tree: RouteTree
): void { ): void {
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry( const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
now, now,
currentSegment FetchStrategy.PPR,
route,
tree.cacheKey
) )
switch (revalidatingSegment.status) { switch (revalidatingSegment.status) {
case EntryStatus.Empty: case EntryStatus.Empty:
// Spawn a prefetch request and upsert the segment into the cache // Spawn a prefetch request and upsert the segment into the cache
// upon completion. // upon completion.
upsertSegmentOnCompletion( upsertSegmentOnCompletion(
task.fetchStrategy,
route,
tree.cacheKey,
spawnPrefetchSubtask( spawnPrefetchSubtask(
fetchSegmentOnCacheMiss( fetchSegmentOnCacheMiss(
route, route,
...@@ -1502,6 +1490,11 @@ function pingPPRSegmentRevalidation( ...@@ -1502,6 +1490,11 @@ function pingPPRSegmentRevalidation(
routeKey, routeKey,
tree tree
) )
),
getGenericSegmentKeypathFromFetchStrategy(
FetchStrategy.PPR,
route,
tree.cacheKey
) )
) )
break break
...@@ -1522,13 +1515,14 @@ function pingPPRSegmentRevalidation( ...@@ -1522,13 +1515,14 @@ function pingPPRSegmentRevalidation(
function pingFullSegmentRevalidation( function pingFullSegmentRevalidation(
now: number, now: number,
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
currentSegment: SegmentCacheEntry,
tree: RouteTree, tree: RouteTree,
fetchStrategy: FetchStrategy.Full | FetchStrategy.PPRRuntime fetchStrategy: FetchStrategy.Full | FetchStrategy.PPRRuntime
): PendingSegmentCacheEntry | null { ): PendingSegmentCacheEntry | null {
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry( const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
now, now,
currentSegment fetchStrategy,
route,
tree.cacheKey
) )
if (revalidatingSegment.status === EntryStatus.Empty) { if (revalidatingSegment.status === EntryStatus.Empty) {
// During a Full/PPRRuntime prefetch, a single dynamic request is made for all the // During a Full/PPRRuntime prefetch, a single dynamic request is made for all the
...@@ -1541,10 +1535,12 @@ function pingFullSegmentRevalidation( ...@@ -1541,10 +1535,12 @@ function pingFullSegmentRevalidation(
fetchStrategy fetchStrategy
) )
upsertSegmentOnCompletion( upsertSegmentOnCompletion(
fetchStrategy, waitForSegmentCacheEntry(pendingSegment),
route, getGenericSegmentKeypathFromFetchStrategy(
tree.cacheKey, fetchStrategy,
waitForSegmentCacheEntry(pendingSegment) route,
tree.cacheKey
)
) )
return pendingSegment return pendingSegment
} else { } else {
...@@ -1558,18 +1554,22 @@ function pingFullSegmentRevalidation( ...@@ -1558,18 +1554,22 @@ function pingFullSegmentRevalidation(
) { ) {
// The existing revalidation was fetched using a less specific strategy. // The existing revalidation was fetched using a less specific strategy.
// Reset it and start a new revalidation. // Reset it and start a new revalidation.
const emptySegment = resetRevalidatingSegmentEntry( const emptySegment = overwriteRevalidatingSegmentCacheEntry(
nonEmptyRevalidatingSegment fetchStrategy,
route,
tree.cacheKey
) )
const pendingSegment = upgradeToPendingSegment( const pendingSegment = upgradeToPendingSegment(
emptySegment, emptySegment,
fetchStrategy fetchStrategy
) )
upsertSegmentOnCompletion( upsertSegmentOnCompletion(
fetchStrategy, waitForSegmentCacheEntry(pendingSegment),
route, getGenericSegmentKeypathFromFetchStrategy(
tree.cacheKey, fetchStrategy,
waitForSegmentCacheEntry(pendingSegment) route,
tree.cacheKey
)
) )
return pendingSegment return pendingSegment
} }
...@@ -1593,16 +1593,13 @@ function pingFullSegmentRevalidation( ...@@ -1593,16 +1593,13 @@ function pingFullSegmentRevalidation(
const noop = () => {} const noop = () => {}
function upsertSegmentOnCompletion( function upsertSegmentOnCompletion(
fetchStrategy: FetchStrategy, promise: Promise<FulfilledSegmentCacheEntry | null>,
route: FulfilledRouteCacheEntry, keypath: SegmentCacheKeypath
cacheKey: SegmentCacheKey,
promise: Promise<FulfilledSegmentCacheEntry | null>
) { ) {
// Wait for a segment to finish loading, then upsert it into the cache // Wait for a segment to finish loading, then upsert it into the cache
promise.then((fulfilled) => { promise.then((fulfilled) => {
if (fulfilled !== null) { if (fulfilled !== null) {
// Received new data. Attempt to replace the existing entry in the cache. // Received new data. Attempt to replace the existing entry in the cache.
const keypath = getSegmentKeypath(fetchStrategy, route, cacheKey)
upsertSegmentEntry(Date.now(), keypath, fulfilled) upsertSegmentEntry(Date.now(), keypath, fulfilled)
} }
}, noop) }, noop)
......
// Utility type. Prefix<[A, B, C, D]> matches [A], [A, B], [A, B, C] etc.
export type Prefix<T extends any[]> = T extends [infer First, ...infer Rest]
? [] | [First] | [First, ...Prefix<Rest>]
: []
export type TupleMap<Keypath extends Array<any>, V> = {
set(keys: Prefix<Keypath>, value: V): void
get(keys: Prefix<Keypath>): V | null
delete(keys: Prefix<Keypath>): void
}
/**
* Creates a map whose keys are tuples. Tuples are compared per-element. This
* is useful when a key has multiple parts, but you don't want to concatenate
* them into a single string value.
*
* In the Segment Cache, we use this to store cache entries by both their href
* and their Next-URL.
*
* Example:
* map.set(['https://localhost', 'foo/bar/baz'], 'yay');
* map.get(['https://localhost', 'foo/bar/baz']); // returns 'yay'
*/
export function createTupleMap<Keypath extends Array<any>, V>(): TupleMap<
Keypath,
V
> {
type MapEntryShared = {
parent: MapEntry | null
key: any
map: Map<any, MapEntry> | null
}
type EmptyMapEntry = MapEntryShared & {
value: null
hasValue: false
}
type FullMapEntry = MapEntryShared & {
value: V
hasValue: true
}
type MapEntry = EmptyMapEntry | FullMapEntry
let rootEntry: MapEntry = {
parent: null,
key: null,
hasValue: false,
value: null,
map: null,
}
// To optimize successive lookups, we cache the last accessed keypath.
// Although it's not encoded in the type, these are both null or
// both non-null. It uses object equality, so to take advantage of this
// optimization, you must pass the same array instance to each successive
// method call, and you must also not mutate the array between calls.
let lastAccessedEntry: MapEntry | null = null
let lastAccessedKeys: Prefix<Keypath> | null = null
function getOrCreateEntry(keys: Prefix<Keypath>): MapEntry {
if (lastAccessedKeys === keys) {
return lastAccessedEntry!
}
// Go through each level of keys until we find the entry that matches,
// or create a new one if it doesn't already exist.
let entry = rootEntry
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
let map = entry.map
if (map !== null) {
const existingEntry = map.get(key)
if (existingEntry !== undefined) {
// Found a match. Keep going.
entry = existingEntry
continue
}
} else {
map = new Map()
entry.map = map
}
// No entry exists yet at this level. Create a new one.
const newEntry: MapEntry = {
parent: entry,
key,
value: null,
hasValue: false,
map: null,
}
map.set(key, newEntry)
entry = newEntry
}
lastAccessedKeys = keys
lastAccessedEntry = entry
return entry
}
function getEntryIfExists(keys: Prefix<Keypath>): MapEntry | null {
if (lastAccessedKeys === keys) {
return lastAccessedEntry
}
// Go through each level of keys until we find the entry that matches, or
// return null if no match exists.
let entry = rootEntry
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
let map = entry.map
if (map !== null) {
const existingEntry = map.get(key)
if (existingEntry !== undefined) {
// Found a match. Keep going.
entry = existingEntry
continue
}
}
// No entry exists at this level.
return null
}
lastAccessedKeys = keys
lastAccessedEntry = entry
return entry
}
function set(keys: Prefix<Keypath>, value: V): void {
const entry = getOrCreateEntry(keys)
entry.hasValue = true
entry.value = value
}
function get(keys: Prefix<Keypath>): V | null {
const entry = getEntryIfExists(keys)
if (entry === null || !entry.hasValue) {
return null
}
return entry.value
}
function deleteEntry(keys: Prefix<Keypath>): void {
const entry = getEntryIfExists(keys)
if (entry === null || !entry.hasValue) {
return
}
// Found a match. Delete it from the cache.
const deletedEntry: EmptyMapEntry = entry as any
deletedEntry.hasValue = false
deletedEntry.value = null
// Check if we can garbage collect the entry.
if (deletedEntry.map === null) {
// Since this entry has no value, and also no child entries, we can
// garbage collect it. Remove it from its parent, and keep garbage
// collecting the parents until we reach a non-empty entry.
// Unlike a `set` operation, these are no longer valid because the entry
// itself is being modified, not just the value it contains.
lastAccessedEntry = null
lastAccessedKeys = null
let parent = deletedEntry.parent
let key = deletedEntry.key
while (parent !== null) {
const parentMap = parent.map
if (parentMap !== null) {
parentMap.delete(key)
if (parentMap.size === 0) {
// We just removed the last entry in the parent map.
parent.map = null
if (parent.value === null) {
// The parent node has no child entries, nor does it have a value
// on itself. It can be garbage collected. Keep going.
key = parent.key
parent = parent.parent
continue
}
}
}
// The parent is not empty. Stop garbage collecting.
break
}
}
}
return {
set,
get,
delete: deleteEntry,
}
}
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