use super::*;
use super::readonly::{PendingChanges, ReadonlyRefgetStore};
use super::alias::AliasKind;
use super::atomic::{atomic_write, atomic_write_bytes};
use super::fhr_metadata;
use super::lock::StoreLock;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::OsStr;
use indexmap::IndexMap;
use std::fs::{self, File, create_dir_all};
use std::io::BufRead;
use std::path::Path;
use anyhow::{Context, Result};
use sha2::{Sha256, Digest};
use crate::collection::{
SequenceCollectionRecordExt, SequenceMetadataExt,
read_rgsi_file,
};
use crate::digest::{
SequenceCollectionMetadata, SequenceCollectionRecord, SequenceMetadata, SequenceRecord,
parse_rgci_line, parse_rgsi_line,
};
use crate::hashkeyable::{HashKeyable, key_to_digest_string};
use chrono::Utc;
const RGSI_HEADER: &str = "#name\tlength\talphabet\tsha512t24u\tmd5\tdescription";
const RGCI_HEADER: &str = "#digest\tn_sequences\tnames_digest\tsequences_digest\tlengths_digest\tname_length_pairs_digest\tsorted_name_length_pairs_digest\tsorted_sequences_digest";
fn remove_cached_artifact(path: &Path) -> Result<()> {
match fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_dir() => fs::remove_dir_all(path)
.with_context(|| format!("Failed to remove cached directory {}", path.display())),
Ok(_) => fs::remove_file(path)
.with_context(|| format!("Failed to remove cached file {}", path.display())),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error)
.with_context(|| format!("Failed to inspect cached artifact {}", path.display())),
}
}
fn remove_cached_indexes<'a, I>(cache_path: &Path, paths: I) -> Result<()>
where
I: IntoIterator<Item = &'a str>,
{
let mut seen = HashSet::new();
for relative_path in paths {
ReadonlyRefgetStore::sanitize_relative_path(relative_path)?;
let full_path = cache_path.join(relative_path);
if seen.insert(full_path.clone()) {
remove_cached_artifact(&full_path)?;
}
}
Ok(())
}
fn validate_remote_manifest_paths(metadata: &StoreMetadata) -> Result<()> {
ReadonlyRefgetStore::sanitize_relative_path(&metadata.seqdata_path_template)?;
ReadonlyRefgetStore::sanitize_relative_path(&metadata.collections_path_template)?;
ReadonlyRefgetStore::sanitize_relative_path(&metadata.sequence_index)?;
if let Some(ref collection_index) = metadata.collection_index {
ReadonlyRefgetStore::sanitize_relative_path(collection_index)?;
}
Ok(())
}
impl ReadonlyRefgetStore {
pub(crate) fn write_sequence_to_disk_single(
&self,
metadata: &SequenceMetadata,
sequence: &[u8],
) -> Result<()> {
let template = self
.seqdata_path_template
.as_ref()
.context("seqdata_path_template not set")?;
let local_path = self.local_path.as_ref().context("local_path not set")?;
let seq_file_path = Self::expand_template(&metadata.sha512t24u, template);
let full_path = local_path.join(&seq_file_path);
if let Some(parent) = full_path.parent() {
create_dir_all(parent)?;
}
super::atomic::publish_bytes_nosync(&full_path, sequence)
}
#[cfg_attr(not(feature = "filesystem"), allow(dead_code))]
pub(crate) fn write_seq_bytes_to_full_path(
full_path: &Path,
sequence: &[u8],
created_shards: &std::sync::Mutex<HashSet<std::path::PathBuf>>,
) -> Result<()> {
if let Some(parent) = full_path.parent() {
let known = {
let guard = created_shards.lock().unwrap();
guard.contains(parent)
};
if !known {
create_dir_all(parent)?;
created_shards.lock().unwrap().insert(parent.to_path_buf());
}
}
super::atomic::publish_bytes_nosync(full_path, sequence)
}
pub(crate) fn write_collection_to_disk_single(&self, record: &SequenceCollectionRecord) -> Result<()> {
let local_path = self.local_path.as_ref().context("local_path not set")?;
let coll_file_path = format!("collections/{}.rgsi", record.metadata().digest);
let full_path = local_path.join(&coll_file_path);
if let Some(parent) = full_path.parent() {
create_dir_all(parent)?;
}
record.write_collection_rgsi(&full_path)?;
Ok(())
}
pub(crate) fn acquire_commit_lock(&self, operation: &str) -> Result<Option<StoreLock>> {
if self.commit_lock.is_some() {
return Ok(None);
}
let Some(local_path) = self.local_path.as_ref() else {
return Ok(None);
};
Ok(Some(StoreLock::acquire(
local_path,
operation,
self.lock_options.clone(),
)?))
}
pub(crate) fn write_index_files(&self) -> Result<()> {
let local_path = self
.local_path
.as_ref()
.context("local_path not set")?
.clone();
let template = self
.seqdata_path_template
.as_ref()
.context("seqdata_path_template not set")?
.clone();
let _guard = self.acquire_commit_lock("write_index_files")?;
let pending = self.pending.lock().unwrap().clone();
let sequence_index_path = local_path.join("sequences.rgsi");
let collection_index_path = local_path.join("collections.rgci");
let mut sequences = read_sequences_rgsi_rows(&sequence_index_path)?;
self.apply_pending_sequence_rows(&mut sequences, &pending);
let mut collections = read_collections_rgci_rows(&collection_index_path)?;
self.apply_pending_collection_rows(&mut collections, &pending);
for coll_key in &pending.collections {
let Some(name_map) = self.name_lookup.get(coll_key) else {
continue;
};
if let Some(missing) = name_map.values().find(|k| !sequences.contains_key(*k)) {
anyhow::bail!(
"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.",
key_to_digest_string(coll_key),
key_to_digest_string(missing),
);
}
}
write_sequences_rgsi_rows(&sequence_index_path, &sequences)?;
write_collections_rgci_rows(&collection_index_path, &collections)?;
self.commit_all_alias_namespaces(&local_path, &pending)?;
let logical_bytes: u64 = sequences
.values()
.map(|m| m.disk_size(&self.mode) as u64)
.sum();
let mut metadata = self.manifest_base(&local_path, &template)?;
metadata.sequences_digest = Self::sha256_file(&sequence_index_path).ok();
metadata.collections_digest = Self::sha256_file(&collection_index_path).ok();
metadata.aliases_digest = self.compute_aliases_digest();
metadata.fhr_digest = self.compute_fhr_digest();
metadata.logical_sequence_bytes = Some(logical_bytes);
let (seq_ns, coll_ns) = published_alias_namespaces(&local_path);
metadata.sequence_alias_namespaces = seq_ns;
metadata.collection_alias_namespaces = coll_ns;
write_manifest(&local_path, &metadata)?;
self.pending.lock().unwrap().clear_matching(&pending);
Ok(())
}
fn apply_pending_sequence_rows(
&self,
rows: &mut HashMap<DigestKey, SequenceMetadata>,
pending: &PendingChanges,
) {
for key in &pending.sequences {
if let Some(record) = self.sequence_store.get(key) {
rows.entry(*key)
.or_insert_with(|| record.metadata().clone());
}
}
for key in &pending.removed_sequences {
rows.remove(key);
}
}
fn apply_pending_collection_rows(
&self,
rows: &mut HashMap<DigestKey, SequenceCollectionMetadata>,
pending: &PendingChanges,
) {
let ancillary_count = |m: &SequenceCollectionMetadata| {
m.name_length_pairs_digest.is_some() as u8
+ m.sorted_name_length_pairs_digest.is_some() as u8
+ m.sorted_sequences_digest.is_some() as u8
};
for key in &pending.collections {
let Some(record) = self.collections.get(key) else {
continue;
};
let mine = record.metadata();
match rows.get(key) {
Some(existing) if ancillary_count(existing) >= ancillary_count(mine) => {}
_ => {
rows.insert(*key, mine.clone());
}
}
}
for key in &pending.removed_collections {
rows.remove(key);
}
}
fn manifest_base(&self, local_path: &Path, seqdata_template: &str) -> Result<StoreMetadata> {
let now = Utc::now().to_rfc3339();
let existing = read_manifest(local_path)?;
let created_at = existing
.as_ref()
.map(|m| m.created_at.clone())
.unwrap_or_else(|| now.clone());
Ok(StoreMetadata {
version: 1,
seqdata_path_template: seqdata_template.to_string(),
collections_path_template: "collections/%s.rgsi".to_string(),
sequence_index: "sequences.rgsi".to_string(),
collection_index: Some("collections.rgci".to_string()),
mode: self.mode,
created_at,
ancillary_digests: self.ancillary_digests,
attribute_index: self.attribute_index,
sequence_alias_namespaces: self.aliases.sequence_namespaces(),
collection_alias_namespaces: self.aliases.collection_namespaces(),
modified: Some(now),
collections_digest: None,
sequences_digest: None,
aliases_digest: None,
fhr_digest: None,
logical_sequence_bytes: None,
})
}
pub(crate) fn write_rgstore_json(&self, dir: &Path, seqdata_template: &str) -> Result<()> {
let now = Utc::now().to_rfc3339();
let metadata = StoreMetadata {
version: 1,
seqdata_path_template: seqdata_template.to_string(),
collections_path_template: "collections/%s.rgsi".to_string(),
sequence_index: "sequences.rgsi".to_string(),
collection_index: Some("collections.rgci".to_string()),
mode: self.mode,
created_at: now.clone(),
ancillary_digests: self.ancillary_digests,
attribute_index: self.attribute_index,
sequence_alias_namespaces: self.aliases.sequence_namespaces(),
collection_alias_namespaces: self.aliases.collection_namespaces(),
modified: Some(now),
collections_digest: None,
sequences_digest: None,
aliases_digest: None,
fhr_digest: None,
logical_sequence_bytes: Some(self.logical_sequence_bytes() as u64),
};
write_manifest(dir, &metadata)
}
pub(crate) fn refresh_manifest_alias_namespaces(&self) -> Result<()> {
let local_path = match self.local_path.as_ref() {
Some(p) => p,
None => return Ok(()),
};
let Some(mut metadata) = read_manifest(local_path)? else {
return Ok(());
};
let (seq_ns, coll_ns) = published_alias_namespaces(local_path);
metadata.sequence_alias_namespaces = seq_ns;
metadata.collection_alias_namespaces = coll_ns;
metadata.aliases_digest = self.compute_aliases_digest();
metadata.modified = Some(Utc::now().to_rfc3339());
write_manifest(local_path, &metadata)
}
pub(crate) fn write_collections_rgci<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
let rows: HashMap<DigestKey, SequenceCollectionMetadata> = self
.collections
.iter()
.map(|(k, v)| (*k, v.metadata().clone()))
.collect();
write_collections_rgci_rows(file_path.as_ref(), &rows)
}
pub fn write_sequences_rgsi<P: AsRef<Path>>(&self, file_path: P) -> Result<()> {
let rows: HashMap<DigestKey, SequenceMetadata> = self
.sequence_store
.iter()
.map(|(k, v)| (*k, v.metadata().clone()))
.collect();
write_sequences_rgsi_rows(file_path.as_ref(), &rows)
}
fn commit_all_alias_namespaces(
&self,
local_path: &Path,
pending: &PendingChanges,
) -> Result<()> {
let aliases_dir = local_path.join("aliases");
for kind in [AliasKind::Sequence, AliasKind::Collection] {
for ns in pending.touched_alias_namespaces(kind) {
self.commit_alias_namespace(&aliases_dir, kind, &ns, pending)?;
}
}
Ok(())
}
pub(crate) fn commit_alias_namespace(
&self,
aliases_dir: &Path,
kind: AliasKind,
namespace: &str,
pending: &PendingChanges,
) -> Result<()> {
let tsv_path = aliases_dir.join(kind.subdir()).join(format!("{}.tsv", namespace));
let mut merged = read_alias_tsv(&tsv_path)?;
for (k, ns, alias) in &pending.aliases {
if *k != kind || ns != namespace {
continue;
}
let Some(digest) = self.aliases.resolve(kind, namespace, alias) else {
continue;
};
match merged.get(alias) {
Some(existing) if *existing != digest => {
if !self.force_alias && !pending.is_forced(kind, namespace, alias) {
return Err(anyhow::anyhow!(
"alias conflict in {} namespace '{}': '{}' is already published as {} \
on disk but this writer has it as {}. Another writer bound it first. \
Re-run with force-alias enabled (CLI: --force-alias) to overwrite the \
published value.",
kind.subdir(),
namespace,
alias,
key_to_digest_string(existing),
key_to_digest_string(&digest),
));
}
merged.insert(alias.clone(), digest);
}
Some(_) => {}
None => {
merged.insert(alias.clone(), digest);
}
}
}
for (k, ns, alias) in &pending.removed_aliases {
if *k == kind && ns == namespace {
merged.remove(alias);
}
}
write_alias_namespace(&tsv_path, &merged)
}
pub(crate) fn live_sequence_digests_from_disk(
&self,
exclude: &DigestKey,
) -> Result<HashSet<DigestKey>> {
let local_path = self.local_path.as_ref().context("local_path not set")?;
let pending = self.pending.lock().unwrap().clone();
let index_path = local_path.join("collections.rgci");
let mut collections = read_collections_rgci_rows(&index_path)?;
self.apply_pending_collection_rows(&mut collections, &pending);
let mut live = HashSet::new();
for (key, meta) in &collections {
if key == exclude {
continue;
}
if let Some(record) = self.collections.get(key) {
if let Some(sequences) = record.sequences() {
for seq in sequences {
live.insert(seq.metadata().sha512t24u.to_key());
}
continue;
}
}
let rgsi_path = local_path.join(format!("collections/{}.rgsi", meta.digest));
let collection = read_rgsi_file(&rgsi_path).with_context(|| {
format!(
"refusing to remove orphan sequences: collection {} is listed in \
collections.rgci but {} could not be read. Treating that as \
'references nothing' would delete live sequence data.",
meta.digest,
rgsi_path.display()
)
})?;
for seq in &collection.sequences {
live.insert(seq.metadata().sha512t24u.to_key());
}
}
Ok(live)
}
pub(crate) fn collection_sequence_digests(&self, digest: &str) -> Result<Vec<DigestKey>> {
let key = digest.to_key();
if let Some(record) = self.collections.get(&key) {
if let Some(sequences) = record.sequences() {
return Ok(sequences
.iter()
.map(|s| s.metadata().sha512t24u.to_key())
.collect());
}
}
if let Some(local_path) = self.local_path.as_ref() {
let rgsi_path = local_path.join(format!("collections/{}.rgsi", digest));
if rgsi_path.exists() {
let collection = read_rgsi_file(&rgsi_path)?;
return Ok(collection
.sequences
.iter()
.map(|s| s.metadata().sha512t24u.to_key())
.collect());
}
}
Ok(self
.name_lookup
.get(&key)
.map(|m| m.values().cloned().collect())
.unwrap_or_default())
}
pub fn store_metadata(&self) -> Result<HashMap<String, String>> {
let local_path = self.local_path.as_ref().context("local_path not set")?;
let json = fs::read_to_string(local_path.join("rgstore.json"))
.context("Failed to read rgstore.json")?;
let metadata: StoreMetadata =
serde_json::from_str(&json).context("Failed to parse store metadata")?;
let mut map = HashMap::new();
if let Some(v) = metadata.modified { map.insert("modified".to_string(), v); }
if let Some(v) = metadata.collections_digest { map.insert("collections_digest".to_string(), v); }
if let Some(v) = metadata.sequences_digest { map.insert("sequences_digest".to_string(), v); }
if let Some(v) = metadata.aliases_digest { map.insert("aliases_digest".to_string(), v); }
if let Some(v) = metadata.fhr_digest { map.insert("fhr_digest".to_string(), v); }
if let Some(v) = metadata.logical_sequence_bytes { map.insert("logical_sequence_bytes".to_string(), v.to_string()); }
Ok(map)
}
fn sha256_file(path: &Path) -> Result<String> {
let bytes = fs::read(path)?;
let hash = Sha256::digest(&bytes);
Ok(format!("{:x}", hash))
}
fn compute_aliases_digest(&self) -> Option<String> {
let local_path = self.local_path.as_ref()?;
let aliases_dir = local_path.join("aliases");
if !aliases_dir.exists() { return None; }
let mut paths: Vec<_> = Vec::new();
for subdir in &["sequences", "collections"] {
let sub = aliases_dir.join(subdir);
if sub.exists() {
if let Ok(entries) = fs::read_dir(&sub) {
for entry in entries.filter_map(|e| e.ok()) {
let p = entry.path();
if p.extension().map_or(false, |e| e == "tsv") {
paths.push(p);
}
}
}
}
}
if paths.is_empty() { return None; }
paths.sort();
let mut hasher = Sha256::new();
for path in &paths {
hasher.update(fs::read(path).ok()?);
}
Some(format!("{:x}", hasher.finalize()))
}
fn compute_fhr_digest(&self) -> Option<String> {
let local_path = self.local_path.as_ref()?;
let fhr_dir = local_path.join("fhr");
if !fhr_dir.exists() { return None; }
let mut paths: Vec<_> = fs::read_dir(&fhr_dir).ok()?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.map_or(false, |n| n.ends_with(super::fhr_metadata::SIDECAR_EXTENSION))
})
.collect();
if paths.is_empty() { return None; }
paths.sort();
let mut hasher = Sha256::new();
for path in paths {
hasher.update(fs::read(&path).ok()?);
}
Some(format!("{:x}", hasher.finalize()))
}
pub(crate) fn open_local<P: AsRef<Path>>(path: P) -> Result<Self> {
let root_path = path.as_ref();
let index_path = root_path.join("rgstore.json");
let json = fs::read_to_string(&index_path).context(format!(
"Failed to read rgstore.json from {}",
index_path.display()
))?;
let metadata: StoreMetadata =
serde_json::from_str(&json).context("Failed to parse store metadata")?;
Self::sanitize_relative_path(&metadata.seqdata_path_template)?;
Self::sanitize_relative_path(&metadata.sequence_index)?;
if let Some(ref ci) = metadata.collection_index {
Self::sanitize_relative_path(ci)?;
}
let mut store = ReadonlyRefgetStore::new(metadata.mode);
store.local_path = Some(root_path.to_path_buf());
store.seqdata_path_template = Some(metadata.seqdata_path_template.clone());
store.persist_to_disk = true;
store.ancillary_digests = metadata.ancillary_digests;
store.attribute_index = metadata.attribute_index;
let sequence_index_path = root_path.join(&metadata.sequence_index);
if sequence_index_path.exists() {
Self::load_sequences_from_index(&mut store, &sequence_index_path)?;
}
if let Some(ref collection_index) = metadata.collection_index {
let collection_index_path = root_path.join(collection_index);
if collection_index_path.exists() {
Self::load_collection_stubs_from_rgci(&mut store, &collection_index_path)?;
}
}
if store.collections.is_empty() {
let collections_dir = root_path.join("collections");
Self::load_collections_from_directory(&mut store, &collections_dir)?;
}
let aliases_dir = root_path.join("aliases");
store.aliases.load_namespaces_from_dir(
&aliases_dir,
&metadata.sequence_alias_namespaces,
&metadata.collection_alias_namespaces,
)?;
store.available_sequence_alias_namespaces = metadata.sequence_alias_namespaces;
store.available_collection_alias_namespaces = metadata.collection_alias_namespaces;
store.fhr_metadata =
fhr_metadata::load_sidecars(&root_path.join("fhr"));
Ok(store)
}
pub(crate) fn open_remote<P: AsRef<Path>, S: AsRef<str>>(
cache_path: P,
remote_url: S,
) -> Result<Self> {
let cache_path = cache_path.as_ref();
let remote_url = remote_url.as_ref().to_string();
create_dir_all(cache_path)
.with_context(|| format!("Failed to create remote cache {}", cache_path.display()))?;
let origin_path = cache_path.join(".origin");
match fs::read_to_string(&origin_path) {
Ok(recorded) => {
let recorded = recorded.strip_suffix('\n').unwrap_or(&recorded);
if recorded != remote_url {
anyhow::bail!(
"Remote cache {} belongs to {}, not requested origin {}",
cache_path.display(),
recorded,
remote_url
);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let contents = format!("{}\n", remote_url);
atomic_write_bytes(&origin_path, contents.as_bytes()).with_context(|| {
format!("Failed to record remote cache origin in {}", origin_path.display())
})?;
}
Err(error) => {
return Err(error).with_context(|| {
format!("Failed to read remote cache origin {}", origin_path.display())
});
}
}
let manifest_path = cache_path.join("rgstore.json");
let cached_json = fs::read_to_string(&manifest_path).ok();
let old_metadata = cached_json
.as_deref()
.and_then(|json| serde_json::from_str::<StoreMetadata>(json).ok())
.filter(|metadata| validate_remote_manifest_paths(metadata).is_ok());
let json = match Self::fetch_file(
&Some(cache_path.to_path_buf()),
&Some(remote_url.clone()),
"rgstore.json",
false,
true,
) {
Ok(bytes) => {
String::from_utf8(bytes).context("Store metadata contains invalid UTF-8")?
}
Err(error) => match (&old_metadata, cached_json) {
(Some(_), Some(json)) => {
eprintln!(
"Could not refresh {} ({}); using cached store metadata",
remote_url, error
);
json
}
_ => return Err(error),
},
};
let metadata: StoreMetadata =
serde_json::from_str(&json).context("Failed to parse store metadata")?;
validate_remote_manifest_paths(&metadata)?;
let collections_changed = old_metadata
.as_ref()
.map(|old| old.collections_digest != metadata.collections_digest)
.unwrap_or(true);
let sequences_changed = old_metadata
.as_ref()
.map(|old| old.sequences_digest != metadata.sequences_digest)
.unwrap_or(true);
let aliases_changed = old_metadata
.as_ref()
.map(|old| old.aliases_digest != metadata.aliases_digest)
.unwrap_or(true);
let fhr_changed = old_metadata
.as_ref()
.map(|old| old.fhr_digest != metadata.fhr_digest)
.unwrap_or(true);
if collections_changed {
let old_index = old_metadata
.as_ref()
.and_then(|old| old.collection_index.as_deref())
.unwrap_or("collections.rgci");
let new_index = metadata.collection_index.as_deref().unwrap_or("collections.rgci");
remove_cached_indexes(cache_path, [old_index, new_index])?;
remove_cached_artifact(&cache_path.join("collections"))?;
}
if sequences_changed {
let old_index = old_metadata
.as_ref()
.map(|old| old.sequence_index.as_str())
.unwrap_or("sequences.rgsi");
remove_cached_indexes(cache_path, [old_index, metadata.sequence_index.as_str()])?;
}
if aliases_changed {
remove_cached_artifact(&cache_path.join("aliases"))?;
}
if fhr_changed {
remove_cached_artifact(&cache_path.join("fhr"))?;
}
atomic_write_bytes(&manifest_path, json.as_bytes())
.context("Failed to publish refreshed remote rgstore.json")?;
let mut store = ReadonlyRefgetStore::new(metadata.mode);
store.local_path = Some(cache_path.to_path_buf());
store.remote_source = Some(remote_url.clone());
store.seqdata_path_template = Some(metadata.seqdata_path_template.clone());
store.persist_to_disk = true;
store.ancillary_digests = metadata.ancillary_digests;
store.attribute_index = metadata.attribute_index;
store.sequence_index_loaded = false;
store.sequence_index_path = Some(metadata.sequence_index.clone());
if let Some(ref collection_index) = metadata.collection_index {
if let Ok(collection_index_data) = Self::fetch_file(
&Some(cache_path.to_path_buf()),
&Some(remote_url.clone()),
collection_index,
true,
false,
) {
let collection_index_str = String::from_utf8(collection_index_data)
.context("collection index contains invalid UTF-8")?;
Self::load_collection_stubs_from_reader(
&mut store,
collection_index_str.as_bytes(),
)?;
}
}
if store.collections.is_empty() {
let local_collections_dir = cache_path.join("collections");
create_dir_all(&local_collections_dir)?;
Self::load_collections_from_directory(&mut store, &local_collections_dir)?;
}
for namespace in &metadata.sequence_alias_namespaces {
let relative_path = format!("aliases/sequences/{}.tsv", namespace);
Self::fetch_file(
&store.local_path,
&store.remote_source,
&relative_path,
true,
false,
)
.with_context(|| {
format!(
"Remote {} advertised sequence alias namespace '{}' but it could not be loaded",
remote_url, namespace
)
})?;
}
for namespace in &metadata.collection_alias_namespaces {
let relative_path = format!("aliases/collections/{}.tsv", namespace);
Self::fetch_file(
&store.local_path,
&store.remote_source,
&relative_path,
true,
false,
)
.with_context(|| {
format!(
"Remote {} advertised collection alias namespace '{}' but it could not be loaded",
remote_url, namespace
)
})?;
}
store.aliases.load_namespaces_from_dir(
&cache_path.join("aliases"),
&metadata.sequence_alias_namespaces,
&metadata.collection_alias_namespaces,
)?;
store.available_sequence_alias_namespaces = metadata.sequence_alias_namespaces;
store.available_collection_alias_namespaces = metadata.collection_alias_namespaces;
Ok(store)
}
pub(crate) fn load_sequences_from_reader<R: BufRead>(store: &mut ReadonlyRefgetStore, reader: R) -> Result<()> {
for line in reader.lines() {
let line = line?;
if line.starts_with('#') {
continue;
}
if let Some(seq_metadata) = parse_rgsi_line(&line) {
let record = SequenceRecord::Stub(seq_metadata.clone());
let sha512_key = seq_metadata.sha512t24u.to_key();
let already_loaded = store
.sequence_store
.get(&sha512_key)
.is_some_and(|existing| existing.is_loaded());
if !already_loaded {
store.sequence_store.insert(sha512_key, record);
}
let md5_key = seq_metadata.md5.to_key();
store.md5_lookup.insert(md5_key, sha512_key);
}
}
Ok(())
}
pub(crate) fn load_sequences_from_index(store: &mut ReadonlyRefgetStore, index_path: &Path) -> Result<()> {
let file = std::fs::File::open(index_path)?;
let reader = std::io::BufReader::new(file);
Self::load_sequences_from_reader(store, reader)
}
pub(crate) fn load_collection_stubs_from_reader<R: BufRead>(
store: &mut ReadonlyRefgetStore,
reader: R,
) -> Result<()> {
for line in reader.lines() {
let line = line?;
if let Some(metadata) = parse_rgci_line(&line) {
let key = metadata.digest.to_key();
store
.collections
.insert(key, SequenceCollectionRecord::Stub(metadata));
}
}
Ok(())
}
pub(crate) fn load_collection_stubs_from_rgci(store: &mut ReadonlyRefgetStore, index_path: &Path) -> Result<()> {
let file = std::fs::File::open(index_path)?;
let reader = std::io::BufReader::new(file);
Self::load_collection_stubs_from_reader(store, reader)
}
pub(crate) fn load_collections_from_directory(
store: &mut ReadonlyRefgetStore,
collections_dir: &Path,
) -> Result<()> {
if !collections_dir.exists() {
return Ok(());
}
for entry in fs::read_dir(collections_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_file() && path.extension() == Some(OsStr::new("rgsi")) {
let collection = read_rgsi_file(&path)?;
let collection_digest = collection.metadata.digest.to_key();
let mut name_map = IndexMap::new();
for sequence_record in &collection.sequences {
let metadata = sequence_record.metadata();
name_map.insert(metadata.name.clone(), metadata.sha512t24u.to_key());
}
store.name_lookup.insert(collection_digest, name_map);
let record = SequenceCollectionRecord::from(collection);
store.collections.insert(collection_digest, record);
}
}
Ok(())
}
}
pub(crate) fn read_sequences_rgsi_rows(path: &Path) -> Result<HashMap<DigestKey, SequenceMetadata>> {
let mut rows = HashMap::new();
let file = match File::open(path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rows),
Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
};
for line in std::io::BufReader::new(file).lines() {
let line = line?;
if line.starts_with('#') {
continue;
}
if let Some(meta) = parse_rgsi_line(&line) {
rows.insert(meta.sha512t24u.to_key(), meta);
}
}
Ok(rows)
}
pub(crate) fn read_collections_rgci_rows(
path: &Path,
) -> Result<HashMap<DigestKey, SequenceCollectionMetadata>> {
let mut rows = HashMap::new();
let file = match File::open(path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rows),
Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
};
for line in std::io::BufReader::new(file).lines() {
let line = line?;
if let Some(meta) = parse_rgci_line(&line) {
rows.insert(meta.digest.to_key(), meta);
}
}
Ok(rows)
}
pub(crate) fn write_sequences_rgsi_rows(
path: &Path,
rows: &HashMap<DigestKey, SequenceMetadata>,
) -> Result<()> {
let mut entries: Vec<&SequenceMetadata> = rows.values().collect();
entries.sort_by(|a, b| a.sha512t24u.cmp(&b.sha512t24u));
atomic_write(path, |w| {
writeln!(w, "{}", RGSI_HEADER)?;
for meta in entries {
writeln!(
w,
"{}\t{}\t{}\t{}\t{}\t{}",
meta.name,
meta.length,
meta.alphabet,
meta.sha512t24u,
meta.md5,
meta.description.as_deref().unwrap_or("")
)?;
}
Ok(())
})
}
pub(crate) fn write_collections_rgci_rows(
path: &Path,
rows: &HashMap<DigestKey, SequenceCollectionMetadata>,
) -> Result<()> {
let mut entries: Vec<&SequenceCollectionMetadata> = rows.values().collect();
entries.sort_by(|a, b| a.digest.cmp(&b.digest));
atomic_write(path, |w| {
writeln!(w, "{}", RGCI_HEADER)?;
for meta in entries {
writeln!(
w,
"{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
meta.digest,
meta.n_sequences,
meta.names_digest,
meta.sequences_digest,
meta.lengths_digest,
meta.name_length_pairs_digest.as_deref().unwrap_or(""),
meta.sorted_name_length_pairs_digest.as_deref().unwrap_or(""),
meta.sorted_sequences_digest.as_deref().unwrap_or(""),
)?;
}
Ok(())
})
}
pub(crate) fn read_manifest(dir: &Path) -> Result<Option<StoreMetadata>> {
let path = dir.join("rgstore.json");
match fs::read_to_string(&path) {
Ok(json) => Ok(Some(serde_json::from_str(&json).with_context(|| {
format!("Failed to parse {}", path.display())
})?)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| format!("Failed to read {}", path.display())),
}
}
pub(crate) fn write_manifest(dir: &Path, metadata: &StoreMetadata) -> Result<()> {
let json = serde_json::to_string_pretty(metadata)
.context("Failed to serialize metadata to JSON")?;
super::atomic::atomic_write_bytes(&dir.join("rgstore.json"), json.as_bytes())
.context("Failed to write rgstore.json")
}
fn scan_alias_namespaces(dir: &Path) -> Vec<String> {
let Ok(entries) = fs::read_dir(dir) else {
return Vec::new();
};
entries
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.extension().and_then(|x| x.to_str()) == Some("tsv"))
.filter_map(|p| p.file_stem().and_then(|s| s.to_str()).map(String::from))
.collect()
}
pub(crate) fn published_alias_namespaces(local_path: &Path) -> (Vec<String>, Vec<String>) {
let aliases_dir = local_path.join("aliases");
let mut seq = scan_alias_namespaces(&aliases_dir.join(AliasKind::Sequence.subdir()));
let mut coll = scan_alias_namespaces(&aliases_dir.join(AliasKind::Collection.subdir()));
seq.sort();
coll.sort();
(seq, coll)
}
pub(crate) fn read_alias_tsv(path: &Path) -> Result<HashMap<String, DigestKey>> {
let mut map = HashMap::new();
let file = match File::open(path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(map),
Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
};
for line in std::io::BufReader::new(file).lines() {
let line = line?;
if line.starts_with('#') || line.trim().is_empty() {
continue;
}
if let Some((alias, digest)) = line.split_once('\t') {
map.insert(alias.to_string(), digest.to_key());
}
}
Ok(map)
}
pub(crate) fn write_alias_namespace(path: &Path, aliases: &HashMap<String, DigestKey>) -> Result<()> {
if aliases.is_empty() {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e).with_context(|| format!("removing empty {}", path.display())),
}
} else {
let sorted: BTreeMap<&String, &DigestKey> = aliases.iter().collect();
atomic_write(path, |w| {
for (alias, digest) in sorted {
writeln!(w, "{}\t{}", alias, key_to_digest_string(digest))?;
}
Ok(())
})
}
}