#![cfg(feature = "cache")]
use bytes::Bytes;
use quick_cache::sync::Cache;
use std::{fmt, sync::Arc};
use crate::ApiError;
type Result<T> = miette::Result<T, ApiError>;
type LastModified = String;
type ApiCache = Cache<String, (Bytes, LastModified)>;
#[derive(Debug)]
pub struct CacheEntry(pub Bytes, pub LastModified);
pub trait CacheManagerSync: Send + Sync + 'static {
fn get(&self, cache_key: &str) -> Result<Option<CacheEntry>>;
fn put(&self, cache_key: &str, last_modified: &str, bytes: Bytes) -> Result<()>;
fn delete(&self, cache_key: &str) -> Result<()>;
}
#[derive(Clone)]
pub struct CacheManagerQuick {
pub cache: Arc<ApiCache>,
}
impl fmt::Debug for CacheManagerQuick {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("QuickManager").finish_non_exhaustive()
}
}
impl CacheManagerQuick {
pub fn new(capacity: usize) -> Self {
Self {
cache: Arc::new(Cache::new(capacity)),
}
}
}
impl CacheManagerSync for CacheManagerQuick {
fn get(&self, cache_key: &str) -> Result<Option<CacheEntry>> {
let entry: CacheEntry = match self.cache.get(cache_key) {
Some((bytes, lm)) => CacheEntry(bytes, lm),
None => return Ok(None),
};
Ok(Some(entry))
}
fn put(&self, cache_key: &str, last_modified: &str, bytes: Bytes) -> Result<()> {
self.cache
.insert(cache_key.into(), (bytes, last_modified.into()));
Ok(())
}
fn delete(&self, cache_key: &str) -> Result<()> {
self.cache.remove(cache_key);
Ok(())
}
}
fn _assert_trait_object(_: &dyn CacheManagerSync) {}