mirror of
https://github.com/ltcptgeneral/cs239-caching.git
synced 2025-09-23 15:10:19 +00:00
Add to db instead of creating new one
This commit is contained in:
59
app/cache/prefetch_cache.py
vendored
59
app/cache/prefetch_cache.py
vendored
@@ -1,11 +1,29 @@
|
||||
from .cache import BaselineCache
|
||||
from .cache import Cache
|
||||
from database import get_user_profile
|
||||
from collections import OrderedDict
|
||||
import math
|
||||
|
||||
class PrefetchCache(BaselineCache):
|
||||
key_relations = None
|
||||
class PrefetchCache(Cache):
|
||||
limit = None
|
||||
cache = None
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, limit):
|
||||
super()
|
||||
self.key_relations = dict()
|
||||
self.limit = limit
|
||||
self.cache = OrderedDict()
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.cache == other
|
||||
|
||||
def __len__(self):
|
||||
return len(self.cache)
|
||||
|
||||
def get(self, key: str) -> str:
|
||||
if key in self.cache:
|
||||
self.cache.move_to_end(key)
|
||||
return self.cache[key]
|
||||
else:
|
||||
return None
|
||||
|
||||
def put(self, key: str, val: str) -> bool:
|
||||
# LRU evict
|
||||
@@ -14,16 +32,29 @@ class PrefetchCache(BaselineCache):
|
||||
self.cache.popitem(last = False)
|
||||
evict = True
|
||||
self.cache[key] = val
|
||||
self.prefetch(key, val)
|
||||
if self.prefetch(val):
|
||||
evict = True
|
||||
|
||||
return evict
|
||||
|
||||
def prefetch(self, key: str, val: str) -> bool:
|
||||
if len(self.cache) >= self.limit and key in self.key_relations:
|
||||
self.cache[self.key_relations[key][0]] = self.key_relations[key][1]
|
||||
return True
|
||||
return False
|
||||
def prefetch(self, profile) -> bool:
|
||||
evict = False
|
||||
for i in range(math.ceil(self.limit*0.1)):
|
||||
if i < len(profile["friends"]):
|
||||
data = get_user_profile(profile["friends"][i])
|
||||
if len(self.cache) >= self.limit:
|
||||
self.cache.popitem(last = False)
|
||||
evict = True
|
||||
self.cache[profile["friends"][i]] = data
|
||||
else:
|
||||
break
|
||||
return evict
|
||||
|
||||
def set_relations(self, key: str, related_key: str, related_val: str):
|
||||
self.key_relations[key] = related_key | related_val
|
||||
return
|
||||
def invalidate(self, key: str) -> bool:
|
||||
# basic delete invalidation, no (p)refetching
|
||||
if key in self.cache:
|
||||
del self.cache[key]
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
Reference in New Issue
Block a user