/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to brzlib/chk_map.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-21 12:41:27 UTC
  • mto: This revision was merged to the branch mainline in revision 6623.
  • Revision ID: jelmer@jelmer.uk-20170521124127-iv8etg0vwymyai6y
s/bzr/brz/ in apport config.

Show diffs side-by-side

added added

removed removed

Lines of Context:
37
37
 
38
38
"""
39
39
 
 
40
from __future__ import absolute_import
 
41
 
40
42
import heapq
41
43
import threading
42
44
 
43
 
from .. import (
 
45
from brzlib import lazy_import
 
46
lazy_import.lazy_import(globals(), """
 
47
from brzlib import (
 
48
    errors,
 
49
    )
 
50
""")
 
51
from brzlib import (
44
52
    errors,
45
53
    lru_cache,
46
54
    osutils,
48
56
    static_tuple,
49
57
    trace,
50
58
    )
51
 
from ..static_tuple import StaticTuple
 
59
from brzlib.static_tuple import StaticTuple
52
60
 
53
61
# approx 4MB
54
62
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
55
63
# out, it takes 3.1MB to cache the layer.
56
 
_PAGE_CACHE_SIZE = 4 * 1024 * 1024
 
64
_PAGE_CACHE_SIZE = 4*1024*1024
57
65
# Per thread caches for 2 reasons:
58
66
# - in the server we may be serving very different content, so we get less
59
67
#   cache thrashing.
62
70
# The page cache.
63
71
_thread_caches.page_cache = None
64
72
 
65
 
 
66
73
def _get_cache():
67
74
    """Get the per-thread page cache.
68
75
 
89
96
 
90
97
def _search_key_plain(key):
91
98
    """Map the key tuple into a search string that just uses the key bytes."""
92
 
    return b'\x00'.join(key)
 
99
    return '\x00'.join(key)
93
100
 
94
101
 
95
102
search_key_registry = registry.Registry()
96
 
search_key_registry.register(b'plain', _search_key_plain)
 
103
search_key_registry.register('plain', _search_key_plain)
97
104
 
98
105
 
99
106
class CHKMap(object):
131
138
        has_deletes = False
132
139
        # Check preconditions first.
133
140
        as_st = StaticTuple.from_sequence
134
 
        new_items = {as_st(key) for (old, key, value) in delta
135
 
                     if key is not None and old is None}
 
141
        new_items = set([as_st(key) for (old, key, value) in delta
 
142
                         if key is not None and old is None])
136
143
        existing_new = list(self.iteritems(key_filter=new_items))
137
144
        if existing_new:
138
145
            raise errors.InconsistentDeltaDelta(delta,
139
 
                                                "New items are already in the map %r." % existing_new)
 
146
                "New items are already in the map %r." % existing_new)
140
147
        # Now apply changes.
141
148
        for old, new, value in delta:
142
149
            if old is not None and old != new:
151
158
 
152
159
    def _ensure_root(self):
153
160
        """Ensure that the root node is an object not a key."""
154
 
        if isinstance(self._root_node, StaticTuple):
 
161
        if type(self._root_node) is StaticTuple:
155
162
            # Demand-load the root
156
163
            self._root_node = self._get_node(self._root_node)
157
164
 
165
172
        :param node: A tuple key or node object.
166
173
        :return: A node object.
167
174
        """
168
 
        if isinstance(node, StaticTuple):
 
175
        if type(node) is StaticTuple:
169
176
            bytes = self._read_bytes(node)
170
177
            return _deserialise(bytes, node,
171
 
                                search_key_func=self._search_key_func)
 
178
                search_key_func=self._search_key_func)
172
179
        else:
173
180
            return node
174
181
 
177
184
            return _get_cache()[key]
178
185
        except KeyError:
179
186
            stream = self._store.get_record_stream([key], 'unordered', True)
180
 
            bytes = next(stream).get_bytes_as('fulltext')
 
187
            bytes = stream.next().get_bytes_as('fulltext')
181
188
            _get_cache()[key] = bytes
182
189
            return bytes
183
190
 
184
 
    def _dump_tree(self, include_keys=False, encoding='utf-8'):
 
191
    def _dump_tree(self, include_keys=False):
185
192
        """Return the tree in a string representation."""
186
193
        self._ensure_root()
187
 
        def decode(x): return x.decode(encoding)
188
 
        res = self._dump_tree_node(self._root_node, prefix=b'', indent='',
189
 
                                   decode=decode, include_keys=include_keys)
190
 
        res.append('')  # Give a trailing '\n'
 
194
        res = self._dump_tree_node(self._root_node, prefix='', indent='',
 
195
                                   include_keys=include_keys)
 
196
        res.append('') # Give a trailing '\n'
191
197
        return '\n'.join(res)
192
198
 
193
 
    def _dump_tree_node(self, node, prefix, indent, decode, include_keys=True):
 
199
    def _dump_tree_node(self, node, prefix, indent, include_keys=True):
194
200
        """For this node and all children, generate a string representation."""
195
201
        result = []
196
202
        if not include_keys:
198
204
        else:
199
205
            node_key = node.key()
200
206
            if node_key is not None:
201
 
                key_str = ' %s' % (decode(node_key[0]),)
 
207
                key_str = ' %s' % (node_key[0],)
202
208
            else:
203
209
                key_str = ' None'
204
 
        result.append('%s%r %s%s' % (indent, decode(prefix), node.__class__.__name__,
 
210
        result.append('%s%r %s%s' % (indent, prefix, node.__class__.__name__,
205
211
                                     key_str))
206
 
        if isinstance(node, InternalNode):
 
212
        if type(node) is InternalNode:
207
213
            # Trigger all child nodes to get loaded
208
214
            list(node._iter_nodes(self._store))
209
 
            for prefix, sub in sorted(node._items.items()):
 
215
            for prefix, sub in sorted(node._items.iteritems()):
210
216
                result.extend(self._dump_tree_node(sub, prefix, indent + '  ',
211
 
                                                   decode=decode, include_keys=include_keys))
 
217
                                                   include_keys=include_keys))
212
218
        else:
213
 
            for key, value in sorted(node._items.items()):
 
219
            for key, value in sorted(node._items.iteritems()):
214
220
                # Don't use prefix nor indent here to line up when used in
215
221
                # tests in conjunction with assertEqualDiff
216
 
                result.append('      %r %r' % (
217
 
                    tuple([decode(ke) for ke in key]), decode(value)))
 
222
                result.append('      %r %r' % (tuple(key), value))
218
223
        return result
219
224
 
220
225
    @classmethod
221
226
    def from_dict(klass, store, initial_value, maximum_size=0, key_width=1,
222
 
                  search_key_func=None):
 
227
        search_key_func=None):
223
228
        """Create a CHKMap in store with initial_value as the content.
