/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 breezy/bzr/chk_map.py

  • Committer: Jelmer Vernooij
  • Date: 2020-01-19 15:14:16 UTC
  • mto: This revision was merged to the branch mainline in revision 7455.
  • Revision ID: jelmer@jelmer.uk-20200119151416-f2x9y9rtvwxndr2l
Don't show submodules that are not checked out as deltas.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
 
1
# Copyright (C) 2008-2011 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
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 bzrlib import lazy_import
44
 
lazy_import.lazy_import(globals(), """
45
 
from bzrlib import (
 
45
from .. import (
46
46
    errors,
47
 
    versionedfile,
48
 
    )
49
 
""")
50
 
from bzrlib import (
51
47
    lru_cache,
52
48
    osutils,
53
49
    registry,
54
50
    static_tuple,
55
51
    trace,
56
52
    )
57
 
from bzrlib.static_tuple import StaticTuple
 
53
from ..sixish import (
 
54
    viewitems,
 
55
    viewvalues,
 
56
    )
 
57
from ..sixish import PY3
 
58
from ..static_tuple import StaticTuple
58
59
 
59
60
# approx 4MB
60
61
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
61
62
# out, it takes 3.1MB to cache the layer.
62
 
_PAGE_CACHE_SIZE = 4*1024*1024
 
63
_PAGE_CACHE_SIZE = 4 * 1024 * 1024
63
64
# Per thread caches for 2 reasons:
64
65
# - in the server we may be serving very different content, so we get less
65
66
#   cache thrashing.
68
69
# The page cache.
69
70
_thread_caches.page_cache = None
70
71
 
 
72
 
71
73
def _get_cache():
72
74
    """Get the per-thread page cache.
73
75
 
90
92
_INTERESTING_NEW_SIZE = 50
91
93
# If a ChildNode shrinks by more than this amount, we check for a remap
92
94
_INTERESTING_SHRINKAGE_LIMIT = 20
93
 
# If we delete more than this many nodes applying a delta, we check for a remap
94
 
_INTERESTING_DELETES_LIMIT = 5
95
95
 
96
96
 
97
97
def _search_key_plain(key):
98
98
    """Map the key tuple into a search string that just uses the key bytes."""
99
 
    return '\x00'.join(key)
 
99
    return b'\x00'.join(key)
100
100
 
101
101
 
102
102
search_key_registry = registry.Registry()
103
 
search_key_registry.register('plain', _search_key_plain)
 
103
search_key_registry.register(b'plain', _search_key_plain)
104
104
 
105
105
 
106
106
class CHKMap(object):
135
135
            into the map; if old_key is not None, then the old mapping
136
136
            of old_key is removed.
137
137
        """
138
 
        delete_count = 0
 
138
        has_deletes = False
139
139
        # Check preconditions first.
140
140
        as_st = StaticTuple.from_sequence
141
 
        new_items = set([as_st(key) for (old, key, value) in delta
142
 
                         if key is not None and old is None])
 
141
        new_items = {as_st(key) for (old, key, value) in delta
 
142
                     if key is not None and old is None}
143
143
        existing_new = list(self.iteritems(key_filter=new_items))
144
144
        if existing_new:
145
145
            raise errors.InconsistentDeltaDelta(delta,
146
 
                "New items are already in the map %r." % existing_new)
 
146
                                                "New items are already in the map %r." % existing_new)
147
147
        # Now apply changes.
148
148
        for old, new, value in delta:
149
149
            if old is not None and old != new:
150
150
                self.unmap(old, check_remap=False)
151
 
                delete_count += 1
 
151
                has_deletes = True
152
152
        for old, new, value in delta:
153
153
            if new is not None:
154
154
                self.map(new, value)
155
 
        if delete_count > _INTERESTING_DELETES_LIMIT:
156
 
            trace.mutter("checking remap as %d deletions", delete_count)
 
155
        if has_deletes:
157
156
            self._check_remap()
158
157
        return self._save()
159
158
 
160
159
    def _ensure_root(self):
161
160
        """Ensure that the root node is an object not a key."""
162
 
        if type(self._root_node) is StaticTuple:
 
161
        if isinstance(self._root_node, StaticTuple):
163
162
            # Demand-load the root
164
163
            self._root_node = self._get_node(self._root_node)
165
164
 
173
172
        :param node: A tuple key or node object.
174
173
        :return: A node object.
175
174
        """
176
 
        if type(node) is StaticTuple:
 
175
        if isinstance(node, StaticTuple):
177
176
            bytes = self._read_bytes(node)
178
177
            return _deserialise(bytes, node,
179
 
                search_key_func=self._search_key_func)
 
178
                                search_key_func=self._search_key_func)
180
179
        else:
181
180
            return node
182
181
 
185
184
            return _get_cache()[key]
186
185
        except KeyError:
187
186
            stream = self._store.get_record_stream([key], 'unordered', True)
188
 
            bytes = stream.next().get_bytes_as('fulltext')
 
187
            bytes = next(stream).get_bytes_as('fulltext')
189
188
            _get_cache()[key] = bytes
190
189
            return bytes
191
190
 
192
 
    def _dump_tree(self, include_keys=False):
 
191
    def _dump_tree(self, include_keys=False, encoding='utf-8'):
193
192
        """Return the tree in a string representation."""
194
193
        self._ensure_root()
195
 
        res = self._dump_tree_node(self._root_node, prefix='', indent='',
196
 
                                   include_keys=include_keys)
197
 
        res.append('') # Give a trailing '\n'
 
194
        if PY3:
 
195
            def decode(x): return x.decode(encoding)
 
196
        else:
 
197
            def decode(x): return x
 
198
        res = self._dump_tree_node(self._root_node, prefix=b'', indent='',
 
199
                                   decode=decode, include_keys=include_keys)
 
200
        res.append('')  # Give a trailing '\n'
198
201
        return '\n'.join(res)
199
202
 
200
 
    def _dump_tree_node(self, node, prefix, indent, include_keys=True):
 
203
    def _dump_tree_node(self, node, prefix, indent, decode, include_keys=True):
201
204
        """For this node and all children, generate a string representation."""
202
205
        result = []
203
206
        if not include_keys:
205
208
        else:
206
209
            node_key = node.key()
207
210
            if node_key is not None:
208
 
                key_str = ' %s' % (node_key[0],)
 
211
                key_str = ' %s' % (decode(node_key[0]),)
209
212
            else:
210
213
                key_str = ' None'
211
 
        result.append('%s%r %s%s' % (indent, prefix, node.__class__.__name__,
 
214
        result.append('%s%r %s%s' % (indent, decode(prefix), node.__class__.__name__,
212
215
                                     key_str))
213
 
        if type(node) is InternalNode:
 
216
        if isinstance(node, InternalNode):
214
217
            # Trigger all child nodes to get loaded
215
218
            list(node._iter_nodes(self._store))
216
 
            for prefix, sub in sorted(node._items.iteritems()):
 
219
            for prefix, sub in sorted(viewitems(node._items)):
217
220
                result.extend(self._dump_tree_node(sub, prefix, indent + '  ',
218
 
                                                   include_keys=include_keys))
 
221
                                                   decode=decode, include_keys=include_keys))
219
222
        else:
220
 
            for key, value in sorted(node._items.iteritems()):
 
223
            for key, value in sorted(viewitems(node._items)):
221
224
                # Don't use prefix nor indent here to line up when used in
222
225
                # tests in conjunction with assertEqualDiff
223
 
                result.append('      %r %r' % (tuple(key), value))
 
226
                result.append('      %r %r' % (
 
227
                    tuple([decode(ke) for ke in key]), decode(value)))
224
228
        return result
225
229
 
226
230
    @classmethod
227
231
    def from_dict(klass, store, initial_value, maximum_size=0, key_width=1,
228
 
        search_key_func=None):
 
232
                  search_key_func=None):
229
233
        """Create a CHKMap in store with initial_value as the content.
