wordval-cache 1.0.6

Wordval cache abstraction: local in-memory cache + Redis integration
Documentation
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! 测试 Cache 完整生命周期 + 回归测试

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use wordval_cache::{Cache, LocalCache, SharedCache};

#[tokio::test]
async fn test_set_and_get() {
    let cache = LocalCache::new(100, 0);
    cache.set("key1", &"value1".to_string()).await.unwrap();
    let val: Option<String> = cache.get("key1").await.unwrap();
    assert_eq!(val, Some("value1".to_string()));
}

#[tokio::test]
async fn test_get_missing() {
    let cache = LocalCache::new(100, 0);
    let val: Option<String> = cache.get("nokey").await.unwrap();
    assert_eq!(val, None);
}

#[tokio::test]
async fn test_set_ex_ttl() {
    let cache = LocalCache::new(100, 0);
    cache.set_ex("temp", &"data", 1).await.unwrap();
    let val: Option<String> = cache.get("temp").await.unwrap();
    assert_eq!(val, Some("data".to_string()));
    tokio::time::sleep(tokio::time::Duration::from_millis(1200)).await;
    let val: Option<String> = cache.get("temp").await.unwrap();
    assert_eq!(val, None);
}

// ttl=0 对齐 Redis "invalid expire time",所有带 TTL 的写入路径均应报错
#[tokio::test]
async fn test_zero_ttl_rejected() {
    let cache = LocalCache::new(100, 0);
    assert!(cache.set_ex("k1", &"v", 0).await.is_err());
    assert!(cache.set_nx("k2", &"v", 0).await.is_err());
    assert!(cache.set_raw_ex("k3", b"{}", 0).await.is_err());
    assert!(cache.expire("k4", 0).await.is_err());
    // 空成员集合操作仍应正常(不受 TTL 校验影响)
    assert_eq!(cache.sadd("s", &[]).await.unwrap(), 0);
    assert_eq!(cache.srem("s", &[]).await.unwrap(), 0);
}

#[tokio::test]
async fn test_delete() {
    let cache = LocalCache::new(100, 0);
    cache.set("del", &"val").await.unwrap();
    cache.del("del").await.unwrap();
    let val: Option<String> = cache.get("del").await.unwrap();
    assert_eq!(val, None);
}

#[tokio::test]
async fn test_exists() {
    let cache = LocalCache::new(100, 0);
    cache.set("e1", &"v").await.unwrap();
    assert!(cache.exists("e1").await.unwrap());
    assert!(!cache.exists("e2").await.unwrap());
}

#[tokio::test]
async fn test_incr() {
    let cache = LocalCache::new(100, 0);
    let v = cache.incr("counter", 5).await.unwrap();
    assert_eq!(v, 5);
    let v = cache.incr("counter", 3).await.unwrap();
    assert_eq!(v, 8);
}

#[tokio::test]
async fn test_set_nx() {
    let cache = LocalCache::new(100, 0);
    let ok = cache.set_nx("nx", &"first", 3600).await.unwrap();
    assert!(ok);
    let ok = cache.set_nx("nx", &"second", 3600).await.unwrap();
    assert!(!ok);
    let val: Option<String> = cache.get("nx").await.unwrap();
    assert_eq!(val, Some("first".to_string()));
}

#[tokio::test]
async fn test_eviction() {
    let cache = LocalCache::new(3, 0);
    cache.set("a", &"1").await.unwrap();
    cache.set("b", &"2").await.unwrap();
    cache.set("c", &"3").await.unwrap();
    cache.set("d", &"4").await.unwrap(); // triggers eviction
    let count = if cache.exists("a").await.unwrap() {
        1
    } else {
        0
    } + if cache.exists("b").await.unwrap() {
        1
    } else {
        0
    } + if cache.exists("c").await.unwrap() {
        1
    } else {
        0
    } + if cache.exists("d").await.unwrap() {
        1
    } else {
        0
    };
    assert_eq!(count, 3); // one evicted, d added = 3 total
}

