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
//! Copyright (c) 2025-2026, Kirky.X
//!
//! MIT License
//!
//! 该模块定义了L1缓存后端的实现,基于内存的高速缓存。
#[cfg(feature = "l1-moka")]
use crate::config::EvictionPolicy;
#[cfg(feature = "l1-moka")]
use crate::error::Result;
#[cfg(feature = "l1-moka")]
use moka::future::Cache;
#[cfg(feature = "l1-moka")]
use std::time::{Duration, Instant};
#[cfg(feature = "l1-moka")]
use tracing::{debug, instrument};
/// 缓存条目类型:(数据, 版本/时间戳, 过期时间)
pub type CacheEntry = (Vec<u8>, u64, Option<Instant>);
/// L1缓存后端实现
///
/// 基于内存的高速缓存实现,使用Moka作为底层缓存库
#[cfg(feature = "l1-moka")]
#[derive(Clone)]
pub struct L1Backend {
// 值: (数据, 版本/时间戳, 过期时间)
cache: Cache<String, CacheEntry>,
// 淘汰策略
eviction_policy: EvictionPolicy,
}
#[cfg(feature = "l1-moka")]
impl L1Backend {
/// 创建新的L1缓存后端实例(使用默认策略)
///
/// # 参数
///
/// * `capacity` - 缓存最大容量(条目数量)
///
/// # 返回值
///
/// 返回新的L1Backend实例
///
/// # 注意
///
/// Moka缓存库使用条目数量而非字节数作为容量单位。
pub fn new(capacity: u64) -> Self {
Self::with_policy(capacity, EvictionPolicy::default())
}
/// 创建新的L1缓存后端实例(指定淘汰策略)
///
/// # 参数
///
/// * `capacity` - 缓存最大容量(条目数量)
/// * `policy` - 淘汰策略
///
/// # 返回值
///
/// 返回新的L1Backend实例
///
/// # 注意
///
/// Moka缓存库使用条目数量而非字节数作为容量单位。
pub fn with_policy(capacity: u64, policy: EvictionPolicy) -> Self {
// 注意:Moka 0.12 使用 TinyLFU 作为默认策略
// 不同策略的行为在 Moka 内部实现,目前我们只存储策略信息
// 实际策略效果由 Moka 库控制
let cache: Cache<String, CacheEntry> = Cache::builder().max_capacity(capacity).build();
Self {
cache,
eviction_policy: policy,
}
}
/// 获取当前使用的淘汰策略
pub fn eviction_policy(&self) -> EvictionPolicy {
self.eviction_policy
}
/// 重建缓存(用于策略切换)
///
/// 当策略变更时,需要重建缓存以应用新策略
///
/// # 参数
///
/// * `new_capacity` - 新的缓存容量(条目数量)
/// * `new_policy` - 新的淘汰策略
/// * `entries` - 需要保留的现有条目
///
/// # 注意
///
/// Moka缓存库使用条目数量而非字节数作为容量单位。
pub async fn rebuild_with_policy(
&self,
new_capacity: u64,
new_policy: EvictionPolicy,
entries: Vec<(String, CacheEntry)>,
) {
// 创建新缓存
let new_cache = match new_policy {
EvictionPolicy::Lru => Cache::builder().max_capacity(new_capacity).build(),
EvictionPolicy::Lfu | EvictionPolicy::TinyLfu => {
Cache::builder().max_capacity(new_capacity).build()
}
EvictionPolicy::Random => Cache::builder().max_capacity(new_capacity).build(),
};
// 重新插入所有有效条目
for (key, (value, version, expire_at)) in entries {
// 只保留未过期的条目
if let Some(expire_time) = expire_at {
if Instant::now() < expire_time {
new_cache.insert(key, (value, version, expire_at)).await;
}
} else {
new_cache.insert(key, (value, version, expire_at)).await;
}
}
// 替换缓存(这里使用内部可变性的简化方案)
// 注意:由于 Cache 不支持克隆,我们需要通过这种方式来处理
// 实际使用中可能需要使用 Arc<Cache> 来共享
debug!(
"L1 cache rebuilt with policy {:?}, capacity {}",
new_policy, new_capacity
);
}
/// 获取带有元数据的缓存值
///
/// # 参数
///
/// * `key` - 缓存键
///
/// # 返回值
///
/// 返回缓存值和版本号的元组,如果不存在则返回None
#[instrument(skip(self), level = "debug")]
pub async fn get_with_metadata(&self, key: &str) -> Result<Option<(Vec<u8>, u64)>> {
let result = self.cache.get(key).await;
match result {
Some((bytes, version, expire_at)) => {
if let Some(expire_time) = expire_at {
if Instant::now() >= expire_time {
self.cache.remove(key).await;
debug!("L1 get_with_metadata: key={}, expired=true, removed", key);
return Ok(None);
}
}
debug!("L1 get_with_metadata: key={}, found=true", key);
Ok(Some((bytes, version)))
}
None => {
debug!("L1 get_with_metadata: key={}, found=false", key);
Ok(None)
}
}
}
/// 获取缓存值(字节形式)
///
/// # 参数
///
/// * `key` - 缓存键
///
/// # 返回值
///
/// 返回缓存值,如果不存在则返回None
#[instrument(skip(self), level = "debug")]
pub async fn get_bytes(&self, key: &str) -> Result<Option<Vec<u8>>> {
let result = self.cache.get(key).await;
match result {
Some((bytes, _, expire_at)) => {
if let Some(expire_time) = expire_at {
if Instant::now() >= expire_time {
self.cache.remove(key).await;
debug!("L1 get_bytes: key={}, expired=true, removed", key);
return Ok(None);
}
}
debug!("L1 get_bytes: key={}, found=true", key);
Ok(Some(bytes))
}
None => {
debug!("L1 get_bytes: key={}, found=false", key);
Ok(None)
}
}
}
/// 设置缓存值(字节形式)
///
/// # 参数
///
/// * `key` - 缓存键
/// * `value` - 缓存值(字节数组)
/// * `ttl` - 过期时间(秒),None表示使用默认值300秒
///
/// # 返回值
///
/// 返回操作结果
#[instrument(skip(self), level = "debug")]
pub async fn set_bytes(&self, key: &str, value: Vec<u8>, ttl: Option<u64>) -> Result<()> {
debug!(
"L1 set_bytes: key={}, value_len={}, ttl={:?}",
key,
value.len(),
ttl
);
self.set_with_metadata(key, value, ttl.unwrap_or(300), 0)
.await
}
/// 设置带有元数据的缓存值
///
/// # 参数
///
/// * `key` - 缓存键
/// * `value` - 缓存值(字节数组)
/// * `ttl` - 过期时间(秒)
/// * `version` - 版本号
///
/// # 返回值
///
/// 返回操作结果
#[instrument(skip(self), level = "debug")]
pub async fn set_with_metadata(
&self,
key: &str,
value: Vec<u8>,
ttl: u64,
version: u64,
) -> Result<()> {
debug!(
"L1 set_with_metadata: key={}, value_len={}, ttl={}, version={}",
key,
value.len(),
ttl,
version
);
let expire_at = if ttl > 0 {
Some(Instant::now() + Duration::from_secs(ttl))
} else {
None
};
self.cache
.insert(key.to_string(), (value, version, expire_at))
.await;
debug!("L1 set_with_metadata: key={} 插入完成", key);
Ok(())
}
/// 删除缓存项
///
/// # 参数
///
/// * `key` - 缓存键
///
/// # 返回值
///
/// 返回操作结果
#[instrument(skip(self), level = "debug")]
pub async fn delete(&self, key: &str) -> Result<()> {
debug!("L1 delete: key={}", key);
self.cache.remove(key).await;
debug!("L1 delete: key={} 删除完成", key);
Ok(())
}
/// 清空 L1 缓存
///
/// # 返回值
///
/// 返回操作结果
#[instrument(skip(self), level = "debug")]
pub fn clear(&self) -> Result<()> {
debug!("L1 clear: 清空所有缓存项");
self.cache.invalidate_all();
debug!("L1 clear: 缓存已清空");
Ok(())
}
/// 查询键的剩余生存时间(TTL)
///
/// # 参数
///
/// * `key` - 缓存键
///
/// # 返回值
///
/// 返回剩余秒数,如果键不存在或未设置 TTL 则返回 None
#[instrument(skip(self), level = "debug")]
pub async fn ttl(&self, key: &str) -> Result<Option<u64>> {
let result = self.cache.get(key).await;
match result {
Some((_, _, expire_at)) => {
if let Some(expire_time) = expire_at {
let now = Instant::now();
if now >= expire_time {
// 已过期,移除并返回 None
self.cache.remove(key).await;
debug!("L1 ttl: key={}, expired=true, removed", key);
Ok(None)
} else {
let remaining = (expire_time - now).as_secs();
debug!("L1 ttl: key={}, remaining={}", key, remaining);
Ok(Some(remaining))
}
} else {
// 未设置 TTL
debug!("L1 ttl: key={}, no_ttl=true", key);
Ok(None)
}
}
None => {
debug!("L1 ttl: key={}, not_found=true", key);
Ok(None)
}
}
}
/// 刷新键的过期时间
///
/// # 参数
///
/// * `key` - 缓存键
/// * `ttl` - 新的过期时间(秒)
///
/// # 返回值
///
/// 返回操作是否成功
#[instrument(skip(self), level = "debug")]
pub async fn refresh_ttl(&self, key: &str, ttl: u64) -> Result<bool> {
let result = self.cache.get(key).await;
match result {
Some((value, version, _)) => {
// 更新过期时间
let expire_at = if ttl > 0 {
Some(Instant::now() + Duration::from_secs(ttl))
} else {
None
};
self.cache
.insert(key.to_string(), (value, version, expire_at))
.await;
debug!("L1 refresh_ttl: key={}, ttl={}, success=true", key, ttl);
Ok(true)
}
None => {
debug!("L1 refresh_ttl: key={}, not_found=true", key);
Ok(false)
}
}
}
}