/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
1
# Copyright (C) 2007 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
"""Indexing facilities."""
18
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
19
__all__ = [
20
    'CombinedGraphIndex',
21
    'GraphIndex',
22
    'GraphIndexBuilder',
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
23
    'GraphIndexPrefixAdapter',
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
24
    'InMemoryGraphIndex',
25
    ]
2592.1.32 by Robert Collins
Add __all__ to index.
26
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
27
from bisect import bisect_right
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
28
from cStringIO import StringIO
2592.1.12 by Robert Collins
Handle basic node adds.
29
import re
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
30
import sys
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
31
2624.2.15 by Robert Collins
Add useful -Dindex flag.
32
from bzrlib.lazy_import import lazy_import
33
lazy_import(globals(), """
2745.1.2 by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly.
34
from bzrlib import trace
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
35
from bzrlib.bisect_multi import bisect_multi_bytes
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
36
from bzrlib.revision import NULL_REVISION
2745.1.2 by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly.
37
from bzrlib.trace import mutter
2624.2.15 by Robert Collins
Add useful -Dindex flag.
38
""")
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
39
from bzrlib import (
40
    debug,
41
    errors,
42
    symbol_versioning,
43
    )
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
44
2979.1.1 by Robert Collins
Use the GraphIndex header to answer key_count queries rather than parsing the entire index unnecessarily.
45
_HEADER_READV = (0, 200)
2624.2.8 by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files.
46
_OPTION_KEY_ELEMENTS = "key_elements="
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
47
_OPTION_LEN = "len="
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
48
_OPTION_NODE_REFS = "node_ref_lists="
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
49
_SIGNATURE = "Bazaar Graph Index 1\n"
50
51
2592.1.14 by Robert Collins
Detect bad reference key values.
52
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]')
2592.1.12 by Robert Collins
Handle basic node adds.
53
_newline_null_re = re.compile('[\n\0]')
54
55
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
56
class GraphIndexBuilder(object):
2592.1.18 by Robert Collins
Add space to mark absent nodes.
57
    """A builder that can build a GraphIndex.
58
    
59
    The resulting graph has the structure:
60
    
61
    _SIGNATURE OPTIONS NODES NEWLINE
62
    _SIGNATURE     := 'Bazaar Graph Index 1' NEWLINE
63
    OPTIONS        := 'node_ref_lists=' DIGITS NEWLINE
64
    NODES          := NODE*
65
    NODE           := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
66
    KEY            := Not-whitespace-utf8
67
    ABSENT         := 'a'
2592.1.19 by Robert Collins
Node references are tab separated.
68
    REFERENCES     := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
69
    REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
70
    REFERENCE      := DIGITS  ; digits is the byte offset in the index of the
71
                              ; referenced key.
2592.1.18 by Robert Collins
Add space to mark absent nodes.
72
    VALUE          := no-newline-no-null-bytes
73
    """
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
74
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
75
    def __init__(self, reference_lists=0, key_elements=1):
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
76
        """Create a GraphIndex builder.
77
78
        :param reference_lists: The number of node references lists for each
79
            entry.
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
80
        :param key_elements: The number of bytestrings in each key.
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
81
        """
82
        self.reference_lists = reference_lists
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
83
        self._keys = set()
3644.2.1 by John Arbash Meinel
Change the IndexBuilders to not generate the nodes_by_key unless needed.
84
        # A dict of {key: (absent, ref_lists, value)}
2592.1.15 by Robert Collins
Detect duplicate key insertion.
85
        self._nodes = {}
3644.2.1 by John Arbash Meinel
Change the IndexBuilders to not generate the nodes_by_key unless needed.
86
        self._nodes_by_key = None
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
87
        self._key_length = key_elements
3777.5.3 by John Arbash Meinel
Add Builder.set_optimize(for_size=True) for GraphIndexBuilder and BTreeBuilder.
88
        self._optimize_for_size = False
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
89
90
    def _check_key(self, key):
91
        """Raise BadIndexKey if key is not a valid key for this index."""
92
        if type(key) != tuple:
93
            raise errors.BadIndexKey(key)
94
        if self._key_length != len(key):
95
            raise errors.BadIndexKey(key)
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
96
        for element in key:
97
            if not element or _whitespace_re.search(element) is not None:
98
                raise errors.BadIndexKey(element)
2592.1.12 by Robert Collins
Handle basic node adds.
99
3644.2.4 by John Arbash Meinel
Change GraphIndex to also have a _get_nodes_by_key
100
    def _get_nodes_by_key(self):
101
        if self._nodes_by_key is None:
102
            nodes_by_key = {}
103
            if self.reference_lists:
104
                for key, (absent, references, value) in self._nodes.iteritems():
105
                    if absent:
106
                        continue
107
                    key_dict = nodes_by_key
108
                    for subkey in key[:-1]:
109
                        key_dict = key_dict.setdefault(subkey, {})
110
                    key_dict[key[-1]] = key, value, references
111
            else:
112
                for key, (absent, references, value) in self._nodes.iteritems():
113
                    if absent:
114
                        continue
115
                    key_dict = nodes_by_key
116
                    for subkey in key[:-1]:
117
                        key_dict = key_dict.setdefault(subkey, {})
118
                    key_dict[key[-1]] = key, value
119
            self._nodes_by_key = nodes_by_key
120
        return self._nodes_by_key
121
3644.2.3 by John Arbash Meinel
Do a bit more work to get all the tests to pass.
122
    def _update_nodes_by_key(self, key, value, node_refs):
123
        """Update the _nodes_by_key dict with a new key.
124
125
        For a key of (foo, bar, baz) create
126
        _nodes_by_key[foo][bar][baz] = key_value
127
        """
128
        if self._nodes_by_key is None:
129
            return
130
        key_dict = self._nodes_by_key
131
        if self.reference_lists:
132
            key_value = key, value, node_refs
133
        else:
134
            key_value = key, value
135
        for subkey in key[:-1]:
136
            key_dict = key_dict.setdefault(subkey, {})
137
        key_dict[key[-1]] = key_value
138
3644.2.9 by John Arbash Meinel
Refactor some code.
139
    def _check_key_ref_value(self, key, references, value):
140
        """Check that 'key' and 'references' are all valid.
2592.1.12 by Robert Collins
Handle basic node adds.
141
3644.2.9 by John Arbash Meinel
Refactor some code.
142
        :param key: A key tuple. Must conform to the key interface (be a tuple,
143
            be of the right length, not have any whitespace or nulls in any key
144
            element.)
145
        :param references: An iterable of reference lists. Something like
146
            [[(ref, key)], [(ref, key), (other, key)]]
147
        :param value: The value associate with this key. Must not contain
148
            newlines or null characters.
149
        :return: (node_refs, absent_references)
150
            node_refs   basically a packed form of 'references' where all
151
                        iterables are tuples
152
            absent_references   reference keys that are not in self._nodes.
153
                                This may contain duplicates if the same key is
154
                                referenced in multiple lists.
2592.1.12 by Robert Collins
Handle basic node adds.
155
        """
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
156
        self._check_key(key)
2592.1.12 by Robert Collins
Handle basic node adds.
157
        if _newline_null_re.search(value) is not None:
158
            raise errors.BadIndexValue(value)
2592.1.13 by Robert Collins
Handle mismatched numbers of reference lists.
159
        if len(references) != self.reference_lists:
160
            raise errors.BadIndexValue(references)
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
161
        node_refs = []
3644.2.9 by John Arbash Meinel
Refactor some code.
162
        absent_references = []
2592.1.14 by Robert Collins
Detect bad reference key values.
163
        for reference_list in references:
164
            for reference in reference_list:
3644.2.9 by John Arbash Meinel
Refactor some code.
165
                # If reference *is* in self._nodes, then we know it has already
166
                # been checked.
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
167
                if reference not in self._nodes:
3644.2.9 by John Arbash Meinel
Refactor some code.
168
                    self._check_key(reference)
169
                    absent_references.append(reference)
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
170
            node_refs.append(tuple(reference_list))
3644.2.9 by John Arbash Meinel
Refactor some code.
171
        return tuple(node_refs), absent_references
172
173
    def add_node(self, key, value, references=()):
174
        """Add a node to the index.
175
176
        :param key: The key. keys are non-empty tuples containing
177
            as many whitespace-free utf8 bytestrings as the key length
178
            defined for this index.
179
        :param references: An iterable of iterables of keys. Each is a
180
            reference to another key.
181
        :param value: The value to associate with the key. It may be any
182
            bytes as long as it does not contain \0 or \n.
183
        """
184
        (node_refs,
185
         absent_references) = self._check_key_ref_value(key, references, value)
186
        if key in self._nodes and self._nodes[key][0] != 'a':
2592.1.15 by Robert Collins
Detect duplicate key insertion.
187
            raise errors.BadIndexDuplicateKey(key, self)
3644.2.9 by John Arbash Meinel
Refactor some code.
188
        for reference in absent_references:
189
            # There may be duplicates, but I don't think it is worth worrying
190
            # about
191
            self._nodes[reference] = ('a', (), '')
