/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4516.2.1 by John Arbash Meinel
Fix bug #396838, Update LRUCache to maintain invariant even
1
# Copyright (C) 2006, 2008, 2009 Canonical Ltd
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
16
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
17
"""A simple least-recently-used (LRU) cache."""
18
6379.6.3 by Jelmer Vernooij
Use absolute_import.
19
from __future__ import absolute_import
20
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
21
from . import (
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
22
    trace,
23
    )
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
24
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
25
_null_key = object()
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
26
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
27
class _LRUNode(object):
28
    """This maintains the linked-list which is the lru internals."""
29
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
30
    __slots__ = ('prev', 'next_key', 'key', 'value')
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
31
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
32
    def __init__(self, key, value):
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
33
        self.prev = None
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
34
        self.next_key = _null_key
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
35
        self.key = key
36
        self.value = value
37
38
    def __repr__(self):
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
39
        if self.prev is None:
40
            prev_key = None
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
41
        else:
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
42
            prev_key = self.prev.key
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
43
        return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
44
                                     self.next_key, prev_key)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
45
46
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
47
class LRUCache(object):
48
    """A class which manages a cache of entries, removing unused ones."""
49
5346.1.4 by Vincent Ladeuil
Delete the after_cleanup_size parameter from the LRUCache constructor.
50
    def __init__(self, max_cache=100, after_cleanup_count=None):
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
51
        self._cache = {}
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
52
        # The "HEAD" of the lru linked list
53
        self._most_recently_used = None
54
        # The "TAIL" of the lru linked list
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
55
        self._least_recently_used = None
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
56
        self._update_max_cache(max_cache, after_cleanup_count)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
57
58
    def __contains__(self, key):
59
        return key in self._cache
60
61
    def __getitem__(self, key):
4287.1.6 by John Arbash Meinel
Remove the double getattr() for self._cache.
62
        cache = self._cache
63
        node = cache[key]
4178.3.4 by John Arbash Meinel
Shave off approx 100ms by inlining _record_access into __getitem__,
64
        # Inlined from _record_access to decrease the overhead of __getitem__
65
        # We also have more knowledge about structure if __getitem__ is
66
        # succeeding, then we know that self._most_recently_used must not be
67
        # None, etc.
68
        mru = self._most_recently_used
69
        if node is mru:
70
            # Nothing to do, this node is already at the head of the queue
71
            return node.value
72
        # Remove this node from the old location
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
73
        node_prev = node.prev
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
74
        next_key = node.next_key
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
75
        # benchmarking shows that the lookup of _null_key in globals is faster
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
76
        # than the attribute lookup for (node is self._least_recently_used)
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
77
        if next_key is _null_key:
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
78
            # 'node' is the _least_recently_used, because it doesn't have a
4287.1.7 by John Arbash Meinel
Fairly significant savings... avoid looking at self._last_recently_used.
79
            # 'next' item. So move the current lru to the previous node.
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
80
            self._least_recently_used = node_prev
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
81
        else:
4287.1.6 by John Arbash Meinel
Remove the double getattr() for self._cache.
82
            node_next = cache[next_key]
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
83
            node_next.prev = node_prev
4287.1.7 by John Arbash Meinel
Fairly significant savings... avoid looking at self._last_recently_used.
84
        node_prev.next_key = next_key
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
85
        # Insert this node at the front of the list
86
        node.next_key = mru.key
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
87
        mru.prev = node
4178.3.4 by John Arbash Meinel
Shave off approx 100ms by inlining _record_access into __getitem__,
88
        self._most_recently_used = node
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
89
        node.prev = None
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
90
        return node.value
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
91
92
    def __len__(self):
93
        return len(self._cache)
94
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
95
    def __setitem__(self, key, value):
96
        """Add a new value to the cache"""
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
97
        if key is _null_key:
98
            raise ValueError('cannot use _null_key as a key')
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
99
        if key in self._cache:
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
100
            node = self._cache[key]
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
101
            node.value = value
102
            self._record_access(node)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
103
        else:
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
104
            node = _LRUNode(key, value)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
105
            self._cache[key] = node
