gtars-refget 0.12.0

Rust implementation of the refget standard for accessing reference sequences
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! RefgetStore wrapper struct with lazy-loading read methods.

use super::*;
use super::readonly::ReadonlyRefgetStore;

use std::fmt::{Display, Formatter};
use std::path::Path;

use anyhow::Result;
use std::fs::create_dir_all;

use crate::digest::{SequenceCollection, SequenceRecord, strip_sq_prefix};
// Only the filesystem FASTA-import wrappers use this return type.
#[cfg(feature = "filesystem")]
use crate::digest::SequenceCollectionMetadata;

/// User-facing store with lazy-loading read methods.
///
/// Wraps `ReadonlyRefgetStore` and provides `&mut self` read methods that
/// automatically load data on first access. Use `into_readonly()` to convert
/// to an immutable store suitable for `Arc<ReadonlyRefgetStore>` in servers.
#[derive(Debug)]
pub struct RefgetStore {
    pub(crate) inner: ReadonlyRefgetStore,
}

impl std::ops::Deref for RefgetStore {
    type Target = ReadonlyRefgetStore;
    fn deref(&self) -> &ReadonlyRefgetStore {
        &self.inner
    }
}

impl Display for RefgetStore {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

impl RefgetStore {
    // =====================================================================
    // Constructors
    // =====================================================================

    /// Check whether a valid RefgetStore exists at the given path.
    pub fn store_exists<P: AsRef<Path>>(path: P) -> bool {
        ReadonlyRefgetStore::store_exists(path)
    }

    /// Create a disk-backed RefgetStore.
    pub fn on_disk<P: AsRef<Path>>(cache_path: P) -> Result<Self> {
        Self::create_or_open(cache_path.as_ref(), Layout::Standalone)
    }

    /// Create a disk-backed RefgetStore with the PACKED sequence layout.
    ///
    /// Sequences are concatenated into sealed, size-capped pack files under
    /// `packs/`, resolved via the `sequences.pack.idx` sidecar, instead of one
    /// `.seq` file per digest. Mirrors [`Self::on_disk`] but sets
    /// `layout = Packed` and creates `packs/`.
    ///
    /// Opening an EXISTING store: the layout always comes from its manifest.
    /// Calling `on_disk_packed` on an existing STANDALONE store is an error,
    /// since there is no in-place conversion (export a standalone image
    /// instead). Calling it on an existing packed store just opens it.
    pub fn on_disk_packed<P: AsRef<Path>>(cache_path: P) -> Result<Self> {
        let cache_path = cache_path.as_ref();
        let store = Self::create_or_open(cache_path, Layout::Packed)?;
        if store.inner.layout != Layout::Packed {
            return Err(anyhow::anyhow!(
                "store at {} already exists with a standalone layout; \
                 on_disk_packed cannot convert it in place. Create a fresh \
                 packed store and export/re-import, or open it with on_disk.",
                cache_path.display()
            ));
        }
        Ok(store)
    }

    /// Open the store at `cache_path`, or create an empty Encoded store with
    /// `layout` there if it has no `rgstore.json`.
    fn create_or_open(cache_path: &Path, layout: Layout) -> Result<Self> {
        if cache_path.join("rgstore.json").exists() {
            return Self::open_local(cache_path);
        }
        create_dir_all(cache_path)?;
        let mut inner = ReadonlyRefgetStore::new(StorageMode::Encoded);
        inner.local_path = Some(cache_path.to_path_buf());
        inner.seqdata_path_template = Some(DEFAULT_SEQDATA_PATH_TEMPLATE.to_string());
        inner.persist_to_disk = true;
        inner.layout = layout;
        create_dir_all(cache_path.join("sequences"))?;
        create_dir_all(cache_path.join("collections"))?;
        create_dir_all(cache_path.join("fhr"))?;
        if layout == Layout::Packed {
            create_dir_all(cache_path.join("packs"))?;
        }
        Ok(Self { inner })
    }

    /// Create an in-memory RefgetStore.
    pub fn in_memory() -> Self {
        Self {
            inner: ReadonlyRefgetStore::new(StorageMode::Encoded),
        }
    }

    /// Open a local RefgetStore from a directory.
    pub fn open_local<P: AsRef<Path>>(path: P) -> Result<Self> {
        Ok(Self {
            inner: ReadonlyRefgetStore::open_local(path)?,
        })
    }