224
229
 
225
230
        :param store: The store to record initial_value in, a VersionedFiles
236
241
        :return: The root chk of the resulting CHKMap.
237
242
        """
238
243
        root_key = klass._create_directly(store, initial_value,
239
 
                                          maximum_size=maximum_size, key_width=key_width,
240
 
                                          search_key_func=search_key_func)
241
 
        if not isinstance(root_key, StaticTuple):
 
244
            maximum_size=maximum_size, key_width=key_width,
 
245
            search_key_func=search_key_func)
 
246
        if type(root_key) is not StaticTuple:
242
247
            raise AssertionError('we got a %s instead of a StaticTuple'
243
248
                                 % (type(root_key),))
244
249
        return root_key
262
267
        node.set_maximum_size(maximum_size)
263
268
        node._key_width = key_width
264
269
        as_st = StaticTuple.from_sequence
265
 
        node._items = dict((as_st(key), val)
266
 
                           for key, val in initial_value.items())
267
 
        node._raw_size = sum(node._key_value_len(key, value)
268
 
                             for key, value in node._items.items())
 
270
        node._items = dict([(as_st(key), val) for key, val
 
271
                                               in initial_value.iteritems()])
 
272
        node._raw_size = sum([node._key_value_len(key, value)
 
273
                              for key,value in node._items.iteritems()])
269
274
        node._len = len(node._items)
270
275
        node._compute_search_prefix()
271
276
        node._compute_serialised_prefix()
272
 
        if (node._len > 1 and
273
 
            maximum_size and
274
 
                node._current_size() > maximum_size):
 
277
        if (node._len > 1
 
278
            and maximum_size
 
279
            and node._current_size() > maximum_size):
275
280
            prefix, node_details = node._split(store)
276
281
            if len(node_details) == 1:
277
282
                raise AssertionError('Failed to split using node._split')
323
328
        # key_path (a list of tuples, tail-sharing down the tree.)
324
329
        self_pending = []
325
330
        basis_pending = []
326
 
 
327
331
        def process_node(node, path, a_map, pending):
328
332
            # take a node and expand it
329
333
            node = a_map._get_node(node)
330
 
            if isinstance(node, LeafNode):
 
334
            if type(node) == LeafNode:
331
335
                path = (node._key, path)
332
336
                for key, value in node._items.items():
333
337
                    # For a LeafNode, the key is a serialized_key, rather than
339
343
                path = (node._key, path)
340
344
                for prefix, child in node._items.items():
341
345
                    heapq.heappush(pending, (prefix, None, child, path))
342
 
 
343
346
        def process_common_internal_nodes(self_node, basis_node):
344
347
            self_items = set(self_node._items.items())
345
348
            basis_items = set(basis_node._items.items())
349
352
            path = (basis_node._key, None)
350
353
            for prefix, child in basis_items - self_items:
351
354
                heapq.heappush(basis_pending, (prefix, None, child, path))
352
 
 
353
355
        def process_common_leaf_nodes(self_node, basis_node):
354
356
            self_items = set(self_node._items.items())
355
357
            basis_items = set(basis_node._items.items())
361
363
            for key, value in basis_items - self_items:
362
364
                prefix = basis._search_key_func(key)
363
365
                heapq.heappush(basis_pending, (prefix, key, value, path))
364
 
 
365
366
        def process_common_prefix_nodes(self_node, self_path,
366
367
                                        basis_node, basis_path):
367
368
            # Would it be more efficient if we could request both at the same
368
369
            # time?
369
370
            self_node = self._get_node(self_node)
370
371
            basis_node = basis._get_node(basis_node)
371
 
            if (isinstance(self_node, InternalNode) and
372
 
                    isinstance(basis_node, InternalNode)):
 
372
            if (type(self_node) == InternalNode
 
373
                and type(basis_node) == InternalNode):
373
374
                # Matching internal nodes
374
375
                process_common_internal_nodes(self_node, basis_node)
375
 
            elif (isinstance(self_node, LeafNode) and
376
 
                  isinstance(basis_node, LeafNode)):
 
376
            elif (type(self_node) == LeafNode
 
377
                  and type(basis_node) == LeafNode):
377
378
                process_common_leaf_nodes(self_node, basis_node)
378
379
            else:
379
380
                process_node(self_node, self_path, self, self_pending)
382
383
        self_seen = set()
383
384
        basis_seen = set()
384
385
        excluded_keys = set()
385
 
 
386
386
        def check_excluded(key_path):
387
387
            # Note that this is N^2, it depends on us trimming trees
388
388
            # aggressively to not become slow.
389
389
            # A better implementation would probably have a reverse map
390
390
            # back to the children of a node, and jump straight to it when
391
391
            # a common node is detected, the proceed to remove the already
392
 
            # pending children. breezy.graph has a searcher module with a
 
392
            # pending children. brzlib.graph has a searcher module with a
393
393
            # similar problem.
394
394
            while key_path is not None:
395
395
                key, key_path = key_path
472
472
                        basis_details = heapq.heappop(basis_pending)
473
473
                        if self_details[2] != basis_details[2]:
474
474
                            yield (self_details[1],
475
 
                                   basis_details[2], self_details[2])
 
475
                                basis_details[2], self_details[2])
476
476
                        continue
477
477
                    # At least one side wasn't a simple value
478
 
                    if (self._node_key(self_pending[0][2])
479
 
                            == self._node_key(basis_pending[0][2])):
 
478
                    if (self._node_key(self_pending[0][2]) ==
 
479
                        self._node_key(basis_pending[0][2])):
480
480
                        # Identical pointers, skip (and don't bother adding to
481
481
                        # excluded, it won't turn up again.
482
482
                        heapq.heappop(self_pending)
519
519
 
520
520
    def key(self):
521
521
        """Return the key for this map."""
522
 
        if isinstance(self._root_node, StaticTuple):
 
522
        if type(self._root_node) is StaticTuple:
523
523
            return self._root_node
524
524
        else:
525
525
            return self._root_node._key
530
530
 
531
531
    def map(self, key, value):
532
532
        """Map a key tuple to value.
