-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy path_cache.py
392 lines (348 loc) · 10.5 KB
/
_cache.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
import copy
import random
import time
from abc import ABC, abstractmethod
from collections import OrderedDict, defaultdict
from enum import Enum
from typing import List, Sequence, Union
from redis.typing import KeyT, ResponseT
class EvictionPolicy(Enum):
LRU = "lru"
LFU = "lfu"
RANDOM = "random"
DEFAULT_EVICTION_POLICY = EvictionPolicy.LRU
DEFAULT_DENY_LIST = [
"BF.CARD",
"BF.DEBUG",
"BF.EXISTS",
"BF.INFO",
"BF.MEXISTS",
"BF.SCANDUMP",
"CF.COMPACT",
"CF.COUNT",
"CF.DEBUG",
"CF.EXISTS",
"CF.INFO",
"CF.MEXISTS",
"CF.SCANDUMP",
"CMS.INFO",
"CMS.QUERY",
"DUMP",
"EXPIRETIME",
"FT.AGGREGATE",
"FT.ALIASADD",
"FT.ALIASDEL",
"FT.ALIASUPDATE",
"FT.CURSOR",
"FT.EXPLAIN",
"FT.EXPLAINCLI",
"FT.GET",
"FT.INFO",
"FT.MGET",
"FT.PROFILE",
"FT.SEARCH",
"FT.SPELLCHECK",
"FT.SUGGET",
"FT.SUGLEN",
"FT.SYNDUMP",
"FT.TAGVALS",
"FT._ALIASADDIFNX",
"FT._ALIASDELIFX",
"HRANDFIELD",
"JSON.DEBUG",
"PEXPIRETIME",
"PFCOUNT",
"PTTL",
"SRANDMEMBER",
"TDIGEST.BYRANK",
"TDIGEST.BYREVRANK",
"TDIGEST.CDF",
"TDIGEST.INFO",
"TDIGEST.MAX",
"TDIGEST.MIN",
"TDIGEST.QUANTILE",
"TDIGEST.RANK",
"TDIGEST.REVRANK",
"TDIGEST.TRIMMED_MEAN",
"TOPK.INFO",
"TOPK.LIST",
"TOPK.QUERY",
"TOUCH",
"TTL",
]
DEFAULT_ALLOW_LIST = [
"BITCOUNT",
"BITFIELD_RO",
"BITPOS",
"EXISTS",
"GEODIST",
"GEOHASH",
"GEOPOS",
"GEORADIUSBYMEMBER_RO",
"GEORADIUS_RO",
"GEOSEARCH",
"GET",
"GETBIT",
"GETRANGE",
"HEXISTS",
"HGET",
"HGETALL",
"HKEYS",
"HLEN",
"HMGET",
"HSTRLEN",
"HVALS",
"JSON.ARRINDEX",
"JSON.ARRLEN",
"JSON.GET",
"JSON.MGET",
"JSON.OBJKEYS",
"JSON.OBJLEN",
"JSON.RESP",
"JSON.STRLEN",
"JSON.TYPE",
"LCS",
"LINDEX",
"LLEN",
"LPOS",
"LRANGE",
"MGET",
"SCARD",
"SDIFF",
"SINTER",
"SINTERCARD",
"SISMEMBER",
"SMEMBERS",
"SMISMEMBER",
"SORT_RO",
"STRLEN",
"SUBSTR",
"SUNION",
"TS.GET",
"TS.INFO",
"TS.RANGE",
"TS.REVRANGE",
"TYPE",
"XLEN",
"XPENDING",
"XRANGE",
"XREAD",
"XREVRANGE",
"ZCARD",
"ZCOUNT",
"ZDIFF",
"ZINTER",
"ZINTERCARD",
"ZLEXCOUNT",
"ZMSCORE",
"ZRANGE",
"ZRANGEBYLEX",
"ZRANGEBYSCORE",
"ZRANK",
"ZREVRANGE",
"ZREVRANGEBYLEX",
"ZREVRANGEBYSCORE",
"ZREVRANK",
"ZSCORE",
"ZUNION",
]
_RESPONSE = "response"
_KEYS = "keys"
_CTIME = "ctime"
_ACCESS_COUNT = "access_count"
IMMUTABLES = (bytes, str, int, float, bool, type(None), tuple)
class AbstractCache(ABC):
"""
An abstract base class for client caching implementations.
If you want to implement your own cache you must support these methods.
"""
@abstractmethod
def set(
self,
command: Union[str, Sequence[str]],
response: ResponseT,
keys_in_command: List[KeyT],
):
pass
@abstractmethod
def get(self, command: Union[str, Sequence[str]]) -> ResponseT:
pass
@abstractmethod
def delete_command(self, command: Union[str, Sequence[str]]):
pass
@abstractmethod
def delete_commands(self, commands: List[Union[str, Sequence[str]]]):
pass
@abstractmethod
def flush(self):
pass
@abstractmethod
def invalidate_key(self, key: KeyT):
pass
class _LocalCache(AbstractCache):
"""
A caching mechanism for storing redis commands and their responses.
Args:
max_size (int): The maximum number of commands to be stored in the cache.
ttl (int): The time-to-live for each command in seconds.
eviction_policy (EvictionPolicy): The eviction policy to use for removing commands when the cache is full.
Attributes:
max_size (int): The maximum number of commands to be stored in the cache.
ttl (int): The time-to-live for each command in seconds.
eviction_policy (EvictionPolicy): The eviction policy used for cache management.
cache (OrderedDict): The ordered dictionary to store commands and their metadata.
key_commands_map (defaultdict): A mapping of keys to the set of commands that use each key.
commands_ttl_list (list): A list to keep track of the commands in the order they were added. # noqa
"""
def __init__(
self,
max_size: int = 10000,
ttl: int = 0,
eviction_policy: EvictionPolicy = DEFAULT_EVICTION_POLICY,
):
self.max_size = max_size
self.ttl = ttl
self.eviction_policy = eviction_policy
self.cache = OrderedDict()
self.key_commands_map = defaultdict(set)
self.commands_ttl_list = []
def set(
self,
command: Union[str, Sequence[str]],
response: ResponseT,
keys_in_command: List[KeyT],
):
"""
Set a redis command and its response in the cache.
Args:
command (Union[str, Sequence[str]]): The redis command.
response (ResponseT): The response associated with the command.
keys_in_command (List[KeyT]): The list of keys used in the command.
"""
if len(self.cache) >= self.max_size:
self._evict()
self.cache[command] = {
_RESPONSE: response,
_KEYS: keys_in_command,
_CTIME: time.monotonic(),
_ACCESS_COUNT: 0, # Used only for LFU
}
self._update_key_commands_map(keys_in_command, command)
self.commands_ttl_list.append(command)
def get(self, command: Union[str, Sequence[str]]) -> ResponseT:
"""
Get the response for a redis command from the cache.
Args:
command (Union[str, Sequence[str]]): The redis command.
Returns:
ResponseT: The response associated with the command, or None if the command is not in the cache. # noqa
"""
if command in self.cache:
if self._is_expired(command):
self.delete_command(command)
return
self._update_access(command)
response = self.cache[command]["response"]
return (
response
if isinstance(response, IMMUTABLES)
else copy.deepcopy(response)
)
def delete_command(self, command: Union[str, Sequence[str]]):
"""
Delete a redis command and its metadata from the cache.
Args:
command (Union[str, Sequence[str]]): The redis command to be deleted.
"""
if command in self.cache:
keys_in_command = self.cache[command].get("keys")
self._del_key_commands_map(keys_in_command, command)
self.commands_ttl_list.remove(command)
del self.cache[command]
def delete_commands(self, commands: List[Union[str, Sequence[str]]]):
"""
Delete multiple commands and their metadata from the cache.
Args:
commands (List[Union[str, Sequence[str]]]): The list of commands to be
deleted.
"""
for command in commands:
self.delete_command(command)
def flush(self):
"""Clear the entire cache, removing all redis commands and metadata."""
self.cache.clear()
self.key_commands_map.clear()
self.commands_ttl_list = []
def _is_expired(self, command: Union[str, Sequence[str]]) -> bool:
"""
Check if a redis command has expired based on its time-to-live.
Args:
command (Union[str, Sequence[str]]): The redis command.
Returns:
bool: True if the command has expired, False otherwise.
"""
if self.ttl == 0:
return False
return time.monotonic() - self.cache[command]["ctime"] > self.ttl
def _update_access(self, command: Union[str, Sequence[str]]):
"""
Update the access information for a redis command based on the eviction policy.
Args:
command (Union[str, Sequence[str]]): The redis command.
"""
if self.eviction_policy == EvictionPolicy.LRU:
self.cache.move_to_end(command)
elif self.eviction_policy == EvictionPolicy.LFU:
self.cache[command]["access_count"] = (
self.cache.get(command, {}).get("access_count", 0) + 1
)
self.cache.move_to_end(command)
elif self.eviction_policy == EvictionPolicy.RANDOM:
pass # Random eviction doesn't require updates
def _evict(self):
"""Evict a redis command from the cache based on the eviction policy."""
if self._is_expired(self.commands_ttl_list[0]):
self.delete_command(self.commands_ttl_list[0])
elif self.eviction_policy == EvictionPolicy.LRU:
self.cache.popitem(last=False)
elif self.eviction_policy == EvictionPolicy.LFU:
min_access_command = min(
self.cache, key=lambda k: self.cache[k].get("access_count", 0)
)
self.cache.pop(min_access_command)
elif self.eviction_policy == EvictionPolicy.RANDOM:
random_command = random.choice(list(self.cache.keys()))
self.cache.pop(random_command)
def _update_key_commands_map(
self, keys: List[KeyT], command: Union[str, Sequence[str]]
):
"""
Update the key_commands_map with command that uses the keys.
Args:
keys (List[KeyT]): The list of keys used in the command.
command (Union[str, Sequence[str]]): The redis command.
"""
for key in keys:
self.key_commands_map[key].add(command)
def _del_key_commands_map(
self, keys: List[KeyT], command: Union[str, Sequence[str]]
):
"""
Remove a redis command from the key_commands_map.
Args:
keys (List[KeyT]): The list of keys used in the redis command.
command (Union[str, Sequence[str]]): The redis command.
"""
for key in keys:
self.key_commands_map[key].remove(command)
def invalidate_key(self, key: KeyT):
"""
Invalidate (delete) all redis commands associated with a specific key.
Args:
key (KeyT): The key to be invalidated.
"""
if key not in self.key_commands_map:
return
commands = list(self.key_commands_map[key])
for command in commands:
self.delete_command(command)