sa_token_adapter/
storage.rs1use async_trait::async_trait;
6use std::time::Duration;
7use thiserror::Error;
8
9pub type StorageResult<T> = Result<T, StorageError>;
10
11#[derive(Debug, Error)]
12pub enum StorageError {
13 #[error("Storage operation failed: {0}")]
14 OperationFailed(String),
15
16 #[error("Key not found: {0}")]
17 KeyNotFound(String),
18
19 #[error("Serialization error: {0}")]
20 SerializationError(String),
21
22 #[error("Connection error: {0}")]
23 ConnectionError(String),
24
25 #[error("Internal error: {0}")]
26 InternalError(String),
27}
28
29#[async_trait]
33pub trait SaStorage: Send + Sync {
34 async fn get(&self, key: &str) -> StorageResult<Option<String>>;
36
37 async fn set(&self, key: &str, value: &str, ttl: Option<Duration>) -> StorageResult<()>;
44
45 async fn delete(&self, key: &str) -> StorageResult<()>;
47
48 async fn exists(&self, key: &str) -> StorageResult<bool>;
50
51 async fn expire(&self, key: &str, ttl: Duration) -> StorageResult<()>;
53
54 async fn ttl(&self, key: &str) -> StorageResult<Option<Duration>>;
56
57 async fn mget(&self, keys: &[&str]) -> StorageResult<Vec<Option<String>>> {
59 let mut results = Vec::with_capacity(keys.len());
60 for key in keys {
61 results.push(self.get(key).await?);
62 }
63 Ok(results)
64 }
65
66 async fn mset(&self, items: &[(&str, &str)], ttl: Option<Duration>) -> StorageResult<()> {
68 for (key, value) in items {
69 self.set(key, value, ttl).await?;
70 }
71 Ok(())
72 }
73
74 async fn mdel(&self, keys: &[&str]) -> StorageResult<()> {
76 for key in keys {
77 self.delete(key).await?;
78 }
79 Ok(())
80 }
81
82 async fn incr(&self, key: &str) -> StorageResult<i64> {
84 let current = self.get(key).await?
85 .and_then(|v| v.parse::<i64>().ok())
86 .unwrap_or(0);
87 let new_value = current + 1;
88 self.set(key, &new_value.to_string(), None).await?;
89 Ok(new_value)
90 }
91
92 async fn decr(&self, key: &str) -> StorageResult<i64> {
94 let current = self.get(key).await?
95 .and_then(|v| v.parse::<i64>().ok())
96 .unwrap_or(0);
97 let new_value = current - 1;
98 self.set(key, &new_value.to_string(), None).await?;
99 Ok(new_value)
100 }
101
102 async fn clear(&self) -> StorageResult<()>;
104
105 async fn keys(&self, _pattern: &str) -> StorageResult<Vec<String>> {
110 Ok(Vec::new())
112 }
113}