/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/lru_cache.py

  • Committer: John Arbash Meinel
  • Date: 2008-12-08 18:23:00 UTC
  • mto: (3882.6.2 xml_cache)
  • mto: This revision was merged to the branch mainline in revision 3887.
  • Revision ID: john@arbash-meinel.com-20081208182300-u1qmnxafwt2rr5dz
Add LRUCache.resize(), and change the init arguments for LRUCache.

The old name was a bit confusing, and caused LRUSizeCache to re-use variables in
a confusing way with LRUCache.


Also, this changes the default cleanup size to be 80% of max_size. This should
be better, as it means we get a little bit of room when adding keys,
rather than having to cleanup after every add, we can instead do it in
batches.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""A simple least-recently-used (LRU) cache."""
 
18
 
 
19
from collections import deque
 
20
 
 
21
from bzrlib import symbol_versioning
 
22
 
 
23
 
 
24
class LRUCache(object):
 
25
    """A class which manages a cache of entries, removing unused ones."""
 
26
 
 
27
    def __init__(self, max_cache=100, after_cleanup_count=None,
 
28
                 after_cleanup_size=symbol_versioning.DEPRECATED_PARAMETER):
 
29
        if symbol_versioning.deprecated_passed(after_cleanup_size):
 
30
            symbol_versioning.warn('LRUCache.__init__(after_cleanup_size) was'
 
31
                                   ' deprecated in 1.11. Use'
 
32
                                   ' after_cleanup_count instead.',
 
33
                                   DeprecationWarning)
 
34
            after_cleanup_count = after_cleanup_size
 
35
        self._cache = {}
 
36
        self._cleanup = {}
 
37
        self._queue = deque() # Track when things are accessed
 
38
        self._refcount = {} # number of entries in self._queue for each key
 
39
        self._update_max_cache(max_cache, after_cleanup_count)
 
40
 
 
41
    def __contains__(self, key):
 
42
        return key in self._cache
 
43
 
 
44
    def __getitem__(self, key):
 
45
        val = self._cache[key]
 
46
        self._record_access(key)
 
47
        return val
 
48
 
 
49
    def __len__(self):
 
50
        return len(self._cache)
 
51
 
 
52
    def add(self, key, value, cleanup=None):
 
53
        """Add a new value to the cache.
 
54
 
 
55
        Also, if the entry is ever removed from the queue, call cleanup.
 
56
        Passing it the key and value being removed.
 
57
 
 
58
        :param key: The key to store it under
 
59
        :param value: The object to store
 
60
        :param cleanup: None or a function taking (key, value) to indicate
 
61
                        'value' sohuld be cleaned up.
 
62
        """
 
63
        if key in self._cache:
 
64
            self._remove(key)
 
65
        self._cache[key] = value
 
66
        self._cleanup[key] = cleanup
 
67
        self._record_access(key)
 
68
 
 
69
        if len(self._cache) > self._max_cache:
 
70
            # Trigger the cleanup
 
71
            self.cleanup()
 
72
 
 
73
    def get(self, key, default=None):
 
74
        if key in self._cache:
 
75
            return self[key]
 
76
        return default
 
77
 
 
78
    def keys(self):
 
79
        """Get the list of keys currently cached.
 
80
 
 
81
        Note that values returned here may not be available by the time you
 
82
        request them later. This is simply meant as a peak into the current
 
83
        state.
 
84
 
 
85
        :return: An unordered list of keys that are currently cached.
 
86
        """
 
87
        return self._cache.keys()
 
88
 
 
89
    def cleanup(self):
 
90
        """Clear the cache until it shrinks to the requested size.
 
91
 
 
92
        This does not completely wipe the cache, just makes sure it is under
 
93
        the after_cleanup_count.
 
94
        """
 
95
        # Make sure the cache is shrunk to the correct size
 
96
        while len(self._cache) > self._after_cleanup_count:
 
97
            self._remove_lru()
 
98
        # No need to compact the queue at this point, because the code that
 
99
        # calls this would have already triggered it based on queue length
 
100
 
 
101
    def __setitem__(self, key, value):
 
102
        """Add a value to the cache, there will be no cleanup function."""
 
103
        self.add(key, value, cleanup=None)
 
104
 
 
105
    def _record_access(self, key):
 
106
        """Record that key was accessed."""
 
107
        self._queue.append(key)
 
108
        # Can't use setdefault because you can't += 1 the result
 
109
        self._refcount[key] = self._refcount.get(key, 0) + 1
 
110
 
 
111
        # If our access queue is too large, clean it up too
 
112
        if len(self._queue) > self._compact_queue_length:
 
113
            self._compact_queue()
 
114
 
 
115
    def _compact_queue(self):
 
116
        """Compact the queue, leaving things in sorted last appended order."""
 
117
        new_queue = deque()
 
118
        for item in self._queue:
 
119
            if self._refcount[item] == 1:
 
120
                new_queue.append(item)
 
121
            else:
 
122
                self._refcount[item] -= 1
 
123
        self._queue = new_queue
 
124
        # All entries should be of the same size. There should be one entry in
 
125
        # queue for each entry in cache, and all refcounts should == 1
 
126
        if not (len(self._queue) == len(self._cache) ==
 
127
                len(self._refcount) == sum(self._refcount.itervalues())):
 
128
            raise AssertionError()
 
129
 
 
130
    def _remove(self, key):
 
131
        """Remove an entry, making sure to maintain the invariants."""
 
132
        cleanup = self._cleanup.pop(key)
 
133
        val = self._cache.pop(key)
 
134
        if cleanup is not None:
 
135
            cleanup(key, val)
 
136
        return val
 
137
 
 
138
    def _remove_lru(self):
 
139
        """Remove one entry from the lru, and handle consequences.
 
