-
-
Notifications
You must be signed in to change notification settings - Fork 351
/
index.ts
2289 lines (2141 loc) · 65.1 KB
/
index.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
/**
* @module LRUCache
*/
// module-private names and types
type Perf = { now: () => number }
const perf: Perf =
typeof performance === 'object' &&
performance &&
typeof performance.now === 'function'
? performance
: Date
const warned = new Set<string>()
// either a function or a class
type ForC = ((...a: any[]) => any) | { new (...a: any[]): any }
/* c8 ignore start */
const PROCESS = (
typeof process === 'object' && !!process ? process : {}
) as { [k: string]: any }
/* c8 ignore start */
const emitWarning = (
msg: string,
type: string,
code: string,
fn: ForC
) => {
typeof PROCESS.emitWarning === 'function'
? PROCESS.emitWarning(msg, type, code, fn)
: console.error(`[${code}] ${type}: ${msg}`)
}
let AC = globalThis.AbortController
let AS = globalThis.AbortSignal
/* c8 ignore start */
if (typeof AC === 'undefined') {
//@ts-ignore
AS = class AbortSignal {
onabort?: (...a: any[]) => any
_onabort: ((...a: any[]) => any)[] = []
reason?: any
aborted: boolean = false
addEventListener(_: string, fn: (...a: any[]) => any) {
this._onabort.push(fn)
}
}
//@ts-ignore
AC = class AbortController {
constructor() {
warnACPolyfill()
}
signal = new AS()
abort(reason: any) {
if (this.signal.aborted) return
//@ts-ignore
this.signal.reason = reason
//@ts-ignore
this.signal.aborted = true
//@ts-ignore
for (const fn of this.signal._onabort) {
fn(reason)
}
this.signal.onabort?.(reason)
}
}
let printACPolyfillWarning =
PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'
const warnACPolyfill = () => {
if (!printACPolyfillWarning) return
printACPolyfillWarning = false
emitWarning(
'AbortController is not defined. If using lru-cache in ' +
'node 14, load an AbortController polyfill from the ' +
'`node-abort-controller` package. A minimal polyfill is ' +
'provided for use by LRUCache.fetch(), but it should not be ' +
'relied upon in other contexts (eg, passing it to other APIs that ' +
'use AbortController/AbortSignal might have undesirable effects). ' +
'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',
'NO_ABORT_CONTROLLER',
'ENOTSUP',
warnACPolyfill
)
}
}
/* c8 ignore stop */
const shouldWarn = (code: string) => !warned.has(code)
const TYPE = Symbol('type')
type PosInt = number & { [TYPE]: 'Positive Integer' }
type Index = number & { [TYPE]: 'LRUCache Index' }
const isPosInt = (n: any): n is PosInt =>
n && n === Math.floor(n) && n > 0 && isFinite(n)
type UintArray = Uint8Array | Uint16Array | Uint32Array
type NumberArray = UintArray | number[]
/* c8 ignore start */
// This is a little bit ridiculous, tbh.
// The maximum array length is 2^32-1 or thereabouts on most JS impls.
// And well before that point, you're caching the entire world, I mean,
// that's ~32GB of just integers for the next/prev links, plus whatever
// else to hold that many keys and values. Just filling the memory with
// zeroes at init time is brutal when you get that big.
// But why not be complete?
// Maybe in the future, these limits will have expanded.
const getUintArray = (max: number) =>
!isPosInt(max)
? null
: max <= Math.pow(2, 8)
? Uint8Array
: max <= Math.pow(2, 16)
? Uint16Array
: max <= Math.pow(2, 32)
? Uint32Array
: max <= Number.MAX_SAFE_INTEGER
? ZeroArray
: null
/* c8 ignore stop */
class ZeroArray extends Array<number> {
constructor(size: number) {
super(size)
this.fill(0)
}
}
type StackLike = Stack | Index[]
class Stack {
heap: NumberArray
length: number
// private constructor
static #constructing: boolean = false
static create(max: number): StackLike {
const HeapCls = getUintArray(max)
if (!HeapCls) return []
Stack.#constructing = true
const s = new Stack(max, HeapCls)
Stack.#constructing = false
return s
}
constructor(
max: number,
HeapCls: { new (n: number): NumberArray }
) {
/* c8 ignore start */
if (!Stack.#constructing) {
throw new TypeError('instantiate Stack using Stack.create(n)')
}
/* c8 ignore stop */
this.heap = new HeapCls(max)
this.length = 0
}
push(n: Index) {
this.heap[this.length++] = n
}
pop(): Index {
return this.heap[--this.length] as Index
}
}
/**
* Promise representing an in-progress {@link LRUCache#fetch} call
*/
export type BackgroundFetch<V> = Promise<V | undefined | void> & {
__returned: BackgroundFetch<V> | undefined
__abortController: AbortController
__staleWhileFetching: V | undefined
}
type DisposeTask<K, V> = [
value: V,
key: K,
reason: LRUCache.DisposeReason
]
export namespace LRUCache {
/**
* An integer greater than 0, reflecting the calculated size of items
*/
export type Size = number
/**
* Integer greater than 0, representing some number of milliseconds, or the
* time at which a TTL started counting from.
*/
export type Milliseconds = number
/**
* An integer greater than 0, reflecting a number of items
*/
export type Count = number
/**
* The reason why an item was removed from the cache, passed
* to the {@link Disposer} methods.
*/
export type DisposeReason = 'evict' | 'set' | 'delete'
/**
* A method called upon item removal, passed as the
* {@link OptionsBase.dispose} and/or
* {@link OptionsBase.disposeAfter} options.
*/
export type Disposer<K, V> = (
value: V,
key: K,
reason: DisposeReason
) => void
/**
* A function that returns the effective calculated size
* of an entry in the cache.
*/
export type SizeCalculator<K, V> = (value: V, key: K) => Size
/**
* Options provided to the
* {@link OptionsBase.fetchMethod} function.
*/
export interface FetcherOptions<K, V, FC = unknown> {
signal: AbortSignal
options: FetcherFetchOptions<K, V, FC>
/**
* Object provided in the {@link FetchOptions.context} option to
* {@link LRUCache#fetch}
*/
context: FC
}
/**
* Status object that may be passed to {@link LRUCache#fetch},
* {@link LRUCache#get}, {@link LRUCache#set}, and {@link LRUCache#has}.
*/
export interface Status<V> {
/**
* The status of a set() operation.
*
* - add: the item was not found in the cache, and was added
* - update: the item was in the cache, with the same value provided
* - replace: the item was in the cache, and replaced
* - miss: the item was not added to the cache for some reason
*/
set?: 'add' | 'update' | 'replace' | 'miss'
/**
* the ttl stored for the item, or undefined if ttls are not used.
*/
ttl?: Milliseconds
/**
* the start time for the item, or undefined if ttls are not used.
*/
start?: Milliseconds
/**
* The timestamp used for TTL calculation
*/
now?: Milliseconds
/**
* the remaining ttl for the item, or undefined if ttls are not used.
*/
remainingTTL?: Milliseconds
/**
* The calculated size for the item, if sizes are used.
*/
entrySize?: Size
/**
* The total calculated size of the cache, if sizes are used.
*/
totalCalculatedSize?: Size
/**
* A flag indicating that the item was not stored, due to exceeding the
* {@link OptionsBase.maxEntrySize}
*/
maxEntrySizeExceeded?: true
/**
* The old value, specified in the case of `set:'update'` or
* `set:'replace'`
*/
oldValue?: V
/**
* The results of a {@link LRUCache#has} operation
*
* - hit: the item was found in the cache
* - stale: the item was found in the cache, but is stale
* - miss: the item was not found in the cache
*/
has?: 'hit' | 'stale' | 'miss'
/**
* The status of a {@link LRUCache#fetch} operation.
* Note that this can change as the underlying fetch() moves through
* various states.
*
* - inflight: there is another fetch() for this key which is in process
* - get: there is no fetchMethod, so {@link LRUCache#get} was called.
* - miss: the item is not in cache, and will be fetched.
* - hit: the item is in the cache, and was resolved immediately.
* - stale: the item is in the cache, but stale.
* - refresh: the item is in the cache, and not stale, but
* {@link FetchOptions.forceRefresh} was specified.
*/
fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'
/**
* The {@link OptionsBase.fetchMethod} was called
*/
fetchDispatched?: true
/**
* The cached value was updated after a successful call to
* {@link OptionsBase.fetchMethod}
*/
fetchUpdated?: true
/**
* The reason for a fetch() rejection. Either the error raised by the
* {@link OptionsBase.fetchMethod}, or the reason for an
* AbortSignal.
*/
fetchError?: Error
/**
* The fetch received an abort signal
*/
fetchAborted?: true
/**
* The abort signal received was ignored, and the fetch was allowed to
* continue.
*/
fetchAbortIgnored?: true
/**
* The fetchMethod promise resolved successfully
*/
fetchResolved?: true
/**
* The fetchMethod promise was rejected
*/
fetchRejected?: true
/**
* The status of a {@link LRUCache#get} operation.
*
* - fetching: The item is currently being fetched. If a previous value
* is present and allowed, that will be returned.
* - stale: The item is in the cache, and is stale.
* - hit: the item is in the cache
* - miss: the item is not in the cache
*/
get?: 'stale' | 'hit' | 'miss'
/**
* A fetch or get operation returned a stale value.
*/
returnedStale?: true
}
/**
* options which override the options set in the LRUCache constructor
* when calling {@link LRUCache#fetch}.
*
* This is the union of {@link GetOptions} and {@link SetOptions}, plus
* {@link OptionsBase.noDeleteOnFetchRejection},
* {@link OptionsBase.allowStaleOnFetchRejection},
* {@link FetchOptions.forceRefresh}, and
* {@link OptionsBase.context}
*
* Any of these may be modified in the {@link OptionsBase.fetchMethod}
* function, but the {@link GetOptions} fields will of course have no
* effect, as the {@link LRUCache#get} call already happened by the time
* the fetchMethod is called.
*/
export interface FetcherFetchOptions<K, V, FC = unknown>
extends Pick<
OptionsBase<K, V, FC>,
| 'allowStale'
| 'updateAgeOnGet'
| 'noDeleteOnStaleGet'
| 'sizeCalculation'
| 'ttl'
| 'noDisposeOnSet'
| 'noUpdateTTL'
| 'noDeleteOnFetchRejection'
| 'allowStaleOnFetchRejection'
| 'ignoreFetchAbort'
| 'allowStaleOnFetchAbort'
> {
status?: Status<V>
size?: Size
}
/**
* Options that may be passed to the {@link LRUCache#fetch} method.
*/
export interface FetchOptions<K, V, FC>
extends FetcherFetchOptions<K, V, FC> {
/**
* Set to true to force a re-load of the existing data, even if it
* is not yet stale.
*/
forceRefresh?: boolean
/**
* Context provided to the {@link OptionsBase.fetchMethod} as
* the {@link FetcherOptions.context} param.
*
* If the FC type is specified as unknown (the default),
* undefined or void, then this is optional. Otherwise, it will
* be required.
*/
context?: FC
signal?: AbortSignal
status?: Status<V>
}
/**
* Options provided to {@link LRUCache#fetch} when the FC type is something
* other than `unknown`, `undefined`, or `void`
*/
export interface FetchOptionsWithContext<K, V, FC>
extends FetchOptions<K, V, FC> {
context: FC
}
/**
* Options provided to {@link LRUCache#fetch} when the FC type is
* `undefined` or `void`
*/
export interface FetchOptionsNoContext<K, V>
extends FetchOptions<K, V, undefined> {
context?: undefined
}
/**
* Options that may be passed to the {@link LRUCache#has} method.
*/
export interface HasOptions<K, V, FC>
extends Pick<OptionsBase<K, V, FC>, 'updateAgeOnHas'> {
status?: Status<V>
}
/**
* Options that may be passed to the {@link LRUCache#get} method.
*/
export interface GetOptions<K, V, FC>
extends Pick<
OptionsBase<K, V, FC>,
'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'
> {
status?: Status<V>
}
/**
* Options that may be passed to the {@link LRUCache#peek} method.
*/
export interface PeekOptions<K, V, FC>
extends Pick<OptionsBase<K, V, FC>, 'allowStale'> {}
/**
* Options that may be passed to the {@link LRUCache#set} method.
*/
export interface SetOptions<K, V, FC>
extends Pick<
OptionsBase<K, V, FC>,
'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'
> {
/**
* If size tracking is enabled, then setting an explicit size
* in the {@link LRUCache#set} call will prevent calling the
* {@link OptionsBase.sizeCalculation} function.
*/
size?: Size
/**
* If TTL tracking is enabled, then setting an explicit start
* time in the {@link LRUCache#set} call will override the
* default time from `performance.now()` or `Date.now()`.
*
* Note that it must be a valid value for whichever time-tracking
* method is in use.
*/
start?: Milliseconds
status?: Status<V>
}
/**
* The type signature for the {@link OptionsBase.fetchMethod} option.
*/
export type Fetcher<K, V, FC = unknown> = (
key: K,
staleValue: V | undefined,
options: FetcherOptions<K, V, FC>
) => Promise<V | void | undefined> | V | void | undefined
/**
* Options which may be passed to the {@link LRUCache} constructor.
*
* Most of these may be overridden in the various options that use
* them.
*
* Despite all being technically optional, the constructor requires that
* a cache is at minimum limited by one or more of {@link OptionsBase.max},
* {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.
*
* If {@link OptionsBase.ttl} is used alone, then it is strongly advised
* (and in fact required by the type definitions here) that the cache
* also set {@link OptionsBase.ttlAutopurge}, to prevent potentially
* unbounded storage.
*/
export interface OptionsBase<K, V, FC> {
/**
* The maximum number of items to store in the cache before evicting
* old entries. This is read-only on the {@link LRUCache} instance,
* and may not be overridden.
*
* If set, then storage space will be pre-allocated at construction
* time, and the cache will perform significantly faster.
*
* Note that significantly fewer items may be stored, if
* {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also
* set.
*/
max?: Count
/**
* Max time in milliseconds for items to live in cache before they are
* considered stale. Note that stale items are NOT preemptively removed
* by default, and MAY live in the cache long after they have expired.
*
* Also, as this cache is optimized for LRU/MRU operations, some of
* the staleness/TTL checks will reduce performance, as they will incur
* overhead by deleting items.
*
* Must be an integer number of ms. If set to 0, this indicates "no TTL"
*
* @default 0
*/
ttl?: Milliseconds
/**
* Minimum amount of time in ms in which to check for staleness.
* Defaults to 1, which means that the current time is checked
* at most once per millisecond.
*
* Set to 0 to check the current time every time staleness is tested.
* (This reduces performance, and is theoretically unnecessary.)
*
* Setting this to a higher value will improve performance somewhat
* while using ttl tracking, albeit at the expense of keeping stale
* items around a bit longer than their TTLs would indicate.
*
* @default 1
*/
ttlResolution?: Milliseconds
/**
* Preemptively remove stale items from the cache.
* Note that this may significantly degrade performance,
* especially if the cache is storing a large number of items.
* It is almost always best to just leave the stale items in
* the cache, and let them fall out as new items are added.
*
* Note that this means that {@link OptionsBase.allowStale} is a bit
* pointless, as stale items will be deleted almost as soon as they
* expire.
*
* @default false
*/
ttlAutopurge?: boolean
/**
* Update the age of items on {@link LRUCache#get}, renewing their TTL
*
* Has no effect if {@link OptionsBase.ttl} is not set.
*
* @default false
*/
updateAgeOnGet?: boolean
/**
* Update the age of items on {@link LRUCache#has}, renewing their TTL
*
* Has no effect if {@link OptionsBase.ttl} is not set.
*
* @default false
*/
updateAgeOnHas?: boolean
/**
* Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return
* stale data, if available.
*/
allowStale?: boolean
/**
* Function that is called on items when they are dropped from the cache.
* This can be handy if you want to close file descriptors or do other
* cleanup tasks when items are no longer accessible. Called with `key,
* value`. It's called before actually removing the item from the
* internal cache, so it is *NOT* safe to re-add them.
*
* Use {@link OptionsBase.disposeAfter} if you wish to dispose items after
* they have been full removed, when it is safe to add them back to the
* cache.
*/
dispose?: Disposer<K, V>
/**
* The same as {@link OptionsBase.dispose}, but called *after* the entry
* is completely removed and the cache is once again in a clean state.
* It is safe to add an item right back into the cache at this point.
* However, note that it is *very* easy to inadvertently create infinite
* recursion this way.
*/
disposeAfter?: Disposer<K, V>
/**
* Set to true to suppress calling the
* {@link OptionsBase.dispose} function if the entry key is
* still accessible within the cache.
* This may be overridden by passing an options object to
* {@link LRUCache#set}.
*/
noDisposeOnSet?: boolean
/**
* Boolean flag to tell the cache to not update the TTL when
* setting a new value for an existing key (ie, when updating a value
* rather than inserting a new value). Note that the TTL value is
* _always_ set (if provided) when adding a new entry into the cache.
*
* Has no effect if a {@link OptionsBase.ttl} is not set.
*/
noUpdateTTL?: boolean
/**
* If you wish to track item size, you must provide a maxSize
* note that we still will only keep up to max *actual items*,
* if max is set, so size tracking may cause fewer than max items
* to be stored. At the extreme, a single item of maxSize size
* will cause everything else in the cache to be dropped when it
* is added. Use with caution!
*
* Note also that size tracking can negatively impact performance,
* though for most cases, only minimally.
*/
maxSize?: Size
/**
* The maximum allowed size for any single item in the cache.
*
* If a larger item is passed to {@link LRUCache#set} or returned by a
* {@link OptionsBase.fetchMethod}, then it will not be stored in the
* cache.
*/
maxEntrySize?: Size
/**
* A function that returns a number indicating the item's size.
*
* If not provided, and {@link OptionsBase.maxSize} or
* {@link OptionsBase.maxEntrySize} are set, then all
* {@link LRUCache#set} calls **must** provide an explicit
* {@link SetOptions.size} or sizeCalculation param.
*/
sizeCalculation?: SizeCalculator<K, V>
/**
* Method that provides the implementation for {@link LRUCache#fetch}
*/
fetchMethod?: Fetcher<K, V, FC>
/**
* Set to true to suppress the deletion of stale data when a
* {@link OptionsBase.fetchMethod} returns a rejected promise.
*/
noDeleteOnFetchRejection?: boolean
/**
* Do not delete stale items when they are retrieved with
* {@link LRUCache#get}.
*
* Note that the `get` return value will still be `undefined`
* unless {@link OptionsBase.allowStale} is true.
*/
noDeleteOnStaleGet?: boolean
/**
* Set to true to allow returning stale data when a
* {@link OptionsBase.fetchMethod} throws an error or returns a rejected
* promise.
*
* This differs from using {@link OptionsBase.allowStale} in that stale
* data will ONLY be returned in the case that the
* {@link LRUCache#fetch} fails, not any other times.
*/
allowStaleOnFetchRejection?: boolean
/**
* Set to true to return a stale value from the cache when the
* `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches an `'abort'`
* event, whether user-triggered, or due to internal cache behavior.
*
* Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying
* {@link OptionsBase.fetchMethod} will still be considered canceled, and its return
* value will be ignored and not cached.
*/
allowStaleOnFetchAbort?: boolean
/**
* Set to true to ignore the `abort` event emitted by the `AbortSignal`
* object passed to {@link OptionsBase.fetchMethod}, and still cache the
* resulting resolution value, as long as it is not `undefined`.
*
* When used on its own, this means aborted {@link LRUCache#fetch} calls are not
* immediately resolved or rejected when they are aborted, and instead
* take the full time to await.
*
* When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted
* {@link LRUCache#fetch} calls will resolve immediately to their stale
* cached value or `undefined`, and will continue to process and eventually
* update the cache when they resolve, as long as the resulting value is
* not `undefined`, thus supporting a "return stale on timeout while
* refreshing" mechanism by passing `AbortSignal.timeout(n)` as the signal.
*
* **Note**: regardless of this setting, an `abort` event _is still
* emitted on the `AbortSignal` object_, so may result in invalid results
* when passed to other underlying APIs that use AbortSignals.
*
* This may be overridden in the {@link OptionsBase.fetchMethod} or the
* call to {@link LRUCache#fetch}.
*/
ignoreFetchAbort?: boolean
}
export interface OptionsMaxLimit<K, V, FC>
extends OptionsBase<K, V, FC> {
max: Count
}
export interface OptionsTTLLimit<K, V, FC>
extends OptionsBase<K, V, FC> {
ttl: Milliseconds
ttlAutopurge: boolean
}
export interface OptionsSizeLimit<K, V, FC>
extends OptionsBase<K, V, FC> {
maxSize: Size
}
/**
* The valid safe options for the {@link LRUCache} constructor
*/
export type Options<K, V, FC> =
| OptionsMaxLimit<K, V, FC>
| OptionsSizeLimit<K, V, FC>
| OptionsTTLLimit<K, V, FC>
/**
* Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump}
*/
export interface Entry<V> {
value: V
ttl?: Milliseconds
size?: Size
start?: Milliseconds
}
}
/**
* Default export, the thing you're using this module to get.
*
* All properties from the options object (with the exception of
* {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
* normal public members. (`max` and `maxBase` are read-only getters.)
* Changing any of these will alter the defaults for subsequent method calls,
* but is otherwise safe.
*/
export class LRUCache<K extends {}, V extends {}, FC = unknown> {
// properties coming in from the options of these, only max and maxSize
// really *need* to be protected. The rest can be modified, as they just
// set defaults for various methods.
readonly #max: LRUCache.Count
readonly #maxSize: LRUCache.Size
readonly #dispose?: LRUCache.Disposer<K, V>
readonly #disposeAfter?: LRUCache.Disposer<K, V>
readonly #fetchMethod?: LRUCache.Fetcher<K, V, FC>
/**
* {@link LRUCache.OptionsBase.ttl}
*/
ttl: LRUCache.Milliseconds
/**
* {@link LRUCache.OptionsBase.ttlResolution}
*/
ttlResolution: LRUCache.Milliseconds
/**
* {@link LRUCache.OptionsBase.ttlAutopurge}
*/
ttlAutopurge: boolean
/**
* {@link LRUCache.OptionsBase.updateAgeOnGet}
*/
updateAgeOnGet: boolean
/**
* {@link LRUCache.OptionsBase.updateAgeOnHas}
*/
updateAgeOnHas: boolean
/**
* {@link LRUCache.OptionsBase.allowStale}
*/
allowStale: boolean
/**
* {@link LRUCache.OptionsBase.noDisposeOnSet}
*/
noDisposeOnSet: boolean
/**
* {@link LRUCache.OptionsBase.noUpdateTTL}
*/
noUpdateTTL: boolean
/**
* {@link LRUCache.OptionsBase.maxEntrySize}
*/
maxEntrySize: LRUCache.Size
/**
* {@link LRUCache.OptionsBase.sizeCalculation}
*/
sizeCalculation?: LRUCache.SizeCalculator<K, V>
/**
* {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
*/
noDeleteOnFetchRejection: boolean
/**
* {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
*/
noDeleteOnStaleGet: boolean
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
*/
allowStaleOnFetchAbort: boolean
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
*/
allowStaleOnFetchRejection: boolean
/**
* {@link LRUCache.OptionsBase.ignoreFetchAbort}
*/
ignoreFetchAbort: boolean
// computed properties
#size: LRUCache.Count
#calculatedSize: LRUCache.Size
#keyMap: Map<K, Index>
#keyList: (K | undefined)[]
#valList: (V | BackgroundFetch<V> | undefined)[]
#next: NumberArray
#prev: NumberArray
#head: Index
#tail: Index
#free: StackLike
#disposed?: DisposeTask<K, V>[]
#sizes?: ZeroArray
#starts?: ZeroArray
#ttls?: ZeroArray
#hasDispose: boolean
#hasFetchMethod: boolean
#hasDisposeAfter: boolean
/**
* Do not call this method unless you need to inspect the
* inner workings of the cache. If anything returned by this
* object is modified in any way, strange breakage may occur.
*
* These fields are private for a reason!
*
* @internal
*/
static unsafeExposeInternals<
K extends {},
V extends {},
FC extends unknown = unknown
>(c: LRUCache<K, V, FC>) {
return {
// properties
starts: c.#starts,
ttls: c.#ttls,
sizes: c.#sizes,
keyMap: c.#keyMap as Map<K, number>,
keyList: c.#keyList,
valList: c.#valList,
next: c.#next,
prev: c.#prev,
get head() {
return c.#head
},
get tail() {
return c.#tail
},
free: c.#free,
// methods
isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),
backgroundFetch: (
k: K,
index: number | undefined,
options: LRUCache.FetchOptions<K, V, FC>,
context: any
): BackgroundFetch<V> =>
c.#backgroundFetch(
k,
index as Index | undefined,
options,
context
),
moveToTail: (index: number): void =>
c.#moveToTail(index as Index),
indexes: (options?: { allowStale: boolean }) =>
c.#indexes(options),
rindexes: (options?: { allowStale: boolean }) =>
c.#rindexes(options),
isStale: (index: number | undefined) =>
c.#isStale(index as Index),
}
}
// Protected read-only members
/**
* {@link LRUCache.OptionsBase.max} (read-only)
*/
get max(): LRUCache.Count {
return this.#max
}
/**
* {@link LRUCache.OptionsBase.maxSize} (read-only)
*/
get maxSize(): LRUCache.Count {
return this.#maxSize
}
/**
* The total computed size of items in the cache (read-only)
*/
get calculatedSize(): LRUCache.Size {
return this.#calculatedSize
}
/**
* The number of items stored in the cache (read-only)
*/
get size(): LRUCache.Count {
return this.#size
}
/**
* {@link LRUCache.OptionsBase.fetchMethod} (read-only)
*/
get fetchMethod(): LRUCache.Fetcher<K, V, FC> | undefined {
return this.#fetchMethod
}
/**
* {@link LRUCache.OptionsBase.dispose} (read-only)
*/
get dispose() {
return this.#dispose
}
/**
* {@link LRUCache.OptionsBase.disposeAfter} (read-only)
*/
get disposeAfter() {
return this.#disposeAfter
}
constructor(
options: LRUCache.Options<K, V, FC> | LRUCache<K, V, FC>
) {
const {
max = 0,
ttl,
ttlResolution = 1,
ttlAutopurge,
updateAgeOnGet,
updateAgeOnHas,
allowStale,
dispose,
disposeAfter,
noDisposeOnSet,
noUpdateTTL,
maxSize = 0,
maxEntrySize = 0,
sizeCalculation,
fetchMethod,