3644.2.3 by John Arbash Meinel
Do a bit more work to get all the tests to pass.
192
        self._nodes[key] = ('', node_refs, value)
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
193
        self._keys.add(key)
3644.2.9 by John Arbash Meinel
Refactor some code.
194
        if self._nodes_by_key is not None and self._key_length > 1:
3644.2.3 by John Arbash Meinel
Do a bit more work to get all the tests to pass.
195
            self._update_nodes_by_key(key, value, node_refs)
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
196
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
197
    def finish(self):
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
198
        lines = [_SIGNATURE]
199
        lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
2624.2.8 by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files.
200
        lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
201
        lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
2624.2.11 by Robert Collins
Review comments.
202
        prefix_length = sum(len(x) for x in lines)
2592.1.22 by Robert Collins
Node references are byte offsets.
203
        # references are byte offsets. To avoid having to do nasty
3644.2.9 by John Arbash Meinel
Refactor some code.
204
        # polynomial work to resolve offsets (references to later in the
2592.1.22 by Robert Collins
Node references are byte offsets.
205
        # file cannot be determined until all the inbetween references have
206
        # been calculated too) we pad the offsets with 0's to make them be
207
        # of consistent length. Using binary offsets would break the trivial
208
        # file parsing.
209
        # to calculate the width of zero's needed we do three passes:
210
        # one to gather all the non-reference data and the number of references.
211
        # one to pad all the data with reference-length and determine entry
212
        # addresses.
213
        # One to serialise.
2592.1.40 by Robert Collins
Reverse index ordering - we do not have date prefixed revids.
214
        
215
        # forward sorted by key. In future we may consider topological sorting,
216
        # at the cost of table scans for direct lookup, or a second index for
217
        # direct lookup
218
        nodes = sorted(self._nodes.items())
2592.1.42 by Robert Collins
Check the index length is as expected, when we have done preprocessing.
219
        # if we do not prepass, we don't know how long it will be up front.
220
        expected_bytes = None
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
221
        # we only need to pre-pass if we have reference lists at all.
222
        if self.reference_lists:
2592.1.41 by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion.
223
            key_offset_info = []
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
224
            non_ref_bytes = prefix_length
225
            total_references = 0
226
            # TODO use simple multiplication for the constants in this loop.
227
            for key, (absent, references, value) in nodes:
2592.1.41 by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion.
228
                # record the offset known *so far* for this key:
229
                # the non reference bytes to date, and the total references to
230
                # date - saves reaccumulating on the second pass
231
                key_offset_info.append((key, non_ref_bytes, total_references))
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
232
                # key is literal, value is literal, there are 3 null's, 1 NL
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
233
                # key is variable length tuple, \x00 between elements
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
234
                non_ref_bytes += sum(len(element) for element in key)
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
235
                if self._key_length > 1:
236
                    non_ref_bytes += self._key_length - 1
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
237
                # value is literal bytes, there are 3 null's, 1 NL.
238
                non_ref_bytes += len(value) + 3 + 1
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
239
                # one byte for absent if set.
240
                if absent:
241
                    non_ref_bytes += 1
2592.1.36 by Robert Collins
Bugfix incorrect offset generation when an absent record is before a referenced record.
242
                elif self.reference_lists:
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
243
                    # (ref_lists -1) tabs
244
                    non_ref_bytes += self.reference_lists - 1
245
                    # (ref-1 cr's per ref_list)
246
                    for ref_list in references:
247
                        # how many references across the whole file?
248
                        total_references += len(ref_list)
249
                        # accrue reference separators
250
                        if ref_list:
251
                            non_ref_bytes += len(ref_list) - 1
252
            # how many digits are needed to represent the total byte count?
253
            digits = 1
2592.1.22 by Robert Collins
Node references are byte offsets.
254
            possible_total_bytes = non_ref_bytes + total_references*digits
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
255
            while 10 ** digits < possible_total_bytes:
256
                digits += 1
257
                possible_total_bytes = non_ref_bytes + total_references*digits
2592.1.42 by Robert Collins
Check the index length is as expected, when we have done preprocessing.
258
            expected_bytes = possible_total_bytes + 1 # terminating newline
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
259
            # resolve key addresses.
260
            key_addresses = {}
2592.1.41 by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion.
261
            for key, non_ref_bytes, total_references in key_offset_info:
262
                key_addresses[key] = non_ref_bytes + total_references*digits
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
263
            # serialise
264
            format_string = '%%0%sd' % digits
265
        for key, (absent, references, value) in nodes:
2592.1.19 by Robert Collins
Node references are tab separated.
266
            flattened_references = []
267
            for ref_list in references:
2592.1.22 by Robert Collins
Node references are byte offsets.
268
                ref_addresses = []
269
                for reference in ref_list:
270
                    ref_addresses.append(format_string % key_addresses[reference])
271
                flattened_references.append('\r'.join(ref_addresses))
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
272
            string_key = '\x00'.join(key)
2624.2.11 by Robert Collins
Review comments.
273
            lines.append("%s\x00%s\x00%s\x00%s\n" % (string_key, absent,
2592.1.19 by Robert Collins
Node references are tab separated.
274
                '\t'.join(flattened_references), value))
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
275
        lines.append('\n')
2592.1.42 by Robert Collins
Check the index length is as expected, when we have done preprocessing.
276
        result = StringIO(''.join(lines))
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
277
        if expected_bytes and len(result.getvalue()) != expected_bytes:
278
            raise errors.BzrError('Failed index creation. Internal error:'
279
                ' mismatched output length and expected length: %d %d' %
280
                (len(result.getvalue()), expected_bytes))
3498.1.1 by James Westby
Don't join the lines of the index twice.
281
        return result
2592.1.5 by Robert Collins
Trivial index reading.
282
3777.5.3 by John Arbash Meinel
Add Builder.set_optimize(for_size=True) for GraphIndexBuilder and BTreeBuilder.
283
    def set_optimize(self, for_size=True):
284
        """Change how the builder tries to optimize the result.
285
286
        :param for_size: Tell the builder to try and make the index as small as
287
            possible.
288
        :return: None
289
        """
290
        # GraphIndexBuilder itself doesn't pay attention to the flag yet, but
291
        # other builders do.
292
        self._optimize_for_size = for_size
293
2592.1.5 by Robert Collins
Trivial index reading.
294
295
class GraphIndex(object):
296
    """An index for data with embedded graphs.
2592.1.10 by Robert Collins
Make validate detect node reference parsing errors.
297
 
298
    The index maps keys to a list of key reference lists, and a value.
299
    Each node has the same number of key reference lists. Each key reference
300
    list can be empty or an arbitrary length. The value is an opaque NULL
2592.1.45 by Robert Collins
Tweak documentation as per Aaron's review.
301
    terminated string without any newlines. The storage of the index is 
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
302
    hidden in the interface: keys and key references are always tuples of
303
    bytestrings, never the internal representation (e.g. dictionary offsets).
2592.1.30 by Robert Collins
Absent entries are not yeilded.
304
305
    It is presumed that the index will not be mutated - it is static data.
2592.1.34 by Robert Collins
Cleanup docs.
306
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
307
    Successive iter_all_entries calls will read the entire index each time.
308
    Additionally, iter_entries calls will read the index linearly until the
309
    desired keys are found. XXX: This must be fixed before the index is
2592.1.34 by Robert Collins
Cleanup docs.
310
    suitable for production use. :XXX
2592.1.5 by Robert Collins
Trivial index reading.
311
    """
312
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
313
    def __init__(self, transport, name, size):
2592.1.5 by Robert Collins
Trivial index reading.
314
        """Open an index called name on transport.
315
316
        :param transport: A bzrlib.transport.Transport.
317
        :param name: A path to provide to transport API calls.
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
318
        :param size: The size of the index in bytes. This is used for bisection
319
            logic to perform partial index reads. While the size could be
320
            obtained by statting the file this introduced an additional round
2890.2.8 by Robert Collins
Make the size of the index optionally None for the pack-names index.
321
            trip as well as requiring stat'able transports, both of which are
322
            avoided by having it supplied. If size is None, then bisection
323
            support will be disabled and accessing the index will just stream
324
            all the data.
2592.1.5 by Robert Collins
Trivial index reading.
325
        """
326
        self._transport = transport
327
        self._name = name
2890.2.16 by Robert Collins
Review feedback.
328
        # Becomes a dict of key:(value, reference-list-byte-locations) used by
329
        # the bisection interface to store parsed but not resolved keys.
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
330
        self._bisect_nodes = None
2890.2.16 by Robert Collins
Review feedback.
331
        # Becomes a dict of key:(value, reference-list-keys) which are ready to
332
        # be returned directly to callers.
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
333
        self._nodes = None
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
334
        # a sorted list of slice-addresses for the parsed bytes of the file.
335
        # e.g. (0,1) would mean that byte 0 is parsed.
2890.2.2 by Robert Collins
Opening an index creates a map for the parsed bytes.
336
        self._parsed_byte_map = []
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
337
        # a sorted list of keys matching each slice address for parsed bytes
338
        # e.g. (None, 'foo@bar') would mean that the first byte contained no
339
        # key, and the end byte of the slice is the of the data for 'foo@bar'