230
234
 
231
235
        :param store: The store to record initial_value in, a VersionedFiles
242
246
        :return: The root chk of the resulting CHKMap.
243
247
        """
244
248
        root_key = klass._create_directly(store, initial_value,
245
 
            maximum_size=maximum_size, key_width=key_width,
246
 
            search_key_func=search_key_func)
247
 
        if type(root_key) is not StaticTuple:
 
249
                                          maximum_size=maximum_size, key_width=key_width,
 
250
                                          search_key_func=search_key_func)
 
251
        if not isinstance(root_key, StaticTuple):
248
252
            raise AssertionError('we got a %s instead of a StaticTuple'
249
253
                                 % (type(root_key),))
250
254
        return root_key
256
260
        result._root_node.set_maximum_size(maximum_size)
257
261
        result._root_node._key_width = key_width
258
262
        delta = []
259
 
        for key, value in initial_value.items():
 
263
        for key, value in viewitems(initial_value):
260
264
            delta.append((None, key, value))
261
265
        root_key = result.apply_delta(delta)
262
266
        return root_key
268
272
        node.set_maximum_size(maximum_size)
269
273
        node._key_width = key_width
270
274
        as_st = StaticTuple.from_sequence
271
 
        node._items = dict([(as_st(key), val) for key, val
272
 
                                               in initial_value.iteritems()])
273
 
        node._raw_size = sum([node._key_value_len(key, value)
274
 
                              for key,value in node._items.iteritems()])
 
275
        node._items = dict((as_st(key), val)
 
276
                           for key, val in viewitems(initial_value))
 
277
        node._raw_size = sum(node._key_value_len(key, value)
 
278
                             for key, value in viewitems(node._items))
275
279
        node._len = len(node._items)
276
280
        node._compute_search_prefix()
277
281
        node._compute_serialised_prefix()
278
 
        if (node._len > 1
279
 
            and maximum_size
280
 
            and node._current_size() > maximum_size):
 
282
        if (node._len > 1 and
 
283
            maximum_size and
 
284
                node._current_size() > maximum_size):
281
285
            prefix, node_details = node._split(store)
282
286
            if len(node_details) == 1:
283
287
                raise AssertionError('Failed to split using node._split')
329
333
        # key_path (a list of tuples, tail-sharing down the tree.)
330
334
        self_pending = []
331
335
        basis_pending = []
 
336
 
332
337
        def process_node(node, path, a_map, pending):
333
338
            # take a node and expand it
334
339
            node = a_map._get_node(node)
335
 
            if type(node) == LeafNode:
 
340
            if isinstance(node, LeafNode):
336
341
                path = (node._key, path)
337
 
                for key, value in node._items.items():
 
342
                for key, value in viewitems(node._items):
338
343
                    # For a LeafNode, the key is a serialized_key, rather than
339
344
                    # a search_key, but the heap is using search_keys
340
345
                    search_key = node._search_key_func(key)
342
347
            else:
343
348
                # type(node) == InternalNode
344
349
                path = (node._key, path)
345
 
                for prefix, child in node._items.items():
 
350
                for prefix, child in viewitems(node._items):
346
351
                    heapq.heappush(pending, (prefix, None, child, path))
 
352
 
347
353
        def process_common_internal_nodes(self_node, basis_node):
348
 
            self_items = set(self_node._items.items())
349
 
            basis_items = set(basis_node._items.items())
 
354
            self_items = set(viewitems(self_node._items))
 
355
            basis_items = set(viewitems(basis_node._items))
350
356
            path = (self_node._key, None)
351
357
            for prefix, child in self_items - basis_items:
352
358
                heapq.heappush(self_pending, (prefix, None, child, path))
353
359
            path = (basis_node._key, None)
354
360
            for prefix, child in basis_items - self_items:
355
361
                heapq.heappush(basis_pending, (prefix, None, child, path))
 
362
 
356
363
        def process_common_leaf_nodes(self_node, basis_node):
357
 
            self_items = set(self_node._items.items())
358
 
            basis_items = set(basis_node._items.items())
 
364
            self_items = set(viewitems(self_node._items))
 
365
            basis_items = set(viewitems(basis_node._items))
359
366
            path = (self_node._key, None)
360
367
            for key, value in self_items - basis_items:
361
368
                prefix = self._search_key_func(key)
364
371
            for key, value in basis_items - self_items:
365
372
                prefix = basis._search_key_func(key)
366
373
                heapq.heappush(basis_pending, (prefix, key, value, path))
 
374
 
367
375
        def process_common_prefix_nodes(self_node, self_path,
368
376
                                        basis_node, basis_path):
369
377
            # Would it be more efficient if we could request both at the same
370
378
            # time?
371
379
            self_node = self._get_node(self_node)
372
380
            basis_node = basis._get_node(basis_node)
373
 
            if (type(self_node) == InternalNode
374
 
                and type(basis_node) == InternalNode):
 
381
            if (isinstance(self_node, InternalNode) and
 
382
                    isinstance(basis_node, InternalNode)):
375
383
                # Matching internal nodes
376
384
                process_common_internal_nodes(self_node, basis_node)
377
 
            elif (type(self_node) == LeafNode
378
 
                  and type(basis_node) == LeafNode):
 
385
            elif (isinstance(self_node, LeafNode) and
 
386
                  isinstance(basis_node, LeafNode)):
379
387
                process_common_leaf_nodes(self_node, basis_node)
380
388
            else:
381
389
                process_node(self_node, self_path, self, self_pending)
384
392
        self_seen = set()
385
393
        basis_seen = set()
386
394
        excluded_keys = set()
 
395
 
387
396
        def check_excluded(key_path):
388
397
            # Note that this is N^2, it depends on us trimming trees
389
398
            # aggressively to not become slow.
390
399
            # A better implementation would probably have a reverse map
391
400
            # back to the children of a node, and jump straight to it when
392
401
            # a common node is detected, the proceed to remove the already
393
 
            # pending children. bzrlib.graph has a searcher module with a
 
402
            # pending children. breezy.graph has a searcher module with a
394
403
            # similar problem.
395
404
            while key_path is not None:
396
405
                key, key_path = key_path
473
482
                        basis_details = heapq.heappop(basis_pending)
474
483
                        if self_details[2] != basis_details[2]:
475
484
                            yield (self_details[1],
476
 
                                basis_details[2], self_details[2])
 
485
                                   basis_details[2], self_details[2])
477
486
                        continue
478
487
                    # At least one side wasn't a simple value
479
 
                    if (self._node_key(self_pending[0][2]) ==
480
 
                        self._node_key(basis_pending[0][2])):
 
488
                    if (self._node_key(self_pending[0][2])
 
489
                            == self._node_key(basis_pending[0][2])):
481
490
                        # Identical pointers, skip (and don't bother adding to
482
491
                        # excluded, it won't turn up again.
483
492
                        heapq.heappop(self_pending)
520
529
 
521
530
    def key(self):
522
531
        """Return the key for this map."""
523
 
        if type(self._root_node) is StaticTuple:
 
532
        if isinstance(self._root_node, StaticTuple):
524
533
            return self._root_node
525
534
        else:
526
535
            return self._root_node._key
531
540
 
532
541
    def map(self, key, value):
533
542
        """Map a key tuple to value.
