| 1 |
from .settings import cachalot_settings |
| 2 |
|
| 3 |
|
| 4 |
class AtomicCache(dict): |
| 5 |
def __init__(self, parent_cache, db_alias): |
| 6 |
super().__init__() |
| 7 |
self.parent_cache = parent_cache |
| 8 |
self.db_alias = db_alias |
| 9 |
self.to_be_invalidated = set() |
| 10 |
|
| 11 |
def set(self, k, v, timeout): |
| 12 |
self[k] = v |
| 13 |
|
| 14 |
def get_many(self, keys): |
| 15 |
# Get values present in this cache level |
| 16 |
data = {k: self[k] for k in keys if k in self} |
| 17 |
|
| 18 |
# Identify keys that are missing at this level |
| 19 |
missing_keys = set(keys) |
| 20 |
missing_keys.difference_update(data) |
| 21 |
|
| 22 |
# Only proceed if there are missing keys |
| 23 |
if missing_keys: |
| 24 |
# Find the bottom-most non-AtomicCache to avoid recursion |
| 25 |
current_cache = self.parent_cache |
| 26 |
visited_caches = set([id(self)]) |
| 27 |
|
| 28 |
# Continue until we hit a non-AtomicCache or visit a cache we've seen before |
| 29 |
while isinstance(current_cache, AtomicCache) and id(current_cache) not in visited_caches: |
| 30 |
# Mark this cache as visited |
| 31 |
visited_caches.add(id(current_cache)) |
| 32 |
|
| 33 |
# Get any keys available in this cache level |
| 34 |
available_keys = missing_keys.intersection(current_cache.keys()) |
| 35 |
if available_keys: |
| 36 |
for k in available_keys: |
| 37 |
data[k] = current_cache[k] |
| 38 |
missing_keys.difference_update(available_keys) |
| 39 |
|
| 40 |
# If we found all keys, no need to go further |
| 41 |
if not missing_keys: |
| 42 |
break |
| 43 |
|
| 44 |
# Move to the parent cache |
| 45 |
current_cache = current_cache.parent_cache |
| 46 |
|
| 47 |
# If we've reached a non-AtomicCache and still have missing keys, use its get_many method |
| 48 |
if missing_keys and not isinstance(current_cache, AtomicCache) and hasattr(current_cache, 'get_many'): |
| 49 |
parent_data = current_cache.get_many(missing_keys) |
| 50 |
data.update(parent_data) |
| 51 |
|
| 52 |
return data |
| 53 |
|
| 54 |
def set_many(self, data, timeout): |
| 55 |
self.update(data) |
| 56 |
|
| 57 |
def commit(self): |
| 58 |
# We import this here to avoid a circular import issue. |
| 59 |
from .utils import _invalidate_tables |
| 60 |
|
| 61 |
if self: |
| 62 |
self.parent_cache.set_many( |
| 63 |
self, cachalot_settings.CACHALOT_TIMEOUT) |
| 64 |
# The previous `set_many` is not enough. The parent cache needs to be |
| 65 |
# invalidated in case another transaction occurred in the meantime. |
| 66 |
_invalidate_tables(self.parent_cache, self.db_alias, |
| 67 |
self.to_be_invalidated) |