340
        self._parsed_key_map = []
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
341
        self._key_count = None
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
342
        self._keys_by_offset = None
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
343
        self._nodes_by_key = None
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
344
        self._size = size
3665.3.3 by John Arbash Meinel
If we read more than 50% of the whole index,
345
        # The number of bytes we've read so far in trying to process this file
346
        self._bytes_read = 0
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
347
2592.3.176 by Robert Collins
Various pack refactorings.
348
    def __eq__(self, other):
2592.3.215 by Robert Collins
Review feedback.
349
        """Equal when self and other were created with the same parameters."""
2592.3.176 by Robert Collins
Various pack refactorings.
350
        return (
351
            type(self) == type(other) and
352
            self._transport == other._transport and
353
            self._name == other._name and
354
            self._size == other._size)
355
356
    def __ne__(self, other):
357
        return not self.__eq__(other)
358
3517.4.13 by Martin Pool
Add repr methods
359
    def __repr__(self):
360
        return "%s(%r)" % (self.__class__.__name__,
361
            self._transport.abspath(self._name))
362
3665.3.1 by John Arbash Meinel
Updates to GraphIndex processing.
363
    def _buffer_all(self, stream=None):
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
364
        """Buffer all the index data.
365
366
        Mutates self._nodes and self.keys_by_offset.
2592.1.5 by Robert Collins
Trivial index reading.
367
        """
3665.3.1 by John Arbash Meinel
Updates to GraphIndex processing.
368
        if self._nodes is not None:
369
            # We already did this
370
            return
2624.2.15 by Robert Collins
Add useful -Dindex flag.
371
        if 'index' in debug.debug_flags:
372
            mutter('Reading entire index %s', self._transport.abspath(self._name))
3665.3.1 by John Arbash Meinel
Updates to GraphIndex processing.
373
        if stream is None:
374
            stream = self._transport.get(self._name)
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
375
        self._read_prefix(stream)
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
376
        self._expected_elements = 3 + self._key_length
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
377
        line_count = 0
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
378
        # raw data keyed by offset
379
        self._keys_by_offset = {}
380
        # ready-to-return key:value or key:value, node_ref_lists
381
        self._nodes = {}
3711.3.13 by John Arbash Meinel
Shave off another 5s by not building 'node_by_key'
382
        self._nodes_by_key = None
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
383
        trailers = 0
384
        pos = stream.tell()
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
385
        lines = stream.read().split('\n')
386
        del lines[-1]
387
        _, _, _, trailers = self._parse_lines(lines, pos)
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
388
        for key, absent, references, value in self._keys_by_offset.itervalues():
2592.1.30 by Robert Collins
Absent entries are not yeilded.
389
            if absent:
390
                continue
2592.1.28 by Robert Collins
Basic two pass iter_all_entries.
391
            # resolve references:
392
            if self.node_ref_lists:
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
393
                node_value = (value, self._resolve_references(references))
2592.1.28 by Robert Collins
Basic two pass iter_all_entries.
394
            else:
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
395
                node_value = value
396
            self._nodes[key] = node_value
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
397
        # cache the keys for quick set intersections
2592.3.54 by Robert Collins
Fix remaining performance discrepancy with regular repositories.
398
        self._keys = set(self._nodes)
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
399
        if trailers != 1:
400
            # there must be one line - the empty trailer line.
401
            raise errors.BadIndexData(self)
402
3711.3.21 by John Arbash Meinel
Fix GraphIndex to properly generate _nodes_by_keys on demand.
403
    def _get_nodes_by_key(self):
404
        if self._nodes_by_key is None:
405
            nodes_by_key = {}
406
            if self.node_ref_lists:
407
                for key, (value, references) in self._nodes.iteritems():
408
                    key_dict = nodes_by_key
409
                    for subkey in key[:-1]:
410
                        key_dict = key_dict.setdefault(subkey, {})
411
                    key_dict[key[-1]] = key, value, references
412
            else:
413
                for key, value in self._nodes.iteritems():
414
                    key_dict = nodes_by_key
415
                    for subkey in key[:-1]:
416
                        key_dict = key_dict.setdefault(subkey, {})
417
                    key_dict[key[-1]] = key, value
418
            self._nodes_by_key = nodes_by_key
419
        return self._nodes_by_key
420
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
421
    def iter_all_entries(self):
422
        """Iterate over all keys within the index.
423
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
424
        :return: An iterable of (index, key, value) or (index, key, value, reference_lists).
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
425
            The former tuple is used when there are no reference lists in the
426
            index, making the API compatible with simple key:value index types.
427
            There is no defined order for the result iteration - it will be in
428
            the most efficient order for the index.
429
        """
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
430
        if 'evil' in debug.debug_flags:
2592.3.112 by Robert Collins
Various fixups found dogfooding.
431
            trace.mutter_callsite(3,
2745.1.2 by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly.
432
                "iter_all_entries scales with size of history.")
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
433
        if self._nodes is None:
434
            self._buffer_all()
435
        if self.node_ref_lists:
436
            for key, (value, node_ref_lists) in self._nodes.iteritems():
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
437
                yield self, key, value, node_ref_lists
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
438
        else:
439
            for key, value in self._nodes.iteritems():
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
440
                yield self, key, value
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
441
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
442
    def _read_prefix(self, stream):
443
        signature = stream.read(len(self._signature()))
444
        if not signature == self._signature():
445
            raise errors.BadIndexFormatSignature(self._name, GraphIndex)
446
        options_line = stream.readline()
447
        if not options_line.startswith(_OPTION_NODE_REFS):
448
            raise errors.BadIndexOptions(self)
449
        try:
450
            self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1])
451
        except ValueError:
452
            raise errors.BadIndexOptions(self)
2624.2.8 by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files.
453
        options_line = stream.readline()
454
        if not options_line.startswith(_OPTION_KEY_ELEMENTS):
455
            raise errors.BadIndexOptions(self)
456
        try:
457
            self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):-1])
458
        except ValueError:
459
            raise errors.BadIndexOptions(self)
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
460
        options_line = stream.readline()
461
        if not options_line.startswith(_OPTION_LEN):
462
            raise errors.BadIndexOptions(self)
463
        try:
464
            self._key_count = int(options_line[len(_OPTION_LEN):-1])
465
        except ValueError:
466
            raise errors.BadIndexOptions(self)
2592.1.5 by Robert Collins
Trivial index reading.
467
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
468
    def _resolve_references(self, references):
2890.2.16 by Robert Collins
Review feedback.
469
        """Return the resolved key references for references.
470
        
471
        References are resolved by looking up the location of the key in the
472
        _keys_by_offset map and substituting the key name, preserving ordering.
473
474
        :param references: An iterable of iterables of key locations. e.g. 
475
            [[123, 456], [123]]
476
        :return: A tuple of tuples of keys.
477
        """
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
478
        node_refs = []
479
        for ref_list in references:
480
            node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
481
        return tuple(node_refs)
482
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
483
    def _find_index(self, range_map, key):
484
        """Helper for the _parsed_*_index calls.
485
486
        Given a range map - [(start, end), ...], finds the index of the range
487
        in the map for key if it is in the map, and if it is not there, the
488
        immediately preceeding range in the map.
489
        """
490
        result = bisect_right(range_map, key) - 1
491
        if result + 1 < len(range_map):
492
            # check the border condition, it may be in result + 1
493
            if range_map[result + 1][0] == key[0]:
494
                return result + 1
495
        return result
496
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
497
    def _parsed_byte_index(self, offset):
498
        """Return the index of the entry immediately before offset.
499
500
        e.g. if the parsed map has regions 0,10 and 11,12 parsed, meaning that
501
        there is one unparsed byte (the 11th, addressed as[10]). then:
502
        asking for 0 will return 0
503
        asking for 10 will return 0
504
        asking for 11 will return 1
505
        asking for 12 will return 1
506
        """
507
        key = (offset, 0)
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
508
        return self._find_index(self._parsed_byte_map, key)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
509
510
    def _parsed_key_index(self, key):
511
        """Return the index of the entry immediately before key.
512
513
        e.g. if the parsed map has regions (None, 'a') and ('b','c') parsed,
514
        meaning that keys from None to 'a' inclusive, and 'b' to 'c' inclusive
515
        have been parsed, then:
516
        asking for '' will return 0
517
        asking for 'a' will return 0
518
        asking for 'b' will return 1
519
        asking for 'e' will return 1
520
        """
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
521
        search_key = (key, None)
522
        return self._find_index(self._parsed_key_map, search_key)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
523
524
    def _is_parsed(self, offset):
525
        """Returns True if offset has been parsed."""
526
        index = self._parsed_byte_index(offset)
527
        if index == len(self._parsed_byte_map):
528
            return offset < self._parsed_byte_map[index - 1][1]
529
        start, end = self._parsed_byte_map[index]
530
        return offset >= start and offset < end
531
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
532
    def _iter_entries_from_total_buffer(self, keys):
533
        """Iterate over keys when the entire index is parsed."""
2592.3.54 by Robert Collins
Fix remaining performance discrepancy with regular repositories.
534
        keys = keys.intersection(self._keys)
