Skip to main content

gtars_refget/store/
export.rs

1//! FASTA export and BED region extraction for RefgetStore.
2//!
3//! Exports stream one sequence at a time: each record's stored bytes are read
4//! once (from RAM, a local `.seq` file, or the remote store) and decoded in
5//! chunks, so peak memory is one sequence's packed bytes plus one chunk. An
6//! export never loads sequences into the store and never writes `.seq` files
7//! into a remote store's cache.
8
9use super::*;
10use super::label::{invert, label_err, AliasIndex, LabelTemplate};
11use super::readonly::ReadonlyRefgetStore;
12
13use std::collections::{HashMap, HashSet};
14use std::ffi::OsStr;
15use std::fs::File;
16use std::io::{BufWriter, Write};
17use std::path::Path;
18
19use anyhow::{anyhow, Context, Result};
20use flate2::Compression;
21use flate2::write::GzEncoder;
22use flate2::read::MultiGzDecoder;
23use gtars_core::utils::get_file_info;
24
25use crate::digest::{
26    AlphabetType, SequenceMetadata, decode_substring_from_bytes, lookup_alphabet, strip_sq_prefix,
27};
28use super::catalog::SeqRow;
29
30/// Bases decoded per chunk when streaming a record.
31pub(crate) const EXPORT_CHUNK_BASES: usize = 1 << 20;
32
33/// Records between progress lines on stderr.
34const PROGRESS_EVERY: usize = 1000;
35
36// ============================================================================
37// Public export types
38// ============================================================================
39
40/// Which records an export writes.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum ExportSelection {
43    /// One or more collections, optionally limited to some sequence names in each.
44    Collections { digests: Vec<String>, names: Option<Vec<String>> },
45    /// Specific sequences by digest. These records have no collection.
46    SeqDigests(Vec<String>),
47    /// Every collection, plus any sequence that is in no collection.
48    All,
49}
50
51impl ExportSelection {
52    /// Build a selection from binding-style arguments: exactly one of
53    /// `collections`, `seq_digests` or `all`, and `names` only with collections.
54    pub fn from_parts(
55        collections: Option<Vec<String>>,
56        names: Option<Vec<String>>,
57        seq_digests: Option<Vec<String>>,
58        all: bool,
59    ) -> Result<Self> {
60        if collections.is_some() as u8 + seq_digests.is_some() as u8 + all as u8 != 1 {
61            return Err(label_err!("Set exactly one of collections, seq_digests or all"));
62        }
63        Ok(match (collections, seq_digests) {
64            (Some(digests), _) => ExportSelection::Collections { digests, names },
65            _ if names.is_some() => {
66                return Err(label_err!("names only applies with collections"))
67            }
68            (_, Some(digests)) => ExportSelection::SeqDigests(digests),
69            _ => ExportSelection::All,
70        })
71    }
72}
73
74/// Molecule filter: BLAST and similar tools need one molecule type per database.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Molecule {
77    /// `Dna2bit`, `Dna3bit` and `DnaIupac` sequences.
78    Dna,
79    /// `Protein` sequences.
80    Protein,
81}
82
83impl Molecule {
84    /// Parse an optional `"dna"` / `"protein"` argument.
85    pub fn from_opt(s: Option<&str>) -> Result<Option<Self>> {
86        s.map(str::parse).transpose()
87    }
88
89    fn keeps(&self, alphabet: &AlphabetType) -> bool {
90        match self {
91            Molecule::Dna => matches!(
92                alphabet,
93                AlphabetType::Dna2bit | AlphabetType::Dna3bit | AlphabetType::DnaIupac
94            ),
95            Molecule::Protein => matches!(alphabet, AlphabetType::Protein),
96        }
97    }
98}
99
100impl std::str::FromStr for Molecule {
101    type Err = anyhow::Error;
102    fn from_str(s: &str) -> Result<Self> {
103        match s.to_ascii_lowercase().as_str() {
104            "dna" => Ok(Molecule::Dna),
105            "protein" => Ok(Molecule::Protein),
106            other => Err(label_err!("Invalid molecule '{}': expected 'dna' or 'protein'", other)),
107        }
108    }
109}
110
111/// How an export labels and formats its records.
112#[derive(Debug, Clone)]
113pub struct ExportOptions {
114    /// Label template; default `{seq}`.
115    pub label: LabelTemplate,
116    /// Keep only sequences of this molecule type.
117    pub molecule: Option<Molecule>,
118    /// Bases per line, default 80; `0` writes each sequence on one line.
119    pub line_width: usize,
120}
121
122impl Default for ExportOptions {
123    fn default() -> Self {
124        Self { label: LabelTemplate::default(), molecule: None, line_width: 80 }
125    }
126}
127
128/// Counts reported by an export.
129#[derive(Debug, Clone, Default, PartialEq, Eq)]
130pub struct ExportSummary {
131    /// Records written.
132    pub n_records: usize,
133    /// Bases written.
134    pub n_bases: u64,
135    /// Records whose label fell back to a digest (missing alias, or no collection).
136    pub n_fallbacks: usize,
137    /// Records skipped because the same label and sequence were already written.
138    pub n_deduplicated: usize,
139}
140
141// ============================================================================
142// Output and record writing
143// ============================================================================
144
145/// Open an export destination. `"-"` is stdout; a `.gz` path is gzipped.
146pub(crate) fn open_output(path: &Path) -> Result<Box<dyn Write>> {
147    if path == Path::new("-") {
148        return Ok(Box::new(BufWriter::with_capacity(1 << 20, std::io::stdout().lock())));
149    }
150    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
151        std::fs::create_dir_all(parent)?;
152    }
153    let file = File::create(path)
154        .with_context(|| format!("Failed to create output file: {}", path.display()))?;
155    Ok(if path.extension() == Some(OsStr::new("gz")) {
156        Box::new(GzEncoder::new(BufWriter::new(file), Compression::default()))
157    } else {
158        Box::new(BufWriter::new(file))
159    })
160}
161
162/// Write `bases` as lines of `line_width` (`0`: no wrapping, no newline).
163/// Callers keep every chunk but the last a multiple of `line_width`.
164fn write_lines(writer: &mut dyn Write, bases: &[u8], line_width: usize) -> Result<()> {
165    if line_width == 0 {
166        writer.write_all(bases)?;
167    } else {
168        for line in bases.chunks(line_width) {
169            writer.write_all(line)?;
170            writer.write_all(b"\n")?;
171        }
172    }
173    Ok(())
174}
175
176/// Read until `buf` is full or the reader ends; return the bytes read.
177fn read_full(reader: &mut impl std::io::Read, buf: &mut [u8]) -> Result<usize> {
178    let mut filled = 0;
179    while filled < buf.len() {
180        match reader.read(&mut buf[filled..]) {
181            Ok(0) => break,
182            Ok(n) => filled += n,
183            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
184            Err(e) => return Err(e.into()),
185        }
186    }
187    Ok(filled)
188}
189
190/// Write one FASTA record, decoding the body in chunks of about `chunk_bases`.
191///
192/// `header` is the label, written as `>{header}`. `data` is the stored bytes
193/// (packed, raw or zstd per `mode`). `line_width > 0` wraps the body;
194/// `0` writes it on a single line.
195pub(crate) fn write_fasta_record(
196    writer: &mut dyn Write,
197    header: &str,
198    meta: &SequenceMetadata,
199    data: &[u8],
200    mode: StorageMode,
201    line_width: usize,
202    chunk_bases: usize,
203) -> Result<()> {
204    // A multiple of line_width, so line breaks never straddle a chunk.
205    let chunk = if line_width == 0 {
206        chunk_bases.max(1)
207    } else {
208        (chunk_bases / line_width).max(1) * line_width
209    };
210
211    writer.write_all(b">")?;
212    writer.write_all(header.as_bytes())?;
213    writer.write_all(b"\n")?;
214
215    match mode {
216        StorageMode::Encoded => {
217            let alphabet = lookup_alphabet(&meta.alphabet);
218            let mut start = 0;
219            while start < meta.length {
220                let end = (start + chunk).min(meta.length);
221                let decoded = decode_substring_from_bytes(data, start, end, alphabet);
222                write_lines(writer, &decoded, line_width)?;
223                start = end;
224            }
225        }
226        StorageMode::Raw => {
227            for piece in data.chunks(chunk) {
228                write_lines(writer, piece, line_width)?;
229            }
230        }
231        StorageMode::Zstd => {
232            let mut decoder = zstd::stream::read::Decoder::with_buffer(data)
233                .context("Failed to open zstd sequence record")?;
234            let mut buf = vec![0u8; chunk];
235            loop {
236                let n = read_full(&mut decoder, &mut buf)
237                    .context("Failed to zstd-decompress sequence record")?;
238                if n == 0 {
239                    break;
240                }
241                write_lines(writer, &buf[..n], line_width)?;
242                if n < chunk {
243                    break;
244                }
245            }
246        }
247    }
248
249    if line_width == 0 {
250        writer.write_all(b"\n")?;
251    }
252    Ok(())
253}
254
255/// One record to write: its label and the sequence behind it.
256struct PlannedRecord {
257    label: String,
258    row: SeqRow,
259}
260
261/// A record before labeling: the sequence plus how it was reached.
262struct Candidate<'a> {
263    row: SeqRow,
264    /// `(collection digest, sequence name)` when reached through a collection.
265    collection: Option<(String, &'a str)>,
266}
267
268fn source_of(collection: &Option<(String, &str)>) -> String {
269    match collection {
270        Some((col, _)) => format!("collection {}", col),
271        None => "the sequence list".to_string(),
272    }
273}
274
275// ============================================================================
276// Shared per-region substring retrieval
277// ============================================================================
278
279/// Retrieve the substring for a single region, shared by the file-based and
280/// vectors-based iterators.
281///
282/// Mutates the caller-owned `previous_parsed_chr` / `current_seq_digest` cache
283/// so the consecutive-same-chrom optimization works across either path.
284/// `region_label` (e.g. `"Line 5"` or `"Region 5"`) is interpolated into error
285/// messages.
286#[allow(clippy::too_many_arguments)]
287fn retrieve_substring_for_region<K: AsRef<[u8]>>(
288    store: &ReadonlyRefgetStore,
289    collection_digest: &K,
290    parsed_chr: String,
291    parsed_start: i64,
292    parsed_end: i64,
293    previous_parsed_chr: &mut String,
294    current_seq_digest: &mut String,
295    region_label: &str,
296) -> Result<RetrievedSequence> {
297    if parsed_start < 0 || parsed_end < 0 {
298        return Err(anyhow!(
299            "{} has invalid start or end coordinates: start={}, end={}",
300            region_label,
301            parsed_start,
302            parsed_end
303        ));
304    }
305
306    if *previous_parsed_chr != parsed_chr {
307        *previous_parsed_chr = parsed_chr.clone();
308
309        let result = store
310            .get_sequence_by_name(collection_digest, &parsed_chr)
311            .map_err(|e| {
312                anyhow!(
313                    "{}: sequence '{}' not found in collection '{}': {}",
314                    region_label,
315                    parsed_chr,
316                    String::from_utf8_lossy(collection_digest.as_ref()),
317                    e
318                )
319            })?;
320
321        *current_seq_digest = result.metadata().sha512t24u.clone();
322    }
323
324    let retrieved_substring = store
325        .get_substring(&*current_seq_digest, parsed_start as usize, parsed_end as usize)
326        .map_err(|e| {
327            anyhow!(
328                "{}: failed to get substring for digest '{}' from {} to {}: {}",
329                region_label,
330                current_seq_digest,
331                parsed_start,
332                parsed_end,
333                e
334            )
335        })?;
336
337    Ok(RetrievedSequence {
338        sequence: retrieved_substring,
339        chrom_name: parsed_chr,
340        start: parsed_start as u32,
341        end: parsed_end as u32,
342    })
343}
344
345// ============================================================================
346// SubstringsFromRegions Iterator impl
347// ============================================================================
348
349impl<K> Iterator for SubstringsFromRegions<'_, K>
350where
351    K: AsRef<[u8]>,
352{
353    type Item = Result<RetrievedSequence, anyhow::Error>;
354
355    fn next(&mut self) -> Option<Self::Item> {
356        use gtars_core::utils::parse_bedlike_file;
357
358        let mut line_string = String::new();
359
360        let num_bytes = self.reader.read_line(&mut line_string);
361        match num_bytes {
362            Ok(bytes) => {
363                if bytes == 0 {
364                    return None;
365                }
366            }
367            Err(err) => return Some(Err(err.into())),
368        };
369
370        self.line_num += 1;
371
372        let (parsed_chr, parsed_start, parsed_end) = match parse_bedlike_file(line_string.trim()) {
373            Some(coords) => coords,
374            None => {
375                let err_str = format!(
376                    "Error reading line {} because it could not be parsed as a BED-like entry: '{}'",
377                    self.line_num + 1,
378                    line_string
379                );
380                return Some(Err(anyhow!(err_str)));
381            }
382        };
383
384        Some(retrieve_substring_for_region(
385            self.store,
386            &self.collection_digest,
387            parsed_chr,
388            parsed_start as i64,
389            parsed_end as i64,
390            &mut self.previous_parsed_chr,
391            &mut self.current_seq_digest,
392            &format!("Line {}", self.line_num + 1),
393        ))
394    }
395}
396
397// ============================================================================
398// SubstringsFromRegionVectors Iterator impl
399// ============================================================================
400
401impl<K> Iterator for SubstringsFromRegionVectors<'_, K>
402where
403    K: AsRef<[u8]>,
404{
405    type Item = Result<RetrievedSequence, anyhow::Error>;
406
407    fn next(&mut self) -> Option<Self::Item> {
408        if self.index >= self.chroms.len() {
409            return None;
410        }
411        let i = self.index;
412        self.index += 1;
413
414        let parsed_chr = self.chroms[i].clone();
415        let parsed_start = self.starts[i] as i64;
416        let parsed_end = self.ends[i] as i64;
417
418        Some(retrieve_substring_for_region(
419            self.store,
420            &self.collection_digest,
421            parsed_chr,
422            parsed_start,
423            parsed_end,
424            &mut self.previous_parsed_chr,
425            &mut self.current_seq_digest,
426            &format!("Region {}", i + 1),
427        ))
428    }
429}
430
431// ============================================================================
432// ReadonlyRefgetStore export methods
433// ============================================================================
434
435impl ReadonlyRefgetStore {
436    /// Get an iterator over substrings defined by BED file regions.
437    pub fn substrings_from_regions<'a, K: AsRef<[u8]>>(
438        &'a self,
439        collection_digest: K,
440        bed_file_path: &str,
441    ) -> Result<SubstringsFromRegions<'a, K>> {
442        let path = Path::new(bed_file_path);
443        let file_info = get_file_info(path);
444        let is_gzipped = file_info.is_gzipped;
445
446        let opened_bed_file = File::open(path)?;
447
448        let reader: Box<dyn std::io::Read> = match is_gzipped {
449            true => Box::new(MultiGzDecoder::new(std::io::BufReader::new(opened_bed_file))),
450            false => Box::new(opened_bed_file),
451        };
452        let reader = std::io::BufReader::new(reader);
453
454        Ok(SubstringsFromRegions {
455            store: self,
456            reader,
457            collection_digest,
458            previous_parsed_chr: String::new(),
459            current_seq_digest: String::new(),
460            line_num: 0,
461        })
462    }
463
464    /// Get an iterator over substrings defined by in-memory region vectors.
465    ///
466    /// `chroms`, `starts`, and `ends` are parallel slices; element `i` defines
467    /// region `chroms[i]:starts[i]-ends[i]`. Yields the same `RetrievedSequence`
468    /// results as `substrings_from_regions` without any temp-file round-trip.
469    pub fn substrings_from_region_vectors<'a, K, S>(
470        &'a self,
471        collection_digest: K,
472        chroms: &[S],
473        starts: &[u32],
474        ends: &[u32],
475    ) -> Result<SubstringsFromRegionVectors<'a, K>>
476    where
477        K: AsRef<[u8]>,
478        S: AsRef<str>,
479    {
480        if chroms.len() != starts.len() || chroms.len() != ends.len() {
481            return Err(anyhow!(
482                "Mismatched region vector lengths: chroms={}, starts={}, ends={}",
483                chroms.len(),
484                starts.len(),
485                ends.len()
486            ));
487        }
488
489        Ok(SubstringsFromRegionVectors {
490            store: self,
491            collection_digest,
492            chroms: chroms.iter().map(|c| c.as_ref().to_string()).collect(),
493            starts: starts.to_vec(),
494            ends: ends.to_vec(),
495            index: 0,
496            previous_parsed_chr: String::new(),
497            current_seq_digest: String::new(),
498        })
499    }
500
501    /// Digest -> alias maps for every sequence and collection namespace
502    /// `label` uses, after checking each namespace exists in this store.
503    pub(crate) fn label_alias_maps(&self, label: &LabelTemplate) -> Result<(AliasIndex, AliasIndex)> {
504        Ok((
505            self.label_aliases(label, AliasKind::Sequence)?,
506            self.label_aliases(label, AliasKind::Collection)?,
507        ))
508    }
509
510    /// [`Self::label_alias_maps`] for the namespaces of one alias kind.
511    fn label_aliases(&self, label: &LabelTemplate, kind: AliasKind) -> Result<AliasIndex> {
512        let what = match kind {
513            AliasKind::Sequence => "sequence",
514            AliasKind::Collection => "collection",
515        };
516        let available = self.aliases.namespaces_for(kind);
517        let mut out = AliasIndex::new();
518        for ns in label.namespaces(kind) {
519            if !available.contains(&ns) {
520                return Err(label_err!(
521                    "Unknown {}-alias namespace '{}' in label '{}'. This store's {}-alias namespaces: {}",
522                    what,
523                    ns,
524                    label,
525                    what,
526                    list_or_none(&available)
527                ));
528            }
529            let map = invert(self.aliases.namespace_map(kind, &ns));
530            out.insert(ns, map);
531        }
532        Ok(out)
533    }
534
535    /// Export sequences from BED file regions to a FASTA file.
536    ///
537    /// Writes one record per BED line, each on a single line, labeled by
538    /// `label` with `:start-end` appended (as samtools does). Labels repeat
539    /// when regions repeat; no uniqueness rule applies.
540    pub fn export_fasta_from_regions<K: AsRef<[u8]>>(
541        &self,
542        collection_digest: K,
543        bed_file_path: &str,
544        output_file_path: &str,
545        label: &LabelTemplate,
546    ) -> Result<ExportSummary> {
547        let coll = self.loaded_coll_row(collection_digest.as_ref())?;
548        let collection_str = self.catalog.coll_meta(coll).digest.clone();
549        let maps = self.label_alias_maps(label)?;
550
551        // Label each name once, from the member the region lookup resolves the
552        // name to (`member_by_name`), so a repeated name labels the same
553        // sequence whose bases are written.
554        let mut name_labels: HashMap<&str, (String, bool)> = HashMap::new();
555        for m in self.catalog.members(coll) {
556            if name_labels.contains_key(m.name()) {
557                continue;
558            }
559            let member = self.catalog.member_by_name(coll, m.name()).unwrap_or(m);
560            let sha = member.seq().sha512t24u();
561            let rendered =
562                label.render(sha.as_str(), Some((&collection_str, m.name())), &maps.0, &maps.1);
563            check_label_whitespace(&rendered.0)?;
564            name_labels.insert(m.name(), rendered);
565        }
566
567        let seq_iter = self.substrings_from_regions(&collection_digest, bed_file_path)?;
568        let mut writer = open_output(Path::new(output_file_path))?;
569        let mut summary = ExportSummary::default();
570
571        for rs in seq_iter {
572            let rs = rs?;
573            let (name_label, fallback) = name_labels
574                .get(rs.chrom_name.as_str())
575                .ok_or_else(|| anyhow!("Sequence '{}' not found in collection", rs.chrom_name))?;
576            writeln!(writer, ">{}:{}-{}", name_label, rs.start, rs.end)?;
577            writer.write_all(rs.sequence.as_bytes())?;
578            writer.write_all(b"\n")?;
579            summary.n_records += 1;
580            summary.n_bases += rs.sequence.len() as u64;
581            summary.n_fallbacks += *fallback as usize;
582        }
583
584        writer.flush()?;
585        Ok(summary)
586    }
587
588    /// Export sequences to a FASTA file, or to stdout when `output_path` is `"-"`.
589    ///
590    /// `selection` chooses which records to write; `opts.label` chooses how
591    /// each is labeled, the same way whatever the selection. The whole
592    /// `(label, sequence)` list is planned from metadata before any output is
593    /// written, so label errors never leave half a file. A repeated label for
594    /// the same sequence is written once (counted in `n_deduplicated`); a
595    /// repeated label for different sequences is an error.
596    ///
597    /// Record order: collections in the order given (digest order for `All`),
598    /// each in its own order; then, for `All`, sequences in no collection, in
599    /// digest order. When the label uses no collection field (`{seq}`,
600    /// `{seq:NS}`), `All` lists each sequence once in digest order, without
601    /// reading any collection.
602    ///
603    /// Exports stream one sequence at a time and leave the store's loaded
604    /// state unchanged. Collections named by `selection` (all of them for
605    /// `All` with a collection field) must be loaded; [`RefgetStore::export_fasta`]
606    /// loads them.
607    pub fn export_fasta<P: AsRef<Path>>(
608        &self,
609        selection: &ExportSelection,
610        output_path: P,
611        opts: &ExportOptions,
612    ) -> Result<ExportSummary> {
613        let line_width = opts.line_width;
614        let maps = self.label_alias_maps(&opts.label)?;
615        let candidates = self.export_candidates(selection, &opts.label)?;
616
617        // Plan: label every record, apply the uniqueness rule.
618        let mut summary = ExportSummary::default();
619        let mut seen: HashMap<String, (SeqRow, String)> = HashMap::new();
620        let mut plan: Vec<PlannedRecord> = Vec::new();
621        for c in candidates {
622            let view = self.catalog.seq(c.row);
623            if let Some(m) = opts.molecule {
624                if !m.keeps(&view.alphabet()) {
625                    continue;
626                }
627            }
628            let sha = view.sha512t24u();
629            let coll = c.collection.as_ref().map(|(col, name)| (col.as_str(), *name));
630            let (label, fallback) = opts.label.render(sha.as_str(), coll, &maps.0, &maps.1);
631            check_label_whitespace(&label)?;
632            match seen.get(&label) {
633                Some((row, _)) if *row == c.row => {
634                    summary.n_deduplicated += 1;
635                    continue;
636                }
637                Some((row, first_source)) => {
638                    return Err(label_err!(
639                        "Label '{}' would name two different sequences: {} from {} and {} from {}. \
640                         Add {{col:NS}} or {{col}} to the label (for example '{{col}}/{{name}}') to make labels unique.",
641                        label,
642                        self.catalog.seq(*row).sha512t24u(),
643                        first_source,
644                        sha,
645                        source_of(&c.collection)
646                    ));
647                }
648                None => {}
649            }
650            summary.n_fallbacks += fallback as usize;
651            seen.insert(label.clone(), (c.row, source_of(&c.collection)));
652            plan.push(PlannedRecord { label, row: c.row });
653        }
654        drop(seen);
655
656        // Write: stream each record's bytes.
657        let mut writer = open_output(output_path.as_ref())?;
658        let total = plan.len();
659        for (i, rec) in plan.iter().enumerate() {
660            let meta = self.catalog.seq(rec.row).to_metadata();
661            let bytes = self.read_stored_bytes(rec.row, false)?;
662            write_fasta_record(
663                &mut *writer,
664                &rec.label,
665                &meta,
666                &bytes[..],
667                self.mode,
668                line_width,
669                EXPORT_CHUNK_BASES,
670            )?;
671            summary.n_records += 1;
672            summary.n_bases += meta.length as u64;
673            if !self.quiet && ((i + 1) % PROGRESS_EVERY == 0 || i + 1 == total) {
674                eprintln!(
675                    "exported {}/{} records ({:.2} GB)",
676                    i + 1,
677                    total,
678                    summary.n_bases as f64 / 1e9
679                );
680            }
681        }
682        writer.flush()?;
683        Ok(summary)
684    }
685
686    /// Every record a selection reaches, in output order, before labeling.
687    fn export_candidates(
688        &self,
689        selection: &ExportSelection,
690        label: &LabelTemplate,
691    ) -> Result<Vec<Candidate<'_>>> {
692        let mut out: Vec<Candidate<'_>> = Vec::new();
693
694        match selection {
695            ExportSelection::Collections { digests, names } => {
696                if digests.is_empty() {
697                    return Err(anyhow!("No collections selected for export"));
698                }
699                for digest in digests {
700                    self.collection_candidates(digest, names.as_deref(), &mut out)?;
701                }
702            }
703            ExportSelection::SeqDigests(digests) => {
704                for d in digests {
705                    let row = self
706                        .catalog
707                        .resolve(strip_sq_prefix(d))
708                        .ok_or_else(|| anyhow!("Sequence record not found for digest: {}", d))?;
709                    out.push(Candidate { row, collection: None });
710                }
711            }
712            ExportSelection::All => {
713                let mut in_collection: HashSet<SeqRow> = HashSet::new();
714                if label.needs_collection() {
715                    let mut coll_digests: Vec<String> = self
716                        .catalog
717                        .coll_rows()
718                        .map(|c| self.catalog.coll_meta(c).digest.clone())
719                        .collect();
720                    coll_digests.sort();
721                    for digest in &coll_digests {
722                        let start = out.len();
723                        self.collection_candidates(digest, None, &mut out)?;
724                        in_collection.extend(out[start..].iter().map(|c| c.row));
725                    }
726                }
727                let mut rest: Vec<(crate::digest::Digest32, SeqRow)> = self
728                    .catalog
729                    .seq_rows()
730                    .filter(|r| !in_collection.contains(r))
731                    .map(|r| (self.catalog.seq(r).sha512t24u(), r))
732                    .collect();
733                rest.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
734                for (_, row) in rest {
735                    out.push(Candidate { row, collection: None });
736                }
737            }
738        }
739        Ok(out)
740    }
741
742    /// Append one collection's records (optionally only `names`) to `out`.
743    fn collection_candidates<'a>(
744        &'a self,
745        digest: &str,
746        names: Option<&[String]>,
747        out: &mut Vec<Candidate<'a>>,
748    ) -> Result<()> {
749        let coll = self.loaded_coll_row(digest)?;
750        let digest_str = self.catalog.coll_meta(coll).digest.clone();
751        let wanted: Option<HashSet<&str>> = names.map(|ns| ns.iter().map(String::as_str).collect());
752        if let Some(names) = names {
753            let present: HashSet<&str> = self.catalog.members(coll).map(|m| m.name()).collect();
754            if let Some(n) = names.iter().find(|n| !present.contains(n.as_str())) {
755                return Err(anyhow!("Sequence '{}' not found in collection {}", n, digest_str));
756            }
757        }
758        for m in self.catalog.members(coll) {
759            if wanted.as_ref().is_some_and(|w| !w.contains(m.name())) {
760                continue;
761            }
762            out.push(Candidate {
763                row: m.seq_row(),
764                collection: Some((digest_str.clone(), m.name())),
765            });
766        }
767        Ok(())
768    }
769}
770
771fn list_or_none(items: &[String]) -> String {
772    if items.is_empty() {
773        "(none)".to_string()
774    } else {
775        items.join(", ")
776    }
777}
778
779fn check_label_whitespace(label: &str) -> Result<()> {
780    if label.is_empty() {
781        return Err(label_err!("A record's label is empty; FASTA IDs need at least one character"));
782    }
783    if label.chars().any(char::is_whitespace) {
784        return Err(label_err!(
785            "Label '{}' contains whitespace; FASTA IDs end at the first space. Change the label template or the alias.",
786            label
787        ));
788    }
789    Ok(())
790}
791
792#[cfg(test)]
793mod tests {
794    use crate::store::{ExportOptions, ExportSelection, FastaImportOptions, LabelTemplate, RefgetStore};
795    use std::io::Write;
796
797    fn coll(digest: &str) -> ExportSelection {
798        ExportSelection::Collections { digests: vec![digest.to_string()], names: None }
799    }
800
801    fn name_opts(line_width: usize) -> ExportOptions {
802        ExportOptions {
803            label: LabelTemplate::parse("{name}").unwrap(),
804            molecule: None,
805            line_width,
806        }
807    }
808    use tempfile::{NamedTempFile, TempDir};
809
810    /// Build a small in-memory store from a temp FASTA and return it plus the
811    /// digest of the single collection created.
812    fn build_store() -> (RefgetStore, String) {
813        let mut fasta = NamedTempFile::new().expect("create temp fasta");
814        // A sequence longer than 80 bases so the wrapped export spans >1 line.
815        writeln!(fasta, ">seq1").unwrap();
816        writeln!(fasta, "{}", "ACGT".repeat(30)).unwrap(); // 120 bases
817        writeln!(fasta, ">seq2").unwrap();
818        writeln!(fasta, "TTGGCCAA").unwrap();
819        fasta.flush().unwrap();
820
821        let mut store = RefgetStore::in_memory();
822        store
823            .add_sequence_collection_from_fasta(fasta.path(), FastaImportOptions::new())
824            .expect("import fasta");
825
826        let collections = store.list_collections(0, usize::MAX, &[]).unwrap();
827        let digest = collections.results[0].digest.clone();
828        (store, digest)
829    }
830
831    /// Two single-record FASTAs with byte-identical sequences but different
832    /// headers: `>chr1 ucsc desc` and `>1 flybase desc`. Mirrors the UCSC vs
833    /// FlyBase situation from issue #270.
834    fn shared_sequence_fastas() -> (NamedTempFile, NamedTempFile) {
835        let seq = "ACGT".repeat(10);
836        let mut a = NamedTempFile::new().expect("create temp fasta A");
837        writeln!(a, ">chr1 ucsc desc").unwrap();
838        writeln!(a, "{}", seq).unwrap();
839        a.flush().unwrap();
840
841        let mut b = NamedTempFile::new().expect("create temp fasta B");
842        writeln!(b, ">1 flybase desc").unwrap();
843        writeln!(b, "{}", seq).unwrap();
844        b.flush().unwrap();
845        (a, b)
846    }
847
848    /// Import `first` then `second` into `store`; return their collection digests.
849    fn import_pair(store: &mut RefgetStore, first: &NamedTempFile, second: &NamedTempFile) -> (String, String) {
850        let (meta_first, _) = store
851            .add_sequence_collection_from_fasta(first.path(), FastaImportOptions::new())
852            .expect("import first fasta");
853        let (meta_second, _) = store
854            .add_sequence_collection_from_fasta(second.path(), FastaImportOptions::new())
855            .expect("import second fasta");
856        (meta_first.digest, meta_second.digest)
857    }
858
859    /// Export a collection unwrapped and return the headers in order.
860    fn export_headers(store: &crate::store::ReadonlyRefgetStore, digest: &str, dir: &TempDir) -> Vec<String> {
861        let out = dir.path().join(format!("{}.fa", digest));
862        store
863            .export_fasta(&coll(digest), &out, &name_opts(0))
864            .expect("export collection");
865        let content = std::fs::read_to_string(&out).unwrap();
866        records(&content).into_iter().map(|(h, _)| h).collect()
867    }
868
869    /// Split a FASTA into (header, body-lines) pairs.
870    fn records(fasta: &str) -> Vec<(String, Vec<String>)> {
871        let mut out: Vec<(String, Vec<String>)> = Vec::new();
872        for line in fasta.lines() {
873            if let Some(header) = line.strip_prefix('>') {
874                out.push((header.to_string(), Vec::new()));
875            } else if let Some(last) = out.last_mut() {
876                last.1.push(line.to_string());
877            }
878        }
879        out
880    }
881
882    #[test]
883    fn export_unwrapped_puts_each_sequence_on_one_line() {
884        let (store, digest) = build_store();
885        let readonly = store.into_readonly();
886
887        let dir = TempDir::new().unwrap();
888        let out = dir.path().join("unwrapped.fa");
889        readonly
890            .export_fasta(&coll(&digest), &out, &name_opts(0))
891            .expect("export unwrapped");
892
893        let content = std::fs::read_to_string(&out).unwrap();
894        let recs = records(&content);
895        assert_eq!(recs.len(), 2, "expected two records");
896        for (header, body) in &recs {
897            assert_eq!(
898                body.len(),
899                1,
900                "record '{}' should have exactly one body line when unwrapped, got {:?}",
901                header,
902                body
903            );
904        }
905        // seq1 body is the full 120 bases on a single line.
906        assert_eq!(recs[0].1[0].len(), 120);
907    }
908
909    #[test]
910    fn export_wrapped_at_80_splits_long_sequences() {
911        let (store, digest) = build_store();
912        let readonly = store.into_readonly();
913
914        let dir = TempDir::new().unwrap();
915        let out = dir.path().join("wrapped.fa");
916        readonly
917            .export_fasta(&coll(&digest), &out, &name_opts(80))
918            .expect("export wrapped");
919
920        let content = std::fs::read_to_string(&out).unwrap();
921        let recs = records(&content);
922        // seq1 (120 bases) wraps to two lines at width 80; seq2 (8 bases) stays one.
923        assert_eq!(recs[0].1.len(), 2, "120-base seq should wrap to 2 lines");
924        assert_eq!(recs[0].1[0].len(), 80);
925        assert_eq!(recs[0].1[1].len(), 40);
926        assert_eq!(recs[1].1.len(), 1);
927    }
928
929    #[test]
930    fn shared_sequence_exports_with_each_collections_own_name() {
931        let (fasta_a, fasta_b) = shared_sequence_fastas();
932
933        // Both import orders: the first-imported label must never leak into
934        // the other collection's export.
935        for swap in [false, true] {
936            let mut store = RefgetStore::in_memory();
937            let (digest_a, digest_b) = if swap {
938                let (b, a) = import_pair(&mut store, &fasta_b, &fasta_a);
939                (a, b)
940            } else {
941                import_pair(&mut store, &fasta_a, &fasta_b)
942            };
943            let readonly = store.into_readonly();
944            let dir = TempDir::new().unwrap();
945
946            assert_eq!(
947                export_headers(&readonly, &digest_a, &dir),
948                vec!["chr1".to_string()],
949                "swap={}",
950                swap
951            );
952            assert_eq!(
953                export_headers(&readonly, &digest_b, &dir),
954                vec!["1".to_string()],
955                "swap={}",
956                swap
957            );
958        }
959    }
960
961    #[test]
962    fn get_collection_returns_per_collection_description() {
963        let (fasta_a, fasta_b) = shared_sequence_fastas();
964        let mut store = RefgetStore::in_memory();
965        let (digest_a, digest_b) = import_pair(&mut store, &fasta_a, &fasta_b);
966        let readonly = store.into_readonly();
967
968        let coll_b = readonly.get_collection(&digest_b).expect("get collection B");
969        assert_eq!(coll_b.sequences.len(), 1);
970        assert_eq!(coll_b.sequences[0].metadata().name, "1");
971        assert_eq!(
972            coll_b.sequences[0].metadata().description.as_deref(),
973            Some("flybase desc")
974        );
975
976        let coll_a = readonly.get_collection(&digest_a).expect("get collection A");
977        assert_eq!(coll_a.sequences[0].metadata().name, "chr1");
978        assert_eq!(
979            coll_a.sequences[0].metadata().description.as_deref(),
980            Some("ucsc desc")
981        );
982    }
983
984    #[test]
985    fn shared_sequence_disk_roundtrip_exports_own_name() {
986        let (fasta_a, fasta_b) = shared_sequence_fastas();
987        let store_dir = TempDir::new().unwrap();
988
989        let (digest_a, digest_b) = {
990            let mut store = RefgetStore::on_disk(store_dir.path()).expect("create disk store");
991            import_pair(&mut store, &fasta_a, &fasta_b)
992        };
993
994        // Reopen so collection stubs come from collections/<digest>.rgsi via
995        // ensure_collection_loaded, not from the import-time in-memory records.
996        let mut store = RefgetStore::open_local(store_dir.path()).expect("reopen store");
997        store.load_collection(&digest_b).expect("load collection B");
998        store.load_collection(&digest_a).expect("load collection A");
999        store.load_all_sequences().expect("load sequences");
1000        let readonly = store.into_readonly();
1001
1002        let dir = TempDir::new().unwrap();
1003        assert_eq!(
1004            export_headers(&readonly, &digest_b, &dir),
1005            vec!["1".to_string()]
1006        );
1007        assert_eq!(
1008            export_headers(&readonly, &digest_a, &dir),
1009            vec!["chr1".to_string()]
1010        );
1011
1012        let coll_b = readonly.get_collection(&digest_b).unwrap();
1013        assert_eq!(
1014            coll_b.sequences[0].metadata().description.as_deref(),
1015            Some("flybase desc")
1016        );
1017    }
1018
1019    #[test]
1020    fn get_sequence_by_name_returns_per_collection_metadata() {
1021        let (fasta_a, fasta_b) = shared_sequence_fastas();
1022
1023        // Both import orders: the first-imported label must never leak into
1024        // the other collection's get_sequence_by_name() result.
1025        for swap in [false, true] {
1026            let mut store = RefgetStore::in_memory();
1027            let (digest_a, digest_b) = if swap {
1028                let (b, a) = import_pair(&mut store, &fasta_b, &fasta_a);
1029                (a, b)
1030            } else {
1031                import_pair(&mut store, &fasta_a, &fasta_b)
1032            };
1033            let readonly = store.into_readonly();
1034
1035            let rec_b = readonly
1036                .get_sequence_by_name(&digest_b, "1")
1037                .expect("get sequence '1' from collection B");
1038            assert_eq!(rec_b.metadata().name, "1", "swap={}", swap);
1039            assert_eq!(
1040                rec_b.metadata().description.as_deref(),
1041                Some("flybase desc"),
1042                "swap={}",
1043                swap
1044            );
1045
1046            let rec_a = readonly
1047                .get_sequence_by_name(&digest_a, "chr1")
1048                .expect("get sequence 'chr1' from collection A");
1049            assert_eq!(rec_a.metadata().name, "chr1", "swap={}", swap);
1050            assert_eq!(
1051                rec_a.metadata().description.as_deref(),
1052                Some("ucsc desc"),
1053                "swap={}",
1054                swap
1055            );
1056
1057            // Same underlying bytes, shared across both collections.
1058            assert_eq!(
1059                rec_a.metadata().sha512t24u,
1060                rec_b.metadata().sha512t24u,
1061                "swap={}",
1062                swap
1063            );
1064
1065            // Names do not leak across collections.
1066            assert!(
1067                readonly.get_sequence_by_name(&digest_b, "chr1").is_err(),
1068                "swap={}",
1069                swap
1070            );
1071        }
1072    }
1073
1074    #[test]
1075    fn get_sequence_by_name_disk_roundtrip() {
1076        let (fasta_a, fasta_b) = shared_sequence_fastas();
1077        let store_dir = TempDir::new().unwrap();
1078
1079        let (digest_a, digest_b) = {
1080            let mut store = RefgetStore::on_disk(store_dir.path()).expect("create disk store");
1081            import_pair(&mut store, &fasta_a, &fasta_b)
1082        };
1083
1084        // Reopen so collection stubs come from collections/<digest>.rgsi via
1085        // ensure_collection_loaded, not from the import-time in-memory records.
1086        let mut store = RefgetStore::open_local(store_dir.path()).expect("reopen store");
1087        store.load_collection(&digest_b).expect("load collection B");
1088        store.load_collection(&digest_a).expect("load collection A");
1089        store.load_all_sequences().expect("load sequences");
1090        let readonly = store.into_readonly();
1091
1092        let rec_b = readonly
1093            .get_sequence_by_name(&digest_b, "1")
1094            .expect("get sequence '1' from collection B");
1095        assert_eq!(rec_b.metadata().name, "1");
1096        assert_eq!(rec_b.metadata().description.as_deref(), Some("flybase desc"));
1097        assert!(rec_b.is_loaded());
1098        assert_eq!(rec_b.decode().unwrap(), "ACGT".repeat(10));
1099
1100        let rec_a = readonly
1101            .get_sequence_by_name(&digest_a, "chr1")
1102            .expect("get sequence 'chr1' from collection A");
1103        assert_eq!(rec_a.metadata().name, "chr1");
1104        assert_eq!(rec_a.metadata().description.as_deref(), Some("ucsc desc"));
1105        assert!(rec_a.is_loaded());
1106        assert_eq!(rec_a.decode().unwrap(), "ACGT".repeat(10));
1107    }
1108}