oxcache 0.5.0-rc.7

A production-grade multi-level cache library for Rust: L1 memory (Moka/DashMap) + L2 distributed (Redis/Valkey/Dragonfly/Aerospike) + optional L3 disk (redb).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: MIT
// MockBackend 实现 - 用于测试

#[cfg(test)]
use std::collections::HashMap;
#[cfg(test)]
use std::sync::Arc;
#[cfg(test)]
use std::time::{Duration, Instant};
#[cfg(test)]
use tokio::sync::RwLock;

/// 单条 Mock 缓存条目:(value, expires_at),`None` 表示永不过期。
#[cfg(test)]
type MockEntry = (Vec<u8>, Option<Instant>);

/// 故障注入标志:控制 MockBackend 的失败行为(用于测试降级/错误路径)
#[cfg(test)]
#[derive(Clone, Debug, Default)]
pub struct MockFaultConfig {
    /// 为 true 时 `get` 返回错误(模拟 L1 故障)
    pub fail_get: bool,
    /// 为 true 时 `set` 返回错误
    pub fail_set: bool,
    /// 为 true 时 `health_check` 返回错误
    pub fail_health: bool,
    /// 为 true 时 `expire` 返回错误(模拟 TTL 调整写入失败路径)
    pub fail_expire: bool,
}

/// Mock 后端 - 用于测试的模拟缓存后端
///
/// 内部数据结构存储 `(value, expires_at)`:`expires_at=None` 表示永不过期,
/// `Some(Instant)` 表示在该时刻过期(`get` 时 lazy 校验并清理)。
#[cfg(test)]
pub struct MockBackend {
    name: &'static str,
    score: u8,
    persistent: bool,
    data: Arc<RwLock<HashMap<String, MockEntry>>>,
    fault: MockFaultConfig,
}

#[cfg(test)]
impl MockBackend {
    pub fn new(name: &'static str, score: u8, persistent: bool) -> Self {
        Self {
            name,
            score,
            persistent,
            data: Arc::new(RwLock::new(HashMap::new())),
            fault: MockFaultConfig::default(),
        }
    }

    /// 注入故障:`get` 返回错误
    pub fn with_fail_get(mut self) -> Self {
        self.fault.fail_get = true;
        self
    }

    /// 注入故障:`set` 返回错误
    pub fn with_fail_set(mut self) -> Self {
        self.fault.fail_set = true;
        self
    }

    /// 注入故障:`health_check` 返回错误
    pub fn with_fail_health(mut self) -> Self {
        self.fault.fail_health = true;
        self
    }

    /// 注入故障:`expire` 返回错误
    pub fn with_fail_expire(mut self) -> Self {
        self.fault.fail_expire = true;
        self
    }

    /// 检查是否配置了 `get` 故障
    pub fn fails_get(&self) -> bool {
        self.fault.fail_get
    }
}

#[cfg(test)]
impl crate::backend::BackendScore for MockBackend {
    fn score(&self) -> u8 {
        self.score
    }

    fn is_persistent(&self) -> bool {
        self.persistent
    }

    fn backend_name(&self) -> &'static str {
        self.name
    }
}

#[cfg(test)]
#[async_trait::async_trait]
impl crate::backend::CacheReader for MockBackend {
    async fn get(&self, key: &str) -> crate::error::OxCacheResult<Option<Vec<u8>>> {
        if self.fault.fail_get {
            return Err(crate::error::OxCacheError::Operation(
                "MockBackend get fault injected".to_string(),
            ));
        }
        let now = Instant::now();
        let mut data = self.data.write().await;
        // 单次查找:克隆 value 与 expires_at 后立即释放不可变借用
        let entry = data.get(key).map(|(v, exp)| (v.clone(), *exp));
        if let Some((value, expires_at)) = entry {
            if let Some(exp) = expires_at
                && exp <= now
            {
                // lazy 过期清理
                data.remove(key);
                return Ok(None);
            }
            return Ok(Some(value));
        }
        Ok(None)
    }

    async fn exists(&self, key: &str) -> crate::error::OxCacheResult<bool> {
        let now = Instant::now();
        let mut data = self.data.write().await;
        if let Some((_v, expires_at)) = data.get(key) {
            if let Some(exp) = expires_at
                && *exp <= now
            {
                data.remove(key);
                return Ok(false);
            }
            return Ok(true);
        }
        Ok(false)
    }