2624.2.3 by Robert Collins
Make GraphIndex.iter_entries do hash lookups rather than table scans.
535
        if self.node_ref_lists:
536
            for key in keys:
537
                value, node_refs = self._nodes[key]
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
538
                yield self, key, value, node_refs
2624.2.3 by Robert Collins
Make GraphIndex.iter_entries do hash lookups rather than table scans.
539
        else:
540
            for key in keys:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
541
                yield self, key, self._nodes[key]
2592.1.7 by Robert Collins
A validate that goes boom.
542
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
543
    def iter_entries(self, keys):
544
        """Iterate over keys within the index.
545
546
        :param keys: An iterable providing the keys to be retrieved.
547
        :return: An iterable as per iter_all_entries, but restricted to the
548
            keys supplied. No additional keys will be returned, and every
549
            key supplied that is in the index will be returned.
550
        """
551
        keys = set(keys)
552
        if not keys:
553
            return []
2890.2.8 by Robert Collins
Make the size of the index optionally None for the pack-names index.
554
        if self._size is None and self._nodes is None:
555
            self._buffer_all()
3665.3.3 by John Arbash Meinel
If we read more than 50% of the whole index,
556
3606.6.1 by Robert Collins
Cherry-pick Robert's index buffering.
557
        # We fit about 20 keys per minimum-read (4K), so if we are looking for
558
        # more than 1/20th of the index its likely (assuming homogenous key
559
        # spread) that we'll read the entire index. If we're going to do that,
560
        # buffer the whole thing. A better analysis might take key spread into
561
        # account - but B+Tree indices are better anyway.
562
        # We could look at all data read, and use a threshold there, which will
563
        # trigger on ancestry walks, but that is not yet fully mapped out.
564
        if self._nodes is None and len(keys) * 20 > self.key_count():
565
            self._buffer_all()
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
566
        if self._nodes is not None:
567
            return self._iter_entries_from_total_buffer(keys)
568
        else:
569
            return (result[1] for result in bisect_multi_bytes(
2890.2.18 by Robert Collins
Review feedback.
570
                self._lookup_keys_via_location, self._size, keys))
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
571
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
572
    def iter_entries_prefix(self, keys):
573
        """Iterate over keys within the index using prefix matching.
574
575
        Prefix matching is applied within the tuple of a key, not to within
576
        the bytestring of each key element. e.g. if you have the keys ('foo',
577
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
578
        only the former key is returned.
579
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
580
        WARNING: Note that this method currently causes a full index parse
581
        unconditionally (which is reasonably appropriate as it is a means for
582
        thunking many small indices into one larger one and still supplies
583
        iter_all_entries at the thunk layer).
584
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
585
        :param keys: An iterable providing the key prefixes to be retrieved.
586
            Each key prefix takes the form of a tuple the length of a key, but
587
            with the last N elements 'None' rather than a regular bytestring.
588
            The first element cannot be 'None'.
589
        :return: An iterable as per iter_all_entries, but restricted to the
590
            keys with a matching prefix to those supplied. No additional keys
591
            will be returned, and every match that is in the index will be
592
            returned.
593
        """
594
        keys = set(keys)
595
        if not keys:
596
            return
597
        # load data - also finds key lengths
598
        if self._nodes is None:
599
            self._buffer_all()
600
        if self._key_length == 1:
601
            for key in keys:
602
                # sanity check
603
                if key[0] is None:
604
                    raise errors.BadIndexKey(key)
605
                if len(key) != self._key_length:
606
                    raise errors.BadIndexKey(key)
607
                if self.node_ref_lists:
608
                    value, node_refs = self._nodes[key]
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
609
                    yield self, key, value, node_refs
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
610
                else:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
611
                    yield self, key, self._nodes[key]
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
612
            return
3711.3.21 by John Arbash Meinel
Fix GraphIndex to properly generate _nodes_by_keys on demand.
613
        nodes_by_key = self._get_nodes_by_key()
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
614
        for key in keys:
615
            # sanity check
616
            if key[0] is None:
617
                raise errors.BadIndexKey(key)
618
            if len(key) != self._key_length:
619
                raise errors.BadIndexKey(key)
620
            # find what it refers to:
3711.3.21 by John Arbash Meinel
Fix GraphIndex to properly generate _nodes_by_keys on demand.
621
            key_dict = nodes_by_key
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
622
            elements = list(key)
2624.2.11 by Robert Collins
Review comments.
623
            # find the subdict whose contents should be returned.
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
624
            try:
625
                while len(elements) and elements[0] is not None:
626
                    key_dict = key_dict[elements[0]]
627
                    elements.pop(0)
628
            except KeyError:
629
                # a non-existant lookup.
630
                continue
631
            if len(elements):
632
                dicts = [key_dict]
633
                while dicts:
634
                    key_dict = dicts.pop(-1)
635
                    # can't be empty or would not exist
636
                    item, value = key_dict.iteritems().next()
637
                    if type(value) == dict:
638
                        # push keys 
639
                        dicts.extend(key_dict.itervalues())
640
                    else:
641
                        # yield keys
642
                        for value in key_dict.itervalues():
2624.2.11 by Robert Collins
Review comments.
643
                            # each value is the key:value:node refs tuple
644
                            # ready to yield.
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
645
                            yield (self, ) + value
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
646
            else:
2624.2.11 by Robert Collins
Review comments.
647
                # the last thing looked up was a terminal element
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
648
                yield (self, ) + key_dict
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
649
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
650
    def key_count(self):
651
        """Return an estimate of the number of keys in this index.
652
        
653
        For GraphIndex the estimate is exact.
654
        """
655
        if self._key_count is None:
2979.1.1 by Robert Collins
Use the GraphIndex header to answer key_count queries rather than parsing the entire index unnecessarily.
656
            self._read_and_parse([_HEADER_READV])
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
657
        return self._key_count
658
2890.2.18 by Robert Collins
Review feedback.
659
    def _lookup_keys_via_location(self, location_keys):
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
660
        """Public interface for implementing bisection.
661
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
662
        If _buffer_all has been called, then all the data for the index is in
663
        memory, and this method should not be called, as it uses a separate
664
        cache because it cannot pre-resolve all indices, which buffer_all does
665
        for performance.
666
2890.2.16 by Robert Collins
Review feedback.
667
        :param location_keys: A list of location(byte offset), key tuples.
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
668
        :return: A list of (location_key, result) tuples as expected by
669
            bzrlib.bisect_multi.bisect_multi_bytes.
670
        """
671
        # Possible improvements:
672
        #  - only bisect lookup each key once
673
        #  - sort the keys first, and use that to reduce the bisection window
674
        # ----- 
675
        # this progresses in three parts:
676
        # read data
677
        # parse it
678
        # attempt to answer the question from the now in memory data.
679
        # build the readv request
680
        # for each location, ask for 800 bytes - much more than rows we've seen
681
        # anywhere.
682
        readv_ranges = []
683
        for location, key in location_keys:
684
            # can we answer from cache?
2911.3.1 by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins).
685
            if self._bisect_nodes and key in self._bisect_nodes:
686
                # We have the key parsed.
687
                continue
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
688
            index = self._parsed_key_index(key)
689
            if (len(self._parsed_key_map) and 
690
                self._parsed_key_map[index][0] <= key and
2911.3.1 by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins).
691
                (self._parsed_key_map[index][1] >= key or
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
692
                 # end of the file has been parsed
693
                 self._parsed_byte_map[index][1] == self._size)):
2911.3.1 by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins).
694
                # the key has been parsed, so no lookup is needed even if its
695
                # not present.
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
696
                continue
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
697
            # - if we have examined this part of the file already - yes
698
            index = self._parsed_byte_index(location)
699
            if (len(self._parsed_byte_map) and 
700
                self._parsed_byte_map[index][0] <= location and
701
                self._parsed_byte_map[index][1] > location):
702
                # the byte region has been parsed, so no read is needed.
703
                continue
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
704
            length = 800
705
            if location + length > self._size:
706
                length = self._size - location
707
            # todo, trim out parsed locations.
708
            if length > 0:
709
                readv_ranges.append((location, length))
710
        # read the header if needed
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
711
        if self._bisect_nodes is None:
2979.1.1 by Robert Collins
Use the GraphIndex header to answer key_count queries rather than parsing the entire index unnecessarily.
712
            readv_ranges.append(_HEADER_READV)
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
713
        self._read_and_parse(readv_ranges)
3665.3.1 by John Arbash Meinel
Updates to GraphIndex processing.
714
        result = []
715
        if self._nodes is not None:
716
            # _read_and_parse triggered a _buffer_all because we requested the
717
            # whole data range
718
            for location, key in location_keys:
719
                if key not in self._nodes: # not present
720
                    result.append(((location, key), False))
721
                elif self.node_ref_lists:
722
                    value, refs = self._nodes[key]
723
                    result.append(((location, key),
724
                        (self, key, value, refs)))
725
                else:
726
                    result.append(((location, key),
727
                        (self, key, self._nodes[key])))
728
            return result
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
729
        # generate results:
730
        #  - figure out <, >, missing, present
731
        #  - result present references so we can return them.
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
732
        # keys that we cannot answer until we resolve references
