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