#[tokio::test]
async fn test_stats() {
    let cache = LocalCache::new(100, 0);
    cache.set("s1", &"v").await.unwrap();
    cache.set("s2", &"v2").await.unwrap();
    let _: Option<String> = cache.get("s1").await.unwrap();
    let _: Option<String> = cache.get("missing").await.unwrap();
    let stats = cache.stats();
    assert_eq!(stats.sets, 2);
    assert_eq!(stats.hits, 1);
    assert_eq!(stats.misses, 1);
}

// ──── 回归测试:get 过期删除竞态 ──────────────────────

#[tokio::test]
async fn test_get_expired_does_not_race_with_concurrent_set() {
    let cache = LocalCache::new(100, 0);
    cache.set_ex("k", &"old", 1).await.unwrap();
    tokio::time::sleep(Duration::from_millis(1100)).await;

    // 在 get 发现过期 -> drop(g) 之间,另一线程写入新值
    let c1 = cache.clone();
    let h = tokio::spawn(async move {
        c1.set("k", &"new").await.unwrap();
    });

    // 即使并发写入,get 也不应误删新值(remove_if_expired 条件删除)
    let _ = cache.get::<String>("k").await.unwrap();
    h.await.unwrap();

    let val: Option<String> = cache.get("k").await.unwrap();
    assert_eq!(
        val,
        Some("new".to_string()),
        "并发写入的新值不应被竞态误删"
    );
}

// ──── 回归测试:sadd 语义 ─────────────────────────────

#[tokio::test]
async fn test_sadd_dedup_input_members() {
    let cache = LocalCache::new(100, 0);
    let added = cache
        .sadd("set1", &["a".into(), "a".into(), "b".into()])
        .await
        .unwrap();
    assert_eq!(added, 2);
    let members = cache.smembers("set1").await.unwrap();
    assert_eq!(members.len(), 2);
    assert!(members.contains(&"a".to_string()));
    assert!(members.contains(&"b".to_string()));
}

#[tokio::test]
async fn test_sadd_preserves_existing_ttl() {
    let cache = LocalCache::new(100, 0);
    cache.set_ex("set1", &["x".to_string()], 3600).await.unwrap();

    // sadd 到已存在的 key(虽然是数组形式,但这里用 sadd 语义写入)
    // 先模拟已有值:JSON 数组
    cache.set_ex("set1", &["old".to_string()], 3600).await.unwrap();
    cache
        .sadd("set1", &["new1".into(), "new2".into()])
        .await
        .unwrap();

    // 不应抹掉过期时间
    let exists = cache.exists("set1").await.unwrap();
    assert!(exists);
}

#[tokio::test]
async fn test_sadd_expired_key_recreates_without_ttl() {
    let cache = LocalCache::new(100, 0);
    cache.set_ex("set1", &["old".to_string()], 1).await.unwrap();
    tokio::time::sleep(Duration::from_millis(1100)).await;

    let added = cache.sadd("set1", &["fresh".into()]).await.unwrap();
    assert_eq!(added, 1);

    // 过期重建后无 TTL(与 incr 过期语义一致:重新创建=无 TTL)
    let val: Option<Vec<String>> = cache.get("set1").await.unwrap();
    assert_eq!(val, Some(vec!["fresh".to_string()]));
}

// ──── 回归测试:incr 溢出 / 非整数 ────────────────────

#[tokio::test]
async fn test_incr_overflow_returns_error() {
    let cache = LocalCache::new(100, 0);
    cache.set("i", &i64::MAX).await.unwrap();
    let err = cache.incr("i", 1).await.unwrap_err();
    let msg = format!("{}", err);
    assert!(
        msg.contains("overflow"),
        "incr i64 溢出应返回错误,实际: {}",
        msg
    );
}

#[tokio::test]
async fn test_incr_non_integer_returns_error() {
    let cache = LocalCache::new(100, 0);
    cache.set("s", &"not_a_number").await.unwrap();
    let err = cache.incr("s", 1).await.unwrap_err();
    let msg = format!("{}", err);
    assert!(
        msg.contains("not an integer"),
        "incr 非整数应返回 WRONGTYPE 风格错误,实际: {}",
        msg
    );
}

