Skip to main content

gtars_refget/
collection.rs

1//! Extended SequenceCollection with filesystem operations.
2//!
3//! This module adds file I/O and caching methods to the core types
4//! defined in `crate::digest::types`.
5
6use anyhow::Result;
7// The RGSI writers get their `Write` through `atomic_write`'s `&mut dyn Write`
8// (trait objects need no import); only the filesystem-only FASTA writer needs
9// the trait itself in scope.
10#[cfg(feature = "filesystem")]
11use std::io::Write;
12use std::path::Path;
13
14// FASTA digesting + path helpers are filesystem-only; the rest of this module
15// (the `*Ext` traits, `read_rgsi_file`, RGSI writers) is WASM-safe.
16#[cfg(feature = "filesystem")]
17use crate::fasta::digest_fasta;
18#[cfg(feature = "filesystem")]
19use crate::utils::PathExtension;
20
21use crate::digest::types::{
22    SeqColDigestLvl1, SequenceCollection, SequenceCollectionMetadata,
23    SequenceMetadata, SequenceRecord, parse_rgsi_line,
24};
25
26/// Write a collection's RGSI (Refget Sequence Index) file: level-1 header
27/// lines, then one row per member.
28///
29/// Published atomically (temp + `rename(2)`): a `collections/<digest>.rgsi` is a
30/// content-addressed per-item file that concurrent writers may produce
31/// simultaneously, and the orphan-GC live-set computation reads these files, so a
32/// torn one would be read as "this collection references nothing".
33pub fn write_collection_rgsi_rows<P, I>(
34    file_path: P,
35    metadata: &SequenceCollectionMetadata,
36    rows: I,
37) -> Result<()>
38where
39    P: AsRef<Path>,
40    I: IntoIterator,
41    I::Item: std::borrow::Borrow<SequenceMetadata>,
42{
43    use std::borrow::Borrow;
44    crate::store::atomic::atomic_write(file_path.as_ref(), |file| {
45        // Write collection digest headers
46        writeln!(file, "##seqcol_digest={}", metadata.digest)?;
47        writeln!(file, "##names_digest={}", metadata.names_digest)?;
48        writeln!(file, "##sequences_digest={}", metadata.sequences_digest)?;
49        writeln!(file, "##lengths_digest={}", metadata.lengths_digest)?;
50        if let Some(ref nlp) = metadata.name_length_pairs_digest {
51            writeln!(file, "##name_length_pairs_digest={}", nlp)?;
52        }
53        if let Some(ref snlp) = metadata.sorted_name_length_pairs_digest {
54            writeln!(file, "##sorted_name_length_pairs_digest={}", snlp)?;
55        }
56        if let Some(ref ss) = metadata.sorted_sequences_digest {
57            writeln!(file, "##sorted_sequences_digest={}", ss)?;
58        }
59        writeln!(
60            file,
61            "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription"
62        )?;
63
64        for row in rows {
65            let seq_meta: &SequenceMetadata = row.borrow();
66            writeln!(
67                file,
68                "{}\t{}\t{}\t{}\t{}\t{}",
69                seq_meta.name,
70                seq_meta.length,
71                seq_meta.alphabet,
72                seq_meta.sha512t24u,
73                seq_meta.md5,
74                seq_meta.description.as_deref().unwrap_or("")
75            )?;
76        }
77        Ok(())
78    })
79}
80
81// ============================================================================
82// Extensions to SequenceMetadata for filesystem operations
83// ============================================================================
84
85/// Extension trait for SequenceMetadata with filesystem-dependent methods.
86pub trait SequenceMetadataExt {
87    fn disk_size(&self, mode: &crate::store::StorageMode) -> usize;
88}
89
90impl SequenceMetadataExt for SequenceMetadata {
91    /// Calculate the disk size in bytes for this sequence.
92    fn disk_size(&self, mode: &crate::store::StorageMode) -> usize {
93        match mode {
94            crate::store::StorageMode::Raw => self.length,
95            crate::store::StorageMode::Encoded => {
96                let bits_per_symbol = self.alphabet.bits_per_symbol();
97                let total_bits = self.length * bits_per_symbol;
98                total_bits.div_ceil(8)
99            }
100            // Zstd compressed size is data-dependent and not derivable from
101            // metadata; report the logical (ASCII) length as an upper-bound
102            // estimate. Callers needing the true on-disk size must `du` the files.
103            crate::store::StorageMode::Zstd => self.length,
104        }
105    }
106}
107
108// ============================================================================
109// Extensions to SequenceRecord for filesystem operations
110// ============================================================================
111
112/// Extension trait for SequenceRecord with filesystem-dependent methods.
113pub trait SequenceRecordExt {
114    fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<()>;
115}
116
117impl SequenceRecordExt for SequenceRecord {
118    /// Write a single sequence to a file.
119    fn to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
120        use std::fs::{self, File};
121        use std::io::Write;
122
123        let data: &[u8] = match self {
124            SequenceRecord::Stub(_) => {
125                return Err(anyhow::anyhow!(
126                    "Cannot write file: sequence data not loaded"
127                ));
128            }
129            SequenceRecord::Full { sequence, .. } => sequence,
130        };
131
132        // Create parent directories if they don't exist
133        if let Some(parent) = path.as_ref().parent() {
134            fs::create_dir_all(parent)?;
135        }
136
137        let mut file = File::create(path)?;
138        file.write_all(data)?;
139        Ok(())
140    }
141}
142
143// ============================================================================
144// ============================================================================
145// Extensions to SequenceCollection for filesystem operations
146// ============================================================================
147
148/// Extension trait for SequenceCollection with filesystem-dependent methods.
149#[cfg(feature = "filesystem")]
150pub trait SequenceCollectionExt {
151    fn from_fasta<P: AsRef<Path>>(file_path: P) -> Result<SequenceCollection>;
152    fn from_rgsi<P: AsRef<Path>>(file_path: P) -> Result<SequenceCollection>;
153    fn from_path_no_cache<P: AsRef<Path>>(file_path: P) -> Result<SequenceCollection>;
154    fn from_path_with_cache<P: AsRef<Path>>(
155        file_path: P,
156        read_cache: bool,
157        write_cache: bool,
158    ) -> Result<SequenceCollection>;
159    fn write_collection_rgsi<P: AsRef<Path>>(&self, file_path: P) -> Result<()>;
160    fn write_rgsi(&self) -> Result<()>;
161    fn write_fasta<P: AsRef<Path>>(&self, file_path: P, line_width: Option<usize>) -> Result<()>;
162}
163
164#[cfg(feature = "filesystem")]
165impl SequenceCollectionExt for SequenceCollection {
166    /// Default behavior: read and write cache
167    fn from_fasta<P: AsRef<Path>>(file_path: P) -> Result<SequenceCollection> {
168        Self::from_path_with_cache(file_path, true, true)
169    }
170
171    fn from_rgsi<P: AsRef<Path>>(file_path: P) -> Result<SequenceCollection> {
172        let rgsi_file_path = file_path.as_ref().replace_exts_with("rgsi");
173
174        if rgsi_file_path.exists() {
175            read_rgsi_file(&rgsi_file_path)
176        } else {
177            Err(anyhow::anyhow!(
178                "RGSI file does not exist at {:?}",
179                rgsi_file_path
180            ))
181        }
182    }
183
184    /// No caching at all
185    fn from_path_no_cache<P: AsRef<Path>>(file_path: P) -> Result<SequenceCollection> {
186        Self::from_path_with_cache(file_path, false, false)
187    }
188
189    fn from_path_with_cache<P: AsRef<Path>>(
190        file_path: P,
191        read_cache: bool,
192        write_cache: bool,
193    ) -> Result<SequenceCollection> {
194        let fa_file_path = file_path.as_ref();
195        let rgsi_file_path = fa_file_path.replace_exts_with("rgsi");
196
197        // Check if the cache file exists and is valid
198        if read_cache && rgsi_file_path.exists() {
199            let seqcol = read_rgsi_file(&rgsi_file_path)?;
200            if !seqcol.sequences.is_empty() {
201                return Ok(seqcol);
202            }
203            // Cache is empty/stale - fall through to re-digest
204            let _ = std::fs::remove_file(&rgsi_file_path);
205        }
206
207        // Digest the fasta file
208        let seqcol: SequenceCollection = digest_fasta(file_path.as_ref())?;
209
210        // Write the SequenceCollection to the RGSI file
211        if write_cache && !rgsi_file_path.exists() {
212            seqcol.write_rgsi()?;
213        }
214        Ok(seqcol)
215    }
216
217    /// Write the SequenceCollection to an RGSI file.
218    fn write_collection_rgsi<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
219        write_collection_rgsi_rows(file_path, &self.metadata, self.sequences.iter().map(|s| s.metadata()))
220    }
221
222    /// Write the SequenceCollection to an RGSI file using the stored file path.
223    fn write_rgsi(&self) -> Result<()> {
224        if let Some(file_path) = &self.metadata.file_path {
225            let rgsi_file_path = file_path.replace_exts_with("rgsi");
226            self.write_collection_rgsi(rgsi_file_path)
227        } else {
228            Err(anyhow::anyhow!(
229                "No file path specified for RGSI output. Use `write_collection_rgsi` to specify a file path."
230            ))
231        }
232    }
233
234    /// Write the SequenceCollection to a FASTA file.
235    fn write_fasta<P: AsRef<Path>>(&self, file_path: P, line_width: Option<usize>) -> Result<()> {
236        use std::fs::File;
237
238        let line_width = line_width.unwrap_or(70);
239        let mut output_file = File::create(file_path)?;
240
241        for record in &self.sequences {
242            if !record.is_loaded() {
243                return Err(anyhow::anyhow!(
244                    "Cannot write FASTA: sequence '{}' does not have data loaded",
245                    record.metadata().name
246                ));
247            }
248
249            let decoded_sequence = record.decode().ok_or_else(|| {
250                anyhow::anyhow!("Failed to decode sequence '{}'", record.metadata().name)
251            })?;
252
253            // Write FASTA header
254            let metadata = record.metadata();
255            let header = match &metadata.description {
256                Some(desc) => format!(">{} {}", metadata.name, desc),
257                None => format!(">{}", metadata.name),
258            };
259            writeln!(output_file, "{}", header)?;
260
261            // Write sequence with line wrapping
262            for chunk in decoded_sequence.as_bytes().chunks(line_width) {
263                output_file.write_all(chunk)?;
264                output_file.write_all(b"\n")?;
265            }
266        }
267
268        Ok(())
269    }
270}
271
272// ============================================================================
273// RGSI File I/O
274// ============================================================================
275
276/// The `##key=value` header lines of a collection RGSI file.
277#[derive(Default)]
278pub(crate) struct RgsiHeader {
279    seqcol_digest: String,
280    names_digest: String,
281    sequences_digest: String,
282    lengths_digest: String,
283    name_length_pairs_digest: Option<String>,
284    sorted_name_length_pairs_digest: Option<String>,
285    sorted_sequences_digest: Option<String>,
286}
287
288impl RgsiHeader {
289    /// Record `line` if it is a `##` header line; returns whether it was one.
290    /// Unknown keys are ignored.
291    pub(crate) fn read_line(&mut self, line: &str) -> bool {
292        let Some(stripped) = line.strip_prefix("##") else {
293            return false;
294        };
295        if let Some((key, value)) = stripped.split_once('=') {
296            match key {
297                "seqcol_digest" => self.seqcol_digest = value.to_string(),
298                "names_digest" => self.names_digest = value.to_string(),
299                "sequences_digest" => self.sequences_digest = value.to_string(),
300                "lengths_digest" => self.lengths_digest = value.to_string(),
301                "name_length_pairs_digest" => self.name_length_pairs_digest = Some(value.to_string()),
302                "sorted_name_length_pairs_digest" => {
303                    self.sorted_name_length_pairs_digest = Some(value.to_string())
304                }
305                "sorted_sequences_digest" => self.sorted_sequences_digest = Some(value.to_string()),
306                _ => {}
307            }
308        }
309        true
310    }
311
312    /// The collection metadata the header describes, or `None` if it lacks
313    /// one of the level-1 digests (files from older writers), in which case
314    /// the digests must be computed from the rows.
315    pub(crate) fn into_metadata(
316        self,
317        n_sequences: usize,
318        file_path: &Path,
319    ) -> Option<SequenceCollectionMetadata> {
320        if self.sequences_digest.is_empty()
321            || self.names_digest.is_empty()
322            || self.lengths_digest.is_empty()
323        {
324            return None;
325        }
326        let lvl1 = SeqColDigestLvl1 {
327            sequences_digest: self.sequences_digest,
328            names_digest: self.names_digest,
329            lengths_digest: self.lengths_digest,
330        };
331        let digest = if self.seqcol_digest.is_empty() {
332            lvl1.to_digest()
333        } else {
334            self.seqcol_digest
335        };
336        Some(SequenceCollectionMetadata {
337            digest,
338            n_sequences,
339            names_digest: lvl1.names_digest,
340            sequences_digest: lvl1.sequences_digest,
341            lengths_digest: lvl1.lengths_digest,
342            name_length_pairs_digest: self.name_length_pairs_digest,
343            sorted_name_length_pairs_digest: self.sorted_name_length_pairs_digest,
344            sorted_sequences_digest: self.sorted_sequences_digest,
345            file_path: Some(file_path.to_path_buf()),
346        })
347    }
348}
349
350/// Read an RGSI file and return a SequenceCollection.
351pub fn read_rgsi_file<T: AsRef<Path>>(file_path: T) -> Result<SequenceCollection> {
352    use std::io::BufRead;
353
354    let file = std::fs::File::open(&file_path)?;
355    let reader = std::io::BufReader::new(file);
356    let mut results = Vec::new();
357    let mut header = RgsiHeader::default();
358    for line in reader.lines() {
359        let line = line?;
360        // Header metadata lines, then other comment lines.
361        if header.read_line(&line) || line.starts_with('#') {
362            continue;
363        }
364        if let Some(metadata) = parse_rgsi_line(&line) {
365            results.push(SequenceRecord::Stub(metadata));
366        }
367    }
368
369    let path = file_path.as_ref();
370    let collection_metadata = match header.into_metadata(results.len(), path) {
371        Some(metadata) => metadata,
372        None => SequenceCollectionMetadata::from_sequences(&results, Some(path.to_path_buf())),
373    };
374
375    Ok(SequenceCollection {
376        metadata: collection_metadata,
377        sequences: results,
378    })
379}
380
381// ============================================================================
382// Tests
383// ============================================================================
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use crate::digest::digest_sequence;
389    use crate::digest::encode_sequence;
390    use crate::digest::{AlphabetType, lookup_alphabet};
391
392    #[test]
393    fn test_decode_handles_encoded_data() {
394        let sequence = b"ACGT";
395        let alphabet = lookup_alphabet(&AlphabetType::Dna2bit);
396        let encoded_data = encode_sequence(sequence, alphabet).unwrap();
397
398        let record = SequenceRecord::Full {
399            metadata: SequenceMetadata {
400                name: "test_seq".to_string(),
401                description: None,
402                length: 4,
403                sha512t24u: "test_digest".to_string(),
404                md5: "test_md5".to_string(),
405                alphabet: AlphabetType::Dna2bit,
406                fai: None,
407            },
408            sequence: std::sync::Arc::new(encoded_data),
409        };
410
411        let decoded = record.decode().expect("Should decode encoded data");
412        assert_eq!(decoded, "ACGT");
413    }
414
415    #[test]
416    fn test_digest_sequence_basic() {
417        let seq = digest_sequence("test_seq", b"ACGTACGT");
418        assert_eq!(seq.metadata().name, "test_seq");
419        assert_eq!(seq.metadata().length, 8);
420        assert!(!seq.metadata().sha512t24u.is_empty());
421        assert!(seq.is_loaded());
422        assert_eq!(seq.sequence().unwrap(), b"ACGTACGT");
423    }
424
425    #[test]
426    fn test_sequence_metadata_disk_size() {
427        use crate::store::StorageMode;
428
429        let metadata = SequenceMetadata {
430            name: "test".to_string(),
431            description: None,
432            length: 1000,
433            sha512t24u: "test".to_string(),
434            md5: "test".to_string(),
435            alphabet: AlphabetType::Dna2bit,
436            fai: None,
437        };
438
439        assert_eq!(metadata.disk_size(&StorageMode::Raw), 1000);
440        assert_eq!(metadata.disk_size(&StorageMode::Encoded), 250);
441    }
442}
443
444// FASTA-based tests require the `filesystem` feature (digest_fasta/load_fasta,
445// SequenceCollectionExt::from_path_no_cache/write_fasta).
446#[cfg(all(test, feature = "filesystem"))]
447mod fasta_tests {
448    use super::*;
449    use crate::digest::digest_sequence;
450    use crate::fasta::{digest_fasta, load_fasta};
451
452    #[test]
453    fn test_decode_returns_none_when_no_data() {
454        let seqcol =
455            digest_fasta("../tests/data/fasta/base.fa").expect("Failed to load test FASTA file");
456
457        for seq_record in &seqcol.sequences {
458            assert!(!seq_record.is_loaded());
459            assert_eq!(seq_record.decode(), None);
460        }
461    }
462
463    #[test]
464    fn test_decode_with_loaded_data() {
465        let seqcol =
466            load_fasta("../tests/data/fasta/base.fa").expect("Failed to load test FASTA file");
467
468        let expected_sequences = vec![("chrX", "TTGGGGAA"), ("chr1", "GGAA"), ("chr2", "GCGC")];
469
470        for (seq_record, (expected_name, expected_seq)) in
471            seqcol.sequences.iter().zip(expected_sequences.iter())
472        {
473            assert_eq!(seq_record.metadata().name, *expected_name);
474            assert!(seq_record.is_loaded());
475            let decoded = seq_record.decode().expect("decode() should return Some");
476            assert_eq!(decoded, *expected_seq);
477        }
478    }
479
480    #[test]
481    fn test_sequence_collection_from_fasta() {
482        let seqcol = SequenceCollection::from_path_no_cache("../tests/data/fasta/base.fa")
483            .expect("Failed to load FASTA");
484
485        assert_eq!(seqcol.sequences.len(), 3);
486        assert!(!seqcol.metadata.digest.is_empty());
487    }
488
489    #[test]
490    fn test_sequence_collection_write_and_read_rgsi() {
491        use tempfile::tempdir;
492
493        let seqcol =
494            digest_fasta("../tests/data/fasta/base.fa").expect("Failed to load test FASTA file");
495
496        let dir = tempdir().expect("Failed to create temp dir");
497        let rgsi_path = dir.path().join("test.rgsi");
498
499        seqcol
500            .write_collection_rgsi(&rgsi_path)
501            .expect("Failed to write RGSI");
502
503        let loaded = read_rgsi_file(&rgsi_path).expect("Failed to read RGSI");
504
505        assert_eq!(loaded.metadata.digest, seqcol.metadata.digest);
506        assert_eq!(loaded.sequences.len(), seqcol.sequences.len());
507    }
508
509    #[test]
510    fn test_sequence_collection_write_fasta() {
511        use std::fs;
512        use tempfile::tempdir;
513
514        let seqcol =
515            load_fasta("../tests/data/fasta/base.fa").expect("Failed to load test FASTA file");
516
517        let dir = tempdir().expect("Failed to create temp dir");
518        let fasta_path = dir.path().join("output.fa");
519
520        seqcol
521            .write_fasta(&fasta_path, None)
522            .expect("Failed to write FASTA");
523
524        let content = fs::read_to_string(&fasta_path).expect("Failed to read file");
525        assert!(content.contains(">chrX"));
526        assert!(content.contains("TTGGGGAA"));
527    }
528
529    #[test]
530    fn test_digest_sequence_matches_fasta_digest() {
531        let seqcol =
532            load_fasta("../tests/data/fasta/base.fa").expect("Failed to load test FASTA file");
533        let fasta_seq = &seqcol.sequences[0]; // chrX: TTGGGGAA
534
535        let prog_seq = digest_sequence("chrX", b"TTGGGGAA");
536
537        assert_eq!(
538            prog_seq.metadata().sha512t24u,
539            fasta_seq.metadata().sha512t24u
540        );
541        assert_eq!(prog_seq.metadata().md5, fasta_seq.metadata().md5);
542    }
543
544    #[test]
545    fn test_sequence_record_to_file() {
546        use std::fs;
547        use tempfile::tempdir;
548
549        let seqcol =
550            load_fasta("../tests/data/fasta/base.fa").expect("Failed to load test FASTA file");
551
552        let dir = tempdir().expect("Failed to create temp dir");
553        let file_path = dir.path().join("test_seq.txt");
554
555        seqcol.sequences[0]
556            .to_file(&file_path)
557            .expect("Failed to write file");
558
559        let content = fs::read(&file_path).expect("Failed to read file");
560        assert!(!content.is_empty());
561    }
562
563    #[test]
564    fn test_rgsi_round_trip_ancillary_digests() {
565        use tempfile::tempdir;
566
567        let mut seqcol =
568            digest_fasta("../tests/data/fasta/base.fa").expect("Failed to load test FASTA file");
569
570        // Compute ancillary digests before writing
571        seqcol
572            .metadata
573            .compute_ancillary_digests(&seqcol.sequences);
574        assert!(seqcol.metadata.name_length_pairs_digest.is_some());
575        assert!(seqcol.metadata.sorted_name_length_pairs_digest.is_some());
576        assert!(seqcol.metadata.sorted_sequences_digest.is_some());
577
578        // Write RGSI
579        let dir = tempdir().expect("Failed to create temp dir");
580        let rgsi_path = dir.path().join("test_ancillary.rgsi");
581        seqcol
582            .write_collection_rgsi(&rgsi_path)
583            .expect("Failed to write RGSI");
584
585        // Read it back
586        let loaded = read_rgsi_file(&rgsi_path).expect("Failed to read RGSI");
587
588        // Ancillary digests should be preserved
589        assert_eq!(
590            loaded.metadata.name_length_pairs_digest,
591            seqcol.metadata.name_length_pairs_digest
592        );
593        assert_eq!(
594            loaded.metadata.sorted_name_length_pairs_digest,
595            seqcol.metadata.sorted_name_length_pairs_digest
596        );
597        assert_eq!(
598            loaded.metadata.sorted_sequences_digest,
599            seqcol.metadata.sorted_sequences_digest
600        );
601    }
602}