forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.ts
1743 lines (1624 loc) · 60.4 KB
/
cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
TreePrefetch,
RootTreePrefetch,
SegmentPrefetch,
} from '../../../server/app-render/collect-segment-data'
import type {
HeadData,
LoadingModuleData,
} from '../../../shared/lib/app-router-context.shared-runtime'
import type {
CacheNodeSeedData,
Segment as FlightRouterStateSegment,
} from '../../../server/app-render/types'
import {
NEXT_DID_POSTPONE_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STALE_TIME_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_URL,
RSC_CONTENT_TYPE_HEADER,
RSC_HEADER,
} from '../app-router-headers'
import {
createFetch,
createFromNextReadableStream,
type RequestHeaders,
} from '../router-reducer/fetch-server-response'
import {
pingPrefetchTask,
isPrefetchTaskDirty,
type PrefetchTask,
type PrefetchSubtaskResult,
} from './scheduler'
import { getAppBuildId } from '../../app-build-id'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import type {
NormalizedHref,
NormalizedNextUrl,
NormalizedSearch,
RouteCacheKey,
} from './cache-key'
import { createTupleMap, type TupleMap, type Prefix } from './tuple-map'
import { createLRU } from './lru'
import {
convertSegmentPathToStaticExportFilename,
encodeChildSegmentKey,
encodeSegment,
ROOT_SEGMENT_KEY,
} from '../../../shared/lib/segment-cache/segment-value-encoding'
import type {
FlightRouterState,
NavigationFlightResponse,
} from '../../../server/app-render/types'
import { normalizeFlightData } from '../../flight-data-helpers'
import { STATIC_STALETIME_MS } from '../router-reducer/prefetch-cache-utils'
import { pingVisibleLinks } from '../links'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
// A note on async/await when working in the prefetch cache:
//
// Most async operations in the prefetch cache should *not* use async/await,
// Instead, spawn a subtask that writes the results to a cache entry, and attach
// a "ping" listener to notify the prefetch queue to try again.
//
// The reason is we need to be able to access the segment cache and traverse its
// data structures synchronously. For example, if there's a synchronous update
// we can take an immediate snapshot of the cache to produce something we can
// render. Limiting the use of async/await also makes it easier to avoid race
// conditions, which is especially important because is cache is mutable.
//
// Another reason is that while we're performing async work, it's possible for
// existing entries to become stale, or for Link prefetches to be removed from
// the queue. For optimal scheduling, we need to be able to "cancel" subtasks
// that are no longer needed. So, when a segment is received from the server, we
// restart from the root of the tree that's being prefetched, to confirm all the
// parent segments are still cached. If the segment is no longer reachable from
// the root, then it's effectively canceled. This is similar to the design of
// Rust Futures, or React Suspense.
export type RouteTree = {
key: string
segment: FlightRouterStateSegment
slots: null | {
[parallelRouteKey: string]: RouteTree
}
isRootLayout: boolean
}
type RouteCacheEntryShared = {
staleAt: number
// This is false only if we're certain the route cannot be intercepted. It's
// true in all other cases, including on initialization when we haven't yet
// received a response from the server.
couldBeIntercepted: boolean
// LRU-related fields
keypath: null | Prefix<RouteCacheKeypath>
next: null | RouteCacheEntry
prev: null | RouteCacheEntry
size: number
}
/**
* Tracks the status of a cache entry as it progresses from no data (Empty),
* waiting for server data (Pending), and finished (either Fulfilled or
* Rejected depending on the response from the server.
*/
export const enum EntryStatus {
Empty,
Pending,
Fulfilled,
Rejected,
}
type PendingRouteCacheEntry = RouteCacheEntryShared & {
status: EntryStatus.Empty | EntryStatus.Pending
blockedTasks: Set<PrefetchTask> | null
canonicalUrl: null
tree: null
head: HeadData | null
isHeadPartial: true
isPPREnabled: false
}
type RejectedRouteCacheEntry = RouteCacheEntryShared & {
status: EntryStatus.Rejected
blockedTasks: Set<PrefetchTask> | null
canonicalUrl: null
tree: null
head: null
isHeadPartial: true
isPPREnabled: boolean
}
export type FulfilledRouteCacheEntry = RouteCacheEntryShared & {
status: EntryStatus.Fulfilled
blockedTasks: null
canonicalUrl: string
tree: RouteTree
head: HeadData
isHeadPartial: boolean
isPPREnabled: boolean
}
export type RouteCacheEntry =
| PendingRouteCacheEntry
| FulfilledRouteCacheEntry
| RejectedRouteCacheEntry
export const enum FetchStrategy {
PPR,
Full,
LoadingBoundary,
}
type SegmentCacheEntryShared = {
staleAt: number
fetchStrategy: FetchStrategy
revalidating: SegmentCacheEntry | null
// LRU-related fields
keypath: null | Prefix<SegmentCacheKeypath>
next: null | SegmentCacheEntry
prev: null | SegmentCacheEntry
size: number
}
export type EmptySegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Empty
rsc: null
loading: null
isPartial: true
promise: null
}
export type PendingSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Pending
rsc: null
loading: null
isPartial: true
promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>
}
type RejectedSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Rejected
rsc: null
loading: null
isPartial: true
promise: null
}
export type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Fulfilled
rsc: React.ReactNode | null
loading: LoadingModuleData | Promise<LoadingModuleData>
isPartial: boolean
promise: null
}
export type SegmentCacheEntry =
| EmptySegmentCacheEntry
| PendingSegmentCacheEntry
| RejectedSegmentCacheEntry
| FulfilledSegmentCacheEntry
export type NonEmptySegmentCacheEntry = Exclude<
SegmentCacheEntry,
EmptySegmentCacheEntry
>
const isOutputExportMode =
process.env.NODE_ENV === 'production' &&
process.env.__NEXT_CONFIG_OUTPUT === 'export'
// 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
// first level is keyed by href, the second level is keyed by Next-Url, and so
// on (if were to add more levels).
type RouteCacheKeypath = [NormalizedHref, NormalizedNextUrl]
let routeCacheMap: TupleMap<RouteCacheKeypath, RouteCacheEntry> =
createTupleMap()
// We use an LRU for memory management. We must update this whenever we add or
// remove a new cache entry, or when an entry changes size.
// TODO: I chose the max size somewhat arbitrarily. Consider setting this based
// on navigator.deviceMemory, or some other heuristic. We should make this
// customizable via the Next.js config, too.
const maxRouteLruSize = 10 * 1024 * 1024 // 10 MB
let routeCacheLru = createLRU<RouteCacheEntry>(
maxRouteLruSize,
onRouteLRUEviction
)
type SegmentCacheKeypath = [string, NormalizedSearch]
let segmentCacheMap: TupleMap<SegmentCacheKeypath, SegmentCacheEntry> =
createTupleMap()
// NOTE: Segments and Route entries are managed by separate LRUs. We could
// combine them into a single LRU, but because they are separate types, we'd
// need to wrap each one in an extra LRU node (to maintain monomorphism, at the
// cost of additional memory).
const maxSegmentLruSize = 50 * 1024 * 1024 // 50 MB
let segmentCacheLru = createLRU<SegmentCacheEntry>(
maxSegmentLruSize,
onSegmentLRUEviction
)
// All invalidation listeners for the whole cache are tracked in single set.
// Since we don't yet support tag or path-based invalidation, there's no point
// tracking them any more granularly than this. Once we add granular
// invalidation, that may change, though generally the model is to just notify
// the listeners and allow the caller to poll the prefetch cache with a new
// prefetch task if desired.
let invalidationListeners: Set<PrefetchTask> | null = null
// Incrementing counter used to track cache invalidations.
let currentCacheVersion = 0
export function getCurrentCacheVersion(): number {
return currentCacheVersion
}
/**
* Used to clear the client prefetch cache when a server action calls
* revalidatePath or revalidateTag. Eventually we will support only clearing the
* segments that were actually affected, but there's more work to be done on the
* server before the client is able to do this correctly.
*/
export function revalidateEntireCache(
nextUrl: string | null,
tree: FlightRouterState
) {
currentCacheVersion++
// Clearing the cache also effectively rejects any pending requests, because
// when the response is received, it gets written into a cache entry that is
// no longer reachable.
// TODO: There's an exception to this case that we don't currently handle
// correctly: background revalidations. See note in `upsertSegmentEntry`.
routeCacheMap = createTupleMap()
routeCacheLru = createLRU(maxRouteLruSize, onRouteLRUEviction)
segmentCacheMap = createTupleMap()
segmentCacheLru = createLRU(maxSegmentLruSize, onSegmentLRUEviction)
// Prefetch all the currently visible links again, to re-fill the cache.
pingVisibleLinks(nextUrl, tree)
// Similarly, notify all invalidation listeners (i.e. those passed to
// `router.prefetch(onInvalidate)`), so they can trigger a new prefetch
// if needed.
pingInvalidationListeners(nextUrl, tree)
}
function attachInvalidationListener(task: PrefetchTask): void {
// This function is called whenever a prefetch task reads a cache entry. If
// the task has an onInvalidate function associated with it — i.e. the one
// optionally passed to router.prefetch(onInvalidate) — then we attach that
// listener to the every cache entry that the task reads. Then, if an entry
// is invalidated, we call the function.
if (task.onInvalidate !== null) {
if (invalidationListeners === null) {
invalidationListeners = new Set([task])
} else {
invalidationListeners.add(task)
}
}
}
function notifyInvalidationListener(task: PrefetchTask): void {
const onInvalidate = task.onInvalidate
if (onInvalidate !== null) {
// Clear the callback from the task object to guarantee it's not called more
// than once.
task.onInvalidate = null
// This is a user-space function, so we must wrap in try/catch.
try {
onInvalidate()
} catch (error) {
if (typeof reportError === 'function') {
reportError(error)
} else {
console.error(error)
}
}
}
}
export function pingInvalidationListeners(
nextUrl: string | null,
tree: FlightRouterState
): void {
// The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.
// This is called when the Next-Url or the base tree changes, since those
// may affect the result of a prefetch task. It's also called after a
// cache invalidation.
if (invalidationListeners !== null) {
const tasks = invalidationListeners
invalidationListeners = null
for (const task of tasks) {
if (isPrefetchTaskDirty(task, nextUrl, tree)) {
notifyInvalidationListener(task)
}
}
}
}
export function readExactRouteCacheEntry(
now: number,
href: NormalizedHref,
nextUrl: NormalizedNextUrl | null
): RouteCacheEntry | null {
const keypath: Prefix<RouteCacheKeypath> =
nextUrl === null ? [href] : [href, nextUrl]
const existingEntry = routeCacheMap.get(keypath)
if (existingEntry !== null) {
// Check if the entry is stale
if (existingEntry.staleAt > now) {
// Reuse the existing entry.
// Since this is an access, move the entry to the front of the LRU.
routeCacheLru.put(existingEntry)
return existingEntry
} else {
// Evict the stale entry from the cache.
deleteRouteFromCache(existingEntry, keypath)
}
}
return null
}
export function readRouteCacheEntry(
now: number,
key: RouteCacheKey
): RouteCacheEntry | null {
// First check if there's a non-intercepted entry. Most routes cannot be
// intercepted, so this is the common case.
const nonInterceptedEntry = readExactRouteCacheEntry(now, key.href, null)
if (nonInterceptedEntry !== null && !nonInterceptedEntry.couldBeIntercepted) {
// Found a match, and the route cannot be intercepted. We can reuse it.
return nonInterceptedEntry
}
// There was no match. Check again but include the Next-Url this time.
return readExactRouteCacheEntry(now, key.href, key.nextUrl)
}
export function getSegmentKeypathForTask(
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
path: string
): Prefix<SegmentCacheKeypath> {
// When a prefetch includes dynamic data, the search params are included
// in the result, so we must include the search string in the segment
// cache key. (Note that this is true even if the search string is empty.)
//
// If we're fetching using PPR, we do not need to include the search params in
// the cache key, because the search params are treated as dynamic data. The
// cache entry is valid for all possible search param values.
const isDynamicTask = task.includeDynamicData || !route.isPPREnabled
return isDynamicTask && path.endsWith('/' + PAGE_SEGMENT_KEY)
? [path, task.key.search]
: [path]
}
export function readSegmentCacheEntry(
now: number,
routeCacheKey: RouteCacheKey,
path: string
): SegmentCacheEntry | null {
if (!path.endsWith('/' + PAGE_SEGMENT_KEY)) {
// Fast path. Search params only exist on page segments.
return readExactSegmentCacheEntry(now, [path])
}
// Page segments may or may not contain search params. If they were prefetched
// using a dynamic request, then we will have an entry with search params.
// Check for that case first.
const entryWithSearchParams = readExactSegmentCacheEntry(now, [
path,
routeCacheKey.search,
])
if (entryWithSearchParams !== null) {
return entryWithSearchParams
}
// If we did not find an entry with the given search params, check for a
// "fallback" entry, where the search params are treated as dynamic data. This
// is the common case because PPR/static prerenders always treat search params
// as dynamic.
//
// See corresponding logic in `getSegmentKeypathForTask`.
const entryWithoutSearchParams = readExactSegmentCacheEntry(now, [path])
return entryWithoutSearchParams
}
function readExactSegmentCacheEntry(
now: number,
keypath: Prefix<SegmentCacheKeypath>
): SegmentCacheEntry | null {
const existingEntry = segmentCacheMap.get(keypath)
if (existingEntry !== null) {
// Check if the entry is stale
if (existingEntry.staleAt > now) {
// Reuse the existing entry.
// Since this is an access, move the entry to the front of the LRU.
segmentCacheLru.put(existingEntry)
return existingEntry
} else {
// This is a stale entry.
const revalidatingEntry = existingEntry.revalidating
if (revalidatingEntry !== null) {
// There's a revalidation in progress. Upsert it.
const upsertedEntry = upsertSegmentEntry(
now,
keypath,
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, keypath)
}
}
}
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
}
export function waitForSegmentCacheEntry(
pendingEntry: PendingSegmentCacheEntry
): Promise<FulfilledSegmentCacheEntry | null> {
// Because the entry is pending, there's already a in-progress request.
// Attach a promise to the entry that will resolve when the server responds.
let promiseWithResolvers = pendingEntry.promise
if (promiseWithResolvers === null) {
promiseWithResolvers = pendingEntry.promise =
createPromiseWithResolvers<FulfilledSegmentCacheEntry | null>()
} else {
// There's already a promise we can use
}
return promiseWithResolvers.promise
}
/**
* Checks if an entry for a route exists in the cache. If so, it returns the
* entry, If not, it adds an empty entry to the cache and returns it.
*/
export function readOrCreateRouteCacheEntry(
now: number,
task: PrefetchTask
): RouteCacheEntry {
attachInvalidationListener(task)
const key = task.key
const existingEntry = readRouteCacheEntry(now, key)
if (existingEntry !== null) {
return existingEntry
}
// Create a pending entry and add it to the cache.
const pendingEntry: PendingRouteCacheEntry = {
canonicalUrl: null,
status: EntryStatus.Empty,
blockedTasks: null,
tree: null,
head: null,
isHeadPartial: true,
// Since this is an empty entry, there's no reason to ever evict it. It will
// be updated when the data is populated.
staleAt: Infinity,
// This is initialized to true because we don't know yet whether the route
// could be intercepted. It's only set to false once we receive a response
// from the server.
couldBeIntercepted: true,
// Similarly, we don't yet know if the route supports PPR.
isPPREnabled: false,
// LRU-related fields
keypath: null,
next: null,
prev: null,
size: 0,
}
const keypath: Prefix<RouteCacheKeypath> =
key.nextUrl === null ? [key.href] : [key.href, key.nextUrl]
routeCacheMap.set(keypath, 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.keypath = keypath
routeCacheLru.put(pendingEntry)
return pendingEntry
}
/**
* Checks if an entry for a segment exists in the cache. If so, it returns the
* entry, If not, it adds an empty entry to the cache and returns it.
*/
export function readOrCreateSegmentCacheEntry(
now: number,
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
path: string
): SegmentCacheEntry {
const keypath = getSegmentKeypathForTask(task, route, path)
const existingEntry = readExactSegmentCacheEntry(now, keypath)
if (existingEntry !== null) {
return existingEntry
}
// Create a pending entry and add it to the cache.
const pendingEntry = createDetachedSegmentCacheEntry(route.staleAt)
segmentCacheMap.set(keypath, 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.keypath = keypath
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,
keypath: Prefix<SegmentCacheKeypath>,
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).
// TODO: We should not upsert an entry if its key was invalidated in the time
// since the request was made. We can do that by passing the "owner" entry to
// this function and confirming it's the same as `existingEntry`.
const existingEntry = readExactSegmentCacheEntry(now, keypath)
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, keypath)
}
segmentCacheMap.set(keypath, 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.keypath = keypath
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,
isPartial: true,
promise: null,
// LRU-related fields
keypath: null,
next: null,
prev: null,
size: 0,
}
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
}
function deleteRouteFromCache(
entry: RouteCacheEntry,
keypath: Prefix<RouteCacheKeypath>
): void {
pingBlockedTasks(entry)
routeCacheMap.delete(keypath)
routeCacheLru.delete(entry)
}
function deleteSegmentFromCache(
entry: SegmentCacheEntry,
keypath: Prefix<SegmentCacheKeypath>
): void {
cancelEntryListeners(entry)
segmentCacheMap.delete(keypath)
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 {
// The LRU evicted this entry. Remove it from the map.
const keypath = entry.keypath
if (keypath !== null) {
entry.keypath = null
pingBlockedTasks(entry)
routeCacheMap.delete(keypath)
}
}
function onSegmentLRUEviction(entry: SegmentCacheEntry): void {
// The LRU evicted this entry. Remove it from the map.
const keypath = entry.keypath
if (keypath !== null) {
entry.keypath = null
cancelEntryListeners(entry)
segmentCacheMap.delete(keypath)
}
}
function cancelEntryListeners(entry: SegmentCacheEntry): void {
if (entry.status === EntryStatus.Pending && entry.promise !== null) {
// There were listeners for this entry. Resolve them with `null` to indicate
// that the prefetch failed. It's up to the listener to decide how to handle
// this case.
// NOTE: We don't currently propagate the reason the prefetch was canceled
// but we could by accepting a `reason` argument.
entry.promise.resolve(null)
entry.promise = null
}
}
function pingBlockedTasks(entry: {
blockedTasks: Set<PrefetchTask> | null
}): void {
const blockedTasks = entry.blockedTasks
if (blockedTasks !== null) {
for (const task of blockedTasks) {
pingPrefetchTask(task)
}
entry.blockedTasks = null
}
}
function fulfillRouteCacheEntry(
entry: RouteCacheEntry,
tree: RouteTree,
head: HeadData,
isHeadPartial: boolean,
staleAt: number,
couldBeIntercepted: boolean,
canonicalUrl: string,
isPPREnabled: boolean
): FulfilledRouteCacheEntry {
const fulfilledEntry: FulfilledRouteCacheEntry = entry as any
fulfilledEntry.status = EntryStatus.Fulfilled
fulfilledEntry.tree = tree
fulfilledEntry.head = head
fulfilledEntry.isHeadPartial = isHeadPartial
fulfilledEntry.staleAt = staleAt
fulfilledEntry.couldBeIntercepted = couldBeIntercepted
fulfilledEntry.canonicalUrl = canonicalUrl
fulfilledEntry.isPPREnabled = isPPREnabled
pingBlockedTasks(entry)
return fulfilledEntry
}
function fulfillSegmentCacheEntry(
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
fulfilledEntry.loading = loading
fulfilledEntry.staleAt = staleAt
fulfilledEntry.isPartial = isPartial
// Resolve any listeners that were waiting for this data.
if (segmentCacheEntry.promise !== null) {
segmentCacheEntry.promise.resolve(fulfilledEntry)
// Free the promise for garbage collection.
fulfilledEntry.promise = null
}
return fulfilledEntry
}
function rejectRouteCacheEntry(
entry: PendingRouteCacheEntry,
staleAt: number
): void {
const rejectedEntry: RejectedRouteCacheEntry = entry as any
rejectedEntry.status = EntryStatus.Rejected
rejectedEntry.staleAt = staleAt
pingBlockedTasks(entry)
}
function rejectSegmentCacheEntry(
entry: PendingSegmentCacheEntry,
staleAt: number
): void {
const rejectedEntry: RejectedSegmentCacheEntry = entry as any
rejectedEntry.status = EntryStatus.Rejected
rejectedEntry.staleAt = staleAt
if (entry.promise !== null) {
// NOTE: We don't currently propagate the reason the prefetch was canceled
// but we could by accepting a `reason` argument.
entry.promise.resolve(null)
entry.promise = null
}
}
function convertRootTreePrefetchToRouteTree(rootTree: RootTreePrefetch) {
return convertTreePrefetchToRouteTree(rootTree.tree, ROOT_SEGMENT_KEY)
}
function convertTreePrefetchToRouteTree(
prefetch: TreePrefetch,
key: string
): RouteTree {
// Converts the route tree sent by the server into the format used by the
// cache. The cached version of the tree includes additional fields, such as a
// cache key for each segment. Since this is frequently accessed, we compute
// it once instead of on every access. This same cache key is also used to
// request the segment from the server.
let slots: { [parallelRouteKey: string]: RouteTree } | null = null
const prefetchSlots = prefetch.slots
if (prefetchSlots !== null) {
slots = {}
for (let parallelRouteKey in prefetchSlots) {
const childPrefetch = prefetchSlots[parallelRouteKey]
const childSegment = childPrefetch.segment
// TODO: Eventually, the param values will not be included in the response
// from the server. We'll instead fill them in on the client by parsing
// the URL. This is where we'll do that.
const childKey = encodeChildSegmentKey(
key,
parallelRouteKey,
encodeSegment(childSegment)
)
slots[parallelRouteKey] = convertTreePrefetchToRouteTree(
childPrefetch,
childKey
)
}
}
return {
key,
segment: prefetch.segment,
slots,
isRootLayout: prefetch.isRootLayout,
}
}
function convertRootFlightRouterStateToRouteTree(
flightRouterState: FlightRouterState
): RouteTree {
return convertFlightRouterStateToRouteTree(
flightRouterState,
ROOT_SEGMENT_KEY
)
}
function convertFlightRouterStateToRouteTree(
flightRouterState: FlightRouterState,
key: string
): RouteTree {
let slots: { [parallelRouteKey: string]: RouteTree } | null = null
const parallelRoutes = flightRouterState[1]
for (let parallelRouteKey in parallelRoutes) {
const childRouterState = parallelRoutes[parallelRouteKey]
const childSegment = childRouterState[0]
// TODO: Eventually, the param values will not be included in the response
// from the server. We'll instead fill them in on the client by parsing
// the URL. This is where we'll do that.
const childKey = encodeChildSegmentKey(
key,
parallelRouteKey,
encodeSegment(childSegment)
)
const childTree = convertFlightRouterStateToRouteTree(
childRouterState,
childKey
)
if (slots === null) {
slots = {
[parallelRouteKey]: childTree,
}
} else {
slots[parallelRouteKey] = childTree
}
}
// The navigation implementation expects the search params to be included
// in the segment. However, in the case of a static response, the search
// params are omitted. So the client needs to add them back in when reading
// from the Segment Cache.
//
// For consistency, we'll do this for dynamic responses, too.
//
// TODO: We should move search params out of FlightRouterState and handle them
// entirely on the client, similar to our plan for dynamic params.
const originalSegment = flightRouterState[0]
const segmentWithoutSearchParams =
typeof originalSegment === 'string' &&
originalSegment.startsWith(PAGE_SEGMENT_KEY)
? PAGE_SEGMENT_KEY
: originalSegment
return {
key,
segment: segmentWithoutSearchParams,
slots,
isRootLayout: flightRouterState[4] === true,
}
}
export function convertRouteTreeToFlightRouterState(
routeTree: RouteTree
): FlightRouterState {
const parallelRoutes: Record<string, FlightRouterState> = {}
if (routeTree.slots !== null) {
for (const parallelRouteKey in routeTree.slots) {
parallelRoutes[parallelRouteKey] = convertRouteTreeToFlightRouterState(
routeTree.slots[parallelRouteKey]
)
}
}
const flightRouterState: FlightRouterState = [
routeTree.segment,
parallelRoutes,
null,
null,
routeTree.isRootLayout,
]
return flightRouterState
}
export async function fetchRouteOnCacheMiss(
entry: PendingRouteCacheEntry,
task: PrefetchTask
): 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 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
const segmentPath = '/_tree'
const headers: RequestHeaders = {
[RSC_HEADER]: '1',
[NEXT_ROUTER_PREFETCH_HEADER]: '1',
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: segmentPath,
}
if (nextUrl !== null) {
headers[NEXT_URL] = nextUrl
}
// In output: "export" mode, we need to add the segment path to the URL.
const url = new URL(href)
const requestUrl = isOutputExportMode
? addSegmentPathToUrlInOutputExportMode(url, segmentPath)
: url
try {
const response = await fetchPrefetchResponse(requestUrl, headers)
if (
!response ||
!response.ok ||
// 204 is a Cache miss. Though theoretically this shouldn't happen when
// PPR is enabled, because we always respond to route tree requests, even
// if it needs to be blockingly generated on demand.
response.status === 204 ||
!response.body
) {