use std::any::Any;
use std::pin::Pin;
use std::sync::Arc;
use async_trait::async_trait;
use futures::Future;
use crate::Result;
use super::CacheCodec;
pub type CacheEntry = Arc<dyn Any + Send + Sync>;
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct InternalCacheKey {
prefix: Arc<str>,
key: Arc<str>,
type_name: &'static str,
}
impl InternalCacheKey {
pub fn new(prefix: Arc<str>, key: Arc<str>, type_name: &'static str) -> Self {
Self {
prefix,
key,
type_name,
}
}
pub fn prefix(&self) -> &str {
&self.prefix
}
pub fn key(&self) -> &str {
&self.key
}
pub fn type_name(&self) -> &'static str {
self.type_name
}
pub fn starts_with(&self, prefix: &str) -> bool {
self.prefix.starts_with(prefix)
}
}
#[async_trait]
pub trait CacheBackend: Send + Sync + std::fmt::Debug {
async fn get(&self, key: &InternalCacheKey, codec: Option<CacheCodec>) -> Option<CacheEntry>;
async fn insert(
&self,
key: &InternalCacheKey,
entry: CacheEntry,
size_bytes: usize,
codec: Option<CacheCodec>,
);
async fn get_or_insert<'a>(
&self,
key: &InternalCacheKey,
loader: Pin<Box<dyn Future<Output = Result<(CacheEntry, usize)>> + Send + 'a>>,
codec: Option<CacheCodec>,
) -> Result<(CacheEntry, bool)>;
async fn invalidate_prefix(&self, prefix: &str);
async fn clear(&self);
async fn num_entries(&self) -> usize;
async fn size_bytes(&self) -> usize;
fn approx_num_entries(&self) -> usize {
0
}
fn approx_size_bytes(&self) -> usize {
0
}
}