533
 
 
 
533
        
534
534
        :param key: A key to map.
535
535
        :param value: The value to assign to key.
536
536
        """
542
542
            self._root_node = node_details[0][1]
543
543
        else:
544
544
            self._root_node = InternalNode(prefix,
545
 
                                           search_key_func=self._search_key_func)
 
545
                                search_key_func=self._search_key_func)
546
546
            self._root_node.set_maximum_size(node_details[0][1].maximum_size)
547
547
            self._root_node._key_width = node_details[0][1]._key_width
548
548
            for split, node in node_details:
550
550
 
551
551
    def _node_key(self, node):
552
552
        """Get the key for a node whether it's a tuple or node."""
553
 
        if isinstance(node, tuple):
 
553
        if type(node) is tuple:
554
554
            node = StaticTuple.from_sequence(node)
555
 
        if isinstance(node, StaticTuple):
 
555
        if type(node) is StaticTuple:
556
556
            return node
557
557
        else:
558
558
            return node._key
561
561
        """remove key from the map."""
562
562
        key = StaticTuple.from_sequence(key)
563
563
        self._ensure_root()
564
 
        if isinstance(self._root_node, InternalNode):
 
564
        if type(self._root_node) is InternalNode:
565
565
            unmapped = self._root_node.unmap(self._store, key,
566
 
                                             check_remap=check_remap)
 
566
                check_remap=check_remap)
567
567
        else:
568
568
            unmapped = self._root_node.unmap(self._store, key)
569
569
        self._root_node = unmapped
571
571
    def _check_remap(self):
572
572
        """Check if nodes can be collapsed."""
573
573
        self._ensure_root()
574
 
        if isinstance(self._root_node, InternalNode):
 
574
        if type(self._root_node) is InternalNode:
575
575
            self._root_node = self._root_node._check_remap(self._store)
576
576
 
577
577
    def _save(self):
579
579
 
580
580
        :return: The key of the root node.
581
581
        """
582
 
        if isinstance(self._root_node, StaticTuple):
 
582
        if type(self._root_node) is StaticTuple:
583
583
            # Already saved.
584
584
            return self._root_node
585
585
        keys = list(self._root_node.serialise(self._store))
595
595
 
596
596
    __slots__ = ('_key', '_len', '_maximum_size', '_key_width',
597
597
                 '_raw_size', '_items', '_search_prefix', '_search_key_func'
598
 
                 )
 
598
                )
599
599
 
600
600
    def __init__(self, key_width=1):
601
601
        """Create a node.
657
657
            if left != right:
658
658
                pos -= 1
659
659
                break
660
 
        common = prefix[:pos + 1]
 
660
        common = prefix[:pos+1]
661
661
        return common
662
662
 
663
663
    @classmethod
676
676
            if not common_prefix:
677
677
                # if common_prefix is the empty string, then we know it won't
678
678
                # change further
679
 
                return b''
 
679
                return ''
680
680
        return common_prefix
681
681
 
682
682
 
683
683
# Singleton indicating we have not computed _search_prefix yet
684
684
_unknown = object()
685
685
 
686
 
 
687
686
class LeafNode(Node):
688
687
    """A node containing actual key:value pairs.
689
688
 
710
709
        return \
711
710
            '%s(key:%s len:%s size:%s max:%s prefix:%s keywidth:%s items:%s)' \
712
711
            % (self.__class__.__name__, self._key, self._len, self._raw_size,
713
 
               self._maximum_size, self._search_prefix, self._key_width, items_str)
 
712
            self._maximum_size, self._search_prefix, self._key_width, items_str)
714
713
 
715
714
    def _current_size(self):
716
715
        """Answer the current serialised size of this node.
727
726
            # entry lines
728
727
            prefix_len = len(self._common_serialised_prefix)
729
728
            bytes_for_items = (self._raw_size - (prefix_len * self._len))
730
 
        return (9 +  # 'chkleaf:\n' +
731
 
                len(str(self._maximum_size)) + 1 +
732
 
                len(str(self._key_width)) + 1 +
733
 
                len(str(self._len)) + 1 +
734
 
                prefix_len + 1 +
735
 
                bytes_for_items)
 
729
        return (9 # 'chkleaf:\n'
 
730
            + len(str(self._maximum_size)) + 1
 
731
            + len(str(self._key_width)) + 1
 
732
            + len(str(self._len)) + 1
 
733
            + prefix_len + 1
 
734
            + bytes_for_items)
736
735
 
737
736
    @classmethod
738
737
    def deserialise(klass, bytes, key, search_key_func=None):
767
766
                        pass
768
767
                else:
769
768
                    # Short items, we need to match based on a prefix
770
 
                    filters.setdefault(len(key), set()).add(key)
 
