sa_token_adapter/
storage.rs

1// Author: 金书记
2//
3//! 存储适配器trait定义
4
5use 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/// 存储适配器trait
30/// 
31/// 所有存储实现(内存、Redis、数据库等)都需要实现这个trait
32#[async_trait]
33pub trait SaStorage: Send + Sync {
34    /// 获取值
35    async fn get(&self, key: &str) -> StorageResult<Option<String>>;
36    
37    /// 设置值
38    /// 
39    /// # 参数
40    /// * `key` - 键
41    /// * `value` - 值
42    /// * `ttl` - 过期时间(None表示永不过期)
43    async fn set(&self, key: &str, value: &str, ttl: Option<Duration>) -> StorageResult<()>;
44    
45    /// 删除值
46    async fn delete(&self, key: &str) -> StorageResult<()>;
47    
48    /// 检查键是否存在
49    async fn exists(&self, key: &str) -> StorageResult<bool>;
50    
51    /// 设置过期时间
52    async fn expire(&self, key: &str, ttl: Duration) -> StorageResult<()>;
53    
54    /// 获取剩余过期时间
55    async fn ttl(&self, key: &str) -> StorageResult<Option<Duration>>;
56    
57    /// 批量获取
58    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    /// 批量设置
67    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    /// 批量删除
75    async fn mdel(&self, keys: &[&str]) -> StorageResult<()> {
76        for key in keys {
77            self.delete(key).await?;
78        }
79        Ok(())
80    }
81    
82    /// 原子递增
83    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    /// 原子递减
93    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    /// 清空所有数据(谨慎使用)
103    async fn clear(&self) -> StorageResult<()>;
104    
105    /// 获取匹配模式的所有键
106    /// 
107    /// # 参数
108    /// * `pattern` - 匹配模式,支持 * 通配符
109    async fn keys(&self, _pattern: &str) -> StorageResult<Vec<String>> {
110        // 默认实现:不支持模式匹配,返回空列表
111        Ok(Vec::new())
112    }
113}