    async fn ttl(&self, key: &str) -> crate::error::OxCacheResult<Option<Duration>> {
        let now = Instant::now();
        let data = self.data.read().await;
        if let Some((_v, Some(exp))) = data.get(key) {
            return Ok(exp.checked_duration_since(now));
        }
        Ok(None)
    }

    async fn len(&self) -> crate::error::OxCacheResult<u64> {
        let data = self.data.read().await;
        Ok(data.len() as u64)
    }

    async fn is_empty(&self) -> crate::error::OxCacheResult<bool> {
        let data = self.data.read().await;
        Ok(data.is_empty())
    }

    async fn capacity(&self) -> crate::error::OxCacheResult<u64> {
        Ok(0)
    }

    async fn stats(&self) -> crate::error::OxCacheResult<HashMap<String, String>> {
        let mut stats = HashMap::new();
        stats.insert("type".to_string(), self.name.to_string());
        Ok(stats)
    }

    async fn keys(&self, pattern: &str) -> crate::error::OxCacheResult<Vec<String>> {
        let now = Instant::now();
        let mut data = self.data.write().await;

        // Lazy 过期清理
        let expired_keys: Vec<String> = data
            .iter()
            .filter(|(_, (_, exp))| exp.is_some_and(|e| e <= now))
            .map(|(k, _)| k.clone())
            .collect();
        for k in &expired_keys {
            data.remove(k);
        }

        // Pattern 匹配(在清理后执行)
        let matched: Vec<String> = data
            .keys()
            .filter(|k| crate::backend::interface::glob_match(pattern, k))
            .cloned()
            .collect();

        Ok(matched)
    }
}

#[cfg(test)]
#[async_trait::async_trait]
impl crate::backend::CacheWriter for MockBackend {
    async fn set(
        &self,
        key: Arc<str>,
        value: Arc<Vec<u8>>,
        ttl: Option<Duration>,
    ) -> crate::error::OxCacheResult<()> {
        if self.fault.fail_set {
            return Err(crate::error::OxCacheError::Operation(
                "MockBackend set fault injected".to_string(),
            ));
        }
        let mut data = self.data.write().await;
        let expires_at = ttl.map(|d| Instant::now() + d);
        data.insert(key.to_string(), ((*value).clone(), expires_at));
        Ok(())
    }

    async fn delete(&self, key: &str) -> crate::error::OxCacheResult<()> {
        let mut data = self.data.write().await;
        data.remove(key);
        Ok(())
    }

    async fn clear(&self) -> crate::error::OxCacheResult<()> {
        let mut data = self.data.write().await;
        data.clear();
        Ok(())
    }

    async fn expire(&self, key: &str, ttl: Duration) -> crate::error::OxCacheResult<bool> {
        if self.fault.fail_expire {
            return Err(crate::error::OxCacheError::Operation(
                "mock expire failure injected".to_string(),
            ));
        }
        let mut data = self.data.write().await;
        // 单次查找:避免 contains_key + get_mut 的双重哈希探测
        if let Some(entry) = data.get_mut(key) {
            entry.1 = Some(Instant::now() + ttl);
            Ok(true)
        } else {
            Ok(false)
        }
    }
}

#[cfg(test)]
#[async_trait::async_trait]
impl crate::backend::CacheConnector for MockBackend {
    async fn health_check(&self) -> crate::error::OxCacheResult<()> {
        if self.fault.fail_health {
            return Err(crate::error::OxCacheError::Operation(
                "MockBackend health fault injected".to_string(),
            ));
        }
        Ok(())
    }

    async fn shutdown(&self) {}

    fn backend_kind(&self) -> crate::backend::interface::BackendKind {
        crate::backend::interface::BackendKind::Mock
    }

    fn as_atomic_writer(&self) -> Option<&dyn crate::backend::AtomicCacheWriter> {
        Some(self)
    }
}

// CacheBackend is automatically implemented via blanket implementation