140
 
 
141
        If there are no more references to the lru, then this entry should be
 
142
        removed from the cache.
 
143
        """
 
144
        key = self._queue.popleft()
 
145
        self._refcount[key] -= 1
 
146
        if not self._refcount[key]:
 
147
            del self._refcount[key]
 
148
            self._remove(key)
 
149
 
 
150
    def clear(self):
 
151
        """Clear out all of the cache."""
 
152
        # Clean up in LRU order
 
153
        while self._cache:
 
154
            self._remove_lru()
 
155
 
 
156
    def resize(self, max_cache, after_cleanup_count=None):
 
157
        """Change the number of entries that will be cached."""
 
158
        self._update_max_cache(max_cache,
 
159
                               after_cleanup_count=after_cleanup_count)
 
160
 
 
161
    def _update_max_cache(self, max_cache, after_cleanup_count=None):
 
162
        self._max_cache = max_cache
 
163
        if after_cleanup_count is None:
 
164
            self._after_cleanup_count = self._max_cache * 8 / 10
 
165
        else:
 
166
            self._after_cleanup_count = min(after_cleanup_count, self._max_cache)
 
167
 
 
168
        self._compact_queue_length = 4*self._max_cache
 
169
        if len(self._queue) > self._compact_queue_length:
 
170
            self._compact_queue()
 
171
        self.cleanup()
 
172
 
 
173
 
 
174
class LRUSizeCache(LRUCache):
 
175
    """An LRUCache that removes things based on the size of the values.
 
176
 
 
177
    This differs in that it doesn't care how many actual items there are,
 
178
    it just restricts the cache to be cleaned up after so much data is stored.
 
179
 
 
180
    The values that are added must support len(value).
 
181
    """
 
182
 
 
183
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
 
184
                 compute_size=None):
 
185
        """Create a new LRUSizeCache.
 
186
 
 
187
        :param max_size: The max number of bytes to store before we start
 
188
            clearing out entries.
 
189
        :param after_cleanup_size: After cleaning up, shrink everything to this
 
190
            size.
 
191
        :param compute_size: A function to compute the size of the values. We
 
192
            use a function here, so that you can pass 'len' if you are just
 
193
            using simple strings, or a more complex function if you are using
 
194
            something like a list of strings, or even a custom object.
 
195
            The function should take the form "compute_size(value) => integer".
 
196
            If not supplied, it defaults to 'len()'
 
197
        """
 
198
        self._value_size = 0
 
199
        self._compute_size = compute_size
 
200
        if compute_size is None:
 
201
            self._compute_size = len
 
202
        # This approximates that texts are > 0.5k in size. It only really
 
203
        # effects when we clean up the queue, so we don't want it to be too
 
204
        # large.
 
205
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
 
206
        LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
 
207
 
 
208
    def add(self, key, value, cleanup=None):
 
209
        """Add a new value to the cache.
 
210
 
 
211
        Also, if the entry is ever removed from the queue, call cleanup.
 
212
        Passing it the key and value being removed.
 
213
 
 
214
        :param key: The key to store it under
 
215
        :param value: The object to store
 
216
        :param cleanup: None or a function taking (key, value) to indicate
 
217
                        'value' sohuld be cleaned up.
 
218
        """
 
219
        if key in self._cache:
 
220
            self._remove(key)
 
221
        value_len = self._compute_size(value)
 
222
        if value_len >= self._after_cleanup_size:
 
223
            return
 
224
        self._value_size += value_len
 
225
        self._cache[key] = value
 
226
        self._cleanup[key] = cleanup
 
227
        self._record_access(key)
 
228
 
 
229
        if self._value_size > self._max_size:
 
230
            # Time to cleanup
 
231
            self.cleanup()
 
232
 
 
233
    def cleanup(self):
 
234
        """Clear the cache until it shrinks to the requested size.
 
235
 
 
236
        This does not completely wipe the cache, just makes sure it is under
 
237
        the after_cleanup_size.
 
238
        """
 
239
        # Make sure the cache is shrunk to the correct size
 
240
        while self._value_size > self._after_cleanup_size:
 
241
            self._remove_lru()
 
242
 
 
243
    def _remove(self, key):
 
244
        """Remove an entry, making sure to maintain the invariants."""
 
245
        val = LRUCache._remove(self, key)
 
246
        self._value_size -= self._compute_size(val)
 
247
 
 
248
    def resize(self, max_size, after_cleanup_size=None):
 
249
        """Change the number of bytes that will be cached."""
 
250
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
 
251
        max_cache = max(int(max_size/512), 1)
 
252
        self._update_max_cache(max_cache)
 
253
 
 
254
    def _update_max_size(self, max_size, after_cleanup_size=None):
 
255
        self._max_size = max_size
 
256
        if after_cleanup_size is None:
 
257
            self._after_cleanup_size = self._max_size * 8 / 10
 
258
        else:
 
259
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)