    /// Open a remote RefgetStore with local caching.
    pub fn open_remote<P: AsRef<Path>, S: AsRef<str>>(
        cache_path: P,
        remote_url: S,
    ) -> Result<Self> {
        Ok(Self {
            inner: ReadonlyRefgetStore::open_remote(cache_path, remote_url)?,
        })
    }

    /// Convert to a ReadonlyRefgetStore for concurrent read access.
    pub fn into_readonly(self) -> ReadonlyRefgetStore {
        self.inner
    }

    // =====================================================================
    // Preload methods (delegate to inner)
    // =====================================================================

    /// Load the sequence index if not already loaded.
    /// Servers should call this during startup to preload the index.
    pub fn load_sequence_index(&mut self) -> Result<()> {
        self.inner.load_sequence_index()
    }

    /// Preload all collections (delegates to inner).
    pub fn load_all_collections(&mut self) -> Result<()> {
        self.inner.load_all_collections()
    }

    /// Preload all sequences (delegates to inner).
    pub fn load_all_sequences(&mut self) -> Result<()> {
        self.inner.ensure_sequence_index_loaded()?;
        self.inner.load_all_sequences()
    }

    /// Load a single collection by digest.
    pub fn load_collection(&mut self, digest: &str) -> Result<()> {
        self.inner.load_collection(digest)
    }

    /// Load a single sequence by digest. Accepts "SQ."-prefixed and MD5
    /// digests; the disk loader needs the canonical SHA-512/24u key.
    pub fn load_sequence(&mut self, digest: &str) -> Result<()> {
        self.inner.ensure_sequence_index_loaded()?;
        let canonical_digest = self
            .inner
            .get_sequence(strip_sq_prefix(digest))
            .map(|record| record.metadata().sha512t24u.clone())?;
        self.inner.load_sequence(&canonical_digest)
    }

    // =====================================================================
    // Lazy-loading read methods
    // =====================================================================

    /// Lazy-loading get_collection. Loads on first access.
    pub fn get_collection(&mut self, digest: &str) -> Result<SequenceCollection> {
        if let Ok(coll) = self.inner.get_collection(digest) {
            return Ok(coll);
        }
        self.inner.load_collection(digest)?;
        self.inner.get_collection(digest)
    }

    /// Lazy-loading get_collection_level2.
    pub fn get_collection_level2(&mut self, digest: &str) -> Result<crate::digest::CollectionLevel2> {
        if let Ok(lvl2) = self.inner.get_collection_level2(digest) {
            return Ok(lvl2);
        }
        self.inner.load_collection(digest)?;
        self.inner.get_collection_level2(digest)
    }

    /// Lazy-loading compare.
    pub fn compare(&mut self, digest_a: &str, digest_b: &str) -> Result<crate::digest::SeqColComparison> {
        if !self.inner.is_collection_loaded(digest_a) {
            self.inner.load_collection(digest_a)?;
        }
        if !self.inner.is_collection_loaded(digest_b) {
            self.inner.load_collection(digest_b)?;
        }
        self.inner.compare(digest_a, digest_b)
    }

    /// List sequence metadata, loading the deferred sequence index if needed.
    ///
    /// This only populates metadata-only records; sequence bodies remain lazy.
    pub fn list_sequences(&mut self) -> Result<Vec<crate::digest::SequenceMetadata>> {
        self.inner.ensure_sequence_index_loaded()?;
        Ok(self.inner.list_sequences())
    }

    /// Retrieve one sequence, loading only its body when necessary.
    ///
    /// The readonly lookup accepts MD5 aliases, but the disk loader needs the
    /// canonical SHA-512/24u key, so resolve before loading.
    pub fn get_sequence<K: AsRef<[u8]>>(&mut self, digest: K) -> Result<SequenceRecord> {
        self.inner.ensure_sequence_index_loaded()?;
        let digest = String::from_utf8_lossy(digest.as_ref());
        let canonical_digest = self
            .inner
            .get_sequence(strip_sq_prefix(&digest))
            .map(|record| record.metadata().sha512t24u.clone())?;
        if !self.inner.is_sequence_loaded(&canonical_digest) {
            self.inner.load_sequence(&canonical_digest)?;
        }
        self.inner.get_sequence(&canonical_digest)
    }

