Skip to main content

tilo_content/
memory.rs

1//! Content held in memory, for tests and headless tools.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::io::Read;
5use std::sync::RwLock;
6
7use crate::{
8    Collected, ContentBackend, ContentError, ContentLimits, ContentReader, Stored, hash_bytes,
9};
10
11pub struct MemoryBackend {
12    limits: ContentLimits,
13    inner: RwLock<State>,
14}
15
16#[derive(Default)]
17struct State {
18    bytes: usize,
19    entries: BTreeMap<String, std::sync::Arc<[u8]>>,
20}
21
22impl Default for MemoryBackend {
23    fn default() -> Self {
24        Self::new(ContentLimits::default())
25    }
26}
27
28impl MemoryBackend {
29    pub fn new(limits: ContentLimits) -> Self {
30        Self {
31            limits,
32            inner: RwLock::new(State::default()),
33        }
34    }
35
36    pub fn limits(&self) -> ContentLimits {
37        self.limits
38    }
39}
40
41impl ContentBackend for MemoryBackend {
42    fn put(&self, reader: &mut dyn Read, _mime: &str) -> Result<Stored, ContentError> {
43        let mut bytes = Vec::new();
44        let sentinel = u64::try_from(self.limits.max_item_bytes)
45            .unwrap_or(u64::MAX)
46            .saturating_add(1);
47        reader.take(sentinel).read_to_end(&mut bytes)?;
48        let hash = hash_bytes(&bytes);
49        let len = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
50        let mut state = self
51            .inner
52            .write()
53            .map_err(|_| ContentError::Io("memory store lock poisoned".into()))?;
54        // Re-storing content already retained consumes no more quota.
55        if state.entries.contains_key(&hash) {
56            return Ok(Stored { hash, len });
57        }
58        check_new_item(&self.limits, state.bytes, state.entries.len(), bytes.len())?;
59        state.bytes = state.bytes.saturating_add(bytes.len());
60        state.entries.insert(hash.clone(), bytes.into());
61        drop(state);
62        Ok(Stored { hash, len })
63    }
64
65    fn open(&self, hash: &str) -> Result<Option<ContentReader>, ContentError> {
66        let state = self
67            .inner
68            .read()
69            .map_err(|_| ContentError::Io("memory store lock poisoned".into()))?;
70        let key = hash.to_ascii_lowercase();
71        Ok(state.entries.get(&key).map(|bytes| {
72            Box::new(std::io::Cursor::new(std::sync::Arc::clone(bytes))) as ContentReader
73        }))
74    }
75
76    fn open_at(&self, hash: &str, offset: u64) -> Result<Option<ContentReader>, ContentError> {
77        use std::io::Seek as _;
78        let state = self
79            .inner
80            .read()
81            .map_err(|_| ContentError::Io("memory store lock poisoned".into()))?;
82        let key = hash.to_ascii_lowercase();
83        let Some(bytes) = state.entries.get(&key).map(std::sync::Arc::clone) else {
84            return Ok(None);
85        };
86        drop(state);
87        let mut reader = std::io::Cursor::new(bytes);
88        reader.seek(std::io::SeekFrom::Start(offset))?;
89        Ok(Some(Box::new(reader)))
90    }
91
92    fn has(&self, hash: &str) -> bool {
93        self.inner
94            .read()
95            .is_ok_and(|state| state.entries.contains_key(&hash.to_ascii_lowercase()))
96    }
97
98    fn size(&self, hash: &str) -> Option<u64> {
99        let key = hash.to_ascii_lowercase();
100        let inner = self.inner.read().ok()?;
101        let size = inner
102            .entries
103            .get(&key)
104            .and_then(|entry| u64::try_from(entry.len()).ok());
105        drop(inner);
106        size
107    }
108
109    fn collect_unreferenced(&self, live: &BTreeSet<String>) -> Result<Collected, ContentError> {
110        self.remove_where(|hash| !live.contains(hash))
111    }
112
113    fn release(&self, hash: &str) -> Result<Collected, ContentError> {
114        self.remove_where(|kept| kept == hash)
115    }
116
117    fn max_item_bytes(&self) -> usize {
118        self.limits.max_item_bytes
119    }
120}
121
122impl MemoryBackend {
123    fn remove_where(&self, gone: impl Fn(&str) -> bool) -> Result<Collected, ContentError> {
124        let mut state = self
125            .inner
126            .write()
127            .map_err(|_| ContentError::Io("memory store lock poisoned".into()))?;
128        let unreferenced: Vec<String> = state
129            .entries
130            .keys()
131            .filter(|hash| gone(hash))
132            .cloned()
133            .collect();
134        let mut collected = Collected::default();
135        for hash in unreferenced {
136            if let Some(bytes) = state.entries.remove(&hash) {
137                state.bytes = state.bytes.saturating_sub(bytes.len());
138                collected.bytes = collected
139                    .bytes
140                    .saturating_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX));
141                collected.hashes.push(hash);
142            }
143        }
144        drop(state);
145        Ok(collected)
146    }
147}
148
149/// Whether one more item of `incoming` bytes fits `limits` on top of what is held.
150pub(crate) fn check_new_item(
151    limits: &ContentLimits,
152    current_bytes: usize,
153    current_entries: usize,
154    incoming: usize,
155) -> Result<(), ContentError> {
156    if incoming > limits.max_item_bytes {
157        return Err(ContentError::ItemTooLarge {
158            actual: incoming,
159            limit: limits.max_item_bytes,
160        });
161    }
162    if current_entries >= limits.max_entries {
163        return Err(ContentError::EntryLimitExceeded {
164            limit: limits.max_entries,
165        });
166    }
167    let attempted = current_bytes.saturating_add(incoming);
168    if attempted > limits.max_total_bytes {
169        return Err(ContentError::TotalQuotaExceeded {
170            attempted,
171            limit: limits.max_total_bytes,
172        });
173    }
174    Ok(())
175}