1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//! # Object storage
//!
//! This module handles object storage. Typically, object storage is handled by an S3-compatible
//! API, but for testing and development purposes, filesystem-backed and memory-backed storage
//! is also implemented.
//!
//! Object storage is implemented as a content-addressable store, meaning that the storage keys are
//! hashes of the content.
//!
//! The object storage functionality can use both compression and encryption to ensure that the
//! storage provider does not need to be trusted.

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 struct Object(Bytes);
//pub struct Compressed(Bytes);
//pub struct Encrypted(Bytes);

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);
        }
    }
}