lru_cache.py 14 KB

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