    /// Retrieve a named sequence from a collection, loading only that
    /// collection and sequence body when necessary.
    pub fn get_sequence_by_name<K: AsRef<[u8]>>(
        &mut self,
        collection_digest: K,
        sequence_name: &str,
    ) -> Result<SequenceRecord> {
        let collection_digest = String::from_utf8_lossy(collection_digest.as_ref());
        if !self.inner.is_collection_loaded(collection_digest.as_bytes()) {
            self.inner.load_collection(collection_digest.as_ref())?;
        }
        let canonical_digest = self
            .inner
            .get_sequence_by_name(collection_digest.as_bytes(), sequence_name)
            .map(|record| record.metadata().sha512t24u.clone())?;
        if !self.inner.is_sequence_loaded(&canonical_digest) {
            self.inner.load_sequence(&canonical_digest)?;
        }
        self.inner
            .get_sequence_by_name(collection_digest.as_bytes(), sequence_name)
    }

    /// Lazily load two collection records and match their local names by content.
    pub fn match_sequence_names(
        &mut self,
        digest_a: &str,
        digest_b: &str,
    ) -> Result<crate::digest::CollectionNameMatch> {
        if !self.inner.is_collection_loaded(digest_a) {
            self.inner.load_collection(digest_a)?;
        }
        if !self.inner.is_collection_loaded(digest_b) {
            self.inner.load_collection(digest_b)?;
        }
        self.inner.match_sequence_names(digest_a, digest_b)
    }

    /// Lazy-loading get_attribute.
    pub fn get_attribute(
        &mut self,
        attr_name: &str,
        attr_digest: &str,
    ) -> Result<Option<serde_json::Value>> {
        let collections = self.inner.find_collections_by_attribute(attr_name, attr_digest)?;
        if collections.is_empty() {
            return Ok(None);
        }
        if !self.inner.is_collection_loaded(&collections[0]) {
            self.inner.load_collection(&collections[0])?;
        }
        self.inner.get_attribute(attr_name, attr_digest)
    }

    /// Verify sequences against their stored digests. `digests: None` checks
    /// every sequence in the store.
    ///
    /// See [`ReadonlyRefgetStore::verify_sequences`] for what this actually
    /// checks and how parallelism is controlled by `opts.jobs`.
    pub fn verify_sequences(
        &mut self,
        digests: Option<&[String]>,
        opts: &VerifyOptions,
    ) -> Result<VerifyReport> {
        self.inner.ensure_sequence_index_loaded()?;
        self.inner.verify_sequences(digests, opts)
    }

    /// Verify only the sequences belonging to one collection.
    ///
    /// Loads the collection's metadata (not sequence bytes) via the usual
    /// lazy-load path, then verifies each of its (deduped) sequence digests.
    pub fn verify_collection(
        &mut self,
        collection_digest: &str,
        opts: &VerifyOptions,
    ) -> Result<VerifyReport> {
        self.inner.ensure_sequence_index_loaded()?;
        self.inner.ensure_collection_loaded(collection_digest)?;
        let mut digests: Vec<String> = self
            .inner
            .collection_members(collection_digest)?
            .map(|m| m.seq().sha512t24u().to_string())
            .collect();
        digests.sort();
        digests.dedup();
        self.inner.verify_sequences(Some(&digests), opts)
    }

    /// Export sequences to FASTA (or stdout with `"-"`), loading only the
    /// metadata the export needs: the sequence index, the selected collections
    /// (every collection for `All` when the label uses a collection field),
    /// and, for a remote store, the alias namespaces the label uses.
    ///
    /// Exports stream one sequence at a time and leave the store's loaded
    /// state unchanged. See [`ReadonlyRefgetStore::export_fasta`].
    #[cfg(feature = "filesystem")]
    pub fn export_fasta<P: AsRef<Path>>(
        &mut self,
        selection: &ExportSelection,
        output_path: P,
        opts: &ExportOptions,
    ) -> Result<ExportSummary> {
        self.prepare_export(selection, &opts.label)?;
        self.inner.export_fasta(selection, output_path, opts)
    }

    /// Export BED regions to FASTA, loading the collection and any alias
    /// namespaces the label uses first.
    #[cfg(feature = "filesystem")]
    pub fn export_fasta_from_regions(
        &mut self,
        collection_digest: &str,
        bed_file_path: &str,
        output_file_path: &str,
        label: &LabelTemplate,
    ) -> Result<ExportSummary> {
        let selection = ExportSelection::Collections {
            digests: vec![collection_digest.to_string()],
            names: None,
        };
        self.prepare_export(&selection, label)?;
        self.inner
            .export_fasta_from_regions(collection_digest, bed_file_path, output_file_path, label)
    }