// ──── 回归测试:expire / exists 对已过期 key ─────────

#[tokio::test]
async fn test_expire_on_expired_key_returns_false() {
    let cache = LocalCache::new(100, 0);
    cache.set_ex("e", &"v", 1).await.unwrap();
    tokio::time::sleep(Duration::from_millis(1100)).await;

    let ok = cache.expire("e", 3600).await.unwrap();
    assert!(!ok, "对过期 key 执行 expire 应返回 false(Redis 语义)");

    let exists = cache.exists("e").await.unwrap();
    assert!(!exists, "过期 key 的 exists 应返回 false");
}

#[tokio::test]
async fn test_exists_cleanup_expired() {
    let cache = LocalCache::new(100, 0);
    cache.set_ex("e", &"v", 1).await.unwrap();
    tokio::time::sleep(Duration::from_millis(1100)).await;

    let exists = cache.exists("e").await.unwrap();
    assert!(!exists);
    // 统计也计入 miss
    let stats = cache.stats();
    assert_eq!(stats.misses, 1);
}

// ──── 回归测试:srem 空集合删除 key ────────────────────

#[tokio::test]
async fn test_srem_empty_set_deletes_key() {
    let cache = LocalCache::new(100, 0);
    cache.sadd("set1", &["a".into(), "b".into()]).await.unwrap();
    let removed = cache.srem("set1", &["a".into(), "b".into()]).await.unwrap();
    assert_eq!(removed, 2);
    let exists = cache.exists("set1").await.unwrap();
    assert!(!exists, "集合变空后 key 应被删除(对齐 Redis)");
}

// ──── 回归测试:set_nx 容量限制 ────────────────────────

#[tokio::test]
async fn test_set_nx_respects_capacity() {
    let cache = LocalCache::new(2, 0);
    assert!(cache.set_nx("a", &"1", 3600).await.unwrap());
    assert!(cache.set_nx("b", &"2", 3600).await.unwrap());
    // 满员时,第三个 set_nx 应触发淘汰,然后写入成功
    assert!(cache.set_nx("c", &"3", 3600).await.unwrap());
    let total = cache.len();
    assert_eq!(total, 2, "容量为 2 时 set_nx 不应突破上限");
}

// ──── 回归测试:SharedCache stats 委派 ────────────────

#[tokio::test]
async fn test_shared_cache_stats_delegation() {
    let local = LocalCache::new(100, 0);
    local.set("s1", &"v").await.unwrap();
    let _: Option<String> = local.get("s1").await.unwrap();

    let shared = SharedCache::Local(local);
    let stats = shared.stats();
    assert_eq!(stats.sets, 1);
    assert_eq!(stats.hits, 1);
}

// ──── 回归测试:raw bytes 直通 ─────────────────────────

#[tokio::test]
async fn test_raw_bytes_roundtrip() {
    let cache = LocalCache::new(100, 0);
    let raw = b"{\"hello\":\"world\"}".as_slice();
    cache.set_raw("raw1", raw).await.unwrap();
    let got = cache.get_raw("raw1").await.unwrap().unwrap();
    assert_eq!(got, raw);
}

#[tokio::test]
async fn test_raw_bytes_ex() {
    let cache = LocalCache::new(100, 0);
    let raw = b"{\"k\":1}".as_slice();
    cache.set_raw_ex("raw2", raw, 1).await.unwrap();
    tokio::time::sleep(Duration::from_millis(1200)).await;
    let got = cache.get_raw("raw2").await.unwrap();
    assert_eq!(got, None);
}

#[tokio::test]
async fn test_raw_invalid_json_rejected() {
    let cache = LocalCache::new(100, 0);
    let err = cache
        .set_raw("raw3", b"not json")
        .await
        .unwrap_err();
    assert!(
        format!("{}", err).contains("EOF") || format!("{}", err).contains("expected"),
        "非法 JSON 应被拒绝"
    );
}

// ──── 回归测试:cleanup_expired / delete_pattern 单趟 ──