#[cfg(test)]
#[async_trait::async_trait]
impl crate::backend::AtomicCacheWriter for MockBackend {
    async fn incr(
        &self,
        key: &str,
        delta: i64,
        ttl: Option<Duration>,
    ) -> crate::error::OxCacheResult<i64> {
        let mut data = self.data.write().await;
        let current = match data.get(key) {
            Some((v, _)) => {
                let s = String::from_utf8(v.clone()).map_err(|e| {
                    crate::error::OxCacheError::Operation(format!(
                        "incr: invalid UTF-8 in stored value for key '{}': {}",
                        key, e
                    ))
                })?;
                s.parse::<i64>().map_err(|e| {
                    crate::error::OxCacheError::Operation(format!(
                        "incr: invalid integer in stored value for key '{}': {}",
                        key, e
                    ))
                })?
            }
            None => 0,
        };
        let new_val = current.checked_add(delta).ok_or_else(|| {
            crate::error::OxCacheError::Operation(format!(
                "incr: i64 overflow for key '{}': {} + {}",
                key, current, delta
            ))
        })?;
        let expires_at = ttl.map(|d| Instant::now() + d);
        data.insert(
            key.to_string(),
            (new_val.to_string().into_bytes(), expires_at),
        );
        Ok(new_val)
    }

    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        new: Vec<u8>,
        ttl: Option<Duration>,
    ) -> crate::error::OxCacheResult<bool> {
        let mut data = self.data.write().await;
        match expected {
            None => {
                // SETNX: set only if absent
                if data.contains_key(key) {
                    Ok(false)
                } else {
                    let expires_at = ttl.map(|d| Instant::now() + d);
                    data.insert(key.to_string(), (new, expires_at));
                    Ok(true)
                }
            }
            Some(exp_bytes) => match data.get(key) {
                Some((current_val, _)) if current_val == exp_bytes => {
                    let expires_at = ttl.map(|d| Instant::now() + d);
                    data.insert(key.to_string(), (new, expires_at));
                    Ok(true)
                }
                _ => Ok(false),
            },
        }
    }

    async fn set_if_absent(
        &self,
        key: &str,
        value: Vec<u8>,
        ttl: Option<Duration>,
    ) -> crate::error::OxCacheResult<bool> {
        let mut data = self.data.write().await;
        if data.contains_key(key) {
            return Ok(false);
        }
        let expires_at = ttl.map(|d| Instant::now() + d);
        data.insert(key.to_string(), (value, expires_at));
        Ok(true)
    }
}

#[cfg(test)]
impl crate::backend::SyncAtomicCacheWriter for MockBackend {
    fn incr(
        &self,
        key: &str,
        delta: i64,
        ttl: Option<Duration>,
    ) -> crate::error::OxCacheResult<i64> {
        // Mirror the async incr: propagate UTF-8/parse/overflow errors instead
        // of silently treating corrupt data as 0.
        let mut data = self.data.blocking_write();
        let current = match data.get(key) {
            Some((v, _)) => {
                let s = String::from_utf8(v.clone()).map_err(|e| {
                    crate::error::OxCacheError::Operation(format!(
                        "incr: invalid UTF-8 in stored value for key '{}': {}",
                        key, e
                    ))
                })?;
                s.parse::<i64>().map_err(|e| {
                    crate::error::OxCacheError::Operation(format!(
                        "incr: invalid integer in stored value for key '{}': {}",
                        key, e
                    ))
                })?
            }
            None => 0,
        };
        let new_val = current.checked_add(delta).ok_or_else(|| {
            crate::error::OxCacheError::Operation(format!(
                "incr: i64 overflow for key '{}': {} + {}",
                key, current, delta
            ))
        })?;
        let expires_at = ttl.map(|d| Instant::now() + d);
        data.insert(
            key.to_string(),
            (new_val.to_string().into_bytes(), expires_at),
        );
        Ok(new_val)
    }

    fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        new: Vec<u8>,
        ttl: Option<Duration>,
    ) -> crate::error::OxCacheResult<bool> {
        let mut data = self.data.blocking_write();
        match expected {
            None => {
                if data.contains_key(key) {
                    Ok(false)
                } else {
                    let expires_at = ttl.map(|d| Instant::now() + d);
                    data.insert(key.to_string(), (new, expires_at));
                    Ok(true)
                }
            }
            Some(exp_bytes) => match data.get(key) {
                Some((current_val, _)) if current_val == exp_bytes => {
                    let expires_at = ttl.map(|d| Instant::now() + d);
                    data.insert(key.to_string(), (new, expires_at));
                    Ok(true)
                }
                _ => Ok(false),
            },
        }
    }

    fn set_if_absent(
        &self,
        key: &str,
        value: Vec<u8>,
        ttl: Option<Duration>,
    ) -> crate::error::OxCacheResult<bool> {
        let mut data = self.data.blocking_write();
        if data.contains_key(key) {
            return Ok(false);
        }
        let expires_at = ttl.map(|d| Instant::now() + d);
        data.insert(key.to_string(), (value, expires_at));
        Ok(true)
    }
}

#[cfg(test)]
mod tests;