769
                    length_filter = filters.setdefault(len(key), set())
 
770
                    length_filter.add(key)
771
771
            if filters:
772
 
                filters_itemview = filters.items()
773
 
                for item in self._items.items():
774
 
                    for length, length_filter in filters_itemview:
 
772
                filters = filters.items()
 
773
                for item in self._items.iteritems():
 
774
                    for length, length_filter in filters:
775
775
                        if item[0][:length] in length_filter:
776
776
                            yield item
777
777
                            break
778
778
        else:
779
 
            yield from self._items.items()
 
779
            for item in self._items.iteritems():
 
780
                yield item
780
781
 
781
782
    def _key_value_len(self, key, value):
782
783
        # TODO: Should probably be done without actually joining the key, but
783
784
        #       then that can be done via the C extension
784
 
        return (len(self._serialise_key(key)) + 1 +
785
 
                len(b'%d' % value.count(b'\n')) + 1 +
786
 
                len(value) + 1)
 
785
        return (len(self._serialise_key(key)) + 1
 
786
                + len(str(value.count('\n'))) + 1
 
787
                + len(value) + 1)
787
788
 
788
789
    def _search_key(self, key):
789
790
        return self._search_key_func(key)
813
814
        else:
814
815
            self._search_prefix = self.common_prefix(
815
816
                self._search_prefix, search_key)
816
 
        if (self._len > 1 and
817
 
            self._maximum_size and
818
 
                self._current_size() > self._maximum_size):
 
817
        if (self._len > 1
 
818
            and self._maximum_size
 
819
            and self._current_size() > self._maximum_size):
819
820
            # Check to see if all of the search_keys for this node are
820
821
            # identical. We allow the node to grow under that circumstance
821
822
            # (we could track this as common state, but it is infrequent)
822
 
            if (search_key != self._search_prefix or
823
 
                    not self._are_search_keys_identical()):
 
823
            if (search_key != self._search_prefix
 
824
                or not self._are_search_keys_identical()):
824
825
                return True
825
826
        return False
826
827
 
837
838
        common_prefix = self._search_prefix
838
839
        split_at = len(common_prefix) + 1
839
840
        result = {}
840
 
        for key, value in self._items.items():
 
841
        for key, value in self._items.iteritems():
841
842
            search_key = self._search_key(key)
842
843
            prefix = search_key[:split_at]
843
844
            # TODO: Generally only 1 key can be exactly the right length,
849
850
            #       may get a '\00' node anywhere, but won't have keys of
850
851
            #       different lengths.
851
852
            if len(prefix) < split_at:
852
 
                prefix += b'\x00' * (split_at - len(prefix))
 
853
                prefix += '\x00'*(split_at - len(prefix))
853
854
            if prefix not in result:
854
855
                node = LeafNode(search_key_func=self._search_key_func)
855
856
                node.set_maximum_size(self._maximum_size)
864
865
                    # path
865
866
                    result.pop(prefix)
866
867
                new_node = InternalNode(sub_prefix,
867
 
                                        search_key_func=self._search_key_func)
 
868
                    search_key_func=self._search_key_func)
868
869
                new_node.set_maximum_size(self._maximum_size)
869
870
                new_node._key_width = self._key_width
870
871
                for split, node in node_details:
871
872
                    new_node.add_node(split, node)
872
873
                result[prefix] = new_node
873
 
        return common_prefix, list(result.items())
 
874
        return common_prefix, result.items()
874
875
 
875
876
    def map(self, store, key, value):
876
877
        """Map key to value."""
883
884
        else:
884
885
            if self._search_prefix is _unknown:
885
886
                raise AssertionError('%r must be known' % self._search_prefix)
886
 
            return self._search_prefix, [(b"", self)]
 
887
            return self._search_prefix, [("", self)]
887
888
 
888
 
    _serialise_key = b'\x00'.join
 
889
    _serialise_key = '\x00'.join
889
890
 
890
891
    def serialise(self, store):
891
892
        """Serialise the LeafNode to store.
893
894
        :param store: A VersionedFiles honouring the CHK extensions.
894
895
        :return: An iterable of the keys inserted by this operation.
895
896
        """
896
 
        lines = [b"chkleaf:\n"]
897
 
        lines.append(b"%d\n" % self._maximum_size)
898
 
        lines.append(b"%d\n" % self._key_width)
899
 
        lines.append(b"%d\n" % self._len)
 
897
        lines = ["chkleaf:\n"]
 
898
        lines.append("%d\n" % self._maximum_size)
 
899
        lines.append("%d\n" % self._key_width)
 
900
        lines.append("%d\n" % self._len)
900
901
        if self._common_serialised_prefix is None:
901
 
            lines.append(b'\n')
 
902
            lines.append('\n')
902
903
            if len(self._items) != 0:
903
904
                raise AssertionError('If _common_serialised_prefix is None'
904
 
                                     ' we should have no items')
 
905
                    ' we should have no items')
905
906
        else:
906
 
            lines.append(b'%s\n' % (self._common_serialised_prefix,))
 
907
            lines.append('%s\n' % (self._common_serialised_prefix,))
907
908
            prefix_len = len(self._common_serialised_prefix)
908
909
        for key, value in sorted(self._items.items()):
909
910
            # Always add a final newline
910
 
            value_lines = osutils.chunks_to_lines([value + b'\n'])
911
 
            serialized = b"%s\x00%d\n" % (self._serialise_key(key),
912
 
                                          len(value_lines))
 
911
            value_lines = osutils.chunks_to_lines([value + '\n'])
 
912
            serialized = "%s\x00%s\n" % (self._serialise_key(key),
 
913
                                         len(value_lines))
913
914
            if not serialized.startswith(self._common_serialised_prefix):
914
915
                raise AssertionError('We thought the common prefix was %r'
915
 
                                     ' but entry %r does not have it in common'
916
 
                                     % (self._common_serialised_prefix, serialized))
 