#[tokio::test]
async fn test_cleanup_expired_count() {
    let cache = LocalCache::new(100, 0);
    cache.set_ex("a", &"1", 1).await.unwrap();
    cache.set_ex("b", &"2", 1).await.unwrap();
    cache.set("c", &"3").await.unwrap();
    tokio::time::sleep(Duration::from_millis(1100)).await;

    let cleaned = cache.cleanup_expired();
    assert_eq!(cleaned, 2);
    assert!(!cache.exists("a").await.unwrap());
    assert!(!cache.exists("b").await.unwrap());
    assert!(cache.exists("c").await.unwrap());

    let stats = cache.stats();
    assert_eq!(stats.expired_cleanups, 2);
}

#[tokio::test]
async fn test_delete_pattern_count() {
    let cache = LocalCache::new(100, 0);
    cache.set("pre:a", &"1").await.unwrap();
    cache.set("pre:b", &"2").await.unwrap();
    cache.set("other", &"3").await.unwrap();

    let deleted = cache.delete_pattern("pre:*").await.unwrap();
    assert_eq!(deleted, 2);
    assert!(!cache.exists("pre:a").await.unwrap());
    assert!(!cache.exists("pre:b").await.unwrap());
    assert!(cache.exists("other").await.unwrap());
}

// ──── 回归测试:后台清理不泄漏 ─────────────────────────

#[tokio::test]
async fn test_background_cleanup_exits_when_cache_dropped() {
    // 缩短清理间隔到 1s,让后台任务在测试时间窗内真实跑起来
    let cache = LocalCache::new(100, 0).with_cleanup_interval(1);
    cache.start_background_cleanup();
    cache.set_ex("a", &"1", 1).await.unwrap();
    tokio::time::sleep(Duration::from_millis(2300)).await;

    // 存活期间后台任务应已完成清理(未经任何读操作触发惰性回收)
    assert!(
        cache.stats().expired_cleanups >= 1,
        "后台任务应在存活期间清理过期条目"
    );

    // 释放唯一强引用 → 任务在下一轮唤醒(≤1s)后随 Weak 退出
    drop(cache);
    tokio::time::sleep(Duration::from_millis(1500)).await;
    // 无崩溃即通过(若任务泄漏持有 Arc/死锁,测试会暴露)
}

// ──── 回归测试:ttl() 查询 ────────────────────────────

#[tokio::test]
async fn test_ttl_query() {
    let cache = LocalCache::new(100, 0);
    // 不存在的 key
    assert_eq!(cache.ttl("nokey").await.unwrap(), None);
    // 永不过期的 key
    cache.set("p", &"v").await.unwrap();
    assert_eq!(cache.ttl("p").await.unwrap(), None, "无 TTL 的 key 应返回 None");
    // 带 TTL 的 key:剩余秒数向上取整,应在 (0, 5] 区间
    cache.set_ex("t", &"v", 5).await.unwrap();
    let t = cache.ttl("t").await.unwrap();
    assert!(
        matches!(t, Some(n) if (1..=5).contains(&n)),
        "ttl 应为剩余秒数,实际: {:?}",
        t
    );
    // 过期后返回 None
    cache.set_ex("e", &"v", 1).await.unwrap();
    tokio::time::sleep(Duration::from_millis(1100)).await;
    assert_eq!(cache.ttl("e").await.unwrap(), None);
}

// ──── 回归测试:sadd_with_ttl ─────────────────────────

#[tokio::test]
async fn test_sadd_with_ttl_and_empty_members() {
    let cache = LocalCache::new(100, 0);
    cache
        .sadd_with_ttl("st", &["a".to_string()], 5)
        .await
        .unwrap();
    assert!(
        cache.ttl("st").await.unwrap().is_some(),
        "sadd_with_ttl 应设置 TTL"
    );
    // 空成员:退化为仅刷新 TTL,不报错
    cache.sadd_with_ttl("st", &[], 10).await.unwrap();
    let members = cache.smembers("st").await.unwrap();
    assert_eq!(members, vec!["a".to_string()]);
    assert!(cache.ttl("st").await.unwrap().is_some());
    // ttl=0 报错
    assert!(cache.sadd_with_ttl("st2", &["a".to_string()], 0).await.is_err());
}