    #[cfg(feature = "filesystem")]
    fn prepare_export(&mut self, selection: &ExportSelection, label: &LabelTemplate) -> Result<()> {
        self.inner.ensure_sequence_index_loaded()?;
        match selection {
            ExportSelection::Collections { digests, .. } => {
                for d in digests {
                    self.inner.ensure_collection_loaded(d)?;
                }
            }
            ExportSelection::All if label.needs_collection() => self.inner.load_all_collections()?,
            _ => {}
        }

        // A remote store lists alias namespaces it has not downloaded yet.
        if self.inner.remote_source.is_some() {
            let loaded_seq = self.inner.list_sequence_alias_namespaces();
            let loaded_col = self.inner.list_collection_alias_namespaces();
            let mut to_pull: Vec<String> = Vec::new();
            for ns in label.namespaces(AliasKind::Sequence) {
                if !loaded_seq.contains(&ns)
                    && self.inner.available_sequence_alias_namespaces.contains(&ns)
                {
                    to_pull.push(ns);
                }
            }
            for ns in label.namespaces(AliasKind::Collection) {
                if !loaded_col.contains(&ns)
                    && self.inner.available_collection_alias_namespaces.contains(&ns)
                    && !to_pull.contains(&ns)
                {
                    to_pull.push(ns);
                }
            }
            for ns in to_pull {
                self.pull_aliases(Some(&ns), SyncStrategy::KeepOurs)?;
            }
        }
        Ok(())
    }

    // =====================================================================
    // Write/mutation methods (delegate to inner)
    // =====================================================================

    /// Set whether to suppress progress output.
    pub fn set_quiet(&mut self, quiet: bool) {
        self.inner.set_quiet(quiet);
    }

    /// Change the storage mode.
    ///
    /// Switching to Encoded fails, leaving the store unchanged, if a sequence
    /// cannot be encoded with its stored alphabet. The store must then be
    /// re-imported.
    pub fn set_encoding_mode(&mut self, new_mode: StorageMode) -> Result<()> {
        self.inner.set_encoding_mode(new_mode)
    }

    /// Set the per-pack size cap in bytes (packed layout).
    pub fn set_pack_cap_bytes(&mut self, cap: u64) {
        self.inner.set_pack_cap_bytes(cap);
    }

    /// Turn the pack block cache on with room for `mb` megabytes, or off with
    /// 0 (the default). See [`ReadonlyRefgetStore::set_pack_cache_mb`].
    pub fn set_pack_cache_mb(&mut self, mb: usize) {
        self.inner.set_pack_cache_mb(mb);
    }

    /// Reclaim dead bytes in a packed store by rewriting live spans into fresh
    /// sealed packs. Byte-identical retrieval before and after.
    pub fn compact(&mut self) -> Result<super::CompactReport> {
        self.inner.compact()
    }

    /// [`Self::compact`] with options. See [`super::CompactOptions`].
    pub fn compact_with(&mut self, opts: super::CompactOptions) -> Result<super::CompactReport> {
        self.inner.compact_with(opts)
    }

    /// Enable 2-bit encoding for space efficiency.
    pub fn enable_encoding(&mut self) -> Result<()> {
        self.inner.enable_encoding()
    }

    /// Disable encoding, use raw byte storage.
    pub fn disable_encoding(&mut self) {
        self.inner.disable_encoding();
    }

    /// Enable disk persistence for this store.
    pub fn enable_persistence<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        self.inner.enable_persistence(path)
    }

    /// Disable disk persistence for this store.
    pub fn disable_persistence(&mut self) {
        self.inner.disable_persistence();
    }

    /// Digest and insert raw sequence bytes without a collection association.
    ///
    /// Unlike `add_sequence_record`, this method can reliably encode a
    /// single-base sequence because its input is known to be raw bytes.
    /// Returns the sequence's sha512t24u digest.
    pub fn ingest_sequence(&mut self, name: &str, bytes: &[u8]) -> Result<String> {
        self.inner.ingest_sequence(name, bytes)
    }

    /// Add a collection and all sequences in it to the store.
    pub fn add_sequence_collection(&mut self, collection: SequenceCollection) -> Result<()> {
        self.inner.add_sequence_collection(collection)
    }

    /// Add a collection, overwriting existing data.
    pub fn add_sequence_collection_force(&mut self, collection: SequenceCollection) -> Result<()> {
        self.inner.add_sequence_collection_force(collection)
    }

    /// Add a sequence collection from a FASTA file.
    #[cfg(feature = "filesystem")]
    pub fn add_sequence_collection_from_fasta<P: AsRef<Path>>(
        &mut self,
        file_path: P,
        opts: FastaImportOptions<'_>,
    ) -> Result<(SequenceCollectionMetadata, bool)> {
        self.inner.add_sequence_collection_from_fasta(file_path, opts)
    }