4516.2.1 by John Arbash Meinel
Fix bug #396838, Update LRUCache to maintain invariant even
106
            self._record_access(node)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
107
108
        if len(self._cache) > self._max_cache:
109
            # Trigger the cleanup
110
            self.cleanup()
111
4178.3.1 by John Arbash Meinel
Implement LRUCache.cache_size(), so that it can trivially substitute for FIFOCache.
112
    def cache_size(self):
113
        """Get the number of entries we will cache."""
114
        return self._max_cache
115
2998.2.1 by John Arbash Meinel
Implement LRUCache.get() which acts like dict.get()
116
    def get(self, key, default=None):
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
117
        node = self._cache.get(key, None)
118
        if node is None:
119
            return default
4178.3.5 by John Arbash Meinel
Add tests that LRUCache.get() properly tracks accesses.
120
        self._record_access(node)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
121
        return node.value
2998.2.1 by John Arbash Meinel
Implement LRUCache.get() which acts like dict.get()
122
3763.8.10 by John Arbash Meinel
Add a .keys() member to LRUCache and LRUSizeCache.
123
    def keys(self):
124
        """Get the list of keys currently cached.
125
126
        Note that values returned here may not be available by the time you
127
        request them later. This is simply meant as a peak into the current
128
        state.
129
130
        :return: An unordered list of keys that are currently cached.
131
        """
132
        return self._cache.keys()
133
6215.1.1 by Martin Packman
Rename confusing LRUCache.items method that doesn't act like dict.items to as_dict
134
    def as_dict(self):
135
        """Get a new dict with the same key:value pairs as the cache"""
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
136
        return dict((k, n.value) for k, n in self._cache.iteritems())
137
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
138
    def cleanup(self):
139
        """Clear the cache until it shrinks to the requested size.
140
141
        This does not completely wipe the cache, just makes sure it is under
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
142
        the after_cleanup_count.
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
143
        """
144
        # Make sure the cache is shrunk to the correct size
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
145
        while len(self._cache) > self._after_cleanup_count:
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
146
            self._remove_lru()
147
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
148
    def _record_access(self, node):
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
149
        """Record that key was accessed."""
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
150
        # Move 'node' to the front of the queue
151
        if self._most_recently_used is None:
152
            self._most_recently_used = node
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
153
            self._least_recently_used = node
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
154
            return
155
        elif node is self._most_recently_used:
156
            # Nothing to do, this node is already at the head of the queue
157
            return
158
        # We've taken care of the tail pointer, remove the node, and insert it
159
        # at the front
160
        # REMOVE
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
161
        if node is self._least_recently_used:
162
            self._least_recently_used = node.prev
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
163
        if node.prev is not None:
164
            node.prev.next_key = node.next_key
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
165
        if node.next_key is not _null_key:
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
166
            node_next = self._cache[node.next_key]
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
167
            node_next.prev = node.prev
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
168
        # INSERT
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
169
        node.next_key = self._most_recently_used.key
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
170
        self._most_recently_used.prev = node
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
171
        self._most_recently_used = node
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
172
        node.prev = None
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
173
174
    def _remove_node(self, node):
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
175
        if node is self._least_recently_used:
176
            self._least_recently_used = node.prev
4178.3.6 by John Arbash Meinel
Remove the asserts, and change some to AssertionError.
177
        self._cache.pop(node.key)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
178
        # If we have removed all entries, remove the head pointer as well
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
179
        if self._least_recently_used is None:
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
180
            self._most_recently_used = None
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
181
        if node.prev is not None:
182
            node.prev.next_key = node.next_key
183
        if node.next_key is not _null_key:
184
            node_next = self._cache[node.next_key]
185
            node_next.prev = node.prev
186
        # And remove this node's pointers
187
        node.prev = None
188
        node.next_key = _null_key
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
189
190
    def _remove_lru(self):
191
        """Remove one entry from the lru, and handle consequences.
192
193
        If there are no more references to the lru, then this entry should be
194
        removed from the cache.
195
        """
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
196
        self._remove_node(self._least_recently_used)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
197
198
    def clear(self):
199
        """Clear out all of the cache."""
200
        # Clean up in LRU order
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
201
        while self._cache:
202
            self._remove_lru()
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
203
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
204
    def resize(self, max_cache, after_cleanup_count=None):
205
        """Change the number of entries that will be cached."""
206
        self._update_max_cache(max_cache,
207
                               after_cleanup_count=after_cleanup_count)
208
209
    def _update_max_cache(self, max_cache, after_cleanup_count=None):
210
        self._max_cache = max_cache
211
        if after_cleanup_count is None:
212
            self._after_cleanup_count = self._max_cache * 8 / 10
213
        else:
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
214
            self._after_cleanup_count = min(after_cleanup_count,
215
                                            self._max_cache)
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
216
        self.cleanup()
217
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
218
219
class LRUSizeCache(LRUCache):
220
    """An LRUCache that removes things based on the size of the values.
221
222
    This differs in that it doesn't care how many actual items there are,
223
    it just restricts the cache to be cleaned up after so much data is stored.
224
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
225
    The size of items added will be computed using compute_size(value), which
226
    defaults to len() if not supplied.
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
227
    """
228
229
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
230
                 compute_size=None):
231
        """Create a new LRUSizeCache.
232
233
        :param max_size: The max number of bytes to store before we start
234
            clearing out entries.
235
        :param after_cleanup_size: After cleaning up, shrink everything to this
236
            size.
237
        :param compute_size: A function to compute the size of the values. We
238
            use a function here, so that you can pass 'len' if you are just
239
            using simple strings, or a more complex function if you are using
240
            something like a list of strings, or even a custom object.
241
            The function should take the form "compute_size(value) => integer".
242
            If not supplied, it defaults to 'len()'
243
        """
244
        self._value_size = 0
245
        self._compute_size = compute_size
246
        if compute_size is None:
247
            self._compute_size = len
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
248
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
249
        LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
250
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
251
    def __setitem__(self, key, value):
252
        """Add a new value to the cache"""
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
253
        if key is _null_key:
254
            raise ValueError('cannot use _null_key as a key')
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
255
        node = self._cache.get(key, None)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
256
        value_len = self._compute_size(value)
257
        if value_len >= self._after_cleanup_size:
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
258
            # The new value is 'too big to fit', as it would fill up/overflow
259
            # the cache all by itself
260
            trace.mutter('Adding the key %r to an LRUSizeCache failed.'
261
                         ' value %d is too big to fit in a the cache'
262
                         ' with size %d %d', key, value_len,
263
                         self._after_cleanup_size, self._max_size)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
264
            if node is not None:
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
265
                # We won't be replacing the old node, so just remove it
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
266
                self._remove_node(node)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
267
            return
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
268
        if node is None:
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
269
            node = _LRUNode(key, value)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
270
            self._cache[key] = node
271
        else:
6215.1.3 by Martin Packman
Recompute size rather than storing on _LRUNode.size
272
            self._value_size -= self._compute_size(node.value)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
273
        self._value_size += value_len
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
274
        self._record_access(node)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
275
276
        if self._value_size > self._max_size:
277
            # Time to cleanup
278
            self.cleanup()
279
280
    def cleanup(self):
281
        """Clear the cache until it shrinks to the requested size.
282
283
        This does not completely wipe the cache, just makes sure it is under
284
        the after_cleanup_size.
285
        """
286
        # Make sure the cache is shrunk to the correct size
287
        while self._value_size > self._after_cleanup_size:
288
            self._remove_lru()
289
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
290
    def _remove_node(self, node):
6215.1.3 by Martin Packman
Recompute size rather than storing on _LRUNode.size
291
        self._value_size -= self._compute_size(node.value)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
292
        LRUCache._remove_node(self, node)
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
293
294
    def resize(self, max_size, after_cleanup_size=None):
295
        """Change the number of bytes that will be cached."""
296
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
297
        max_cache = max(int(max_size/512), 1)
298
        self._update_max_cache(max_cache)
299
300
    def _update_max_size(self, max_size, after_cleanup_size=None):
301
        self._max_size = max_size
302
        if after_cleanup_size is None:
303
            self._after_cleanup_size = self._max_size * 8 / 10
304
        else:
305
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)