Skip to main content

lrwf_core/cache/
trait_def.rs

1//! Core caching trait — `IDistributedCache`.
2//!
3//! Matches ASP.NET Core `IDistributedCache` interface:
4//| ASP.NET Core                    | LRWF                            |
5//|---------------------------------|---------------------------------|
6//| `GetAsync(string, tok)`         | `get(&self, key)`               |
7//| `SetAsync(string, byte[], opts)`| `set(&self, key, value, opts)`  |
8//| `RefreshAsync(string)`          | `refresh(&self, key)`           |
9//| `RemoveAsync(string)`           | `remove(&self, key)`            |
10
11use super::options::DistributedCacheEntryOptions;
12
13#[derive(Debug, Clone)]
14pub enum CacheError {
15    NotFound(String),
16    Serialization(String),
17    Unavailable(String),
18    Message(String),
19}
20
21impl std::fmt::Display for CacheError {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            CacheError::NotFound(k) => write!(f, "cache key not found: {}", k),
25            CacheError::Serialization(e) => write!(f, "cache serialization error: {}", e),
26            CacheError::Unavailable(e) => write!(f, "cache unavailable: {}", e),
27            CacheError::Message(m) => write!(f, "{}", m),
28        }
29    }
30}
31
32impl std::error::Error for CacheError {}
33
34pub type Result<T> = std::result::Result<T, CacheError>;
35
36#[async_trait::async_trait]
37pub trait IDistributedCache: Send + Sync + 'static {
38    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;
39    async fn set(
40        &self,
41        key: &str,
42        value: Vec<u8>,
43        options: Option<&DistributedCacheEntryOptions>,
44    ) -> Result<()>;
45    async fn remove(&self, key: &str) -> Result<()>;
46    async fn refresh(&self, key: &str) -> Result<()>;
47    async fn exists(&self, key: &str) -> Result<bool>;
48    async fn clear(&self) -> Result<()> {
49        Ok(())
50    }
51}