lru_cache.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. # Copyright (C) 2006, 2008 Canonical Ltd
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  16. """A simple least-recently-used (LRU) cache."""
  17. _null_key = object()
  18. class _LRUNode(object):
  19. """This maintains the linked-list which is the lru internals."""
  20. __slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size')
  21. def __init__(self, key, value, cleanup=None):
  22. self.prev = None
  23. self.next_key = _null_key
  24. self.key = key
  25. self.value = value
  26. self.cleanup = cleanup
  27. # TODO: We could compute this 'on-the-fly' like we used to, and remove
  28. # one pointer from this object, we just need to decide if it
  29. # actually costs us much of anything in normal usage
  30. self.size = None
  31. def __repr__(self):
  32. if self.prev is None:
  33. prev_key = None
  34. else:
  35. prev_key = self.prev.key
  36. return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
  37. self.next_key, prev_key)
  38. def run_cleanup(self):
  39. if self.cleanup is not None:
  40. self.cleanup(self.key, self.value)
  41. self.cleanup = None
  42. # Just make sure to break any refcycles, etc
  43. self.value = None
  44. class LRUCache(object):
  45. """A class which manages a cache of entries, removing unused ones."""
  46. def __init__(self, max_cache=100, after_cleanup_count=None):
  47. self._cache = {}
  48. # The "HEAD" of the lru linked list
  49. self._most_recently_used = None
  50. # The "TAIL" of the lru linked list
  51. self._least_recently_used = None
  52. self._update_max_cache(max_cache, after_cleanup_count)
  53. def __contains__(self, key):
  54. return key in self._cache
  55. def __getitem__(self, key):
  56. cache = self._cache
  57. node = cache[key]
  58. # Inlined from _record_access to decrease the overhead of __getitem__
  59. # We also have more knowledge about structure if __getitem__ is
  60. # succeeding, then we know that self._most_recently_used must not be
  61. # None, etc.
  62. mru = self._most_recently_used
  63. if node is mru:
  64. # Nothing to do, this node is already at the head of the queue
  65. return node.value
  66. # Remove this node from the old location
  67. node_prev = node.prev
  68. next_key = node.next_key
  69. # benchmarking shows that the lookup of _null_key in globals is faster
  70. # than the attribute lookup for (node is self._least_recently_used)
  71. if next_key is _null_key:
  72. # 'node' is the _least_recently_used, because it doesn't have a
  73. # 'next' item. So move the current lru to the previous node.
  74. self._least_recently_used = node_prev
  75. else:
  76. node_next = cache[next_key]
  77. node_next.prev = node_prev
  78. node_prev.next_key = next_key
  79. # Insert this node at the front of the list
  80. node.next_key = mru.key
  81. mru.prev = node
  82. self._most_recently_used = node
  83. node.prev = None
  84. return node.value
  85. def __len__(self):
  86. return len(self._cache)
  87. def _walk_lru(self):
  88. """Walk the LRU list, only meant to be used in tests."""
  89. node = self._most_recently_used
  90. if node is not None:
  91. if node.prev is not None:
  92. raise AssertionError('the _most_recently_used entry is not'
  93. ' supposed to have a previous entry'
  94. ' %s' % (node,))
  95. while node is not None:
  96. if node.next_key is _null_key:
  97. if node is not self._least_recently_used:
  98. raise AssertionError('only the last node should have'
  99. ' no next value: %s' % (node,))
  100. node_next = None
  101. else:
  102. node_next = self._cache[node.next_key]
  103. if node_next.prev is not node:
  104. raise AssertionError('inconsistency found, node.next.prev'
  105. ' != node: %s' % (node,))
  106. if node.prev is None:
  107. if node is not self._most_recently_used:
  108. raise AssertionError('only the _most_recently_used should'
  109. ' not have a previous node: %s'
  110. % (node,))
  111. else:
  112. if node.prev.next_key != node.key:
  113. raise AssertionError('inconsistency found, node.prev.next'
  114. ' != node: %s' % (node,))
  115. yield node
  116. node = node_next
  117. def add(self, key, value, cleanup=None):
  118. """Add a new value to the cache.
  119. Also, if the entry is ever removed from the cache, call
  120. cleanup(key, value).
  121. :param key: The key to store it under
  122. :param value: The object to store
  123. :param cleanup: None or a function taking (key, value) to indicate
  124. 'value' should be cleaned up.
  125. """
  126. if key is _null_key:
  127. raise ValueError('cannot use _null_key as a key')
  128. if key in self._cache:
  129. node = self._cache[key]
  130. node.run_cleanup()
  131. node.value = value
  132. node.cleanup = cleanup
  133. else:
  134. node = _LRUNode(key, value, cleanup=cleanup)
  135. self._cache[key] = node
  136. self._record_access(node)
  137. if len(self._cache) > self._max_cache:
  138. # Trigger the cleanup
  139. self.cleanup()
  140. def cache_size(self):
  141. """Get the number of entries we will cache."""
  142. return self._max_cache
  143. def get(self, key, default=None):
  144. node = self._cache.get(key, None)
  145. if node is None:
  146. return default
  147. self._record_access(node)
  148. return node.value
  149. def keys(self):
  150. """Get the list of keys currently cached.
  151. Note that values returned here may not be available by the time you
  152. request them later. This is simply meant as a peak into the current
  153. state.
  154. :return: An unordered list of keys that are currently cached.
  155. """
  156. return self._cache.keys()
  157. def items(self):
  158. """Get the key:value pairs as a dict."""
  159. return dict((k, n.value) for k, n in self._cache.iteritems())
  160. def cleanup(self):
  161. """Clear the cache until it shrinks to the requested size.
  162. This does not completely wipe the cache, just makes sure it is under
  163. the after_cleanup_count.
  164. """
  165. # Make sure the cache is shrunk to the correct size
  166. while len(self._cache) > self._after_cleanup_count:
  167. self._remove_lru()
  168. def __setitem__(self, key, value):
  169. """Add a value to the cache, there will be no cleanup function."""
  170. self.add(key, value, cleanup=None)
  171. def _record_access(self, node):
  172. """Record that key was accessed."""
  173. # Move 'node' to the front of the queue
  174. if self._most_recently_used is None:
  175. self._most_recently_used = node
  176. self._least_recently_used = node
  177. return
  178. elif node is self._most_recently_used:
  179. # Nothing to do, this node is already at the head of the queue
  180. return
  181. # We've taken care of the tail pointer, remove the node, and insert it
  182. # at the front
  183. # REMOVE
  184. if node is self._least_recently_used:
  185. self._least_recently_used = node.prev
  186. if node.prev is not None:
  187. node.prev.next_key = node.next_key
  188. if node.next_key is not _null_key:
  189. node_next = self._cache[node.next_key]
  190. node_next.prev = node.prev
  191. # INSERT
  192. node.next_key = self._most_recently_used.key
  193. self._most_recently_used.prev = node
  194. self._most_recently_used = node
  195. node.prev = None
  196. def _remove_node(self, node):
  197. if node is self._least_recently_used:
  198. self._least_recently_used = node.prev
  199. self._cache.pop(node.key)
  200. # If we have removed all entries, remove the head pointer as well
  201. if self._least_recently_used is None:
  202. self._most_recently_used = None
  203. node.run_cleanup()
  204. # Now remove this node from the linked list
  205. if node.prev is not None:
  206. node.prev.next_key = node.next_key
  207. if node.next_key is not _null_key:
  208. node_next = self._cache[node.next_key]
  209. node_next.prev = node.prev
  210. # And remove this node's pointers
  211. node.prev = None
  212. node.next_key = _null_key
  213. def _remove_lru(self):
  214. """Remove one entry from the lru, and handle consequences.
  215. If there are no more references to the lru, then this entry should be
  216. removed from the cache.
  217. """
  218. self._remove_node(self._least_recently_used)
  219. def clear(self):
  220. """Clear out all of the cache."""
  221. # Clean up in LRU order
  222. while self._cache:
  223. self._remove_lru()
  224. def resize(self, max_cache, after_cleanup_count=None):
  225. """Change the number of entries that will be cached."""
  226. self._update_max_cache(max_cache,
  227. after_cleanup_count=after_cleanup_count)
  228. def _update_max_cache(self, max_cache, after_cleanup_count=None):
  229. self._max_cache = max_cache
  230. if after_cleanup_count is None:
  231. self._after_cleanup_count = self._max_cache * 8 / 10
  232. else:
  233. self._after_cleanup_count = min(after_cleanup_count,
  234. self._max_cache)
  235. self.cleanup()
  236. class LRUSizeCache(LRUCache):
  237. """An LRUCache that removes things based on the size of the values.
  238. This differs in that it doesn't care how many actual items there are,
  239. it just restricts the cache to be cleaned up after so much data is stored.
  240. The size of items added will be computed using compute_size(value), which
  241. defaults to len() if not supplied.
  242. """
  243. def __init__(self, max_size=1024*1024, after_cleanup_size=None,
  244. compute_size=None):
  245. """Create a new LRUSizeCache.
  246. :param max_size: The max number of bytes to store before we start
  247. clearing out entries.
  248. :param after_cleanup_size: After cleaning up, shrink everything to this
  249. size.
  250. :param compute_size: A function to compute the size of the values. We
  251. use a function here, so that you can pass 'len' if you are just
  252. using simple strings, or a more complex function if you are using
  253. something like a list of strings, or even a custom object.
  254. The function should take the form "compute_size(value) => integer".
  255. If not supplied, it defaults to 'len()'
  256. """
  257. self._value_size = 0
  258. self._compute_size = compute_size
  259. if compute_size is None:
  260. self._compute_size = len
  261. self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
  262. LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
  263. def add(self, key, value, cleanup=None):
  264. """Add a new value to the cache.
  265. Also, if the entry is ever removed from the cache, call
  266. cleanup(key, value).
  267. :param key: The key to store it under
  268. :param value: The object to store
  269. :param cleanup: None or a function taking (key, value) to indicate
  270. 'value' should be cleaned up.
  271. """
  272. if key is _null_key:
  273. raise ValueError('cannot use _null_key as a key')
  274. node = self._cache.get(key, None)
  275. value_len = self._compute_size(value)
  276. if value_len >= self._after_cleanup_size:
  277. # The new value is 'too big to fit', as it would fill up/overflow
  278. # the cache all by itself
  279. if node is not None:
  280. # We won't be replacing the old node, so just remove it
  281. self._remove_node(node)
  282. if cleanup is not None:
  283. cleanup(key, value)
  284. return
  285. if node is None:
  286. node = _LRUNode(key, value, cleanup=cleanup)
  287. self._cache[key] = node
  288. else:
  289. self._value_size -= node.size
  290. node.size = value_len
  291. self._value_size += value_len
  292. self._record_access(node)
  293. if self._value_size > self._max_size:
  294. # Time to cleanup
  295. self.cleanup()
  296. def cleanup(self):
  297. """Clear the cache until it shrinks to the requested size.
  298. This does not completely wipe the cache, just makes sure it is under
  299. the after_cleanup_size.
  300. """
  301. # Make sure the cache is shrunk to the correct size
  302. while self._value_size > self._after_cleanup_size:
  303. self._remove_lru()
  304. def _remove_node(self, node):
  305. self._value_size -= node.size
  306. LRUCache._remove_node(self, node)
  307. def resize(self, max_size, after_cleanup_size=None):
  308. """Change the number of bytes that will be cached."""
  309. self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
  310. max_cache = max(int(max_size/512), 1)
  311. self._update_max_cache(max_cache)
  312. def _update_max_size(self, max_size, after_cleanup_size=None):
  313. self._max_size = max_size
  314. if after_cleanup_size is None:
  315. self._after_cleanup_size = self._max_size * 8 / 10
  316. else:
  317. self._after_cleanup_size = min(after_cleanup_size, self._max_size)