916
                    ' but entry %r does not have it in common'
 
917
                    % (self._common_serialised_prefix, serialized))
917
918
            lines.append(serialized[prefix_len:])
918
919
            lines.extend(value_lines)
919
920
        sha1, _, _ = store.add_lines((None,), (), lines)
920
 
        self._key = StaticTuple(b"sha1:" + sha1,).intern()
921
 
        data = b''.join(lines)
922
 
        if len(data) != self._current_size():
 
921
        self._key = StaticTuple("sha1:" + sha1,).intern()
 
922
        bytes = ''.join(lines)
 
923
        if len(bytes) != self._current_size():
923
924
            raise AssertionError('Invalid _current_size')
924
 
        _get_cache()[self._key] = data
 
925
        _get_cache()[self._key] = bytes
925
926
        return [self._key]
926
927
 
927
928
    def refs(self):
993
994
 
994
995
    __slots__ = ('_node_width',)
995
996
 
996
 
    def __init__(self, prefix=b'', search_key_func=None):
 
997
    def __init__(self, prefix='', search_key_func=None):
997
998
        Node.__init__(self)
998
999
        # The size of an internalnode with default values and no children.
999
1000
        # How many octets key prefixes within this node are.
1014
1015
            raise AssertionError("_search_prefix should not be None")
1015
1016
        if not prefix.startswith(self._search_prefix):
1016
1017
            raise AssertionError("prefixes mismatch: %s must start with %s"
1017
 
                                 % (prefix, self._search_prefix))
 
1018
                % (prefix,self._search_prefix))
1018
1019
        if len(prefix) != len(self._search_prefix) + 1:
1019
1020
            raise AssertionError("prefix wrong length: len(%s) is not %d" %
1020
 
                                 (prefix, len(self._search_prefix) + 1))
 
1021
                (prefix, len(self._search_prefix) + 1))
1021
1022
        self._len += len(node)
1022
1023
        if not len(self._items):
1023
1024
            self._node_width = len(prefix)
1024
1025
        if self._node_width != len(self._search_prefix) + 1:
1025
1026
            raise AssertionError("node width mismatch: %d is not %d" %
1026
 
                                 (self._node_width, len(self._search_prefix) + 1))
 
1027
                (self._node_width, len(self._search_prefix) + 1))
1027
1028
        self._items[prefix] = node
1028
1029
        self._key = None
1029
1030
 
1030
1031
    def _current_size(self):
1031
1032
        """Answer the current serialised size of this node."""
1032
 
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width))
1033
 
                + len(str(self._maximum_size)))
 
1033
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width)) +
 
1034
            len(str(self._maximum_size)))
1034
1035
 
1035
1036
    @classmethod
1036
1037
    def deserialise(klass, bytes, key, search_key_func=None):
1070
1071
            # yielding all nodes, yield whatever we have, and queue up a read
1071
1072
            # for whatever we are missing
1072
1073
            shortcut = True
1073
 
            for prefix, node in self._items.items():
 
1074
            for prefix, node in self._items.iteritems():
1074
1075
                if node.__class__ is StaticTuple:
1075
1076
                    keys[node] = (prefix, None)
1076
1077
                else:
1121
1122
            for key in key_filter:
1122
1123
                search_prefix = self._search_prefix_filter(key)
1123
1124
                length_filter = length_filters.setdefault(
1124
 
                    len(search_prefix), set())
 
1125
                                    len(search_prefix), set())
1125
1126
                length_filter.add(search_prefix)
1126
1127
                prefix_to_keys.setdefault(search_prefix, []).append(key)
1127
1128
 
1128
 
            if (self._node_width in length_filters and
1129
 
                    len(length_filters) == 1):
 
1129
            if (self._node_width in length_filters
 
1130
                and len(length_filters) == 1):
1130
1131
                # all of the search prefixes match exactly _node_width. This
1131
1132
                # means that everything is an exact match, and we can do a
1132
1133
                # lookup into self._items, rather than iterating over the items
1146
1147
            else:
1147
1148
                # The slow way. We walk every item in self._items, and check to
1148
1149
                # see if there are any matches
1149
 
                length_filters_itemview = length_filters.items()
1150
 
                for prefix, node in self._items.items():
 
1150
                length_filters = length_filters.items()
 
1151
                for prefix, node in self._items.iteritems():
1151
1152
                    node_key_filter = []
1152
 
                    for length, length_filter in length_filters_itemview:
 
1153
                    for length, length_filter in length_filters:
1153
1154
                        sub_prefix = prefix[:length]
1154
1155
                        if sub_prefix in length_filter:
1155
1156
                            node_key_filter.extend(prefix_to_keys[sub_prefix])
1156
 
                    if node_key_filter:  # this key matched something, yield it
 
1157
                    if node_key_filter: # this key matched something, yield it
1157
1158
                        if node.__class__ is StaticTuple:
1158
1159
                            keys[node] = (prefix, node_key_filter)
1159
1160
                        else:
1168
1169
                    continue
1169
1170
                else:
1170
1171
                    node = _deserialise(bytes, key,
1171
 
                                        search_key_func=self._search_key_func)
 
1172
                        search_key_func=self._search_key_func)
1172
1173
                    prefix, node_key_filter = keys[key]
1173
1174
                    self._items[prefix] = node
1174
1175
                    found_keys.add(key)
1190
1191
                for record in stream:
1191
1192
                    bytes = record.get_bytes_as('fulltext')
1192
1193
                    node = _deserialise(bytes, record.key,
1193
 
                                        search_key_func=self._search_key_func)
 
1194
                        search_key_func=self._search_key_func)
1194
1195
                    prefix, node_key_filter = keys[record.key]
1195
1196
                    node_and_filters.append((node, node_key_filter))
1196
1197
                    self._items[prefix] = node