    /// Add sequence collections from multiple FASTA files, decoding up to
    /// `opts.file_jobs` files concurrently. Inserts in fixed input order so the
    /// resulting store is byte-identical to a serial build.
    ///
    /// Returns an [`ImportReport`] with per-file results and per-run ingest
    /// counters.
    #[cfg(feature = "filesystem")]
    pub fn add_sequence_collections_from_fastas(
        &mut self,
        files: &[std::path::PathBuf],
        opts: FastaImportOptions<'_>,
    ) -> Result<ImportReport> {
        self.inner.add_sequence_collections_from_fastas(files, opts)
    }

    /// Add a SequenceRecord directly to the store.
    pub fn add_sequence_record(&mut self, sr: SequenceRecord, force: bool) -> Result<()> {
        self.inner.add_sequence_record(sr, force)
    }

    /// Remove a collection from the store.
    pub fn remove_collection(&mut self, digest: &str, remove_orphan_sequences: bool) -> Result<bool> {
        self.inner.remove_collection(digest, remove_orphan_sequences)
    }

    /// Dry-run of the orphan cleanup in [`Self::remove_collection`].
    pub fn plan_orphan_removal(&self, digest: &str) -> Result<Vec<String>> {
        self.inner.plan_orphan_removal(digest)
    }

    // --- Write locking (delegates; `Deref` only yields `&`) ---

    /// Hold the store's exclusive writer lock across several mutations.
    pub fn lock_for_batch(&mut self, operation: &str) -> Result<()> {
        self.inner.lock_for_batch(operation)
    }

    /// Release a lock taken by [`Self::lock_for_batch`].
    pub fn release_batch_lock(&mut self) {
        self.inner.release_batch_lock();
    }

    /// Override the timeout/staleness settings used when acquiring the write lock.
    pub fn set_lock_options(&mut self, options: super::LockOptions) {
        self.inner.set_lock_options(options);
    }

    /// Allow re-pointing an existing alias to a different digest.
    pub fn set_force_alias(&mut self, force: bool) {
        self.inner.set_force_alias(force);
    }

    /// Import a collection (with sequences, aliases, FHR) from another store.
    /// The source must already have the collection loaded.
    pub fn import_collection_from_readonly(&mut self, source: &ReadonlyRefgetStore, digest: &str) -> Result<()> {
        self.inner.import_collection(source, digest)
    }

    /// Import a collection from another RefgetStore, lazy-loading the source if needed.
    pub fn import_collection(&mut self, source: &mut RefgetStore, digest: &str) -> Result<()> {
        if !source.inner.is_collection_loaded(digest) {
            source.inner.load_collection(digest)?;
        }
        self.inner.import_collection(&source.inner, digest)
    }

    /// Clear in-memory sequence data, preserving metadata.
    pub fn clear(&mut self) {
        self.inner.clear();
    }

    /// Check whether a sequence's bytes are loaded.
    pub fn is_sequence_loaded<K: AsRef<[u8]>>(&self, seq_digest: K) -> bool {
        self.inner.is_sequence_loaded(seq_digest)
    }

    // --- Seqcol config methods ---

    /// Enable computation of ancillary digests.
    pub fn enable_ancillary_digests(&mut self) {
        self.inner.enable_ancillary_digests();
    }

    /// Disable computation of ancillary digests.
    pub fn disable_ancillary_digests(&mut self) {
        self.inner.disable_ancillary_digests();
    }

    /// Enable indexed attribute lookup.
    pub fn enable_attribute_index(&mut self) {
        self.inner.enable_attribute_index();
    }

    /// Disable indexed attribute lookup.
    pub fn disable_attribute_index(&mut self) {
        self.inner.disable_attribute_index();
    }

    // --- Write methods ---

    /// Write the store using its configured paths.
    pub fn write(&self) -> Result<()> {
        self.inner.write()
    }

    /// Write the store to a directory.
    pub fn write_store_to_dir<P: AsRef<Path>>(
        &self,
        root_path: P,
        seqdata_path_template: Option<&str>,
    ) -> Result<()> {
        self.inner.write_store_to_dir(root_path, seqdata_path_template)
    }

    /// Write all sequence metadata to an RGSI file.
    pub fn write_sequences_rgsi<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
        self.inner.write_sequences_rgsi(file_path)
    }
}