534
 
        
 
543
 
535
544
        :param key: A key to map.
536
545
        :param value: The value to assign to key.
537
546
        """
543
552
            self._root_node = node_details[0][1]
544
553
        else:
545
554
            self._root_node = InternalNode(prefix,
546
 
                                search_key_func=self._search_key_func)
 
555
                                           search_key_func=self._search_key_func)
547
556
            self._root_node.set_maximum_size(node_details[0][1].maximum_size)
548
557
            self._root_node._key_width = node_details[0][1]._key_width
549
558
            for split, node in node_details:
551
560
 
552
561
    def _node_key(self, node):
553
562
        """Get the key for a node whether it's a tuple or node."""
554
 
        if type(node) is tuple:
 
563
        if isinstance(node, tuple):
555
564
            node = StaticTuple.from_sequence(node)
556
 
        if type(node) is StaticTuple:
 
565
        if isinstance(node, StaticTuple):
557
566
            return node
558
567
        else:
559
568
            return node._key
562
571
        """remove key from the map."""
563
572
        key = StaticTuple.from_sequence(key)
564
573
        self._ensure_root()
565
 
        if type(self._root_node) is InternalNode:
 
574
        if isinstance(self._root_node, InternalNode):
566
575
            unmapped = self._root_node.unmap(self._store, key,
567
 
                check_remap=check_remap)
 
576
                                             check_remap=check_remap)
568
577
        else:
569
578
            unmapped = self._root_node.unmap(self._store, key)
570
579
        self._root_node = unmapped
572
581
    def _check_remap(self):
573
582
        """Check if nodes can be collapsed."""
574
583
        self._ensure_root()
575
 
        if type(self._root_node) is InternalNode:
576
 
            self._root_node._check_remap(self._store)
 
584
        if isinstance(self._root_node, InternalNode):
 
585
            self._root_node = self._root_node._check_remap(self._store)
577
586
 
578
587
    def _save(self):
579
588
        """Save the map completely.
580
589
 
581
590
        :return: The key of the root node.
582
591
        """
583
 
        if type(self._root_node) is StaticTuple:
 
592
        if isinstance(self._root_node, StaticTuple):
584
593
            # Already saved.
585
594
            return self._root_node
586
595
        keys = list(self._root_node.serialise(self._store))
596
605
 
597
606
    __slots__ = ('_key', '_len', '_maximum_size', '_key_width',
598
607
                 '_raw_size', '_items', '_search_prefix', '_search_key_func'
599
 
                )
 
608
                 )
600
609
 
601
610
    def __init__(self, key_width=1):
602
611
        """Create a node.
658
667
            if left != right:
659
668
                pos -= 1
660
669
                break
661
 
        common = prefix[:pos+1]
 
670
        common = prefix[:pos + 1]
662
671
        return common
663
672
 
664
673
    @classmethod
677
686
            if not common_prefix:
678
687
                # if common_prefix is the empty string, then we know it won't
679
688
                # change further
680
 
                return ''
 
689
                return b''
681
690
        return common_prefix
682
691
 
683
692
 
684
693
# Singleton indicating we have not computed _search_prefix yet
685
694
_unknown = object()
686
695
 
 
696
 
687
697
class LeafNode(Node):
688
698
    """A node containing actual key:value pairs.
689
699
 
710
720
        return \
711
721
            '%s(key:%s len:%s size:%s max:%s prefix:%s keywidth:%s items:%s)' \
