Skip to main content

gen_models/assets/
compression.rs

1use std::{
2    fs,
3    io::{self, Chain, Cursor, Read, Write},
4};
5
6use gen_core::{Sha256Hash, Workspace};
7use noodles::bgzf;
8use tempfile::NamedTempFile;
9
10use super::{ChecksummedReader, ChecksummedWriter, FileTypes};
11use crate::errors::FileAdditionError;
12
13/// A compression encoding inferred from an asset path or detected from its bytes.
14#[derive(Clone, Copy, Debug, Eq, PartialEq)]
15pub enum CompressionType {
16    /// The bytes are uncompressed or their path does not identify a compressed format.
17    Plain,
18    /// The bytes use ordinary gzip compression.
19    Gzip,
20    /// The bytes use BGZF compression, including BAM files.
21    Bgzf,
22}
23
24type ReplayedReader<R> = Chain<Cursor<Vec<u8>>, R>;
25
26impl CompressionType {
27    /// Classifies input compression from header bytes and returns a reader that replays inspected bytes.
28    ///
29    /// Replaying lets callers hash or decode the complete stream without losing bytes read during
30    /// classification. [`super::AssetUri::compression_type`] infers from the URI suffix only.
31    pub fn sniff<R: Read>(reader: R) -> io::Result<(Self, impl Read)> {
32        classify_input(reader)
33    }
34}
35
36// Read enough header bytes to distinguish BGZF from ordinary gzip, then replay them into storage.
37fn classify_input<R: Read>(mut reader: R) -> io::Result<(CompressionType, ReplayedReader<R>)> {
38    let mut prefix = Vec::with_capacity(12);
39    let encoding = if !fill_prefix(&mut reader, &mut prefix, 2)? || prefix[..2] != [0x1f, 0x8b] {
40        CompressionType::Plain
41    } else if !fill_prefix(&mut reader, &mut prefix, 10)?
42        || prefix[2] != 8
43        || prefix[3] & 0x04 == 0
44        || !fill_prefix(&mut reader, &mut prefix, 12)?
45    {
46        CompressionType::Gzip
47    } else {
48        let extra_length = usize::from(u16::from_le_bytes([prefix[10], prefix[11]]));
49        if !fill_prefix(&mut reader, &mut prefix, 12 + extra_length)? {
50            CompressionType::Gzip
51        } else if has_bgzf_subfield(&prefix[12..]) {
52            CompressionType::Bgzf
53        } else {
54            CompressionType::Gzip
55        }
56    };
57
58    Ok((encoding, Cursor::new(prefix).chain(reader)))
59}
60
61// This creates a temporary bgzipped file that is then copied into the asset directory.
62//
63// It creates a checksum as the file is read and compressed. If the incoming file is already
64// compressed with bgz, it copied through. If a file is compressed already with an algorithm
65// such as gzip, it is decompressed and then recompressed as bgz. This is because many places will
66// ship a fasta or other assets as a .gz which does not allow random access.
67pub(crate) fn stage_bgzf_asset_copy(
68    workspace: &Workspace,
69    file_type: FileTypes,
70    reader: impl Read + 'static,
71    compression_type: CompressionType,
72    source_checksum_override: Option<Sha256Hash>,
73) -> Result<(Sha256Hash, Sha256Hash), FileAdditionError> {
74    let asset_dir = workspace.asset_dir()?;
75    fs::create_dir_all(&asset_dir).map_err(FileAdditionError::FileReadError)?;
76
77    let source_reader = ChecksummedReader::new(reader);
78    let source_checksum_handle = source_reader.checksum_handle();
79    let mut staged_file =
80        NamedTempFile::new_in(&asset_dir).map_err(FileAdditionError::FileReadError)?;
81    let archive_checksum = {
82        let checksummed_writer = ChecksummedWriter::new(staged_file.as_file_mut());
83        match compression_type {
84            CompressionType::Gzip => {
85                let mut bgzf_writer = bgzf::io::Writer::new(checksummed_writer);
86                io::copy(
87                    &mut flate2::read::MultiGzDecoder::new(source_reader),
88                    &mut bgzf_writer,
89                )
90                .map_err(FileAdditionError::FileReadError)?;
91                let mut checksummed_writer = bgzf_writer
92                    .finish()
93                    .map_err(FileAdditionError::FileReadError)?;
94                checksummed_writer
95                    .flush()
96                    .map_err(FileAdditionError::FileReadError)?;
97                checksummed_writer.checksum()
98            }
99            CompressionType::Bgzf => {
100                let mut checksummed_writer = checksummed_writer;
101                let mut source_reader = source_reader;
102                io::copy(&mut source_reader, &mut checksummed_writer)
103                    .map_err(FileAdditionError::FileReadError)?;
104                checksummed_writer
105                    .flush()
106                    .map_err(FileAdditionError::FileReadError)?;
107                checksummed_writer.checksum()
108            }
109            CompressionType::Plain => {
110                let mut bgzf_writer = bgzf::io::Writer::new(checksummed_writer);
111                let mut source_reader = source_reader;
112                io::copy(&mut source_reader, &mut bgzf_writer)
113                    .map_err(FileAdditionError::FileReadError)?;
114                let mut checksummed_writer = bgzf_writer
115                    .finish()
116                    .map_err(FileAdditionError::FileReadError)?;
117                checksummed_writer
118                    .flush()
119                    .map_err(FileAdditionError::FileReadError)?;
120                checksummed_writer.checksum()
121            }
122        }
123    };
124    staged_file
125        .flush()
126        .map_err(FileAdditionError::FileReadError)?;
127    let source_checksum = source_checksum_handle.checksum().ok_or_else(|| {
128        FileAdditionError::ChecksumError("local asset stream did not reach EOF".to_string())
129    })?;
130    if let Some(expected_checksum) = source_checksum_override
131        && source_checksum != expected_checksum
132    {
133        return Err(FileAdditionError::ChecksumError(
134            "local source checksum does not match the provided checksum".to_string(),
135        ));
136    }
137
138    let archive_filename = format!("{archive_checksum}.{}.bgz", FileTypes::suffix(file_type));
139    let archived_path = asset_dir.join(archive_filename);
140    match staged_file.persist_noclobber(&archived_path) {
141        Ok(_) => {}
142        Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {}
143        Err(error) => return Err(FileAdditionError::FileReadError(error.error)),
144    }
145    Ok((archive_checksum, source_checksum))
146}
147
148fn fill_prefix<R: Read>(reader: &mut R, prefix: &mut Vec<u8>, target: usize) -> io::Result<bool> {
149    let mut buffer = [0; 8192];
150    while prefix.len() < target {
151        let remaining = target - prefix.len();
152        let read_length = remaining.min(buffer.len());
153        let read = match reader.read(&mut buffer[..read_length]) {
154            Ok(read) => read,
155            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
156            Err(error) => return Err(error),
157        };
158        if read == 0 {
159            return Ok(false);
160        }
161        prefix.extend_from_slice(&buffer[..read]);
162    }
163    Ok(true)
164}
165
166fn has_bgzf_subfield(extra: &[u8]) -> bool {
167    let mut offset = 0;
168    while offset + 4 <= extra.len() {
169        let subfield_length =
170            usize::from(u16::from_le_bytes([extra[offset + 2], extra[offset + 3]]));
171        let end = offset + 4 + subfield_length;
172        if end > extra.len() {
173            return false;
174        }
175        if extra[offset] == b'B' && extra[offset + 1] == b'C' && subfield_length == 2 {
176            return true;
177        }
178        offset = end;
179    }
180    false
181}
182
183#[cfg(test)]
184mod tests {
185    use std::io::{self, Cursor, Read, Write as _};
186
187    use noodles::bgzf;
188
189    use super::CompressionType;
190
191    struct ShortReadReader<R> {
192        reader: R,
193        maximum_read: usize,
194    }
195
196    impl<R: Read> Read for ShortReadReader<R> {
197        fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
198            let maximum_read = buffer.len().min(self.maximum_read);
199            self.reader.read(&mut buffer[..maximum_read])
200        }
201    }
202
203    #[test]
204    fn test_classify_replays_short_read_plain_gzip_and_bgzf_inputs() {
205        let mut gzip_writer =
206            flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
207        gzip_writer
208            .write_all(b"plain bytes")
209            .expect("should write gzip bytes");
210        let gzip_contents = gzip_writer.finish().expect("should finish gzip bytes");
211        let mut bgzf_writer = bgzf::io::Writer::new(Vec::new());
212        bgzf_writer
213            .write_all(b"bgzf bytes")
214            .expect("should write BGZF bytes");
215        let bgzf_contents = bgzf_writer.finish().expect("should finish BGZF bytes");
216        let cases = [
217            (b"plain bytes".to_vec(), CompressionType::Plain),
218            (gzip_contents, CompressionType::Gzip),
219            (bgzf_contents, CompressionType::Bgzf),
220        ];
221
222        for (contents, expected_encoding) in cases {
223            let reader = ShortReadReader {
224                reader: Cursor::new(contents.clone()),
225                maximum_read: 1,
226            };
227            let (encoding, mut replayed_reader) =
228                CompressionType::sniff(reader).expect("should classify source bytes");
229            let mut replayed_contents = Vec::new();
230            replayed_reader
231                .read_to_end(&mut replayed_contents)
232                .expect("should replay the complete source");
233
234            assert_eq!(encoding, expected_encoding);
235            assert_eq!(replayed_contents, contents);
236        }
237    }
238
239    #[test]
240    fn test_classify_finds_bgzf_after_a_full_gzip_extra_field() {
241        let mut contents = vec![0x1f, 0x8b, 8, 0x04, 0, 0, 0, 0, 0, 255];
242        contents.extend_from_slice(&u16::MAX.to_le_bytes());
243        let unknown_subfield_length = usize::from(u16::MAX) - 6;
244        let unknown_payload_length = unknown_subfield_length - 4;
245        contents.extend_from_slice(&[
246            b'X',
247            b'Y',
248            unknown_payload_length as u8,
249            (unknown_payload_length >> 8) as u8,
250        ]);
251        contents.resize(12 + unknown_subfield_length, 0);
252        contents.extend_from_slice(&[b'B', b'C', 2, 0, 0, 0]);
253        contents.extend_from_slice(b"compressed payload");
254
255        let reader = ShortReadReader {
256            reader: Cursor::new(contents.clone()),
257            maximum_read: 7,
258        };
259        let (encoding, mut replayed_reader) =
260            CompressionType::sniff(reader).expect("should parse the complete gzip extra field");
261        let mut replayed_contents = Vec::new();
262        replayed_reader
263            .read_to_end(&mut replayed_contents)
264            .expect("should replay all source bytes");
265
266        assert_eq!(encoding, CompressionType::Bgzf);
267        assert_eq!(replayed_contents, contents);
268    }
269
270    mod stage_bgzf_asset_copy_tests {
271        use std::{
272            fs::{self, File, FileTimes},
273            io::{Cursor, Read, Write as _},
274            time::{Duration, SystemTime},
275        };
276
277        use gen_core::{Sha256Hash, Workspace};
278        use noodles::bgzf;
279        use sha2::{Digest, Sha256};
280        use tempfile::{TempDir, tempdir};
281
282        use super::super::{CompressionType, FileTypes, stage_bgzf_asset_copy};
283
284        fn setup_workspace(temp_dir: &TempDir) -> Workspace {
285            let workspace = Workspace::new(temp_dir.path());
286            workspace.ensure_gen_dir();
287            workspace
288        }
289
290        fn checksum(bytes: &[u8]) -> Sha256Hash {
291            Sha256Hash(Sha256::digest(bytes).into())
292        }
293
294        fn retained_archive_path(
295            workspace: &Workspace,
296            archive_checksum: Sha256Hash,
297        ) -> std::path::PathBuf {
298            workspace
299                .asset_dir()
300                .expect("should find asset directory")
301                .join(format!(
302                    "{archive_checksum}.{}.bgz",
303                    FileTypes::suffix(FileTypes::Fasta)
304                ))
305        }
306
307        fn assert_retained_bgzf_asset(
308            workspace: &Workspace,
309            archive_checksum: Sha256Hash,
310            expected_contents: &[u8],
311        ) -> Vec<u8> {
312            let archive_path = retained_archive_path(workspace, archive_checksum);
313            let archive_bytes = fs::read(archive_path).expect("should read retained BGZF asset");
314            assert_eq!(
315                checksum(&archive_bytes),
316                archive_checksum,
317                "archive checksum should match retained BGZF bytes"
318            );
319            let (compression_type, _) = CompressionType::sniff(Cursor::new(archive_bytes.clone()))
320                .expect("should classify retained BGZF asset");
321            assert_eq!(
322                compression_type,
323                CompressionType::Bgzf,
324                "retained archive should use BGZF compression"
325            );
326            let mut decoder = bgzf::io::Reader::new(Cursor::new(archive_bytes.clone()));
327            let mut decoded_contents = Vec::new();
328            decoder
329                .read_to_end(&mut decoded_contents)
330                .expect("should decode retained BGZF asset");
331            assert_eq!(
332                decoded_contents, expected_contents,
333                "retained BGZF asset should decode to source contents"
334            );
335            archive_bytes
336        }
337
338        #[test]
339        fn test_stage_bgzf_asset_copy_compresses_gzip_input() {
340            let temp_dir = tempdir().expect("should create temporary directory");
341            let workspace = setup_workspace(&temp_dir);
342            let expected_contents = b">sequence\nACGT\n";
343            let mut gzip_writer =
344                flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
345            gzip_writer
346                .write_all(expected_contents)
347                .expect("should write gzip source");
348            let source_bytes = gzip_writer.finish().expect("should finish gzip source");
349
350            let (archive_checksum, source_checksum) = stage_bgzf_asset_copy(
351                &workspace,
352                FileTypes::Fasta,
353                Cursor::new(source_bytes.clone()),
354                CompressionType::Gzip,
355                None,
356            )
357            .expect("should retain gzip input as BGZF");
358
359            assert_eq!(
360                source_checksum,
361                checksum(&source_bytes),
362                "source checksum should cover the exact gzip input bytes"
363            );
364            assert_retained_bgzf_asset(&workspace, archive_checksum, expected_contents);
365        }
366
367        #[test]
368        fn test_stage_bgzf_asset_copy_retains_bgzf_input() {
369            let temp_dir = tempdir().expect("should create temporary directory");
370            let workspace = setup_workspace(&temp_dir);
371            let expected_contents = b">sequence\nACGT\n";
372            let mut bgzf_writer = bgzf::io::writer::Builder::default()
373                .set_compression_level(bgzf::io::writer::CompressionLevel::NONE)
374                .build_from_writer(Vec::new());
375            bgzf_writer
376                .write_all(expected_contents)
377                .expect("should write BGZF source");
378            let source_bytes = bgzf_writer.finish().expect("should finish BGZF source");
379
380            let (archive_checksum, source_checksum) = stage_bgzf_asset_copy(
381                &workspace,
382                FileTypes::Fasta,
383                Cursor::new(source_bytes.clone()),
384                CompressionType::Bgzf,
385                None,
386            )
387            .expect("should retain BGZF input");
388
389            let expected_checksum = checksum(&source_bytes);
390            assert_eq!(source_checksum, expected_checksum);
391            assert_eq!(archive_checksum, expected_checksum);
392            assert_eq!(
393                assert_retained_bgzf_asset(&workspace, archive_checksum, expected_contents),
394                source_bytes,
395                "retained BGZF bytes should be identical to source bytes"
396            );
397        }
398
399        #[test]
400        fn test_stage_bgzf_asset_copy_compresses_plain_input() {
401            let temp_dir = tempdir().expect("should create temporary directory");
402            let workspace = setup_workspace(&temp_dir);
403            let source_bytes = b">sequence\nACGT\n";
404
405            let (archive_checksum, source_checksum) = stage_bgzf_asset_copy(
406                &workspace,
407                FileTypes::Fasta,
408                Cursor::new(source_bytes.to_vec()),
409                CompressionType::Plain,
410                None,
411            )
412            .expect("should retain plain input as BGZF");
413
414            assert_eq!(
415                source_checksum,
416                checksum(source_bytes),
417                "source checksum should cover the exact plain input bytes"
418            );
419            assert_retained_bgzf_asset(&workspace, archive_checksum, source_bytes);
420        }
421
422        #[test]
423        fn test_stage_bgzf_asset_copy_does_not_overwrite_existing_archive() {
424            let temp_dir = tempdir().expect("should create temporary directory");
425            let workspace = setup_workspace(&temp_dir);
426            let mut bgzf_writer = bgzf::io::Writer::new(Vec::new());
427            bgzf_writer
428                .write_all(b">sequence\nACGT\n")
429                .expect("should write BGZF source");
430            let source_bytes = bgzf_writer.finish().expect("should finish BGZF source");
431            let first_result = stage_bgzf_asset_copy(
432                &workspace,
433                FileTypes::Fasta,
434                Cursor::new(source_bytes.clone()),
435                CompressionType::Bgzf,
436                None,
437            )
438            .expect("should retain first BGZF source");
439            let archive_path = retained_archive_path(&workspace, first_result.0);
440            let original_archive_bytes =
441                fs::read(&archive_path).expect("should read first retained BGZF asset");
442
443            let fixed_modified_time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_600_000_000);
444            File::options()
445                .write(true)
446                .open(&archive_path)
447                .expect("should open retained BGZF asset")
448                .set_times(FileTimes::new().set_modified(fixed_modified_time))
449                .expect("should set retained asset modification time");
450            let modified_time_before = fs::metadata(&archive_path)
451                .expect("should inspect retained BGZF asset")
452                .modified()
453                .expect("should read retained asset modification time");
454
455            let second_result = stage_bgzf_asset_copy(
456                &workspace,
457                FileTypes::Fasta,
458                Cursor::new(source_bytes.clone()),
459                CompressionType::Bgzf,
460                None,
461            )
462            .expect("should retain duplicate BGZF source");
463
464            assert_eq!(first_result, second_result);
465            assert_eq!(
466                fs::read(&archive_path).expect("should read retained BGZF asset again"),
467                original_archive_bytes,
468                "existing archive bytes should be unchanged"
469            );
470            assert_eq!(
471                fs::metadata(&archive_path)
472                    .expect("should inspect retained BGZF asset again")
473                    .modified()
474                    .expect("should read retained asset modification time again"),
475                modified_time_before,
476                "existing archive modification time should be unchanged"
477            );
478            assert_eq!(
479                fs::read_dir(workspace.asset_dir().expect("should find asset directory"))
480                    .expect("should read asset directory")
481                    .count(),
482                1,
483                "duplicate retention should leave no staged files behind"
484            );
485        }
486    }
487}