// ──── 回归测试:smembers 统计口径 ─────────────────────

#[tokio::test]
async fn test_smembers_stats() {
    let cache = LocalCache::new(100, 0);
    cache.sadd("s1", &["a".to_string()]).await.unwrap();
    let _ = cache.smembers("s1").await.unwrap();
    let _ = cache.smembers("missing").await.unwrap();
    let stats = cache.stats();
    assert_eq!(stats.hits, 1, "smembers 命中应计入 hits");
    assert_eq!(stats.misses, 1, "smembers 未命中应计入 misses");
}

// ──── 回归测试:SharedCache raw 字节直通 ───────────────
// SharedCache 必须覆盖 raw 三方法转发到后端直通实现;若退回 trait 默认
// 实现(serde_json::Value 中转),带空格的 JSON 会被重写为紧凑格式

#[tokio::test]
async fn test_shared_cache_raw_passthrough() {
    let cache = SharedCache::Local(LocalCache::new(100, 0));
    let raw: &[u8] = br#"{"a": 1}"#;
    cache.set_raw("raw1", raw).await.unwrap();
    let got = cache.get_raw("raw1").await.unwrap().unwrap();
    assert_eq!(got, raw, "SharedCache::Local 的 raw 读写应字节直通,不经 Value 中转");

    let raw2: &[u8] = br#"{"b": [1, 2]}"#;
    cache.set_raw_ex("raw2", raw2, 100).await.unwrap();
    let got2 = cache.get_raw("raw2").await.unwrap().unwrap();
    assert_eq!(got2, raw2, "set_raw_ex 同样应字节直通");
    assert!(cache.ttl("raw2").await.unwrap().is_some());
}

// ──── 回归测试:TTL 超过 i64::MAX 拒绝 ─────────────────
// Redis 秒级 TTL 上限即 i64;超限值 `as i64` 收窄会变负数,
// 而 Redis 对负 TTL 的行为是立即删除 key(静默数据丢失)

#[tokio::test]
async fn test_ttl_out_of_range_rejected() {
    let cache = LocalCache::new(100, 0);
    let huge = (i64::MAX as u64) + 1;
    assert!(cache.set_ex("k1", &"v", huge).await.is_err());
    assert!(cache.set_nx("k2", &"v", huge).await.is_err());
    assert!(cache.set_raw_ex("k3", b"{}", huge).await.is_err());
    assert!(cache.expire("k4", huge).await.is_err());
    assert!(
        cache
            .sadd_with_ttl("k5", &["a".to_string()], huge)
            .await
            .is_err()
    );
    // 全部路径都在写入前校验:不留下半成品数据
    assert_eq!(cache.len(), 0, "非法 TTL 写入不应留下任何 key");
}

// ──── 回归测试:set 对齐 Redis 契约为永不过期 ──────────
// 旧实现会让 local 后端的 set 在配置 default_ttl>0 时静默过期,
// 与 Redis 后端及 trait 契约不一致(get_or_insert_with(ttl=0) 的
// 「永不过期」承诺同样被破坏)

#[tokio::test]
async fn test_set_ignores_default_ttl() {
    let cache = LocalCache::new(100, 3600);
    cache.set("k", &"v".to_string()).await.unwrap();
    assert_eq!(
        cache.ttl("k").await.unwrap(),
        None,
        "set 不应应用 default_ttl"
    );
    cache.set_raw("raw", b"{}").await.unwrap();
    assert_eq!(
        cache.ttl("raw").await.unwrap(),
        None,
        "set_raw 不应应用 default_ttl"
    );

    let _: String = cache
        .get_or_insert_with("sf", 0, || async { Ok("x".to_string()) })
        .await
        .unwrap();
    assert_eq!(
        cache.ttl("sf").await.unwrap(),
        None,
        "get_or_insert_with(ttl=0) 应为永不过期"
    );
}

// ──── 回归测试:create_cache 未知 type 报配置错误 ──────
// 旧实现 _ 分支静默回退本地缓存,配置 typo(如 "loacl")难以排查

