lru_cache.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. Args:
  126. key: The key to store it under
  127. value: The object to store
  128. cleanup: None or a function taking (key, value) to indicate
  129. 'value' should be cleaned up.
  130. """
  131. if key is _null_key:
  132. raise ValueError('cannot use _null_key as a key')
  133. if key in self._cache:
  134. node = self._cache[key]
  135. node.run_cleanup()
  136. node.value = value
  137. node.cleanup = cleanup
  138. else:
  139. node = _LRUNode(key, value, cleanup=cleanup)
  140. self._cache[key] = node
  141. self._record_access(node)
  142. if len(self._cache) > self._max_cache:
  143. # Trigger the cleanup
  144. self.cleanup()
  145. def cache_size(self):
  146. """Get the number of entries we will cache."""
  147. return self._max_cache
  148. def get(self, key, default=None):
  149. node = self._cache.get(key, None)
  150. if node is None:
  151. return default
  152. self._record_access(node)
  153. return node.value
  154. def keys(self):
  155. """Get the list of keys currently cached.
  156. Note that values returned here may not be available by the time you
  157. request them later. This is simply meant as a peak into the current
  158. state.
  159. Returns: An unordered list of keys that are currently cached.
  160. """
  161. return self._cache.keys()
  162. def items(self):
  163. """Get the key:value pairs as a dict."""
  164. return dict((k, n.value) for k, n in self._cache.items())
  165. def cleanup(self):
  166. """Clear the cache until it shrinks to the requested size.
  167. This does not completely wipe the cache, just makes sure it is under
  168. the after_cleanup_count.
  169. """
  170. # Make sure the cache is shrunk to the correct size
  171. while len(self._cache) > self._after_cleanup_count:
  172. self._remove_lru()
  173. def __setitem__(self, key, value):
  174. """Add a value to the cache, there will be no cleanup function."""
  175. self.add(key, value, cleanup=None)
  176. def _record_access(self, node):
  177. """Record that key was accessed."""
  178. # Move 'node' to the front of the queue
  179. if self._most_recently_used is None:
  180. self._most_recently_used = node
  181. self._least_recently_used = node
  182. return
  183. elif node is self._most_recently_used:
  184. # Nothing to do, this node is already at the head of the queue
  185. return
  186. # We've taken care of the tail pointer, remove the node, and insert it
  187. # at the front
  188. # REMOVE
  189. if node is self._least_recently_used:
  190. self._least_recently_used = node.prev
  191. if node.prev is not None:
  192. node.prev.next_key = node.next_key
  193. if node.next_key is not _null_key:
  194. node_next = self._cache[node.next_key]
  195. node_next.prev = node.prev
  196. # INSERT
  197. node.next_key = self._most_recently_used.key
  198. self._most_recently_used.prev = node
  199. self._most_recently_used = node
  200. node.prev = None
  201. def _remove_node(self, node):
  202. if node is self._least_recently_used:
  203. self._least_recently_used = node.prev
  204. self._cache.pop(node.key)
  205. # If we have removed all entries, remove the head pointer as well
  206. if self._least_recently_used is None:
  207. self._most_recently_used = None
  208. node.run_cleanup()
  209. # Now remove this node from the linked list
  210. if node.prev is not None:
  211. node.prev.next_key = node.next_key
  212. if node.next_key is not _null_key:
  213. node_next = self._cache[node.next_key]
  214. node_next.prev = node.prev
  215. # And remove this node's pointers
  216. node.prev = None
  217. node.next_key = _null_key
  218. def _remove_lru(self):
  219. """Remove one entry from the lru, and handle consequences.
  220. If there are no more references to the lru, then this entry should be
  221. removed from the cache.
  222. """
  223. self._remove_node(self._least_recently_used)
  224. def clear(self):
  225. """Clear out all of the cache."""
  226. # Clean up in LRU order
  227. while self._cache:
  228. self._remove_lru()
  229. def resize(self, max_cache, after_cleanup_count=None):
  230. """Change the number of entries that will be cached."""
  231. self._update_max_cache(max_cache,
  232. after_cleanup_count=after_cleanup_count)
  233. def _update_max_cache(self, max_cache, after_cleanup_count=None):
  234. self._max_cache = max_cache
  235. if after_cleanup_count is None:
  236. self._after_cleanup_count = self._max_cache * 8 / 10
  237. else:
  238. self._after_cleanup_count = min(after_cleanup_count,
  239. self._max_cache)
  240. self.cleanup()
  241. class LRUSizeCache(LRUCache):
  242. """An LRUCache that removes things based on the size of the values.
  243. This differs in that it doesn't care how many actual items there are,
  244. it just restricts the cache to be cleaned up after so much data is stored.
  245. The size of items added will be computed using compute_size(value), which
  246. defaults to len() if not supplied.
  247. """
  248. def __init__(self, max_size=1024*1024, after_cleanup_size=None,
  249. compute_size=None):
  250. """Create a new LRUSizeCache.
  251. Args:
  252. max_size: The max number of bytes to store before we start
  253. clearing out entries.
  254. after_cleanup_size: After cleaning up, shrink everything to this
  255. size.
  256. compute_size: A function to compute the size of the values. We
  257. use a function here, so that you can pass 'len' if you are just
  258. using simple strings, or a more complex function if you are using
  259. something like a list of strings, or even a custom object.
  260. The function should take the form "compute_size(value) => integer".
  261. If not supplied, it defaults to 'len()'
  262. """
  263. self._value_size = 0
  264. self._compute_size = compute_size
  265. if compute_size is None:
  266. self._compute_size = len
  267. self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
  268. LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
  269. def add(self, key, value, cleanup=None):
  270. """Add a new value to the cache.
  271. Also, if the entry is ever removed from the cache, call
  272. cleanup(key, value).
  273. Args:
  274. key: The key to store it under
  275. value: The object to store
  276. cleanup: None or a function taking (key, value) to indicate
  277. 'value' should be cleaned up.
  278. """
  279. if key is _null_key:
  280. raise ValueError('cannot use _null_key as a key')
  281. node = self._cache.get(key, None)
  282. value_len = self._compute_size(value)
  283. if value_len >= self._after_cleanup_size:
  284. # The new value is 'too big to fit', as it would fill up/overflow
  285. # the cache all by itself
  286. if node is not None:
  287. # We won't be replacing the old node, so just remove it
  288. self._remove_node(node)
  289. if cleanup is not None:
  290. cleanup(key, value)
  291. return
  292. if node is None:
  293. node = _LRUNode(key, value, cleanup=cleanup)
  294. self._cache[key] = node
  295. else:
  296. self._value_size -= node.size
  297. node.size = value_len
  298. self._value_size += value_len
  299. self._record_access(node)
  300. if self._value_size > self._max_size:
  301. # Time to cleanup
  302. self.cleanup()
  303. def cleanup(self):
  304. """Clear the cache until it shrinks to the requested size.
  305. This does not completely wipe the cache, just makes sure it is under
  306. the after_cleanup_size.
  307. """
  308. # Make sure the cache is shrunk to the correct size
  309. while self._value_size > self._after_cleanup_size:
  310. self._remove_lru()
  311. def _remove_node(self, node):
  312. self._value_size -= node.size
  313. LRUCache._remove_node(self, node)
  314. def resize(self, max_size, after_cleanup_size=None):
  315. """Change the number of bytes that will be cached."""
  316. self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
  317. max_cache = max(int(max_size/512), 1)
  318. self._update_max_cache(max_cache)
  319. def _update_max_size(self, max_size, after_cleanup_size=None):
  320. self._max_size = max_size
  321. if after_cleanup_size is None:
  322. self._after_cleanup_size = self._max_size * 8 // 10
  323. else:
  324. self._after_cleanup_size = min(after_cleanup_size, self._max_size)