712
722
            % (self.__class__.__name__, self._key, self._len, self._raw_size,
713
 
            self._maximum_size, self._search_prefix, self._key_width, items_str)
 
723
               self._maximum_size, self._search_prefix, self._key_width, items_str)
714
724
 
715
725
    def _current_size(self):
716
726
        """Answer the current serialised size of this node.
727
737
            # entry lines
728
738
            prefix_len = len(self._common_serialised_prefix)
729
739
            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)
 
740
        return (9 +  # 'chkleaf:\n' +
 
741
                len(str(self._maximum_size)) + 1 +
 
742
                len(str(self._key_width)) + 1 +
 
743
                len(str(self._len)) + 1 +
 
744
                prefix_len + 1 +
 
745
                bytes_for_items)
736
746
 
737
747
    @classmethod
738
748
    def deserialise(klass, bytes, key, search_key_func=None):
767
777
                        pass
768
778
                else:
769
779
                    # Short items, we need to match based on a prefix
770
 
                    length_filter = filters.setdefault(len(key), set())
771
 
                    length_filter.add(key)
 
780
                    filters.setdefault(len(key), set()).add(key)
772
781
            if filters:
773
 
                filters = filters.items()
774
 
                for item in self._items.iteritems():
775
 
                    for length, length_filter in filters:
 
782
                filters_itemview = viewitems(filters)
 
783
                for item in viewitems(self._items):
 
784
                    for length, length_filter in filters_itemview:
776
785
                        if item[0][:length] in length_filter:
777
786
                            yield item
778
787
                            break
779
788
        else:
780
 
            for item in self._items.iteritems():
 
789
            for item in viewitems(self._items):
781
790
                yield item
782
791
 
783
792
    def _key_value_len(self, key, value):
784
793
        # TODO: Should probably be done without actually joining the key, but
785
794
        #       then that can be done via the C extension
786
 
        return (len(self._serialise_key(key)) + 1
787
 
                + len(str(value.count('\n'))) + 1
788
 
                + len(value) + 1)
 
795
        return (len(self._serialise_key(key)) + 1 +
 
796
                len(b'%d' % value.count(b'\n')) + 1 +
 
797
                len(value) + 1)
789
798
 
790
799
    def _search_key(self, key):
791
800
        return self._search_key_func(key)
815
824
        else:
816
825
            self._search_prefix = self.common_prefix(
817
826
                self._search_prefix, search_key)
818
 
        if (self._len > 1
819
 
            and self._maximum_size
820
 
            and self._current_size() > self._maximum_size):
 
827
        if (self._len > 1 and
 
828
            self._maximum_size and
 
829
                self._current_size() > self._maximum_size):
821
830
            # Check to see if all of the search_keys for this node are
822
831
            # identical. We allow the node to grow under that circumstance
823
832
            # (we could track this as common state, but it is infrequent)
824
 
            if (search_key != self._search_prefix
825
 
                or not self._are_search_keys_identical()):
 
833
            if (search_key != self._search_prefix or
 
834
                    not self._are_search_keys_identical()):
826
835
                return True
827
836
        return False
828
837
 
839
848
        common_prefix = self._search_prefix
840
849
        split_at = len(common_prefix) + 1
841
850
        result = {}
842
 
        for key, value in self._items.iteritems():
 
851
        for key, value in viewitems(self._items):
843
852
            search_key = self._search_key(key)
844
853
            prefix = search_key[:split_at]
845
854
            # TODO: Generally only 1 key can be exactly the right length,
851
860
            #       may get a '\00' node anywhere, but won't have keys of
852
861
            #       different lengths.
853
862
            if len(prefix) < split_at:
854
 
                prefix += '\x00'*(split_at - len(prefix))
 
863
                prefix += b'\x00' * (split_at - len(prefix))
855
864
            if prefix not in result:
856
865
                node = LeafNode(search_key_func=self._search_key_func)
857
866
                node.set_maximum_size(self._maximum_size)
866
875
                    # path
867
876
                    result.pop(prefix)
868
877
                new_node = InternalNode(sub_prefix,
869
 
                    search_key_func=self._search_key_func)
 
878
                                        search_key_func=self._search_key_func)
870
879
                new_node.set_maximum_size(self._maximum_size)
871
880
                new_node._key_width = self._key_width
872
881
                for split, node in node_details:
873
882
                    new_node.add_node(split, node)
874
883
                result[prefix] = new_node
875
 
        return common_prefix, result.items()
 
884
        return common_prefix, list(viewitems(result))
876
885
 
877
886
    def map(self, store, key, value):
878
887
        """Map key to value."""
885
894
        else:
886
895
            if self._search_prefix is _unknown:
887
896
                raise AssertionError('%r must be known' % self._search_prefix)
888
 
            return self._search_prefix, [("", self)]
 
897
            return self._search_prefix, [(b"", self)]
889
898
 
890
 
    _serialise_key = '\x00'.join
 
899
    _serialise_key = b'\x00'.join
891
900
 
892
901
    def serialise(self, store):
893
902
        """Serialise the LeafNode to store.
895
904
        :param store: A VersionedFiles honouring the CHK extensions.
896
905
        :return: An iterable of the keys inserted by this operation.