733
        pending_references = []
734
        pending_locations = set()
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
735
        for location, key in location_keys:
736
            # can we answer from cache?
2911.3.1 by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins).
737
            if key in self._bisect_nodes:
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
738
                # the key has been parsed, so no lookup is needed
2911.3.1 by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins).
739
                if self.node_ref_lists:
740
                    # the references may not have been all parsed.
741
                    value, refs = self._bisect_nodes[key]
742
                    wanted_locations = []
743
                    for ref_list in refs:
744
                        for ref in ref_list:
745
                            if ref not in self._keys_by_offset:
746
                                wanted_locations.append(ref)
747
                    if wanted_locations:
748
                        pending_locations.update(wanted_locations)
749
                        pending_references.append((location, key))
750
                        continue
751
                    result.append(((location, key), (self, key,
752
                        value, self._resolve_references(refs))))
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
753
                else:
2911.3.1 by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins).
754
                    result.append(((location, key),
755
                        (self, key, self._bisect_nodes[key])))
756
                continue
757
            else:
758
                # has the region the key should be in, been parsed?
759
                index = self._parsed_key_index(key)
760
                if (self._parsed_key_map[index][0] <= key and
761
                    (self._parsed_key_map[index][1] >= key or
762
                     # end of the file has been parsed
763
                     self._parsed_byte_map[index][1] == self._size)):
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
764
                    result.append(((location, key), False))
2911.3.1 by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins).
765
                    continue
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
766
            # no, is the key above or below the probed location:
767
            # get the range of the probed & parsed location
768
            index = self._parsed_byte_index(location)
769
            # if the key is below the start of the range, its below
770
            if key < self._parsed_key_map[index][0]:
771
                direction = -1
772
            else:
773
                direction = +1
774
            result.append(((location, key), direction))
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
775
        readv_ranges = []
776
        # lookup data to resolve references
777
        for location in pending_locations:
778
            length = 800
779
            if location + length > self._size:
780
                length = self._size - location
781
            # TODO: trim out parsed locations (e.g. if the 800 is into the
2890.2.16 by Robert Collins
Review feedback.
782
            # parsed region trim it, and dont use the adjust_for_latency
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
783
            # facility)
784
            if length > 0:
785
                readv_ranges.append((location, length))
786
        self._read_and_parse(readv_ranges)
3665.3.5 by John Arbash Meinel
Move the point at which we 'buffer_all' if we've read >50% of the index.
787
        if self._nodes is not None:
788
            # The _read_and_parse triggered a _buffer_all, grab the data and
789
            # return it
790
            for location, key in pending_references:
791
                value, refs = self._nodes[key]
792
                result.append(((location, key), (self, key, value, refs)))
793
            return result
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
794
        for location, key in pending_references:
795
            # answer key references we had to look-up-late.
796
            value, refs = self._bisect_nodes[key]
797
            result.append(((location, key), (self, key,
798
                value, self._resolve_references(refs))))
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
799
        return result
800
801
    def _parse_header_from_bytes(self, bytes):
802
        """Parse the header from a region of bytes.
803
804
        :param bytes: The data to parse.
805
        :return: An offset, data tuple such as readv yields, for the unparsed
806
            data. (which may length 0).
807
        """
808
        signature = bytes[0:len(self._signature())]
809
        if not signature == self._signature():
810
            raise errors.BadIndexFormatSignature(self._name, GraphIndex)
811
        lines = bytes[len(self._signature()):].splitlines()
812
        options_line = lines[0]
813
        if not options_line.startswith(_OPTION_NODE_REFS):
814
            raise errors.BadIndexOptions(self)
815
        try:
816
            self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):])
817
        except ValueError:
818
            raise errors.BadIndexOptions(self)
819
        options_line = lines[1]
820
        if not options_line.startswith(_OPTION_KEY_ELEMENTS):
821
            raise errors.BadIndexOptions(self)
822
        try:
823
            self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):])
824
        except ValueError:
825
            raise errors.BadIndexOptions(self)
826
        options_line = lines[2]
827
        if not options_line.startswith(_OPTION_LEN):
828
            raise errors.BadIndexOptions(self)
829
        try:
830
            self._key_count = int(options_line[len(_OPTION_LEN):])
831
        except ValueError:
832
            raise errors.BadIndexOptions(self)
833
        # calculate the bytes we have processed
834
        header_end = (len(signature) + len(lines[0]) + len(lines[1]) +
835
            len(lines[2]) + 3)
836
        self._parsed_bytes(0, None, header_end, None)
837
        # setup parsing state
838
        self._expected_elements = 3 + self._key_length
839
        # raw data keyed by offset
840
        self._keys_by_offset = {}
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
841
        # keys with the value and node references
842
        self._bisect_nodes = {}
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
843
        return header_end, bytes[header_end:]
844
845
    def _parse_region(self, offset, data):
846
        """Parse node data returned from a readv operation.
847
848
        :param offset: The byte offset the data starts at.
849
        :param data: The data to parse.
850
        """
851
        # trim the data.
852
        # end first:
853
        end = offset + len(data)
2890.2.15 by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that.
854
        high_parsed = offset
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
855
        while True:
856
            # Trivial test - if the current index's end is within the
857
            # low-matching parsed range, we're done.
2890.2.15 by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that.
858
            index = self._parsed_byte_index(high_parsed)
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
859
            if end < self._parsed_byte_map[index][1]:
860
                return
2890.2.15 by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that.
861
            # print "[%d:%d]" % (offset, end), \
862
            #     self._parsed_byte_map[index:index + 2]
863
            high_parsed, last_segment = self._parse_segment(
864
                offset, data, end, index)
865
            if last_segment:
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
866
                return
867
868
    def _parse_segment(self, offset, data, end, index):
869
        """Parse one segment of data.
870
871
        :param offset: Where 'data' begins in the file.
872
        :param data: Some data to parse a segment of.
873
        :param end: Where data ends
874
        :param index: The current index into the parsed bytes map.
875
        :return: True if the parsed segment is the last possible one in the
876
            range of data.
2890.2.15 by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that.
877
        :return: high_parsed_byte, last_segment.
878
            high_parsed_byte is the location of the highest parsed byte in this
879
            segment, last_segment is True if the parsed segment is the last
880
            possible one in the data block.
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
881
        """
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
882
        # default is to use all data
883
        trim_end = None
884
        # accomodate overlap with data before this.
885
        if offset < self._parsed_byte_map[index][1]:
886
            # overlaps the lower parsed region
887
            # skip the parsed data
888
            trim_start = self._parsed_byte_map[index][1] - offset
889
            # don't trim the start for \n
890
            start_adjacent = True
891
        elif offset == self._parsed_byte_map[index][1]:
892
            # abuts the lower parsed region
893
            # use all data
894
            trim_start = None
895
            # do not trim anything
896
            start_adjacent = True
897
        else:
898
            # does not overlap the lower parsed region
899
            # use all data
900
            trim_start = None
901
            # but trim the leading \n
902
            start_adjacent = False
903
        if end == self._size:
904
            # lines up to the end of all data:
905
            # use it all
906
            trim_end = None
907
            # do not strip to the last \n
908
            end_adjacent = True
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
909
            last_segment = True
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
910
        elif index + 1 == len(self._parsed_byte_map):
911
            # at the end of the parsed data
912
            # use it all
913
            trim_end = None
914
            # but strip to the last \n
915
            end_adjacent = False
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
916
            last_segment = True
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
917
        elif end == self._parsed_byte_map[index + 1][0]:
918
            # buts up against the next parsed region
919
            # use it all
920
            trim_end = None
921
            # do not strip to the last \n
922
            end_adjacent = True
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
923
            last_segment = True
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
924
        elif end > self._parsed_byte_map[index + 1][0]:
925
            # overlaps into the next parsed region
926
            # only consider the unparsed data
927
            trim_end = self._parsed_byte_map[index + 1][0] - offset
928
            # do not strip to the last \n as we know its an entire record
929
            end_adjacent = True
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
930
            last_segment = end < self._parsed_byte_map[index + 1][1]
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
931
        else:
932
            # does not overlap into the next region
933
            # use it all
934
            trim_end = None
935
            # but strip to the last \n
936
            end_adjacent = False
2890.2.14 by Robert Collins
Parse more than one segment of data from a single readv response if needed.
937
            last_segment = True
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
938
        # now find bytes to discard if needed
939
        if not start_adjacent:
940
            # work around python bug in rfind
941
            if trim_start is None:
942
                trim_start = data.find('\n') + 1
943
            else:
944
                trim_start = data.find('\n', trim_start) + 1
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
945
            if not (trim_start != 0):
946
                raise AssertionError('no \n was present')
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
947
            # print 'removing start', offset, trim_start, repr(data[:trim_start])
948
        if not end_adjacent:
949
            # work around python bug in rfind
950
            if trim_end is None:
951
                trim_end = data.rfind('\n') + 1
952
            else:
953
                trim_end = data.rfind('\n', None, trim_end) + 1
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
954
            if not (trim_end != 0):
955
                raise AssertionError('no \n was present')
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
956
            # print 'removing end', offset, trim_end, repr(data[trim_end:])
