/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/groupcompress.py

  • Committer: Jelmer Vernooij
  • Date: 2019-05-28 23:22:25 UTC
  • mto: This revision was merged to the branch mainline in revision 7303.
  • Revision ID: jelmer@jelmer.uk-20190528232225-xalg131vp3to7a13
Install dulwich from git.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008-2011 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Core compression logic for compressing streams of related files."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
import time
 
22
import zlib
 
23
 
 
24
from ..lazy_import import lazy_import
 
25
lazy_import(globals(), """
 
26
from breezy import (
 
27
    annotate,
 
28
    config,
 
29
    debug,
 
30
    osutils,
 
31
    static_tuple,
 
32
    trace,
 
33
    tsort,
 
34
    )
 
35
from breezy.bzr import (
 
36
    knit,
 
37
    pack,
 
38
    pack_repo,
 
39
    )
 
40
 
 
41
from breezy.i18n import gettext
 
42
""")
 
43
 
 
44
from .. import (
 
45
    errors,
 
46
    )
 
47
from .btree_index import BTreeBuilder
 
48
from ..lru_cache import LRUSizeCache
 
49
from ..sixish import (
 
50
    indexbytes,
 
51
    map,
 
52
    range,
 
53
    viewitems,
 
54
    )
 
55
from .versionedfile import (
 
56
    _KeyRefs,
 
57
    adapter_registry,
 
58
    AbsentContentFactory,
 
59
    ChunkedContentFactory,
 
60
    FulltextContentFactory,
 
61
    VersionedFilesWithFallbacks,
 
62
    )
 
63
 
 
64
# Minimum number of uncompressed bytes to try fetch at once when retrieving
 
65
# groupcompress blocks.
 
66
BATCH_SIZE = 2**16
 
67
 
 
68
# osutils.sha_string(b'')
 
69
_null_sha1 = b'da39a3ee5e6b4b0d3255bfef95601890afd80709'
 
70
 
 
71
 
 
72
def sort_gc_optimal(parent_map):
 
73
    """Sort and group the keys in parent_map into groupcompress order.
 
74
 
 
75
    groupcompress is defined (currently) as reverse-topological order, grouped
 
76
    by the key prefix.
 
77
 
 
78
    :return: A sorted-list of keys
 
79
    """
 
80
    # groupcompress ordering is approximately reverse topological,
 
81
    # properly grouped by file-id.
 
82
    per_prefix_map = {}
 
83
    for key, value in viewitems(parent_map):
 
84
        if isinstance(key, bytes) or len(key) == 1:
 
85
            prefix = b''
 
86
        else:
 
87
            prefix = key[0]
 
88
        try:
 
89
            per_prefix_map[prefix][key] = value
 
90
        except KeyError:
 
91
            per_prefix_map[prefix] = {key: value}
 
92
 
 
93
    present_keys = []
 
94
    for prefix in sorted(per_prefix_map):
 
95
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
 
96
    return present_keys
 
97
 
 
98
 
 
99
class DecompressCorruption(errors.BzrError):
 
100
 
 
101
    _fmt = "Corruption while decompressing repository file%(orig_error)s"
 
102
 
 
103
    def __init__(self, orig_error=None):
 
104
        if orig_error is not None:
 
105
            self.orig_error = ", %s" % (orig_error,)
 
106
        else:
 
107
            self.orig_error = ""
 
108
        errors.BzrError.__init__(self)
 
109
 
 
110
 
 
111
# The max zlib window size is 32kB, so if we set 'max_size' output of the
 
112
# decompressor to the requested bytes + 32kB, then we should guarantee
 
113
# num_bytes coming out.
 
114
_ZLIB_DECOMP_WINDOW = 32 * 1024
 
115
 
 
116
 
 
117
class GroupCompressBlock(object):
 
118
    """An object which maintains the internal structure of the compressed data.
 
119
 
 
120
    This tracks the meta info (start of text, length, type, etc.)
 
121
    """
 
122
 
 
123
    # Group Compress Block v1 Zlib
 
124
    GCB_HEADER = b'gcb1z\n'
 
125
    # Group Compress Block v1 Lzma
 
126
    GCB_LZ_HEADER = b'gcb1l\n'
 
127
    GCB_KNOWN_HEADERS = (GCB_HEADER, GCB_LZ_HEADER)
 
128
 
 
129
    def __init__(self):
 
130
        # map by key? or just order in file?
 
131
        self._compressor_name = None
 
132
        self._z_content_chunks = None
 
133
        self._z_content_decompressor = None
 
134
        self._z_content_length = None
 
135
        self._content_length = None
 
136
        self._content = None
 
137
        self._content_chunks = None
 
138
 
 
139
    def __len__(self):
 
140
        # This is the maximum number of bytes this object will reference if
 
141
        # everything is decompressed. However, if we decompress less than
 
142
        # everything... (this would cause some problems for LRUSizeCache)
 
143
        return self._content_length + self._z_content_length
 
144
 
 
145
    def _ensure_content(self, num_bytes=None):
 
146
        """Make sure that content has been expanded enough.
 
147
 
 
148
        :param num_bytes: Ensure that we have extracted at least num_bytes of
 
149
            content. If None, consume everything
 
150
        """
 
151
        if self._content_length is None:
 
152
            raise AssertionError('self._content_length should never be None')
 
153
        if num_bytes is None:
 
154
            num_bytes = self._content_length
 
155
        elif (self._content_length is not None
 
156
              and num_bytes > self._content_length):
 
157
            raise AssertionError(
 
158
                'requested num_bytes (%d) > content length (%d)'
 
159
                % (num_bytes, self._content_length))
 
160
        # Expand the content if required
 
161
        if self._content is None:
 
162
            if self._content_chunks is not None:
 
163
                self._content = b''.join(self._content_chunks)
 
164
                self._content_chunks = None
 
165
        if self._content is None:
 
166
            # We join self._z_content_chunks here, because if we are
 
167
            # decompressing, then it is *very* likely that we have a single
 
168
            # chunk
 
169
            if self._z_content_chunks is None:
 
170
                raise AssertionError('No content to decompress')
 
171
            z_content = b''.join(self._z_content_chunks)
 
172
            if z_content == b'':
 
173
                self._content = b''
 
174
            elif self._compressor_name == 'lzma':
 
175
                # We don't do partial lzma decomp yet
 
176
                import pylzma
 
177
                self._content = pylzma.decompress(z_content)
 
178
            elif self._compressor_name == 'zlib':
 
179
                # Start a zlib decompressor
 
180
                if num_bytes * 4 > self._content_length * 3:
 
181
                    # If we are requesting more that 3/4ths of the content,
 
182
                    # just extract the whole thing in a single pass
 
183
                    num_bytes = self._content_length
 
184
                    self._content = zlib.decompress(z_content)
 
185
                else:
 
186
                    self._z_content_decompressor = zlib.decompressobj()
 
187
                    # Seed the decompressor with the uncompressed bytes, so
 
188
                    # that the rest of the code is simplified
 
