Skip to main content

yang_base/
cache.rs

1//! 通用 Redis 缓存与固定窗口限流门面(`feature = "redis"`)。
2//!
3//! 提供 cache-aside(`get_or_load`)、空值缓存、TTL 抖动、single-flight
4//! 与通用限流;安全路径(token 撤销、MFA、鉴权限流)仍保持各自模块的
5//! fail-closed 策略,不经过本模块的 `fail_open` 开关。
6
7use crate::error::{BaseError, Result};
8use serde::{de::DeserializeOwned, Serialize};
9use std::collections::HashMap;
10use std::future::Future;
11use std::sync::{Arc, Mutex as StdMutex, Weak};
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13use tokio::sync::Mutex;
14use yang_db::{JsonCodec, RedisClient, RedisCodec};
15
16/// 空值缓存哨兵:与普通 JSON 值区分(JSON 编码不会产生该字节序列)。
17const NULL_SENTINEL: &[u8] = b"\x00yang-cache-null";
18
19/// 缓存行为配置。
20#[derive(Debug, Clone)]
21pub struct CacheConfig {
22    /// 默认 TTL。
23    pub default_ttl: Duration,
24    /// TTL 随机抖动百分比(0-100),用于分散过期时间、避免缓存雪崩。
25    pub ttl_jitter_percent: u8,
26    /// 空值缓存 TTL。
27    pub null_ttl: Duration,
28    /// 是否启用 single-flight(同一 key 并发 miss 只回源一次)。
29    pub single_flight: bool,
30    /// Redis 故障时是否按 cache miss 处理(仅适用于纯缓存场景)。
31    ///
32    /// 安全敏感路径必须保持 `false`(fail-closed)。
33    pub fail_open: bool,
34}
35
36impl Default for CacheConfig {
37    fn default() -> Self {
38        Self {
39            default_ttl: Duration::from_secs(300),
40            ttl_jitter_percent: 10,
41            null_ttl: Duration::from_secs(60),
42            single_flight: true,
43            fail_open: false,
44        }
45    }
46}
47
48/// 通用缓存门面。
49#[derive(Clone)]
50pub struct Cache {
51    client: RedisClient,
52    config: CacheConfig,
53    // 每个 key 一个 tokio Mutex,用 Weak 保存:所有 waiter 释放后条目可自动回收,
54    // 不会因任务取消/panic 导致 map 无界增长,也不会在 remove 时误删他人正在用的锁。
55    key_locks: Arc<StdMutex<HashMap<String, Weak<Mutex<()>>>>>,
56}
57
58enum Lookup {
59    Hit(Vec<u8>),
60    Null,
61    Miss,
62}
63
64impl Cache {
65    /// 创建缓存门面。
66    pub fn new(client: RedisClient, config: CacheConfig) -> Self {
67        Self {
68            client,
69            config,
70            key_locks: Arc::new(StdMutex::new(HashMap::new())),
71        }
72    }
73
74    /// 底层 Redis 客户端(高级用法)。
75    pub fn client(&self) -> &RedisClient {
76        &self.client
77    }
78
79    /// 当前配置。
80    pub fn config(&self) -> &CacheConfig {
81        &self.config
82    }
83
84    /// 读取缓存;miss 与缓存空值都返回 `None`。
85    pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
86        match self.lookup(key).await? {
87            Lookup::Hit(bytes) => Ok(Some(JsonCodec.decode(&bytes)?)),
88            Lookup::Null | Lookup::Miss => Ok(None),
89        }
90    }
91
92    /// 写入缓存(使用默认 TTL)。
93    pub async fn set<T: Serialize>(&self, key: &str, value: &T) -> Result<()> {
94        self.set_with_ttl(key, value, self.config.default_ttl).await
95    }
96
97    /// 写入缓存并指定 TTL。
98    pub async fn set_with_ttl<T: Serialize>(
99        &self,
100        key: &str,
101        value: &T,
102        ttl: Duration,
103    ) -> Result<()> {
104        let bytes = JsonCodec.encode(value)?;
105        self.store(key, &bytes, self.jitter(ttl)).await
106    }
107
108    /// 删除缓存。
109    pub async fn delete(&self, key: &str) -> Result<()> {
110        let namespaced = self.client.key_for(key);
111        match self.client.del_bytes(&[namespaced]).await {
112            Ok(_) => Ok(()),
113            Err(error) if self.config.fail_open => {
114                log::warn!("Redis 缓存删除失败(fail-open): {error}");
115                Ok(())
116            }
117            Err(error) => Err(BaseError::RedisOperationFailed(error)),
118        }
119    }
120
121    /// Cache-aside:miss 时调用 loader 并回填。
122    ///
123    /// 启用 `single_flight` 时,同一 key 的并发 miss 只有一个请求回源。
124    pub async fn get_or_load<T, F, Fut>(
125        &self,
126        key: &str,
127        ttl: Option<Duration>,
128        loader: F,
129    ) -> Result<T>
130    where
131        T: Serialize + DeserializeOwned,
132        F: FnOnce() -> Fut,
133        Fut: Future<Output = Result<T>>,
134    {
135        if let Lookup::Hit(bytes) = self.lookup(key).await? {
136            return Ok(JsonCodec.decode(&bytes)?);
137        }
138
139        let key_lock = self.key_lock(key);
140        let guard = if self.config.single_flight {
141            Some(key_lock.clone().lock_owned().await)
142        } else {
143            None
144        };
145
146        let result = async {
147            // double-check:等待锁期间可能已有其他请求回填
148            if let Lookup::Hit(bytes) = self.lookup(key).await? {
149                return Ok(JsonCodec.decode(&bytes)?);
150            }
151            let value = loader().await?;
152            let bytes = JsonCodec.encode(&value)?;
153            self.store(
154                key,
155                &bytes,
156                self.jitter(ttl.unwrap_or(self.config.default_ttl)),
157            )
158            .await?;
159            Ok(value)
160        }
161        .await;
162
163        drop(guard);
164        result
165    }
166
167    /// Cache-aside(允许缓存空值)。
168    ///
169    /// loader 返回 `None` 时写入空值哨兵,避免穿透。
170    pub async fn get_or_load_optional<T, F, Fut>(
171        &self,
172        key: &str,
173        ttl: Option<Duration>,
174        loader: F,
175    ) -> Result<Option<T>>
176    where
177        T: Serialize + DeserializeOwned,
178        F: FnOnce() -> Fut,
179        Fut: Future<Output = Result<Option<T>>>,
180    {
181        match self.lookup(key).await? {
182            Lookup::Hit(bytes) => return Ok(Some(JsonCodec.decode(&bytes)?)),
183            Lookup::Null => return Ok(None),
184            Lookup::Miss => {}
185        }
186
187        let key_lock = self.key_lock(key);
188        let guard = if self.config.single_flight {
189            Some(key_lock.clone().lock_owned().await)
190        } else {
191            None
192        };
193
194        let result = async {
195            match self.lookup(key).await? {
196                Lookup::Hit(bytes) => return Ok(Some(JsonCodec.decode(&bytes)?)),
197                Lookup::Null => return Ok(None),
198                Lookup::Miss => {}
199            }
200            let value = loader().await?;
201            match &value {
202                Some(value) => {
203                    let bytes = JsonCodec.encode(value)?;
204                    self.store(
205                        key,
206                        &bytes,
207                        self.jitter(ttl.unwrap_or(self.config.default_ttl)),
208                    )
209                    .await?;
210                }
211                None => {
212                    self.store(key, NULL_SENTINEL, self.config.null_ttl).await?;
213                }
214            }
215            Ok(value)
216        }
217        .await;
218
219        drop(guard);
220        result
221    }
222
223    async fn lookup(&self, key: &str) -> Result<Lookup> {
224        let namespaced = self.client.key_for(key);
225        match self.client.get_bytes(namespaced).await {
226            Ok(Some(bytes)) if bytes.as_slice() == NULL_SENTINEL => Ok(Lookup::Null),
227            Ok(Some(bytes)) => Ok(Lookup::Hit(bytes)),
228            Ok(None) => Ok(Lookup::Miss),
229            Err(error) if self.config.fail_open => {
230                log::warn!("Redis 缓存读取失败(fail-open,按 miss 处理): {error}");
231                Ok(Lookup::Miss)
232            }
233            Err(error) => Err(BaseError::RedisOperationFailed(error)),
234        }
235    }
236
237    async fn store(&self, key: &str, bytes: &[u8], ttl: Duration) -> Result<()> {
238        let namespaced = self.client.key_for(key);
239        let ttl_seconds = i64::try_from(ttl.as_secs().max(1))
240            .map_err(|_| BaseError::ConfigError("缓存 TTL 超出 i64 范围".to_string()))?;
241        match self
242            .client
243            .setex_bytes(namespaced, ttl_seconds, bytes)
244            .await
245        {
246            Ok(()) => Ok(()),
247            Err(error) if self.config.fail_open => {
248                log::warn!("Redis 缓存写入失败(fail-open): {error}");
249                Ok(())
250            }
251            Err(error) => Err(BaseError::RedisOperationFailed(error)),
252        }
253    }
254
255    fn jitter(&self, ttl: Duration) -> Duration {
256        jitter_ttl(ttl, self.config.ttl_jitter_percent)
257    }
258
259    fn key_lock(&self, key: &str) -> Arc<Mutex<()>> {
260        let mut locks = self
261            .key_locks
262            .lock()
263            .unwrap_or_else(|poisoned| poisoned.into_inner());
264        // 回收已经没有任何持有者的条目
265        locks.retain(|_, weak| weak.strong_count() > 0);
266        if let Some(lock) = locks.get(key).and_then(Weak::upgrade) {
267            return lock;
268        }
269        let lock = Arc::new(Mutex::new(()));
270        locks.insert(key.to_string(), Arc::downgrade(&lock));
271        lock
272    }
273}
274
275/// 按百分比抖动 TTL(0 表示不抖动)。
276fn jitter_ttl(ttl: Duration, percent: u8) -> Duration {
277    let percent = u64::from(percent.min(100));
278    if percent == 0 {
279        return ttl;
280    }
281    let nanos = SystemTime::now()
282        .duration_since(UNIX_EPOCH)
283        .map(|duration| u64::from(duration.subsec_nanos()))
284        .unwrap_or(0);
285    let extra_percent = nanos % (percent + 1);
286    let extra_ms = (ttl.as_millis() as u64).saturating_mul(extra_percent) / 100;
287    ttl + Duration::from_millis(extra_ms)
288}
289
290/// 固定窗口限流结果。
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub struct RateLimitDecision {
293    /// 是否放行。
294    pub allowed: bool,
295    /// 当前窗口内计数。
296    pub current: i64,
297    /// 配置的上限。
298    pub limit: i64,
299    /// 窗口剩余时间(毫秒)。
300    pub reset_after_ms: i64,
301}
302
303const RATE_LIMIT_SCRIPT: &str = r#"
304local current = redis.call('INCR', KEYS[1])
305if current == 1 then
306    redis.call('PEXPIRE', KEYS[1], ARGV[1])
307end
308return {current, redis.call('PTTL', KEYS[1])}
309"#;
310
311/// 通用固定窗口限流器。
312#[derive(Debug, Clone)]
313pub struct RateLimiter {
314    client: RedisClient,
315    prefix: String,
316}
317
318impl RateLimiter {
319    /// 创建限流器。
320    pub fn new(client: RedisClient, prefix: impl Into<String>) -> Self {
321        Self {
322            client,
323            prefix: prefix.into(),
324        }
325    }
326
327    /// 对 `key` 在 `window` 内做固定窗口计数,返回是否放行。
328    pub async fn check(
329        &self,
330        key: &str,
331        limit: i64,
332        window: Duration,
333    ) -> Result<RateLimitDecision> {
334        if limit <= 0 {
335            return Err(BaseError::ConfigError("限流 limit 必须大于 0".to_string()));
336        }
337        let window_ms = i64::try_from(window.as_millis())
338            .map_err(|_| BaseError::ConfigError("限流窗口超出 i64 范围".to_string()))?;
339        if window_ms <= 0 {
340            return Err(BaseError::ConfigError(
341                "限流窗口必须大于 0 毫秒".to_string(),
342            ));
343        }
344
345        let cache_key = format!("{}:{}", self.prefix, key);
346        let namespaced = match self.client.namespace() {
347            Some(namespace) => namespace.key_str(&cache_key),
348            None => cache_key,
349        };
350        let script = self.client.script(RATE_LIMIT_SCRIPT);
351        let (current, ttl_ms): (i64, i64) = self
352            .client
353            .eval_script(&script, &[namespaced], &[window_ms.to_string()])
354            .await
355            .map_err(BaseError::RedisOperationFailed)?;
356
357        Ok(RateLimitDecision {
358            allowed: current <= limit,
359            current,
360            limit,
361            reset_after_ms: ttl_ms.max(0),
362        })
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[test]
371    fn jitter_is_noop_when_percent_is_zero() {
372        let ttl = Duration::from_secs(100);
373        assert_eq!(jitter_ttl(ttl, 0), ttl);
374    }
375
376    #[test]
377    fn jitter_stays_within_configured_percent() {
378        let ttl = Duration::from_secs(100);
379        for _ in 0..100 {
380            let jittered = jitter_ttl(ttl, 10);
381            assert!(jittered >= ttl);
382            assert!(jittered <= ttl + Duration::from_secs(10));
383        }
384    }
385
386    #[test]
387    fn null_sentinel_is_not_valid_json() {
388        assert!(serde_json::from_slice::<serde_json::Value>(NULL_SENTINEL).is_err());
389    }
390}