Skip to main content

gtars_refget/store/
core.rs

1//! RefgetStore wrapper struct with lazy-loading read methods.
2
3use super::*;
4use super::readonly::ReadonlyRefgetStore;
5
6use std::fmt::{Display, Formatter};
7use std::path::Path;
8
9use anyhow::Result;
10use std::fs::create_dir_all;
11
12use crate::digest::{SequenceCollection, SequenceRecord, strip_sq_prefix};
13// Only the filesystem FASTA-import wrappers use this return type.
14#[cfg(feature = "filesystem")]
15use crate::digest::SequenceCollectionMetadata;
16
17/// User-facing store with lazy-loading read methods.
18///
19/// Wraps `ReadonlyRefgetStore` and provides `&mut self` read methods that
20/// automatically load data on first access. Use `into_readonly()` to convert
21/// to an immutable store suitable for `Arc<ReadonlyRefgetStore>` in servers.
22#[derive(Debug)]
23pub struct RefgetStore {
24    pub(crate) inner: ReadonlyRefgetStore,
25}
26
27impl std::ops::Deref for RefgetStore {
28    type Target = ReadonlyRefgetStore;
29    fn deref(&self) -> &ReadonlyRefgetStore {
30        &self.inner
31    }
32}
33
34impl Display for RefgetStore {
35    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
36        write!(f, "{}", self.inner)
37    }
38}
39
40impl RefgetStore {
41    // =====================================================================
42    // Constructors
43    // =====================================================================
44
45    /// Check whether a valid RefgetStore exists at the given path.
46    pub fn store_exists<P: AsRef<Path>>(path: P) -> bool {
47        ReadonlyRefgetStore::store_exists(path)
48    }
49
50    /// Create a disk-backed RefgetStore.
51    pub fn on_disk<P: AsRef<Path>>(cache_path: P) -> Result<Self> {
52        Self::create_or_open(cache_path.as_ref(), Layout::Standalone)
53    }
54
55    /// Create a disk-backed RefgetStore with the PACKED sequence layout.
56    ///
57    /// Sequences are concatenated into sealed, size-capped pack files under
58    /// `packs/`, resolved via the `sequences.pack.idx` sidecar, instead of one
59    /// `.seq` file per digest. Mirrors [`Self::on_disk`] but sets
60    /// `layout = Packed` and creates `packs/`.
61    ///
62    /// Opening an EXISTING store: the layout always comes from its manifest.
63    /// Calling `on_disk_packed` on an existing STANDALONE store is an error,
64    /// since there is no in-place conversion (export a standalone image
65    /// instead). Calling it on an existing packed store just opens it.
66    pub fn on_disk_packed<P: AsRef<Path>>(cache_path: P) -> Result<Self> {
67        let cache_path = cache_path.as_ref();
68        let store = Self::create_or_open(cache_path, Layout::Packed)?;
69        if store.inner.layout != Layout::Packed {
70            return Err(anyhow::anyhow!(
71                "store at {} already exists with a standalone layout; \
72                 on_disk_packed cannot convert it in place. Create a fresh \
73                 packed store and export/re-import, or open it with on_disk.",
74                cache_path.display()
75            ));
76        }
77        Ok(store)
78    }
79
80    /// Open the store at `cache_path`, or create an empty Encoded store with
81    /// `layout` there if it has no `rgstore.json`.
82    fn create_or_open(cache_path: &Path, layout: Layout) -> Result<Self> {
83        if cache_path.join("rgstore.json").exists() {
84            return Self::open_local(cache_path);
85        }
86        create_dir_all(cache_path)?;
87        let mut inner = ReadonlyRefgetStore::new(StorageMode::Encoded);
88        inner.local_path = Some(cache_path.to_path_buf());
89        inner.seqdata_path_template = Some(DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());
90        inner.persist_to_disk = true;
91        inner.layout = layout;
92        create_dir_all(cache_path.join("sequences"))?;
93        create_dir_all(cache_path.join("collections"))?;
94        create_dir_all(cache_path.join("fhr"))?;
95        if layout == Layout::Packed {
96            create_dir_all(cache_path.join("packs"))?;
97        }
98        Ok(Self { inner })
99    }
100
101    /// Create an in-memory RefgetStore.
102    pub fn in_memory() -> Self {
103        Self {
104            inner: ReadonlyRefgetStore::new(StorageMode::Encoded),
105        }
106    }
107
108    /// Open a local RefgetStore from a directory.
109    pub fn open_local<P: AsRef<Path>>(path: P) -> Result<Self> {
110        Ok(Self {
111            inner: ReadonlyRefgetStore::open_local(path)?,
112        })
113    }
114
115    /// Open a remote RefgetStore with local caching.
116    pub fn open_remote<P: AsRef<Path>, S: AsRef<str>>(
117        cache_path: P,
118        remote_url: S,
119    ) -> Result<Self> {
120        Ok(Self {
121            inner: ReadonlyRefgetStore::open_remote(cache_path, remote_url)?,
122        })
123    }
124
125    /// Convert to a ReadonlyRefgetStore for concurrent read access.
126    pub fn into_readonly(self) -> ReadonlyRefgetStore {
127        self.inner
128    }
129
130    // =====================================================================
131    // Preload methods (delegate to inner)
132    // =====================================================================
133
134    /// Load the sequence index if not already loaded.
135    /// Servers should call this during startup to preload the index.
136    pub fn load_sequence_index(&mut self) -> Result<()> {
137        self.inner.load_sequence_index()
138    }
139
140    /// Preload all collections (delegates to inner).
141    pub fn load_all_collections(&mut self) -> Result<()> {
142        self.inner.load_all_collections()
143    }
144
145    /// Preload all sequences (delegates to inner).
146    pub fn load_all_sequences(&mut self) -> Result<()> {
147        self.inner.ensure_sequence_index_loaded()?;
148        self.inner.load_all_sequences()
149    }
150
151    /// Load a single collection by digest.
152    pub fn load_collection(&mut self, digest: &str) -> Result<()> {
153        self.inner.load_collection(digest)
154    }
155
156    /// Load a single sequence by digest. Accepts "SQ."-prefixed and MD5
157    /// digests; the disk loader needs the canonical SHA-512/24u key.
158    pub fn load_sequence(&mut self, digest: &str) -> Result<()> {
159        self.inner.ensure_sequence_index_loaded()?;
160        let canonical_digest = self
161            .inner
162            .get_sequence(strip_sq_prefix(digest))
163            .map(|record| record.metadata().sha512t24u.clone())?;
164        self.inner.load_sequence(&canonical_digest)
165    }
166
167    // =====================================================================
168    // Lazy-loading read methods
169    // =====================================================================
170
171    /// Lazy-loading get_collection. Loads on first access.
172    pub fn get_collection(&mut self, digest: &str) -> Result<SequenceCollection> {
173        if let Ok(coll) = self.inner.get_collection(digest) {
174            return Ok(coll);
175        }
176        self.inner.load_collection(digest)?;
177        self.inner.get_collection(digest)
178    }
179
180    /// Lazy-loading get_collection_level2.
181    pub fn get_collection_level2(&mut self, digest: &str) -> Result<crate::digest::CollectionLevel2> {
182        if let Ok(lvl2) = self.inner.get_collection_level2(digest) {
183            return Ok(lvl2);
184        }
185        self.inner.load_collection(digest)?;
186        self.inner.get_collection_level2(digest)
187    }
188
189    /// Lazy-loading compare.
190    pub fn compare(&mut self, digest_a: &str, digest_b: &str) -> Result<crate::digest::SeqColComparison> {
191        if !self.inner.is_collection_loaded(digest_a) {
192            self.inner.load_collection(digest_a)?;
193        }
194        if !self.inner.is_collection_loaded(digest_b) {
195            self.inner.load_collection(digest_b)?;
196        }
197        self.inner.compare(digest_a, digest_b)
198    }
199
200    /// List sequence metadata, loading the deferred sequence index if needed.
201    ///
202    /// This only populates metadata-only records; sequence bodies remain lazy.
203    pub fn list_sequences(&mut self) -> Result<Vec<crate::digest::SequenceMetadata>> {
204        self.inner.ensure_sequence_index_loaded()?;
205        Ok(self.inner.list_sequences())
206    }
207
208    /// Retrieve one sequence, loading only its body when necessary.
209    ///
210    /// The readonly lookup accepts MD5 aliases, but the disk loader needs the
211    /// canonical SHA-512/24u key, so resolve before loading.
212    pub fn get_sequence<K: AsRef<[u8]>>(&mut self, digest: K) -> Result<SequenceRecord> {
213        self.inner.ensure_sequence_index_loaded()?;
214        let digest = String::from_utf8_lossy(digest.as_ref());
215        let canonical_digest = self
216            .inner
217            .get_sequence(strip_sq_prefix(&digest))
218            .map(|record| record.metadata().sha512t24u.clone())?;
219        if !self.inner.is_sequence_loaded(&canonical_digest) {
220            self.inner.load_sequence(&canonical_digest)?;
221        }
222        self.inner.get_sequence(&canonical_digest)
223    }
224
225    /// Retrieve a named sequence from a collection, loading only that
226    /// collection and sequence body when necessary.
227    pub fn get_sequence_by_name<K: AsRef<[u8]>>(
228        &mut self,
229        collection_digest: K,
230        sequence_name: &str,
231    ) -> Result<SequenceRecord> {
232        let collection_digest = String::from_utf8_lossy(collection_digest.as_ref());
233        if !self.inner.is_collection_loaded(collection_digest.as_bytes()) {
234            self.inner.load_collection(collection_digest.as_ref())?;
235        }
236        let canonical_digest = self
237            .inner
238            .get_sequence_by_name(collection_digest.as_bytes(), sequence_name)
239            .map(|record| record.metadata().sha512t24u.clone())?;
240        if !self.inner.is_sequence_loaded(&canonical_digest) {
241            self.inner.load_sequence(&canonical_digest)?;
242        }
243        self.inner
244            .get_sequence_by_name(collection_digest.as_bytes(), sequence_name)
245    }
246
247    /// Lazily load two collection records and match their local names by content.
248    pub fn match_sequence_names(
249        &mut self,
250        digest_a: &str,
251        digest_b: &str,
252    ) -> Result<crate::digest::CollectionNameMatch> {
253        if !self.inner.is_collection_loaded(digest_a) {
254            self.inner.load_collection(digest_a)?;
255        }
256        if !self.inner.is_collection_loaded(digest_b) {
257            self.inner.load_collection(digest_b)?;
258        }
259        self.inner.match_sequence_names(digest_a, digest_b)
260    }
261
262    /// Lazy-loading get_attribute.
263    pub fn get_attribute(
264        &mut self,
265        attr_name: &str,
266        attr_digest: &str,
267    ) -> Result<Option<serde_json::Value>> {
268        let collections = self.inner.find_collections_by_attribute(attr_name, attr_digest)?;
269        if collections.is_empty() {
270            return Ok(None);
271        }
272        if !self.inner.is_collection_loaded(&collections[0]) {
273            self.inner.load_collection(&collections[0])?;
274        }
275        self.inner.get_attribute(attr_name, attr_digest)
276    }
277
278    /// Verify sequences against their stored digests. `digests: None` checks
279    /// every sequence in the store.
280    ///
281    /// See [`ReadonlyRefgetStore::verify_sequences`] for what this actually
282    /// checks and how parallelism is controlled by `opts.jobs`.
283    pub fn verify_sequences(
284        &mut self,
285        digests: Option<&[String]>,
286        opts: &VerifyOptions,
287    ) -> Result<VerifyReport> {
288        self.inner.ensure_sequence_index_loaded()?;
289        self.inner.verify_sequences(digests, opts)
290    }
291
292    /// Verify only the sequences belonging to one collection.
293    ///
294    /// Loads the collection's metadata (not sequence bytes) via the usual
295    /// lazy-load path, then verifies each of its (deduped) sequence digests.
296    pub fn verify_collection(
297        &mut self,
298        collection_digest: &str,
299        opts: &VerifyOptions,
300    ) -> Result<VerifyReport> {
301        self.inner.ensure_sequence_index_loaded()?;
302        self.inner.ensure_collection_loaded(collection_digest)?;
303        let mut digests: Vec<String> = self
304            .inner
305            .collection_members(collection_digest)?
306            .map(|m| m.seq().sha512t24u().to_string())
307            .collect();
308        digests.sort();
309        digests.dedup();
310        self.inner.verify_sequences(Some(&digests), opts)
311    }
312
313    /// Export sequences to FASTA (or stdout with `"-"`), loading only the
314    /// metadata the export needs: the sequence index, the selected collections
315    /// (every collection for `All` when the label uses a collection field),
316    /// and, for a remote store, the alias namespaces the label uses.
317    ///
318    /// Exports stream one sequence at a time and leave the store's loaded
319    /// state unchanged. See [`ReadonlyRefgetStore::export_fasta`].
320    #[cfg(feature = "filesystem")]
321    pub fn export_fasta<P: AsRef<Path>>(
322        &mut self,
323        selection: &ExportSelection,
324        output_path: P,
325        opts: &ExportOptions,
326    ) -> Result<ExportSummary> {
327        self.prepare_export(selection, &opts.label)?;
328        self.inner.export_fasta(selection, output_path, opts)
329    }
330
331    /// Export BED regions to FASTA, loading the collection and any alias
332    /// namespaces the label uses first.
333    #[cfg(feature = "filesystem")]
334    pub fn export_fasta_from_regions(
335        &mut self,
336        collection_digest: &str,
337        bed_file_path: &str,
338        output_file_path: &str,
339        label: &LabelTemplate,
340    ) -> Result<ExportSummary> {
341        let selection = ExportSelection::Collections {
342            digests: vec![collection_digest.to_string()],
343            names: None,
344        };
345        self.prepare_export(&selection, label)?;
346        self.inner
347            .export_fasta_from_regions(collection_digest, bed_file_path, output_file_path, label)
348    }
349
350    #[cfg(feature = "filesystem")]
351    fn prepare_export(&mut self, selection: &ExportSelection, label: &LabelTemplate) -> Result<()> {
352        self.inner.ensure_sequence_index_loaded()?;
353        match selection {
354            ExportSelection::Collections { digests, .. } => {
355                for d in digests {
356                    self.inner.ensure_collection_loaded(d)?;
357                }
358            }
359            ExportSelection::All if label.needs_collection() => self.inner.load_all_collections()?,
360            _ => {}
361        }
362
363        // A remote store lists alias namespaces it has not downloaded yet.
364        if self.inner.remote_source.is_some() {
365            let loaded_seq = self.inner.list_sequence_alias_namespaces();
366            let loaded_col = self.inner.list_collection_alias_namespaces();
367            let mut to_pull: Vec<String> = Vec::new();
368            for ns in label.namespaces(AliasKind::Sequence) {
369                if !loaded_seq.contains(&ns)
370                    && self.inner.available_sequence_alias_namespaces.contains(&ns)
371                {
372                    to_pull.push(ns);
373                }
374            }
375            for ns in label.namespaces(AliasKind::Collection) {
376                if !loaded_col.contains(&ns)
377                    && self.inner.available_collection_alias_namespaces.contains(&ns)
378                    && !to_pull.contains(&ns)
379                {
380                    to_pull.push(ns);
381                }
382            }
383            for ns in to_pull {
384                self.pull_aliases(Some(&ns), SyncStrategy::KeepOurs)?;
385            }
386        }
387        Ok(())
388    }
389
390    // =====================================================================
391    // Write/mutation methods (delegate to inner)
392    // =====================================================================
393
394    /// Set whether to suppress progress output.
395    pub fn set_quiet(&mut self, quiet: bool) {
396        self.inner.set_quiet(quiet);
397    }
398
399    /// Change the storage mode.
400    ///
401    /// Switching to Encoded fails, leaving the store unchanged, if a sequence
402    /// cannot be encoded with its stored alphabet. The store must then be
403    /// re-imported.
404    pub fn set_encoding_mode(&mut self, new_mode: StorageMode) -> Result<()> {
405        self.inner.set_encoding_mode(new_mode)
406    }
407
408    /// Set the per-pack size cap in bytes (packed layout).
409    pub fn set_pack_cap_bytes(&mut self, cap: u64) {
410        self.inner.set_pack_cap_bytes(cap);
411    }
412
413    /// Turn the pack block cache on with room for `mb` megabytes, or off with
414    /// 0 (the default). See [`ReadonlyRefgetStore::set_pack_cache_mb`].
415    pub fn set_pack_cache_mb(&mut self, mb: usize) {
416        self.inner.set_pack_cache_mb(mb);
417    }
418
419    /// Reclaim dead bytes in a packed store by rewriting live spans into fresh
420    /// sealed packs. Byte-identical retrieval before and after.
421    pub fn compact(&mut self) -> Result<super::CompactReport> {
422        self.inner.compact()
423    }
424
425    /// [`Self::compact`] with options. See [`super::CompactOptions`].
426    pub fn compact_with(&mut self, opts: super::CompactOptions) -> Result<super::CompactReport> {
427        self.inner.compact_with(opts)
428    }
429
430    /// Enable 2-bit encoding for space efficiency.
431    pub fn enable_encoding(&mut self) -> Result<()> {
432        self.inner.enable_encoding()
433    }
434
435    /// Disable encoding, use raw byte storage.
436    pub fn disable_encoding(&mut self) {
437        self.inner.disable_encoding();
438    }
439
440    /// Enable disk persistence for this store.
441    pub fn enable_persistence<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
442        self.inner.enable_persistence(path)
443    }
444
445    /// Disable disk persistence for this store.
446    pub fn disable_persistence(&mut self) {
447        self.inner.disable_persistence();
448    }
449
450    /// Digest and insert raw sequence bytes without a collection association.
451    ///
452    /// Unlike `add_sequence_record`, this method can reliably encode a
453    /// single-base sequence because its input is known to be raw bytes.
454    /// Returns the sequence's sha512t24u digest.
455    pub fn ingest_sequence(&mut self, name: &str, bytes: &[u8]) -> Result<String> {
456        self.inner.ingest_sequence(name, bytes)
457    }
458
459    /// Add a collection and all sequences in it to the store.
460    pub fn add_sequence_collection(&mut self, collection: SequenceCollection) -> Result<()> {
461        self.inner.add_sequence_collection(collection)
462    }
463
464    /// Add a collection, overwriting existing data.
465    pub fn add_sequence_collection_force(&mut self, collection: SequenceCollection) -> Result<()> {
466        self.inner.add_sequence_collection_force(collection)
467    }
468
469    /// Add a sequence collection from a FASTA file.
470    #[cfg(feature = "filesystem")]
471    pub fn add_sequence_collection_from_fasta<P: AsRef<Path>>(
472        &mut self,
473        file_path: P,
474        opts: FastaImportOptions<'_>,
475    ) -> Result<(SequenceCollectionMetadata, bool)> {
476        self.inner.add_sequence_collection_from_fasta(file_path, opts)
477    }
478
479    /// Add sequence collections from multiple FASTA files, decoding up to
480    /// `opts.file_jobs` files concurrently. Inserts in fixed input order so the
481    /// resulting store is byte-identical to a serial build.
482    ///
483    /// Returns an [`ImportReport`] with per-file results and per-run ingest
484    /// counters.
485    #[cfg(feature = "filesystem")]
486    pub fn add_sequence_collections_from_fastas(
487        &mut self,
488        files: &[std::path::PathBuf],
489        opts: FastaImportOptions<'_>,
490    ) -> Result<ImportReport> {
491        self.inner.add_sequence_collections_from_fastas(files, opts)
492    }
493
494    /// Add a SequenceRecord directly to the store.
495    pub fn add_sequence_record(&mut self, sr: SequenceRecord, force: bool) -> Result<()> {
496        self.inner.add_sequence_record(sr, force)
497    }
498
499    /// Remove a collection from the store.
500    pub fn remove_collection(&mut self, digest: &str, remove_orphan_sequences: bool) -> Result<bool> {
501        self.inner.remove_collection(digest, remove_orphan_sequences)
502    }
503
504    /// Dry-run of the orphan cleanup in [`Self::remove_collection`].
505    pub fn plan_orphan_removal(&self, digest: &str) -> Result<Vec<String>> {
506        self.inner.plan_orphan_removal(digest)
507    }
508
509    // --- Write locking (delegates; `Deref` only yields `&`) ---
510
511    /// Hold the store's exclusive writer lock across several mutations.
512    pub fn lock_for_batch(&mut self, operation: &str) -> Result<()> {
513        self.inner.lock_for_batch(operation)
514    }
515
516    /// Release a lock taken by [`Self::lock_for_batch`].
517    pub fn release_batch_lock(&mut self) {
518        self.inner.release_batch_lock();
519    }
520
521    /// Override the timeout/staleness settings used when acquiring the write lock.
522    pub fn set_lock_options(&mut self, options: super::LockOptions) {
523        self.inner.set_lock_options(options);
524    }
525
526    /// Allow re-pointing an existing alias to a different digest.
527    pub fn set_force_alias(&mut self, force: bool) {
528        self.inner.set_force_alias(force);
529    }
530
531    /// Import a collection (with sequences, aliases, FHR) from another store.
532    /// The source must already have the collection loaded.
533    pub fn import_collection_from_readonly(&mut self, source: &ReadonlyRefgetStore, digest: &str) -> Result<()> {
534        self.inner.import_collection(source, digest)
535    }
536
537    /// Import a collection from another RefgetStore, lazy-loading the source if needed.
538    pub fn import_collection(&mut self, source: &mut RefgetStore, digest: &str) -> Result<()> {
539        if !source.inner.is_collection_loaded(digest) {
540            source.inner.load_collection(digest)?;
541        }
542        self.inner.import_collection(&source.inner, digest)
543    }
544
545    /// Clear in-memory sequence data, preserving metadata.
546    pub fn clear(&mut self) {
547        self.inner.clear();
548    }
549
550    /// Check whether a sequence's bytes are loaded.
551    pub fn is_sequence_loaded<K: AsRef<[u8]>>(&self, seq_digest: K) -> bool {
552        self.inner.is_sequence_loaded(seq_digest)
553    }
554
555    // --- Seqcol config methods ---
556
557    /// Enable computation of ancillary digests.
558    pub fn enable_ancillary_digests(&mut self) {
559        self.inner.enable_ancillary_digests();
560    }
561
562    /// Disable computation of ancillary digests.
563    pub fn disable_ancillary_digests(&mut self) {
564        self.inner.disable_ancillary_digests();
565    }
566
567    /// Enable indexed attribute lookup.
568    pub fn enable_attribute_index(&mut self) {
569        self.inner.enable_attribute_index();
570    }
571
572    /// Disable indexed attribute lookup.
573    pub fn disable_attribute_index(&mut self) {
574        self.inner.disable_attribute_index();
575    }
576
577    // --- Write methods ---
578
579    /// Write the store using its configured paths.
580    pub fn write(&self) -> Result<()> {
581        self.inner.write()
582    }
583
584    /// Write the store to a directory.
585    pub fn write_store_to_dir<P: AsRef<Path>>(
586        &self,
587        root_path: P,
588        seqdata_path_template: Option<&str>,
589    ) -> Result<()> {
590        self.inner.write_store_to_dir(root_path, seqdata_path_template)
591    }
592
593    /// Write all sequence metadata to an RGSI file.
594    pub fn write_sequences_rgsi<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
595        self.inner.write_sequences_rgsi(file_path)
596    }
597}