Coverage Report

Created: 2025-04-19 16:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-store/src/compression_store.rs
Line
Count
Source
1
// Copyright 2024 The NativeLink Authors. All rights reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use std::cmp;
16
use std::pin::Pin;
17
use std::sync::Arc;
18
19
use async_trait::async_trait;
20
use bincode::config::{FixintEncoding, WithOtherIntEncoding};
21
use bincode::{DefaultOptions, Options};
22
use byteorder::{ByteOrder, LittleEndian};
23
use bytes::{Buf, BufMut, BytesMut};
24
use futures::future::FutureExt;
25
use lz4_flex::block::{compress_into, decompress_into, get_maximum_output_size};
26
use nativelink_config::stores::CompressionSpec;
27
use nativelink_error::{Code, Error, ResultExt, error_if, make_err};
28
use nativelink_metric::MetricsComponent;
29
use nativelink_util::buf_channel::{
30
    DropCloserReadHalf, DropCloserWriteHalf, make_buf_channel_pair,
31
};
32
use nativelink_util::health_utils::{HealthStatusIndicator, default_health_status_indicator};
33
use nativelink_util::spawn;
34
use nativelink_util::store_trait::{Store, StoreDriver, StoreKey, StoreLike, UploadSizeInfo};
35
use serde::{Deserialize, Serialize};
36
37
use crate::cas_utils::is_zero_digest;
38
39
// In the event the bytestream format changes this number should be incremented to prevent
40
// backwards compatibility issues.
41
pub const CURRENT_STREAM_FORMAT_VERSION: u8 = 1;
42
43
// Default block size that will be used to slice stream into.
44
pub const DEFAULT_BLOCK_SIZE: u32 = 64 * 1024;
45
46
const U32_SZ: u64 = size_of::<u8>() as u64;
47
48
type BincodeOptions = WithOtherIntEncoding<DefaultOptions, FixintEncoding>;
49
50
// We use a custom frame format here because I wanted the ability in the future to:
51
// * Read a random part of the data without needing to parse entire file.
52
// * Compress the data on the fly without needing to know the exact input size.
53
//
54
// The frame format that LZ4 uses does not contain an index of where the different
55
// blocks are located. This would mean in the event we only wanted the last byte of
56
// a file, we'd need to seek to the header of each block to find where the next block
57
// offset is until we got to the last block then decompress it.
58
//
59
// By using this custom frame format we keep the ability to have each block reference
60
// the next block (for efficiency), but also after all blocks we have a footer frame
61
// which contains an index of each block in the stream. This means that we can read a
62
// fixed number of bytes of the file, which always contain the size of the index, then
63
// with that size we know the exact size of the footer frame, which contains the entire
64
// index. Once this footer frame is loaded, we could then do some math to figure out
65
// which block each byte is in and the offset of each block within the compressed file.
66
//
67
// The frame format is as follows:
68
// |----------------------------------HEADER-----------------------------------------|
69
// |  version(u8) |  block_size (u32) |  upload_size_type (u32) |  upload_size (u32) |
70
// |----------------------------------BLOCK------------------------------------------|
71
// |  frame_type(u8) 0x00 |  compressed_data_size (u32) |        ...DATA...          |
72
// |                                ...DATA...                                       |
73
// | [Possibly repeat block]                                                         |
74
// |----------------------------------FOOTER-----------------------------------------|
75
// |  frame_type(u8) 0x01 |    footer_size (u32) |           index_count1 (u64)      |
76
// |      ...[pos_from_prev_index (u32) - repeat for count {index_count*}]...        |
77
// |  index_count2 (u32) |    uncompressed_data_sz (u64) |    block_size (u32)       |
78
// | version (u8) |------------------------------------------------------------------|
79
// |---------------------------------------------------------------------------------|
80
//
81
// version              - A constant number used to define what version of this format is being
82
//                        used. Version in header and footer must match.
83
// block_size           - Size of each block uncompressed except for last block. This means that
84
//                        every block uncompressed will be a constant size except last block may
85
//                        be variable size. Block size in header and footer must match.
86
// upload_size_type     - Value of 0 = UploadSizeInfo::ExactSize, 1 = UploadSizeInfo::MaxSize.
87
//                        This is for debug reasons only.
88
// upload_size          - The size of the data. WARNING: Do not rely on this being the uncompressed
89
//                        payload size. It is a debug field and a "best guess" on how large the data
90
//                        is. The header does not contain the upload data size. This value is the
91
//                        value counter part to what the `upload_size_type` field.
92
// frame_type           - Type of each frame. 0 = BLOCK frame, 1 = FOOTER frame. Header frame will
93
//                        always start with the first byte of the stream, so no magic number for it.
94
// compressed_data_size - The size of this block. The bytes after this field should be read
95
//                        in sequence to get all of the block's data in this block.
96
// footer_size          - Size of the footer for bytes after this field.
97
// index_count1         - Number of items in the index. ({index_count1} * 4) represents the number
98
//                        of bytes that should be read after this field in order to get all index
99
//                        data.
100
// pos_from_prev_index  - Index of an individual block in the stream relative to the previous
101
//                        block. This field may repeat {index_count} times.
102
// index_count2         - Same as {index_count1} and should always be equal. This field might be
103
//                        useful if you want to read a random byte from this stream, have random
104
//                        access to it and know the size of the stream during reading, because
105
//                        this field is always in the exact same place in the stream relative to
106
//                        the last byte.
107
// uncompressed_data_sz - Size of the original uncompressed data.
108
//
109
// Note: All fields fields little-endian.
110
111
/// Number representing a chunk.
112
pub const CHUNK_FRAME_TYPE: u8 = 0;
113
114
/// Number representing the footer.
115
pub const FOOTER_FRAME_TYPE: u8 = 1;
116
117
/// This is a partial mirror of `nativelink_config::stores::Lz4Config`.
118
/// We cannot use that natively here because it could cause our
119
/// serialized format to change if we added more configs.
120
#[derive(Serialize, Deserialize, PartialEq, Debug, Default, Copy, Clone)]
121
pub struct Lz4Config {
122
    pub block_size: u32,
123
}
124
125
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy)]
126
pub struct Header {
127
    pub version: u8,
128
    pub config: Lz4Config,
129
    pub upload_size: UploadSizeInfo,
130
}
131
132
#[derive(Serialize, Deserialize, PartialEq, Debug, Default, Clone, Copy)]
133
pub struct SliceIndex {
134
    pub position_from_prev_index: u32,
135
}
136
137
#[derive(Serialize, Deserialize, PartialEq, Debug, Default)]
138
pub struct Footer {
139
    pub indexes: Vec<SliceIndex>,
140
    pub index_count: u32,
141
    pub uncompressed_data_size: u64,
142
    pub config: Lz4Config,
143
    pub version: u8,
144
}
145
146
/// `lz4_flex::block::get_maximum_output_size()` way over estimates, so we use the
147
/// one provided here: <https://github.com/torvalds/linux/blob/master/include/linux/lz4.h#L61>
148
/// Local testing shows this gives quite accurate worst case given random input.
149
6
const fn lz4_compress_bound(input_size: u64) -> u64 {
150
6
    input_size + (input_size / 255) + 16
151
6
}
152
153
struct UploadState {
154
    header: Header,
155
    footer: Footer,
156
    max_output_size: u64,
157
    input_max_size: u64,
158
}
159
160
impl UploadState {
161
6
    pub(crate) fn new(
162
6
        store: &CompressionStore,
163
6
        upload_size: UploadSizeInfo,
164
6
    ) -> Result<Self, Error> {
165
6
        let input_max_size = match upload_size {
166
6
            UploadSizeInfo::MaxSize(
sz1
) | UploadSizeInfo::ExactSize(
sz5
) => sz,
167
6
        };
168
6
169
6
        let max_index_count = (input_max_size / u64::from(store.config.block_size)) + 1;
170
6
171
6
        let header = Header {
172
6
            version: CURRENT_STREAM_FORMAT_VERSION,
173
6
            config: Lz4Config {
174
6
                block_size: store.config.block_size,
175
6
            },
176
6
            upload_size,
177
6
        };
178
6
        let footer = Footer {
179
6
            indexes: vec![
180
6
                SliceIndex {
181
6
                    ..Default::default()
182
6
                };
183
6
                usize::try_from(max_index_count)
184
6
                    .err_tip(|| 
"Could not convert max_index_count to usize"0
)
?0
185
            ],
186
6
            index_count: max_index_count as u32,
187
6
            uncompressed_data_size: 0, // Updated later.
188
6
            config: header.config,
189
6
            version: CURRENT_STREAM_FORMAT_VERSION,
190
6
        };
191
6
192
6
        // This is more accurate of an estimate than what get_maximum_output_size calculates.
193
6
        let max_block_size = lz4_compress_bound(u64::from(store.config.block_size)) + U32_SZ + 1;
194
6
195
6
        let max_output_size = {
196
6
            let header_size = store.bincode_options.serialized_size(&header).unwrap();
197
6
            let max_content_size = max_block_size * max_index_count;
198
6
            let max_footer_size =
199
6
                U32_SZ + 1 + store.bincode_options.serialized_size(&footer).unwrap();
200
6
            header_size + max_content_size + max_footer_size
201
6
        };
202
6
203
6
        Ok(Self {
204
6
            header,
205
6
            footer,
206
6
            max_output_size,
207
6
            input_max_size,
208
6
        })
209
6
    }
210
}
211
212
/// This store will compress data before sending it on to the inner store.
213
/// Note: Currently using `get_part()` and trying to read part of the data will
214
/// result in the entire contents being read from the inner store but will
215
/// only send the contents requested.
216
#[derive(MetricsComponent)]
217
pub struct CompressionStore {
218
    #[metric(group = "inner_store")]
219
    inner_store: Store,
220
    config: nativelink_config::stores::Lz4Config,
221
    bincode_options: BincodeOptions,
222
}
223
224
impl std::fmt::Debug for CompressionStore {
225
0
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226
0
        f.debug_struct("CompressionStore")
227
0
            .field("inner_store", &self.inner_store)
228
0
            .field("config", &self.config)
229
0
            .finish_non_exhaustive()
230
0
    }