1205
1206
        search_key = self._search_key(key)
1206
1207
        if self._node_width != len(self._search_prefix) + 1:
1207
1208
            raise AssertionError("node width mismatch: %d is not %d" %
1208
 
                                 (self._node_width, len(self._search_prefix) + 1))
 
1209
                (self._node_width, len(self._search_prefix) + 1))
1209
1210
        if not search_key.startswith(self._search_prefix):
1210
1211
            # This key doesn't fit in this index, so we need to split at the
1211
1212
            # point where it would fit, insert self into that internal node,
1213
1214
            new_prefix = self.common_prefix(self._search_prefix,
1214
1215
                                            search_key)
1215
1216
            new_parent = InternalNode(new_prefix,
1216
 
                                      search_key_func=self._search_key_func)
 
1217
                search_key_func=self._search_key_func)
1217
1218
            new_parent.set_maximum_size(self._maximum_size)
1218
1219
            new_parent._key_width = self._key_width
1219
 
            new_parent.add_node(self._search_prefix[:len(new_prefix) + 1],
 
1220
            new_parent.add_node(self._search_prefix[:len(new_prefix)+1],
1220
1221
                                self)
1221
1222
            return new_parent.map(store, key, value)
1222
 
        children = [node for node, _ in self._iter_nodes(
1223
 
            store, key_filter=[key])]
 
1223
        children = [node for node, _
 
1224
                          in self._iter_nodes(store, key_filter=[key])]
1224
1225
        if children:
1225
1226
            child = children[0]
1226
1227
        else:
1227
1228
            # new child needed:
1228
1229
            child = self._new_child(search_key, LeafNode)
1229
1230
        old_len = len(child)
1230
 
        if isinstance(child, LeafNode):
 
1231
        if type(child) is LeafNode:
1231
1232
            old_size = child._current_size()
1232
1233
        else:
1233
1234
            old_size = None
1239
1240
            self._items[search_key] = child
1240
1241
            self._key = None
1241
1242
            new_node = self
1242
 
            if isinstance(child, LeafNode):
 
1243
            if type(child) is LeafNode:
1243
1244
                if old_size is None:
1244
1245
                    # The old node was an InternalNode which means it has now
1245
1246
                    # collapsed, so we need to check if it will chain to a
1255
1256
                    # amount is over a configurable limit.
1256
1257
                    new_size = child._current_size()
1257
1258
                    shrinkage = old_size - new_size
1258
 
                    if (shrinkage > 0 and new_size < _INTERESTING_NEW_SIZE or
1259
 
                            shrinkage > _INTERESTING_SHRINKAGE_LIMIT):
 
1259
                    if (shrinkage > 0 and new_size < _INTERESTING_NEW_SIZE
 
1260
                        or shrinkage > _INTERESTING_SHRINKAGE_LIMIT):
1260
1261
                        trace.mutter(
1261
1262
                            "checking remap as size shrunk by %d to be %d",
1262
1263
                            shrinkage, new_size)
1263
1264
                        new_node = self._check_remap(store)
1264
1265
            if new_node._search_prefix is None:
1265
1266
                raise AssertionError("_search_prefix should not be None")
1266
 
            return new_node._search_prefix, [(b'', new_node)]
 
1267
            return new_node._search_prefix, [('', new_node)]
1267
1268
        # child has overflown - create a new intermediate node.
1268
1269
        # XXX: This is where we might want to try and expand our depth
1269
1270
        # to refer to more bytes of every child (which would give us
1274
1275
            child.add_node(split, node)
1275
1276
        self._len = self._len - old_len + len(child)
1276
1277
        self._key = None
1277
 
        return self._search_prefix, [(b"", self)]
 
1278
        return self._search_prefix, [("", self)]
1278
1279
 
1279
1280
    def _new_child(self, search_key, klass):
1280
1281
        """Create a new child node of type klass."""
1291
1292
        :param store: A VersionedFiles honouring the CHK extensions.
1292
1293
        :return: An iterable of the keys inserted by this operation.
1293
1294
        """
1294
 
        for node in self._items.values():
1295
 
            if isinstance(node, StaticTuple):
 
1295
        for node in self._items.itervalues():
 
1296
            if type(node) is StaticTuple:
1296
1297
                # Never deserialised.
1297
1298
                continue
1298
1299
            if node._key is not None:
1300
1301
                continue
1301
1302
            for key in node.serialise(store):
1302
1303
                yield key
1303
 
        lines = [b"chknode:\n"]
1304
 
        lines.append(b"%d\n" % self._maximum_size)
1305
 
        lines.append(b"%d\n" % self._key_width)
1306
 
        lines.append(b"%d\n" % self._len)
 
1304
        lines = ["chknode:\n"]
 
1305
        lines.append("%d\n" % self._maximum_size)
 
1306
        lines.append("%d\n" % self._key_width)
 
1307
        lines.append("%d\n" % self._len)
1307
1308
        if self._search_prefix is None:
1308
1309
            raise AssertionError("_search_prefix should not be None")
1309
 
        lines.append(b'%s\n' % (self._search_prefix,))
 
1310
        lines.append('%s\n' % (self._search_prefix,))
1310
1311
        prefix_len = len(self._search_prefix)
1311
1312
        for prefix, node in sorted(self._items.items()):
1312
 
            if isinstance(node, StaticTuple):
 
1313
            if type(node) is StaticTuple:
1313
1314
                key = node[0]
1314
1315
            else:
1315
1316
                key = node._key[0]
1316
 
            serialised = b"%s\x00%s\n" % (prefix, key)
 
1317
            serialised = "%s\x00%s\n" % (prefix, key)
1317
1318
            if not serialised.startswith(self._search_prefix):
1318
1319
                raise AssertionError("prefixes mismatch: %s must start with %s"
1319
 
                                     % (serialised, self._search_prefix))
 
1320
                    % (serialised, self._search_prefix))
1320
1321
            lines.append(serialised[prefix_len:])
1321
1322
        sha1, _, _ = store.add_lines((None,), (), lines)
1322
 
        self._key = StaticTuple(b"sha1:" + sha1,).intern()
1323
 
        _get_cache()[self._key] = b''.join(lines)
 
1323
        self._key = StaticTuple("sha1:" + sha1,).intern()
 
1324
        _get_cache()[self._key] = ''.join(lines)
1324
1325
        yield self._key
1325
1326
 
1326
1327
    def _search_key(self, key):
1327
1328
        """Return the serialised key for key in this node."""
1328
1329
        # search keys are fixed width. All will be self._node_width wide, so we
1329
1330
        # pad as necessary.
1330
 
        return (self._search_key_func(key) + b'\x00' * self._node_width)[:self._node_width]
 
1331
        return (self._search_key_func(key) + '\x00'*self._node_width)[:self._node_width]
1331
1332
 
1332
1333
    def _search_prefix_filter(self, key):
1333
1334
        """Serialise key for use as a prefix filter in iteritems."""
1341
1342
            prefix for reaching node.
1342
1343
        """
1343
1344
        if offset >= self._node_width:
1344
 
            for node in valueview(self._items):
 
1345
            for node in self._items.values():
1345
1346
                for result in node._split(offset):
1346
1347
                    yield result
 
1348
            return
 
1349
        for key, node in self._items.items():
 
1350
            pass
1347
1351
 
1348
1352
    def refs(self):
1349
1353
        """Return the references to other CHK's held by this node."""
1350
1354
        if self._key is None:
1351
1355
            raise AssertionError("unserialised nodes have no refs.")
1352
1356
        refs = []
1353
 
        for value in self._items.values():
1354
 
            if isinstance(value, StaticTuple):
 
1357
        for value in self._items.itervalues():
 
1358
            if type(value) is StaticTuple:
1355
1359
                refs.append(value)
1356
1360
            else:
1357
1361
                refs.append(value.key())
1371
1375
        if not len(self._items):
1372
1376
            raise AssertionError("can't unmap in an empty InternalNode.")
1373
1377
        children = [node for node, _
1374
 
                    in self._iter_nodes(store, key_filter=[key])]
 
1378
                          in self._iter_nodes(store, key_filter=[key])]