897
906
        """
898
 
        lines = ["chkleaf:\n"]
899
 
        lines.append("%d\n" % self._maximum_size)
900
 
        lines.append("%d\n" % self._key_width)
901
 
        lines.append("%d\n" % self._len)
 
907
        lines = [b"chkleaf:\n"]
 
908
        lines.append(b"%d\n" % self._maximum_size)
 
909
        lines.append(b"%d\n" % self._key_width)
 
910
        lines.append(b"%d\n" % self._len)
902
911
        if self._common_serialised_prefix is None:
903
 
            lines.append('\n')
 
912
            lines.append(b'\n')
904
913
            if len(self._items) != 0:
905
914
                raise AssertionError('If _common_serialised_prefix is None'
906
 
                    ' we should have no items')
 
915
                                     ' we should have no items')
907
916
        else:
908
 
            lines.append('%s\n' % (self._common_serialised_prefix,))
 
917
            lines.append(b'%s\n' % (self._common_serialised_prefix,))
909
918
            prefix_len = len(self._common_serialised_prefix)
910
 
        for key, value in sorted(self._items.items()):
 
919
        for key, value in sorted(viewitems(self._items)):
911
920
            # Always add a final newline
912
 
            value_lines = osutils.chunks_to_lines([value + '\n'])
913
 
            serialized = "%s\x00%s\n" % (self._serialise_key(key),
914
 
                                         len(value_lines))
 
921
            value_lines = osutils.chunks_to_lines([value + b'\n'])
 
922
            serialized = b"%s\x00%d\n" % (self._serialise_key(key),
 
923
                                          len(value_lines))
915
924
            if not serialized.startswith(self._common_serialised_prefix):
916
925
                raise AssertionError('We thought the common prefix was %r'
917
 
                    ' but entry %r does not have it in common'
918
 
                    % (self._common_serialised_prefix, serialized))
 
926
                                     ' but entry %r does not have it in common'
 
927
                                     % (self._common_serialised_prefix, serialized))
919
928
            lines.append(serialized[prefix_len:])
920
929
            lines.extend(value_lines)
921
930
        sha1, _, _ = store.add_lines((None,), (), lines)
922
 
        self._key = StaticTuple("sha1:" + sha1,).intern()
923
 
        bytes = ''.join(lines)
924
 
        if len(bytes) != self._current_size():
 
931
        self._key = StaticTuple(b"sha1:" + sha1,).intern()
 
932
        data = b''.join(lines)
 
933
        if len(data) != self._current_size():
925
934
            raise AssertionError('Invalid _current_size')
926
 
        _get_cache().add(self._key, bytes)
 
935
        _get_cache()[self._key] = data
927
936
        return [self._key]
928
937
 
929
938
    def refs(self):
995
1004
 
996
1005
    __slots__ = ('_node_width',)
997
1006
 
998
 
    def __init__(self, prefix='', search_key_func=None):
 
1007
    def __init__(self, prefix=b'', search_key_func=None):
999
1008
        Node.__init__(self)
1000
1009
        # The size of an internalnode with default values and no children.
1001
1010
        # How many octets key prefixes within this node are.
1016
1025
            raise AssertionError("_search_prefix should not be None")
1017
1026
        if not prefix.startswith(self._search_prefix):
1018
1027
            raise AssertionError("prefixes mismatch: %s must start with %s"
1019
 
                % (prefix,self._search_prefix))
 
1028
                                 % (prefix, self._search_prefix))
1020
1029
        if len(prefix) != len(self._search_prefix) + 1:
1021
1030
            raise AssertionError("prefix wrong length: len(%s) is not %d" %
1022
 
                (prefix, len(self._search_prefix) + 1))
 
1031
                                 (prefix, len(self._search_prefix) + 1))
1023
1032
        self._len += len(node)
1024
1033
        if not len(self._items):
1025
1034
            self._node_width = len(prefix)
1026
1035
        if self._node_width != len(self._search_prefix) + 1:
1027
1036
            raise AssertionError("node width mismatch: %d is not %d" %
1028
 
                (self._node_width, len(self._search_prefix) + 1))
 
1037
                                 (self._node_width, len(self._search_prefix) + 1))
1029
1038
        self._items[prefix] = node
1030
1039
        self._key = None
1031
1040
 
1032
1041
    def _current_size(self):
1033
1042
        """Answer the current serialised size of this node."""
1034
 
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width)) +
1035
 
            len(str(self._maximum_size)))
 
1043
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width))
 
1044
                + len(str(self._maximum_size)))
1036
1045
 
1037
1046
    @classmethod
1038
1047
    def deserialise(klass, bytes, key, search_key_func=None):
1072
1081
            # yielding all nodes, yield whatever we have, and queue up a read
1073
1082
            # for whatever we are missing
1074
1083
            shortcut = True
1075
 
            for prefix, node in self._items.iteritems():
 
1084
            for prefix, node in viewitems(self._items):
1076
1085
                if node.__class__ is StaticTuple:
1077
1086
                    keys[node] = (prefix, None)
1078
1087
                else:
1123
1132
            for key in key_filter:
1124
1133
                search_prefix = self._search_prefix_filter(key)
1125
1134
                length_filter = length_filters.setdefault(
1126
 
                                    len(search_prefix), set())
 
1135
                    len(search_prefix), set())
1127
1136
                length_filter.add(search_prefix)
1128
1137
                prefix_to_keys.setdefault(search_prefix, []).append(key)
1129
1138
 
1130
 
            if (self._node_width in length_filters
1131
 
                and len(length_filters) == 1):
 
1139
            if (self._node_width in length_filters and
 
1140
                    len(length_filters) == 1):
1132
1141
                # all of the search prefixes match exactly _node_width. This
1133
1142
                # means that everything is an exact match, and we can do a
1134
1143
                # lookup into self._items, rather than iterating over the items
1148
1157
            else:
1149
1158
                # The slow way. We walk every item in self._items, and check to
1150
1159
                # see if there are any matches
1151
 
                length_filters = length_filters.items()
1152
 
                for prefix, node in self._items.iteritems():
 
1160
                length_filters_itemview = viewitems(length_filters)
 
1161
                for prefix, node in viewitems(self._items):
1153
1162
                    node_key_filter = []
1154
 
                    for length, length_filter in length_filters:
 
1163
                    for length, length_filter in length_filters_itemview:
1155
1164
                        sub_prefix = prefix[:length]
1156
1165
                        if sub_prefix in length_filter:
1157
1166
                            node_key_filter.extend(prefix_to_keys[sub_prefix])
1158
 
                    if node_key_filter: # this key matched something, yield it
 
1167
                    if node_key_filter:  # this key matched something, yield it
1159
1168
                        if node.__class__ is StaticTuple:
1160
1169
                            keys[node] = (prefix, node_key_filter)
1161
1170
                        else:
1170
1179
                    continue
1171
1180
                else:
1172
1181
                    node = _deserialise(bytes, key,
1173
 
                        search_key_func=self._search_key_func)
 
1182
                                        search_key_func=self._search_key_func)
1174
1183
                    prefix, node_key_filter = keys[key]
1175
1184
                    self._items[prefix] = node
1176
1185
                    found_keys.add(key)
1192
1201
                for record in stream:
1193
1202
                    bytes = record.get_bytes_as('fulltext')
1194
1203
                    node = _deserialise(bytes, record.key,
1195
 
                        search_key_func=self._search_key_func)
 
1204
                                        search_key_func=self._search_key_func)
1196
1205
                    prefix, node_key_filter = keys[record.key]
1197
1206
                    node_and_filters.append((node, node_key_filter))
1198
1207
                    self._items[prefix] = node
1199
 
                    _get_cache().add(record.key, bytes)
 
1208
                    _get_cache()[record.key] = bytes
1200
1209
                for info in node_and_filters:
1201
1210
                    yield info
1202
1211
 
1207
1216
        search_key = self._search_key(key)
1208
1217
        if self._node_width != len(self._search_prefix) + 1:
1209
1218
            raise AssertionError("node width mismatch: %d is not %d" %
1210
 
                (self._node_width, len(self._search_prefix) + 1))
 
1219
                                 (self._node_width, len(self._search_prefix) + 1))
1211
1220
        if not search_key.startswith(self._search_prefix):
1212
1221
            # This key doesn't fit in this index, so we need to split at the
1213
1222
            # point where it would fit, insert self into that internal node,
1215
1224
            new_prefix = self.common_prefix(self._search_prefix,
1216
1225
                                            search_key)
1217
1226
            new_parent = InternalNode(new_prefix,
1218
 
                search_key_func=self._search_key_func)
 
1227
                                      search_key_func=self._search_key_func)
1219
1228
            new_parent.set_maximum_size(self._maximum_size)
1220
1229
            new_parent._key_width = self._key_width
1221
 
            new_parent.add_node(self._search_prefix[:len(new_prefix)+1],
 
1230
            new_parent.add_node(self._search_prefix[:len(new_prefix) + 1],
1222
1231
                                self)
1223
1232
            return new_parent.map(store, key, value)
1224
 
        children = [node for node, _
1225
 
                          in self._iter_nodes(store, key_filter=[key])]
 
1233
        children = [node for node, _ in self._iter_nodes(
 
1234
            store, key_filter=[key])]
1226
1235
        if children:
1227
1236
            child = children[0]
1228
1237
        else:
1229
1238
            # new child needed:
1230
1239
            child = self._new_child(search_key, LeafNode)
1231
1240
        old_len = len(child)
1232
 
        if type(child) is LeafNode:
 
1241
        if isinstance(child, LeafNode):
1233
1242
            old_size = child._current_size()
1234
1243
        else:
1235
1244
            old_size = None
1241
1250
            self._items[search_key] = child
1242
1251
            self._key = None
1243
1252
            new_node = self
1244
 
            if type(child) is LeafNode:
 
1253
            if isinstance(child, LeafNode):
1245
1254
                if old_size is None:
1246
1255
                    # The old node was an InternalNode which means it has now
1247
1256
                    # collapsed, so we need to check if it will chain to a
1257
1266
                    # amount is over a configurable limit.
1258
1267
                    new_size = child._current_size()
1259
1268
                    shrinkage = old_size - new_size
1260
 
                    if (shrinkage > 0 and new_size < _INTERESTING_NEW_SIZE
1261
 
                        or shrinkage > _INTERESTING_SHRINKAGE_LIMIT):
 
1269
                    if (shrinkage > 0 and new_size < _INTERESTING_NEW_SIZE or
 
1270
                            shrinkage > _INTERESTING_SHRINKAGE_LIMIT):
1262
1271
                        trace.mutter(
1263
1272
                            "checking remap as size shrunk by %d to be %d",
1264
1273
                            shrinkage, new_size)
1265
1274
                        new_node = self._check_remap(store)
1266
1275
            if new_node._search_prefix is None:
1267
1276
                raise AssertionError("_search_prefix should not be None")
1268
 
            return new_node._search_prefix, [('', new_node)]
 
1277
            return new_node._search_prefix, [(b'', new_node)]
1269
1278
        # child has overflown - create a new intermediate node.
1270
1279
        # XXX: This is where we might want to try and expand our depth
1271
1280
        # to refer to more bytes of every child (which would give us
1276
1285
            child.add_node(split, node)
1277
1286
        self._len = self._len - old_len + len(child)
1278
1287
        self._key = None
1279
 
        return self._search_prefix, [("", self)]
 
1288
        return self._search_prefix, [(b"", self)]
1280
1289
 
1281
1290
    def _new_child(self, search_key, klass):
1282
1291
        """Create a new child node of type klass."""
1293
1302
        :param store: A VersionedFiles honouring the CHK extensions.
1294
1303
        :return: An iterable of the keys inserted by this operation.
1295
1304
        """