#[tokio::test]
async fn test_create_cache_unknown_type_rejected() {
    let cache_cfg = wordval_config::CacheConfig {
        r#type: "loacl".into(),
        max_capacity: 100,
        default_ttl: 3600,
    };
    let redis_cfg = wordval_config::RedisConfig {
        enabled: false,
        url: "redis://127.0.0.1:6379".into(),
        max_connections: 10,
    };
    let err = match wordval_cache::create_cache(&cache_cfg, &redis_cfg).await {
        Ok(_) => panic!("未知 cache.type 应返回配置错误"),
        Err(e) => e,
    };
    let msg = format!("{err}");
    assert!(
        msg.contains("loacl") && msg.contains("cache.type"),
        "错误信息应包含无效 type 原值,实际: {msg}"
    );
}

// ──── 回归测试:get_or_insert_with 单飞去重 ────────────

#[tokio::test]
async fn test_get_or_insert_with_basic() {
    let cache = LocalCache::new(100, 0);
    let v: i64 = cache
        .get_or_insert_with("sf1", 60, || async { Ok(42) })
        .await
        .unwrap();
    assert_eq!(v, 42);

    // 第二次直接命中缓存,加载器不被调用
    let loaded = Arc::new(AtomicUsize::new(0));
    let l2 = loaded.clone();
    let v2: i64 = cache
        .get_or_insert_with("sf1", 60, move || {
            let loaded = l2.clone();
            async move {
                loaded.fetch_add(1, Ordering::Relaxed);
                Ok(42)
            }
        })
        .await
        .unwrap();
    assert_eq!(v2, 42);
    assert_eq!(loaded.load(Ordering::Relaxed), 0, "命中后不应再回源");
    assert!(cache.ttl("sf1").await.unwrap().is_some(), "ttl>0 应写入 TTL");
}

#[tokio::test]
async fn test_get_or_insert_with_ttl_zero_permanent() {
    let cache = LocalCache::new(100, 0);
    let _: i64 = cache
        .get_or_insert_with("sf2", 0, || async { Ok(7) })
        .await
        .unwrap();
    assert_eq!(cache.ttl("sf2").await.unwrap(), None, "ttl=0 应为永不过期");
}

#[tokio::test]
async fn test_get_or_insert_with_single_flight() {
    let cache = LocalCache::new(100, 0);
    let loaded = Arc::new(AtomicUsize::new(0));
    let mut handles = Vec::new();
    for _ in 0..32 {
        let cache = cache.clone();
        let loaded = loaded.clone();
        handles.push(tokio::spawn(async move {
            cache
                .get_or_insert_with("sf3", 60, move || {
                    let loaded = loaded.clone();
                    async move {
                        // 延长回源耗时,放大并发等待窗口
                        tokio::time::sleep(Duration::from_millis(50)).await;
                        loaded.fetch_add(1, Ordering::Relaxed);
                        Ok("v".to_string())
                    }
                })
                .await
                .unwrap()
        }));
    }
    for h in handles {
        h.await.unwrap();
    }
    assert_eq!(
        loaded.load(Ordering::Relaxed),
        1,
        "同 key 32 路并发应只回源一次"
    );
}

#[tokio::test]
async fn test_get_or_insert_with_error_not_cached() {
    let cache = LocalCache::new(100, 0);
    let first = cache
        .get_or_insert_with::<String, _, _>("sf4", 60, || async {
            Err(wordval_cache::Error::Msg("boom".into()))
        })
        .await;
    assert!(first.is_err(), "加载失败应向上传播");
    assert!(!cache.exists("sf4").await.unwrap(), "失败结果不应写入缓存");

    // 失败后下一次调用仍会回源(等待者重试语义)
    let loaded = Arc::new(AtomicUsize::new(0));
    let l2 = loaded.clone();
    let v: String = cache
        .get_or_insert_with("sf4", 60, move || {
            let loaded = l2.clone();
            async move {
                loaded.fetch_add(1, Ordering::Relaxed);
                Ok("ok".to_string())
            }
        })
        .await
        .unwrap();
    assert_eq!(v, "ok");
    assert_eq!(loaded.load(Ordering::Relaxed), 1);
}