|
2 | 2 |
|
3 | 3 | import threading |
4 | 4 | import time |
| 5 | +from functools import update_wrapper |
5 | 6 |
|
| 7 | +import six |
6 | 8 |
|
7 | | -class ElementExpiredException(Exception): |
8 | | - """Exception to be thrown when an element requested is present but expired.""" |
9 | 9 |
|
10 | | - pass |
| 10 | +DEFAULT_MAX_AGE = 5 |
| 11 | +DEFAULT_MAX_SIZE = 100 |
11 | 12 |
|
12 | 13 |
|
13 | | -class ElementNotPresentException(Exception): |
14 | | - """Exception to be thrown when an element requested is not present.""" |
| 14 | +class LocalMemoryCache(object): #pylint: disable=too-many-instance-attributes |
| 15 | + """ |
| 16 | + Key/Value local memory cache. with expiration & LRU eviction. |
15 | 17 |
|
16 | | - pass |
| 18 | + LRU double-linked-list format: |
17 | 19 |
|
| 20 | + { |
| 21 | + 'key1'--------------------------------------------------------------- |
| 22 | + 'key2'------------------------------------ | |
| 23 | + 'key3'------------ | | |
| 24 | + } | | | |
| 25 | + V V V |
| 26 | + || MRU || -previous-> || X || ... -previous-> || LRU || -previous-> None |
| 27 | + None <---next--- || node || <---next--- || node || ... <---next--- || node || |
| 28 | + """ |
18 | 29 |
|
19 | | -class LocalMemoryCache(object): |
20 | | - """Key/Value local memory cache. with deprecation.""" |
| 30 | + class _Node(object): #pylint: disable=too-few-public-methods |
| 31 | + """Links to previous an next items in the circular list.""" |
21 | 32 |
|
22 | | - def __init__(self, max_age_seconds=5): |
| 33 | + def __init__(self, key, value, last_update, previous_element, next_element): #pylint: disable=too-many-arguments |
| 34 | + """Class constructor.""" |
| 35 | + self.key = key # we also keep the key for O(1) access when removing the LRU. |
| 36 | + self.value = value |
| 37 | + self.last_update = last_update |
| 38 | + self.previous = previous_element |
| 39 | + self.next = next_element |
| 40 | + |
| 41 | + def __str__(self): |
| 42 | + """Return string representation.""" |
| 43 | + return '(%s, %s)' % (self.key, self.value) |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + key_func, |
| 48 | + user_func, |
| 49 | + max_age_seconds=DEFAULT_MAX_AGE, |
| 50 | + max_size=DEFAULT_MAX_SIZE |
| 51 | + ): |
23 | 52 | """Class constructor.""" |
24 | 53 | self._data = {} |
25 | 54 | self._lock = threading.RLock() |
26 | 55 | self._max_age_seconds = max_age_seconds |
| 56 | + self._max_size = max_size |
| 57 | + self._lru = None |
| 58 | + self._mru = None |
| 59 | + self._key_func = key_func |
| 60 | + self._user_func = user_func |
27 | 61 |
|
28 | | - def set(self, key, value): |
| 62 | + def get(self, *args, **kwargs): |
29 | 63 | """ |
30 | | - Set a key/value pair. |
| 64 | + Fetch an item from the cache. If it's a miss, call user function to refill. |
31 | 65 |
|
32 | | - :param key: Key used to reference the value. |
33 | | - :type key: str |
34 | | - :param value: Value to store. |
35 | | - :type value: object |
| 66 | + :param args: User supplied positional arguments |
| 67 | + :type args: list |
| 68 | + :param kwargs: User supplied keyword arguments |
| 69 | + :type kwargs: dict |
| 70 | +
|
| 71 | + :return: Cached/Fetched object |
| 72 | + :rtype: object |
36 | 73 | """ |
37 | 74 | with self._lock: |
38 | | - self._data[key] = (value, time.time()) |
| 75 | + key = self._key_func(*args, **kwargs) |
| 76 | + node = self._data.get(key) |
| 77 | + if node is not None: |
| 78 | + if self._is_expired(node): |
| 79 | + node.value = self._user_func(*args, **kwargs) |
| 80 | + node.last_update = time.time() |
| 81 | + else: |
| 82 | + value = self._user_func(*args, **kwargs) |
| 83 | + node = LocalMemoryCache._Node(key, value, time.time(), None, None) |
| 84 | + node = self._bubble_up(node) |
| 85 | + self._data[key] = node |
| 86 | + self._rollover() |
| 87 | + return node.value |
| 88 | + |
| 89 | + def remove_expired(self): |
| 90 | + """Remove expired elements.""" |
| 91 | + with self._lock: |
| 92 | + self._data = { |
| 93 | + key: value for (key, value) in six.iteritems(self._data) |
| 94 | + if not self._is_expired(value) |
| 95 | + } |
39 | 96 |
|
40 | | - def get(self, key): |
| 97 | + def clear(self): |
| 98 | + """Clear the cache.""" |
| 99 | + self._data = {} |
| 100 | + self._lru = None |
| 101 | + self._mru = None |
| 102 | + |
| 103 | + def _is_expired(self, node): |
| 104 | + """Return whether the data held by the node is expired.""" |
| 105 | + return time.time() - self._max_age_seconds > node.last_update |
| 106 | + |
| 107 | + def _bubble_up(self, node): |
| 108 | + """Send node to the top of the list (mark it as the MRU).""" |
| 109 | + if node is None: |
| 110 | + return None |
| 111 | + |
| 112 | + if node.previous is not None: |
| 113 | + node.previous.next = node.next |
| 114 | + |
| 115 | + if node.next is not None: |
| 116 | + node.next.previous = node.previous |
| 117 | + |
| 118 | + if self._lru == node: |
| 119 | + if node.next is not None: #only update lru pointer if there are more than 1 elements. |
| 120 | + self._lru = node.next |
| 121 | + |
| 122 | + if not self._data: |
| 123 | + # if there are no items, set the LRU to this node |
| 124 | + self._lru = node |
| 125 | + else: |
| 126 | + # if there is at least one item, update the MRU chain |
| 127 | + self._mru.next = node |
| 128 | + |
| 129 | + node.next = None |
| 130 | + node.previous = self._mru |
| 131 | + self._mru = node |
| 132 | + return node |
| 133 | + |
| 134 | + def _rollover(self): |
| 135 | + """Check we're within the size limit. Otherwise drop the LRU.""" |
| 136 | + if len(self._data) > self._max_size: |
| 137 | + next_item = self._lru.next |
| 138 | + del self._data[self._lru.key] |
| 139 | + self._lru = next_item |
| 140 | + |
| 141 | + def __str__(self): |
| 142 | + """User friendly representation of cache.""" |
| 143 | + nodes = [] |
| 144 | + node = self._mru |
| 145 | + while node is not None: |
| 146 | + nodes.append('<%s: %s> -->' % (node.key, node.value)) |
| 147 | + node = node.previous |
| 148 | + return '<MRU>\n' + '\n'.join(nodes) + '\n<LRU>' |
| 149 | + |
| 150 | + |
| 151 | +def decorate(key_func, max_age_seconds=DEFAULT_MAX_AGE, max_size=DEFAULT_MAX_SIZE): |
| 152 | + """ |
| 153 | + Decorate a function or method to cache results up to `max_age_seconds`. |
| 154 | +
|
| 155 | + :param key_func: user specified function to execute over the arguments to determine the key. |
| 156 | + :type key_func: callable |
| 157 | + :param max_age_seconds: Maximum number of seconds during which the cached value is valid. |
| 158 | + :type max_age_seconds: int |
| 159 | +
|
| 160 | + :return: Decorating function wrapper. |
| 161 | + :rtype: callable |
| 162 | + """ |
| 163 | + if max_age_seconds < 0: |
| 164 | + raise TypeError('Max cache age cannot be a negative number.') |
| 165 | + |
| 166 | + if max_size < 0: |
| 167 | + raise TypeError('Max cache size cannot be a negative number.') |
| 168 | + |
| 169 | + if max_age_seconds == 0 or max_size == 0: |
| 170 | + return lambda function: function # bypass cache overlay. |
| 171 | + |
| 172 | + def _decorator(user_function): |
41 | 173 | """ |
42 | | - Attempt to get a value based on a key. |
| 174 | + Decorate function to be used with `@` syntax. |
43 | 175 |
|
44 | | - :param key: Key associated with the value. |
45 | | - :type key: str |
| 176 | + :param user_function: Function to decorate with cacheable results |
| 177 | + :type user_function: callable |
46 | 178 |
|
47 | | - :return: The value associated with the key. None if it doesn't exist. |
48 | | - :rtype: object |
| 179 | + :return: A function that looks exactly the same but with cacheable results. |
| 180 | + :rtype: callable |
49 | 181 | """ |
50 | | - try: |
51 | | - value, set_time = self._data[key] |
52 | | - except KeyError: |
53 | | - raise ElementNotPresentException('Element %s not present in local storage' % key) |
54 | | - |
55 | | - if (time.time() - set_time) > self._max_age_seconds: |
56 | | - raise ElementExpiredException('Element %s present but expired' % key) |
| 182 | + _cache = LocalMemoryCache(key_func, user_function, max_age_seconds, max_size) |
| 183 | + wrapper = _cache.get |
| 184 | + return update_wrapper(wrapper, user_function) |
57 | 185 |
|
58 | | - return value |
| 186 | + return _decorator |
0 commit comments