1296
 
        for node in self._items.itervalues():
1297
 
            if type(node) is StaticTuple:
 
1305
        for node in viewvalues(self._items):
 
1306
            if isinstance(node, StaticTuple):
1298
1307
                # Never deserialised.
1299
1308
                continue
1300
1309
            if node._key is not None:
1302
1311
                continue
1303
1312
            for key in node.serialise(store):
1304
1313
                yield key
1305
 
        lines = ["chknode:\n"]
1306
 
        lines.append("%d\n" % self._maximum_size)
1307
 
        lines.append("%d\n" % self._key_width)
1308
 
        lines.append("%d\n" % self._len)
 
1314
        lines = [b"chknode:\n"]
 
1315
        lines.append(b"%d\n" % self._maximum_size)
 
1316
        lines.append(b"%d\n" % self._key_width)
 
1317
        lines.append(b"%d\n" % self._len)
1309
1318
        if self._search_prefix is None:
1310
1319
            raise AssertionError("_search_prefix should not be None")
1311
 
        lines.append('%s\n' % (self._search_prefix,))
 
1320
        lines.append(b'%s\n' % (self._search_prefix,))
1312
1321
        prefix_len = len(self._search_prefix)
1313
 
        for prefix, node in sorted(self._items.items()):
1314
 
            if type(node) is StaticTuple:
 
1322
        for prefix, node in sorted(viewitems(self._items)):
 
1323
            if isinstance(node, StaticTuple):
1315
1324
                key = node[0]
