use anyhow::Result;
use bytes::Bytes;
use opendal::{services::Memory, ErrorKind, Operator};
use openvet_common::rust::Checksum;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct Objects {
operator: Operator,
}
pub enum Config {
Filesystem(FilesystemConfig),
}
pub struct FilesystemConfig {
pub path: PathBuf,
}
impl Objects {
pub async fn new(config: &Config) -> Result<Self> {
todo!()
}
pub async fn memory() -> Result<Self> {
let builder = Memory::default();
let operator = Operator::new(builder)?.finish();
Ok(Self { operator })
}
pub async fn read(&self, checksum: Checksum) -> Result<Option<Bytes>> {
match self.operator.read(&checksum.to_string()).await {
Ok(data) => Ok(Some(data.to_bytes())),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error.into()),
}
}
pub async fn write(&self, data: Bytes) -> Result<Checksum> {
let checksum = Checksum::sha2_256(&data);
self.operator.write(&checksum.to_string(), data).await?;
Ok(checksum)
}
pub async fn delete(&self, checksum: Checksum) -> Result<()> {
self.operator.delete(&checksum.to_string()).await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use test_strategy::*;
#[proptest(async = "tokio")]
async fn can_write(data: Vec<Vec<u8>>) {
let objects = Objects::memory().await.unwrap();
for bytes in data {
let bytes: Bytes = bytes.into();
let checksum = objects.write(bytes.clone()).await.unwrap();
assert_eq!(checksum, Checksum::sha2_256(&bytes));
let returned = objects.read(checksum).await.unwrap().unwrap();
assert_eq!(returned, bytes);
}
}
}