1use std::collections::HashMap;
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9use std::sync::{Arc, Mutex, MutexGuard};
10use std::time::Duration;
11
12use web_time::Instant;
13use zeroize::Zeroizing;
14
15const IDLE: Duration = Duration::from_secs(30 * 60);
16const TRIM_EVERY: Duration = Duration::from_secs(5 * 60);
17
18pub struct Entry {
20 bytes: Zeroizing<Vec<u8>>,
21 mime: Box<str>,
22 live: Arc<AtomicU64>,
23}
24
25impl Entry {
26 pub fn bytes(&self) -> &[u8] {
27 &self.bytes
28 }
29}
30
31impl Drop for Entry {
32 fn drop(&mut self) {
33 self.live.fetch_sub(self.bytes.len() as u64, Ordering::Relaxed);
34 }
35}
36
37impl super::MediaSource for Entry {
38 fn len(&self) -> u64 {
39 self.bytes.len() as u64
40 }
41
42 fn mime(&self) -> &str {
43 &self.mime
44 }
45
46 fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize> {
47 let start = usize::try_from(offset).unwrap_or(usize::MAX).min(self.bytes.len());
48 let n = buf.len().min(self.bytes.len() - start);
49 buf[..n].copy_from_slice(&self.bytes[start..start + n]);
50 Ok(n)
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Refused {
56 TooLarge,
58 Busy,
60}
61
62struct Slot {
63 entry: Arc<Entry>,
64 touched: Instant,
65 holds: u32,
66 parent: Option<[u8; 32]>,
68}
69
70pub struct MediaRam {
71 budget: u64,
72 live: Arc<AtomicU64>,
73 slots: Mutex<HashMap<[u8; 32], Slot>>,
74}
75
76impl Default for MediaRam {
77 fn default() -> Self {
78 Self::with_budget(budget())
79 }
80}
81
82impl MediaRam {
83 fn with_budget(budget: u64) -> Self {
84 MediaRam { budget, live: Arc::new(AtomicU64::new(0)), slots: Mutex::new(HashMap::new()) }
85 }
86
87 fn lock(&self) -> MutexGuard<'_, HashMap<[u8; 32], Slot>> {
88 self.slots.lock().unwrap_or_else(|e| e.into_inner())
89 }
90
91 pub fn insert(&self, hash: [u8; 32], bytes: Vec<u8>, mime: &str) -> Result<Arc<Entry>, Refused> {
92 self.insert_at(hash, bytes, mime, Instant::now(), None)
93 }
94
95 pub fn insert_derived(&self, parent: [u8; 32], key: [u8; 32], bytes: Vec<u8>, mime: &str) -> Result<Arc<Entry>, Refused> {
97 self.insert_at(key, bytes, mime, Instant::now(), Some(parent))
98 }
99
100 fn insert_at(&self, hash: [u8; 32], bytes: Vec<u8>, mime: &str, now: Instant, parent: Option<[u8; 32]>) -> Result<Arc<Entry>, Refused> {
101 let bytes = Zeroizing::new(bytes);
102 let len = bytes.len() as u64;
103 if !self.admits(len) {
104 return Err(Refused::TooLarge);
105 }
106 let mut slots = self.lock();
107 if let Some(slot) = slots.get_mut(&hash) {
108 slot.touched = now;
109 return Ok(slot.entry.clone());
110 }
111 trim_idle(&mut slots, now);
112
113 let freeable = |slot: &Slot| slot.holds == 0 && Arc::strong_count(&slot.entry) == 1;
115 let free_now: u64 = slots.values().filter(|s| freeable(s)).map(|s| s.entry.bytes.len() as u64).sum();
116 if self.live.load(Ordering::Relaxed).saturating_sub(free_now) + len > self.budget {
117 return Err(Refused::Busy);
118 }
119 while self.live.load(Ordering::Relaxed) + len > self.budget {
120 let oldest = slots.iter().filter(|(_, s)| freeable(s)).min_by_key(|(_, s)| s.touched).map(|(h, _)| *h);
121 let Some(oldest) = oldest else { return Err(Refused::Busy) };
122 slots.remove(&oldest);
123 }
124
125 self.live.fetch_add(len, Ordering::Relaxed);
126 let entry = Arc::new(Entry { bytes, mime: mime.into(), live: self.live.clone() });
127 slots.insert(hash, Slot { entry: entry.clone(), touched: now, holds: 0, parent });
128 Ok(entry)
129 }
130
131 pub fn largest(&self) -> u64 {
133 self.budget / 3
134 }
135
136 pub fn admits(&self, len: u64) -> bool {
137 len <= self.largest()
138 }
139
140 pub fn get(&self, hash: &[u8; 32]) -> Option<Arc<Entry>> {
141 let mut slots = self.lock();
142 let slot = slots.get_mut(hash)?;
143 slot.touched = Instant::now();
144 Some(slot.entry.clone())
145 }
146
147 pub fn contains(&self, hash: &[u8; 32]) -> bool {
148 self.lock().contains_key(hash)
149 }
150
151 pub fn hold(&self, hash: &[u8; 32]) -> bool {
153 let mut slots = self.lock();
154 let Some(slot) = slots.get_mut(hash) else { return false };
155 slot.holds += 1;
156 slot.touched = Instant::now();
157 true
158 }
159
160 pub fn release(&self, hash: &[u8; 32]) {
161 if let Some(slot) = self.lock().get_mut(hash) {
162 slot.holds = slot.holds.saturating_sub(1);
163 slot.touched = Instant::now();
164 }
165 }
166
167 pub fn remove(&self, hash: &[u8; 32]) {
168 self.lock().retain(|key, slot| key != hash && slot.parent.as_ref() != Some(hash));
169 }
170
171 pub fn clear(&self) {
172 self.lock().clear();
173 }
174
175 pub fn trim(&self) {
176 trim_idle(&mut self.lock(), Instant::now());
177 }
178
179 pub fn live_bytes(&self) -> u64 {
181 self.live.load(Ordering::Relaxed)
182 }
183}
184
185fn trim_idle(slots: &mut HashMap<[u8; 32], Slot>, now: Instant) {
186 slots.retain(|_, s| s.holds > 0 || now.saturating_duration_since(s.touched) < IDLE);
187}
188
189fn budget() -> u64 {
190 const MIB: u64 = 1 << 20;
191 #[cfg(target_arch = "wasm32")]
193 let fixed = 128 * MIB;
194 #[cfg(any(target_os = "android", target_os = "ios"))]
195 let fixed = 192 * MIB;
196 #[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
197 let fixed = 512 * MIB;
198 device_memory().map_or(fixed, |total| fixed.min(total / 8))
199}
200
201#[cfg(any(target_os = "android", target_os = "linux"))]
202fn device_memory() -> Option<u64> {
203 let info = std::fs::read_to_string("/proc/meminfo").ok()?;
204 let kib = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().strip_suffix("kB")?.trim();
205 kib.parse::<u64>().ok().map(|k| k * 1024)
206}
207
208#[cfg(not(any(target_os = "android", target_os = "linux")))]
209fn device_memory() -> Option<u64> {
210 None
211}
212
213struct MediaRamKey;
214
215pub fn cache() -> Arc<MediaRam> {
217 crate::db::current_session().scoped::<MediaRamKey, MediaRam>()
218}
219
220pub(crate) fn attach(session: &Arc<crate::db::Session>) {
222 let _ = session.scoped::<MediaRamKey, MediaRam>();
223}
224
225pub(crate) fn clear_for(session: &Arc<crate::db::Session>) {
226 session.scoped::<MediaRamKey, MediaRam>().clear();
227}
228
229pub fn insert(hash: [u8; 32], bytes: Vec<u8>, mime: &str) -> Result<Arc<Entry>, Refused> {
231 start_trimming();
232 cache().insert(hash, bytes, mime)
233}
234
235pub fn insert_derived(parent: [u8; 32], key: [u8; 32], bytes: Vec<u8>, mime: &str) -> Result<Arc<Entry>, Refused> {
237 start_trimming();
238 cache().insert_derived(parent, key, bytes, mime)
239}
240
241fn start_trimming() {
244 static STARTED: AtomicBool = AtomicBool::new(false);
245 #[cfg(not(target_arch = "wasm32"))]
246 if tokio::runtime::Handle::try_current().is_err() {
247 return;
248 }
249 if STARTED.swap(true, Ordering::AcqRel) {
250 return;
251 }
252 crate::rt::spawn(async {
254 loop {
255 crate::rt::time::sleep(TRIM_EVERY).await;
256 cache().trim();
257 }
258 });
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264 use crate::media::MediaSource;
265
266 const H1: [u8; 32] = [1; 32];
267 const H2: [u8; 32] = [2; 32];
268 const H3: [u8; 32] = [3; 32];
269 const H4: [u8; 32] = [4; 32];
270
271 fn bytes(n: usize) -> Vec<u8> {
272 vec![0x5a; n]
273 }
274
275 #[test]
276 fn a_picture_drawn_from_a_file_goes_with_it() {
277 let ram = MediaRam::with_budget(10_000);
278 ram.insert(H1, bytes(100), "image/png").unwrap();
279 ram.insert_derived(H1, H2, bytes(10), "image/jpeg").unwrap();
280 ram.insert(H3, bytes(10), "image/png").unwrap();
281 ram.remove(&H1);
282 assert!(!ram.contains(&H1) && !ram.contains(&H2), "the copy goes with the file");
283 assert!(ram.contains(&H3), "nothing else does");
284
285 ram.insert_derived(H4, H2, bytes(10), "image/jpeg").unwrap();
287 ram.remove(&H4);
288 assert!(!ram.contains(&H2));
289 }
290
291 #[test]
292 fn the_least_recently_used_goes_first_and_a_held_entry_never_does() {
293 let ram = MediaRam::with_budget(300);
294 let t0 = Instant::now();
295 ram.insert_at(H1, bytes(100), "image/png", t0, None).unwrap();
296 ram.insert_at(H2, bytes(100), "image/png", t0 + Duration::from_secs(1), None).unwrap();
297 assert!(ram.hold(&H1));
298 ram.insert_at(H3, bytes(100), "image/png", t0 + Duration::from_secs(2), None).unwrap();
299 ram.insert_at(H4, bytes(100), "image/png", t0 + Duration::from_secs(3), None).unwrap();
300 assert!(ram.contains(&H1), "held, though oldest");
301 assert!(!ram.contains(&H2), "the oldest unheld went");
302 assert!(ram.contains(&H3) && ram.contains(&H4));
303 assert_eq!(ram.live_bytes(), 300);
304 }
305
306 #[test]
307 fn a_file_too_big_or_a_budget_full_of_holds_is_refused() {
308 let ram = MediaRam::with_budget(300);
309 assert_eq!(ram.insert(H1, bytes(101), "video/mp4").err(), Some(Refused::TooLarge));
310 for h in [H1, H2, H3] {
311 ram.insert(h, bytes(100), "video/mp4").unwrap();
312 assert!(ram.hold(&h));
313 }
314 assert_eq!(ram.insert(H4, bytes(1), "image/png").err(), Some(Refused::Busy));
315 assert!(ram.contains(&H1) && ram.contains(&H2) && ram.contains(&H3), "nothing held was given up");
316 ram.release(&H2);
317 ram.insert(H4, bytes(1), "image/png").unwrap();
318 assert!(!ram.contains(&H2), "released, then the first to go");
319 }
320
321 #[test]
322 fn bytes_a_reader_still_holds_count_and_leave_with_the_reader() {
323 let ram = MediaRam::with_budget(300);
324 let playing = ram.insert(H1, bytes(100), "audio/mpeg").unwrap();
325 ram.insert(H2, bytes(100), "image/png").unwrap();
326 ram.remove(&H1);
327 assert_eq!(ram.live_bytes(), 200, "out of the map, still in memory");
328 assert_eq!(ram.insert(H3, bytes(100), "image/png").err(), None);
329 assert_eq!(ram.insert(H4, bytes(100), "image/png").err(), None, "H2 made room; the reader's copy did not");
330 assert!(!ram.contains(&H2));
331 assert_eq!(ram.live_bytes(), 300);
332 drop(playing);
333 assert_eq!(ram.live_bytes(), 200);
334 }
335
336 #[test]
337 fn a_reader_mid_request_keeps_its_entry_out_of_eviction() {
338 let ram = MediaRam::with_budget(300);
339 let t0 = Instant::now();
340 ram.insert_at(H1, bytes(100), "video/mp4", t0, None).unwrap();
341 let reading = ram.get(&H1).unwrap();
342 ram.insert_at(H2, bytes(100), "image/png", t0 + Duration::from_secs(1), None).unwrap();
343 ram.insert_at(H3, bytes(100), "image/png", t0 + Duration::from_secs(2), None).unwrap();
344 ram.insert_at(H4, bytes(100), "image/png", t0 + Duration::from_secs(3), None).unwrap();
345 assert!(ram.contains(&H1), "the oldest, but being read");
346 assert!(!ram.contains(&H2), "so the next oldest went");
347 drop(reading);
348 }
349
350 #[test]
351 fn an_idle_entry_goes_after_half_an_hour_unless_held() {
352 let ram = MediaRam::with_budget(1000);
353 let t0 = Instant::now();
354 ram.insert_at(H1, bytes(10), "image/png", t0, None).unwrap();
355 ram.insert_at(H2, bytes(10), "video/mp4", t0, None).unwrap();
356 assert!(ram.hold(&H2));
357 ram.insert_at(H3, bytes(10), "image/png", t0 + IDLE + Duration::from_secs(1), None).unwrap();
358 assert!(!ram.contains(&H1), "idle");
359 assert!(ram.contains(&H2), "held");
360 assert!(ram.contains(&H3));
361 }
362
363 #[test]
364 fn an_entry_reads_like_the_bytes_it_holds() {
365 let ram = MediaRam::with_budget(1000);
366 let data: Vec<u8> = (0..50u8).collect();
367 let entry = ram.insert(H1, data.clone(), "image/png").unwrap();
368 assert_eq!((entry.len(), entry.mime()), (50, "image/png"));
369 let mut buf = [0u8; 8];
370 assert_eq!(entry.read_at(45, &mut buf).unwrap(), 5);
371 assert_eq!(&buf[..5], &data[45..]);
372 assert_eq!(entry.read_at(50, &mut buf).unwrap(), 0);
373 assert_eq!(entry.read_at(u64::MAX, &mut buf).unwrap(), 0);
374 let again = ram.insert(H1, bytes(3), "image/png").unwrap();
375 assert_eq!(again.bytes(), &data[..], "a second insert of a hash keeps the first copy");
376 assert_eq!(ram.live_bytes(), 50);
377 }
378
379 static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(93000);
380
381 fn make_test_npub(n: u32) -> String {
382 const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
383 let mut payload = vec![b'q'; 58];
384 let mut x = n as u64;
385 let mut i = 58;
386 while x > 0 && i > 0 {
387 i -= 1;
388 payload[i] = BECH32[(x as usize) % 32];
389 x /= 32;
390 }
391 format!("npub1{}", String::from_utf8(payload).unwrap())
392 }
393
394 fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, String) {
395 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
396 crate::db::close_database();
397 let tmp = tempfile::tempdir().unwrap();
398 let account = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
399 std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
400 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
401 crate::db::set_current_account(account.clone()).unwrap();
402 crate::db::init_database(&account).unwrap();
403 (tmp, guard, account)
404 }
405
406 #[test]
407 fn a_rebind_keeps_the_one_cache_and_a_swap_empties_it() {
408 let (_tmp, _guard, account) = init_test_db();
409 let before = crate::db::current_session();
410 cache().insert(H1, bytes(10), "image/png").unwrap();
411
412 crate::db::init_database(&account).unwrap();
413 let after = crate::db::current_session();
414 assert!(!Arc::ptr_eq(&before, &after), "init_database rebinds");
415 assert!(Arc::ptr_eq(&before.scoped::<MediaRamKey, MediaRam>(), &cache()), "one cache across the rebind");
416 assert!(cache().contains(&H1));
417
418 let held = cache();
419 crate::db::close_database();
420 assert!(!held.contains(&H1), "the outgoing account's media leaves with it");
421 assert!(!cache().contains(&H1));
422 }
423}