1375
1379
        if children:
1376
1380
            child = children[0]
1377
1381
        else:
1389
1393
            self._items[search_key] = unmapped
1390
1394
        if len(self._items) == 1:
1391
1395
            # this node is no longer needed:
1392
 
            return list(self._items.values())[0]
1393
 
        if isinstance(unmapped, InternalNode):
 
1396
            return self._items.values()[0]
 
1397
        if type(unmapped) is InternalNode:
1394
1398
            return self
1395
1399
        if check_remap:
1396
1400
            return self._check_remap(store)
1436
1440
        #   c) With 255-way fan out, we don't want to read all 255 and destroy
1437
1441
        #      the page cache, just to determine that we really don't need it.
1438
1442
        for node, _ in self._iter_nodes(store, batch_size=16):
1439
 
            if isinstance(node, InternalNode):
 
1443
            if type(node) is InternalNode:
1440
1444
                # Without looking at any leaf nodes, we are sure
1441
1445
                return self
1442
 
            for key, value in node._items.items():
 
1446
            for key, value in node._items.iteritems():
1443
1447
                if new_leaf._map_no_split(key, value):
1444
1448
                    return self
1445
1449
        trace.mutter("remap generated a new LeafNode")
1446
1450
        return new_leaf
1447
1451
 
1448
1452
 
1449
 
def _deserialise(data, key, search_key_func):
 
1453
def _deserialise(bytes, key, search_key_func):
1450
1454
    """Helper for repositorydetails - convert bytes to a node."""
1451
 
    if data.startswith(b"chkleaf:\n"):
1452
 
        node = LeafNode.deserialise(data, key, search_key_func=search_key_func)
1453
 
    elif data.startswith(b"chknode:\n"):
1454
 
        node = InternalNode.deserialise(data, key,
1455
 
                                        search_key_func=search_key_func)
 
1455
    if bytes.startswith("chkleaf:\n"):
 
1456
        node = LeafNode.deserialise(bytes, key, search_key_func=search_key_func)
 
1457
    elif bytes.startswith("chknode:\n"):
 
1458
        node = InternalNode.deserialise(bytes, key,
 
1459
            search_key_func=search_key_func)
1456
1460
    else:
1457
1461
        raise AssertionError("Unknown node type.")
1458
1462
    return node
1521
1525
            bytes = record.get_bytes_as('fulltext')
1522
1526
            node = _deserialise(bytes, record.key,
1523
1527
                                search_key_func=self._search_key_func)
1524
 
            if isinstance(node, InternalNode):
 
1528
            if type(node) is InternalNode:
1525
1529
                # Note we don't have to do node.refs() because we know that
1526
1530
                # there are no children that have been pushed into this node
1527
1531
                # Note: Using as_st() here seemed to save 1.2MB, which would
1528
1532
                #       indicate that we keep 100k prefix_refs around while
1529
1533
                #       processing. They *should* be shorter lived than that...
1530
1534
                #       It does cost us ~10s of processing time
1531
 
                prefix_refs = list(node._items.items())
 
1535
                #prefix_refs = [as_st(item) for item in node._items.iteritems()]
 
1536
                prefix_refs = node._items.items()
1532
1537
                items = []
1533
1538
            else:
1534
1539
                prefix_refs = []
1535
1540
                # Note: We don't use a StaticTuple here. Profiling showed a
1536
1541
                #       minor memory improvement (0.8MB out of 335MB peak 0.2%)
1537
1542
                #       But a significant slowdown (15s / 145s, or 10%)
1538
 
                items = list(node._items.items())
 
