use crate::db_cache::{CachedEntry, CachedKey, DbCache, DEFAULT_MAX_CAPACITY};
use async_trait::async_trait;
use std::time::Duration;
#[derive(Clone, Copy, Debug)]
pub struct MokaCacheOptions {
pub max_capacity: u64,
pub time_to_live: Option<Duration>,
pub time_to_idle: Option<Duration>,
}
impl Default for MokaCacheOptions {
fn default() -> Self {
Self {
max_capacity: DEFAULT_MAX_CAPACITY,
time_to_live: None,
time_to_idle: None,
}
}
}
pub struct MokaCache {
inner: moka::future::Cache<CachedKey, CachedEntry>,
}
impl MokaCache {
pub fn new() -> Self {
Self::new_with_opts(MokaCacheOptions::default())
}
pub fn new_with_opts(options: MokaCacheOptions) -> Self {
let mut builder = moka::future::Cache::builder()
.weigher(|_, v: &CachedEntry| v.size() as u32)
.max_capacity(options.max_capacity);
if let Some(ttl) = options.time_to_live {
builder = builder.time_to_live(ttl);
}
if let Some(tti) = options.time_to_idle {
builder = builder.time_to_idle(tti);
}
let cache = builder.build();
Self { inner: cache }
}
}
impl Default for MokaCache {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl DbCache for MokaCache {
async fn get_block(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).await)
}
async fn get_index(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).await)
}
async fn get_filter(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).await)
}
async fn get_stats(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).await)
}
async fn insert(&self, key: CachedKey, value: CachedEntry) {
self.inner.insert(key, value).await;
}
async fn remove(&self, key: &CachedKey) {
self.inner.remove(key).await;
}
fn entry_count(&self) -> u64 {
self.inner.entry_count()
}
}