957
        # adjust offset and data to the parseable data.
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
958
        trimmed_data = data[trim_start:trim_end]
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
959
        if not (trimmed_data):
960
            raise AssertionError('read unneeded data [%d:%d] from [%d:%d]' 
961
                % (trim_start, trim_end, offset, offset + len(data)))
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
962
        if trim_start:
963
            offset += trim_start
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
964
        # print "parsing", repr(trimmed_data)
2890.2.10 by Robert Collins
Add test coverage to ensure \r's are not mangled by bisection parsing.
965
        # splitlines mangles the \r delimiters.. don't use it.
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
966
        lines = trimmed_data.split('\n')
2890.2.9 by Robert Collins
Don't use splitlines for index data parsing, we embed \r.
967
        del lines[-1]
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
968
        pos = offset
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
969
        first_key, last_key, nodes, _ = self._parse_lines(lines, pos)
970
        for key, value in nodes:
971
            self._bisect_nodes[key] = value
972
        self._parsed_bytes(offset, first_key,
973
            offset + len(trimmed_data), last_key)
974
        return offset + len(trimmed_data), last_segment
975
976
    def _parse_lines(self, lines, pos):
977
        key = None
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
978
        first_key = None
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
979
        trailers = 0
980
        nodes = []
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
981
        for line in lines:
982
            if line == '':
983
                # must be at the end
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
984
                if self._size:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
985
                    if not (self._size == pos + 1):
986
                        raise AssertionError("%s %s" % (self._size, pos))
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
987
                trailers += 1
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
988
                continue
989
            elements = line.split('\0')
990
            if len(elements) != self._expected_elements:
991
                raise errors.BadIndexData(self)
3530.3.3 by Robert Collins
Credit and explanation for interning.
992
            # keys are tuples. Each element is a string that may occur many
993
            # times, so we intern them to save space. AB, RC, 200807
3711.3.13 by John Arbash Meinel
Shave off another 5s by not building 'node_by_key'
994
            key = tuple([intern(element) for element in elements[:self._key_length]])
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
995
            if first_key is None:
996
                first_key = key
997
            absent, references, value = elements[-3:]
998
            ref_lists = []
999
            for ref_string in references.split('\t'):
1000
                ref_lists.append(tuple([
1001
                    int(ref) for ref in ref_string.split('\r') if ref
1002
                    ]))
1003
            ref_lists = tuple(ref_lists)
1004
            self._keys_by_offset[pos] = (key, absent, ref_lists, value)
1005
            pos += len(line) + 1 # +1 for the \n
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
1006
            if absent:
1007
                continue
1008
            if self.node_ref_lists:
1009
                node_value = (value, ref_lists)
1010
            else:
1011
                node_value = value
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
1012
            nodes.append((key, node_value))
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
1013
            # print "parsed ", key
2890.2.17 by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing.
1014
        return first_key, key, nodes, trailers
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
1015
1016
    def _parsed_bytes(self, start, start_key, end, end_key):
1017
        """Mark the bytes from start to end as parsed.
1018
1019
        Calling self._parsed_bytes(1,2) will mark one byte (the one at offset
1020
        1) as parsed.
1021
1022
        :param start: The start of the parsed region.
1023
        :param end: The end of the parsed region.
1024
        """
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
1025
        index = self._parsed_byte_index(start)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
1026
        new_value = (start, end)
1027
        new_key = (start_key, end_key)
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
1028
        if index == -1:
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
1029
            # first range parsed is always the beginning.
1030
            self._parsed_byte_map.insert(index, new_value)
1031
            self._parsed_key_map.insert(index, new_key)
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
1032
            return
1033
        # four cases:
1034
        # new region
1035
        # extend lower region
1036
        # extend higher region
1037
        # combine two regions
1038
        if (index + 1 < len(self._parsed_byte_map) and
1039
            self._parsed_byte_map[index][1] == start and
1040
            self._parsed_byte_map[index + 1][0] == end):
1041
            # combine two regions
1042
            self._parsed_byte_map[index] = (self._parsed_byte_map[index][0],
1043
                self._parsed_byte_map[index + 1][1])
1044
            self._parsed_key_map[index] = (self._parsed_key_map[index][0],
1045
                self._parsed_key_map[index + 1][1])
2890.2.12 by Robert Collins
More index tweaks.
1046
            del self._parsed_byte_map[index + 1]
1047
            del self._parsed_key_map[index + 1]
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
1048
        elif self._parsed_byte_map[index][1] == start:
1049
            # extend the lower entry
1050
            self._parsed_byte_map[index] = (
1051
                self._parsed_byte_map[index][0], end)
1052
            self._parsed_key_map[index] = (
1053
                self._parsed_key_map[index][0], end_key)
1054
        elif (index + 1 < len(self._parsed_byte_map) and
1055
            self._parsed_byte_map[index + 1][0] == end):
1056
            # extend the higher entry
1057
            self._parsed_byte_map[index + 1] = (
1058
                start, self._parsed_byte_map[index + 1][1])
1059
            self._parsed_key_map[index + 1] = (
1060
                start_key, self._parsed_key_map[index + 1][1])
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
1061
        else:
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
1062
            # new entry
1063
            self._parsed_byte_map.insert(index + 1, new_value)
1064
            self._parsed_key_map.insert(index + 1, new_key)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
1065
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
1066
    def _read_and_parse(self, readv_ranges):
1067
        """Read the the ranges and parse the resulting data.
1068
1069
        :param readv_ranges: A prepared readv range list.
1070
        """
3665.3.5 by John Arbash Meinel
Move the point at which we 'buffer_all' if we've read >50% of the index.
1071
        if not readv_ranges:
1072
            return
1073
        if self._nodes is None and self._bytes_read * 2 >= self._size:
1074
            # We've already read more than 50% of the file and we are about to
1075
            # request more data, just _buffer_all() and be done
1076
            self._buffer_all()
1077
            return
1078
1079
        readv_data = self._transport.readv(self._name, readv_ranges, True,
1080
            self._size)
1081
        # parse
1082
        for offset, data in readv_data:
1083
            self._bytes_read += len(data)
1084
            if offset == 0 and len(data) == self._size:
1085
                # We read the whole range, most likely because the
1086
                # Transport upcast our readv ranges into one long request
1087
                # for enough total data to grab the whole index.
1088
                self._buffer_all(StringIO(data))
1089
                return
1090
            if self._bisect_nodes is None:
1091
                # this must be the start
1092
                if not (offset == 0):
1093
                    raise AssertionError()
1094
                offset, data = self._parse_header_from_bytes(data)
1095
            # print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1096
            self._parse_region(offset, data)
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
1097
2592.1.8 by Robert Collins
Empty files should validate ok.
1098
    def _signature(self):
1099
        """The file signature for this index type."""
1100
        return _SIGNATURE
1101
2592.1.7 by Robert Collins
A validate that goes boom.
1102
    def validate(self):
1103
        """Validate that everything in the index can be accessed."""
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
1104
        # iter_all validates completely at the moment, so just do that.
1105
        for node in self.iter_all_entries():
1106
            pass
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1107
1108
1109
class CombinedGraphIndex(object):
1110
    """A GraphIndex made up from smaller GraphIndices.
1111
    
1112
    The backing indices must implement GraphIndex, and are presumed to be
1113
    static data.
2592.1.45 by Robert Collins
Tweak documentation as per Aaron's review.
1114
1115
    Queries against the combined index will be made against the first index,
1116
    and then the second and so on. The order of index's can thus influence
1117
    performance significantly. For example, if one index is on local disk and a
1118
    second on a remote server, the local disk index should be before the other
1119
    in the index list.
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1120
    """
1121
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
1122
    def __init__(self, indices, reload_func=None):
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1123
        """Create a CombinedGraphIndex backed by indices.
1124
2592.1.45 by Robert Collins
Tweak documentation as per Aaron's review.
1125
        :param indices: An ordered list of indices to query for data.
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
1126
        :param reload_func: A function to call if we find we are missing an
1127
            index. Should have the form reload_func() => True/False to indicate
1128
            if reloading actually changed anything.
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1129
        """
1130
        self._indices = indices
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
1131
        self._reload_func = reload_func
2592.1.37 by Robert Collins
Add CombinedGraphIndex.insert_index.
1132
2592.5.4 by Martin Pool
Add CombinedGraphIndex repr
1133
    def __repr__(self):
1134
        return "%s(%s)" % (
1135
                self.__class__.__name__,
1136
                ', '.join(map(repr, self._indices)))
1137
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
1138
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
1139
    def get_parents(self, revision_ids):
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1140
        """See graph._StackedParentsProvider.get_parents.
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
1141
        
1142
        This implementation thunks the graph.Graph.get_parents api across to
1143
        GraphIndex.
1144
1145
        :param revision_ids: An iterable of graph keys for this graph.
1146
        :return: A list of parent details for each key in revision_ids.
1147
            Each parent details will be one of:
1148
             * None when the key was missing
1149
             * (NULL_REVISION,) when the key has no parents.
1150
             * (parent_key, parent_key...) otherwise.
1151
        """
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1152
        parent_map = self.get_parent_map(revision_ids)