1316
1325
            else:
1317
1326
                key = node._key[0]
1318
 
            serialised = "%s\x00%s\n" % (prefix, key)
 
1327
            serialised = b"%s\x00%s\n" % (prefix, key)
1319
1328
            if not serialised.startswith(self._search_prefix):
1320
1329
                raise AssertionError("prefixes mismatch: %s must start with %s"
1321
 
                    % (serialised, self._search_prefix))
 
1330
                                     % (serialised, self._search_prefix))
1322
1331
            lines.append(serialised[prefix_len:])
1323
1332
        sha1, _, _ = store.add_lines((None,), (), lines)
1324
 
        self._key = StaticTuple("sha1:" + sha1,).intern()
1325
 
        _get_cache().add(self._key, ''.join(lines))
 
1333
        self._key = StaticTuple(b"sha1:" + sha1,).intern()
 
1334
        _get_cache()[self._key] = b''.join(lines)
1326
1335
        yield self._key
1327
1336
 
1328
1337
    def _search_key(self, key):
1329
1338
        """Return the serialised key for key in this node."""
1330
1339
        # search keys are fixed width. All will be self._node_width wide, so we
1331
1340
        # pad as necessary.
1332
 
        return (self._search_key_func(key) + '\x00'*self._node_width)[:self._node_width]
 
1341
        return (self._search_key_func(key) + b'\x00' * self._node_width)[:self._node_width]
1333
1342
 
1334
1343
    def _search_prefix_filter(self, key):
1335
1344
        """Serialise key for use as a prefix filter in iteritems."""
1343
1352
            prefix for reaching node.
1344
1353
        """
1345
1354
        if offset >= self._node_width:
1346
 
            for node in self._items.values():
 
1355
            for node in valueview(self._items):
1347
1356
                for result in node._split(offset):
1348
1357
                    yield result
1349
 
            return
1350
 
        for key, node in self._items.items():
1351
 
            pass
1352
1358
 
1353
1359
    def refs(self):
1354
1360
        """Return the references to other CHK's held by this node."""
1355
1361
        if self._key is None:
1356
1362
            raise AssertionError("unserialised nodes have no refs.")
1357
1363
        refs = []
1358
 
        for value in self._items.itervalues():
1359
 
            if type(value) is StaticTuple:
 
1364
        for value in viewvalues(self._items):
 
1365
            if isinstance(value, StaticTuple):
1360
1366
                refs.append(value)
1361
1367
            else:
1362
1368
                refs.append(value.key())
1372
1378
        return self._search_prefix
1373
1379
 
1374
1380
    def unmap(self, store, key, check_remap=True):
1375
 
        """Remove key from this node and it's children."""
 
1381
        """Remove key from this node and its children."""
1376
1382
        if not len(self._items):
1377
1383
            raise AssertionError("can't unmap in an empty InternalNode.")
1378
1384
        children = [node for node, _
1379
 
                          in self._iter_nodes(store, key_filter=[key])]
 
1385
                    in self._iter_nodes(store, key_filter=[key])]
1380
1386
        if children:
1381
1387
            child = children[0]
1382
1388
        else:
1394
1400
            self._items[search_key] = unmapped
1395
1401
        if len(self._items) == 1:
1396
1402
            # this node is no longer needed:
1397
 
            return self._items.values()[0]
1398
 
        if type(unmapped) is InternalNode:
 
1403
            return list(viewvalues(self._items))[0]
 
1404
        if isinstance(unmapped, InternalNode):
1399
1405
            return self
1400
1406
        if check_remap:
1401
1407
            return self._check_remap(store)
1441
1447
        #   c) With 255-way fan out, we don't want to read all 255 and destroy
1442
1448
        #      the page cache, just to determine that we really don't need it.
1443
1449
        for node, _ in self._iter_nodes(store, batch_size=16):
1444
 
            if type(node) is InternalNode:
 
1450
            if isinstance(node, InternalNode):
1445
1451
                # Without looking at any leaf nodes, we are sure
1446
1452
                return self
1447
 
            for key, value in node._items.iteritems():
 
1453
            for key, value in viewitems(node._items):
1448
1454
                if new_leaf._map_no_split(key, value):
1449
1455
                    return self
1450
1456
        trace.mutter("remap generated a new LeafNode")
1451
1457
        return new_leaf
1452
1458
 
1453
1459
 
1454
 
def _deserialise(bytes, key, search_key_func):
 
1460
def _deserialise(data, key, search_key_func):
1455
1461
    """Helper for repositorydetails - convert bytes to a node."""
1456
 
    if bytes.startswith("chkleaf:\n"):
1457
 
        node = LeafNode.deserialise(bytes, key, search_key_func=search_key_func)
1458
 
    elif bytes.startswith("chknode:\n"):
1459
 
        node = InternalNode.deserialise(bytes, key,
1460
 
            search_key_func=search_key_func)
 
1462
    if data.startswith(b"chkleaf:\n"):
 
1463
        node = LeafNode.deserialise(data, key, search_key_func=search_key_func)
 
1464
    elif data.startswith(b"chknode:\n"):
 
1465
        node = InternalNode.deserialise(data, key,
 
1466
                                        search_key_func=search_key_func)
1461
1467
    else:
1462
1468
        raise AssertionError("Unknown node type.")
1463
1469
    return node
1526
1532
            bytes = record.get_bytes_as('fulltext')
1527
1533
            node = _deserialise(bytes, record.key,
1528
1534
                                search_key_func=self._search_key_func)
1529
 
            if type(node) is InternalNode:
 
1535
            if isinstance(node, InternalNode):
1530
1536
                # Note we don't have to do node.refs() because we know that
1531
1537
                # there are no children that have been pushed into this node
1532
1538
                # Note: Using as_st() here seemed to save 1.2MB, which would
1533
1539
                #       indicate that we keep 100k prefix_refs around while
1534
1540
                #       processing. They *should* be shorter lived than that...
1535
1541
                #       It does cost us ~10s of processing time
1536
 
                #prefix_refs = [as_st(item) for item in node._items.iteritems()]
1537
 
                prefix_refs = node._items.items()
 
1542
                prefix_refs = list(viewitems(node._items))
1538
1543
                items = []
1539
1544
            else:
1540
1545
                prefix_refs = []
1541
1546
                # Note: We don't use a StaticTuple here. Profiling showed a
1542
1547
                #       minor memory improvement (0.8MB out of 335MB peak 0.2%)
1543
1548
                #       But a significant slowdown (15s / 145s, or 10%)
1544
 
                items = node._items.items()
 
1549
                items = list(viewitems(node._items))
1545
1550
            yield record, node, prefix_refs, items
1546
1551
 
1547
1552
    def _read_old_roots(self):
1551
1556
                self._read_nodes_from_store(self._old_root_keys):
1552
1557
            # Uninteresting node
1553
1558
            prefix_refs = [p_r for p_r in prefix_refs
1554
 
                                if p_r[1] not in all_old_chks]
 
1559
                           if p_r[1] not in all_old_chks]
1555
1560
            new_refs = [p_r[1] for p_r in prefix_refs]
1556
1561
            all_old_chks.update(new_refs)
1557
1562
            # TODO: This might be a good time to turn items into StaticTuple
1571
1576
        # handled the interesting ones
1572
1577
        for prefix, ref in old_chks_to_enqueue:
1573
1578
            not_interesting = True
1574
 
            for i in xrange(len(prefix), 0, -1):
 
1579
            for i in range(len(prefix), 0, -1):
1575
1580
                if prefix[:i] in new_prefixes:
1576
1581
                    not_interesting = False
1577
1582
                    break
1607
1612
            # At this level, we now know all the uninteresting references
1608
1613
            # So we filter and queue up whatever is remaining
1609
1614
            prefix_refs = [p_r for p_r in prefix_refs
1610
 
                           if p_r[1] not in self._all_old_chks
1611
 
                              and p_r[1] not in processed_new_refs]
 
1615
                           if p_r[1] not in self._all_old_chks and
 
1616
                           p_r[1] not in processed_new_refs]
1612
1617
            refs = [p_r[1] for p_r in prefix_refs]
1613
1618
            new_prefixes.update([p_r[0] for p_r in prefix_refs])
1614
1619
            self._new_queue.extend(refs)
1620
1625
            #       self._new_item_queue will hold the contents of multiple
1621
1626
            #       records for an extended lifetime
1622
1627
            new_items = [item for item in items
1623
 
                               if item not in self._all_old_items]
 
1628
                         if item not in self._all_old_items]
1624
1629
            self._new_item_queue.extend(new_items)
1625
1630
            new_prefixes.update([self._search_key_func(item[0])
1626
1631
                                 for item in new_items])
1631
1636
        # 'ab', then we also need to include 'a'.) So expand the
1632
1637
        # new_prefixes to include all shorter prefixes
1633
1638
        for prefix in list(new_prefixes):
1634
 
            new_prefixes.update([prefix[:i] for i in xrange(1, len(prefix))])
 
1639
            new_prefixes.update([prefix[:i] for i in range(1, len(prefix))])
1635
1640
        self._enqueue_old(new_prefixes, old_chks_to_enqueue)
1636
1641
 
1637
1642
    def _flush_new_queue(self):
1644
1649
        processed_new_refs = self._processed_new_refs
1645
1650
        all_old_items = self._all_old_items
1646
1651
        new_items = [item for item in self._new_item_queue
1647
 
                           if item not in all_old_items]
 
1652
                     if item not in all_old_items]
1648
1653
        self._new_item_queue = []
1649
1654
        if new_items:
1650
1655
            yield None, new_items
1688
1693
        for record, _, prefix_refs, items in self._read_nodes_from_store(refs):
1689
1694
            # TODO: Use StaticTuple here?
1690
1695
            self._all_old_items.update(items)
1691
 
            refs = [r for _,r in prefix_refs if r not in all_old_chks]
 
1696
            refs = [r for _, r in prefix_refs if r not in all_old_chks]
1692
1697
            self._old_queue.extend(refs)
1693
1698
            all_old_chks.update(refs)
1694
1699
 
1726
1731
 
1727
1732
 
1728
1733
try:
1729
 
    from bzrlib._chk_map_pyx import (
 
1734
    from ._chk_map_pyx import (
 
1735
        _bytes_to_text_key,
1730
1736
        _search_key_16,
1731
1737
        _search_key_255,
1732
1738
        _deserialise_leaf_node,
1733
1739
        _deserialise_internal_node,
1734
1740
        )
1735
 
except ImportError, e:
 
1741
except ImportError as e:
1736
1742
    osutils.failed_to_load_extension(e)
1737
 
    from bzrlib._chk_map_py import (
 
1743
    from ._chk_map_py import (
 
1744
        _bytes_to_text_key,
1738
1745
        _search_key_16,
1739
1746
        _search_key_255,
1740
1747
        _deserialise_leaf_node,
1741
1748
        _deserialise_internal_node,
1742
 
        )
1743
 
search_key_registry.register('hash-16-way', _search_key_16)
1744
 
search_key_registry.register('hash-255-way', _search_key_255)
 
1749
        )  # noqa: F401
 
1750
search_key_registry.register(b'hash-16-way', _search_key_16)
 
1751
search_key_registry.register(b'hash-255-way', _search_key_255)
1745
1752
 
1746
1753
 
1747
1754
def _check_key(key):
1750
1757
    This generally shouldn't be used in production code, but it can be helpful
1751
1758
    to debug problems.
1752
1759
    """
1753
 
    if type(key) is not StaticTuple:
 
1760
    if not isinstance(key, StaticTuple):
1754
1761
        raise TypeError('key %r is not StaticTuple but %s' % (key, type(key)))
1755
1762
    if len(key) != 1:
1756
 
        raise ValueError('key %r should have length 1, not %d' % (key, len(key),))
1757
 
    if type(key[0]) is not str:
 
1763
        raise ValueError('key %r should have length 1, not %d' %
 
1764
                         (key, len(key),))
 
1765
    if not isinstance(key[0], str):
1758
1766
        raise TypeError('key %r should hold a str, not %r'
1759
1767
                        % (key, type(key[0])))
1760
1768
    if not key[0].startswith('sha1:'):
1761
1769
        raise ValueError('key %r should point to a sha1:' % (key,))
1762
 
 
1763