189
                    self._content = self._z_content_decompressor.decompress(
 
190
                        z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
 
191
                    if not self._z_content_decompressor.unconsumed_tail:
 
192
                        self._z_content_decompressor = None
 
193
            else:
 
194
                raise AssertionError('Unknown compressor: %r'
 
195
                                     % self._compressor_name)
 
196
        # Any bytes remaining to be decompressed will be in the decompressors
 
197
        # 'unconsumed_tail'
 
198
 
 
199
        # Do we have enough bytes already?
 
200
        if len(self._content) >= num_bytes:
 
201
            return
 
202
        # If we got this far, and don't have a decompressor, something is wrong
 
203
        if self._z_content_decompressor is None:
 
204
            raise AssertionError(
 
205
                'No decompressor to decompress %d bytes' % num_bytes)
 
206
        remaining_decomp = self._z_content_decompressor.unconsumed_tail
 
207
        if not remaining_decomp:
 
208
            raise AssertionError('Nothing left to decompress')
 
209
        needed_bytes = num_bytes - len(self._content)
 
210
        # We always set max_size to 32kB over the minimum needed, so that
 
211
        # zlib will give us as much as we really want.
 
212
        # TODO: If this isn't good enough, we could make a loop here,
 
213
        #       that keeps expanding the request until we get enough
 
214
        self._content += self._z_content_decompressor.decompress(
 
215
            remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
 
216
        if len(self._content) < num_bytes:
 
217
            raise AssertionError('%d bytes wanted, only %d available'
 
218
                                 % (num_bytes, len(self._content)))
 
219
        if not self._z_content_decompressor.unconsumed_tail:
 
220
            # The stream is finished
 
221
            self._z_content_decompressor = None
 
222
 
 
223
    def _parse_bytes(self, data, pos):
 
224
        """Read the various lengths from the header.
 
225
 
 
226
        This also populates the various 'compressed' buffers.
 
227
 
 
228
        :return: The position in bytes just after the last newline
 
229
        """
 
230
        # At present, we have 2 integers for the compressed and uncompressed
 
231
        # content. In base10 (ascii) 14 bytes can represent > 1TB, so to avoid
 
232
        # checking too far, cap the search to 14 bytes.
 
233
        pos2 = data.index(b'\n', pos, pos + 14)
 
234
        self._z_content_length = int(data[pos:pos2])
 
235
        pos = pos2 + 1
 
236
        pos2 = data.index(b'\n', pos, pos + 14)
 
237
        self._content_length = int(data[pos:pos2])
 
238
        pos = pos2 + 1
 
239
        if len(data) != (pos + self._z_content_length):
 
240
            # XXX: Define some GCCorrupt error ?
 
241
            raise AssertionError('Invalid bytes: (%d) != %d + %d' %
 
242
                                 (len(data), pos, self._z_content_length))
 
243
        self._z_content_chunks = (data[pos:],)
 
244
 
 
245
    @property
 
246
    def _z_content(self):
 
247
        """Return z_content_chunks as a simple string.
 
248
 
 
249
        Meant only to be used by the test suite.
 
250
        """
 
251
        if self._z_content_chunks is not None:
 
252
            return b''.join(self._z_content_chunks)
 
253
        return None
 
254
 
 
255
    @classmethod
 
256
    def from_bytes(cls, bytes):
 
257
        out = cls()
 
258
        header = bytes[:6]
 
259
        if header not in cls.GCB_KNOWN_HEADERS:
 
260
            raise ValueError('bytes did not start with any of %r'
 
261
                             % (cls.GCB_KNOWN_HEADERS,))
 
262
        if header == cls.GCB_HEADER:
 
263
            out._compressor_name = 'zlib'
 
264
        elif header == cls.GCB_LZ_HEADER:
 
265
            out._compressor_name = 'lzma'
 
266
        else:
 
267
            raise ValueError('unknown compressor: %r' % (header,))
 
268
        out._parse_bytes(bytes, 6)
 
269
        return out
 
270
 
 
271
    def extract(self, key, start, end, sha1=None):
 
272
        """Extract the text for a specific key.
 
273
 
 
274
        :param key: The label used for this content
 
275
        :param sha1: TODO (should we validate only when sha1 is supplied?)
 
276
        :return: The bytes for the content
 
277
        """
 
278
        if start == end == 0:
 
279
            return b''
 
280
        self._ensure_content(end)
 
281
        # The bytes are 'f' or 'd' for the type, then a variable-length
 
282
        # base128 integer for the content size, then the actual content
 
283
        # We know that the variable-length integer won't be longer than 5
 
284
        # bytes (it takes 5 bytes to encode 2^32)
 
285
        c = self._content[start:start + 1]
 
286
        if c == b'f':
 
287
            type = 'fulltext'
 
288
        else:
 
289
            if c != b'd':
 
290
                raise ValueError('Unknown content control code: %s'
 
291
                                 % (c,))
 
292
            type = 'delta'
 
293
        content_len, len_len = decode_base128_int(
 
294
            self._content[start + 1:start + 6])
 
295
        content_start = start + 1 + len_len
 
296
        if end != content_start + content_len:
 
297
            raise ValueError('end != len according to field header'
 
298
                             ' %s != %s' % (end, content_start + content_len))
 
299
        if c == b'f':
 
300
            return self._content[content_start:end]
 
301
        # Must be type delta as checked above
 
302
        return apply_delta_to_source(self._content, content_start, end)
 
303
 
 
304
    def set_chunked_content(self, content_chunks, length):
 
305
        """Set the content of this block to the given chunks."""
 
306
        # If we have lots of short lines, it is may be more efficient to join
 
307
        # the content ahead of time. If the content is <10MiB, we don't really
 
308
        # care about the extra memory consumption, so we can just pack it and
 
309
        # be done. However, timing showed 18s => 17.9s for repacking 1k revs of
 
310
        # mysql, which is below the noise margin
 
311
        self._content_length = length
 
312
        self._content_chunks = content_chunks
 
313
        self._content = None
 
314
        self._z_content_chunks = None
 
315
 
 
316
    def set_content(self, content):
 
317
        """Set the content of this block."""
 
318
        self._content_length = len(content)
 
319
        self._content = content
 
320
        self._z_content_chunks = None
 
321
 
 
322
    def _create_z_content_from_chunks(self, chunks):
 
323
        compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION)
 
324
        # Peak in this point is 1 fulltext, 1 compressed text, + zlib overhead
 
325
        # (measured peak is maybe 30MB over the above...)
 
326
        compressed_chunks = list(map(compressor.compress, chunks))
 
327
        compressed_chunks.append(compressor.flush())
 
328
        # Ignore empty chunks
 
329
        self._z_content_chunks = [c for c in compressed_chunks if c]
 
330
        self._z_content_length = sum(map(len, self._z_content_chunks))
 
331
 
 
332
    def _create_z_content(self):
 
333
        if self._z_content_chunks is not None:
 
334
            return
 
335
        if self._content_chunks is not None:
 
336
            chunks = self._content_chunks
 
337
        else:
 
338
            chunks = (self._content,)
 
339
        self._create_z_content_from_chunks(chunks)
 
340
 
 
341
    def to_chunks(self):
 
342
        """Create the byte stream as a series of 'chunks'"""
 
343
        self._create_z_content()
 
344
        header = self.GCB_HEADER
 
345
        chunks = [b'%s%d\n%d\n'
 
346
                  % (header, self._z_content_length, self._content_length),
 
347
                  ]
 
348
        chunks.extend(self._z_content_chunks)
 
349
        total_len = sum(map(len, chunks))
 
350
        return total_len, chunks
 
351
 
 
352
    def to_bytes(self):
 
353
        """Encode the information into a byte stream."""
 
354
        total_len, chunks = self.to_chunks()
 
355
        return b''.join(chunks)
 
356
 
 
357
    def _dump(self, include_text=False):
 
358
        """Take this block, and spit out a human-readable structure.
 
359
 
 
360
        :param include_text: Inserts also include text bits, chose whether you
 
361
            want this displayed in the dump or not.
 
362
        :return: A dump of the given block. The layout is something like:
 
363
            [('f', length), ('d', delta_length, text_length, [delta_info])]
 
364
            delta_info := [('i', num_bytes, text), ('c', offset, num_bytes),
 
365
            ...]
 
366
        """
 
367
        self._ensure_content()
 
368
        result = []
 
369
        pos = 0
 
370
        while pos < self._content_length:
 
371
            kind = self._content[pos:pos + 1]
 
372
            pos += 1
 
373
            if kind not in (b'f', b'd'):
 
374
                raise ValueError('invalid kind character: %r' % (kind,))
 
375
            content_len, len_len = decode_base128_int(
 
376
                self._content[pos:pos + 5])
 
377
            pos += len_len
 
378
            if content_len + pos > self._content_length:
 
379
                raise ValueError('invalid content_len %d for record @ pos %d'
 
380
                                 % (content_len, pos - len_len - 1))
 
381
            if kind == b'f':  # Fulltext
 
382
                if include_text:
 
383
                    text = self._content[pos:pos + content_len]
 
384
                    result.append((b'f', content_len, text))
 
385
                else:
 
386
                    result.append((b'f', content_len))
 
387
            elif kind == b'd':  # Delta
 
388
                delta_content = self._content[pos:pos + content_len]
 
389
                delta_info = []
 
390
                # The first entry in a delta is the decompressed length
 
391
                decomp_len, delta_pos = decode_base128_int(delta_content)
 
392
                result.append((b'd', content_len, decomp_len, delta_info))
 
393
                measured_len = 0
 
394
                while delta_pos < content_len:
 
395
                    c = indexbytes(delta_content, delta_pos)
 
396
                    delta_pos += 1
 
397
                    if c & 0x80:  # Copy
 
398
                        (offset, length,
 
399
                         delta_pos) = decode_copy_instruction(delta_content, c,
 
400
                                                              delta_pos)
 
401
                        if include_text:
 
402
                            text = self._content[offset:offset + length]
 
403
                            delta_info.append((b'c', offset, length, text))
 
404
                        else:
 
405
                            delta_info.append((b'c', offset, length))
 
406
                        measured_len += length
 
407
                    else:  # Insert
 
408
                        if include_text:
 
409
                            txt = delta_content[delta_pos:delta_pos + c]
 
410
                        else:
 
411
                            txt = b''
 
412
                        delta_info.append((b'i', c, txt))
 
413
                        measured_len += c
 
414
                        delta_pos += c
 
415
                if delta_pos != content_len:
 
416
                    raise ValueError('Delta consumed a bad number of bytes:'
 
417
                                     ' %d != %d' % (delta_pos, content_len))
 
418
                if measured_len != decomp_len:
 
419
                    raise ValueError('Delta claimed fulltext was %d bytes, but'
 
420
                                     ' extraction resulted in %d bytes'
 
421
                                     % (decomp_len, measured_len))
 
422
            pos += content_len
 
423
        return result
 
424
 
 
425
 
 
426
class _LazyGroupCompressFactory(object):
 
427
    """Yield content from a GroupCompressBlock on demand."""
 
428
 
 
429
    def __init__(self, key, parents, manager, start, end, first):
 
430
        """Create a _LazyGroupCompressFactory
 
431
 
 
432
        :param key: The key of just this record
 
433
        :param parents: The parents of this key (possibly None)
 
434
        :param gc_block: A GroupCompressBlock object
 
435
        :param start: Offset of the first byte for this record in the
 
436
            uncompressd content
 
437
        :param end: Offset of the byte just after the end of this record
 
438
            (ie, bytes = content[start:end])
 
439
        :param first: Is this the first Factory for the given block?
 
440
        """
 
441
        self.key = key
 
442
        self.parents = parents
 
443
        self.sha1 = None
 
444
        # Note: This attribute coupled with Manager._factories creates a
 
445
        #       reference cycle. Perhaps we would rather use a weakref(), or
 
446
        #       find an appropriate time to release the ref. After the first
 
447
        #       get_bytes_as call? After Manager.get_record_stream() returns
 
448
        #       the object?
 
449
        self._manager = manager
 
450
        self._bytes = None
 
451
        self.storage_kind = 'groupcompress-block'
 
452
        if not first:
 
453
            self.storage_kind = 'groupcompress-block-ref'
 
454
        self._first = first
 
455
        self._start = start
 
456
        self._end = end
 
457
 
 
458
    def __repr__(self):
 
459
        return '%s(%s, first=%s)' % (self.__class__.__name__,
 
460
                                     self.key, self._first)
 
461
 
 
462
    def get_bytes_as(self, storage_kind):
 
463
        if storage_kind == self.storage_kind:
 
464
            if self._first:
 
465
                # wire bytes, something...
 
466
                return self._manager._wire_bytes()
 
467
            else:
 
468
                return b''
 
469
        if storage_kind in ('fulltext', 'chunked'):
 
470
            if self._bytes is None:
 
471
                # Grab and cache the raw bytes for this entry
 
472
                # and break the ref-cycle with _manager since we don't need it
 
473
                # anymore
 
474
                try:
 
475
                    self._manager._prepare_for_extract()
 
476
                except zlib.error as value:
 
477
                    raise DecompressCorruption("zlib: " + str(value))
 
478
                block = self._manager._block
 
479
                self._bytes = block.extract(self.key, self._start, self._end)
 
480
                # There are code paths that first extract as fulltext, and then
 
481
                # extract as storage_kind (smart fetch). So we don't break the
 
482
                # refcycle here, but instead in manager.get_record_stream()
 
483
            if storage_kind == 'fulltext':
 
484
                return self._bytes
 
485
            else:
 
486
                return [self._bytes]
 
487
        raise errors.UnavailableRepresentation(self.key, storage_kind,
 
488
                                               self.storage_kind)
 
489
 
 
490
 
 
491
class _LazyGroupContentManager(object):
 
492
    """This manages a group of _LazyGroupCompressFactory objects."""
 
493
 
 
494
    _max_cut_fraction = 0.75  # We allow a block to be trimmed to 75% of
 
495
    # current size, and still be considered
 
496
    # resuable
 
497
    _full_block_size = 4 * 1024 * 1024
 
498
    _full_mixed_block_size = 2 * 1024 * 1024
 
499
    _full_enough_block_size = 3 * 1024 * 1024  # size at which we won't repack
 
500
    _full_enough_mixed_block_size = 2 * 768 * 1024  # 1.5MB
 
501
 
 
502
    def __init__(self, block, get_compressor_settings=None):
 
503
        self._block = block
 
504
        # We need to preserve the ordering
 
505
        self._factories = []
 
506
        self._last_byte = 0
 
507
        self._get_settings = get_compressor_settings
 
508
        self._compressor_settings = None
 
509
 
 
510
    def _get_compressor_settings(self):
 
511
        if self._compressor_settings is not None:
 
512
            return self._compressor_settings
 
513
        settings = None
 
514
        if self._get_settings is not None:
 
515
            settings = self._get_settings()
 
516
        if settings is None:
 
517
            vf = GroupCompressVersionedFiles
 
518
            settings = vf._DEFAULT_COMPRESSOR_SETTINGS
 
519
        self._compressor_settings = settings
 
520
        return self._compressor_settings
 
521
 
 
522
    def add_factory(self, key, parents, start, end):
 
523
        if not self._factories:
 
524
            first = True
 
525
        else:
 
526
            first = False
 
527
        # Note that this creates a reference cycle....
 
528
        factory = _LazyGroupCompressFactory(key, parents, self,
 
529
                                            start, end, first=first)
 
530
        # max() works here, but as a function call, doing a compare seems to be
 
531
        # significantly faster, timeit says 250ms for max() and 100ms for the
 
532
        # comparison
 
533
        if end > self._last_byte:
 
534
            self._last_byte = end
 
535
        self._factories.append(factory)
 
536
 
 
537
    def get_record_stream(self):
 
538
        """Get a record for all keys added so far."""
 
539
        for factory in self._factories:
 
540
            yield factory
 
541
            # Break the ref-cycle
 
542
            factory._bytes = None
 
543
            factory._manager = None
 
544
        # TODO: Consider setting self._factories = None after the above loop,
 
545
        #       as it will break the reference cycle
 
546
 
 
547
    def _trim_block(self, last_byte):
 
548
        """Create a new GroupCompressBlock, with just some of the content."""
 
549
        # None of the factories need to be adjusted, because the content is
 
550
        # located in an identical place. Just that some of the unreferenced
 
551
        # trailing bytes are stripped
 
552
        trace.mutter('stripping trailing bytes from groupcompress block'
 
553
                     ' %d => %d', self._block._content_length, last_byte)
 
554
        new_block = GroupCompressBlock()
 
555
        self._block._ensure_content(last_byte)
 
556
        new_block.set_content(self._block._content[:last_byte])
 
557
        self._block = new_block
 
558
 
 
559
    def _make_group_compressor(self):
 
560
        return GroupCompressor(self._get_compressor_settings())
 
561
 
 
562
    def _rebuild_block(self):
 
563
        """Create a new GroupCompressBlock with only the referenced texts."""
 
564
        compressor = self._make_group_compressor()
 
565
        tstart = time.time()
 
566
        old_length = self._block._content_length
 
567
        end_point = 0
 
568
        for factory in self._factories:
 
569
            bytes = factory.get_bytes_as('fulltext')
 
570
            (found_sha1, start_point, end_point,
 
571
             type) = compressor.compress(factory.key, bytes, factory.sha1)
 
572
            # Now update this factory with the new offsets, etc
 
573
            factory.sha1 = found_sha1
 
574
            factory._start = start_point
 
575
            factory._end = end_point
 
576
        self._last_byte = end_point
 
577
        new_block = compressor.flush()
 
578
        # TODO: Should we check that new_block really *is* smaller than the old
 
579
        #       block? It seems hard to come up with a method that it would
 
580
        #       expand, since we do full compression again. Perhaps based on a
 
581
        #       request that ends up poorly ordered?
 
582
        # TODO: If the content would have expanded, then we would want to
 
583
        #       handle a case where we need to split the block.
 
584
        #       Now that we have a user-tweakable option
 
585
        #       (max_bytes_to_index), it is possible that one person set it
 
586
        #       to a very low value, causing poor compression.
 
587
        delta = time.time() - tstart
 
588
        self._block = new_block
 
589
        trace.mutter('creating new compressed block on-the-fly in %.3fs'
 
590
                     ' %d bytes => %d bytes', delta, old_length,
 
591
                     self._block._content_length)
 
592
 
 
593
    def _prepare_for_extract(self):
 
594
        """A _LazyGroupCompressFactory is about to extract to fulltext."""
 
595
        # We expect that if one child is going to fulltext, all will be. This
 
596
        # helps prevent all of them from extracting a small amount at a time.
 
597
        # Which in itself isn't terribly expensive, but resizing 2MB 32kB at a
 
598
        # time (self._block._content) is a little expensive.
 
599
        self._block._ensure_content(self._last_byte)
 
600
 
 
601
    def _check_rebuild_action(self):
 
602
        """Check to see if our block should be repacked."""
 
603
        total_bytes_used = 0
 
604
        last_byte_used = 0
 
605
        for factory in self._factories:
 
606
            total_bytes_used += factory._end - factory._start
 
607
            if last_byte_used < factory._end:
 
608
                last_byte_used = factory._end
 
609
        # If we are using more than half of the bytes from the block, we have
 
610
        # nothing else to check
 
611
        if total_bytes_used * 2 >= self._block._content_length:
 
612
            return None, last_byte_used, total_bytes_used
 
613
        # We are using less than 50% of the content. Is the content we are
 
614
        # using at the beginning of the block? If so, we can just trim the
 
615
        # tail, rather than rebuilding from scratch.
 
616
        if total_bytes_used * 2 > last_byte_used:
 
617
            return 'trim', last_byte_used, total_bytes_used
 
618
 
 
619
        # We are using a small amount of the data, and it isn't just packed
 
620
        # nicely at the front, so rebuild the content.
 
621
        # Note: This would be *nicer* as a strip-data-from-group, rather than
 
622
        #       building it up again from scratch
 
623
        #       It might be reasonable to consider the fulltext sizes for
 
624
        #       different bits when deciding this, too. As you may have a small
 
625
        #       fulltext, and a trivial delta, and you are just trading around
 
626
        #       for another fulltext. If we do a simple 'prune' you may end up
 
627
        #       expanding many deltas into fulltexts, as well.
 
628
        #       If we build a cheap enough 'strip', then we could try a strip,
 
629
        #       if that expands the content, we then rebuild.
 
630
        return 'rebuild', last_byte_used, total_bytes_used
 
631
 
 
632
    def check_is_well_utilized(self):
 
633
        """Is the current block considered 'well utilized'?
 
634
 
 
635
        This heuristic asks if the current block considers itself to be a fully
 
636
        developed group, rather than just a loose collection of data.
 
637
        """
 
638
        if len(self._factories) == 1:
 
639
            # A block of length 1 could be improved by combining with other
 
640
            # groups - don't look deeper. Even larger than max size groups
 
641
            # could compress well with adjacent versions of the same thing.
 
642
            return False
 
643
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
 
644
        block_size = self._block._content_length
 
645
        if total_bytes_used < block_size * self._max_cut_fraction:
 
646
            # This block wants to trim itself small enough that we want to
 
647
            # consider it under-utilized.
 
648
            return False
 
649
        # TODO: This code is meant to be the twin of _insert_record_stream's
 
650
        #       'start_new_block' logic. It would probably be better to factor
 
651
        #       out that logic into a shared location, so that it stays
 
652
        #       together better
 
653
        # We currently assume a block is properly utilized whenever it is >75%
 
654
        # of the size of a 'full' block. In normal operation, a block is
 
655
        # considered full when it hits 4MB of same-file content. So any block
 
656
        # >3MB is 'full enough'.
 
657
        # The only time this isn't true is when a given block has large-object
 
658
        # content. (a single file >4MB, etc.)
 
659
        # Under these circumstances, we allow a block to grow to
 
660
        # 2 x largest_content.  Which means that if a given block had a large
 
661
        # object, it may actually be under-utilized. However, given that this
 
662
        # is 'pack-on-the-fly' it is probably reasonable to not repack large
 
663
        # content blobs on-the-fly. Note that because we return False for all
 
664
        # 1-item blobs, we will repack them; we may wish to reevaluate our
 
665
        # treatment of large object blobs in the future.
 
666
        if block_size >= self._full_enough_block_size:
 
667
            return True
 
668
        # If a block is <3MB, it still may be considered 'full' if it contains
 
669
        # mixed content. The current rule is 2MB of mixed content is considered
 
670
        # full. So check to see if this block contains mixed content, and
 
671
        # set the threshold appropriately.
 
672
        common_prefix = None
 
673
        for factory in self._factories:
 
674
            prefix = factory.key[:-1]
 
675
            if common_prefix is None:
 
676
                common_prefix = prefix
 
677
            elif prefix != common_prefix:
 
678
                # Mixed content, check the size appropriately
 
679
                if block_size >= self._full_enough_mixed_block_size:
 
680
                    return True
 
681
                break
 
682
        # The content failed both the mixed check and the single-content check
 
683
        # so obviously it is not fully utilized
 
684
        # TODO: there is one other constraint that isn't being checked
 
685
        #       namely, that the entries in the block are in the appropriate
 
686
        #       order. For example, you could insert the entries in exactly
 
687
        #       reverse groupcompress order, and we would think that is ok.
 
688
        #       (all the right objects are in one group, and it is fully
 
689
        #       utilized, etc.) For now, we assume that case is rare,
 
690
        #       especially since we should always fetch in 'groupcompress'
 
691
        #       order.
 
692
        return False
 
693
 
 
694
    def _check_rebuild_block(self):
 
695
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
 
696
        if action is None:
 
697
            return
 
698
        if action == 'trim':
 
699
            self._trim_block(last_byte_used)
 
700
        elif action == 'rebuild':
 
701
            self._rebuild_block()
 
702
        else:
 
703
            raise ValueError('unknown rebuild action: %r' % (action,))
 
704
 
 
705
    def _wire_bytes(self):
 
706
        """Return a byte stream suitable for transmitting over the wire."""
 
707
        self._check_rebuild_block()
 
708
        # The outer block starts with:
 
709
        #   'groupcompress-block\n'
 
710
        #   <length of compressed key info>\n
 
711
        #   <length of uncompressed info>\n
 
712
        #   <length of gc block>\n
 
713
        #   <header bytes>
 
714
        #   <gc-block>
 
715
        lines = [b'groupcompress-block\n']
 
716
        # The minimal info we need is the key, the start offset, and the
 
717
        # parents. The length and type are encoded in the record itself.
 
718
        # However, passing in the other bits makes it easier.  The list of
 
719
        # keys, and the start offset, the length
 
720
        # 1 line key
 
721
        # 1 line with parents, '' for ()
 
722
        # 1 line for start offset
 
723
        # 1 line for end byte
 
724
        header_lines = []
 
725
        for factory in self._factories:
 
726
            key_bytes = b'\x00'.join(factory.key)
 
727
            parents = factory.parents
 
728
            if parents is None:
 
729
                parent_bytes = b'None:'
 
730
            else:
 
731
                parent_bytes = b'\t'.join(b'\x00'.join(key) for key in parents)
 
732
            record_header = b'%s\n%s\n%d\n%d\n' % (
 
733
                key_bytes, parent_bytes, factory._start, factory._end)
 
734
            header_lines.append(record_header)
 
735
            # TODO: Can we break the refcycle at this point and set
 
736
            #       factory._manager = None?
 
737
        header_bytes = b''.join(header_lines)
 
738
        del header_lines
 
739
        header_bytes_len = len(header_bytes)
 
740
        z_header_bytes = zlib.compress(header_bytes)
 
741
        del header_bytes
 
742
        z_header_bytes_len = len(z_header_bytes)
 
743
        block_bytes_len, block_chunks = self._block.to_chunks()
 
744
        lines.append(b'%d\n%d\n%d\n' % (
 
745
            z_header_bytes_len, header_bytes_len, block_bytes_len))
 
746
        lines.append(z_header_bytes)
 
747
        lines.extend(block_chunks)
 
748
        del z_header_bytes, block_chunks
 
749
        # TODO: This is a point where we will double the memory consumption. To
 
750
        #       avoid this, we probably have to switch to a 'chunked' api
 
751
        return b''.join(lines)
 
752
 
 
753
    @classmethod
 
754
    def from_bytes(cls, bytes):
 
755
        # TODO: This does extra string copying, probably better to do it a
 
756
        #       different way. At a minimum this creates 2 copies of the
 
757
        #       compressed content
 
758
        (storage_kind, z_header_len, header_len,
 
759
         block_len, rest) = bytes.split(b'\n', 4)
 
760
        del bytes
 
761
        if storage_kind != b'groupcompress-block':
 
762
            raise ValueError('Unknown storage kind: %s' % (storage_kind,))
 
763
        z_header_len = int(z_header_len)
 
764
        if len(rest) < z_header_len:
 
765
            raise ValueError('Compressed header len shorter than all bytes')
 
766
        z_header = rest[:z_header_len]
 
767
        header_len = int(header_len)
 
768
        header = zlib.decompress(z_header)
 
769
        if len(header) != header_len:
 
770
            raise ValueError('invalid length for decompressed bytes')
 
771
        del z_header
 
772
        block_len = int(block_len)
 
773
        if len(rest) != z_header_len + block_len:
 
774
            raise ValueError('Invalid length for block')
 
775
        block_bytes = rest[z_header_len:]
 
776
        del rest
 
777
        # So now we have a valid GCB, we just need to parse the factories that
 
778
        # were sent to us
 
779
        header_lines = header.split(b'\n')
 
780
        del header
 
781
        last = header_lines.pop()
 
782
        if last != b'':
 
783
            raise ValueError('header lines did not end with a trailing'
 
784
                             ' newline')
 
785
        if len(header_lines) % 4 != 0:
 
786
            raise ValueError('The header was not an even multiple of 4 lines')
 
787
        block = GroupCompressBlock.from_bytes(block_bytes)
 
788
        del block_bytes
 
789
        result = cls(block)
 
790
        for start in range(0, len(header_lines), 4):
 
791
            # intern()?
 
792
            key = tuple(header_lines[start].split(b'\x00'))
 
793
            parents_line = header_lines[start + 1]
 
794
            if parents_line == b'None:':
 
795
                parents = None
 
796
            else:
 
797
                parents = tuple([tuple(segment.split(b'\x00'))
 
798
                                 for segment in parents_line.split(b'\t')
 
799
                                 if segment])
 
800
            start_offset = int(header_lines[start + 2])
 
801
            end_offset = int(header_lines[start + 3])
 
802
            result.add_factory(key, parents, start_offset, end_offset)
 
803
        return result
 
804
 
 
805
 
 
806
def network_block_to_records(storage_kind, bytes, line_end):
 
807
    if storage_kind != 'groupcompress-block':
 
808
        raise ValueError('Unknown storage kind: %s' % (storage_kind,))
 
809
    manager = _LazyGroupContentManager.from_bytes(bytes)
 
810
    return manager.get_record_stream()
 
811
 
 
812
 
 
813
class _CommonGroupCompressor(object):
 
814
 
 
815
    def __init__(self, settings=None):
 
816
        """Create a GroupCompressor."""
 
817
        self.chunks = []
 
818
        self._last = None
 
819
        self.endpoint = 0
 
820
        self.input_bytes = 0
 
821
        self.labels_deltas = {}
 
822
        self._delta_index = None  # Set by the children
 
823
        self._block = GroupCompressBlock()
 
824
        if settings is None:
 
825
            self._settings = {}
 
826
        else:
 
827
            self._settings = settings
 
828
 
 
829
    def compress(self, key, bytes, expected_sha, nostore_sha=None, soft=False):
 
830
        """Compress lines with label key.
 
831
 
 
832
        :param key: A key tuple. It is stored in the output
 
833
            for identification of the text during decompression. If the last
 
834
            element is b'None' it is replaced with the sha1 of the text -
 
835
            e.g. sha1:xxxxxxx.
 
836
        :param bytes: The bytes to be compressed
 
837
        :param expected_sha: If non-None, the sha the lines are believed to
 
838
            have. During compression the sha is calculated; a mismatch will
 
839
            cause an error.
 
840
        :param nostore_sha: If the computed sha1 sum matches, we will raise
 
841
            ExistingContent rather than adding the text.
 
842
        :param soft: Do a 'soft' compression. This means that we require larger
 
843
            ranges to match to be considered for a copy command.
 
844
 
 
845
        :return: The sha1 of lines, the start and end offsets in the delta, and
 
846
            the type ('fulltext' or 'delta').
 
847
 
 
848
        :seealso VersionedFiles.add_lines:
 
849
        """
 
850
        if not bytes:  # empty, like a dir entry, etc
 
851
            if nostore_sha == _null_sha1:
 
852
                raise errors.ExistingContent()
 
853
            return _null_sha1, 0, 0, 'fulltext'
 
854
        # we assume someone knew what they were doing when they passed it in
 
855
        if expected_sha is not None:
 
856
            sha1 = expected_sha
 
857
        else:
 
858
            sha1 = osutils.sha_string(bytes)
 
859
        if nostore_sha is not None:
 
860
            if sha1 == nostore_sha:
 
861
                raise errors.ExistingContent()
 
862
        if key[-1] is None:
 
863
            key = key[:-1] + (b'sha1:' + sha1,)
 
864
 
 
865
        start, end, type = self._compress(key, bytes, len(bytes) / 2, soft)
 
866
        return sha1, start, end, type
 
867
 
 
868
    def _compress(self, key, bytes, max_delta_size, soft=False):
 
869
        """Compress lines with label key.
 
870
 
 
871
        :param key: A key tuple. It is stored in the output for identification
 
872
            of the text during decompression.
 
873
 
 
874
        :param bytes: The bytes to be compressed
 
875
 
 
876
        :param max_delta_size: The size above which we issue a fulltext instead
 
877
            of a delta.
 
878
 
 
879
        :param soft: Do a 'soft' compression. This means that we require larger
 
880
            ranges to match to be considered for a copy command.
 
881
 
 
882
        :return: The sha1 of lines, the start and end offsets in the delta, and
 
883
            the type ('fulltext' or 'delta').
 
884
        """
 
885
        raise NotImplementedError(self._compress)
 
886
 
 
887
    def extract(self, key):
 
888
        """Extract a key previously added to the compressor.
 
889
 
 
890
        :param key: The key to extract.
 
891
        :return: An iterable over bytes and the sha1.
 
892
        """
 
893
        (start_byte, start_chunk, end_byte,
 
894
         end_chunk) = self.labels_deltas[key]
 
895
        delta_chunks = self.chunks[start_chunk:end_chunk]
 
896
        stored_bytes = b''.join(delta_chunks)
 
897
        kind = stored_bytes[:1]
 
898
        if kind == b'f':
 
899
            fulltext_len, offset = decode_base128_int(stored_bytes[1:10])
 
900
            data_len = fulltext_len + 1 + offset
 
901
            if data_len != len(stored_bytes):
 
902
                raise ValueError('Index claimed fulltext len, but stored bytes'
 
903
                                 ' claim %s != %s'
 
904
                                 % (len(stored_bytes), data_len))
 
905
            data = stored_bytes[offset + 1:]
 
906
        else:
 
907
            if kind != b'd':
 
908
                raise ValueError('Unknown content kind, bytes claim %s' % kind)
 
909
            # XXX: This is inefficient at best
 
910
            source = b''.join(self.chunks[:start_chunk])
 
911
            delta_len, offset = decode_base128_int(stored_bytes[1:10])
 
912
            data_len = delta_len + 1 + offset
 
913
            if data_len != len(stored_bytes):
 
914
                raise ValueError('Index claimed delta len, but stored bytes'
 
915
                                 ' claim %s != %s'
 
916
                                 % (len(stored_bytes), data_len))
 
917
            data = apply_delta(source, stored_bytes[offset + 1:])
 
918
        data_sha1 = osutils.sha_string(data)
 
919
        return data, data_sha1
 
920
 
 
921
    def flush(self):
 
922
        """Finish this group, creating a formatted stream.
 
923
 
 
924
        After calling this, the compressor should no longer be used
 
925
        """
 
926
        self._block.set_chunked_content(self.chunks, self.endpoint)
 
927
        self.chunks = None
 
928
        self._delta_index = None
 
929
        return self._block
 
930
 
 
931
    def pop_last(self):
 
932
        """Call this if you want to 'revoke' the last compression.
 
933
 
 
934
        After this, the data structures will be rolled back, but you cannot do
 
935
        more compression.
 
936
        """
 
937
        self._delta_index = None
 
938
        del self.chunks[self._last[0]:]
 
939
        self.endpoint = self._last[1]
 
940
        self._last = None
 
941
 
 
942
    def ratio(self):
 
943
        """Return the overall compression ratio."""
 
944
        return float(self.input_bytes) / float(self.endpoint)
 
945
 
 
946
 
 
947
class PythonGroupCompressor(_CommonGroupCompressor):
 
948
 
 
949
    def __init__(self, settings=None):
 
950
        """Create a GroupCompressor.
 
951
 
 
952
        Used only if the pyrex version is not available.
 
953
        """
 
954
        super(PythonGroupCompressor, self).__init__(settings)
 
955
        self._delta_index = LinesDeltaIndex([])
 
956
        # The actual content is managed by LinesDeltaIndex
 
957
        self.chunks = self._delta_index.lines
 
958
 
 
959
    def _compress(self, key, bytes, max_delta_size, soft=False):
 
960
        """see _CommonGroupCompressor._compress"""
 
961
        input_len = len(bytes)
 
962
        new_lines = osutils.split_lines(bytes)
 
963
        out_lines, index_lines = self._delta_index.make_delta(
 
964
            new_lines, bytes_length=input_len, soft=soft)
 
965
        delta_length = sum(map(len, out_lines))
 
966
        if delta_length > max_delta_size:
 
967
            # The delta is longer than the fulltext, insert a fulltext
 
968
            type = 'fulltext'
 
969
            out_lines = [b'f', encode_base128_int(input_len)]
 
970
            out_lines.extend(new_lines)
 
971
            index_lines = [False, False]
 
972
            index_lines.extend([True] * len(new_lines))
 
973
        else:
 
974
            # this is a worthy delta, output it
 
975
            type = 'delta'
 
976
            out_lines[0] = b'd'
 
977
            # Update the delta_length to include those two encoded integers
 
978
            out_lines[1] = encode_base128_int(delta_length)
 
979
        # Before insertion
 
980
        start = self.endpoint
 
981
        chunk_start = len(self.chunks)
 
982
        self._last = (chunk_start, self.endpoint)
 
983
        self._delta_index.extend_lines(out_lines, index_lines)
 
984
        self.endpoint = self._delta_index.endpoint
 
985
        self.input_bytes += input_len
 
986
        chunk_end = len(self.chunks)
 
987
        self.labels_deltas[key] = (start, chunk_start,
 
988
                                   self.endpoint, chunk_end)
 
989
        return start, self.endpoint, type
 
990
 
 
991
 
 
992
class PyrexGroupCompressor(_CommonGroupCompressor):
 
993
    """Produce a serialised group of compressed texts.
 
994
 
 
995
    It contains code very similar to SequenceMatcher because of having a similar
 
996
    task. However some key differences apply:
 
997
 
 
998
    * there is no junk, we want a minimal edit not a human readable diff.
 
999
    * we don't filter very common lines (because we don't know where a good
 
1000
      range will start, and after the first text we want to be emitting minmal
 
1001
      edits only.
 
1002
    * we chain the left side, not the right side
 
1003
    * we incrementally update the adjacency matrix as new lines are provided.
 
1004
    * we look for matches in all of the left side, so the routine which does
 
1005
      the analagous task of find_longest_match does not need to filter on the
 
1006
      left side.
 
1007
    """
 
1008
 
 
1009
    def __init__(self, settings=None):
 
1010
        super(PyrexGroupCompressor, self).__init__(settings)
 
1011
        max_bytes_to_index = self._settings.get('max_bytes_to_index', 0)
 
1012
        self._delta_index = DeltaIndex(max_bytes_to_index=max_bytes_to_index)
 
1013
 
 
1014
    def _compress(self, key, bytes, max_delta_size, soft=False):
 
1015
        """see _CommonGroupCompressor._compress"""
 
1016
        input_len = len(bytes)
 
1017
        # By having action/label/sha1/len, we can parse the group if the index
 
1018
        # was ever destroyed, we have the key in 'label', we know the final
 
1019
        # bytes are valid from sha1, and we know where to find the end of this
 
1020
        # record because of 'len'. (the delta record itself will store the
 
1021
        # total length for the expanded record)
 
1022
        # 'len: %d\n' costs approximately 1% increase in total data
 
1023
        # Having the labels at all costs us 9-10% increase, 38% increase for
 
1024
        # inventory pages, and 5.8% increase for text pages
 
1025
        # new_chunks = ['label:%s\nsha1:%s\n' % (label, sha1)]
 
1026
        if self._delta_index._source_offset != self.endpoint:
 
1027
            raise AssertionError('_source_offset != endpoint'
 
1028
                                 ' somehow the DeltaIndex got out of sync with'
 
1029
                                 ' the output lines')
 
1030
        delta = self._delta_index.make_delta(bytes, max_delta_size)
 
1031
        if (delta is None):
 
1032
            type = 'fulltext'
 
1033
            enc_length = encode_base128_int(len(bytes))
 
1034
            len_mini_header = 1 + len(enc_length)
 
1035
            self._delta_index.add_source(bytes, len_mini_header)
 
1036
            new_chunks = [b'f', enc_length, bytes]
 
1037
        else:
 
1038
            type = 'delta'
 
1039
            enc_length = encode_base128_int(len(delta))
 
1040
            len_mini_header = 1 + len(enc_length)
 
1041
            new_chunks = [b'd', enc_length, delta]
 
1042
            self._delta_index.add_delta_source(delta, len_mini_header)
 
1043
        # Before insertion
 
1044
        start = self.endpoint
 
1045
        chunk_start = len(self.chunks)
 
1046
        # Now output these bytes
 
1047
        self._output_chunks(new_chunks)
 
1048
        self.input_bytes += input_len
 
1049
        chunk_end = len(self.chunks)
 
1050
        self.labels_deltas[key] = (start, chunk_start,
 
1051
                                   self.endpoint, chunk_end)
 
1052
        if not self._delta_index._source_offset == self.endpoint:
 
1053
            raise AssertionError('the delta index is out of sync'
 
1054
                                 'with the output lines %s != %s'
 
1055
                                 % (self._delta_index._source_offset, self.endpoint))
 
1056
        return start, self.endpoint, type
 
1057
 
 
1058
    def _output_chunks(self, new_chunks):
 
1059
        """Output some chunks.
 
1060
 
 
1061
        :param new_chunks: The chunks to output.
 
1062
        """
 
1063
        self._last = (len(self.chunks), self.endpoint)
 
1064
        endpoint = self.endpoint
 
1065
        self.chunks.extend(new_chunks)
 
1066
        endpoint += sum(map(len, new_chunks))
 
1067
        self.endpoint = endpoint
 
1068
 
 
1069
 
 
1070
def make_pack_factory(graph, delta, keylength, inconsistency_fatal=True):
 
1071
    """Create a factory for creating a pack based groupcompress.
 
1072
 
 
1073
    This is only functional enough to run interface tests, it doesn't try to
 
1074
    provide a full pack environment.
 
1075
 
 
1076
    :param graph: Store a graph.
 
1077
    :param delta: Delta compress contents.
 
1078
    :param keylength: How long should keys be.
 
1079
    """
 
1080
    def factory(transport):
 
1081
        parents = graph
 
1082
        ref_length = 0
 
1083
        if graph:
 
1084
            ref_length = 1
 
1085
        graph_index = BTreeBuilder(reference_lists=ref_length,
 
1086
                                   key_elements=keylength)
 
1087
        stream = transport.open_write_stream('newpack')
 
1088
        writer = pack.ContainerWriter(stream.write)
 
1089
        writer.begin()
 
1090
        index = _GCGraphIndex(graph_index, lambda: True, parents=parents,
 
1091
                              add_callback=graph_index.add_nodes,
 
1092
                              inconsistency_fatal=inconsistency_fatal)
 
1093
        access = pack_repo._DirectPackAccess({})
 
1094
        access.set_writer(writer, graph_index, (transport, 'newpack'))
 
1095
        result = GroupCompressVersionedFiles(index, access, delta)
 
1096
        result.stream = stream
 
1097
        result.writer = writer
 
1098
        return result
 
1099
    return factory
 
1100
 
 
1101
 
 
1102
def cleanup_pack_group(versioned_files):
 
1103
    versioned_files.writer.end()
 
1104
    versioned_files.stream.close()
 
1105
 
 
1106
 
 
1107
class _BatchingBlockFetcher(object):
 
1108
    """Fetch group compress blocks in batches.
 
1109
 
 
1110
    :ivar total_bytes: int of expected number of bytes needed to fetch the
 
1111
        currently pending batch.
 
1112
    """
 
1113
 
 
1114
    def __init__(self, gcvf, locations, get_compressor_settings=None):
 
1115
        self.gcvf = gcvf
 
1116
        self.locations = locations
 
1117
        self.keys = []
 
1118
        self.batch_memos = {}
 
1119
        self.memos_to_get = []
 
1120
        self.total_bytes = 0
 
1121
        self.last_read_memo = None
 
1122
        self.manager = None
 
1123
        self._get_compressor_settings = get_compressor_settings
 
1124
 
 
1125
    def add_key(self, key):
 
1126
        """Add another to key to fetch.
 
1127
 
 
1128
        :return: The estimated number of bytes needed to fetch the batch so
 
1129
            far.
 
1130
        """
 
1131
        self.keys.append(key)
 
1132
        index_memo, _, _, _ = self.locations[key]
 
1133
        read_memo = index_memo[0:3]
 
1134
        # Three possibilities for this read_memo:
 
1135
        #  - it's already part of this batch; or
 
1136
        #  - it's not yet part of this batch, but is already cached; or
 
1137
        #  - it's not yet part of this batch and will need to be fetched.
 
1138
        if read_memo in self.batch_memos:
 
1139
            # This read memo is already in this batch.
 
1140
            return self.total_bytes
 
1141
        try:
 
1142
            cached_block = self.gcvf._group_cache[read_memo]
 
1143
        except KeyError:
 
1144
            # This read memo is new to this batch, and the data isn't cached
 
1145
            # either.
 
1146
            self.batch_memos[read_memo] = None
 
1147
            self.memos_to_get.append(read_memo)
 
1148
            byte_length = read_memo[2]
 
1149
            self.total_bytes += byte_length
 
1150
        else:
 
1151
            # This read memo is new to this batch, but cached.
 
1152
            # Keep a reference to the cached block in batch_memos because it's
 
1153
            # certain that we'll use it when this batch is processed, but
 
1154
            # there's a risk that it would fall out of _group_cache between now
 
1155
            # and then.
 
1156
            self.batch_memos[read_memo] = cached_block
 
1157
        return self.total_bytes
 
1158
 
 
1159
    def _flush_manager(self):
 
1160
        if self.manager is not None:
 
1161
            for factory in self.manager.get_record_stream():
 
1162
                yield factory
 
1163
            self.manager = None
 
1164
            self.last_read_memo = None
 
1165
 
 
1166
    def yield_factories(self, full_flush=False):
 
1167
        """Yield factories for keys added since the last yield.  They will be
 
1168
        returned in the order they were added via add_key.
 
1169
 
 
1170
        :param full_flush: by default, some results may not be returned in case
 
1171
            they can be part of the next batch.  If full_flush is True, then
 
1172
            all results are returned.
 
1173
        """
 
1174
        if self.manager is None and not self.keys:
 
1175
            return
 
1176
        # Fetch all memos in this batch.
 
1177
        blocks = self.gcvf._get_blocks(self.memos_to_get)
 
1178
        # Turn blocks into factories and yield them.
 
1179
        memos_to_get_stack = list(self.memos_to_get)
 
1180
        memos_to_get_stack.reverse()
 
1181
        for key in self.keys:
 
1182
            index_memo, _, parents, _ = self.locations[key]
 
1183
            read_memo = index_memo[:3]
 
1184
            if self.last_read_memo != read_memo:
 
1185
                # We are starting a new block. If we have a
 
1186
                # manager, we have found everything that fits for
 
1187
                # now, so yield records
 
1188
                for factory in self._flush_manager():
 
1189
                    yield factory
 
1190
                # Now start a new manager.
 
1191
                if memos_to_get_stack and memos_to_get_stack[-1] == read_memo:
 
1192
                    # The next block from _get_blocks will be the block we
 
1193
                    # need.
 
1194
                    block_read_memo, block = next(blocks)
 
1195
                    if block_read_memo != read_memo:
 
1196
                        raise AssertionError(
 
1197
                            "block_read_memo out of sync with read_memo"
 
1198
                            "(%r != %r)" % (block_read_memo, read_memo))
 
1199
                    self.batch_memos[read_memo] = block
 
1200
                    memos_to_get_stack.pop()
 
1201
                else:
 
1202
                    block = self.batch_memos[read_memo]
 
1203
                self.manager = _LazyGroupContentManager(block,
 
1204
                                                        get_compressor_settings=self._get_compressor_settings)
 
1205
                self.last_read_memo = read_memo
 
1206
            start, end = index_memo[3:5]
 
1207
            self.manager.add_factory(key, parents, start, end)
 
1208
        if full_flush:
 
1209
            for factory in self._flush_manager():
 
1210
                yield factory
 
1211
        del self.keys[:]
 
1212
        self.batch_memos.clear()
 
1213
        del self.memos_to_get[:]
 
1214
        self.total_bytes = 0
 
1215
 
 
1216
 
 
1217
class GroupCompressVersionedFiles(VersionedFilesWithFallbacks):
 
1218
    """A group-compress based VersionedFiles implementation."""
 
1219
 
 
1220
    # This controls how the GroupCompress DeltaIndex works. Basically, we
 
1221
    # compute hash pointers into the source blocks (so hash(text) => text).
 
1222
    # However each of these references costs some memory in trade against a
 
1223
    # more accurate match result. For very large files, they either are
 
1224
    # pre-compressed and change in bulk whenever they change, or change in just
 
1225
    # local blocks. Either way, 'improved resolution' is not very helpful,
 
1226
    # versus running out of memory trying to track everything. The default max
 
1227
    # gives 100% sampling of a 1MB file.
 
1228
    _DEFAULT_MAX_BYTES_TO_INDEX = 1024 * 1024
 
1229
    _DEFAULT_COMPRESSOR_SETTINGS = {'max_bytes_to_index':
 
1230
                                    _DEFAULT_MAX_BYTES_TO_INDEX}
 
1231
 
 
1232
    def __init__(self, index, access, delta=True, _unadded_refs=None,
 
1233
                 _group_cache=None):
 
1234
        """Create a GroupCompressVersionedFiles object.
 
1235
 
 
1236
        :param index: The index object storing access and graph data.
 
1237
        :param access: The access object storing raw data.
 
1238
        :param delta: Whether to delta compress or just entropy compress.
 
1239
        :param _unadded_refs: private parameter, don't use.
 
1240
        :param _group_cache: private parameter, don't use.
 
1241
        """
 
1242
        self._index = index
 
1243
        self._access = access
 
1244
        self._delta = delta
 
1245
        if _unadded_refs is None:
 
1246
            _unadded_refs = {}
 
1247
        self._unadded_refs = _unadded_refs
 
1248
        if _group_cache is None:
 
1249
            _group_cache = LRUSizeCache(max_size=50 * 1024 * 1024)
 
1250
        self._group_cache = _group_cache
 
1251
        self._immediate_fallback_vfs = []
 
1252
        self._max_bytes_to_index = None
 
1253
 
 
1254
    def without_fallbacks(self):
 
1255
        """Return a clone of this object without any fallbacks configured."""
 
1256
        return GroupCompressVersionedFiles(self._index, self._access,
 
1257
                                           self._delta, _unadded_refs=dict(
 
1258
                                               self._unadded_refs),
 
1259
                                           _group_cache=self._group_cache)
 
1260
 
 
1261
    def add_lines(self, key, parents, lines, parent_texts=None,
 
1262
                  left_matching_blocks=None, nostore_sha=None, random_id=False,
 
1263
                  check_content=True):
 
1264
        """Add a text to the store.
 
1265
 
 
1266
        :param key: The key tuple of the text to add.
 
1267
        :param parents: The parents key tuples of the text to add.
 
1268
        :param lines: A list of lines. Each line must be a bytestring. And all
 
1269
            of them except the last must be terminated with \\n and contain no
 
1270
            other \\n's. The last line may either contain no \\n's or a single
 
1271
            terminating \\n. If the lines list does meet this constraint the
 
1272
            add routine may error or may succeed - but you will be unable to
 
1273
            read the data back accurately. (Checking the lines have been split
 
1274
            correctly is expensive and extremely unlikely to catch bugs so it
 
1275
            is not done at runtime unless check_content is True.)
 
1276
        :param parent_texts: An optional dictionary containing the opaque
 
1277
            representations of some or all of the parents of version_id to
 
1278
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
1279
            returned by add_lines or data corruption can be caused.
 
1280
        :param left_matching_blocks: a hint about which areas are common
 
1281
            between the text and its left-hand-parent.  The format is
 
1282
            the SequenceMatcher.get_matching_blocks format.
 
1283
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
1284
            the versioned file if the digest of the lines matches this.
 
1285
        :param random_id: If True a random id has been selected rather than
 
1286
            an id determined by some deterministic process such as a converter
 
1287
            from a foreign VCS. When True the backend may choose not to check
 
1288
            for uniqueness of the resulting key within the versioned file, so
 
1289
            this should only be done when the result is expected to be unique
 
1290
            anyway.
 
1291
        :param check_content: If True, the lines supplied are verified to be
 
1292
            bytestrings that are correctly formed lines.
 
1293
        :return: The text sha1, the number of bytes in the text, and an opaque
 
1294
                 representation of the inserted version which can be provided
 
1295
                 back to future add_lines calls in the parent_texts dictionary.
 
1296
        """
 
1297
        self._index._check_write_ok()
 
1298
        self._check_add(key, lines, random_id, check_content)
 
1299
        if parents is None:
 
1300
            # The caller might pass None if there is no graph data, but kndx
 
1301
            # indexes can't directly store that, so we give them
 
1302
            # an empty tuple instead.
 
1303
            parents = ()
 
1304
        # double handling for now. Make it work until then.
 
1305
        length = sum(map(len, lines))
 
1306
        record = ChunkedContentFactory(key, parents, None, lines)
 
1307
        sha1 = list(self._insert_record_stream([record], random_id=random_id,
 
1308
                                               nostore_sha=nostore_sha))[0]
 
1309
        return sha1, length, None
 
1310
 
 
1311
    def add_fallback_versioned_files(self, a_versioned_files):
 
1312
        """Add a source of texts for texts not present in this knit.
 
1313
 
 
1314
        :param a_versioned_files: A VersionedFiles object.
 
1315
        """
 
1316
        self._immediate_fallback_vfs.append(a_versioned_files)
 
1317
 
 
1318
    def annotate(self, key):
 
1319
        """See VersionedFiles.annotate."""
 
1320
        ann = annotate.Annotator(self)
 
1321
        return ann.annotate_flat(key)
 
1322
 
 
1323
    def get_annotator(self):
 
1324
        return annotate.Annotator(self)
 
1325
 
 
1326
    def check(self, progress_bar=None, keys=None):
 
1327
        """See VersionedFiles.check()."""
 
1328
        if keys is None:
 
1329
            keys = self.keys()
 
1330
            for record in self.get_record_stream(keys, 'unordered', True):
 
1331
                record.get_bytes_as('fulltext')
 
1332
        else:
 
1333
            return self.get_record_stream(keys, 'unordered', True)
 
1334
 
 
1335
    def clear_cache(self):
 
1336
        """See VersionedFiles.clear_cache()"""
 
1337
        self._group_cache.clear()
 
1338
        self._index._graph_index.clear_cache()
 
1339
        self._index._int_cache.clear()
 
1340
 
 
1341
    def _check_add(self, key, lines, random_id, check_content):
 
1342
        """check that version_id and lines are safe to add."""
 
1343
        version_id = key[-1]
 
1344
        if version_id is not None:
 
1345
            if osutils.contains_whitespace(version_id):
 
1346
                raise errors.InvalidRevisionId(version_id, self)
 
1347
        self.check_not_reserved_id(version_id)
 
1348
        # TODO: If random_id==False and the key is already present, we should
 
1349
        # probably check that the existing content is identical to what is
 
1350
        # being inserted, and otherwise raise an exception.  This would make
 
1351
        # the bundle code simpler.
 
1352
        if check_content:
 
1353
            self._check_lines_not_unicode(lines)
 
1354
            self._check_lines_are_lines(lines)
 
1355
 
 
1356
    def get_parent_map(self, keys):
 
1357
        """Get a map of the graph parents of keys.
 
1358
 
 
1359
        :param keys: The keys to look up parents for.
 
1360
        :return: A mapping from keys to parents. Absent keys are absent from
 
1361
            the mapping.
 
1362
        """
 
1363
        return self._get_parent_map_with_sources(keys)[0]
 
1364
 
 
1365
    def _get_parent_map_with_sources(self, keys):
 
1366
        """Get a map of the parents of keys.
 
1367
 
 
1368
        :param keys: The keys to look up parents for.
 
1369
        :return: A tuple. The first element is a mapping from keys to parents.
 
1370
            Absent keys are absent from the mapping. The second element is a
 
1371
            list with the locations each key was found in. The first element
 
1372
            is the in-this-knit parents, the second the first fallback source,
 
1373
            and so on.
 
1374
        """
 
1375
        result = {}
 
1376
        sources = [self._index] + self._immediate_fallback_vfs
 
1377
        source_results = []
 
1378
        missing = set(keys)
 
1379
        for source in sources:
 
1380
            if not missing:
 
1381
                break
 
1382
            new_result = source.get_parent_map(missing)
 
1383
            source_results.append(new_result)
 
1384
            result.update(new_result)
 
1385
            missing.difference_update(set(new_result))
 
1386
        return result, source_results
 
1387
 
 
1388
    def _get_blocks(self, read_memos):
 
1389
        """Get GroupCompressBlocks for the given read_memos.
 
1390
 
 
1391
        :returns: a series of (read_memo, block) pairs, in the order they were
 
1392
            originally passed.
 
1393
        """
 
1394
        cached = {}
 
1395
        for read_memo in read_memos:
 
1396
            try:
 
1397
                block = self._group_cache[read_memo]
 
1398
            except KeyError:
 
1399
                pass
 
1400
            else:
 
1401
                cached[read_memo] = block
 
1402
        not_cached = []
 
1403
        not_cached_seen = set()
 
1404
        for read_memo in read_memos:
 
1405
            if read_memo in cached:
 
1406
                # Don't fetch what we already have
 
1407
                continue
 
1408
            if read_memo in not_cached_seen:
 
1409
                # Don't try to fetch the same data twice
 
1410
                continue
 
1411
            not_cached.append(read_memo)
 
1412
            not_cached_seen.add(read_memo)
 
1413
        raw_records = self._access.get_raw_records(not_cached)
 
1414
        for read_memo in read_memos:
 
1415
            try:
 
1416
                yield read_memo, cached[read_memo]
 
1417
            except KeyError:
 
1418
                # Read the block, and cache it.
 
1419
                zdata = next(raw_records)
 
1420
                block = GroupCompressBlock.from_bytes(zdata)
 
1421
                self._group_cache[read_memo] = block
 
1422
                cached[read_memo] = block
 
1423
                yield read_memo, block
 
1424
 
 
1425
    def get_missing_compression_parent_keys(self):
 
1426
        """Return the keys of missing compression parents.
 
1427
 
 
1428
        Missing compression parents occur when a record stream was missing
 
1429
        basis texts, or a index was scanned that had missing basis texts.
 
1430
        """
 
1431
        # GroupCompress cannot currently reference texts that are not in the
 
1432
        # group, so this is valid for now
 
1433
        return frozenset()
 
1434
 
 
1435
    def get_record_stream(self, keys, ordering, include_delta_closure):
 
1436
        """Get a stream of records for keys.
 
1437
 
 
1438
        :param keys: The keys to include.
 
1439
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
1440
            sorted stream has compression parents strictly before their
 
1441
            children.
 
1442
        :param include_delta_closure: If True then the closure across any
 
1443
            compression parents will be included (in the opaque data).
 
1444
        :return: An iterator of ContentFactory objects, each of which is only
 
1445
            valid until the iterator is advanced.
 
1446
        """
 
1447
        # keys might be a generator
 
1448
        orig_keys = list(keys)
 
1449
        keys = set(keys)
 
1450
        if not keys:
 
1451
            return
 
1452
        if (not self._index.has_graph
 
1453
                and ordering in ('topological', 'groupcompress')):
 
1454
            # Cannot topological order when no graph has been stored.
 
1455
            # but we allow 'as-requested' or 'unordered'
 
1456
            ordering = 'unordered'
 
1457
 
 
1458
        remaining_keys = keys
 
1459
        while True:
 
1460
            try:
 
1461
                keys = set(remaining_keys)
 
1462
                for content_factory in self._get_remaining_record_stream(keys,
 
1463
                                                                         orig_keys, ordering, include_delta_closure):
 
1464
                    remaining_keys.discard(content_factory.key)
 
1465
                    yield content_factory
 
1466
                return
 
1467
            except errors.RetryWithNewPacks as e:
 
1468
                self._access.reload_or_raise(e)
 
1469
 
 
1470
    def _find_from_fallback(self, missing):
 
1471
        """Find whatever keys you can from the fallbacks.
 
1472
 
 
1473
        :param missing: A set of missing keys. This set will be mutated as keys
 
1474
            are found from a fallback_vfs
 
1475
        :return: (parent_map, key_to_source_map, source_results)
 
1476
            parent_map  the overall key => parent_keys
 
1477
            key_to_source_map   a dict from {key: source}
 
1478
            source_results      a list of (source: keys)
 
1479
        """
 
1480
        parent_map = {}
 
1481
        key_to_source_map = {}
 
1482
        source_results = []
 
1483
        for source in self._immediate_fallback_vfs:
 
1484
            if not missing:
 
1485
                break
 
1486
            source_parents = source.get_parent_map(missing)
 
1487
            parent_map.update(source_parents)
 
1488
            source_parents = list(source_parents)
 
1489
            source_results.append((source, source_parents))
 
1490
            key_to_source_map.update((key, source) for key in source_parents)
 
1491
            missing.difference_update(source_parents)
 
1492
        return parent_map, key_to_source_map, source_results
 
1493
 
 
1494
    def _get_ordered_source_keys(self, ordering, parent_map, key_to_source_map):
 
1495
        """Get the (source, [keys]) list.
 
1496
 
 
1497
        The returned objects should be in the order defined by 'ordering',
 
1498
        which can weave between different sources.
 
1499
 
 
1500
        :param ordering: Must be one of 'topological' or 'groupcompress'
 
1501
        :return: List of [(source, [keys])] tuples, such that all keys are in
 
1502
            the defined order, regardless of source.
 
1503
        """
 
1504
        if ordering == 'topological':
 
1505
            present_keys = tsort.topo_sort(parent_map)
 
1506
        else:
 
1507
            # ordering == 'groupcompress'
 
1508
            # XXX: This only optimizes for the target ordering. We may need
 
1509
            #      to balance that with the time it takes to extract
 
1510
            #      ordering, by somehow grouping based on
 
1511
            #      locations[key][0:3]
 
1512
            present_keys = sort_gc_optimal(parent_map)
 
1513
        # Now group by source:
 
1514
        source_keys = []
 
1515
        current_source = None
 
1516
        for key in present_keys:
 
1517
            source = key_to_source_map.get(key, self)
 
1518
            if source is not current_source:
 
1519
                source_keys.append((source, []))
 
1520
                current_source = source
 
1521
            source_keys[-1][1].append(key)
 
1522
        return source_keys
 
1523
 
 
1524
    def _get_as_requested_source_keys(self, orig_keys, locations, unadded_keys,
 
1525
                                      key_to_source_map):
 
1526
        source_keys = []
 
1527
        current_source = None
 
1528
        for key in orig_keys:
 
1529
            if key in locations or key in unadded_keys:
 
1530
                source = self
 
1531
            elif key in key_to_source_map:
 
1532
                source = key_to_source_map[key]
 
1533
            else:  # absent
 
1534
                continue
 
1535
            if source is not current_source:
 
1536
                source_keys.append((source, []))
 
1537
                current_source = source
 
1538
            source_keys[-1][1].append(key)
 
1539
        return source_keys
 
1540
 
 
1541
    def _get_io_ordered_source_keys(self, locations, unadded_keys,
 
1542
                                    source_result):
 
1543
        def get_group(key):
 
1544
            # This is the group the bytes are stored in, followed by the
 
1545
            # location in the group
 
1546
            return locations[key][0]
 
1547
        # We don't have an ordering for keys in the in-memory object, but
 
1548
        # lets process the in-memory ones first.
 
1549
        present_keys = list(unadded_keys)
 
1550
        present_keys.extend(sorted(locations, key=get_group))
 
1551
        # Now grab all of the ones from other sources
 
1552
        source_keys = [(self, present_keys)]
 
1553
        source_keys.extend(source_result)
 
1554
        return source_keys
 
1555
 
 
1556
    def _get_remaining_record_stream(self, keys, orig_keys, ordering,
 
1557
                                     include_delta_closure):
 
1558
        """Get a stream of records for keys.
 
1559
 
 
1560
        :param keys: The keys to include.
 
1561
        :param ordering: one of 'unordered', 'topological', 'groupcompress' or
 
1562
            'as-requested'
 
1563
        :param include_delta_closure: If True then the closure across any
 
1564
            compression parents will be included (in the opaque data).
 
1565
        :return: An iterator of ContentFactory objects, each of which is only
 
1566
            valid until the iterator is advanced.
 
1567
        """
 
1568
        # Cheap: iterate
 
1569
        locations = self._index.get_build_details(keys)
 
1570
        unadded_keys = set(self._unadded_refs).intersection(keys)
 
1571
        missing = keys.difference(locations)
 
1572
        missing.difference_update(unadded_keys)
 
1573
        (fallback_parent_map, key_to_source_map,
 
1574
         source_result) = self._find_from_fallback(missing)
 
1575
        if ordering in ('topological', 'groupcompress'):
 
1576
            # would be better to not globally sort initially but instead
 
1577
            # start with one key, recurse to its oldest parent, then grab
 
1578
            # everything in the same group, etc.
 
1579
            parent_map = dict((key, details[2]) for key, details in
 
1580
                              viewitems(locations))
 
1581
            for key in unadded_keys:
 
1582
                parent_map[key] = self._unadded_refs[key]
 
1583
            parent_map.update(fallback_parent_map)
 
1584
            source_keys = self._get_ordered_source_keys(ordering, parent_map,
 
1585
                                                        key_to_source_map)
 
1586
        elif ordering == 'as-requested':
 
1587
            source_keys = self._get_as_requested_source_keys(orig_keys,
 
1588
                                                             locations, unadded_keys, key_to_source_map)
 
1589
        else:
 
1590
            # We want to yield the keys in a semi-optimal (read-wise) ordering.
 
1591
            # Otherwise we thrash the _group_cache and destroy performance
 
1592
            source_keys = self._get_io_ordered_source_keys(locations,
 
1593
                                                           unadded_keys, source_result)
 
1594
        for key in missing:
 
1595
            yield AbsentContentFactory(key)
 
1596
        # Batch up as many keys as we can until either:
 
1597
        #  - we encounter an unadded ref, or
 
1598
        #  - we run out of keys, or
 
1599
        #  - the total bytes to retrieve for this batch > BATCH_SIZE
 
1600
        batcher = _BatchingBlockFetcher(self, locations,
 
1601
                                        get_compressor_settings=self._get_compressor_settings)
 
1602
        for source, keys in source_keys:
 
1603
            if source is self:
 
1604
                for key in keys:
 
1605
                    if key in self._unadded_refs:
 
1606
                        # Flush batch, then yield unadded ref from
 
1607
                        # self._compressor.
 
1608
                        for factory in batcher.yield_factories(full_flush=True):
 
1609
                            yield factory
 
1610
                        bytes, sha1 = self._compressor.extract(key)
 
1611
                        parents = self._unadded_refs[key]
 
1612
                        yield FulltextContentFactory(key, parents, sha1, bytes)
 
1613
                        continue
 
1614
                    if batcher.add_key(key) > BATCH_SIZE:
 
1615
                        # Ok, this batch is big enough.  Yield some results.
 
1616
                        for factory in batcher.yield_factories():
 
1617
                            yield factory
 
1618
            else:
 
1619
                for factory in batcher.yield_factories(full_flush=True):
 
1620
                    yield factory
 
1621
                for record in source.get_record_stream(keys, ordering,
 
1622
                                                       include_delta_closure):
 
1623
                    yield record
 
1624
        for factory in batcher.yield_factories(full_flush=True):
 
1625
            yield factory
 
1626
 
 
1627
    def get_sha1s(self, keys):
 
1628
        """See VersionedFiles.get_sha1s()."""
 
1629
        result = {}
 
1630
        for record in self.get_record_stream(keys, 'unordered', True):
 
1631
            if record.sha1 is not None:
 
1632
                result[record.key] = record.sha1
 
1633
            else:
 
1634
                if record.storage_kind != 'absent':
 
1635
                    result[record.key] = osutils.sha_string(
 
1636
                        record.get_bytes_as('fulltext'))
 
1637
        return result
 
1638
 
 
1639
    def insert_record_stream(self, stream):
 
1640
        """Insert a record stream into this container.
 
1641
 
 
1642
        :param stream: A stream of records to insert.
 
1643
        :return: None
 
1644
        :seealso VersionedFiles.get_record_stream:
 
1645
        """
 
1646
        # XXX: Setting random_id=True makes
 
1647
        # test_insert_record_stream_existing_keys fail for groupcompress and
 
1648
        # groupcompress-nograph, this needs to be revisited while addressing
 
1649
        # 'bzr branch' performance issues.
 
1650
        for _ in self._insert_record_stream(stream, random_id=False):
 
1651
            pass
 
1652
 
 
1653
    def _get_compressor_settings(self):
 
1654
        if self._max_bytes_to_index is None:
 
1655
            # TODO: VersionedFiles don't know about their containing
 
1656
            #       repository, so they don't have much of an idea about their
 
1657
            #       location. So for now, this is only a global option.
 
1658
            c = config.GlobalConfig()
 
1659
            val = c.get_user_option('bzr.groupcompress.max_bytes_to_index')
 
1660
            if val is not None:
 
1661
                try:
 
1662
                    val = int(val)
 
1663
                except ValueError as e:
 
1664
                    trace.warning('Value for '
 
1665
                                  '"bzr.groupcompress.max_bytes_to_index"'
 
1666
                                  ' %r is not an integer'
 
1667
                                  % (val,))
 
1668
                    val = None
 
1669
            if val is None:
 
1670
                val = self._DEFAULT_MAX_BYTES_TO_INDEX
 
1671
            self._max_bytes_to_index = val
 
1672
        return {'max_bytes_to_index': self._max_bytes_to_index}
 
1673
 
 
1674
    def _make_group_compressor(self):
 
1675
        return GroupCompressor(self._get_compressor_settings())
 
1676
 
 
1677
    def _insert_record_stream(self, stream, random_id=False, nostore_sha=None,
 
1678
                              reuse_blocks=True):
 
1679
        """Internal core to insert a record stream into this container.
 
1680
 
 
1681
        This helper function has a different interface than insert_record_stream
 
1682
        to allow add_lines to be minimal, but still return the needed data.
 
1683
 
 
1684
        :param stream: A stream of records to insert.
 
1685
        :param nostore_sha: If the sha1 of a given text matches nostore_sha,
 
1686
            raise ExistingContent, rather than committing the new text.
 
1687
        :param reuse_blocks: If the source is streaming from
 
1688
            groupcompress-blocks, just insert the blocks as-is, rather than
 
1689
            expanding the texts and inserting again.
 
1690
        :return: An iterator over the sha1 of the inserted records.
 
1691
        :seealso insert_record_stream:
 
1692
        :seealso add_lines:
 
1693
        """
 
1694
        adapters = {}
 
1695
 
 
1696
        def get_adapter(adapter_key):
 
1697
            try:
 
1698
                return adapters[adapter_key]
 
1699
            except KeyError:
 
1700
                adapter_factory = adapter_registry.get(adapter_key)
 
1701
                adapter = adapter_factory(self)
 
1702
                adapters[adapter_key] = adapter
 
1703
                return adapter
 
1704
        # This will go up to fulltexts for gc to gc fetching, which isn't
 
1705
        # ideal.
 
1706
        self._compressor = self._make_group_compressor()
 
1707
        self._unadded_refs = {}
 
1708
        keys_to_add = []
 
1709
 
 
1710
        def flush():
 
1711
            bytes_len, chunks = self._compressor.flush().to_chunks()
 
1712
            self._compressor = self._make_group_compressor()
 
1713
            # Note: At this point we still have 1 copy of the fulltext (in
 
1714
            #       record and the var 'bytes'), and this generates 2 copies of
 
1715
            #       the compressed text (one for bytes, one in chunks)
 
1716
            # TODO: Push 'chunks' down into the _access api, so that we don't
 
1717
            #       have to double compressed memory here
 
1718
            # TODO: Figure out how to indicate that we would be happy to free
 
1719
            #       the fulltext content at this point. Note that sometimes we
 
1720
            #       will want it later (streaming CHK pages), but most of the
 
1721
            #       time we won't (everything else)
 
1722
            data = b''.join(chunks)
 
1723
            del chunks
 
1724
            index, start, length = self._access.add_raw_records(
 
1725
                [(None, len(data))], data)[0]
 
1726
            nodes = []
 
1727
            for key, reads, refs in keys_to_add:
 
1728
                nodes.append((key, b"%d %d %s" % (start, length, reads), refs))
 
1729
            self._index.add_records(nodes, random_id=random_id)
 
1730
            self._unadded_refs = {}
 
1731
            del keys_to_add[:]
 
1732
 
 
1733
        last_prefix = None
 
1734
        max_fulltext_len = 0
 
1735
        max_fulltext_prefix = None
 
1736
        insert_manager = None
 
1737
        block_start = None
 
1738
        block_length = None
 
1739
        # XXX: TODO: remove this, it is just for safety checking for now
 
1740
        inserted_keys = set()
 
1741
        reuse_this_block = reuse_blocks
 
1742
        for record in stream:
 
1743
            # Raise an error when a record is missing.
 
1744
            if record.storage_kind == 'absent':
 
1745
                raise errors.RevisionNotPresent(record.key, self)
 
1746
            if random_id:
 
1747
                if record.key in inserted_keys:
 
1748
                    trace.note(gettext('Insert claimed random_id=True,'
 
1749
                                       ' but then inserted %r two times'), record.key)
 
1750
                    continue
 
1751
                inserted_keys.add(record.key)
 
1752
            if reuse_blocks:
 
1753
                # If the reuse_blocks flag is set, check to see if we can just
 
1754
                # copy a groupcompress block as-is.
 
1755
                # We only check on the first record (groupcompress-block) not
 
1756
                # on all of the (groupcompress-block-ref) entries.
 
1757
                # The reuse_this_block flag is then kept for as long as
 
1758
                if record.storage_kind == 'groupcompress-block':
 
1759
                    # Check to see if we really want to re-use this block
 
1760
                    insert_manager = record._manager
 
1761
                    reuse_this_block = insert_manager.check_is_well_utilized()
 
1762
            else:
 
1763
                reuse_this_block = False
 
1764
            if reuse_this_block:
 
1765
                # We still want to reuse this block
 
1766
                if record.storage_kind == 'groupcompress-block':
 
1767
                    # Insert the raw block into the target repo
 
1768
                    insert_manager = record._manager
 
1769
                    bytes = record._manager._block.to_bytes()
 
1770
                    _, start, length = self._access.add_raw_records(
 
1771
                        [(None, len(bytes))], bytes)[0]
 
1772
                    del bytes
 
1773
                    block_start = start
 
1774
                    block_length = length
 
1775
                if record.storage_kind in ('groupcompress-block',
 
1776
                                           'groupcompress-block-ref'):
 
1777
                    if insert_manager is None:
 
1778
                        raise AssertionError('No insert_manager set')
 
1779
                    if insert_manager is not record._manager:
 
1780
                        raise AssertionError('insert_manager does not match'
 
1781
                                             ' the current record, we cannot be positive'
 
1782
                                             ' that the appropriate content was inserted.'
 
1783
                                             )
 
1784
                    value = b"%d %d %d %d" % (block_start, block_length,
 
1785
                                              record._start, record._end)
 
1786
                    nodes = [(record.key, value, (record.parents,))]
 
1787
                    # TODO: Consider buffering up many nodes to be added, not
 
1788
                    #       sure how much overhead this has, but we're seeing
 
1789
                    #       ~23s / 120s in add_records calls
 
1790
                    self._index.add_records(nodes, random_id=random_id)
 
1791
                    continue
 
1792
            try:
 
1793
                bytes = record.get_bytes_as('fulltext')
 
1794
            except errors.UnavailableRepresentation:
 
1795
                adapter_key = record.storage_kind, 'fulltext'
 
1796
                adapter = get_adapter(adapter_key)
 
1797
                bytes = adapter.get_bytes(record)
 
1798
            if len(record.key) > 1:
 
1799
                prefix = record.key[0]
 
1800
                soft = (prefix == last_prefix)
 
1801
            else:
 
1802
                prefix = None
 
1803
                soft = False
 
1804
            if max_fulltext_len < len(bytes):
 
1805
                max_fulltext_len = len(bytes)
 
1806
                max_fulltext_prefix = prefix
 
1807
            (found_sha1, start_point, end_point,
 
1808
             type) = self._compressor.compress(record.key,
 
1809
                                               bytes, record.sha1, soft=soft,
 
1810
                                               nostore_sha=nostore_sha)
 
1811
            # delta_ratio = float(len(bytes)) / (end_point - start_point)
 
1812
            # Check if we want to continue to include that text
 
1813
            if (prefix == max_fulltext_prefix
 
1814
                    and end_point < 2 * max_fulltext_len):
 
1815
                # As long as we are on the same file_id, we will fill at least
 
1816
                # 2 * max_fulltext_len
 
1817
                start_new_block = False
 
1818
            elif end_point > 4 * 1024 * 1024:
 
1819
                start_new_block = True
 
1820
            elif (prefix is not None and prefix != last_prefix
 
1821
                  and end_point > 2 * 1024 * 1024):
 
1822
                start_new_block = True
 
1823
            else:
 
1824
                start_new_block = False
 
1825
            last_prefix = prefix
 
1826
            if start_new_block:
 
1827
                self._compressor.pop_last()
 
1828
                flush()
 
1829
                max_fulltext_len = len(bytes)
 
1830
                (found_sha1, start_point, end_point,
 
1831
                 type) = self._compressor.compress(record.key, bytes,
 
1832
                                                   record.sha1)
 
1833
            if record.key[-1] is None:
 
1834
                key = record.key[:-1] + (b'sha1:' + found_sha1,)
 
1835
            else:
 
1836
                key = record.key
 
1837
            self._unadded_refs[key] = record.parents
 
1838
            yield found_sha1
 
1839
            as_st = static_tuple.StaticTuple.from_sequence
 
1840
            if record.parents is not None:
 
1841
                parents = as_st([as_st(p) for p in record.parents])
 
1842
            else:
 
1843
                parents = None
 
1844
            refs = static_tuple.StaticTuple(parents)
 
1845
            keys_to_add.append(
 
1846
                (key, b'%d %d' % (start_point, end_point), refs))
 
1847
        if len(keys_to_add):
 
1848
            flush()
 
1849
        self._compressor = None
 
1850
 
 
1851
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
 
1852
        """Iterate over the lines in the versioned files from keys.
 
1853
 
 
1854
        This may return lines from other keys. Each item the returned
 
1855
        iterator yields is a tuple of a line and a text version that that line
 
1856
        is present in (not introduced in).
 
1857
 
 
1858
        Ordering of results is in whatever order is most suitable for the
 
1859
        underlying storage format.
 
1860
 
 
1861
        If a progress bar is supplied, it may be used to indicate progress.
 
1862
        The caller is responsible for cleaning up progress bars (because this
 
1863
        is an iterator).
 
1864
 
 
1865
        NOTES:
 
1866
         * Lines are normalised by the underlying store: they will all have \n
 
1867
           terminators.
 
1868
         * Lines are returned in arbitrary order.
 
1869
 
 
1870
        :return: An iterator over (line, key).
 
1871
        """
 
1872
        keys = set(keys)
 
1873
        total = len(keys)
 
1874
        # we don't care about inclusions, the caller cares.
 
1875
        # but we need to setup a list of records to visit.
 
1876
        # we need key, position, length
 
1877
        for key_idx, record in enumerate(self.get_record_stream(keys,
 
1878
                                                                'unordered', True)):
 
1879
            # XXX: todo - optimise to use less than full texts.
 
1880
            key = record.key
 
1881
            if pb is not None:
 
1882
                pb.update('Walking content', key_idx, total)
 
1883
            if record.storage_kind == 'absent':
 
1884
                raise errors.RevisionNotPresent(key, self)
 
1885
            lines = osutils.split_lines(record.get_bytes_as('fulltext'))
 
1886
            for line in lines:
 
1887
                yield line, key
 
1888
        if pb is not None:
 
1889
            pb.update('Walking content', total, total)
 
1890
 
 
1891
    def keys(self):
 
1892
        """See VersionedFiles.keys."""
 
1893
        if 'evil' in debug.debug_flags:
 
1894
            trace.mutter_callsite(2, "keys scales with size of history")
 
1895
        sources = [self._index] + self._immediate_fallback_vfs
 
1896
        result = set()
 
1897
        for source in sources:
 
1898
            result.update(source.keys())
 
1899
        return result
 
1900
 
 
1901
 
 
1902
class _GCBuildDetails(object):
 
1903
    """A blob of data about the build details.
 
1904
 
 
1905
    This stores the minimal data, which then allows compatibility with the old
 
1906
    api, without taking as much memory.
 
1907
    """
 
1908
 
 
1909
    __slots__ = ('_index', '_group_start', '_group_end', '_basis_end',
 
1910
                 '_delta_end', '_parents')
 
1911
 
 
1912
    method = 'group'
 
1913
    compression_parent = None
 
1914
 
 
1915
    def __init__(self, parents, position_info):
 
1916
        self._parents = parents
 
1917
        (self._index, self._group_start, self._group_end, self._basis_end,
 
1918
         self._delta_end) = position_info
 
1919
 
 
1920
    def __repr__(self):
 
1921
        return '%s(%s, %s)' % (self.__class__.__name__,
 
1922
                               self.index_memo, self._parents)
 
1923
 
 
1924
    @property
 
1925
    def index_memo(self):
 
1926
        return (self._index, self._group_start, self._group_end,
 
1927
                self._basis_end, self._delta_end)
 
1928
 
 
1929
    @property
 
1930
    def record_details(self):
 
1931
        return static_tuple.StaticTuple(self.method, None)
 
1932
 
 
1933
    def __getitem__(self, offset):
 
1934
        """Compatibility thunk to act like a tuple."""
 
1935
        if offset == 0:
 
1936
            return self.index_memo
 
1937
        elif offset == 1:
 
1938
            return self.compression_parent  # Always None
 
1939
        elif offset == 2:
 
1940
            return self._parents
 
1941
        elif offset == 3:
 
1942
            return self.record_details
 
1943
        else:
 
1944
            raise IndexError('offset out of range')
 
1945
 
 
1946
    def __len__(self):
 
1947
        return 4
 
1948
 
 
1949
 
 
1950
class _GCGraphIndex(object):
 
1951
    """Mapper from GroupCompressVersionedFiles needs into GraphIndex storage."""
 
1952
 
 
1953
    def __init__(self, graph_index, is_locked, parents=True,
 
1954
                 add_callback=None, track_external_parent_refs=False,
 
1955
                 inconsistency_fatal=True, track_new_keys=False):
 
1956
        """Construct a _GCGraphIndex on a graph_index.
 
1957
 
 
1958
        :param graph_index: An implementation of breezy.index.GraphIndex.
 
1959
        :param is_locked: A callback, returns True if the index is locked and
 
1960
            thus usable.
 
1961
        :param parents: If True, record knits parents, if not do not record
 
1962
            parents.
 
1963
        :param add_callback: If not None, allow additions to the index and call
 
1964
            this callback with a list of added GraphIndex nodes:
 
1965
            [(node, value, node_refs), ...]
 
1966
        :param track_external_parent_refs: As keys are added, keep track of the
 
1967
            keys they reference, so that we can query get_missing_parents(),
 
1968
            etc.
 
1969
        :param inconsistency_fatal: When asked to add records that are already
 
1970
            present, and the details are inconsistent with the existing
 
1971
            record, raise an exception instead of warning (and skipping the
 
1972
            record).
 
1973
        """
 
1974
        self._add_callback = add_callback
 
1975
        self._graph_index = graph_index
 
1976
        self._parents = parents
 
1977
        self.has_graph = parents
 
1978
        self._is_locked = is_locked
 
1979
        self._inconsistency_fatal = inconsistency_fatal
 
1980
        # GroupCompress records tend to have the same 'group' start + offset
 
1981
        # repeated over and over, this creates a surplus of ints
 
1982
        self._int_cache = {}
 
1983
        if track_external_parent_refs:
 
1984
            self._key_dependencies = _KeyRefs(
 
1985
                track_new_keys=track_new_keys)
 
1986
        else:
 
1987
            self._key_dependencies = None
 
1988
 
 
1989
    def add_records(self, records, random_id=False):
 
1990
        """Add multiple records to the index.
 
1991
 
 
1992
        This function does not insert data into the Immutable GraphIndex
 
1993
        backing the KnitGraphIndex, instead it prepares data for insertion by
 
1994
        the caller and checks that it is safe to insert then calls
 
1995
        self._add_callback with the prepared GraphIndex nodes.
 
1996
 
 
1997
        :param records: a list of tuples:
 
1998
                         (key, options, access_memo, parents).
 
1999
        :param random_id: If True the ids being added were randomly generated
 
2000
            and no check for existence will be performed.
 
2001
        """
 
2002
        if not self._add_callback:
 
2003
            raise errors.ReadOnlyError(self)
 
2004
        # we hope there are no repositories with inconsistent parentage
 
2005
        # anymore.
 
2006
 
 
2007
        changed = False
 
2008
        keys = {}
 
2009
        for (key, value, refs) in records:
 
2010
            if not self._parents:
 
2011
                if refs:
 
2012
                    for ref in refs:
 
2013
                        if ref:
 
2014
                            raise knit.KnitCorrupt(self,
 
2015
                                                   "attempt to add node with parents "
 
2016
                                                   "in parentless index.")
 
2017
                    refs = ()
 
2018
                    changed = True
 
2019
            keys[key] = (value, refs)
 
2020
        # check for dups
 
2021
        if not random_id:
 
2022
            present_nodes = self._get_entries(keys)
 
2023
            for (index, key, value, node_refs) in present_nodes:
 
2024
                # Sometimes these are passed as a list rather than a tuple
 
2025
                node_refs = static_tuple.as_tuples(node_refs)
 
2026
                passed = static_tuple.as_tuples(keys[key])
 
2027
                if node_refs != passed[1]:
 
2028
                    details = '%s %s %s' % (key, (value, node_refs), passed)
 
2029
                    if self._inconsistency_fatal:
 
2030
                        raise knit.KnitCorrupt(self, "inconsistent details"
 
2031
                                               " in add_records: %s" %
 
2032
                                               details)
 
2033
                    else:
 
2034
                        trace.warning("inconsistent details in skipped"
 
2035
                                      " record: %s", details)
 
2036
                del keys[key]
 
2037
                changed = True
 
2038
        if changed:
 
2039
            result = []
 
2040
            if self._parents:
 
2041
                for key, (value, node_refs) in viewitems(keys):
 
2042
                    result.append((key, value, node_refs))
 
2043
            else:
 
2044
                for key, (value, node_refs) in viewitems(keys):
 
2045
                    result.append((key, value))
 
2046
            records = result
 
2047
        key_dependencies = self._key_dependencies
 
2048
        if key_dependencies is not None:
 
2049
            if self._parents:
 
2050
                for key, value, refs in records:
 
2051
                    parents = refs[0]
 
2052
                    key_dependencies.add_references(key, parents)
 
2053
            else:
 
2054
                for key, value, refs in records:
 
2055
                    new_keys.add_key(key)
 
2056
        self._add_callback(records)
 
2057
 
 
2058
    def _check_read(self):
 
2059
        """Raise an exception if reads are not permitted."""
 
2060
        if not self._is_locked():
 
2061
            raise errors.ObjectNotLocked(self)
 
2062
 
 
2063
    def _check_write_ok(self):
 
2064
        """Raise an exception if writes are not permitted."""
 
2065
        if not self._is_locked():
 
2066
            raise errors.ObjectNotLocked(self)
 
2067
 
 
2068
    def _get_entries(self, keys, check_present=False):
 
2069
        """Get the entries for keys.
 
2070
 
 
2071
        Note: Callers are responsible for checking that the index is locked
 
2072
        before calling this method.
 
2073
 
 
2074
        :param keys: An iterable of index key tuples.
 
2075
        """
 
2076
        keys = set(keys)
 
2077
        found_keys = set()
 
2078
        if self._parents:
 
2079
            for node in self._graph_index.iter_entries(keys):
 
2080
                yield node
 
2081
                found_keys.add(node[1])
 
2082
        else:
 
2083
            # adapt parentless index to the rest of the code.
 
2084
            for node in self._graph_index.iter_entries(keys):
 
2085
                yield node[0], node[1], node[2], ()
 
2086
                found_keys.add(node[1])
 
2087
        if check_present:
 
2088
            missing_keys = keys.difference(found_keys)
 
2089
            if missing_keys:
 
2090
                raise errors.RevisionNotPresent(missing_keys.pop(), self)
 
2091
 
 
2092
    def find_ancestry(self, keys):
 
2093
        """See CombinedGraphIndex.find_ancestry"""
 
2094
        return self._graph_index.find_ancestry(keys, 0)
 
2095
 
 
2096
    def get_parent_map(self, keys):
 
2097
        """Get a map of the parents of keys.
 
2098
 
 
2099
        :param keys: The keys to look up parents for.
 
2100
        :return: A mapping from keys to parents. Absent keys are absent from
 
2101
            the mapping.
 
2102
        """
 
2103
        self._check_read()
 
2104
        nodes = self._get_entries(keys)
 
2105
        result = {}
 
2106
        if self._parents:
 
2107
            for node in nodes:
 
2108
                result[node[1]] = node[3][0]
 
2109
        else:
 
2110
            for node in nodes:
 
2111
                result[node[1]] = None
 
2112
        return result
 
2113
 
 
2114
    def get_missing_parents(self):
 
2115
        """Return the keys of missing parents."""
 
2116
        # Copied from _KnitGraphIndex.get_missing_parents
 
2117
        # We may have false positives, so filter those out.
 
2118
        self._key_dependencies.satisfy_refs_for_keys(
 
2119
            self.get_parent_map(self._key_dependencies.get_unsatisfied_refs()))
 
2120
        return frozenset(self._key_dependencies.get_unsatisfied_refs())
 
2121
 
 
2122
    def get_build_details(self, keys):
 
2123
        """Get the various build details for keys.
 
2124
 
 
2125
        Ghosts are omitted from the result.
 
2126
 
 
2127
        :param keys: An iterable of keys.
 
2128
        :return: A dict of key:
 
2129
            (index_memo, compression_parent, parents, record_details).
 
2130
 
 
2131
            * index_memo: opaque structure to pass to read_records to extract
 
2132
              the raw data
 
2133
            * compression_parent: Content that this record is built upon, may
 
2134
              be None
 
2135
            * parents: Logical parents of this node
 
2136
            * record_details: extra information about the content which needs
 
2137
              to be passed to Factory.parse_record
 
2138
        """
 
2139
        self._check_read()
 
2140
        result = {}
 
2141
        entries = self._get_entries(keys)
 
2142
        for entry in entries:
 
2143
            key = entry[1]
 
2144
            if not self._parents:
 
2145
                parents = None
 
2146
            else:
 
2147
                parents = entry[3][0]
 
2148
            details = _GCBuildDetails(parents, self._node_to_position(entry))
 
2149
            result[key] = details
 
2150
        return result
 
2151
 
 
2152
    def keys(self):
 
2153
        """Get all the keys in the collection.
 
2154
 
 
2155
        The keys are not ordered.
 
2156
        """
 
2157
        self._check_read()
 
2158
        return [node[1] for node in self._graph_index.iter_all_entries()]
 
2159
 
 
2160
    def _node_to_position(self, node):
 
2161
        """Convert an index value to position details."""
 
2162
        bits = node[2].split(b' ')
 
2163
        # It would be nice not to read the entire gzip.
 
2164
        # start and stop are put into _int_cache because they are very common.
 
2165
        # They define the 'group' that an entry is in, and many groups can have
 
2166
        # thousands of objects.
 
2167
        # Branching Launchpad, for example, saves ~600k integers, at 12 bytes
 
2168
        # each, or about 7MB. Note that it might be even more when you consider
 
2169
        # how PyInt is allocated in separate slabs. And you can't return a slab
 
2170
        # to the OS if even 1 int on it is in use. Note though that Python uses
 
2171
        # a LIFO when re-using PyInt slots, which might cause more
 
2172
        # fragmentation.
 
2173
        start = int(bits[0])
 
2174
        start = self._int_cache.setdefault(start, start)
 
2175
        stop = int(bits[1])
 
2176
        stop = self._int_cache.setdefault(stop, stop)
 
2177
        basis_end = int(bits[2])
 
2178
        delta_end = int(bits[3])
 
2179
        # We can't use StaticTuple here, because node[0] is a BTreeGraphIndex
 
2180
        # instance...
 
2181
        return (node[0], start, stop, basis_end, delta_end)
 
2182
 
 
2183
    def scan_unvalidated_index(self, graph_index):
 
2184
        """Inform this _GCGraphIndex that there is an unvalidated index.
 
2185
 
 
2186
        This allows this _GCGraphIndex to keep track of any missing
 
2187
        compression parents we may want to have filled in to make those
 
2188
        indices valid.  It also allows _GCGraphIndex to track any new keys.
 
2189
 
 
2190
        :param graph_index: A GraphIndex
 
2191
        """
 
2192
        key_dependencies = self._key_dependencies
 
2193
        if key_dependencies is None:
 
2194
            return
 
2195
        for node in graph_index.iter_all_entries():
 
2196
            # Add parent refs from graph_index (and discard parent refs
 
2197
            # that the graph_index has).
 
2198
            key_dependencies.add_references(node[1], node[3][0])
 
2199
 
 
2200
 
 
2201
from ._groupcompress_py import (
 
2202
    apply_delta,
 
2203
    apply_delta_to_source,
 
2204
    encode_base128_int,
 
2205
    decode_base128_int,
 
2206
    decode_copy_instruction,
 
2207
    LinesDeltaIndex,
 
2208
    )
 
2209
try:
 
2210
    from ._groupcompress_pyx import (
 
2211
        apply_delta,
 
2212
        apply_delta_to_source,
 
2213
        DeltaIndex,
 
2214
        encode_base128_int,
 
2215
        decode_base128_int,
 
2216
        )
 
2217
    GroupCompressor = PyrexGroupCompressor
 
2218
except ImportError as e:
 
2219
    osutils.failed_to_load_extension(e)
 
2220
    GroupCompressor = PythonGroupCompressor