url_cleaner_engine/glue/caching/outer.rs
1//! The home of [`Cache`].
2
3use std::cell::RefCell;
4use parking_lot::ReentrantMutex;
5
6use super::*;
7
8/// A shareable [`InnerCache`].
9/// # Examples
10/// ```
11/// use url_cleaner_engine::glue::*;
12///
13/// // Note the immutability.
14/// let cache = Cache::new(CachePath::Memory);
15///
16/// assert_eq!(cache.read(CacheEntryKeys { subject: "subject", key: "key" }).unwrap().map(|entry| entry.value), None);
17/// cache.write(NewCacheEntry { subject: "subject", key: "key", value: None, duration: Default::default() }).unwrap();
18/// assert_eq!(cache.read(CacheEntryKeys { subject: "subject", key: "key" }).unwrap().map(|entry| entry.value), Some(None));
19/// cache.write(NewCacheEntry { subject: "subject", key: "key", value: Some("value"), duration: Default::default() }).unwrap();
20/// assert_eq!(cache.read(CacheEntryKeys { subject: "subject", key: "key" }).unwrap().map(|entry| entry.value), Some(Some("value".into())));
21/// ```
22#[derive(Debug, Default)]
23pub struct Cache(pub ReentrantMutex<RefCell<InnerCache>>);
24
25impl Cache {
26 /// Create a new unconnected [`Self`].
27 #[allow(dead_code, reason = "Public API.")]
28 pub fn new(path: CachePath) -> Self {
29 path.into()
30 }
31}
32
33impl From<InnerCache> for Cache {
34 fn from(value: InnerCache) -> Self {
35 Self(ReentrantMutex::new(RefCell::new(value)))
36 }
37}
38
39impl From<CachePath> for Cache {
40 fn from(value: CachePath) -> Self {
41 Cache::from(InnerCache::from(value))
42 }
43}
44
45impl Cache {
46 /// Reads from the cache.
47 /// # Errors
48 /// If the call to [`InnerCache::read`] returns an error, that error is returned.
49 pub fn read(&self, keys: CacheEntryKeys) -> Result<Option<CacheEntryValues>, ReadFromCacheError> {
50 self.0.lock().borrow_mut().read(keys)
51 }
52
53 /// Writes to the cache.
54 ///
55 /// If an entry for the `subject` and `key` already exists, overwrites it.
56 /// # Errors
57 /// If the call to [`InnerCache::write`] returns an error, that error is returned.
58 pub fn write(&self, entry: NewCacheEntry) -> Result<(), WriteToCacheError> {
59 self.0.lock().borrow_mut().write(entry)
60 }
61}