1153
        return [parent_map.get(r, None) for r in revision_ids]
1154
1155
    def get_parent_map(self, keys):
1156
        """See graph._StackedParentsProvider.get_parent_map"""
1157
        search_keys = set(keys)
1158
        if NULL_REVISION in search_keys:
1159
            search_keys.discard(NULL_REVISION)
1160
            found_parents = {NULL_REVISION:[]}
1161
        else:
1162
            found_parents = {}
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
1163
        for index, key, value, refs in self.iter_entries(search_keys):
1164
            parents = refs[0]
1165
            if not parents:
1166
                parents = (NULL_REVISION,)
1167
            found_parents[key] = parents
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
1168
        return found_parents
2979.2.2 by Robert Collins
Per-file graph heads detection during commit for pack repositories.
1169
2592.1.37 by Robert Collins
Add CombinedGraphIndex.insert_index.
1170
    def insert_index(self, pos, index):
1171
        """Insert a new index in the list of indices to query.
1172
1173
        :param pos: The position to insert the index.
1174
        :param index: The index to insert.
1175
        """
1176
        self._indices.insert(pos, index)
1177
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1178
    def iter_all_entries(self):
1179
        """Iterate over all keys within the index
1180
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
1181
        Duplicate keys across child indices are presumed to have the same
1182
        value and are only reported once.
1183
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
1184
        :return: An iterable of (index, key, reference_lists, value).
1185
            There is no defined order for the result iteration - it will be in
1186
            the most efficient order for the index.
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1187
        """
1188
        seen_keys = set()
3789.1.5 by John Arbash Meinel
CombinedGraphIndex.iter_all_entries() can now reload when needed.
1189
        while True:
1190
            try:
1191
                for index in self._indices:
1192
                    for node in index.iter_all_entries():
1193
                        if node[1] not in seen_keys:
1194
                            yield node
1195
                            seen_keys.add(node[1])
1196
                return
1197
            except errors.NoSuchFile:
1198
                self._reload_or_raise()
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1199
1200
    def iter_entries(self, keys):
1201
        """Iterate over keys within the index.
1202
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
1203
        Duplicate keys across child indices are presumed to have the same
1204
        value and are only reported once.
1205
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1206
        :param keys: An iterable providing the keys to be retrieved.
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
1207
        :return: An iterable of (index, key, reference_lists, value). There is no
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1208
            defined order for the result iteration - it will be in the most
1209
            efficient order for the index.
1210
        """
1211
        keys = set(keys)
3789.1.4 by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request.
1212
        while True:
1213
            try:
1214
                for index in self._indices:
1215
                    if not keys:
1216
                        return
1217
                    for node in index.iter_entries(keys):
1218
                        keys.remove(node[1])
1219
                        yield node
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
1220
                return
3789.1.4 by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request.
1221
            except errors.NoSuchFile:
1222
                self._reload_or_raise()
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1223
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
1224
    def iter_entries_prefix(self, keys):
1225
        """Iterate over keys within the index using prefix matching.
1226
1227
        Duplicate keys across child indices are presumed to have the same
1228
        value and are only reported once.
1229
1230
        Prefix matching is applied within the tuple of a key, not to within
1231
        the bytestring of each key element. e.g. if you have the keys ('foo',
1232
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1233
        only the former key is returned.
1234
1235
        :param keys: An iterable providing the key prefixes to be retrieved.
1236
            Each key prefix takes the form of a tuple the length of a key, but
1237
            with the last N elements 'None' rather than a regular bytestring.
1238
            The first element cannot be 'None'.
1239
        :return: An iterable as per iter_all_entries, but restricted to the
1240
            keys with a matching prefix to those supplied. No additional keys
1241
            will be returned, and every match that is in the index will be
1242
            returned.
1243
        """
1244
        keys = set(keys)
1245
        if not keys:
1246
            return
1247
        seen_keys = set()
3789.1.6 by John Arbash Meinel
CombinedGraphIndex.iter_entries_prefix can now reload when needed.
1248
        while True:
1249
            try:
1250
                for index in self._indices:
1251
                    for node in index.iter_entries_prefix(keys):
1252
                        if node[1] in seen_keys:
1253
                            continue
1254
                        seen_keys.add(node[1])
1255
                        yield node
1256
                return
1257
            except errors.NoSuchFile:
1258
                self._reload_or_raise()
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
1259
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1260
    def key_count(self):
1261
        """Return an estimate of the number of keys in this index.
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
1262
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1263
        For CombinedGraphIndex this is approximated by the sum of the keys of
1264
        the child indices. As child indices may have duplicate keys this can
1265
        have a maximum error of the number of child indices * largest number of
1266
        keys in any index.
1267
        """
3789.1.4 by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request.
1268
        while True:
3789.1.3 by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count().
1269
            try:
1270
                return sum((index.key_count() for index in self._indices), 0)
1271
            except errors.NoSuchFile:
3789.1.4 by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request.
1272
                self._reload_or_raise()
1273
1274
    def _reload_or_raise(self):
1275
        """We just got a NoSuchFile exception.
1276
1277
        Try to reload the indices, if it fails, just raise the current
1278
        exception.
1279
        """
1280
        if self._reload_func is None:
1281
            raise
1282
        exc_type, exc_value, exc_traceback = sys.exc_info()
3789.1.10 by John Arbash Meinel
Review comments from Martin.
1283
        trace.mutter('Trying to reload after getting exception: %s',
1284
                     exc_value)
3789.1.4 by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request.
1285
        if not self._reload_func():
1286
            # We tried to reload, but nothing changed, so we fail anyway
3789.1.10 by John Arbash Meinel
Review comments from Martin.
1287
            trace.mutter('_reload_func indicated nothing has changed.'
1288
                         ' Raising original exception.')
3789.1.4 by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request.
1289
            raise exc_type, exc_value, exc_traceback
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1290
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1291
    def validate(self):
1292
        """Validate that everything in the index can be accessed."""
3789.1.7 by John Arbash Meinel
CombinedGraphIndex.validate() will now reload.
1293
        while True:
1294
            try:
1295
                for index in self._indices:
1296
                    index.validate()
1297
                return
1298
            except errors.NoSuchFile:
1299
                self._reload_or_raise()
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1300
1301
1302
class InMemoryGraphIndex(GraphIndexBuilder):
1303
    """A GraphIndex which operates entirely out of memory and is mutable.
1304
1305
    This is designed to allow the accumulation of GraphIndex entries during a
1306
    single write operation, where the accumulated entries need to be immediately
1307
    available - for example via a CombinedGraphIndex.
1308
    """
1309
1310
    def add_nodes(self, nodes):
1311
        """Add nodes to the index.
1312
1313
        :param nodes: An iterable of (key, node_refs, value) entries to add.
1314
        """
2592.3.39 by Robert Collins
Fugly version to remove signatures.kndx
1315
        if self.reference_lists:
1316
            for (key, value, node_refs) in nodes:
1317
                self.add_node(key, value, node_refs)
1318
        else:
1319
            for (key, value) in nodes:
1320
                self.add_node(key, value)
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1321
1322
    def iter_all_entries(self):
1323
        """Iterate over all keys within the index
1324
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
1325
        :return: An iterable of (index, key, reference_lists, value). There is no
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1326
            defined order for the result iteration - it will be in the most
1327
            efficient order for the index (in this case dictionary hash order).
1328
        """
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
1329
        if 'evil' in debug.debug_flags:
2592.3.112 by Robert Collins
Various fixups found dogfooding.
1330
            trace.mutter_callsite(3,
2745.1.2 by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly.
1331
                "iter_all_entries scales with size of history.")
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1332
        if self.reference_lists:
1333
            for key, (absent, references, value) in self._nodes.iteritems():
1334
                if not absent:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1335
                    yield self, key, value, references
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1336
        else:
1337
            for key, (absent, references, value) in self._nodes.iteritems():
1338
                if not absent:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1339
                    yield self, key, value
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1340
1341
    def iter_entries(self, keys):
1342
        """Iterate over keys within the index.
1343
1344
        :param keys: An iterable providing the keys to be retrieved.
2979.2.4 by Robert Collins
Docstring fixes from review.
1345
        :return: An iterable of (index, key, value, reference_lists). There is no
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1346
            defined order for the result iteration - it will be in the most
1347
            efficient order for the index (keys iteration order in this case).
1348
        """
1349
        keys = set(keys)
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1350
        if self.reference_lists:
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
1351
            for key in keys.intersection(self._keys):
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1352
                node = self._nodes[key]
1353
                if not node[0]:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1354
                    yield self, key, node[2], node[1]
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1355
        else:
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
1356
            for key in keys.intersection(self._keys):
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1357
                node = self._nodes[key]
1358
                if not node[0]:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1359
                    yield self, key, node[2]
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1360
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1361
    def iter_entries_prefix(self, keys):
