2023-06-03 13:31:57 +02:00
|
|
|
#![feature(box_into_inner)]
|
|
|
|
|
2023-06-01 10:41:58 +02:00
|
|
|
use std::borrow::Cow;
|
|
|
|
|
|
|
|
use async_trait::async_trait;
|
2023-06-01 22:02:47 +02:00
|
|
|
pub use config::PluginConfig;
|
2023-06-03 13:31:57 +02:00
|
|
|
use tracing::warn;
|
2023-06-01 10:41:58 +02:00
|
|
|
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
|
|
pub enum Error {
|
|
|
|
#[error("Unable to connect")]
|
|
|
|
Connect,
|
|
|
|
#[error("Entry is invalid")]
|
|
|
|
InvalidEntry,
|
|
|
|
#[error("Can't invalidate keys {0:?}")]
|
|
|
|
Invalidate(Vec<String>),
|
|
|
|
#[error("Failed to parse config")]
|
|
|
|
InvalidConfig,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub type CResult<T> = Result<T, Error>;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum InvalidatePattern<'s> {
|
|
|
|
StartsWith(Cow<'s, str>),
|
|
|
|
EndsWith(Cow<'s, str>),
|
|
|
|
Contains(Cow<'s, str>),
|
|
|
|
Const(Cow<'s, str>),
|
|
|
|
}
|
|
|
|
|
2023-06-03 13:31:57 +02:00
|
|
|
pub struct CacheObject(pub Option<Vec<u8>>);
|
2023-06-01 10:41:58 +02:00
|
|
|
|
2023-06-03 13:31:57 +02:00
|
|
|
impl CacheObject {
|
|
|
|
pub fn into_inner<T>(self) -> CResult<Option<T>>
|
2023-06-01 10:41:58 +02:00
|
|
|
where
|
2023-06-03 13:31:57 +02:00
|
|
|
T: serde::de::DeserializeOwned,
|
|
|
|
{
|
|
|
|
let Some(data) = self.0 else {
|
|
|
|
return Ok(None)
|
|
|
|
};
|
|
|
|
bincode::deserialize(&data)
|
|
|
|
.map_err(|e| {
|
|
|
|
warn!("Malformed cache entry: {e}");
|
|
|
|
Error::InvalidEntry
|
|
|
|
})
|
|
|
|
.map(Some)
|
|
|
|
}
|
|
|
|
}
|
2023-06-01 10:41:58 +02:00
|
|
|
|
2023-06-03 13:31:57 +02:00
|
|
|
#[async_trait]
|
|
|
|
pub trait CacheAdapter {
|
|
|
|
async fn new(config: PluginConfig) -> CResult<Self>
|
|
|
|
where
|
|
|
|
Self: Sized;
|
|
|
|
|
|
|
|
async fn read(&self, key: &str) -> CResult<CacheObject>;
|
|
|
|
|
|
|
|
async fn set(
|
2023-06-01 10:41:58 +02:00
|
|
|
&mut self,
|
|
|
|
key: &str,
|
2023-06-03 13:31:57 +02:00
|
|
|
data: &[u8],
|
2023-06-01 10:41:58 +02:00
|
|
|
expires_in: Option<std::time::Duration>,
|
2023-06-03 13:31:57 +02:00
|
|
|
) -> CResult<()>;
|
2023-06-01 10:41:58 +02:00
|
|
|
|
|
|
|
async fn invalidate(&mut self, pattern: InvalidatePattern<'_>) -> CResult<u64>;
|
|
|
|
|
|
|
|
async fn clear(&mut self) -> CResult<u64>;
|
|
|
|
}
|