120
119
:param num_bytes: Ensure that we have extracted at least num_bytes of
121
120
content. If None, consume everything
123
if self._content_length is None:
124
raise AssertionError('self._content_length should never be None')
122
# TODO: If we re-use the same content block at different times during
123
# get_record_stream(), it is possible that the first pass will
124
# get inserted, triggering an extract/_ensure_content() which
125
# will get rid of _z_content. And then the next use of the block
126
# will try to access _z_content (to send it over the wire), and
127
# fail because it is already extracted. Consider never releasing
128
# _z_content because of this.
125
129
if num_bytes is None:
126
130
num_bytes = self._content_length
127
elif (self._content_length is not None
128
and num_bytes > self._content_length):
129
raise AssertionError(
130
'requested num_bytes (%d) > content length (%d)'
131
% (num_bytes, self._content_length))
132
# Expand the content if required
133
if self._content is None:
134
if self._content_chunks is not None:
135
self._content = ''.join(self._content_chunks)
136
self._content_chunks = None
137
if self._content is None:
138
if self._z_content is None:
139
raise AssertionError('No content to decompress')
131
if self._content_length is not None:
132
assert num_bytes <= self._content_length
133
if self._content is None:
134
assert self._z_content is not None
140
135
if self._z_content == '':
141
136
self._content = ''
142
137
elif self._compressor_name == 'lzma':
143
138
# We don't do partial lzma decomp yet
144
139
self._content = pylzma.decompress(self._z_content)
145
elif self._compressor_name == 'zlib':
146
141
# Start a zlib decompressor
147
if num_bytes * 4 > self._content_length * 3:
148
# If we are requesting more that 3/4ths of the content,
149
# just extract the whole thing in a single pass
150
num_bytes = self._content_length
142
assert self._compressor_name == 'zlib'
143
if num_bytes is None:
151
144
self._content = zlib.decompress(self._z_content)
153
146
self._z_content_decompressor = zlib.decompressobj()
155
148
# that the rest of the code is simplified
156
149
self._content = self._z_content_decompressor.decompress(
157
150
self._z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
158
if not self._z_content_decompressor.unconsumed_tail:
159
self._z_content_decompressor = None
161
raise AssertionError('Unknown compressor: %r'
162
% self._compressor_name)
163
# Any bytes remaining to be decompressed will be in the decompressors
151
# Any bytes remaining to be decompressed will be in the
152
# decompressors 'unconsumed_tail'
166
153
# Do we have enough bytes already?
167
if len(self._content) >= num_bytes:
154
if num_bytes is not None and len(self._content) >= num_bytes:
156
if num_bytes is None and self._z_content_decompressor is None:
157
# We must have already decompressed everything
169
159
# If we got this far, and don't have a decompressor, something is wrong
170
if self._z_content_decompressor is None:
171
raise AssertionError(
172
'No decompressor to decompress %d bytes' % num_bytes)
160
assert self._z_content_decompressor is not None
173
161
remaining_decomp = self._z_content_decompressor.unconsumed_tail
174
if not remaining_decomp:
175
raise AssertionError('Nothing left to decompress')
176
needed_bytes = num_bytes - len(self._content)
177
# We always set max_size to 32kB over the minimum needed, so that
178
# zlib will give us as much as we really want.
179
# TODO: If this isn't good enough, we could make a loop here,
180
# that keeps expanding the request until we get enough
181
self._content += self._z_content_decompressor.decompress(
182
remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
183
if len(self._content) < num_bytes:
184
raise AssertionError('%d bytes wanted, only %d available'
185
% (num_bytes, len(self._content)))
186
if not self._z_content_decompressor.unconsumed_tail:
187
# The stream is finished
188
self._z_content_decompressor = None
162
if num_bytes is None:
164
# We don't know how much is left, but we'll decompress it all
165
self._content += self._z_content_decompressor.decompress(
167
# Note: There what I consider a bug in zlib.decompressobj
168
# If you pass back in the entire unconsumed_tail, only
169
# this time you don't pass a max-size, it doesn't
170
# change the unconsumed_tail back to None/''.
171
# However, we know we are done with the whole stream
172
self._z_content_decompressor = None
173
self._content_length = len(self._content)
175
# If we have nothing left to decomp, we ran out of decomp bytes
176
assert remaining_decomp
177
needed_bytes = num_bytes - len(self._content)
178
# We always set max_size to 32kB over the minimum needed, so that
179
# zlib will give us as much as we really want.
180
# TODO: If this isn't good enough, we could make a loop here,
181
# that keeps expanding the request until we get enough
182
self._content += self._z_content_decompressor.decompress(
183
remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
184
assert len(self._content) >= num_bytes
185
if not self._z_content_decompressor.unconsumed_tail:
186
# The stream is finished
187
self._z_content_decompressor = None
190
189
def _parse_bytes(self, bytes, pos):
191
190
"""Read the various lengths from the header.
203
202
pos2 = bytes.index('\n', pos, pos + 14)
204
203
self._content_length = int(bytes[pos:pos2])
206
if len(bytes) != (pos + self._z_content_length):
207
# XXX: Define some GCCorrupt error ?
208
raise AssertionError('Invalid bytes: (%d) != %d + %d' %
209
(len(bytes), pos, self._z_content_length))
205
assert len(bytes) == (pos + self._z_content_length)
210
206
self._z_content = bytes[pos:]
207
assert len(self._z_content) == self._z_content_length
213
210
def from_bytes(cls, bytes):
215
if bytes[:6] not in cls.GCB_KNOWN_HEADERS:
216
raise ValueError('bytes did not start with any of %r'
217
% (cls.GCB_KNOWN_HEADERS,))
218
# XXX: why not testing the whole header ?
212
if bytes[:6] not in (cls.GCB_HEADER, cls.GCB_LZ_HEADER):
213
raise ValueError('bytes did not start with %r' % (cls.GCB_HEADER,))
219
214
if bytes[4] == 'z':
220
215
out._compressor_name = 'zlib'
221
216
elif bytes[4] == 'l':
259
254
bytes = apply_delta_to_source(self._content, content_start, end)
262
def set_chunked_content(self, content_chunks, length):
263
"""Set the content of this block to the given chunks."""
264
# If we have lots of short lines, it is may be more efficient to join
265
# the content ahead of time. If the content is <10MiB, we don't really
266
# care about the extra memory consumption, so we can just pack it and
267
# be done. However, timing showed 18s => 17.9s for repacking 1k revs of
268
# mysql, which is below the noise margin
269
self._content_length = length
270
self._content_chunks = content_chunks
272
self._z_content = None
274
257
def set_content(self, content):
275
258
"""Set the content of this block."""
276
259
self._content_length = len(content)
277
260
self._content = content
278
261
self._z_content = None
280
def _create_z_content_using_lzma(self):
281
if self._content_chunks is not None:
282
self._content = ''.join(self._content_chunks)
283
self._content_chunks = None
284
if self._content is None:
285
raise AssertionError('Nothing to compress')
286
self._z_content = pylzma.compress(self._content)
287
self._z_content_length = len(self._z_content)
289
def _create_z_content_from_chunks(self):
290
compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION)
291
compressed_chunks = map(compressor.compress, self._content_chunks)
292
compressed_chunks.append(compressor.flush())
293
self._z_content = ''.join(compressed_chunks)
294
self._z_content_length = len(self._z_content)
296
def _create_z_content(self):
297
if self._z_content is not None:
300
self._create_z_content_using_lzma()
302
if self._content_chunks is not None:
303
self._create_z_content_from_chunks()
305
self._z_content = zlib.compress(self._content)
306
self._z_content_length = len(self._z_content)
308
263
def to_bytes(self):
309
264
"""Encode the information into a byte stream."""
310
self._create_z_content()
265
compress = zlib.compress
267
compress = pylzma.compress
268
if self._z_content is None:
269
assert self._content is not None
270
self._z_content = compress(self._content)
271
self._z_content_length = len(self._z_content)
312
273
header = self.GCB_LZ_HEADER
319
280
return ''.join(chunks)
321
def _dump(self, include_text=False):
322
"""Take this block, and spit out a human-readable structure.
324
:param include_text: Inserts also include text bits, chose whether you
325
want this displayed in the dump or not.
326
:return: A dump of the given block. The layout is something like:
327
[('f', length), ('d', delta_length, text_length, [delta_info])]
328
delta_info := [('i', num_bytes, text), ('c', offset, num_bytes),
331
self._ensure_content()
334
while pos < self._content_length:
335
kind = self._content[pos]
337
if kind not in ('f', 'd'):
338
raise ValueError('invalid kind character: %r' % (kind,))
339
content_len, len_len = decode_base128_int(
340
self._content[pos:pos + 5])
342
if content_len + pos > self._content_length:
343
raise ValueError('invalid content_len %d for record @ pos %d'
344
% (content_len, pos - len_len - 1))
345
if kind == 'f': # Fulltext
347
text = self._content[pos:pos+content_len]
348
result.append(('f', content_len, text))
350
result.append(('f', content_len))
351
elif kind == 'd': # Delta
352
delta_content = self._content[pos:pos+content_len]
354
# The first entry in a delta is the decompressed length
355
decomp_len, delta_pos = decode_base128_int(delta_content)
356
result.append(('d', content_len, decomp_len, delta_info))
358
while delta_pos < content_len:
359
c = ord(delta_content[delta_pos])
363
delta_pos) = decode_copy_instruction(delta_content, c,
366
text = self._content[offset:offset+length]
367
delta_info.append(('c', offset, length, text))
369
delta_info.append(('c', offset, length))
370
measured_len += length
373
txt = delta_content[delta_pos:delta_pos+c]
376
delta_info.append(('i', c, txt))
379
if delta_pos != content_len:
380
raise ValueError('Delta consumed a bad number of bytes:'
381
' %d != %d' % (delta_pos, content_len))
382
if measured_len != decomp_len:
383
raise ValueError('Delta claimed fulltext was %d bytes, but'
384
' extraction resulted in %d bytes'
385
% (decomp_len, measured_len))
390
283
class _LazyGroupCompressFactory(object):
391
284
"""Yield content from a GroupCompressBlock on demand."""
537
432
# time (self._block._content) is a little expensive.
538
433
self._block._ensure_content(self._last_byte)
540
def _check_rebuild_action(self):
435
def _check_rebuild_block(self):
541
436
"""Check to see if our block should be repacked."""
542
437
total_bytes_used = 0
543
438
last_byte_used = 0
544
439
for factory in self._factories:
545
440
total_bytes_used += factory._end - factory._start
546
if last_byte_used < factory._end:
547
last_byte_used = factory._end
548
# If we are using more than half of the bytes from the block, we have
549
# nothing else to check
441
last_byte_used = max(last_byte_used, factory._end)
442
# If we are using most of the bytes from the block, we have nothing
443
# else to check (currently more that 1/2)
550
444
if total_bytes_used * 2 >= self._block._content_length:
551
return None, last_byte_used, total_bytes_used
552
# We are using less than 50% of the content. Is the content we are
553
# using at the beginning of the block? If so, we can just trim the
554
# tail, rather than rebuilding from scratch.
446
# Can we just strip off the trailing bytes? If we are going to be
447
# transmitting more than 50% of the front of the content, go ahead
555
448
if total_bytes_used * 2 > last_byte_used:
556
return 'trim', last_byte_used, total_bytes_used
449
self._trim_block(last_byte_used)
558
452
# We are using a small amount of the data, and it isn't just packed
559
453
# nicely at the front, so rebuild the content.
566
460
# expanding many deltas into fulltexts, as well.
567
461
# If we build a cheap enough 'strip', then we could try a strip,
568
462
# if that expands the content, we then rebuild.
569
return 'rebuild', last_byte_used, total_bytes_used
571
def check_is_well_utilized(self):
572
"""Is the current block considered 'well utilized'?
574
This heuristic asks if the current block considers itself to be a fully
575
developed group, rather than just a loose collection of data.
577
if len(self._factories) == 1:
578
# A block of length 1 could be improved by combining with other
579
# groups - don't look deeper. Even larger than max size groups
580
# could compress well with adjacent versions of the same thing.
582
action, last_byte_used, total_bytes_used = self._check_rebuild_action()
583
block_size = self._block._content_length
584
if total_bytes_used < block_size * self._max_cut_fraction:
585
# This block wants to trim itself small enough that we want to
586
# consider it under-utilized.
588
# TODO: This code is meant to be the twin of _insert_record_stream's
589
# 'start_new_block' logic. It would probably be better to factor
590
# out that logic into a shared location, so that it stays
592
# We currently assume a block is properly utilized whenever it is >75%
593
# of the size of a 'full' block. In normal operation, a block is
594
# considered full when it hits 4MB of same-file content. So any block
595
# >3MB is 'full enough'.
596
# The only time this isn't true is when a given block has large-object
597
# content. (a single file >4MB, etc.)
598
# Under these circumstances, we allow a block to grow to
599
# 2 x largest_content. Which means that if a given block had a large
600
# object, it may actually be under-utilized. However, given that this
601
# is 'pack-on-the-fly' it is probably reasonable to not repack large
602
# content blobs on-the-fly. Note that because we return False for all
603
# 1-item blobs, we will repack them; we may wish to reevaluate our
604
# treatment of large object blobs in the future.
605
if block_size >= self._full_enough_block_size:
607
# If a block is <3MB, it still may be considered 'full' if it contains
608
# mixed content. The current rule is 2MB of mixed content is considered
609
# full. So check to see if this block contains mixed content, and
610
# set the threshold appropriately.
612
for factory in self._factories:
613
prefix = factory.key[:-1]
614
if common_prefix is None:
615
common_prefix = prefix
616
elif prefix != common_prefix:
617
# Mixed content, check the size appropriately
618
if block_size >= self._full_enough_mixed_block_size:
621
# The content failed both the mixed check and the single-content check
622
# so obviously it is not fully utilized
623
# TODO: there is one other constraint that isn't being checked
624
# namely, that the entries in the block are in the appropriate
625
# order. For example, you could insert the entries in exactly
626
# reverse groupcompress order, and we would think that is ok.
627
# (all the right objects are in one group, and it is fully
628
# utilized, etc.) For now, we assume that case is rare,
629
# especially since we should always fetch in 'groupcompress'
633
def _check_rebuild_block(self):
634
action, last_byte_used, total_bytes_used = self._check_rebuild_action()
638
self._trim_block(last_byte_used)
639
elif action == 'rebuild':
640
self._rebuild_block()
642
raise ValueError('unknown rebuild action: %r' % (action,))
463
self._rebuild_block()
644
465
def _wire_bytes(self):
645
466
"""Return a byte stream suitable for transmitting over the wire."""
774
593
:param soft: Do a 'soft' compression. This means that we require larger
775
594
ranges to match to be considered for a copy command.
777
:return: The sha1 of lines, the start and end offsets in the delta, and
778
the type ('fulltext' or 'delta').
596
:return: The sha1 of lines, the start and end offsets in the delta, the
597
type ('fulltext' or 'delta') and the number of bytes accumulated in
598
the group output so far.
780
600
:seealso VersionedFiles.add_lines:
782
602
if not bytes: # empty, like a dir entry, etc
783
603
if nostore_sha == _null_sha1:
784
604
raise errors.ExistingContent()
785
return _null_sha1, 0, 0, 'fulltext'
605
return _null_sha1, 0, 0, 'fulltext', 0
786
606
# we assume someone knew what they were doing when they passed it in
787
607
if expected_sha is not None:
788
608
sha1 = expected_sha
794
614
if key[-1] is None:
795
615
key = key[:-1] + ('sha1:' + sha1,)
797
start, end, type = self._compress(key, bytes, len(bytes) / 2, soft)
798
return sha1, start, end, type
617
return self._compress(key, bytes, sha1, len(bytes) / 2, soft)
800
def _compress(self, key, bytes, max_delta_size, soft=False):
619
def _compress(self, key, bytes, sha1, max_delta_size, soft=False):
801
620
"""Compress lines with label key.
803
622
:param key: A key tuple. It is stored in the output for identification
888
703
def __init__(self):
889
704
"""Create a GroupCompressor.
891
Used only if the pyrex version is not available.
706
:param delta: If False, do not compress records.
893
708
super(PythonGroupCompressor, self).__init__()
894
709
self._delta_index = LinesDeltaIndex([])
895
710
# The actual content is managed by LinesDeltaIndex
896
711
self.chunks = self._delta_index.lines
898
def _compress(self, key, bytes, max_delta_size, soft=False):
713
def _compress(self, key, bytes, sha1, max_delta_size, soft=False):
899
714
"""see _CommonGroupCompressor._compress"""
900
input_len = len(bytes)
715
bytes_length = len(bytes)
901
716
new_lines = osutils.split_lines(bytes)
902
out_lines, index_lines = self._delta_index.make_delta(
903
new_lines, bytes_length=input_len, soft=soft)
717
out_lines, index_lines = self._delta_index.make_delta(new_lines,
718
bytes_length=bytes_length, soft=soft)
904
719
delta_length = sum(map(len, out_lines))
905
720
if delta_length > max_delta_size:
906
721
# The delta is longer than the fulltext, insert a fulltext
907
722
type = 'fulltext'
908
out_lines = ['f', encode_base128_int(input_len)]
723
out_lines = ['f', encode_base128_int(bytes_length)]
909
724
out_lines.extend(new_lines)
910
725
index_lines = [False, False]
911
726
index_lines.extend([True] * len(new_lines))
727
out_length = len(out_lines[1]) + bytes_length + 1
913
729
# this is a worthy delta, output it
915
731
out_lines[0] = 'd'
916
732
# Update the delta_length to include those two encoded integers
917
733
out_lines[1] = encode_base128_int(delta_length)
919
start = self.endpoint
920
chunk_start = len(self.chunks)
921
self._last = (chunk_start, self.endpoint)
734
out_length = len(out_lines[3]) + 1 + delta_length
735
start = self.endpoint # Before insertion
736
chunk_start = len(self._delta_index.lines)
922
737
self._delta_index.extend_lines(out_lines, index_lines)
923
738
self.endpoint = self._delta_index.endpoint
924
self.input_bytes += input_len
925
chunk_end = len(self.chunks)
739
self.input_bytes += bytes_length
740
chunk_end = len(self._delta_index.lines)
926
741
self.labels_deltas[key] = (start, chunk_start,
927
742
self.endpoint, chunk_end)
928
return start, self.endpoint, type
743
return sha1, start, self.endpoint, type, out_length
931
746
class PyrexGroupCompressor(_CommonGroupCompressor):
1041
857
versioned_files.stream.close()
1044
class _BatchingBlockFetcher(object):
1045
"""Fetch group compress blocks in batches.
1047
:ivar total_bytes: int of expected number of bytes needed to fetch the
1048
currently pending batch.
1051
def __init__(self, gcvf, locations):
1053
self.locations = locations
1055
self.batch_memos = {}
1056
self.memos_to_get = []
1057
self.total_bytes = 0
1058
self.last_read_memo = None
1061
def add_key(self, key):
1062
"""Add another to key to fetch.
1064
:return: The estimated number of bytes needed to fetch the batch so
1067
self.keys.append(key)
1068
index_memo, _, _, _ = self.locations[key]
1069
read_memo = index_memo[0:3]
1070
# Three possibilities for this read_memo:
1071
# - it's already part of this batch; or
1072
# - it's not yet part of this batch, but is already cached; or
1073
# - it's not yet part of this batch and will need to be fetched.
1074
if read_memo in self.batch_memos:
1075
# This read memo is already in this batch.
1076
return self.total_bytes
1078
cached_block = self.gcvf._group_cache[read_memo]
1080
# This read memo is new to this batch, and the data isn't cached
1082
self.batch_memos[read_memo] = None
1083
self.memos_to_get.append(read_memo)
1084
byte_length = read_memo[2]
1085
self.total_bytes += byte_length
1087
# This read memo is new to this batch, but cached.
1088
# Keep a reference to the cached block in batch_memos because it's
1089
# certain that we'll use it when this batch is processed, but
1090
# there's a risk that it would fall out of _group_cache between now
1092
self.batch_memos[read_memo] = cached_block
1093
return self.total_bytes
1095
def _flush_manager(self):
1096
if self.manager is not None:
1097
for factory in self.manager.get_record_stream():
1100
self.last_read_memo = None
1102
def yield_factories(self, full_flush=False):
1103
"""Yield factories for keys added since the last yield. They will be
1104
returned in the order they were added via add_key.
1106
:param full_flush: by default, some results may not be returned in case
1107
they can be part of the next batch. If full_flush is True, then
1108
all results are returned.
1110
if self.manager is None and not self.keys:
1112
# Fetch all memos in this batch.
1113
blocks = self.gcvf._get_blocks(self.memos_to_get)
1114
# Turn blocks into factories and yield them.
1115
memos_to_get_stack = list(self.memos_to_get)
1116
memos_to_get_stack.reverse()
1117
for key in self.keys:
1118
index_memo, _, parents, _ = self.locations[key]
1119
read_memo = index_memo[:3]
1120
if self.last_read_memo != read_memo:
1121
# We are starting a new block. If we have a
1122
# manager, we have found everything that fits for
1123
# now, so yield records
1124
for factory in self._flush_manager():
1126
# Now start a new manager.
1127
if memos_to_get_stack and memos_to_get_stack[-1] == read_memo:
1128
# The next block from _get_blocks will be the block we
1130
block_read_memo, block = blocks.next()
1131
if block_read_memo != read_memo:
1132
raise AssertionError(
1133
"block_read_memo out of sync with read_memo"
1134
"(%r != %r)" % (block_read_memo, read_memo))
1135
self.batch_memos[read_memo] = block
1136
memos_to_get_stack.pop()
1138
block = self.batch_memos[read_memo]
1139
self.manager = _LazyGroupContentManager(block)
1140
self.last_read_memo = read_memo
1141
start, end = index_memo[3:5]
1142
self.manager.add_factory(key, parents, start, end)
1144
for factory in self._flush_manager():
1147
self.batch_memos.clear()
1148
del self.memos_to_get[:]
1149
self.total_bytes = 0
1152
860
class GroupCompressVersionedFiles(VersionedFiles):
1153
861
"""A group-compress based VersionedFiles implementation."""
1155
def __init__(self, index, access, delta=True, _unadded_refs=None):
863
def __init__(self, index, access, delta=True):
1156
864
"""Create a GroupCompressVersionedFiles object.
1158
866
:param index: The index object storing access and graph data.
1159
867
:param access: The access object storing raw data.
1160
868
:param delta: Whether to delta compress or just entropy compress.
1161
:param _unadded_refs: private parameter, don't use.
1163
870
self._index = index
1164
871
self._access = access
1165
872
self._delta = delta
1166
if _unadded_refs is None:
1168
self._unadded_refs = _unadded_refs
873
self._unadded_refs = {}
1169
874
self._group_cache = LRUSizeCache(max_size=50*1024*1024)
1170
875
self._fallback_vfs = []
1172
def without_fallbacks(self):
1173
"""Return a clone of this object without any fallbacks configured."""
1174
return GroupCompressVersionedFiles(self._index, self._access,
1175
self._delta, _unadded_refs=dict(self._unadded_refs))
1177
877
def add_lines(self, key, parents, lines, parent_texts=None,
1178
878
left_matching_blocks=None, nostore_sha=None, random_id=False,
1179
879
check_content=True):
1224
924
nostore_sha=nostore_sha))[0]
1225
925
return sha1, length, None
1227
def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
1228
"""See VersionedFiles._add_text()."""
1229
self._index._check_write_ok()
1230
self._check_add(key, None, random_id, check_content=False)
1231
if text.__class__ is not str:
1232
raise errors.BzrBadParameterUnicode("text")
1234
# The caller might pass None if there is no graph data, but kndx
1235
# indexes can't directly store that, so we give them
1236
# an empty tuple instead.
1238
# double handling for now. Make it work until then.
1240
record = FulltextContentFactory(key, parents, None, text)
1241
sha1 = list(self._insert_record_stream([record], random_id=random_id,
1242
nostore_sha=nostore_sha))[0]
1243
return sha1, length, None
1245
927
def add_fallback_versioned_files(self, a_versioned_files):
1246
928
"""Add a source of texts for texts not present in this knit.
1252
934
def annotate(self, key):
1253
935
"""See VersionedFiles.annotate."""
1254
ann = annotate.Annotator(self)
1255
return ann.annotate_flat(key)
1257
def get_annotator(self):
1258
return annotate.Annotator(self)
1260
def check(self, progress_bar=None, keys=None):
937
parent_map = self.get_parent_map([key])
939
raise errors.RevisionNotPresent(key, self)
940
if parent_map[key] is not None:
941
search = graph._make_breadth_first_searcher([key])
945
present, ghosts = search.next_with_ghosts()
946
except StopIteration:
949
parent_map = self.get_parent_map(keys)
952
parent_map = {key:()}
953
head_cache = _mod_graph.FrozenHeadsCache(graph)
955
reannotate = annotate.reannotate
956
for record in self.get_record_stream(keys, 'topological', True):
958
chunks = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
959
parent_lines = [parent_cache[parent] for parent in parent_map[key]]
960
parent_cache[key] = list(
961
reannotate(parent_lines, chunks, key, None, head_cache))
962
return parent_cache[key]
964
def check(self, progress_bar=None):
1261
965
"""See VersionedFiles.check()."""
1264
for record in self.get_record_stream(keys, 'unordered', True):
1265
record.get_bytes_as('fulltext')
1267
return self.get_record_stream(keys, 'unordered', True)
1269
def clear_cache(self):
1270
"""See VersionedFiles.clear_cache()"""
1271
self._group_cache.clear()
1272
self._index._graph_index.clear_cache()
1273
self._index._int_cache.clear()
967
for record in self.get_record_stream(keys, 'unordered', True):
968
record.get_bytes_as('fulltext')
1275
970
def _check_add(self, key, lines, random_id, check_content):
1276
971
"""check that version_id and lines are safe to add."""
1335
1014
missing.difference_update(set(new_result))
1336
1015
return result, source_results
1338
def _get_blocks(self, read_memos):
1339
"""Get GroupCompressBlocks for the given read_memos.
1341
:returns: a series of (read_memo, block) pairs, in the order they were
1345
for read_memo in read_memos:
1347
block = self._group_cache[read_memo]
1351
cached[read_memo] = block
1353
not_cached_seen = set()
1354
for read_memo in read_memos:
1355
if read_memo in cached:
1356
# Don't fetch what we already have
1358
if read_memo in not_cached_seen:
1359
# Don't try to fetch the same data twice
1361
not_cached.append(read_memo)
1362
not_cached_seen.add(read_memo)
1363
raw_records = self._access.get_raw_records(not_cached)
1364
for read_memo in read_memos:
1366
yield read_memo, cached[read_memo]
1368
# Read the block, and cache it.
1369
zdata = raw_records.next()
1370
block = GroupCompressBlock.from_bytes(zdata)
1371
self._group_cache[read_memo] = block
1372
cached[read_memo] = block
1373
yield read_memo, block
1017
def _get_block(self, index_memo):
1018
read_memo = index_memo[0:3]
1021
block = self._group_cache[read_memo]
1024
zdata = self._access.get_raw_records([read_memo]).next()
1025
# decompress - whole thing - this is not a bug, as it
1026
# permits caching. We might want to store the partially
1027
# decompresed group and decompress object, so that recent
1028
# texts are not penalised by big groups.
1029
block = GroupCompressBlock.from_bytes(zdata)
1030
self._group_cache[read_memo] = block
1032
# print len(zdata), len(plain)
1033
# parse - requires split_lines, better to have byte offsets
1034
# here (but not by much - we only split the region for the
1035
# recipe, and we often want to end up with lines anyway.
1375
1038
def get_missing_compression_parent_keys(self):
1376
1039
"""Return the keys of missing compression parents.
1542
1205
unadded_keys, source_result)
1543
1206
for key in missing:
1544
1207
yield AbsentContentFactory(key)
1545
# Batch up as many keys as we can until either:
1546
# - we encounter an unadded ref, or
1547
# - we run out of keys, or
1548
# - the total bytes to retrieve for this batch > BATCH_SIZE
1549
batcher = _BatchingBlockFetcher(self, locations)
1209
last_read_memo = None
1210
# TODO: This works fairly well at batching up existing groups into a
1211
# streamable format, and possibly allowing for taking one big
1212
# group and splitting it when it isn't fully utilized.
1213
# However, it doesn't allow us to find under-utilized groups and
1214
# combine them into a bigger group on the fly.
1215
# (Consider the issue with how chk_map inserts texts
1216
# one-at-a-time.) This could be done at insert_record_stream()
1217
# time, but it probably would decrease the number of
1218
# bytes-on-the-wire for fetch.
1550
1219
for source, keys in source_keys:
1551
1220
if source is self:
1552
1221
for key in keys:
1553
1222
if key in self._unadded_refs:
1554
# Flush batch, then yield unadded ref from
1556
for factory in batcher.yield_factories(full_flush=True):
1223
if manager is not None:
1224
for factory in manager.get_record_stream():
1226
last_read_memo = manager = None
1558
1227
bytes, sha1 = self._compressor.extract(key)
1559
1228
parents = self._unadded_refs[key]
1560
1229
yield FulltextContentFactory(key, parents, sha1, bytes)
1562
if batcher.add_key(key) > BATCH_SIZE:
1563
# Ok, this batch is big enough. Yield some results.
1564
for factory in batcher.yield_factories():
1231
index_memo, _, parents, (method, _) = locations[key]
1232
read_memo = index_memo[0:3]
1233
if last_read_memo != read_memo:
1234
# We are starting a new block. If we have a
1235
# manager, we have found everything that fits for
1236
# now, so yield records
1237
if manager is not None:
1238
for factory in manager.get_record_stream():
1240
# Now start a new manager
1241
block = self._get_block(index_memo)
1242
manager = _LazyGroupContentManager(block)
1243
last_read_memo = read_memo
1244
start, end = index_memo[3:5]
1245
manager.add_factory(key, parents, start, end)
1567
for factory in batcher.yield_factories(full_flush=True):
1247
if manager is not None:
1248
for factory in manager.get_record_stream():
1250
last_read_memo = manager = None
1569
1251
for record in source.get_record_stream(keys, ordering,
1570
1252
include_delta_closure):
1572
for factory in batcher.yield_factories(full_flush=True):
1254
if manager is not None:
1255
for factory in manager.get_record_stream():
1575
1258
def get_sha1s(self, keys):
1576
1259
"""See VersionedFiles.get_sha1s()."""
1640
1318
self._index.add_records(nodes, random_id=random_id)
1641
1319
self._unadded_refs = {}
1642
1320
del keys_to_add[:]
1321
self._compressor = GroupCompressor()
1644
1323
last_prefix = None
1324
last_fulltext_len = None
1645
1325
max_fulltext_len = 0
1646
1326
max_fulltext_prefix = None
1647
1327
insert_manager = None
1648
1328
block_start = None
1649
1329
block_length = None
1650
# XXX: TODO: remove this, it is just for safety checking for now
1651
inserted_keys = set()
1652
reuse_this_block = reuse_blocks
1653
1330
for record in stream:
1654
1331
# Raise an error when a record is missing.
1655
1332
if record.storage_kind == 'absent':
1656
1333
raise errors.RevisionNotPresent(record.key, self)
1658
if record.key in inserted_keys:
1659
trace.note('Insert claimed random_id=True,'
1660
' but then inserted %r two times', record.key)
1662
inserted_keys.add(record.key)
1663
1334
if reuse_blocks:
1664
1335
# If the reuse_blocks flag is set, check to see if we can just
1665
1336
# copy a groupcompress block as-is.
1666
# We only check on the first record (groupcompress-block) not
1667
# on all of the (groupcompress-block-ref) entries.
1668
# The reuse_this_block flag is then kept for as long as
1669
if record.storage_kind == 'groupcompress-block':
1670
# Check to see if we really want to re-use this block
1671
insert_manager = record._manager
1672
reuse_this_block = insert_manager.check_is_well_utilized()
1674
reuse_this_block = False
1675
if reuse_this_block:
1676
# We still want to reuse this block
1677
1337
if record.storage_kind == 'groupcompress-block':
1678
1338
# Insert the raw block into the target repo
1679
1339
insert_manager = record._manager
1340
insert_manager._check_rebuild_block()
1680
1341
bytes = record._manager._block.to_bytes()
1681
1342
_, start, length = self._access.add_raw_records(
1682
1343
[(None, len(bytes))], bytes)[0]
1715
1371
if max_fulltext_len < len(bytes):
1716
1372
max_fulltext_len = len(bytes)
1717
1373
max_fulltext_prefix = prefix
1718
(found_sha1, start_point, end_point,
1719
type) = self._compressor.compress(record.key,
1720
bytes, record.sha1, soft=soft,
1721
nostore_sha=nostore_sha)
1722
# delta_ratio = float(len(bytes)) / (end_point - start_point)
1374
(found_sha1, start_point, end_point, type,
1375
length) = self._compressor.compress(record.key,
1376
bytes, record.sha1, soft=soft,
1377
nostore_sha=nostore_sha)
1378
# delta_ratio = float(len(bytes)) / length
1723
1379
# Check if we want to continue to include that text
1724
1380
if (prefix == max_fulltext_prefix
1725
1381
and end_point < 2 * max_fulltext_len):
1738
1394
self._compressor.pop_last()
1740
1396
max_fulltext_len = len(bytes)
1741
(found_sha1, start_point, end_point,
1742
type) = self._compressor.compress(record.key, bytes,
1397
(found_sha1, start_point, end_point, type,
1398
length) = self._compressor.compress(record.key,
1400
last_fulltext_len = length
1744
1401
if record.key[-1] is None:
1745
1402
key = record.key[:-1] + ('sha1:' + found_sha1,)
1747
1404
key = record.key
1748
1405
self._unadded_refs[key] = record.parents
1749
1406
yield found_sha1
1750
as_st = static_tuple.StaticTuple.from_sequence
1751
if record.parents is not None:
1752
parents = as_st([as_st(p) for p in record.parents])
1755
refs = static_tuple.StaticTuple(parents)
1756
keys_to_add.append((key, '%d %d' % (start_point, end_point), refs))
1407
keys_to_add.append((key, '%d %d' % (start_point, end_point),
1757
1409
if len(keys_to_add):
1759
1411
self._compressor = None
1825
1476
:param add_callback: If not None, allow additions to the index and call
1826
1477
this callback with a list of added GraphIndex nodes:
1827
1478
[(node, value, node_refs), ...]
1828
:param track_external_parent_refs: As keys are added, keep track of the
1829
keys they reference, so that we can query get_missing_parents(),
1831
:param inconsistency_fatal: When asked to add records that are already
1832
present, and the details are inconsistent with the existing
1833
record, raise an exception instead of warning (and skipping the
1836
1480
self._add_callback = add_callback
1837
1481
self._graph_index = graph_index
1838
1482
self._parents = parents
1839
1483
self.has_graph = parents
1840
1484
self._is_locked = is_locked
1841
self._inconsistency_fatal = inconsistency_fatal
1842
# GroupCompress records tend to have the same 'group' start + offset
1843
# repeated over and over, this creates a surplus of ints
1844
self._int_cache = {}
1845
if track_external_parent_refs:
1846
self._key_dependencies = knit._KeyRefs(
1847
track_new_keys=track_new_keys)
1849
self._key_dependencies = None
1851
1486
def add_records(self, records, random_id=False):
1852
1487
"""Add multiple records to the index.
1883
1518
if not random_id:
1884
1519
present_nodes = self._get_entries(keys)
1885
1520
for (index, key, value, node_refs) in present_nodes:
1886
# Sometimes these are passed as a list rather than a tuple
1887
node_refs = static_tuple.as_tuples(node_refs)
1888
passed = static_tuple.as_tuples(keys[key])
1889
if node_refs != passed[1]:
1890
details = '%s %s %s' % (key, (value, node_refs), passed)
1891
if self._inconsistency_fatal:
1892
raise errors.KnitCorrupt(self, "inconsistent details"
1893
" in add_records: %s" %
1896
trace.warning("inconsistent details in skipped"
1897
" record: %s", details)
1521
if node_refs != keys[key][1]:
1522
raise errors.KnitCorrupt(self, "inconsistent details in add_records"
1523
": %s %s" % ((value, node_refs), keys[key]))
2026
1631
"""Convert an index value to position details."""
2027
1632
bits = node[2].split(' ')
2028
1633
# It would be nice not to read the entire gzip.
2029
# start and stop are put into _int_cache because they are very common.
2030
# They define the 'group' that an entry is in, and many groups can have
2031
# thousands of objects.
2032
# Branching Launchpad, for example, saves ~600k integers, at 12 bytes
2033
# each, or about 7MB. Note that it might be even more when you consider
2034
# how PyInt is allocated in separate slabs. And you can't return a slab
2035
# to the OS if even 1 int on it is in use. Note though that Python uses
2036
# a LIFO when re-using PyInt slots, which probably causes more
2038
1634
start = int(bits[0])
2039
start = self._int_cache.setdefault(start, start)
2040
1635
stop = int(bits[1])
2041
stop = self._int_cache.setdefault(stop, stop)
2042
1636
basis_end = int(bits[2])
2043
1637
delta_end = int(bits[3])
2044
# We can't use StaticTuple here, because node[0] is a BTreeGraphIndex
2046
return (node[0], start, stop, basis_end, delta_end)
2048
def scan_unvalidated_index(self, graph_index):
2049
"""Inform this _GCGraphIndex that there is an unvalidated index.
2051
This allows this _GCGraphIndex to keep track of any missing
2052
compression parents we may want to have filled in to make those
2053
indices valid. It also allows _GCGraphIndex to track any new keys.
2055
:param graph_index: A GraphIndex
2057
key_dependencies = self._key_dependencies
2058
if key_dependencies is None:
2060
for node in graph_index.iter_all_entries():
2061
# Add parent refs from graph_index (and discard parent refs
2062
# that the graph_index has).
2063
key_dependencies.add_references(node[1], node[3][0])
1638
return node[0], start, stop, basis_end, delta_end
2066
1641
from bzrlib._groupcompress_py import (