1use super::*;
45use super::readonly::{PendingChanges, ReadonlyRefgetStore};
46use super::alias::AliasKind;
47use super::atomic::{atomic_write, atomic_write_bytes};
48use super::fhr_metadata;
49use super::lock::StoreLock;
50
51use std::collections::{BTreeMap, HashMap, HashSet};
52use std::ffi::OsStr;
53
54use std::fs::{self, File, create_dir_all};
55use std::io::BufRead;
56use std::path::Path;
57
58use anyhow::{anyhow, Context, Result};
59
60use super::catalog::{CollRow, NewMember};
61use sha2::{Sha256, Digest};
62
63use crate::collection::{
64 RgsiHeader,
65 SequenceMetadataExt,
66 read_rgsi_file,
67};
68use crate::digest::{
69 SequenceCollectionMetadata, SequenceMetadata,
70 parse_rgci_line, parse_rgsi_fields, parse_rgsi_line,
71};
72use crate::hashkeyable::{HashKeyable, key_to_digest_string};
73
74use chrono::Utc;
75
76const RGSI_HEADER: &str = "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription";
78
79const RGCI_HEADER: &str = "#digest\tn_sequences\tnames_digest\tsequences_digest\tlengths_digest\tname_length_pairs_digest\tsorted_name_length_pairs_digest\tsorted_sequences_digest";
81
82fn remove_cached_artifact(path: &Path) -> Result<()> {
83 match fs::symlink_metadata(path) {
84 Ok(metadata) if metadata.is_dir() => fs::remove_dir_all(path)
85 .with_context(|| format!("Failed to remove cached directory {}", path.display())),
86 Ok(_) => fs::remove_file(path)
87 .with_context(|| format!("Failed to remove cached file {}", path.display())),
88 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
89 Err(error) => Err(error)
90 .with_context(|| format!("Failed to inspect cached artifact {}", path.display())),
91 }
92}
93
94fn remove_cached_indexes<'a, I>(cache_path: &Path, paths: I) -> Result<()>
95where
96 I: IntoIterator<Item = &'a str>,
97{
98 let mut seen = HashSet::new();
99 for relative_path in paths {
100 ReadonlyRefgetStore::sanitize_relative_path(relative_path)?;
101 let full_path = cache_path.join(relative_path);
102 if seen.insert(full_path.clone()) {
103 remove_cached_artifact(&full_path)?;
104 }
105 }
106 Ok(())
107}
108
109fn validate_remote_manifest_paths(metadata: &StoreMetadata) -> Result<()> {
110 ReadonlyRefgetStore::sanitize_relative_path(&metadata.seqdata_path_template)?;
111 ReadonlyRefgetStore::sanitize_relative_path(&metadata.collections_path_template)?;
112 ReadonlyRefgetStore::sanitize_relative_path(&metadata.sequence_index)?;
113 if let Some(ref collection_index) = metadata.collection_index {
114 ReadonlyRefgetStore::sanitize_relative_path(collection_index)?;
115 }
116 Ok(())
117}
118
119impl ReadonlyRefgetStore {
124 pub(crate) fn write_sequence_to_disk_single(
126 &self,
127 metadata: &SequenceMetadata,
128 sequence: &[u8],
129 ) -> Result<()> {
130 let template = self
131 .seqdata_path_template
132 .as_ref()
133 .context("seqdata_path_template not set")?;
134 let local_path = self.local_path.as_ref().context("local_path not set")?;
135
136 let seq_file_path = Self::expand_template(&metadata.sha512t24u, template);
137 let full_path = local_path.join(&seq_file_path);
138
139 if let Some(parent) = full_path.parent() {
140 create_dir_all(parent)?;
141 }
142
143 super::atomic::publish_bytes_nosync(&full_path, sequence)
144 }
145
146 #[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
156 pub(crate) fn write_seq_bytes_to_full_path(
157 full_path: &Path,
158 sequence: &[u8],
159 created_shards: &std::sync::Mutex<HashSet<std::path::PathBuf>>,
160 ) -> Result<()> {
161 if let Some(parent) = full_path.parent() {
162 let known = {
164 let guard = created_shards.lock().unwrap();
165 guard.contains(parent)
166 };
167 if !known {
168 create_dir_all(parent)?;
169 created_shards.lock().unwrap().insert(parent.to_path_buf());
170 }
171 }
172
173 super::atomic::publish_bytes_nosync(full_path, sequence)
177 }
178
179 pub(crate) fn write_collection_to_disk_single<I>(
182 &self,
183 metadata: &SequenceCollectionMetadata,
184 members: I,
185 ) -> Result<()>
186 where
187 I: IntoIterator,
188 I::Item: std::borrow::Borrow<SequenceMetadata>,
189 {
190 let local_path = self.local_path.as_ref().context("local_path not set")?;
191
192 let coll_file_path = format!("collections/{}.rgsi", metadata.digest);
193 let full_path = local_path.join(&coll_file_path);
194
195 if let Some(parent) = full_path.parent() {
196 create_dir_all(parent)?;
197 }
198
199 crate::collection::write_collection_rgsi_rows(&full_path, metadata, members)?;
200
201 Ok(())
202 }
203
204 pub(crate) fn acquire_commit_lock(&self, operation: &str) -> Result<Option<StoreLock>> {
216 if self.commit_lock.is_some() {
217 return Ok(None);
218 }
219 let Some(local_path) = self.local_path.as_ref() else {
220 return Ok(None);
221 };
222 Ok(Some(StoreLock::acquire(
223 local_path,
224 operation,
225 self.lock_options.clone(),
226 )?))
227 }
228
229 pub(crate) fn write_index_files(&self) -> Result<()> {
242 let local_path = self
243 .local_path
244 .as_ref()
245 .context("local_path not set")?
246 .clone();
247 let template = self
248 .seqdata_path_template
249 .as_ref()
250 .context("seqdata_path_template not set")?
251 .clone();
252
253 let _guard = self.acquire_commit_lock("write_index_files")?;
254
255 let pending = self.pending.lock().unwrap().clone();
258
259 let sequence_index_path = local_path.join("sequences.rgsi");
260 let collection_index_path = local_path.join("collections.rgci");
261
262 let mut sequences = read_sequences_rgsi_rows(&sequence_index_path)?;
265 self.apply_pending_sequence_rows(&mut sequences, &pending);
266 let mut collections = read_collections_rgci_rows(&collection_index_path)?;
267 self.apply_pending_collection_rows(&mut collections, &pending);
268
269 for coll_key in &pending.collections {
277 let member_keys = self.loaded_member_seq_keys(&key_to_digest_string(coll_key));
278 if let Some(missing) = member_keys.iter().find(|k| !sequences.contains_key(*k)) {
279 anyhow::bail!(
280 "cannot commit collection {}: its sequence {} is no longer in the store index. Another writer removed it while this import was in progress. Re-run the import.",
281 key_to_digest_string(coll_key),
282 key_to_digest_string(missing),
283 );
284 }
285 }
286
287 write_sequences_rgsi_rows(&sequence_index_path, &sequences)?;
289 write_collections_rgci_rows(&collection_index_path, &collections)?;
290
291 if self.layout == Layout::Packed {
295 self.commit_pack_idx(&local_path, &pending)?;
296 self.invalidate_pack_index();
297 }
298
299 self.commit_all_alias_namespaces(&local_path, &pending)?;
301
302 let logical_bytes: u64 = sequences
305 .values()
306 .map(|m| m.disk_size(&self.mode) as u64)
307 .sum();
308
309 let mut metadata = self.manifest_base(&local_path, &template)?;
310 metadata.sequences_digest = Self::sha256_file(&sequence_index_path).ok();
311 metadata.collections_digest = Self::sha256_file(&collection_index_path).ok();
312 metadata.aliases_digest = self.compute_aliases_digest();
313 metadata.fhr_digest = self.compute_fhr_digest();
314 metadata.logical_sequence_bytes = Some(logical_bytes);
315 let (seq_ns, coll_ns) = published_alias_namespaces(&local_path);
316 metadata.sequence_alias_namespaces = seq_ns;
317 metadata.collection_alias_namespaces = coll_ns;
318
319 write_manifest(&local_path, &metadata)?;
321
322 self.pending.lock().unwrap().clear_matching(&pending);
324
325 Ok(())
326 }
327
328 pub(crate) fn commit_pack_idx(&self, local_path: &Path, pending: &PendingChanges) -> Result<()> {
336 use super::packidx::{read_pack_idx_rows, write_pack_idx, PackRow};
337
338 let idx_path = local_path.join("sequences.pack.idx");
339
340 let mut rows: BTreeMap<String, PackRow> =
342 read_pack_idx_rows(&super::packidx::load_pack_idx_or_empty(local_path)?)?;
343
344 let packs_dir = local_path.join("packs");
352 let check_packs = |new_rows: &mut dyn Iterator<Item = &PackRow>| -> Result<()> {
353 let mut seen: HashSet<&str> = HashSet::new();
354 for row in new_rows {
355 if seen.insert(&row.pack) && !packs_dir.join(format!("{}.pack", row.pack)).exists() {
356 anyhow::bail!(
357 "cannot commit: pack {} is no longer in the store. Another writer \
358 removed it while this handle was writing. Reopen the store and \
359 re-run the import.",
360 row.pack
361 );
362 }
363 }
364 Ok(())
365 };
366 check_packs(&mut pending.pack_rows.values())?;
367
368 let session_rows = self.seal_open_session_pack()?;
370 check_packs(&mut session_rows.iter().map(|(_, row)| row))?;
371 for (digest, row) in session_rows {
372 rows.insert(digest, row);
373 }
374
375 for (key, row) in &pending.pack_rows {
377 rows.insert(key_to_digest_string(key), row.clone());
378 }
379 for key in &pending.removed_sequences {
381 rows.remove(&key_to_digest_string(key));
382 }
383
384 write_pack_idx(&idx_path, &rows)
385 }
386
387 fn apply_pending_sequence_rows(
404 &self,
405 rows: &mut HashMap<DigestKey, SequenceMetadata>,
406 pending: &PendingChanges,
407 ) {
408 for key in &pending.sequences {
409 if let Some(view) = self.sequence_view(key_to_digest_string(key)) {
410 rows.entry(*key).or_insert_with(|| view.to_metadata());
411 }
412 }
413 for key in &pending.removed_sequences {
414 rows.remove(key);
415 }
416 }
417
418 fn apply_pending_collection_rows(
428 &self,
429 rows: &mut HashMap<DigestKey, SequenceCollectionMetadata>,
430 pending: &PendingChanges,
431 ) {
432 let ancillary_count = |m: &SequenceCollectionMetadata| {
433 m.name_length_pairs_digest.is_some() as u8
434 + m.sorted_name_length_pairs_digest.is_some() as u8
435 + m.sorted_sequences_digest.is_some() as u8
436 };
437 for key in &pending.collections {
438 let Some(mine) = self.get_collection_metadata(key_to_digest_string(key)) else {
439 continue;
440 };
441 match rows.get(key) {
442 Some(existing) if ancillary_count(existing) >= ancillary_count(mine) => {}
443 _ => {
444 rows.insert(*key, mine.clone());
445 }
446 }
447 }
448 for key in &pending.removed_collections {
449 rows.remove(key);
450 }
451 }
452
453 fn manifest_base(&self, local_path: &Path, seqdata_template: &str) -> Result<StoreMetadata> {
461 let now = Utc::now().to_rfc3339();
462 let existing = read_manifest(local_path)?;
463 let created_at = existing
464 .as_ref()
465 .map(|m| m.created_at.clone())
466 .unwrap_or_else(|| now.clone());
467
468 Ok(StoreMetadata {
469 version: 1,
470 seqdata_path_template: seqdata_template.to_string(),
471 collections_path_template: "collections/%s.rgsi".to_string(),
472 sequence_index: "sequences.rgsi".to_string(),
473 collection_index: Some("collections.rgci".to_string()),
474 mode: self.mode,
475 layout: self.layout,
476 created_at,
477 ancillary_digests: self.ancillary_digests,
478 attribute_index: self.attribute_index,
479 sequence_alias_namespaces: self.aliases.sequence_namespaces(),
480 collection_alias_namespaces: self.aliases.collection_namespaces(),
481 modified: Some(now),
482 collections_digest: None,
483 sequences_digest: None,
484 aliases_digest: None,
485 fhr_digest: None,
486 logical_sequence_bytes: None,
487 })
488 }
489
490 pub(crate) fn write_rgstore_json(&self, dir: &Path, seqdata_template: &str) -> Result<()> {
494 let now = Utc::now().to_rfc3339();
495 let metadata = StoreMetadata {
496 version: 1,
497 seqdata_path_template: seqdata_template.to_string(),
498 collections_path_template: "collections/%s.rgsi".to_string(),
499 sequence_index: "sequences.rgsi".to_string(),
500 collection_index: Some("collections.rgci".to_string()),
501 mode: self.mode,
502 layout: Layout::Standalone,
505 created_at: now.clone(),
506 ancillary_digests: self.ancillary_digests,
507 attribute_index: self.attribute_index,
508 sequence_alias_namespaces: self.aliases.sequence_namespaces(),
509 collection_alias_namespaces: self.aliases.collection_namespaces(),
510 modified: Some(now),
511 collections_digest: None,
512 sequences_digest: None,
513 aliases_digest: None,
514 fhr_digest: None,
515 logical_sequence_bytes: Some(self.logical_sequence_bytes() as u64),
516 };
517 write_manifest(dir, &metadata)
518 }
519
520 pub(crate) fn refresh_manifest_alias_namespaces(&self) -> Result<()> {
539 let local_path = match self.local_path.as_ref() {
540 Some(p) => p,
541 None => return Ok(()),
542 };
543 let Some(mut metadata) = read_manifest(local_path)? else {
544 return Ok(());
545 };
546
547 let (seq_ns, coll_ns) = published_alias_namespaces(local_path);
548 metadata.sequence_alias_namespaces = seq_ns;
549 metadata.collection_alias_namespaces = coll_ns;
550 metadata.aliases_digest = self.compute_aliases_digest();
551 metadata.modified = Some(Utc::now().to_rfc3339());
552
553 write_manifest(local_path, &metadata)
554 }
555
556 pub(crate) fn write_collections_rgci<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
567 let rows: HashMap<DigestKey, SequenceCollectionMetadata> = self
568 .catalog
569 .coll_rows()
570 .map(|c| {
571 let m = self.catalog.coll_meta(c);
572 (m.digest.to_key(), m.clone())
573 })
574 .collect();
575 write_collections_rgci_rows(file_path.as_ref(), &rows)
576 }
577
578 pub fn write_sequences_rgsi<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
582 let rows: HashMap<DigestKey, SequenceMetadata> = self
583 .sequence_views()
584 .map(|v| (v.sha512t24u().to_key(), v.to_metadata()))
585 .collect();
586 write_sequences_rgsi_rows(file_path.as_ref(), &rows)
587 }
588
589 fn commit_all_alias_namespaces(
602 &self,
603 local_path: &Path,
604 pending: &PendingChanges,
605 ) -> Result<()> {
606 let aliases_dir = local_path.join("aliases");
607 for kind in [AliasKind::Sequence, AliasKind::Collection] {
608 for ns in pending.touched_alias_namespaces(kind) {
609 self.commit_alias_namespace(&aliases_dir, kind, &ns, pending)?;
610 }
611 }
612 Ok(())
613 }
614
615 pub(crate) fn commit_alias_namespace(
629 &self,
630 aliases_dir: &Path,
631 kind: AliasKind,
632 namespace: &str,
633 pending: &PendingChanges,
634 ) -> Result<()> {
635 let tsv_path = aliases_dir.join(kind.subdir()).join(format!("{}.tsv", namespace));
636
637 let mut merged = read_alias_tsv(&tsv_path)?;
638
639 for (k, ns, alias) in &pending.aliases {
640 if *k != kind || ns != namespace {
641 continue;
642 }
643 let Some(digest) = self.aliases.resolve(kind, namespace, alias) else {
646 continue;
647 };
648 match merged.get(alias) {
649 Some(existing) if *existing != digest => {
650 if !self.force_alias && !pending.is_forced(kind, namespace, alias) {
654 return Err(anyhow::anyhow!(
655 "alias conflict in {} namespace '{}': '{}' is already published as {} \
656 on disk but this writer has it as {}. Another writer bound it first. \
657 Re-run with force-alias enabled (CLI: --force-alias) to overwrite the \
658 published value.",
659 kind.subdir(),
660 namespace,
661 alias,
662 key_to_digest_string(existing),
663 key_to_digest_string(&digest),
664 ));
665 }
666 merged.insert(alias.clone(), digest);
667 }
668 Some(_) => {}
669 None => {
670 merged.insert(alias.clone(), digest);
671 }
672 }
673 }
674
675 for (k, ns, alias) in &pending.removed_aliases {
676 if *k == kind && ns == namespace {
677 merged.remove(alias);
678 }
679 }
680
681 write_alias_namespace(&tsv_path, &merged)
682 }
683
684 pub(crate) fn live_sequence_digests_from_disk(
705 &self,
706 exclude: &DigestKey,
707 ) -> Result<HashSet<DigestKey>> {
708 let local_path = self.local_path.as_ref().context("local_path not set")?;
709 let pending = self.pending.lock().unwrap().clone();
710 let index_path = local_path.join("collections.rgci");
711 let mut collections = read_collections_rgci_rows(&index_path)?;
714 self.apply_pending_collection_rows(&mut collections, &pending);
715
716 let mut live = HashSet::new();
717 for (key, meta) in &collections {
718 if key == exclude {
719 continue;
720 }
721
722 if self.is_collection_loaded(&meta.digest) {
725 live.extend(self.loaded_member_seq_keys(&meta.digest));
726 continue;
727 }
728
729 let rgsi_path = local_path.join(format!("collections/{}.rgsi", meta.digest));
730 let collection = read_rgsi_file(&rgsi_path).with_context(|| {
731 format!(
732 "refusing to remove orphan sequences: collection {} is listed in \
733 collections.rgci but {} could not be read. Treating that as \
734 'references nothing' would delete live sequence data.",
735 meta.digest,
736 rgsi_path.display()
737 )
738 })?;
739 for seq in &collection.sequences {
740 live.insert(seq.metadata().sha512t24u.to_key());
741 }
742 }
743 Ok(live)
744 }
745
746 pub(crate) fn collection_sequence_digests(&self, digest: &str) -> Result<Vec<DigestKey>> {
749 if self.is_collection_loaded(digest) {
750 return Ok(self.loaded_member_seq_keys(digest));
751 }
752 if let Some(local_path) = self.local_path.as_ref() {
753 let rgsi_path = local_path.join(format!("collections/{}.rgsi", digest));
754 if rgsi_path.exists() {
755 let collection = read_rgsi_file(&rgsi_path)?;
756 return Ok(collection
757 .sequences
758 .iter()
759 .map(|s| s.metadata().sha512t24u.to_key())
760 .collect());
761 }
762 }
763 Ok(Vec::new())
765 }
766
767 pub fn store_metadata(&self) -> Result<HashMap<String, String>> {
773 let local_path = self.local_path.as_ref().context("local_path not set")?;
774 let json = fs::read_to_string(local_path.join("rgstore.json"))
775 .context("Failed to read rgstore.json")?;
776 let metadata: StoreMetadata =
777 serde_json::from_str(&json).context("Failed to parse store metadata")?;
778
779 let mut map = HashMap::new();
780 if let Some(v) = metadata.modified { map.insert("modified".to_string(), v); }
781 if let Some(v) = metadata.collections_digest { map.insert("collections_digest".to_string(), v); }
782 if let Some(v) = metadata.sequences_digest { map.insert("sequences_digest".to_string(), v); }
783 if let Some(v) = metadata.aliases_digest { map.insert("aliases_digest".to_string(), v); }
784 if let Some(v) = metadata.fhr_digest { map.insert("fhr_digest".to_string(), v); }
785 if let Some(v) = metadata.logical_sequence_bytes { map.insert("logical_sequence_bytes".to_string(), v.to_string()); }
786 Ok(map)
787 }
788
789 fn sha256_file(path: &Path) -> Result<String> {
791 let bytes = fs::read(path)?;
792 let hash = Sha256::digest(&bytes);
793 Ok(format!("{:x}", hash))
794 }
795
796 fn compute_aliases_digest(&self) -> Option<String> {
799 let local_path = self.local_path.as_ref()?;
800 let aliases_dir = local_path.join("aliases");
801 if !aliases_dir.exists() { return None; }
802
803 let mut paths: Vec<_> = Vec::new();
804 for subdir in &["sequences", "collections"] {
805 let sub = aliases_dir.join(subdir);
806 if sub.exists() {
807 if let Ok(entries) = fs::read_dir(&sub) {
808 for entry in entries.filter_map(|e| e.ok()) {
809 let p = entry.path();
810 if p.extension().map_or(false, |e| e == "tsv") {
811 paths.push(p);
812 }
813 }
814 }
815 }
816 }
817 if paths.is_empty() { return None; }
818 paths.sort();
819
820 let mut hasher = Sha256::new();
821 for path in &paths {
822 hasher.update(fs::read(path).ok()?);
823 }
824 Some(format!("{:x}", hasher.finalize()))
825 }
826
827 fn compute_fhr_digest(&self) -> Option<String> {
829 let local_path = self.local_path.as_ref()?;
830 let fhr_dir = local_path.join("fhr");
831 if !fhr_dir.exists() { return None; }
832
833 let mut paths: Vec<_> = fs::read_dir(&fhr_dir).ok()?
837 .filter_map(|e| e.ok())
838 .map(|e| e.path())
839 .filter(|p| {
840 p.file_name()
841 .and_then(|n| n.to_str())
842 .map_or(false, |n| n.ends_with(super::fhr_metadata::SIDECAR_EXTENSION))
843 })
844 .collect();
845 if paths.is_empty() { return None; }
846 paths.sort();
847
848 let mut hasher = Sha256::new();
849 for path in paths {
850 hasher.update(fs::read(&path).ok()?);
851 }
852 Some(format!("{:x}", hasher.finalize()))
853 }
854
855 pub(crate) fn open_local<P: AsRef<Path>>(path: P) -> Result<Self> {
861 let root_path = path.as_ref();
862
863 let index_path = root_path.join("rgstore.json");
864 let json = fs::read_to_string(&index_path).context(format!(
865 "Failed to read rgstore.json from {}",
866 index_path.display()
867 ))?;
868
869 let metadata: StoreMetadata =
870 serde_json::from_str(&json).context("Failed to parse store metadata")?;
871
872 Self::sanitize_relative_path(&metadata.seqdata_path_template)?;
873 Self::sanitize_relative_path(&metadata.sequence_index)?;
874 if let Some(ref ci) = metadata.collection_index {
875 Self::sanitize_relative_path(ci)?;
876 }
877
878 let mut store = ReadonlyRefgetStore::new(metadata.mode);
879 store.local_path = Some(root_path.to_path_buf());
880 store.seqdata_path_template = Some(metadata.seqdata_path_template.clone());
881 store.persist_to_disk = true;
882 store.layout = metadata.layout;
883 store.ancillary_digests = metadata.ancillary_digests;
884 store.attribute_index = metadata.attribute_index;
885
886 debug_assert!(!(store.layout == Layout::Packed && store.remote_source.is_some()));
888
889 let sequence_index_path = root_path.join(&metadata.sequence_index);
890 if sequence_index_path.exists() {
891 Self::load_sequences_from_index(&mut store, &sequence_index_path)?;
892 }
893
894 if let Some(ref collection_index) = metadata.collection_index {
895 let collection_index_path = root_path.join(collection_index);
896 if collection_index_path.exists() {
897 Self::load_collection_stubs_from_rgci(&mut store, &collection_index_path)?;
898 }
899 }
900
901 if store.catalog.n_collections() == 0 {
902 let collections_dir = root_path.join("collections");
903 Self::load_collections_from_directory(&mut store, &collections_dir)?;
904 }
905
906 let aliases_dir = root_path.join("aliases");
913 store.aliases.load_namespaces_from_dir(
914 &aliases_dir,
915 &metadata.sequence_alias_namespaces,
916 &metadata.collection_alias_namespaces,
917 )?;
918 store.available_sequence_alias_namespaces = metadata.sequence_alias_namespaces;
919 store.available_collection_alias_namespaces = metadata.collection_alias_namespaces;
920
921 store.fhr_metadata =
922 fhr_metadata::load_sidecars(&root_path.join("fhr"));
923
924 Ok(store)
925 }
926
927 pub(crate) fn open_remote<P: AsRef<Path>, S: AsRef<str>>(
929 cache_path: P,
930 remote_url: S,
931 ) -> Result<Self> {
932 let cache_path = cache_path.as_ref();
933 let remote_url = remote_url.as_ref().to_string();
934
935 create_dir_all(cache_path)
936 .with_context(|| format!("Failed to create remote cache {}", cache_path.display()))?;
937
938 let origin_path = cache_path.join(".origin");
939 match fs::read_to_string(&origin_path) {
940 Ok(recorded) => {
941 let recorded = recorded.strip_suffix('\n').unwrap_or(&recorded);
942 if recorded != remote_url {
943 anyhow::bail!(
944 "Remote cache {} belongs to {}, not requested origin {}",
945 cache_path.display(),
946 recorded,
947 remote_url
948 );
949 }
950 }
951 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
952 let contents = format!("{}\n", remote_url);
953 atomic_write_bytes(&origin_path, contents.as_bytes()).with_context(|| {
954 format!("Failed to record remote cache origin in {}", origin_path.display())
955 })?;
956 }
957 Err(error) => {
958 return Err(error).with_context(|| {
959 format!("Failed to read remote cache origin {}", origin_path.display())
960 });
961 }
962 }
963
964 let manifest_path = cache_path.join("rgstore.json");
965 let cached_json = fs::read_to_string(&manifest_path).ok();
966 let old_metadata = cached_json
967 .as_deref()
968 .and_then(|json| serde_json::from_str::<StoreMetadata>(json).ok())
969 .filter(|metadata| validate_remote_manifest_paths(metadata).is_ok());
970
971 let json = match Self::fetch_file(
974 &Some(cache_path.to_path_buf()),
975 &Some(remote_url.clone()),
976 "rgstore.json",
977 false,
978 true,
979 ) {
980 Ok(bytes) => {
981 String::from_utf8(bytes).context("Store metadata contains invalid UTF-8")?
982 }
983 Err(error) => match (&old_metadata, cached_json) {
984 (Some(_), Some(json)) => {
985 eprintln!(
986 "Could not refresh {} ({}); using cached store metadata",
987 remote_url, error
988 );
989 json
990 }
991 _ => return Err(error),
992 },
993 };
994
995 let metadata: StoreMetadata =
996 serde_json::from_str(&json).context("Failed to parse store metadata")?;
997
998 validate_remote_manifest_paths(&metadata)?;
999
1000 let collections_changed = old_metadata
1001 .as_ref()
1002 .map(|old| old.collections_digest != metadata.collections_digest)
1003 .unwrap_or(true);
1004 let sequences_changed = old_metadata
1005 .as_ref()
1006 .map(|old| old.sequences_digest != metadata.sequences_digest)
1007 .unwrap_or(true);
1008 let aliases_changed = old_metadata
1009 .as_ref()
1010 .map(|old| old.aliases_digest != metadata.aliases_digest)
1011 .unwrap_or(true);
1012 let fhr_changed = old_metadata
1013 .as_ref()
1014 .map(|old| old.fhr_digest != metadata.fhr_digest)
1015 .unwrap_or(true);
1016
1017 if collections_changed {
1018 let old_index = old_metadata
1019 .as_ref()
1020 .and_then(|old| old.collection_index.as_deref())
1021 .unwrap_or("collections.rgci");
1022 let new_index = metadata.collection_index.as_deref().unwrap_or("collections.rgci");
1023 remove_cached_indexes(cache_path, [old_index, new_index])?;
1024 remove_cached_artifact(&cache_path.join("collections"))?;
1025 }
1026 if sequences_changed {
1027 let old_index = old_metadata
1028 .as_ref()
1029 .map(|old| old.sequence_index.as_str())
1030 .unwrap_or("sequences.rgsi");
1031 remove_cached_indexes(cache_path, [old_index, metadata.sequence_index.as_str()])?;
1032 }
1033 if aliases_changed {
1034 remove_cached_artifact(&cache_path.join("aliases"))?;
1035 }
1036 if fhr_changed {
1037 remove_cached_artifact(&cache_path.join("fhr"))?;
1038 }
1039
1040 atomic_write_bytes(&manifest_path, json.as_bytes())
1041 .context("Failed to publish refreshed remote rgstore.json")?;
1042
1043 let mut store = ReadonlyRefgetStore::new(metadata.mode);
1044 store.local_path = Some(cache_path.to_path_buf());
1045 store.remote_source = Some(remote_url.clone());
1046 store.seqdata_path_template = Some(metadata.seqdata_path_template.clone());
1047 store.persist_to_disk = true;
1048 store.remote_layout = metadata.layout;
1051 store.layout = Layout::Standalone;
1052 store.ancillary_digests = metadata.ancillary_digests;
1053 store.attribute_index = metadata.attribute_index;
1054
1055 store.sequence_index_loaded = false;
1058 store.sequence_index_path = Some(metadata.sequence_index.clone());
1059
1060 if let Some(ref collection_index) = metadata.collection_index {
1061 if let Ok(collection_index_data) = Self::fetch_file(
1062 &Some(cache_path.to_path_buf()),
1063 &Some(remote_url.clone()),
1064 collection_index,
1065 true,
1066 false,
1067 ) {
1068 let collection_index_str = String::from_utf8(collection_index_data)
1069 .context("collection index contains invalid UTF-8")?;
1070
1071 Self::load_collection_stubs_from_reader(
1072 &mut store,
1073 collection_index_str.as_bytes(),
1074 )?;
1075 }
1076 }
1077
1078 if store.catalog.n_collections() == 0 {
1079 let local_collections_dir = cache_path.join("collections");
1080 create_dir_all(&local_collections_dir)?;
1081 Self::load_collections_from_directory(&mut store, &local_collections_dir)?;
1082 }
1083
1084 for namespace in &metadata.sequence_alias_namespaces {
1085 let relative_path = format!("aliases/sequences/{}.tsv", namespace);
1086 Self::fetch_file(
1087 &store.local_path,
1088 &store.remote_source,
1089 &relative_path,
1090 true,
1091 false,
1092 )
1093 .with_context(|| {
1094 format!(
1095 "Remote {} advertised sequence alias namespace '{}' but it could not be loaded",
1096 remote_url, namespace
1097 )
1098 })?;
1099 }
1100 for namespace in &metadata.collection_alias_namespaces {
1101 let relative_path = format!("aliases/collections/{}.tsv", namespace);
1102 Self::fetch_file(
1103 &store.local_path,
1104 &store.remote_source,
1105 &relative_path,
1106 true,
1107 false,
1108 )
1109 .with_context(|| {
1110 format!(
1111 "Remote {} advertised collection alias namespace '{}' but it could not be loaded",
1112 remote_url, namespace
1113 )
1114 })?;
1115 }
1116 store.aliases.load_namespaces_from_dir(
1117 &cache_path.join("aliases"),
1118 &metadata.sequence_alias_namespaces,
1119 &metadata.collection_alias_namespaces,
1120 )?;
1121 store.available_sequence_alias_namespaces = metadata.sequence_alias_namespaces;
1122 store.available_collection_alias_namespaces = metadata.collection_alias_namespaces;
1123
1124 Ok(store)
1125 }
1126
1127 pub(crate) fn load_sequences_from_reader<R: BufRead>(store: &mut ReadonlyRefgetStore, mut reader: R) -> Result<()> {
1133 let mut line = String::new();
1134 loop {
1135 line.clear();
1136 if reader.read_line(&mut line)? == 0 {
1137 break;
1138 }
1139 if line.starts_with('#') {
1140 continue;
1141 }
1142 if let Some(f) = parse_rgsi_fields(&line) {
1143 store.catalog.add_sequence_parts(f)?;
1146 }
1147 }
1148 Ok(())
1149 }
1150
1151 pub(crate) fn load_sequences_from_index(store: &mut ReadonlyRefgetStore, index_path: &Path) -> Result<()> {
1153 let file = std::fs::File::open(index_path)?;
1154 let reader = std::io::BufReader::with_capacity(1 << 20, file);
1155 Self::load_sequences_from_reader(store, reader)
1156 }
1157
1158 pub(crate) fn load_collection_stubs_from_reader<R: BufRead>(
1161 store: &mut ReadonlyRefgetStore,
1162 reader: R,
1163 ) -> Result<()> {
1164 for line in reader.lines() {
1165 let line = line?;
1166
1167 if let Some(metadata) = parse_rgci_line(&line) {
1168 store.catalog.upsert_collection(metadata)?;
1169 }
1170 }
1171
1172 Ok(())
1173 }
1174
1175 pub(crate) fn load_collection_stubs_from_rgci(store: &mut ReadonlyRefgetStore, index_path: &Path) -> Result<()> {
1177 let file = std::fs::File::open(index_path)?;
1178 let reader = std::io::BufReader::new(file);
1179 Self::load_collection_stubs_from_reader(store, reader)
1180 }
1181
1182 pub(crate) fn load_collections_from_directory(
1184 store: &mut ReadonlyRefgetStore,
1185 collections_dir: &Path,
1186 ) -> Result<()> {
1187 if !collections_dir.exists() {
1188 return Ok(());
1189 }
1190
1191 for entry in fs::read_dir(collections_dir)? {
1192 let entry = entry?;
1193 let path = entry.path();
1194
1195 if path.is_file() && path.extension() == Some(OsStr::new("rgsi")) {
1196 store.load_collection_rgsi(&path, None)?;
1197 }
1198 }
1199
1200 Ok(())
1201 }
1202
1203 pub(crate) fn load_collection_rgsi(&mut self, path: &Path, expected: Option<&str>) -> Result<CollRow> {
1211 let file = std::fs::File::open(path)
1212 .with_context(|| format!("opening {}", path.display()))?;
1213 let mut reader = std::io::BufReader::with_capacity(1 << 20, file);
1214 let mut line = String::new();
1215
1216 let mut header = RgsiHeader::default();
1217 let mut pending_data = false;
1218 loop {
1219 line.clear();
1220 if reader.read_line(&mut line)? == 0 {
1221 break;
1222 }
1223 let l = line.trim_end_matches(['\n', '\r']);
1224 if header.read_line(l) || l.starts_with('#') {
1225 continue;
1226 }
1227 pending_data = true;
1228 break;
1229 }
1230
1231 let Some(meta) = header.into_metadata(0, path) else {
1233 let collection = read_rgsi_file(path)?;
1234 if let Some(e) = expected {
1235 if collection.metadata.digest != e {
1236 return Err(anyhow!(
1237 "Collection digest mismatch: expected {}, got {}",
1238 e,
1239 collection.metadata.digest
1240 ));
1241 }
1242 }
1243 let crate::digest::SequenceCollection { metadata, sequences } = collection;
1244 let members: Vec<SequenceMetadata> =
1245 sequences.iter().map(|s| s.metadata().clone()).collect();
1246 return Ok(self.insert_collection(metadata, &members)?.0);
1247 };
1248 if let Some(e) = expected {
1249 if meta.digest != e {
1250 return Err(anyhow!("Collection digest mismatch: expected {}, got {}", e, meta.digest));
1251 }
1252 }
1253 let c = self.catalog.upsert_collection(meta)?;
1254 self.catalog.start_members(c);
1255
1256 let mut n = 0usize;
1257 let result = (|| -> Result<()> {
1258 loop {
1259 if !pending_data {
1260 line.clear();
1261 if reader.read_line(&mut line)? == 0 {
1262 break;
1263 }
1264 }
1265 pending_data = false;
1266 if line.starts_with('#') {
1267 continue;
1268 }
1269 let Some(f) = parse_rgsi_fields(&line) else { continue };
1270 let (name, description) = (f.name, f.description);
1271 let (seq, _) = self.catalog.add_sequence_parts(f)?;
1272 self.catalog.push_member(c, NewMember { seq, name, description, fai: None })?;
1273 n += 1;
1274 }
1275 Ok(())
1276 })();
1277 if let Err(e) = result {
1278 self.catalog.unload_members(c);
1279 return Err(e.context(format!("reading {}", path.display())));
1280 }
1281 self.catalog.set_coll_n_sequences(c, n);
1282 Ok(c)
1283 }
1284}
1285
1286pub(crate) fn read_sequences_rgsi_rows(path: &Path) -> Result<HashMap<DigestKey, SequenceMetadata>> {
1298 let mut rows = HashMap::new();
1299 let file = match File::open(path) {
1300 Ok(f) => f,
1301 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rows),
1302 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
1303 };
1304 for line in std::io::BufReader::new(file).lines() {
1305 let line = line?;
1306 if line.starts_with('#') {
1307 continue;
1308 }
1309 if let Some(meta) = parse_rgsi_line(&line) {
1310 rows.insert(meta.sha512t24u.to_key(), meta);
1311 }
1312 }
1313 Ok(rows)
1314}
1315
1316pub(crate) fn read_collections_rgci_rows(
1318 path: &Path,
1319) -> Result<HashMap<DigestKey, SequenceCollectionMetadata>> {
1320 let mut rows = HashMap::new();
1321 let file = match File::open(path) {
1322 Ok(f) => f,
1323 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rows),
1324 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
1325 };
1326 for line in std::io::BufReader::new(file).lines() {
1327 let line = line?;
1328 if let Some(meta) = parse_rgci_line(&line) {
1329 rows.insert(meta.digest.to_key(), meta);
1330 }
1331 }
1332 Ok(rows)
1333}
1334
1335pub(crate) fn write_sequences_rgsi_rows(
1340 path: &Path,
1341 rows: &HashMap<DigestKey, SequenceMetadata>,
1342) -> Result<()> {
1343 let mut entries: Vec<&SequenceMetadata> = rows.values().collect();
1344 entries.sort_by(|a, b| a.sha512t24u.cmp(&b.sha512t24u));
1345
1346 atomic_write(path, |w| {
1347 writeln!(w, "{}", RGSI_HEADER)?;
1348 for meta in entries {
1349 writeln!(
1350 w,
1351 "{}\t{}\t{}\t{}\t{}\t{}",
1352 meta.name,
1353 meta.length,
1354 meta.alphabet,
1355 meta.sha512t24u,
1356 meta.md5,
1357 meta.description.as_deref().unwrap_or("")
1358 )?;
1359 }
1360 Ok(())
1361 })
1362}
1363
1364pub(crate) fn write_collections_rgci_rows(
1368 path: &Path,
1369 rows: &HashMap<DigestKey, SequenceCollectionMetadata>,
1370) -> Result<()> {
1371 let mut entries: Vec<&SequenceCollectionMetadata> = rows.values().collect();
1372 entries.sort_by(|a, b| a.digest.cmp(&b.digest));
1373
1374 atomic_write(path, |w| {
1375 writeln!(w, "{}", RGCI_HEADER)?;
1376 for meta in entries {
1377 writeln!(
1378 w,
1379 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
1380 meta.digest,
1381 meta.n_sequences,
1382 meta.names_digest,
1383 meta.sequences_digest,
1384 meta.lengths_digest,
1385 meta.name_length_pairs_digest.as_deref().unwrap_or(""),
1386 meta.sorted_name_length_pairs_digest.as_deref().unwrap_or(""),
1387 meta.sorted_sequences_digest.as_deref().unwrap_or(""),
1388 )?;
1389 }
1390 Ok(())
1391 })
1392}
1393
1394pub(crate) fn read_manifest(dir: &Path) -> Result<Option<StoreMetadata>> {
1400 let path = dir.join("rgstore.json");
1401 match fs::read_to_string(&path) {
1402 Ok(json) => Ok(Some(serde_json::from_str(&json).with_context(|| {
1403 format!("Failed to parse {}", path.display())
1404 })?)),
1405 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1406 Err(e) => Err(e).with_context(|| format!("Failed to read {}", path.display())),
1407 }
1408}
1409
1410pub(crate) fn write_manifest(dir: &Path, metadata: &StoreMetadata) -> Result<()> {
1412 let json = serde_json::to_string_pretty(metadata)
1413 .context("Failed to serialize metadata to JSON")?;
1414 super::atomic::atomic_write_bytes(&dir.join("rgstore.json"), json.as_bytes())
1415 .context("Failed to write rgstore.json")
1416}
1417
1418fn scan_alias_namespaces(dir: &Path) -> Vec<String> {
1420 let Ok(entries) = fs::read_dir(dir) else {
1421 return Vec::new();
1422 };
1423 entries
1424 .filter_map(|e| e.ok())
1425 .map(|e| e.path())
1426 .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("tsv"))
1427 .filter_map(|p| p.file_stem().and_then(|s| s.to_str()).map(String::from))
1428 .collect()
1429}
1430
1431pub(crate) fn published_alias_namespaces(local_path: &Path) -> (Vec<String>, Vec<String>) {
1440 let aliases_dir = local_path.join("aliases");
1441 let mut seq = scan_alias_namespaces(&aliases_dir.join(AliasKind::Sequence.subdir()));
1442 let mut coll = scan_alias_namespaces(&aliases_dir.join(AliasKind::Collection.subdir()));
1443 seq.sort();
1444 coll.sort();
1445 (seq, coll)
1446}
1447
1448pub(crate) fn read_alias_tsv(path: &Path) -> Result<HashMap<String, DigestKey>> {
1450 let mut map = HashMap::new();
1451 let file = match File::open(path) {
1452 Ok(f) => f,
1453 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(map),
1454 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
1455 };
1456 for line in std::io::BufReader::new(file).lines() {
1457 let line = line?;
1458 if line.starts_with('#') || line.trim().is_empty() {
1459 continue;
1460 }
1461 if let Some((alias, digest)) = line.split_once('\t') {
1462 map.insert(alias.to_string(), digest.to_key());
1463 }
1464 }
1465 Ok(map)
1466}
1467
1468pub(crate) fn write_alias_namespace(path: &Path, aliases: &HashMap<String, DigestKey>) -> Result<()> {
1474 if aliases.is_empty() {
1475 match fs::remove_file(path) {
1476 Ok(()) => Ok(()),
1477 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1478 Err(e) => Err(e).with_context(|| format!("removing empty {}", path.display())),
1479 }
1480 } else {
1481 let sorted: BTreeMap<&String, &DigestKey> = aliases.iter().collect();
1482 atomic_write(path, |w| {
1483 for (alias, digest) in sorted {
1484 writeln!(w, "{}\t{}", alias, key_to_digest_string(digest))?;
1485 }
1486 Ok(())
1487 })
1488 }
1489}