#[cfg(not(feature = "remote-store"))]
use super::{BlobStore, StoreError};
#[cfg(not(feature = "remote-store"))]
const WITHOUT: &str = "this build of Ligase has no remote-store support. \
Install `ligase-bio[remote-store]` from source, or build the engine \
with `--features remote-store`. A `file://` store needs neither and \
works in every build";
#[cfg(not(feature = "remote-store"))]
pub fn open(url: &str) -> Result<Box<dyn BlobStore + Send + Sync>, StoreError> {
Err(StoreError::Unsupported {
url: url.to_owned(),
reason: WITHOUT.to_owned(),
})
}
#[cfg(feature = "remote-store")]
pub use enabled::open;
#[cfg(feature = "remote-store")]
mod enabled {
use std::path::Path;
use object_store::path::Path as StorePath;
use object_store::{ObjectStore, ObjectStoreExt as _};
use super::super::{BlobStore, ObjectKey, StoreError};
const MULTIPART_ABOVE: u64 = 16 * 1024 * 1024;
const CHUNK: usize = 8 * 1024 * 1024;
struct Bucket {
store: Box<dyn ObjectStore>,
prefix: StorePath,
runtime: tokio::runtime::Runtime,
url: String,
}
pub fn open(url: &str) -> Result<Box<dyn BlobStore + Send + Sync>, StoreError> {
let unsupported = |reason: String| StoreError::Unsupported {
url: url.to_owned(),
reason,
};
let parsed = url::Url::parse(url).map_err(|error| unsupported(error.to_string()))?;
let (store, prefix) =
object_store::parse_url_opts(&parsed, std::env::vars()).map_err(|error| {
unsupported(format!(
"{error}. Credentials and endpoint come from the \
provider's own environment; Ligase reads none of its \
own. A named AWS profile is not read from \
~/.aws/credentials: export it first with \
`aws configure export-credentials --format env`"
))
})?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.map_err(|error| unsupported(error.to_string()))?;
Ok(Box::new(Bucket {
store,
prefix,
runtime,
url: url.to_owned(),
}))
}
impl Bucket {
fn path_of(&self, key: &ObjectKey) -> StorePath {
let hex = key.hash.to_hex();
self.prefix
.clone()
.join(&hex[..2])
.join(format!("{}{}", &hex[2..], key.suffix))
}
fn io(&self, key: &ObjectKey, error: &dyn std::fmt::Display) -> StoreError {
StoreError::Io {
path: std::path::PathBuf::from(format!("{}/{}", self.url, self.path_of(key))),
source: std::io::Error::other(error.to_string()),
}
}
}
impl BlobStore for Bucket {
fn has(&self, key: &ObjectKey) -> Result<bool, StoreError> {
let path = self.path_of(key);
match self.runtime.block_on(self.store.head(&path)) {
Ok(_) => Ok(true),
Err(object_store::Error::NotFound { .. }) => Ok(false),
Err(error) => Err(self.io(key, &error)),
}
}
fn get(&self, key: &ObjectKey) -> Result<Option<Vec<u8>>, StoreError> {
let path = self.path_of(key);
let read = self
.runtime
.block_on(async { self.store.get(&path).await?.bytes().await });
match read {
Ok(bytes) => Ok(Some(bytes.to_vec())),
Err(object_store::Error::NotFound { .. }) => Ok(None),
Err(error) => Err(self.io(key, &error)),
}
}
fn put(&self, key: &ObjectKey, bytes: &[u8]) -> Result<(), StoreError> {
let path = self.path_of(key);
let payload = object_store::PutPayload::from(bytes.to_vec());
self.runtime
.block_on(self.store.put(&path, payload))
.map(|_| ())
.map_err(|error| self.io(key, &error))
}
fn put_from_path(&self, key: &ObjectKey, from: &Path) -> Result<(), StoreError> {
use std::io::Read as _;
let length = std::fs::metadata(from)
.map_err(|source| StoreError::Io {
path: from.to_path_buf(),
source,
})?
.len();
if length <= MULTIPART_ABOVE {
let bytes = std::fs::read(from).map_err(|source| StoreError::Io {
path: from.to_path_buf(),
source,
})?;
return self.put(key, &bytes);
}
let path = self.path_of(key);
let mut file = std::fs::File::open(from).map_err(|source| StoreError::Io {
path: from.to_path_buf(),
source,
})?;
let mut upload = self
.runtime
.block_on(self.store.put_multipart(&path))
.map_err(|error| self.io(key, &error))?;
let mut buffer = vec![0_u8; CHUNK];
loop {
let read = file.read(&mut buffer).map_err(|source| StoreError::Io {
path: from.to_path_buf(),
source,
})?;
if read == 0 {
break;
}
let part = object_store::PutPayload::from(buffer[..read].to_vec());
self.runtime
.block_on(upload.put_part(part))
.map_err(|error| self.io(key, &error))?;
}
self.runtime
.block_on(upload.complete())
.map(|_| ())
.map_err(|error| self.io(key, &error))
}
fn put_file(&self, staged: &Path, suffix: &str) -> Result<ObjectKey, StoreError> {
let hash =
crate::hash::ContentHash::of_file(staged).map_err(|source| StoreError::Io {
path: staged.to_path_buf(),
source,
})?;
let key = ObjectKey::new(hash, suffix);
self.put_from_path(&key, staged)?;
std::fs::remove_file(staged).map_err(|source| StoreError::Io {
path: staged.to_path_buf(),
source,
})?;
Ok(key)
}
fn put_file_as(&self, staged: &Path, key: &ObjectKey) -> Result<(), StoreError> {
let found =
crate::hash::ContentHash::of_file(staged).map_err(|source| StoreError::Io {
path: staged.to_path_buf(),
source,
})?;
if found != key.hash {
return Err(StoreError::Mismatch {
expected: key.hash,
found,
at: staged.to_path_buf(),
});
}
self.put_from_path(key, staged)?;
std::fs::remove_file(staged).map_err(|source| StoreError::Io {
path: staged.to_path_buf(),
source,
})
}
fn local_path(&self, _: &ObjectKey) -> Result<Option<std::path::PathBuf>, StoreError> {
Ok(None)
}
}
}