231
}
232
233
impl CompressionStore {
234
7
    pub fn new(spec: &CompressionSpec, inner_store: Store) -> Result<Arc<Self>, Error> {
235
7
        let lz4_config = match spec.compression_algorithm {
236
7
            nativelink_config::stores::CompressionAlgorithm::Lz4(mut lz4_config) => {
237
7
                if lz4_config.block_size == 0 {
  Branch (237:20): [True: 3, False: 4]
  Branch (237:20): [Folded - Ignored]
238
3
                    lz4_config.block_size = DEFAULT_BLOCK_SIZE;
239
4
                }
240
7
                if lz4_config.max_decode_block_size == 0 {
  Branch (240:20): [True: 7, False: 0]
  Branch (240:20): [Folded - Ignored]
241
7
                    lz4_config.max_decode_block_size = lz4_config.block_size;
242
7
                
}0
243
7
                lz4_config
244
7
            }
245
7
        };
246
7
        Ok(Arc::new(CompressionStore {
247
7
            inner_store,
248
7
            config: lz4_config,
249
7
            bincode_options: DefaultOptions::new().with_fixint_encoding(),
250
7
        }))
251
7
    }
252
}
253
254
#[async_trait]
255
impl StoreDriver for CompressionStore {
256
    async fn has_with_results(
257
        self: Pin<&Self>,
258
        digests: &[StoreKey<'_>],
259
        results: &mut [Option<u64>],
260
0
    ) -> Result<(), Error> {
261
0
        self.inner_store.has_with_results(digests, results).await
262
0
    }
263
264
    async fn update(
265
        self: Pin<&Self>,
266
        key: StoreKey<'_>,
267
        mut reader: DropCloserReadHalf,
268
        upload_size: UploadSizeInfo,
269
12
    ) -> Result<(), Error> {
270
6
        let mut output_state = UploadState::new(&self, upload_size)
?0
;
271
272
6
        let (mut tx, rx) = make_buf_channel_pair();
273
6
274
6
        let inner_store = self.inner_store.clone();
275
6
        let key = key.into_owned();
276
6
        let update_fut = spawn!("compression_store_update_spawn", async move {
277
6
            inner_store
278
6
                .update(
279
6
                    key,
280
6
                    rx,
281
6
                    UploadSizeInfo::MaxSize(output_state.max_output_size),
282
6
                )
283
6
                .await
284
6
                .err_tip(|| 
"Inner store update in compression store failed"0
)
285
6
        })
286
6
        .map(
287
6
            |result| match result.err_tip(|| 
"Failed to run compression update spawn"0
) {
288
6
                Ok(inner_result) => {
289
6
                    inner_result.err_tip(|| 
"Compression underlying store update failed"0
)
290
                }
291
0
                Err(e) => Err(e),
292
6
            },
293
        );
294
295
6
        let write_fut = async move {
296
            {
297
                // Write Header.
298
6
                let serialized_header = self
299
6
                    .bincode_options
300
6
                    .serialize(&output_state.header)
301
6
                    .map_err(|e| {
302
0
                        make_err!(Code::Internal, "Failed to serialize header : {:?}", e)
303
0
                    })?;
304
6
                tx.send(serialized_header.into())
305
6
                    .await
306
6
                    .err_tip(|| 
"Failed to write compression header on upload"0
)
?0
;
307
            }
308
309
6
            let mut received_amt = 0;
310
6
            let mut index_count: u32 = 0;
311
99
            for 
index98
in &mut output_state.footer.indexes {
312
98
                let chunk = reader
313
98
                    .consume(Some(self.config.block_size as usize))
314
98
                    .await
315
98
                    .err_tip(|| 
"Failed to read take in update in compression store"0
)
?0
;
316
98
                if chunk.is_empty() {
  Branch (316:20): [True: 5, False: 93]
  Branch (316:20): [Folded - Ignored]
317
5
                    break; // EOF.
318
93
                }
319
93
320
93
                received_amt += u64::try_from(chunk.len())
321
93
                    .err_tip(|| 
"Could not convert chunk.len() to u64"0
)
?0
;
322
0
                error_if!(
323
93
                    received_amt > output_state.input_max_size,
  Branch (323:21): [True: 0, False: 93]
  Branch (323:21): [Folded - Ignored]
324
                    "Got more data than stated in compression store upload request"
325
                );
326
327
93
                let max_output_size = get_maximum_output_size(self.config.block_size as usize);
328
93
                let mut compressed_data_buf = BytesMut::with_capacity(max_output_size);
329
93
                compressed_data_buf.put_u8(CHUNK_FRAME_TYPE);
330
93
                compressed_data_buf.put_u32_le(0); // Filled later.
331
93
332
93
                // For efficiency reasons we do some raw slice manipulation so we can write directly
333
93
                // into our buffer instead of having to do another allocation.
334
93
                let raw_compressed_data = unsafe {
335
93
                    std::slice::from_raw_parts_mut(
336
93
                        compressed_data_buf.chunk_mut().as_mut_ptr(),
337
93
                        max_output_size,
338
93
                    )
339
                };
340
341
93
                let compressed_data_sz = compress_into(&chunk, raw_compressed_data)
342
93
                    .map_err(|e| 
make_err!(Code::Internal, "Compression error {:?}", e)0
)
?0
;
343
93
                unsafe {
344
93
                    compressed_data_buf.advance_mut(compressed_data_sz);
345
93
                }
346
93
347
93
                // Now fill the size in our slice.
348
93
                LittleEndian::write_u32(&mut compressed_data_buf[1..5], compressed_data_sz as u32);
349
93
350
93
                // Now send our chunk.
351
93
                tx.send(compressed_data_buf.freeze())
352
93
                    .await
353
93
                    .err_tip(|| 
"Failed to write chunk to inner store in compression store"0
)
?0
;
354
355
93
                index.position_from_prev_index = compressed_data_sz as u32;
356
93
357
93
                index_count += 1;
358
            }
359
            // Index 0 is actually a pointer to the second chunk. This is because we don't need
360
            // an index for the first item, since it starts at position `{header_len}`.
361
            // The code above causes us to create 1 more index than we actually need, so we
362
            // remove the last index from our vector here, because at this point we are always
363
            // one index too many.
364
            // Note: We need to be careful that if we don't have any data (zero bytes) it
365
            // doesn't go to -1.
366
6
            index_count = index_count.saturating_sub(1);
367
6
            output_state.footer.indexes.resize(
368
6
                index_count as usize,
369
6
                SliceIndex {
370
6
                    ..Default::default()
371
6
                },
372
6
            );
373
6
            output_state.footer.index_count = output_state.footer.indexes.len() as u32;
374
6
            output_state.footer.uncompressed_data_size = received_amt;
375
            {
376
                // Write Footer.
377
6
                let serialized_footer = self
378
6
                    .bincode_options
379
6
                    .serialize(&output_state.footer)
380
6
                    .map_err(|e| {
381
0
                        make_err!(Code::Internal, "Failed to serialize header : {:?}", e)
382
0
                    })?;
383
384
6
                let mut footer = BytesMut::with_capacity(1 + 4 + serialized_footer.len());
385
6
                footer.put_u8(FOOTER_FRAME_TYPE);
386
6
                footer.put_u32_le(serialized_footer.len() as u32);
387
6
                footer.extend_from_slice(&serialized_footer);
388
6
389
6
                tx.send(footer.freeze())
390
6
                    .await
391
6
                    .err_tip(|| 
"Failed to write footer to inner store in compression store"0
)
?0
;
392
6
                tx.send_eof()
393
6
                    .err_tip(|| 
"Failed writing EOF in compression store update"0
)
?0
;
394
            }
395
396
6
            Result::<(), Error>::Ok(())
397
6
        };
398
6
        let (write_result, update_result) = tokio::join!(write_fut, update_fut);
399
6
        write_result.merge(update_result)
400
12
    }
401
402
    async fn get_part(
403
        self: Pin<&Self>,
404
        key: StoreKey<'_>,
405
        writer: &mut DropCloserWriteHalf,
406
        offset: u64,
407
        length: Option<u64>,
408
2.45k
    ) -> Result<(), Error> {
409
1.22k
        if is_zero_digest(key.borrow()) {
  Branch (409:12): [True: 1, False: 1.22k]
  Branch (409:12): [Folded - Ignored]
410
1
            writer
411
1
                .send_eof()
412
1
                .err_tip(|| 
"Failed to send zero EOF in filesystem store get_part"0
)
?0
;
413
1
            return Ok(());
414
1.22k
        }
415
1.22k
416
1.22k
        let (tx, mut rx) = make_buf_channel_pair();
417
1.22k
418
1.22k
        let inner_store = self.inner_store.clone();
419
1.22k
        let key = key.into_owned();
420
1.22k
        let get_part_fut = spawn!("compression_store_get_part_spawn", async move {
421
1.22k
            inner_store
422
1.22k
                .get_part(key, tx, 0, None)
423
1.22k
                .await
424
1.22k
                .err_tip(|| 
"Inner store get in compression store failed"0
)
425
1.22k
        })
426
1.22k
        .map(
427
1.22k
            |result| match result.err_tip(|| 
"Failed to run compression get spawn"0
) {
428
1.22k
                Ok(inner_result) => {
429
1.22k
                    inner_result.err_tip(|| 
"Compression underlying store get failed"0
)
430
                }
431
0
                Err(e) => Err(e),
432
1.22k
            },
433
        );
434
1.22k
        let read_fut = async move {
435
1.22k
            let header = {
436
                // Read header.
437
                const EMPTY_HEADER: Header = Header {
438
                    version: CURRENT_STREAM_FORMAT_VERSION,
439
                    config: Lz4Config { block_size: 0 },
440
                    upload_size: UploadSizeInfo::ExactSize(0),
441
                };
442
1.22k
                let header_size = self.bincode_options.serialized_size(&EMPTY_HEADER).unwrap();
443
1.22k
                let chunk = rx
444
1.22k
                    .consume(Some(header_size as usize))
445
1.22k
                    .await
446
1.22k
                    .err_tip(|| 
"Failed to read header in get_part compression store"0
)
?0
;
447
0
                error_if!(
448
1.22k
                    chunk.len() as u64 != header_size,
  Branch (448:21): [True: 0, False: 1.22k]
  Branch (448:21): [Folded - Ignored]
449
                    "Expected inner store to return the proper amount of data in compression store {} != {}",
450
0
                    chunk.len(),
451
                    header_size,
452
                );
453
454
1.22k
                self.bincode_options
455
1.22k
                    .deserialize::<Header>(&chunk)
456
1.22k
                    .map_err(|e| {
457
0
                        make_err!(Code::Internal, "Failed to deserialize header : {:?}", e)
458
0
                    })?
459
            };
460
461
0
            error_if!(
462
1.22k
                header.version != CURRENT_STREAM_FORMAT_VERSION,
  Branch (462:17): [True: 0, False: 1.22k]
  Branch (462:17): [Folded - Ignored]
463
                "Expected header version to match in get compression, got {}, want {}",
464
                header.version,
465
                CURRENT_STREAM_FORMAT_VERSION
466
            );
467
0
            error_if!(
468
1.22k
                header.config.block_size > self.config.max_decode_block_size,
  Branch (468:17): [True: 0, False: 1.22k]
  Branch (468:17): [Folded - Ignored]
469
                "Block size is too large in compression, got {} > {}",
470
                header.config.block_size,
471
0
                self.config.max_decode_block_size
472
            );
473
474
1.22k
            let mut chunk = rx
475
1.22k
                .consume(Some(1 + 4))
476
1.22k
                .await
477
1.22k
                .err_tip(|| 
"Failed to read init frame info in compression store"0
)
?0
;
478
0
            error_if!(
479
1.22k
                chunk.len() < 1 + 4,
  Branch (479:17): [True: 0, False: 1.22k]
  Branch (479:17): [Folded - Ignored]
480
                "Received EOF too early while reading init frame info in compression store"
481
            );
482
483
1.22k
            let mut frame_type = chunk.get_u8();
484
1.22k
            let mut frame_sz = chunk.get_u32_le();
485
1.22k
486
1.22k
            let mut uncompressed_data_sz: u64 = 0;
487
1.22k
            let mut remaining_bytes_to_send: u64 = length.unwrap_or(u64::MAX);
488
1.22k
            let mut chunks_count: u32 = 0;
489
4.98k
            while frame_type != FOOTER_FRAME_TYPE {
  Branch (489:19): [True: 3.75k, False: 1.22k]
  Branch (489:19): [Folded - Ignored]
490
0
                error_if!(
491
3.75k
                    frame_type != CHUNK_FRAME_TYPE,
  Branch (491:21): [True: 0, False: 3.75k]
  Branch (491:21): [Folded - Ignored]
492
                    "Expected frame to be BODY in compression store, got {} at {}",
493
                    frame_type,
494
                    chunks_count
495
                );
496
497
3.75k
                let chunk = rx
498
3.75k
                    .consume(Some(frame_sz as usize))
499
3.75k
                    .await
500
3.75k
                    .err_tip(|| 
"Failed to read chunk in get_part compression store"0
)
?0
;
501
3.75k
                if chunk.len() < frame_sz as usize {
  Branch (501:20): [True: 0, False: 3.75k]
  Branch (501:20): [Folded - Ignored]
502
0
                    return Err(make_err!(
503
0
                        Code::Internal,
504
0
                        "Got EOF earlier than expected. Maybe the data is not compressed or different format?"
505
0
                    ));
506
3.75k
                }
507
3.75k
                {
508
3.75k
                    let max_output_size =
509
3.75k
                        get_maximum_output_size(header.config.block_size as usize);
510
3.75k
                    let mut uncompressed_data = BytesMut::with_capacity(max_output_size);
511
3.75k
512
3.75k
                    // For efficiency reasons we do some raw slice manipulation so we can write directly
513
3.75k
                    // into our buffer instead of having to do another allocation.
514
3.75k
                    let raw_decompressed_data = unsafe {
515
3.75k
                        std::slice::from_raw_parts_mut(
516
3.75k
                            uncompressed_data.chunk_mut().as_mut_ptr(),
517
3.75k
                            max_output_size,
518
3.75k
                        )
519
                    };
520
521
3.75k
                    let uncompressed_chunk_sz = decompress_into(&chunk, raw_decompressed_data)
522
3.75k
                        .map_err(|e| 
make_err!(Code::Internal, "Decompression error {:?}", e)0
)
?0
;
523
3.75k
                    unsafe { uncompressed_data.advance_mut(uncompressed_chunk_sz) };
524
3.75k
                    let new_uncompressed_data_sz =
525
3.75k
                        uncompressed_data_sz + uncompressed_chunk_sz as u64;
526
3.75k
                    if new_uncompressed_data_sz >= offset && 
remaining_bytes_to_send > 02.28k
{
  Branch (526:24): [True: 2.28k, False: 1.47k]
  Branch (526:62): [True: 1.95k, False: 328]
  Branch (526:24): [Folded - Ignored]
  Branch (526:62): [Folded - Ignored]
527
1.95k
                        let start_pos = offset.saturating_sub(uncompressed_data_sz) as usize;
528
1.95k
                        let end_pos = cmp::min(
529
1.95k
                            start_pos + remaining_bytes_to_send as usize,
530
1.95k
                            uncompressed_chunk_sz,
531
1.95k
                        );
532
1.95k
                        if end_pos != start_pos {
  Branch (532:28): [True: 1.85k, False: 102]
  Branch (532:28): [Folded - Ignored]
533
                            // Make sure we don't send an EOF by accident.
534
1.85k
                            writer
535
1.85k
                                .send(uncompressed_data.freeze().slice(start_pos..end_pos))
536
1.85k
                                .await
537
1.85k
                                .err_tip(|| 
"Failed sending chunk in compression store"0
)
?0
;
538
102
                        }
539
1.95k
                        remaining_bytes_to_send -= (end_pos - start_pos) as u64;
540
1.79k
                    }
541
3.75k
                    uncompressed_data_sz = new_uncompressed_data_sz;
542
3.75k
                }
543
3.75k
                chunks_count += 1;
544
545
3.75k
                let mut chunk = rx
546
3.75k
                    .consume(Some(1 + 4))
547
3.75k
                    .await
548
3.75k
                    .err_tip(|| 
"Failed to read frame info in compression store"0
)
?0
;
549
0
                error_if!(
550
3.75k
                    chunk.len() < 1 + 4,
  Branch (550:21): [True: 0, False: 3.75k]
  Branch (550:21): [Folded - Ignored]
551
                    "Received EOF too early while reading frame info in compression store"
552
                );
553
554
3.75k
                frame_type = chunk.get_u8();
555
3.75k
                frame_sz = chunk.get_u32_le();
556
            }
557
            // Index count will always be +1 (unless it is zero bytes long).
558
1.22k
            chunks_count = chunks_count.saturating_sub(1);
559
            {
560
                // Read and validate footer.
561
1.22k
                let chunk = rx
562
1.22k
                    .consume(Some(frame_sz as usize))
563
1.22k
                    .await
564
1.22k
                    .err_tip(|| 
"Failed to read chunk in get_part compression store"0
)
?0
;
565
0
                error_if!(
566
1.22k
                    chunk.len() < frame_sz as usize,
  Branch (566:21): [True: 0, False: 1.22k]
  Branch (566:21): [Folded - Ignored]
567
                    "Unexpected EOF when reading footer in compression store get_part"
568
                );
569
570
1.22k
                let footer = self
571
1.22k
                    .bincode_options
572
1.22k
                    .deserialize::<Footer>(&chunk)
573
1.22k
                    .map_err(|e| {
574
0
                        make_err!(Code::Internal, "Failed to deserialize footer : {:?}", e)
575
0
                    })?;
576
577
0
                error_if!(
578
1.22k
                    header.version != footer.version,
  Branch (578:21): [True: 0, False: 1.22k]
  Branch (578:21): [Folded - Ignored]
579
                    "Expected header and footer versions to match compression store get_part, {} != {}",
580
                    header.version,
581
                    footer.version
582
                );
583
0
                error_if!(
584
1.22k
                    footer.indexes.len() != footer.index_count as usize,
  Branch (584:21): [True: 0, False: 1.22k]
  Branch (584:21): [Folded - Ignored]
585
                    "Expected index counts to match in compression store footer in get_part, {} != {}",
586
0
                    footer.indexes.len(),
587
                    footer.index_count
588
                );
589
0
                error_if!(
590
1.22k
                    footer.index_count != chunks_count,
  Branch (590:21): [True: 0, False: 1.22k]
  Branch (590:21): [Folded - Ignored]
591
                    concat!(
592
                        "Expected index counts to match received chunks count ",
593
                        "in compression store footer in get_part, {} != {}"
594
                    ),
595
                    footer.index_count,
596
                    chunks_count
597
                );
598
0
                error_if!(
599
1.22k
                    footer.uncompressed_data_size != uncompressed_data_sz,
  Branch (599:21): [True: 0, False: 1.22k]
  Branch (599:21): [Folded - Ignored]
600
                    "Expected uncompressed data sizes to match in compression store footer in get_part, {} != {}",
601
                    footer.uncompressed_data_size,
602
                    uncompressed_data_sz
603
                );
604
            }
605
606
1.22k
            writer
607
1.22k
                .send_eof()
608
1.22k
                .err_tip(|| 
"Failed to send eof in compression store write"0
)
?0
;
609
1.22k
            Ok(())
610
1.22k
        };
611
612
1.22k
        let (read_result, get_part_fut_result) = tokio::join!(read_fut, get_part_fut);
613
1.22k
        if let Err(
mut e0
) = read_result {
  Branch (613:16): [True: 0, False: 1.22k]
  Branch (613:16): [Folded - Ignored]
614
            // We may need to propagate the error from reading the data through first.
615
0
            if let Err(err) = get_part_fut_result {
  Branch (615:20): [True: 0, False: 0]
  Branch (615:20): [Folded - Ignored]
616
0
                e = err.merge(e);
617
0
            }
618
0
            return Err(e);
619
1.22k
        }
620
1.22k
        Ok(())
621
2.45k
    }
622
623
0
    fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver {
624
0
        self
625
0
    }
626
627
0
    fn as_any(&self) -> &(dyn std::any::Any + Sync + Send + 'static) {
628
0
        self
629
0
    }
630
631
0
    fn as_any_arc(self: Arc<Self>) -> Arc<dyn std::any::Any + Sync + Send + 'static> {
632
0
        self
633
0
    }
634
}
635
636
default_health_status_indicator!(CompressionStore);