1362
        """Iterate over keys within the index using prefix matching.
1363
1364
        Prefix matching is applied within the tuple of a key, not to within
1365
        the bytestring of each key element. e.g. if you have the keys ('foo',
1366
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1367
        only the former key is returned.
1368
1369
        :param keys: An iterable providing the key prefixes to be retrieved.
1370
            Each key prefix takes the form of a tuple the length of a key, but
1371
            with the last N elements 'None' rather than a regular bytestring.
1372
            The first element cannot be 'None'.
1373
        :return: An iterable as per iter_all_entries, but restricted to the
1374
            keys with a matching prefix to those supplied. No additional keys
1375
            will be returned, and every match that is in the index will be
1376
            returned.
1377
        """
1378
        # XXX: To much duplication with the GraphIndex class; consider finding
1379
        # a good place to pull out the actual common logic.
1380
        keys = set(keys)
1381
        if not keys:
1382
            return
1383
        if self._key_length == 1:
1384
            for key in keys:
1385
                # sanity check
1386
                if key[0] is None:
1387
                    raise errors.BadIndexKey(key)
1388
                if len(key) != self._key_length:
1389
                    raise errors.BadIndexKey(key)
1390
                node = self._nodes[key]
1391
                if node[0]:
1392
                    continue 
1393
                if self.reference_lists:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1394
                    yield self, key, node[2], node[1]
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1395
                else:
2624.2.17 by Robert Collins
Review feedback.
1396
                    yield self, key, node[2]
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1397
            return
3644.2.4 by John Arbash Meinel
Change GraphIndex to also have a _get_nodes_by_key
1398
        nodes_by_key = self._get_nodes_by_key()
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1399
        for key in keys:
1400
            # sanity check
1401
            if key[0] is None:
1402
                raise errors.BadIndexKey(key)
1403
            if len(key) != self._key_length:
1404
                raise errors.BadIndexKey(key)
1405
            # find what it refers to:
3644.2.4 by John Arbash Meinel
Change GraphIndex to also have a _get_nodes_by_key
1406
            key_dict = nodes_by_key
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1407
            elements = list(key)
1408
            # find the subdict to return
1409
            try:
1410
                while len(elements) and elements[0] is not None:
1411
                    key_dict = key_dict[elements[0]]
1412
                    elements.pop(0)
1413
            except KeyError:
1414
                # a non-existant lookup.
1415
                continue
1416
            if len(elements):
1417
                dicts = [key_dict]
1418
                while dicts:
1419
                    key_dict = dicts.pop(-1)
1420
                    # can't be empty or would not exist
1421
                    item, value = key_dict.iteritems().next()
1422
                    if type(value) == dict:
1423
                        # push keys 
1424
                        dicts.extend(key_dict.itervalues())
1425
                    else:
1426
                        # yield keys
1427
                        for value in key_dict.itervalues():
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1428
                            yield (self, ) + value
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1429
            else:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1430
                yield (self, ) + key_dict
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1431
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1432
    def key_count(self):
1433
        """Return an estimate of the number of keys in this index.
1434
        
1435
        For InMemoryGraphIndex the estimate is exact.
1436
        """
1437
        return len(self._keys)
1438
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1439
    def validate(self):
1440
        """In memory index's have no known corruption at the moment."""
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1441
1442
1443
class GraphIndexPrefixAdapter(object):
1444
    """An adapter between GraphIndex with different key lengths.
1445
1446
    Queries against this will emit queries against the adapted Graph with the
1447
    prefix added, queries for all items use iter_entries_prefix. The returned
1448
    nodes will have their keys and node references adjusted to remove the 
1449
    prefix. Finally, an add_nodes_callback can be supplied - when called the
1450
    nodes and references being added will have prefix prepended.
1451
    """
1452
2624.2.17 by Robert Collins
Review feedback.
1453
    def __init__(self, adapted, prefix, missing_key_length,
1454
        add_nodes_callback=None):
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1455
        """Construct an adapter against adapted with prefix."""
1456
        self.adapted = adapted
2624.2.19 by Robert Collins
Why we should always test before committing.
1457
        self.prefix_key = prefix + (None,)*missing_key_length
2624.2.17 by Robert Collins
Review feedback.
1458
        self.prefix = prefix
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1459
        self.prefix_len = len(prefix)
1460
        self.add_nodes_callback = add_nodes_callback
1461
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1462
    def add_nodes(self, nodes):
1463
        """Add nodes to the index.
1464
1465
        :param nodes: An iterable of (key, node_refs, value) entries to add.
1466
        """
1467
        # save nodes in case its an iterator
1468
        nodes = tuple(nodes)
1469
        translated_nodes = []
1470
        try:
2624.2.17 by Robert Collins
Review feedback.
1471
            # Add prefix_key to each reference node_refs is a tuple of tuples,
1472
            # so split it apart, and add prefix_key to the internal reference
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1473
            for (key, value, node_refs) in nodes:
1474
                adjusted_references = (
2624.2.17 by Robert Collins
Review feedback.
1475
                    tuple(tuple(self.prefix + ref_node for ref_node in ref_list)
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1476
                        for ref_list in node_refs))
2624.2.17 by Robert Collins
Review feedback.
1477
                translated_nodes.append((self.prefix + key, value,
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1478
                    adjusted_references))
1479
        except ValueError:
1480
            # XXX: TODO add an explicit interface for getting the reference list
1481
            # status, to handle this bit of user-friendliness in the API more 
1482
            # explicitly.
1483
            for (key, value) in nodes:
2624.2.17 by Robert Collins
Review feedback.
1484
                translated_nodes.append((self.prefix + key, value))
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1485
        self.add_nodes_callback(translated_nodes)
1486
1487
    def add_node(self, key, value, references=()):
1488
        """Add a node to the index.
1489
1490
        :param key: The key. keys are non-empty tuples containing
1491
            as many whitespace-free utf8 bytestrings as the key length
1492
            defined for this index.
1493
        :param references: An iterable of iterables of keys. Each is a
1494
            reference to another key.
1495
        :param value: The value to associate with the key. It may be any
1496
            bytes as long as it does not contain \0 or \n.
1497
        """
1498
        self.add_nodes(((key, value, references), ))
1499
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1500
    def _strip_prefix(self, an_iter):
1501
        """Strip prefix data from nodes and return it."""
1502
        for node in an_iter:
1503
            # cross checks
2624.2.17 by Robert Collins
Review feedback.
1504
            if node[1][:self.prefix_len] != self.prefix:
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1505
                raise errors.BadIndexData(self)
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1506
            for ref_list in node[3]:
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1507
                for ref_node in ref_list:
2624.2.17 by Robert Collins
Review feedback.
1508
                    if ref_node[:self.prefix_len] != self.prefix:
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1509
                        raise errors.BadIndexData(self)
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1510
            yield node[0], node[1][self.prefix_len:], node[2], (
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1511
                tuple(tuple(ref_node[self.prefix_len:] for ref_node in ref_list)
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1512
                for ref_list in node[3]))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1513
1514
    def iter_all_entries(self):
1515
        """Iterate over all keys within the index
1516
1517
        iter_all_entries is implemented against the adapted index using
1518
        iter_entries_prefix.
1519
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
1520
        :return: An iterable of (index, key, reference_lists, value). There is no
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1521
            defined order for the result iteration - it will be in the most
1522
            efficient order for the index (in this case dictionary hash order).
1523
        """
2624.2.19 by Robert Collins
Why we should always test before committing.
1524
        return self._strip_prefix(self.adapted.iter_entries_prefix([self.prefix_key]))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1525
1526
    def iter_entries(self, keys):
1527
        """Iterate over keys within the index.
1528
1529
        :param keys: An iterable providing the keys to be retrieved.
2979.2.4 by Robert Collins
Docstring fixes from review.
1530
        :return: An iterable of (index, key, value, reference_lists). There is no
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1531
            defined order for the result iteration - it will be in the most
1532
            efficient order for the index (keys iteration order in this case).
1533
        """
1534
        return self._strip_prefix(self.adapted.iter_entries(
2624.2.17 by Robert Collins
Review feedback.
1535
            self.prefix + key for key in keys))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1536
1537
    def iter_entries_prefix(self, keys):
1538
        """Iterate over keys within the index using prefix matching.
1539
1540
        Prefix matching is applied within the tuple of a key, not to within
1541
        the bytestring of each key element. e.g. if you have the keys ('foo',
1542
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1543
        only the former key is returned.
1544
1545
        :param keys: An iterable providing the key prefixes to be retrieved.
1546
            Each key prefix takes the form of a tuple the length of a key, but
1547
            with the last N elements 'None' rather than a regular bytestring.
1548
            The first element cannot be 'None'.
1549
        :return: An iterable as per iter_all_entries, but restricted to the
1550
            keys with a matching prefix to those supplied. No additional keys
1551
            will be returned, and every match that is in the index will be
1552
            returned.
1553
        """
1554
        return self._strip_prefix(self.adapted.iter_entries_prefix(
2624.2.17 by Robert Collins
Review feedback.
1555
            self.prefix + key for key in keys))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1556
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1557
    def key_count(self):
1558
        """Return an estimate of the number of keys in this index.
1559
        
1560
        For GraphIndexPrefixAdapter this is relatively expensive - key
1561
        iteration with the prefix is done.
1562
        """
1563
        return len(list(self.iter_all_entries()))
1564
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1565
    def validate(self):
1566
        """Call the adapted's validate."""
1567
        self.adapted.validate()