use std::any::Any;
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use async_trait::async_trait;
use bytes::Bytes;
use crate::config::CacheStoreConfig;
use crate::{CacheValue, Error};
#[derive(Clone, Copy, Debug)]
pub enum CacheExpiry {
Unknown,
Never,
At(Instant),
}
pub struct CacheEntry {
pub bytes: Bytes,
pub expiry: CacheExpiry,
}
#[async_trait]
pub trait CacheStore: Any + Send + Sync + 'static {
fn store_name(&self) -> &str;
fn driver_name(&self) -> &str;
fn as_any(&self) -> &dyn Any;
fn supports_ttl(&self) -> bool;
async fn get(
&self,
key: &str,
) -> crate::Result<Option<Bytes>>;
async fn get_entry(
&self,
key: &str,
) -> crate::Result<Option<CacheEntry>> {
Ok(self
.get(key)
.await?
.map(|bytes| CacheEntry { bytes, expiry: CacheExpiry::Unknown }))
}
async fn put(
&self,
key: &str,
value: Cow<'_, [u8]>,
ttl: Option<Duration>,
) -> crate::Result<()>;
async fn forget(
&self,
key: &str,
) -> crate::Result<()>;
async fn clear(&self) -> crate::Result<()> {
Err(Error::Rejected(format!(
"cache store '{}' with driver '{}' does not support clearing its namespace",
self.store_name(),
self.driver_name()
)))
}
fn tagged(&self) -> Option<&dyn TaggedCacheStore> {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FillToken {
source: u64,
clock: u64,
}
impl FillToken {
pub const fn new(
source: u64,
clock: u64,
) -> Self {
Self { source, clock }
}
pub const fn source(self) -> u64 {
self.source
}
pub const fn clock(self) -> u64 {
self.clock
}
}
#[must_use = "a refused fill is not an error, but nothing was stored"]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Fill {
Kept,
Invalidated,
Superseded,
Skipped,
}
impl Fill {
pub const fn is_kept(self) -> bool {
matches!(self, Self::Kept)
}
}
#[async_trait]
pub trait TaggedCacheStore: Send + Sync {
async fn put_tagged(
&self,
key: &str,
value: Cow<'_, [u8]>,
ttl: Option<Duration>,
tags: &[&str],
) -> crate::Result<()>;
async fn fill_token(&self) -> crate::Result<FillToken>;
async fn fill_tagged(
&self,
token: FillToken,
key: &str,
value: Cow<'_, [u8]>,
ttl: Option<Duration>,
tags: &[&str],
) -> crate::Result<Fill>;
async fn invalidate_tags(
&self,
tags: &[&str],
) -> crate::Result<()>;
}
pub trait CacheStoreResolver {
fn store(
&self,
name: &str,
) -> crate::Result<Arc<dyn CacheStore>>;
}
impl CacheStoreResolver for HashMap<String, Arc<dyn CacheStore>> {
fn store(
&self,
name: &str,
) -> crate::Result<Arc<dyn CacheStore>> {
self.get(name).cloned().ok_or_else(|| {
Error::Missing(format!("cache store '{name}' is not registered"))
})
}
}
pub trait CacheDriver: Any + Send + Sync + 'static {
fn driver_name(&self) -> &'static str;
fn create_store(
self: Arc<Self>,
store_name: &str,
config: &CacheStoreConfig,
) -> crate::Result<Arc<dyn CacheStore>>;
fn create_reload_store(
self: Arc<Self>,
store_name: &str,
config: &CacheStoreConfig,
) -> crate::Result<Arc<dyn CacheStore>> {
self.create_store(store_name, config)
}
fn finish_store(
&self,
_store: &Arc<dyn CacheStore>,
_stores: &dyn CacheStoreResolver,
) -> crate::Result<()> {
Ok(())
}
}
pub struct CacheRepository {
store: Arc<dyn CacheStore>,
}
impl CacheRepository {
pub(crate) fn new(store: Arc<dyn CacheStore>) -> Self {
Self { store }
}
pub fn store_name(&self) -> &str {
self.store.store_name()
}
pub fn driver_name(&self) -> &str {
self.store.driver_name()
}
pub fn supports_ttl(&self) -> bool {
self.store.supports_ttl()
}
pub fn supports_tags(&self) -> bool {
self.store.tagged().is_some()
}
pub fn as_any(&self) -> &dyn Any {
self.store.as_any()
}
pub fn store(&self) -> Arc<dyn CacheStore> {
self.store.clone()
}
pub async fn get(
&self,
key: &str,
) -> crate::Result<Option<Bytes>> {
self.store.get(key).await
}
pub async fn put<'v>(
&self,
key: &str,
value: impl Into<Cow<'v, [u8]>>,
ttl: Option<Duration>,
) -> crate::Result<()> {
self.store.put(key, value.into(), ttl).await
}
pub async fn get_value(
&self,
key: &str,
) -> crate::Result<Option<CacheValue>> {
self.get(key)
.await?
.map(|bytes| CacheValue::decode(&bytes).map_err(Error::from))
.transpose()
}
pub async fn put_value(
&self,
key: &str,
value: CacheValue,
ttl: Option<Duration>,
) -> crate::Result<()> {
let encoded = value.encode().map_err(Error::from)?;
self.put(key, encoded, ttl).await
}
pub async fn put_tagged<'v>(
&self,
key: &str,
value: impl Into<Cow<'v, [u8]>>,
ttl: Option<Duration>,
tags: &[&str],
) -> crate::Result<()> {
self.tagged()?.put_tagged(key, value.into(), ttl, tags).await
}
pub async fn put_value_tagged(
&self,
key: &str,
value: CacheValue,
ttl: Option<Duration>,
tags: &[&str],
) -> crate::Result<()> {
let tagged = self.tagged()?;
let encoded = value.encode().map_err(Error::from)?;
tagged.put_tagged(key, encoded.into(), ttl, tags).await
}
pub async fn fill_token(&self) -> crate::Result<FillToken> {
self.tagged()?.fill_token().await
}
pub async fn fill_tagged<'v>(
&self,
token: FillToken,
key: &str,
value: impl Into<Cow<'v, [u8]>>,
ttl: Option<Duration>,
tags: &[&str],
) -> crate::Result<Fill> {
self.tagged()?.fill_tagged(token, key, value.into(), ttl, tags).await
}
pub async fn invalidate_tags(
&self,
tags: &[&str],
) -> crate::Result<()> {
self.tagged()?.invalidate_tags(tags).await
}
pub async fn forget(
&self,
key: &str,
) -> crate::Result<()> {
self.store.forget(key).await
}
pub async fn clear(&self) -> crate::Result<()> {
self.store.clear().await
}
fn tagged(&self) -> crate::Result<&dyn TaggedCacheStore> {
self.store.tagged().ok_or_else(|| Error::TagsUnsupported {
store: self.store_name().into(),
driver: self.driver_name().into(),
})
}
}