use crate::db_cache::{CachedEntry, CachedKey, DbCache, DEFAULT_MAX_CAPACITY};
use async_trait::async_trait;
use sysinfo::{CpuRefreshKind, System};
#[derive(Clone, Copy, Debug)]
pub struct FoyerCacheOptions {
pub max_capacity: u64,
pub shards: usize,
}
impl Default for FoyerCacheOptions {
fn default() -> Self {
Self {
max_capacity: DEFAULT_MAX_CAPACITY,
shards: {
let mut sys = System::new();
sys.refresh_cpu_specifics(CpuRefreshKind::nothing());
sys.cpus().len()
},
}
}
}
pub struct FoyerCache {
inner: foyer::Cache<CachedKey, CachedEntry>,
}
impl FoyerCache {
pub fn new() -> Self {
Self::new_with_opts(FoyerCacheOptions::default())
}
pub fn new_with_opts(options: FoyerCacheOptions) -> Self {
let builder = foyer::CacheBuilder::new(options.max_capacity as _)
.with_weighter(|_, v: &CachedEntry| v.size());
let cache = builder.build();
Self { inner: cache }
}
}
impl Default for FoyerCache {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl DbCache for FoyerCache {
async fn get_block(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).map(|entry| entry.value().clone()))
}
async fn get_index(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).map(|entry| entry.value().clone()))
}
async fn get_filter(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).map(|entry| entry.value().clone()))
}
async fn get_stats(&self, key: &CachedKey) -> Result<Option<CachedEntry>, crate::Error> {
Ok(self.inner.get(key).map(|entry| entry.value().clone()))
}
async fn insert(&self, key: CachedKey, value: CachedEntry) {
self.inner.insert(key, value);
}
async fn remove(&self, key: &CachedKey) {
self.inner.remove(key);
}
fn entry_count(&self) -> u64 {
0
}
}