Skip to main content

storage_kit/backend/
local.rs

1//! `LocalBackend` — the default, no-network backend. A thin async wrapper
2//! over [`crate::store::PartitionStore`]; all packfile/fragmentation logic
3//! lives once, in [`crate::store`]/[`crate::fragment`], and this module
4//! never reimplements it.
5
6use crate::addressing::{Hash, PartitionId};
7use crate::backend::AsyncImmutableStore;
8use crate::error::StorageError;
9use crate::store::{ImmutableStore, PartitionStore};
10use async_trait::async_trait;
11use std::path::Path;
12use std::sync::{Arc, Mutex};
13
14pub struct LocalBackend {
15    store: Arc<Mutex<PartitionStore>>,
16    partition_id: PartitionId,
17}
18
19impl LocalBackend {
20    pub fn open(store_root: &Path, partition_id: PartitionId) -> Result<Self, StorageError> {
21        let store = PartitionStore::open(store_root, partition_id)?;
22        Ok(LocalBackend {
23            store: Arc::new(Mutex::new(store)),
24            partition_id,
25        })
26    }
27}
28
29fn join_err<T>(e: tokio::task::JoinError) -> Result<T, StorageError> {
30    Err(StorageError::Backend(format!(
31        "local backend task panicked: {e}"
32    )))
33}
34
35#[async_trait]
36impl AsyncImmutableStore for LocalBackend {
37    async fn get(&self, hash: &Hash) -> Result<Vec<u8>, StorageError> {
38        let store = self.store.clone();
39        let hash = *hash;
40        match tokio::task::spawn_blocking(move || {
41            let store = store.lock().expect("local backend mutex poisoned");
42            store.get(&hash)
43        })
44        .await
45        {
46            Ok(result) => result,
47            Err(e) => join_err(e),
48        }
49    }
50
51    async fn put(&self, data: &[u8]) -> Result<Hash, StorageError> {
52        let store = self.store.clone();
53        let data = data.to_vec();
54        match tokio::task::spawn_blocking(move || {
55            let mut store = store.lock().expect("local backend mutex poisoned");
56            store.put(&data)
57        })
58        .await
59        {
60            Ok(result) => result,
61            Err(e) => join_err(e),
62        }
63    }
64
65    async fn has(&self, hash: &Hash) -> Result<bool, StorageError> {
66        let store = self.store.clone();
67        let hash = *hash;
68        match tokio::task::spawn_blocking(move || {
69            let store = store.lock().expect("local backend mutex poisoned");
70            store.has(&hash)
71        })
72        .await
73        {
74            Ok(result) => Ok(result),
75            Err(e) => join_err(e),
76        }
77    }
78
79    fn partition_id(&self) -> PartitionId {
80        self.partition_id
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::partition::{EncryptionMode, PartitionSpec, RetentionClass, Subject, SubjectKind};
88    use tempfile::tempdir;
89
90    #[tokio::test]
91    async fn put_then_get_roundtrips() {
92        let dir = tempdir().unwrap();
93        let partition_id = PartitionId::for_person("storage-kit-local-test");
94        let spec = PartitionSpec {
95            subject: Subject {
96                kind: SubjectKind::Person,
97                id: "storage-kit-local-test".to_string(),
98            },
99            retention_class: RetentionClass::Standard,
100            encryption_mode: EncryptionMode::Plaintext,
101            label: None,
102        };
103        // `LocalBackend::open` wraps `PartitionStore::open`, which no
104        // longer provisions on first use — provision first, same as any
105        // other caller now must.
106        PartitionStore::create(dir.path(), partition_id, spec).unwrap();
107        let backend = LocalBackend::open(dir.path(), partition_id).unwrap();
108
109        let hash = backend.put(b"local backend round trip").await.unwrap();
110        assert!(backend.has(&hash).await.unwrap());
111        let back = backend.get(&hash).await.unwrap();
112        assert_eq!(back, b"local backend round trip");
113        assert_eq!(backend.partition_id(), partition_id);
114    }
115}