Skip to main content

hashtree_cli/
webrtc_store.rs

1use anyhow::{anyhow, Result};
2use hashtree_core::from_hex;
3use std::sync::Arc;
4
5use crate::blob_cache::BlobCache;
6use crate::storage::HashtreeStore;
7
8/// Daemon-side content adapter for the mesh router.
9///
10/// The storage engine stays a plain key/value reader. This wrapper owns
11/// request-level policy that is useful for network serving: a bounded cache for
12/// immutable chunk bodies and a short-lived negative cache for repeated misses.
13pub struct CachedWebRtcContentStore {
14    store: Arc<HashtreeStore>,
15    cache: BlobCache,
16}
17
18impl CachedWebRtcContentStore {
19    pub fn new(store: Arc<HashtreeStore>) -> Self {
20        Self {
21            store,
22            cache: BlobCache::from_env(),
23        }
24    }
25}
26
27impl crate::webrtc::ContentStore for CachedWebRtcContentStore {
28    fn get(&self, hash_hex: &str) -> Result<Option<Vec<u8>>> {
29        if let Some(data) = self.cache.get_body(hash_hex) {
30            return Ok(Some(data));
31        }
32        if let Some(None) = self.cache.get_size(hash_hex) {
33            return Ok(None);
34        }
35
36        let hash = from_hex(hash_hex).map_err(|e| anyhow!("Invalid hash: {}", e))?;
37        let data = self.store.get_chunk(&hash)?;
38        self.cache.put_size(
39            hash_hex.to_string(),
40            data.as_ref().map(|bytes| bytes.len() as u64),
41        );
42        if let Some(ref bytes) = data {
43            self.cache.put_body(hash_hex.to_string(), bytes);
44        }
45        Ok(data)
46    }
47}