1543
                items = node._items.items()
1539
1544
            yield record, node, prefix_refs, items
1540
1545
 
1541
1546
    def _read_old_roots(self):
1545
1550
                self._read_nodes_from_store(self._old_root_keys):
1546
1551
            # Uninteresting node
1547
1552
            prefix_refs = [p_r for p_r in prefix_refs
1548
 
                           if p_r[1] not in all_old_chks]
 
1553
                                if p_r[1] not in all_old_chks]
1549
1554
            new_refs = [p_r[1] for p_r in prefix_refs]
1550
1555
            all_old_chks.update(new_refs)
1551
1556
            # TODO: This might be a good time to turn items into StaticTuple
1565
1570
        # handled the interesting ones
1566
1571
        for prefix, ref in old_chks_to_enqueue:
1567
1572
            not_interesting = True
1568
 
            for i in range(len(prefix), 0, -1):
 
1573
            for i in xrange(len(prefix), 0, -1):
1569
1574
                if prefix[:i] in new_prefixes:
1570
1575
                    not_interesting = False
1571
1576
                    break
1601
1606
            # At this level, we now know all the uninteresting references
1602
1607
            # So we filter and queue up whatever is remaining
1603
1608
            prefix_refs = [p_r for p_r in prefix_refs
1604
 
                           if p_r[1] not in self._all_old_chks and
1605
 
                           p_r[1] not in processed_new_refs]
 
1609
                           if p_r[1] not in self._all_old_chks
 
1610
                              and p_r[1] not in processed_new_refs]
1606
1611
            refs = [p_r[1] for p_r in prefix_refs]
1607
1612
            new_prefixes.update([p_r[0] for p_r in prefix_refs])
1608
1613
            self._new_queue.extend(refs)
1614
1619
            #       self._new_item_queue will hold the contents of multiple
1615
1620
            #       records for an extended lifetime
1616
1621
            new_items = [item for item in items
1617
 
                         if item not in self._all_old_items]
 
1622
                               if item not in self._all_old_items]
1618
1623
            self._new_item_queue.extend(new_items)
1619
1624
            new_prefixes.update([self._search_key_func(item[0])
1620
1625
                                 for item in new_items])
1625
1630
        # 'ab', then we also need to include 'a'.) So expand the
1626
1631
        # new_prefixes to include all shorter prefixes
1627
1632
        for prefix in list(new_prefixes):
1628
 
            new_prefixes.update([prefix[:i] for i in range(1, len(prefix))])
 
1633
            new_prefixes.update([prefix[:i] for i in xrange(1, len(prefix))])
1629
1634
        self._enqueue_old(new_prefixes, old_chks_to_enqueue)
1630
1635
 
1631
1636
    def _flush_new_queue(self):
1638
1643
        processed_new_refs = self._processed_new_refs
1639
1644
        all_old_items = self._all_old_items
1640
1645
        new_items = [item for item in self._new_item_queue
1641
 
                     if item not in all_old_items]
 
1646
                           if item not in all_old_items]
1642
1647
        self._new_item_queue = []
1643
1648
        if new_items:
1644
1649
            yield None, new_items
1682
1687
        for record, _, prefix_refs, items in self._read_nodes_from_store(refs):
1683
1688
            # TODO: Use StaticTuple here?
1684
1689
            self._all_old_items.update(items)
1685
 
            refs = [r for _, r in prefix_refs if r not in all_old_chks]
 
1690
            refs = [r for _,r in prefix_refs if r not in all_old_chks]
1686
1691
            self._old_queue.extend(refs)
1687
1692
            all_old_chks.update(refs)
1688
1693
 
1720
1725
 
1721
1726
 
1722
1727
try:
1723
 
    from ._chk_map_pyx import (
 
1728
    from brzlib._chk_map_pyx import (
1724
1729
        _bytes_to_text_key,
1725
1730
        _search_key_16,
1726
1731
        _search_key_255,
1727
1732
        _deserialise_leaf_node,
1728
1733
        _deserialise_internal_node,
1729
1734
        )
1730
 
except ImportError as e:
 
1735
except ImportError, e:
1731
1736
    osutils.failed_to_load_extension(e)
1732
 
    from ._chk_map_py import (
 
1737
    from brzlib._chk_map_py import (
1733
1738
        _bytes_to_text_key,
1734
1739
        _search_key_16,
1735
1740
        _search_key_255,
1736
1741
        _deserialise_leaf_node,
1737
1742
        _deserialise_internal_node,
1738
 
        )  # noqa: F401
1739
 
search_key_registry.register(b'hash-16-way', _search_key_16)
1740
 
search_key_registry.register(b'hash-255-way', _search_key_255)
 
1743
        )
 
1744
search_key_registry.register('hash-16-way', _search_key_16)
 
1745
search_key_registry.register('hash-255-way', _search_key_255)
1741
1746
 
1742
1747
 
1743
1748
def _check_key(key):
1746
1751
    This generally shouldn't be used in production code, but it can be helpful
1747
1752
    to debug problems.
1748
1753
    """
1749
 
    if not isinstance(key, StaticTuple):
 
1754
    if type(key) is not StaticTuple:
1750
1755
        raise TypeError('key %r is not StaticTuple but %s' % (key, type(key)))
1751
1756
    if len(key) != 1:
1752
 
        raise ValueError('key %r should have length 1, not %d' %
1753
 
                         (key, len(key),))
1754
 
    if not isinstance(key[0], str):
 
1757
        raise ValueError('key %r should have length 1, not %d' % (key, len(key),))
 
1758
    if type(key[0]) is not str:
1755
1759
        raise TypeError('key %r should hold a str, not %r'
1756
1760
                        % (key, type(key[0])))
1757
1761
    if not key[0].startswith('sha1:'):
1758
1762
        raise ValueError('key %r should point to a sha1:' % (key,))
 
1763
 
 
1764