use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use crate::hash::ContentHash;
mod fs;
pub mod published;
mod remote;
mod tiered;
pub use fs::FsStore;
pub use tiered::{StoreStats, Survey, TieredStore};
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ObjectKey {
pub hash: ContentHash,
pub suffix: String,
}
impl ObjectKey {
#[must_use]
pub fn new(hash: ContentHash, suffix: &str) -> Self {
Self {
hash,
suffix: suffix.to_owned(),
}
}
#[must_use]
pub fn of_bytes(bytes: &[u8], suffix: &str) -> Self {
Self::new(ContentHash::of_bytes(bytes), suffix)
}
}
impl fmt::Display for ObjectKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.hash.to_hex(), self.suffix)
}
}
#[derive(Debug)]
pub enum StoreError {
Io {
path: PathBuf,
source: io::Error,
},
Mismatch {
expected: ContentHash,
found: ContentHash,
at: PathBuf,
},
Impostor {
at: String,
claims: String,
},
Unsupported {
url: String,
reason: String,
},
}
impl fmt::Display for StoreError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::Mismatch {
expected,
found,
at,
} => write!(
f,
"the object at {} is not what its name says: it is named for \
{} but its contents hash to {}. It has been changed since it \
was stored, so it is refused rather than served",
at.display(),
expected.to_hex(),
found.to_hex()
),
Self::Impostor { at, claims } => write!(
f,
"the row at {at} is not the row it was asked for: it is {claims}. \
It has been refused rather than believed"
),
Self::Unsupported { url, reason } => write!(f, "{url}: {reason}"),
}
}
}
impl std::error::Error for StoreError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Mismatch { .. } | Self::Impostor { .. } | Self::Unsupported { .. } => None,
}
}
}
pub trait BlobStore {
fn has(&self, key: &ObjectKey) -> Result<bool, StoreError>;
fn get(&self, key: &ObjectKey) -> Result<Option<Vec<u8>>, StoreError>;
fn put(&self, key: &ObjectKey, bytes: &[u8]) -> Result<(), StoreError>;
fn put_file(&self, staged: &Path, suffix: &str) -> Result<ObjectKey, StoreError>;
fn put_file_as(&self, staged: &Path, key: &ObjectKey) -> Result<(), StoreError>;
fn put_from_path(&self, key: &ObjectKey, from: &Path) -> Result<(), StoreError> {
let bytes = std::fs::read(from).map_err(|source| StoreError::Io {
path: from.to_path_buf(),
source,
})?;
self.put(key, &bytes)
}
fn local_path(&self, key: &ObjectKey) -> Result<Option<PathBuf>, StoreError>;
fn get_row(&self, key: &ObjectKey) -> Result<Option<Vec<u8>>, StoreError> {
if key.suffix != ROW_SUFFIX {
return self.checked_get(key);
}
self.get(key)
}
fn checked_get(&self, key: &ObjectKey) -> Result<Option<Vec<u8>>, StoreError> {
let Some(bytes) = self.get(key)? else {
return Ok(None);
};
let found = ContentHash::of_bytes(&bytes);
if found == key.hash {
return Ok(Some(bytes));
}
Err(StoreError::Mismatch {
expected: key.hash,
found,
at: self
.local_path(key)?
.unwrap_or_else(|| PathBuf::from(key.to_string())),
})
}
}
pub const ROW_SUFFIX: &str = ".row";
pub const STORE_VARIABLE: &str = "LIGASE_STORE";
pub const SCHEMES: [&str; 4] = ["file", "s3", "gs", "az"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Backend {
Local(PathBuf),
Remote {
url: String,
},
}
impl Backend {
pub fn parse(url: &str) -> Result<Self, StoreError> {
let unsupported = |reason: &str| StoreError::Unsupported {
url: url.to_owned(),
reason: reason.to_owned(),
};
let Some((scheme, rest)) = url.split_once("://") else {
return Err(unsupported(&format!(
"a store URL needs a scheme, one of {}",
SCHEMES.join(", ")
)));
};
if rest.is_empty() {
return Err(unsupported("a store URL needs something after its scheme"));
}
if !SCHEMES.contains(&scheme) {
return Err(unsupported(&format!(
"`{scheme}` is not a store Ligase knows; it reads {}",
SCHEMES.join(", ")
)));
}
if scheme == "file" {
return Ok(Self::Local(PathBuf::from(rest)));
}
Ok(Self::Remote {
url: url.to_owned(),
})
}
}
#[must_use]
pub const fn supports_remote() -> bool {
cfg!(feature = "remote-store")
}
#[must_use]
pub fn configured() -> Option<String> {
std::env::var(STORE_VARIABLE)
.ok()
.filter(|url| !url.trim().is_empty())
}
#[must_use]
pub fn suffix_of(path: &Path) -> String {
path.file_name()
.map(|name| name.to_string_lossy())
.and_then(|name| name.find('.').map(|at| name[at..].to_owned()))
.unwrap_or_default()
}