~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/index.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-03-16 14:01:20 UTC
  • mfrom: (3280.2.5 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080316140120-i3yq8yr1l66m11h7
Start 1.4 development

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Indexing facilities."""
18
18
 
27
27
from bisect import bisect_right
28
28
from cStringIO import StringIO
29
29
import re
30
 
import sys
31
30
 
32
31
from bzrlib.lazy_import import lazy_import
33
32
lazy_import(globals(), """
53
52
_newline_null_re = re.compile('[\n\0]')
54
53
 
55
54
 
56
 
def _has_key_from_parent_map(self, key):
57
 
    """Check if this index has one key.
58
 
 
59
 
    If it's possible to check for multiple keys at once through
60
 
    calling get_parent_map that should be faster.
61
 
    """
62
 
    return (key in self.get_parent_map([key]))
63
 
 
64
 
 
65
 
def _missing_keys_from_parent_map(self, keys):
66
 
    return set(keys) - set(self.get_parent_map(keys))
67
 
 
68
 
 
69
55
class GraphIndexBuilder(object):
70
56
    """A builder that can build a GraphIndex.
71
 
 
 
57
    
72
58
    The resulting graph has the structure:
73
 
 
 
59
    
74
60
    _SIGNATURE OPTIONS NODES NEWLINE
75
61
    _SIGNATURE     := 'Bazaar Graph Index 1' NEWLINE
76
62
    OPTIONS        := 'node_ref_lists=' DIGITS NEWLINE
94
80
        """
95
81
        self.reference_lists = reference_lists
96
82
        self._keys = set()
97
 
        # A dict of {key: (absent, ref_lists, value)}
98
83
        self._nodes = {}
99
 
        self._nodes_by_key = None
 
84
        self._nodes_by_key = {}
100
85
        self._key_length = key_elements
101
 
        self._optimize_for_size = False
102
 
        self._combine_backing_indices = True
103
86
 
104
87
    def _check_key(self, key):
105
88
        """Raise BadIndexKey if key is not a valid key for this index."""
111
94
            if not element or _whitespace_re.search(element) is not None:
112
95
                raise errors.BadIndexKey(element)
113
96
 
114
 
    def _external_references(self):
115
 
        """Return references that are not present in this index.
116
 
        """
117
 
        keys = set()
118
 
        refs = set()
119
 
        # TODO: JAM 2008-11-21 This makes an assumption about how the reference
120
 
        #       lists are used. It is currently correct for pack-0.92 through
121
 
        #       1.9, which use the node references (3rd column) second
122
 
        #       reference list as the compression parent. Perhaps this should
123
 
        #       be moved into something higher up the stack, since it
124
 
        #       makes assumptions about how the index is used.
125
 
        if self.reference_lists > 1:
126
 
            for node in self.iter_all_entries():
127
 
                keys.add(node[1])
128
 
                refs.update(node[3][1])
129
 
            return refs - keys
130
 
        else:
131
 
            # If reference_lists == 0 there can be no external references, and
132
 
            # if reference_lists == 1, then there isn't a place to store the
133
 
            # compression parent
134
 
            return set()
135
 
 
136
 
    def _get_nodes_by_key(self):
137
 
        if self._nodes_by_key is None:
138
 
            nodes_by_key = {}
139
 
            if self.reference_lists:
140
 
                for key, (absent, references, value) in self._nodes.iteritems():
141
 
                    if absent:
142
 
                        continue
143
 
                    key_dict = nodes_by_key
144
 
                    for subkey in key[:-1]:
145
 
                        key_dict = key_dict.setdefault(subkey, {})
146
 
                    key_dict[key[-1]] = key, value, references
147
 
            else:
148
 
                for key, (absent, references, value) in self._nodes.iteritems():
149
 
                    if absent:
150
 
                        continue
151
 
                    key_dict = nodes_by_key
152
 
                    for subkey in key[:-1]:
153
 
                        key_dict = key_dict.setdefault(subkey, {})
154
 
                    key_dict[key[-1]] = key, value
155
 
            self._nodes_by_key = nodes_by_key
156
 
        return self._nodes_by_key
157
 
 
158
 
    def _update_nodes_by_key(self, key, value, node_refs):
159
 
        """Update the _nodes_by_key dict with a new key.
160
 
 
161
 
        For a key of (foo, bar, baz) create
162
 
        _nodes_by_key[foo][bar][baz] = key_value
163
 
        """
164
 
        if self._nodes_by_key is None:
165
 
            return
166
 
        key_dict = self._nodes_by_key
167
 
        if self.reference_lists:
168
 
            key_value = key, value, node_refs
169
 
        else:
170
 
            key_value = key, value
171
 
        for subkey in key[:-1]:
172
 
            key_dict = key_dict.setdefault(subkey, {})
173
 
        key_dict[key[-1]] = key_value
174
 
 
175
 
    def _check_key_ref_value(self, key, references, value):
176
 
        """Check that 'key' and 'references' are all valid.
177
 
 
178
 
        :param key: A key tuple. Must conform to the key interface (be a tuple,
179
 
            be of the right length, not have any whitespace or nulls in any key
180
 
            element.)
181
 
        :param references: An iterable of reference lists. Something like
182
 
            [[(ref, key)], [(ref, key), (other, key)]]
183
 
        :param value: The value associate with this key. Must not contain
184
 
            newlines or null characters.
185
 
        :return: (node_refs, absent_references)
186
 
            node_refs   basically a packed form of 'references' where all
187
 
                        iterables are tuples
188
 
            absent_references   reference keys that are not in self._nodes.
189
 
                                This may contain duplicates if the same key is
190
 
                                referenced in multiple lists.
 
97
    def add_node(self, key, value, references=()):
 
98
        """Add a node to the index.
 
99
 
 
100
        :param key: The key. keys are non-empty tuples containing
 
101
            as many whitespace-free utf8 bytestrings as the key length
 
102
            defined for this index.
 
103
        :param references: An iterable of iterables of keys. Each is a
 
104
            reference to another key.
 
105
        :param value: The value to associate with the key. It may be any
 
106
            bytes as long as it does not contain \0 or \n.
191
107
        """
192
108
        self._check_key(key)
193
109
        if _newline_null_re.search(value) is not None:
195
111
        if len(references) != self.reference_lists:
196
112
            raise errors.BadIndexValue(references)
197
113
        node_refs = []
198
 
        absent_references = []
199
114
        for reference_list in references:
200
115
            for reference in reference_list:
201
 
                # If reference *is* in self._nodes, then we know it has already
202
 
                # been checked.
 
116
                self._check_key(reference)
203
117
                if reference not in self._nodes:
204
 
                    self._check_key(reference)
205
 
                    absent_references.append(reference)
 
118
                    self._nodes[reference] = ('a', (), '')
206
119
            node_refs.append(tuple(reference_list))
207
 
        return tuple(node_refs), absent_references
208
 
 
209
 
    def add_node(self, key, value, references=()):
210
 
        """Add a node to the index.
211
 
 
212
 
        :param key: The key. keys are non-empty tuples containing
213
 
            as many whitespace-free utf8 bytestrings as the key length
214
 
            defined for this index.
215
 
        :param references: An iterable of iterables of keys. Each is a
216
 
            reference to another key.
217
 
        :param value: The value to associate with the key. It may be any
218
 
            bytes as long as it does not contain \0 or \n.
219
 
        """
220
 
        (node_refs,
221
 
         absent_references) = self._check_key_ref_value(key, references, value)
222
 
        if key in self._nodes and self._nodes[key][0] != 'a':
 
120
        if key in self._nodes and self._nodes[key][0] == '':
223
121
            raise errors.BadIndexDuplicateKey(key, self)
224
 
        for reference in absent_references:
225
 
            # There may be duplicates, but I don't think it is worth worrying
226
 
            # about
227
 
            self._nodes[reference] = ('a', (), '')
228
 
        self._nodes[key] = ('', node_refs, value)
 
122
        self._nodes[key] = ('', tuple(node_refs), value)
229
123
        self._keys.add(key)
230
 
        if self._nodes_by_key is not None and self._key_length > 1:
231
 
            self._update_nodes_by_key(key, value, node_refs)
 
124
        if self._key_length > 1:
 
125
            key_dict = self._nodes_by_key
 
126
            if self.reference_lists:
 
127
                key_value = key, value, tuple(node_refs)
 
128
            else:
 
129
                key_value = key, value
 
130
            # possibly should do this on-demand, but it seems likely it is 
 
131
            # always wanted
 
132
            # For a key of (foo, bar, baz) create
 
133
            # _nodes_by_key[foo][bar][baz] = key_value
 
134
            for subkey in key[:-1]:
 
135
                key_dict = key_dict.setdefault(subkey, {})
 
136
            key_dict[key[-1]] = key_value
232
137
 
233
138
    def finish(self):
234
139
        lines = [_SIGNATURE]
237
142
        lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
238
143
        prefix_length = sum(len(x) for x in lines)
239
144
        # references are byte offsets. To avoid having to do nasty
240
 
        # polynomial work to resolve offsets (references to later in the
 
145
        # polynomial work to resolve offsets (references to later in the 
241
146
        # file cannot be determined until all the inbetween references have
242
147
        # been calculated too) we pad the offsets with 0's to make them be
243
148
        # of consistent length. Using binary offsets would break the trivial
247
152
        # one to pad all the data with reference-length and determine entry
248
153
        # addresses.
249
154
        # One to serialise.
250
 
 
 
155
        
251
156
        # forward sorted by key. In future we may consider topological sorting,
252
157
        # at the cost of table scans for direct lookup, or a second index for
253
158
        # direct lookup
314
219
            raise errors.BzrError('Failed index creation. Internal error:'
315
220
                ' mismatched output length and expected length: %d %d' %
316
221
                (len(result.getvalue()), expected_bytes))
317
 
        return result
318
 
 
319
 
    def set_optimize(self, for_size=None, combine_backing_indices=None):
320
 
        """Change how the builder tries to optimize the result.
321
 
 
322
 
        :param for_size: Tell the builder to try and make the index as small as
323
 
            possible.
324
 
        :param combine_backing_indices: If the builder spills to disk to save
325
 
            memory, should the on-disk indices be combined. Set to True if you
326
 
            are going to be probing the index, but to False if you are not. (If
327
 
            you are not querying, then the time spent combining is wasted.)
328
 
        :return: None
329
 
        """
330
 
        # GraphIndexBuilder itself doesn't pay attention to the flag yet, but
331
 
        # other builders do.
332
 
        if for_size is not None:
333
 
            self._optimize_for_size = for_size
334
 
        if combine_backing_indices is not None:
335
 
            self._combine_backing_indices = combine_backing_indices
 
222
        return StringIO(''.join(lines))
336
223
 
337
224
 
338
225
class GraphIndex(object):
339
226
    """An index for data with embedded graphs.
340
 
 
 
227
 
341
228
    The index maps keys to a list of key reference lists, and a value.
342
229
    Each node has the same number of key reference lists. Each key reference
343
230
    list can be empty or an arbitrary length. The value is an opaque NULL
344
 
    terminated string without any newlines. The storage of the index is
 
231
    terminated string without any newlines. The storage of the index is 
345
232
    hidden in the interface: keys and key references are always tuples of
346
233
    bytestrings, never the internal representation (e.g. dictionary offsets).
347
234
 
385
272
        self._keys_by_offset = None
386
273
        self._nodes_by_key = None
387
274
        self._size = size
388
 
        # The number of bytes we've read so far in trying to process this file
389
 
        self._bytes_read = 0
390
275
 
391
276
    def __eq__(self, other):
392
277
        """Equal when self and other were created with the same parameters."""
399
284
    def __ne__(self, other):
400
285
        return not self.__eq__(other)
401
286
 
402
 
    def __repr__(self):
403
 
        return "%s(%r)" % (self.__class__.__name__,
404
 
            self._transport.abspath(self._name))
405
 
 
406
 
    def _buffer_all(self, stream=None):
 
287
    def _buffer_all(self):
407
288
        """Buffer all the index data.
408
289
 
409
290
        Mutates self._nodes and self.keys_by_offset.
410
291
        """
411
 
        if self._nodes is not None:
412
 
            # We already did this
413
 
            return
414
292
        if 'index' in debug.debug_flags:
415
293
            mutter('Reading entire index %s', self._transport.abspath(self._name))
416
 
        if stream is None:
417
 
            stream = self._transport.get(self._name)
 
294
        stream = self._transport.get(self._name)
418
295
        self._read_prefix(stream)
419
296
        self._expected_elements = 3 + self._key_length
420
297
        line_count = 0
422
299
        self._keys_by_offset = {}
423
300
        # ready-to-return key:value or key:value, node_ref_lists
424
301
        self._nodes = {}
425
 
        self._nodes_by_key = None
 
302
        self._nodes_by_key = {}
426
303
        trailers = 0
427
304
        pos = stream.tell()
428
305
        lines = stream.read().split('\n')
437
314
            else:
438
315
                node_value = value
439
316
            self._nodes[key] = node_value
 
317
            if self._key_length > 1:
 
318
                subkey = list(reversed(key[:-1]))
 
319
                key_dict = self._nodes_by_key
 
320
                if self.node_ref_lists:
 
321
                    key_value = key, node_value[0], node_value[1]
 
322
                else:
 
323
                    key_value = key, node_value
 
324
                # possibly should do this on-demand, but it seems likely it is 
 
325
                # always wanted
 
326
                # For a key of (foo, bar, baz) create
 
327
                # _nodes_by_key[foo][bar][baz] = key_value
 
328
                for subkey in key[:-1]:
 
329
                    key_dict = key_dict.setdefault(subkey, {})
 
330
                key_dict[key[-1]] = key_value
440
331
        # cache the keys for quick set intersections
441
332
        self._keys = set(self._nodes)
442
333
        if trailers != 1:
443
334
            # there must be one line - the empty trailer line.
444
335
            raise errors.BadIndexData(self)
445
336
 
446
 
    def external_references(self, ref_list_num):
447
 
        """Return references that are not present in this index.
448
 
        """
449
 
        self._buffer_all()
450
 
        if ref_list_num + 1 > self.node_ref_lists:
451
 
            raise ValueError('No ref list %d, index has %d ref lists'
452
 
                % (ref_list_num, self.node_ref_lists))
453
 
        refs = set()
454
 
        for key, (value, ref_lists) in self._nodes.iteritems():
455
 
            ref_list = ref_lists[ref_list_num]
456
 
            refs.update(ref_list)
457
 
        return refs - self._keys
458
 
 
459
 
    def _get_nodes_by_key(self):
460
 
        if self._nodes_by_key is None:
461
 
            nodes_by_key = {}
462
 
            if self.node_ref_lists:
463
 
                for key, (value, references) in self._nodes.iteritems():
464
 
                    key_dict = nodes_by_key
465
 
                    for subkey in key[:-1]:
466
 
                        key_dict = key_dict.setdefault(subkey, {})
467
 
                    key_dict[key[-1]] = key, value, references
468
 
            else:
469
 
                for key, value in self._nodes.iteritems():
470
 
                    key_dict = nodes_by_key
471
 
                    for subkey in key[:-1]:
472
 
                        key_dict = key_dict.setdefault(subkey, {})
473
 
                    key_dict[key[-1]] = key, value
474
 
            self._nodes_by_key = nodes_by_key
475
 
        return self._nodes_by_key
476
 
 
477
337
    def iter_all_entries(self):
478
338
        """Iterate over all keys within the index.
479
339
 
523
383
 
524
384
    def _resolve_references(self, references):
525
385
        """Return the resolved key references for references.
526
 
 
 
386
        
527
387
        References are resolved by looking up the location of the key in the
528
388
        _keys_by_offset map and substituting the key name, preserving ordering.
529
389
 
530
 
        :param references: An iterable of iterables of key locations. e.g.
 
390
        :param references: An iterable of iterables of key locations. e.g. 
531
391
            [[123, 456], [123]]
532
392
        :return: A tuple of tuples of keys.
533
393
        """
604
464
            keys supplied. No additional keys will be returned, and every
605
465
            key supplied that is in the index will be returned.
606
466
        """
 
467
        # PERFORMANCE TODO: parse and bisect all remaining data at some
 
468
        # threshold of total-index processing/get calling layers that expect to
 
469
        # read the entire index to use the iter_all_entries  method instead.
607
470
        keys = set(keys)
608
471
        if not keys:
609
472
            return []
610
473
        if self._size is None and self._nodes is None:
611
474
            self._buffer_all()
612
 
 
613
 
        # We fit about 20 keys per minimum-read (4K), so if we are looking for
614
 
        # more than 1/20th of the index its likely (assuming homogenous key
615
 
        # spread) that we'll read the entire index. If we're going to do that,
616
 
        # buffer the whole thing. A better analysis might take key spread into
617
 
        # account - but B+Tree indices are better anyway.
618
 
        # We could look at all data read, and use a threshold there, which will
619
 
        # trigger on ancestry walks, but that is not yet fully mapped out.
620
 
        if self._nodes is None and len(keys) * 20 > self.key_count():
621
 
            self._buffer_all()
622
475
        if self._nodes is not None:
623
476
            return self._iter_entries_from_total_buffer(keys)
624
477
        else:
666
519
                else:
667
520
                    yield self, key, self._nodes[key]
668
521
            return
669
 
        nodes_by_key = self._get_nodes_by_key()
670
522
        for key in keys:
671
523
            # sanity check
672
524
            if key[0] is None:
674
526
            if len(key) != self._key_length:
675
527
                raise errors.BadIndexKey(key)
676
528
            # find what it refers to:
677
 
            key_dict = nodes_by_key
 
529
            key_dict = self._nodes_by_key
678
530
            elements = list(key)
679
531
            # find the subdict whose contents should be returned.
680
532
            try:
691
543
                    # can't be empty or would not exist
692
544
                    item, value = key_dict.iteritems().next()
693
545
                    if type(value) == dict:
694
 
                        # push keys
 
546
                        # push keys 
695
547
                        dicts.extend(key_dict.itervalues())
696
548
                    else:
697
549
                        # yield keys
705
557
 
706
558
    def key_count(self):
707
559
        """Return an estimate of the number of keys in this index.
708
 
 
 
560
        
709
561
        For GraphIndex the estimate is exact.
710
562
        """
711
563
        if self._key_count is None:
727
579
        # Possible improvements:
728
580
        #  - only bisect lookup each key once
729
581
        #  - sort the keys first, and use that to reduce the bisection window
730
 
        # -----
 
582
        # ----- 
731
583
        # this progresses in three parts:
732
584
        # read data
733
585
        # parse it
742
594
                # We have the key parsed.
743
595
                continue
744
596
            index = self._parsed_key_index(key)
745
 
            if (len(self._parsed_key_map) and
 
597
            if (len(self._parsed_key_map) and 
746
598
                self._parsed_key_map[index][0] <= key and
747
599
                (self._parsed_key_map[index][1] >= key or
748
600
                 # end of the file has been parsed
752
604
                continue
753
605
            # - if we have examined this part of the file already - yes
754
606
            index = self._parsed_byte_index(location)
755
 
            if (len(self._parsed_byte_map) and
 
607
            if (len(self._parsed_byte_map) and 
756
608
                self._parsed_byte_map[index][0] <= location and
757
609
                self._parsed_byte_map[index][1] > location):
758
610
                # the byte region has been parsed, so no read is needed.
767
619
        if self._bisect_nodes is None:
768
620
            readv_ranges.append(_HEADER_READV)
769
621
        self._read_and_parse(readv_ranges)
770
 
        result = []
771
 
        if self._nodes is not None:
772
 
            # _read_and_parse triggered a _buffer_all because we requested the
773
 
            # whole data range
774
 
            for location, key in location_keys:
775
 
                if key not in self._nodes: # not present
776
 
                    result.append(((location, key), False))
777
 
                elif self.node_ref_lists:
778
 
                    value, refs = self._nodes[key]
779
 
                    result.append(((location, key),
780
 
                        (self, key, value, refs)))
781
 
                else:
782
 
                    result.append(((location, key),
783
 
                        (self, key, self._nodes[key])))
784
 
            return result
785
622
        # generate results:
786
623
        #  - figure out <, >, missing, present
787
624
        #  - result present references so we can return them.
 
625
        result = []
788
626
        # keys that we cannot answer until we resolve references
789
627
        pending_references = []
790
628
        pending_locations = set()
840
678
            if length > 0:
841
679
                readv_ranges.append((location, length))
842
680
        self._read_and_parse(readv_ranges)
843
 
        if self._nodes is not None:
844
 
            # The _read_and_parse triggered a _buffer_all, grab the data and
845
 
            # return it
846
 
            for location, key in pending_references:
847
 
                value, refs = self._nodes[key]
848
 
                result.append(((location, key), (self, key, value, refs)))
849
 
            return result
850
681
        for location, key in pending_references:
851
682
            # answer key references we had to look-up-late.
 
683
            index = self._parsed_key_index(key)
852
684
            value, refs = self._bisect_nodes[key]
853
685
            result.append(((location, key), (self, key,
854
686
                value, self._resolve_references(refs))))
998
830
                trim_start = data.find('\n') + 1
999
831
            else:
1000
832
                trim_start = data.find('\n', trim_start) + 1
1001
 
            if not (trim_start != 0):
1002
 
                raise AssertionError('no \n was present')
 
833
            assert trim_start != 0, 'no \n was present'
1003
834
            # print 'removing start', offset, trim_start, repr(data[:trim_start])
1004
835
        if not end_adjacent:
1005
836
            # work around python bug in rfind
1007
838
                trim_end = data.rfind('\n') + 1
1008
839
            else:
1009
840
                trim_end = data.rfind('\n', None, trim_end) + 1
1010
 
            if not (trim_end != 0):
1011
 
                raise AssertionError('no \n was present')
 
841
            assert trim_end != 0, 'no \n was present'
1012
842
            # print 'removing end', offset, trim_end, repr(data[trim_end:])
1013
843
        # adjust offset and data to the parseable data.
1014
844
        trimmed_data = data[trim_start:trim_end]
1015
 
        if not (trimmed_data):
1016
 
            raise AssertionError('read unneeded data [%d:%d] from [%d:%d]'
1017
 
                % (trim_start, trim_end, offset, offset + len(data)))
 
845
        assert trimmed_data, 'read unneeded data [%d:%d] from [%d:%d]' % (
 
846
            trim_start, trim_end, offset, offset + len(data))
1018
847
        if trim_start:
1019
848
            offset += trim_start
1020
849
        # print "parsing", repr(trimmed_data)
1038
867
            if line == '':
1039
868
                # must be at the end
1040
869
                if self._size:
1041
 
                    if not (self._size == pos + 1):
1042
 
                        raise AssertionError("%s %s" % (self._size, pos))
 
870
                    assert self._size == pos + 1, "%s %s" % (self._size, pos)
1043
871
                trailers += 1
1044
872
                continue
1045
873
            elements = line.split('\0')
1046
874
            if len(elements) != self._expected_elements:
1047
875
                raise errors.BadIndexData(self)
1048
 
            # keys are tuples. Each element is a string that may occur many
1049
 
            # times, so we intern them to save space. AB, RC, 200807
1050
 
            key = tuple([intern(element) for element in elements[:self._key_length]])
 
876
            # keys are tuples
 
877
            key = tuple(elements[:self._key_length])
1051
878
            if first_key is None:
1052
879
                first_key = key
1053
880
            absent, references, value = elements[-3:]
1124
951
 
1125
952
        :param readv_ranges: A prepared readv range list.
1126
953
        """
1127
 
        if not readv_ranges:
1128
 
            return
1129
 
        if self._nodes is None and self._bytes_read * 2 >= self._size:
1130
 
            # We've already read more than 50% of the file and we are about to
1131
 
            # request more data, just _buffer_all() and be done
1132
 
            self._buffer_all()
1133
 
            return
1134
 
 
1135
 
        readv_data = self._transport.readv(self._name, readv_ranges, True,
1136
 
            self._size)
1137
 
        # parse
1138
 
        for offset, data in readv_data:
1139
 
            self._bytes_read += len(data)
1140
 
            if offset == 0 and len(data) == self._size:
1141
 
                # We read the whole range, most likely because the
1142
 
                # Transport upcast our readv ranges into one long request
1143
 
                # for enough total data to grab the whole index.
1144
 
                self._buffer_all(StringIO(data))
1145
 
                return
1146
 
            if self._bisect_nodes is None:
1147
 
                # this must be the start
1148
 
                if not (offset == 0):
1149
 
                    raise AssertionError()
1150
 
                offset, data = self._parse_header_from_bytes(data)
1151
 
            # print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1152
 
            self._parse_region(offset, data)
 
954
        if readv_ranges:
 
955
            readv_data = self._transport.readv(self._name, readv_ranges, True,
 
956
                self._size)
 
957
            # parse
 
958
            for offset, data in readv_data:
 
959
                if self._bisect_nodes is None:
 
960
                    # this must be the start
 
961
                    assert offset == 0
 
962
                    offset, data = self._parse_header_from_bytes(data)
 
963
                # print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
 
964
                self._parse_region(offset, data)
1153
965
 
1154
966
    def _signature(self):
1155
967
        """The file signature for this index type."""
1164
976
 
1165
977
class CombinedGraphIndex(object):
1166
978
    """A GraphIndex made up from smaller GraphIndices.
1167
 
 
 
979
    
1168
980
    The backing indices must implement GraphIndex, and are presumed to be
1169
981
    static data.
1170
982
 
1175
987
    in the index list.
1176
988
    """
1177
989
 
1178
 
    def __init__(self, indices, reload_func=None):
 
990
    def __init__(self, indices):
1179
991
        """Create a CombinedGraphIndex backed by indices.
1180
992
 
1181
993
        :param indices: An ordered list of indices to query for data.
1182
 
        :param reload_func: A function to call if we find we are missing an
1183
 
            index. Should have the form reload_func() => True/False to indicate
1184
 
            if reloading actually changed anything.
1185
994
        """
1186
995
        self._indices = indices
1187
 
        self._reload_func = reload_func
1188
996
 
1189
997
    def __repr__(self):
1190
998
        return "%s(%s)" % (
1191
999
                self.__class__.__name__,
1192
1000
                ', '.join(map(repr, self._indices)))
1193
1001
 
 
1002
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
 
1003
    def get_parents(self, revision_ids):
 
1004
        """See graph._StackedParentsProvider.get_parents.
 
1005
        
 
1006
        This implementation thunks the graph.Graph.get_parents api across to
 
1007
        GraphIndex.
 
1008
 
 
1009
        :param revision_ids: An iterable of graph keys for this graph.
 
1010
        :return: A list of parent details for each key in revision_ids.
 
1011
            Each parent details will be one of:
 
1012
             * None when the key was missing
 
1013
             * (NULL_REVISION,) when the key has no parents.
 
1014
             * (parent_key, parent_key...) otherwise.
 
1015
        """
 
1016
        parent_map = self.get_parent_map(revision_ids)
 
1017
        return [parent_map.get(r, None) for r in revision_ids]
 
1018
 
1194
1019
    def get_parent_map(self, keys):
1195
1020
        """See graph._StackedParentsProvider.get_parent_map"""
1196
1021
        search_keys = set(keys)
1206
1031
            found_parents[key] = parents
1207
1032
        return found_parents
1208
1033
 
1209
 
    has_key = _has_key_from_parent_map
1210
 
 
1211
1034
    def insert_index(self, pos, index):
1212
1035
        """Insert a new index in the list of indices to query.
1213
1036
 
1227
1050
            the most efficient order for the index.
1228
1051
        """
1229
1052
        seen_keys = set()
1230
 
        while True:
1231
 
            try:
1232
 
                for index in self._indices:
1233
 
                    for node in index.iter_all_entries():
1234
 
                        if node[1] not in seen_keys:
1235
 
                            yield node
1236
 
                            seen_keys.add(node[1])
1237
 
                return
1238
 
            except errors.NoSuchFile:
1239
 
                self._reload_or_raise()
 
1053
        for index in self._indices:
 
1054
            for node in index.iter_all_entries():
 
1055
                if node[1] not in seen_keys:
 
1056
                    yield node
 
1057
                    seen_keys.add(node[1])
1240
1058
 
1241
1059
    def iter_entries(self, keys):
1242
1060
        """Iterate over keys within the index.
1250
1068
            efficient order for the index.
1251
1069
        """
1252
1070
        keys = set(keys)
1253
 
        while True:
1254
 
            try:
1255
 
                for index in self._indices:
1256
 
                    if not keys:
1257
 
                        return
1258
 
                    for node in index.iter_entries(keys):
1259
 
                        keys.remove(node[1])
1260
 
                        yield node
 
1071
        for index in self._indices:
 
1072
            if not keys:
1261
1073
                return
1262
 
            except errors.NoSuchFile:
1263
 
                self._reload_or_raise()
 
1074
            for node in index.iter_entries(keys):
 
1075
                keys.remove(node[1])
 
1076
                yield node
1264
1077
 
1265
1078
    def iter_entries_prefix(self, keys):
1266
1079
        """Iterate over keys within the index using prefix matching.
1286
1099
        if not keys:
1287
1100
            return
1288
1101
        seen_keys = set()
1289
 
        while True:
1290
 
            try:
1291
 
                for index in self._indices:
1292
 
                    for node in index.iter_entries_prefix(keys):
1293
 
                        if node[1] in seen_keys:
1294
 
                            continue
1295
 
                        seen_keys.add(node[1])
1296
 
                        yield node
1297
 
                return
1298
 
            except errors.NoSuchFile:
1299
 
                self._reload_or_raise()
 
1102
        for index in self._indices:
 
1103
            for node in index.iter_entries_prefix(keys):
 
1104
                if node[1] in seen_keys:
 
1105
                    continue
 
1106
                seen_keys.add(node[1])
 
1107
                yield node
1300
1108
 
1301
1109
    def key_count(self):
1302
1110
        """Return an estimate of the number of keys in this index.
1303
 
 
 
1111
        
1304
1112
        For CombinedGraphIndex this is approximated by the sum of the keys of
1305
1113
        the child indices. As child indices may have duplicate keys this can
1306
1114
        have a maximum error of the number of child indices * largest number of
1307
1115
        keys in any index.
1308
1116
        """
1309
 
        while True:
1310
 
            try:
1311
 
                return sum((index.key_count() for index in self._indices), 0)
1312
 
            except errors.NoSuchFile:
1313
 
                self._reload_or_raise()
1314
 
 
1315
 
    missing_keys = _missing_keys_from_parent_map
1316
 
 
1317
 
    def _reload_or_raise(self):
1318
 
        """We just got a NoSuchFile exception.
1319
 
 
1320
 
        Try to reload the indices, if it fails, just raise the current
1321
 
        exception.
1322
 
        """
1323
 
        if self._reload_func is None:
1324
 
            raise
1325
 
        exc_type, exc_value, exc_traceback = sys.exc_info()
1326
 
        trace.mutter('Trying to reload after getting exception: %s',
1327
 
                     exc_value)
1328
 
        if not self._reload_func():
1329
 
            # We tried to reload, but nothing changed, so we fail anyway
1330
 
            trace.mutter('_reload_func indicated nothing has changed.'
1331
 
                         ' Raising original exception.')
1332
 
            raise exc_type, exc_value, exc_traceback
 
1117
        return sum((index.key_count() for index in self._indices), 0)
1333
1118
 
1334
1119
    def validate(self):
1335
1120
        """Validate that everything in the index can be accessed."""
1336
 
        while True:
1337
 
            try:
1338
 
                for index in self._indices:
1339
 
                    index.validate()
1340
 
                return
1341
 
            except errors.NoSuchFile:
1342
 
                self._reload_or_raise()
 
1121
        for index in self._indices:
 
1122
            index.validate()
1343
1123
 
1344
1124
 
1345
1125
class InMemoryGraphIndex(GraphIndexBuilder):
1432
1212
                    raise errors.BadIndexKey(key)
1433
1213
                node = self._nodes[key]
1434
1214
                if node[0]:
1435
 
                    continue
 
1215
                    continue 
1436
1216
                if self.reference_lists:
1437
1217
                    yield self, key, node[2], node[1]
1438
1218
                else:
1439
1219
                    yield self, key, node[2]
1440
1220
            return
1441
 
        nodes_by_key = self._get_nodes_by_key()
1442
1221
        for key in keys:
1443
1222
            # sanity check
1444
1223
            if key[0] is None:
1446
1225
            if len(key) != self._key_length:
1447
1226
                raise errors.BadIndexKey(key)
1448
1227
            # find what it refers to:
1449
 
            key_dict = nodes_by_key
 
1228
            key_dict = self._nodes_by_key
1450
1229
            elements = list(key)
1451
1230
            # find the subdict to return
1452
1231
            try:
1463
1242
                    # can't be empty or would not exist
1464
1243
                    item, value = key_dict.iteritems().next()
1465
1244
                    if type(value) == dict:
1466
 
                        # push keys
 
1245
                        # push keys 
1467
1246
                        dicts.extend(key_dict.itervalues())
1468
1247
                    else:
1469
1248
                        # yield keys
1474
1253
 
1475
1254
    def key_count(self):
1476
1255
        """Return an estimate of the number of keys in this index.
1477
 
 
 
1256
        
1478
1257
        For InMemoryGraphIndex the estimate is exact.
1479
1258
        """
1480
1259
        return len(self._keys)
1488
1267
 
1489
1268
    Queries against this will emit queries against the adapted Graph with the
1490
1269
    prefix added, queries for all items use iter_entries_prefix. The returned
1491
 
    nodes will have their keys and node references adjusted to remove the
 
1270
    nodes will have their keys and node references adjusted to remove the 
1492
1271
    prefix. Finally, an add_nodes_callback can be supplied - when called the
1493
1272
    nodes and references being added will have prefix prepended.
1494
1273
    """
1521
1300
                    adjusted_references))
1522
1301
        except ValueError:
1523
1302
            # XXX: TODO add an explicit interface for getting the reference list
1524
 
            # status, to handle this bit of user-friendliness in the API more
 
1303
            # status, to handle this bit of user-friendliness in the API more 
1525
1304
            # explicitly.
1526
1305
            for (key, value) in nodes:
1527
1306
                translated_nodes.append((self.prefix + key, value))
1599
1378
 
1600
1379
    def key_count(self):
1601
1380
        """Return an estimate of the number of keys in this index.
1602
 
 
 
1381
        
1603
1382
        For GraphIndexPrefixAdapter this is relatively expensive - key
1604
1383
        iteration with the prefix is done.
1605
1384
        """