-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
1199 lines (951 loc) · 34.1 KB
/
__init__.py
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
"""
Cacheing library providing various cacheing API's. Inspired
by `cachetools` and Redis, this library supports Redis-like eviction
policies that are not available in the `cachetools` python
standard library.
Per-item TTL's are supported in the 'VTTLCache', as opposed
to the global TTL's offered by `cachetools` TTLCache.
Copyright 2022, Blake Reid.
Licensed under MIT.
"""
import random
import time
from collections import OrderedDict, Counter
from collections.abc import MutableMapping, Iterable, KeysView, ItemsView, ValuesView
from typing import List
from .utils import (
_TTLLink,
_TTLLinkedList,
LFULinkedList,
LFUNode
)
__all__ = (
"RCache",
"LRUCache",
"VolatileLRUCache",
"LFUCache",
"VolatileLFUCache",
"RandomCache",
"VolatileRandomCache",
"TTLCache",
"VolatileTTLCache",
"BoundedTTLCache"
)
class RCache(MutableMapping):
"""Cache base-class.
Evicts the oldest item from the cache
when the cache reaches maximum capacity.
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
__singleton = object()
def __init__(self, capacity, callback=None):
self.__cache = {}
self.__size = 0 # Number of Items in the Cache
self.__capacity = capacity
self._callback = callback
@property
def capacity(self):
return self.__capacity
def __setitem__(self, _key, _value):
if _key not in self.__cache:
while self.__size >= self.__capacity:
self._evict()
self.__cache[_key] = _value
self.__size += 1
else:
self.__cache[_key] = _value
def __getitem__(self, _key):
try:
return self.__cache[_key]
except KeyError:
raise KeyError(_key) from None
def get(self, _key, _default=None):
try:
return self[_key]
except KeyError:
return _default
def __delitem__(self, _key):
del self.__cache[_key]
self.__size -= 1
def pop(self, _key, default=__singleton):
try:
_value = self[_key]
del self[_key]
except KeyError:
if default is self.__singleton:
raise
return default
else:
return _value
def popitem(self):
"""Pop the most recent item from the cache."""
try:
itm = self.__cache.popitem()
except KeyError:
raise KeyError("cache is empty") from None
else:
self.__size -= 1
return itm
def _evict(self):
"""Evicts an item from the cache determined
by the relevant algorithm.
Raises:
KeyError: Cache is empty.
"""
try:
key = next(iter(self))
except StopIteration:
raise KeyError("cache is empty") from None
value = self[key]
del self.__cache[key]
self.__size -= 1
if self._callback:
self._callback(key, value)
return key, value
def __contains__(self, _key):
return _key in self.__cache
def __iter__(self):
return iter(self.__cache)
def __len__(self):
return len(self.__cache)
def __repr__(self):
return "{}{}".format(self.__class__.__name__, self.__cache)
def keys(self):
return self.__cache.keys()
def values(self):
return self.__cache.values()
def items(self):
return self.__cache.items()
def __eq__(self, obj):
if isinstance(obj, RCache):
if self.__dict__ == obj.__dict__:
return True
return False
class VolatileCache:
"""Base class for volatile-type caches.
Supports cases of per-item persistance and non-evictions.
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
__singleton = object()
def __init__(self, capacity, callback=None):
self.__cache = {}
self.__size = 0
self.__capacity = capacity
self._callback = callback
# Dict containing items which expire
self._expires_map = {}
@property
def capacity(self):
return self.__capacity
def __setitem__(self, _keymeta, _value):
_key, expires = _keymeta
if _key not in self.__cache:
while self.__size >= self.__capacity and self._expires_map:
self._evict()
if self.__size < self.__capacity: # Otherwise, new data item is discarded
self.__cache[_key] = _value
if expires:
self._expires_map[_key] = _value
self.__size += 1
else:
self.__cache[_key] = _value
if expires:
self._expires_map[_key] = _value
def __getitem__(self, _key):
try:
return self.__cache[_key]
except KeyError:
raise KeyError(_key) from None
def get(self, _key, _default=None):
"""If key does not exist in the cache, returns default.
Args:
_key (hashable): Item key.
_default (object, optional): Defaults to None.
"""
try:
return self[_key]
except KeyError:
return _default
def __delitem__(self, _key):
del self.__cache[_key]
self._expires_map.pop(_key, None)
self.__size -= 1
def pop(self, _key, default=__singleton):
"""_summary_
Args:
_key (_type_): _description_
default (_type_, optional): _description_. Defaults to __singleton.
Returns:
_type_: _description_
"""
try:
_value = self[_key]
del self[_key]
except KeyError:
if default is self.__singleton:
raise
return default
else:
return _value
def popitem(self):
"""Pop the most recent item from the cache."""
try:
key, value = self.__cache.popitem()
self._expires_map.pop(key, None)
except KeyError:
raise KeyError("cache is empty") from None
else:
self.__size -= 1
return (key, value)
def _evict(self):
"""Evicts an item from the cache determined
by the relevant algorithm.
Raises:
KeyError: Cache is empty.
"""
try:
key = next(iter(self._expires_map))
except StopIteration:
raise KeyError("no candidate keys available to evict") from None
value = self[key]
del self.__cache[key]
del self._expires_map[key]
self.__size -= 1
if self._callback:
return self._callback(key, value)
return key, value
def __contains__(self, _key):
return _key in self.__cache
def __iter__(self):
return iter(self.__cache)
def __len__(self):
return len(self.__cache)
def __repr__(self):
return "{}{}".format(self.__class__.__name__, self.__cache)
def keys(self):
return self.__cache.keys()
def values(self):
return self.__cache.values()
def items(self):
return self.__cache.items()
def __eq__(self, obj):
if isinstance(obj, VolatileCache):
if self.__dict__ == obj.__dict__:
return True
return False
class LRUCache(RCache):
"""Least Recently Used Cache.
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
def __init__(self, capacity, callback=None):
RCache.__init__(self, capacity, callback)
self._lru = OrderedDict()
def __getitem__(self, _key):
"""Retrieves item from the cache.
If the item exists, retrieve it from the cache
and move it to the back of the OrderedDict.
Args:
_key (hashable): Key.
"""
try:
_value = RCache.__getitem__(self, _key)
except KeyError:
raise KeyError from None
else:
self._lru.move_to_end(_key, last=False)
return _value
def __setitem__(self, _key, _value):
"""Add item to the cache..
If the item exists in the cache, update it's LRU ordering.
If the item does not exist in the cache, add the item and
then update it's LRU ordering.
Args:
_key (hashable): Item Key.
_value (object): Item Value.
"""
RCache.__setitem__(self, _key, _value)
self._lru[_key] = _value
# Update LRU Ordering
self._lru.move_to_end(_key, last=False)
def __delitem__(self, _key):
RCache.__delitem__(self, _key)
del self._lru[_key]
def popitem(self):
"""Force eviction of least-recently used item."""
try:
_key, _value = self._lru.popitem()
except KeyError:
raise KeyError("cannot pop from empty cache") from None
else:
RCache.__delitem__(self, _key)
return (_key, _value)
def _evict(self):
"""Evict the least-recently used item.
Called when items are implicitly evicted
from the cache.
Evicts the least-recently used item from
the cache and updates the LRU ordering.
If a callback function is specified, the callback
function is invoked.
"""
try:
_key, _value = self.popitem()
except KeyError:
raise KeyError("cannot evict from empty cache") from None
else:
if self._callback:
self._callback(_key, _value)
class VolatileLRUCache(VolatileCache):
"""Volatile Least-Recently Used Cache.
Evicts key with `expire` field set to True using
a least-recently used eviction policy.
Persists keys with the 'expire' field set to False.
If the cache capacity is reached and there are no
keys to expire, new data is discarded.
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
def __init__(self, capacity, callback=None):
VolatileCache.__init__(self, capacity, callback)
self._lru = OrderedDict()
def __setitem__(self, _keymeta, _value):
"""Set an item in the cache.
Args:
_expire (bool): Defines if this cache item expires.
_keymeta (tuple): Item Key & Expire Field.
_value (object): Item Value.
"""
_key, _expires = _keymeta
if not isinstance(_expires, bool):
raise TypeError("{} is not bool".format(_expires))
VolatileCache.__setitem__(self, _keymeta, _value)
if _expires:
self._lru[_key] = _value
# Update LRU Ordering
self._lru.move_to_end(_key, last=False)
def __getitem__(self, _key):
"""Retrieves item and updates it's priority.
Args:
_key (object): Key.
"""
try:
_value = VolatileCache.__getitem__(self, _key)
except KeyError:
raise KeyError from None
else:
if self._expires_map.get(_key): # Key Expires
self._lru.move_to_end(_key, last=False)
return _value
def __delitem__(self, _key):
VolatileCache.__delitem__(self, _key)
if self._lru[_key]:
del self._lru[_key]
def popitem(self):
"""Pop non-persistent LRU item from the cache.
If no candidate keys are available, raises KeyError.
"""
try:
_key, _value = self._lru.popitem()
except KeyError:
# Cache is at full-capacity and there are
# no candidate keys to pop.
raise KeyError("no candidate keys") from None
else:
VolatileCache.__delitem__(self, _key)
return (_key, _value)
def _evict(self):
try:
_key, _value = self.popitem()
except KeyError:
raise KeyError("cannot evict from empty cache") from None
else:
if self._callback:
self._callback(_key, _value)
class LFUCache(RCache):
"""Least-frequently used cache implementation.
O(1) insertion, lookup, and deletion.
References:
Ketan Shah, Anirban Mitra, and Dhruv Matani, An O(1) algorithm for implementing the LFU
cache eviction scheme, (August 16, 2010).
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
def __init__(self, capacity, callback=None):
RCache.__init__(self, capacity=capacity, callback=callback)
self.__lfu = LFULinkedList()
self.node_cache = self.__lfu.node_cache
def __setitem__(self, _key, _value):
RCache.__setitem__(self, _key, _value)
if _key in self.node_cache:
self.__lfu.increment(_key)
else:
self.__lfu.insert(_key)
def __getitem__(self, _key):
_value = RCache.__getitem__(self, _key)
self.__lfu.increment(_key)
return _value
def __delitem__(self, _key):
RCache.__delitem__(self, _key)
self.__lfu.delete(_key)
def popitem(self):
"""Force eviction of LFU item.
Returns:
tuple: LFU item key, value pair.
"""
key = self.__lfu.popleft()
value = RCache.__getitem__(self, key)
RCache.__delitem__(self, key)
return (key, value)
def _evict(self):
key, value = self.popitem()
if self._callback:
self._callback(key, value)
class VolatileLFUCache(VolatileCache):
"""Volatile Least-Frequently Used Cache.
Evicts key with `expire` field set to true using
a least-frequently used eviction policy.
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
def __init__(self, capacity, callback=None):
VolatileCache.__init__(self, capacity, callback)
self.__lfu = LFULinkedList()
self.node_cache = self.__lfu.node_cache
def __setitem__(self, _keymeta, _value):
_key, _expires = _keymeta
if not isinstance(_expires, bool):
raise TypeError("{} is not bool".format(_expires))
VolatileCache.__setitem__(self, _keymeta, _value)
# Check if a node with this key already exists.
# If a node sharing this key exists in the LFU stream
# and it's expiry is CHANGED to False, remove
# it from the LFU stream:
if _key in self.node_cache and not _expires:
self.__lfu.delete(_key)
# Otherwise, increment it's access frequency:
elif _key in self.node_cache and _expires:
self.__lfu.increment(_key)
# If the item does not exist, and it's expiry is
# set to True - insert it into the linked list:
elif _key not in self.node_cache and _expires:
self.__lfu.insert(_key)
def __getitem__(self, _key):
_value = VolatileCache.__getitem__(self, _key)
if _key in self.node_cache:
self.__lfu.increment(_key)
return _value
def __delitem__(self, _key):
VolatileCache.__delitem__(self, _key)
if _key in self.node_cache:
self.__lfu.delete(_key)
def popitem(self):
# If there's no items to expire, return None
if not self._expires_map:
return (None, None)
_key = self.__lfu.popleft()
_value = VolatileCache.__getitem__(self, _key)
VolatileCache.__delitem__(self, _key)
return (_key, _value)
def _evict(self):
"""Evicts non-persistent LFU Item."""
_key, _value = self.popitem()
if self._callback:
self._callback(_key, _value)
class RandomCache(RCache):
"""Cache with Random Eviction Policy.
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
def __init__(self, capacity, callback=None):
RCache.__init__(self, capacity, callback)
self.set = []
# To maintain constant time across
# all operations, maintain a dictionary
# which tracks the index of each key stored
# in `self.set`.
self.idx_map = {}
def __setitem__(self, _key, _value):
RCache.__setitem__(self, _key, _value)
if _key not in self.idx_map:
self.set.append(_key)
self.idx_map[_key] = len(self.set) - 1
def __delitem__(self, _key):
RCache.__delitem__(self, _key)
# In order to perform a deletion without having
# to decrement each element of `idx_map`, we
# swap the last element of `set` with the element
# to be deleted, and replace its index in `idx_map`.
last_elem = self.set[-1]
index = self.idx_map[_key]
ssize = len(self.set) - 1
if index < ssize:
self.set[index] = last_elem
self.idx_map[last_elem] = index
self.set.pop()
del self.idx_map[_key]
def popitem(self):
"""Force Eviction of Random item."""
try:
_key = self.__get_rand_key()
except:
raise KeyError("cannot pop from empty cache") from None
else:
_val = RCache.__getitem__(self, _key)
del self[_key]
return (_key, _val)
def _evict(self):
_key, _value = self.popitem()
if self._callback:
self._callback(_key, _value)
def __get_rand_key(self):
"""Generate a random key from the cache."""
return random.choice(self.set)
class VolatileRandomCache(VolatileCache):
"""Randomly evicts keys that are set to expire.
Attributes:
capacity (int): Maximum capacity of the cache.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
"""
def __init__(self, capacity, callback=None):
VolatileCache.__init__(self, capacity, callback)
self._set = []
# To maintain constant time across
# all operations, maintain a dictionary
# which tracks the index of each key stored
# in `self.set`.
self.idx_map = {}
def __setitem__(self, _keymeta, _value):
_key, expires = _keymeta
VolatileCache.__setitem__(self, _keymeta, _value)
if _key not in self.idx_map and expires:
self._set.append(_key)
self.idx_map[_key] = len(self._set) - 1
def __delitem__(self, _key):
VolatileCache.__delitem__(self, _key)
# In order to perform a deletion without having
# to iteratively decrement each element of `idx_map`,
# we swap the last element of `set` with the element
# to be deleted, and then pop the last element from `set`.
if _key in self.idx_map:
last_elem = self._set[-1]
index = self.idx_map[_key]
ssize = len(self._set) - 1
if index < ssize:
self._set[index] = last_elem
self.idx_map[last_elem] = index
self._set.pop()
del self.idx_map[_key]
def popitem(self):
"""Force Eviction of Random item."""
try:
_key = self.__get_rand_key()
except:
raise KeyError("cannot pop from empty cache") from None
else:
_val = VolatileCache.__getitem__(self, _key)
del self[_key]
return (_key, _val)
def _evict(self):
_key, _value = self.popitem()
if self._callback:
self._callback(_key, _value)
def __get_rand_key(self):
"""Generate a random key from the cache.
"""
return random.choice(self._set)
class TTLCache(LRUCache):
"""TTL cache with global object fixed expiry times.
Monotonic time is used to track key expiry times.
Attributes:
capacity (int): Maximum capacity of the cache.
ttl (int): Cache items time-to-live.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
time (callable): Callable time function used by the
cache.
"""
def __init__(self, capacity, ttl, callback=None, _time=time.monotonic):
LRUCache.__init__(self, capacity, callback)
self._time = _time
self.__ttl = ttl
# Dict Mapping Keys to `_TTLLinks`
# this is primarily used for O(1)
# lookup and deletions of `_TTLLinks`
self._links = {}
# Linked List of '_TTLLinks'
# The linked list is 'sorted' in time-ascending
# order. The key with the nearest expiry time is
# at the front of the list.
self._list = _TTLLinkedList()
def expire(_time):
"""Removes expired keys from the cache.
Decorator for class methods. Iterates over the linked
list and removes expired keys from the cache when
the cache is accessed.
"""
def wrap(func):
def wrapped_f(self, *args):
curr = self._list.head
while curr:
if curr.expiry <= _time():
LRUCache.__delitem__(self, curr.key)
self._list.remove(curr)
del self._links[curr.key]
curr = curr.next
else:
return func(self, *args)
return func(self, *args)
return wrapped_f
return wrap
@expire(_time=time.monotonic)
def __setitem__(self, _key, _value):
LRUCache.__setitem__(self, _key, _value)
try:
link = self._links[_key]
except KeyError:
expiry = self._time() + self.__ttl
self._links[_key] = link = _TTLLink(_key, expiry, None, None)
else:
self._list.remove(link)
expiry = self._time() + self.__ttl
link.expiry = expiry
self._list.insert(link)
@expire(_time=time.monotonic)
def __getitem__(self, _key):
try:
_value = LRUCache.__getitem__(self, _key)
except KeyError:
raise KeyError(f"{_key}") from None
else:
return _value
@expire(_time=time.monotonic)
def get(self, _key, _default=None):
try:
return self[_key]
except KeyError:
return _default
@expire(_time=time.monotonic)
def __delitem__(self, _key):
try:
LRUCache.__delitem__(self, _key)
except KeyError:
raise KeyError(f"{_key}") from None
else:
link = self._links[_key]
self._list.remove(link)
del self._links[_key]
@expire(_time=time.monotonic)
def __contains__(self, _object: object):
return RCache.__contains__(self, _object)
@expire(_time=time.monotonic)
def __iter__(self):
return RCache.__iter__(self)
@expire(_time=time.monotonic)
def __len__(self):
return RCache.__len__(self)
def _evict(self):
"""Handle evictions when Cache exceeds capacity.
Not time-related.
Invokes callback function whenever an item is evicted.
"""
# Fetch and Evict LRU Item from LRUCache
_key, _value = LRUCache.popitem(self)
# Remove References to Link
link = self._links[_key]
self._list.remove(link)
del self._links[_key]
if self._callback:
self._callback(_key, _value)
@expire(_time=time.monotonic)
def __str__(self):
return RCache.__repr__(self)
def popitem(self):
"""Evict the LRU item."""
# Fetch and Evict LRU Item from LRUCache
_key, _value = LRUCache.popitem(self)
# Remove References to Link
link = self._links[_key]
self._list.remove(link)
del self._links[_key]
# Enable 'expire' decorator to be accessed
# outside of the scope of the class, while
# still being inside the class namespace.
expire = staticmethod(expire)
class VolatileTTLCache(VolatileLRUCache):
"""TTL Cache with Volatile Keys.
Items with the expire field set to "True"
are evicted from the cache. Items with the
expire field set to "False" persist.
Attributes:
capacity (int): Maximum capacity of the cache.
ttl (int): Cache items time-to-live.
callback (callable, optional): Callable defining
behaviour when an item is evicted from the cache.
Defaults to None.
time (callable): Callable time function used by the
cache.
"""
def __init__(self, capacity, ttl, callback=None, _time=time.monotonic):
VolatileLRUCache.__init__(self, capacity, callback)
self._time = _time
self.__ttl = ttl
# Dict Mapping Keys to `_TTLLinks`
# this is primarily used for O(1)
# lookup and deletions of `_TTLLinks`
self._links = {}
# Linked List of '_TTLLinks'
# The linked list is 'sorted' in time-ascending
# order. The key with the nearest expiry time is
# at the front of the list.
self._list = _TTLLinkedList()
def expire(_time):
"""Removes expired keys from the cache.
Decorator for class methods. Iterates over the linked
list and removes expired keys from the cache when
the cache is accessed.
"""
def wrap(func):
def wrapped_f(self, *args):
curr = self._list.head
while curr:
if curr.expiry <= _time():
VolatileLRUCache.__delitem__(self, curr.key)
self._list.remove(curr)
del self._links[curr.key]
curr = curr.next
else:
return func(self, *args)
return func(self, *args)
return wrapped_f
return wrap
@expire(_time=time.monotonic)
def __setitem__(self, _keymeta, _value):
_key, expires = _keymeta
VolatileLRUCache.__setitem__(self, _keymeta, _value)
try:
link = self._links[_key]
except KeyError:
if expires:
expiry = self._time() + self.__ttl
self._links[_key] = link = _TTLLink(_key, expiry, None, None)
else:
self._list.remove(link)
expiry = self._time() + self.__ttl
link.expiry = expiry
if expires:
self._list.insert(link)
@expire(_time=time.monotonic)
def __getitem__(self, _key):
try:
_value = VolatileLRUCache.__getitem__(self, _key)
except KeyError:
raise KeyError(f"{_key}") from None
else:
return _value
@expire(_time=time.monotonic)
def get(self, _key, _default=None):
try:
return self[_key]
except KeyError:
return _default
@expire(_time=time.monotonic)
def __delitem__(self, _key):
try:
VolatileLRUCache.__delitem__(self, _key)
except KeyError:
raise KeyError(f"{_key}") from None
else:
if _key in self._links:
link = self._links[_key]
self._list.remove(link)
del self._links[_key]
@expire(_time=time.monotonic)
def __contains__(self, _object: object):
return VolatileLRUCache.__contains__(self, _object)
@expire(_time=time.monotonic)
def __iter__(self):
return VolatileLRUCache.__iter__(self)