oxcache 0.2.0

A high-performance multi-level cache library for Rust with L1 (memory) and L2 (Redis) caching.
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
// Copyright (c) 2025-2026, Kirky.X
//
// MIT License
//
// 链式缓存核心实现
//
// ChainCache 提供多后端链式访问,按分数从高到低遍历后端。
// 读取时从高分后端开始,写入时写入所有后端。

use crate::backend::interface::{BackendKind, CacheBackend, CacheConnector, CacheReader, CacheWriter};
use crate::backend::score::BackendScore;
use crate::error::{CacheError, Result};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tracing::instrument;

/// 链式缓存中的一个后端链接
///
/// ChainLink 封装了一个后端实例及其分数信息。
/// 分数用于确定链式访问的顺序。
#[derive(Clone)]
pub struct ChainLink {
    /// 后端实例
    backend: Arc<dyn CacheBackend>,
    /// 后端分数(越高越快)
    score: u8,
    /// 是否为持久化后端
    is_persistent: bool,
    /// 后端名称
    name: &'static str,
}

impl ChainLink {
    /// 创建新的链式链接
    pub fn new<B>(backend: B, score: u8, is_persistent: bool, name: &'static str) -> Self
    where
        B: CacheBackend + BackendScore + 'static,
    {
        Self {
            backend: Arc::new(backend),
            score,
            is_persistent,
            name,
        }
    }

    /// 从实现了 BackendScore 的后端创建链接
    pub fn from_backend<B>(backend: B) -> Self
    where
        B: CacheBackend + BackendScore + 'static,
    {
        let score = backend.score();
        let is_persistent = backend.is_persistent();
        let name = backend.backend_name();
        Self {
            backend: Arc::new(backend),
            score,
            is_persistent,
            name,
        }
    }

    /// 获取后端实例引用
    pub fn backend(&self) -> &Arc<dyn CacheBackend> {
        &self.backend
    }

    /// 获取后端分数
    pub fn score(&self) -> u8 {
        self.score
    }

    /// 是否为持久化后端
    pub fn is_persistent(&self) -> bool {
        self.is_persistent
    }

    /// 获取后端名称
    pub fn name(&self) -> &'static str {
        self.name
    }
}

impl std::fmt::Debug for ChainLink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChainLink")
            .field("score", &self.score)
            .field("is_persistent", &self.is_persistent)
            .field("name", &self.name)
            .finish()
    }
}

/// 链式缓存
///
/// ChainCache 管理多个后端,按分数从高到低排序。
/// 读取时从高分后端开始,找到即返回;写入时写入所有后端。
///
/// # TTL 行为
///
/// - `chain.set(key, value, None)` → 各 backend 使用自己的默认 TTL
/// - `chain.set(key, value, Some(ttl))` → 所有 backend 使用传入的 TTL
///
/// # Example
///
/// ```rust,ignore
/// use oxcache::cache::{ChainCache, ChainLink};
/// use oxcache::backend::MokaMemoryBackend;
///
/// let l1 = MokaMemoryBackend::builder().capacity(10000).ttl(Duration::from_secs(300)).build();
/// let l2 = oxcache::backend::RedisBackend::builder().ttl(Duration::from_secs(3600)).build().await?;
///
/// let chain = ChainCache::builder()
///     .link(ChainLink::from_backend(l1))  // L1: 5分钟 TTL
///     .link(ChainLink::from_backend(l2))  // L2: 1小时 TTL
///     .enable_backfill()
///     .build();
///
/// chain.set("key", value, None).await?;  // L1 用 5分钟,L2 用 1小时
/// ```
pub struct ChainCache {
    /// 后端链接列表(按分数降序排列)
    links: Vec<ChainLink>,
    /// 是否启用回填
    backfill_enabled: bool,
    /// 默认 TTL
    default_ttl: Option<Duration>,
}

impl ChainCache {
    /// 创建新的链式缓存
    pub fn new(links: Vec<ChainLink>) -> Self {
        Self::builder().links(links).build()
    }

    /// 创建链式缓存构建器
    pub fn builder() -> ChainCacheBuilder {
        ChainCacheBuilder::default()
    }

    /// 获取后端链接列表
    pub fn links(&self) -> &[ChainLink] {
        &self.links
    }

    /// 获取后端数量
    pub fn len(&self) -> usize {
        self.links.len()
    }

    /// 检查是否为空
    pub fn is_empty(&self) -> bool {
        self.links.is_empty()
    }

    /// 获取指定分数的后端
    pub fn get_by_score(&self, score: u8) -> Option<&ChainLink> {
        self.links.iter().find(|link| link.score() == score)
    }

    /// 获取最高分后端
    pub fn highest_score_backend(&self) -> Option<&ChainLink> {
        self.links.first()
    }

    /// 获取最低分后端
    pub fn lowest_score_backend(&self) -> Option<&ChainLink> {
        self.links.last()
    }

    /// 获取所有持久化后端
    pub fn persistent_backends(&self) -> Vec<&ChainLink> {
        self.links.iter().filter(|link| link.is_persistent()).collect()
    }

    /// 获取所有非持久化后端
    pub fn non_persistent_backends(&self) -> Vec<&ChainLink> {
        self.links.iter().filter(|link| !link.is_persistent()).collect()
    }

    /// 从链中读取数据
    #[instrument(skip(self), fields(key = %key))]
    async fn read_from_chain(&self, key: &str) -> Result<Option<Vec<u8>>> {
        for (index, link) in self.links.iter().enumerate() {
            match link.backend().get(key).await {
                Ok(Some(value)) => {
                    // 回填到更高分后端
                    if self.backfill_enabled && index > 0 {
                        self.backfill_to_higher_backends(key, &value, index).await;
                    }
                    return Ok(Some(value));
                }
                Ok(None) => continue,
                Err(_) => continue,
            }
        }
        Ok(None)
    }

    /// 回填数据到更高分后端(使用各 backend 自己的默认 TTL)
    async fn backfill_to_higher_backends(&self, key: &str, value: &[u8], from_index: usize) {
        for link in &self.links[..from_index] {
            let _ = link.backend().set(key, value.to_vec(), None).await;
        }
    }

    /// 写入数据到所有后端
    /// ttl=None 时各 backend 用自己的默认 TTL
    /// ttl=Some 时所有 backend 用同一个 TTL
    #[instrument(skip(self, value), fields(key = %key))]
    async fn write_to_all_backends(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<()> {
        let mut errors = Vec::new();
        let count = self.links.len();

        if count == 0 {
            return Ok(());
        }

        // Clone for all but the last backend
        let effective_ttl = ttl.or(self.default_ttl);
        for link in self.links.iter().take(count - 1) {
            if let Err(e) = link.backend().set(key, value.clone(), effective_ttl).await {
                errors.push((link.name(), e));
            }
        }

        // Last backend: use the owned value directly (no clone)
        if let Some(link) = self.links.last() {
            if let Err(e) = link.backend().set(key, value, effective_ttl).await {
                errors.push((link.name(), e));
            }
        }

        if errors.len() == self.links.len() {
            return Err(CacheError::Operation("All backends failed to write".to_string()));
        }

        Ok(())
    }

    /// 从所有后端删除数据
    #[instrument(skip(self), fields(key = %key))]
    async fn delete_from_all_backends(&self, key: &str) -> Result<()> {
        let mut errors = Vec::new();

        for link in &self.links {
            if let Err(e) = link.backend().delete(key).await {
                errors.push((link.name(), e));
            }
        }

        if errors.len() == self.links.len() {
            return Err(CacheError::Operation(format!(
                "All backends failed to delete: {:?}",
                errors
            )));
        }

        Ok(())
    }
}

#[async_trait]
impl CacheReader for ChainCache {
    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
        if self.links.is_empty() {
            return Ok(None);
        }
        self.read_from_chain(key).await
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        for link in &self.links {
            match link.backend().exists(key).await {
                Ok(true) => return Ok(true),
                Ok(false) => continue,
                Err(_) => continue,
            }
        }
        Ok(false)
    }

    async fn ttl(&self, key: &str) -> Result<Option<Duration>> {
        for link in &self.links {
            match link.backend().ttl(key).await {
                Ok(Some(ttl)) => return Ok(Some(ttl)),
                Ok(None) => continue,
                Err(_) => continue,
            }
        }
        Ok(None)
    }

    async fn len(&self) -> Result<u64> {
        if let Some(link) = self.links.first() {
            link.backend().len().await
        } else {
            Ok(0)
        }
    }

    async fn is_empty(&self) -> Result<bool> {
        if let Some(link) = self.links.first() {
            link.backend().is_empty().await
        } else {
            Ok(true)
        }
    }

    async fn capacity(&self) -> Result<u64> {
        if let Some(link) = self.links.first() {
            link.backend().capacity().await
        } else {
            Ok(0)
        }
    }

    async fn stats(&self) -> Result<HashMap<String, String>> {
        let mut stats = HashMap::new();
        stats.insert("type".to_string(), "chain".to_string());
        stats.insert("backend_count".to_string(), self.links.len().to_string());

        for (index, link) in self.links.iter().enumerate() {
            stats.insert(format!("backend_{}_name", index), link.name().to_string());
            stats.insert(format!("backend_{}_score", index), link.score().to_string());
        }

        Ok(stats)
    }
}

#[async_trait]
impl CacheWriter for ChainCache {
    async fn set(&self, key: &str, value: Vec<u8>, ttl: Option<Duration>) -> Result<()> {
        if self.links.is_empty() {
            return Err(CacheError::Operation("Chain has no backends".to_string()));
        }
        self.write_to_all_backends(key, value, ttl).await
    }

    async fn delete(&self, key: &str) -> Result<()> {
        if self.links.is_empty() {
            return Ok(());
        }
        self.delete_from_all_backends(key).await
    }

    async fn clear(&self) -> Result<()> {
        let mut errors = Vec::new();

        for link in &self.links {
            if let Err(e) = link.backend().clear().await {
                errors.push((link.name(), e));
            }
        }

        if errors.len() == self.links.len() && !self.links.is_empty() {
            return Err(CacheError::Operation(format!(
                "All backends failed to clear: {:?}",
                errors
            )));
        }

        Ok(())
    }

    async fn expire(&self, key: &str, ttl: Duration) -> Result<bool> {
        let mut any_success = false;

        for link in &self.links {
            match link.backend().expire(key, ttl).await {
                Ok(true) => any_success = true,
                _ => continue,
            }
        }

        Ok(any_success)
    }
}

#[async_trait]
impl CacheConnector for ChainCache {
    async fn health_check(&self) -> Result<()> {
        if self.links.is_empty() {
            return Ok(());
        }

        for link in &self.links {
            link.backend().health_check().await?;
        }

        Ok(())
    }

    async fn shutdown(&self) {
        for link in &self.links {
            link.backend().shutdown().await;
        }
    }

    fn backend_kind(&self) -> BackendKind {
        BackendKind::Chain
    }
}

/// 链式缓存构建器
#[derive(Default)]
pub struct ChainCacheBuilder {
    links: Vec<ChainLink>,
    backfill_enabled: bool,
    default_ttl: Option<Duration>,
}

impl ChainCacheBuilder {
    /// 添加后端链接
    pub fn link(mut self, link: ChainLink) -> Self {
        self.links.push(link);
        self
    }

    /// 添加多个后端链接
    pub fn links(mut self, mut links: Vec<ChainLink>) -> Self {
        self.links.append(&mut links);
        self
    }

    /// 添加后端(自动创建链接)
    pub fn backend<B>(self, backend: B) -> Self
    where
        B: CacheBackend + BackendScore + 'static,
    {
        self.link(ChainLink::from_backend(backend))
    }

    /// 设置默认 TTL
    pub fn default_time_to_live(mut self, ttl: Duration) -> Self {
        self.default_ttl = Some(ttl);
        self
    }

    /// 启用回填
    pub fn enable_backfill(mut self) -> Self {
        self.backfill_enabled = true;
        self
    }

    /// 禁用回填
    pub fn disable_backfill(mut self) -> Self {
        self.backfill_enabled = false;
        self
    }

    /// 构建链式缓存
    pub fn build(self) -> ChainCache {
        // 按分数降序排序
        let mut links = self.links;
        links.sort_by_key(|link| std::cmp::Reverse(link.score()));

        ChainCache {
            links,
            backfill_enabled: self.backfill_enabled,
            default_ttl: self.default_ttl,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::MokaMemoryBackend;
    use crate::testing::mock::MockBackend;

    #[test]
    fn test_chain_link_creation() {
        let backend = MockBackend::new("test", 50, false);
        let link = ChainLink::from_backend(backend);

        assert_eq!(link.score(), 50);
        assert!(!link.is_persistent());
        assert_eq!(link.name(), "test");
    }

    #[test]
    fn test_chain_cache_builder() {
        let high = MockBackend::new("high", 100, false);
        let low = MockBackend::new("low", 50, true);

        let chain = ChainCache::builder()
            .backend(low)
            .backend(high)
            .enable_backfill()
            .build();

        assert_eq!(chain.links().len(), 2);
        assert_eq!(chain.links()[0].score(), 100);
        assert_eq!(chain.links()[1].score(), 50);
    }

    #[tokio::test]
    async fn test_chain_cache_get_set() {
        let high = MockBackend::new("high", 100, false);
        let low = MockBackend::new("low", 50, true);

        let chain = ChainCache::builder().backend(high).backend(low).build();

        chain.set("key", b"value".to_vec(), None).await.unwrap();

        let value = chain.get("key").await.unwrap();
        assert_eq!(value, Some(b"value".to_vec()));
    }

    #[tokio::test]
    async fn test_chain_cache_delete() {
        let high = MockBackend::new("high", 100, false);
        let low = MockBackend::new("low", 50, true);

        let chain = ChainCache::builder().backend(high).backend(low).build();

        chain.set("key", b"value".to_vec(), None).await.unwrap();
        chain.delete("key").await.unwrap();

        let exists = chain.exists("key").await.unwrap();
        assert!(!exists);
    }

    #[tokio::test]
    async fn test_chain_cache_backfill() {
        // Build chain with backfill enabled
        let chain = ChainCache::builder()
            .link(ChainLink::new(MockBackend::new("high", 100, false), 100, false, "high"))
            .link(ChainLink::new(MockBackend::new("low", 50, true), 50, true, "low"))
            .enable_backfill()
            .build();

        // Set value in chain (writes to all backends)
        chain.set("key", b"value".to_vec(), None).await.unwrap();

        // Read should succeed
        let value = chain.get("key").await.unwrap();
        assert_eq!(value, Some(b"value".to_vec()));
    }

    #[tokio::test]
    async fn test_empty_chain() {
        let chain = ChainCache::new(vec![]);

        let value = chain.get("key").await.unwrap();
        assert!(value.is_none());

        let exists = chain.exists("key").await.unwrap();
        assert!(!exists);
    }

    // ========================================================================
    // ChainLink tests
    // ========================================================================

    #[test]
    fn test_chain_link_new_constructor() {
        let backend = MokaMemoryBackend::new();
        let link = ChainLink::new(backend, 75, true, "custom");

        assert_eq!(link.score(), 75);
        assert!(link.is_persistent());
        assert_eq!(link.name(), "custom");
        // backend() getter should return a usable reference
        let _backend_ref = link.backend();
    }

    #[test]
    fn test_chain_link_from_backend_moka() {
        let backend = MokaMemoryBackend::new();
        let link = ChainLink::from_backend(backend);

        // Moka scores 100 (Scores::MOKA), non-persistent, name "moka"
        assert_eq!(link.score(), 100);
        assert!(!link.is_persistent());
        assert_eq!(link.name(), "moka");
    }

    #[test]
    fn test_chain_link_debug() {
        let backend = MokaMemoryBackend::new();
        let link = ChainLink::new(backend, 80, true, "dbg");

        let debug_str = format!("{:?}", link);
        assert!(debug_str.contains("ChainLink"));
        assert!(debug_str.contains("80"));
        assert!(debug_str.contains("dbg"));
    }

    // ========================================================================
    // ChainCache accessor tests
    // ========================================================================

    #[test]
    fn test_chain_cache_new_constructor() {
        let link = ChainLink::from_backend(MokaMemoryBackend::new());
        let chain = ChainCache::new(vec![link]);

        assert_eq!(chain.len(), 1);
        assert!(!chain.is_empty());
    }

    #[test]
    fn test_chain_cache_len_is_empty() {
        let empty = ChainCache::new(vec![]);
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);

        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();
        assert!(!chain.is_empty());
        assert_eq!(chain.len(), 1);
    }

    #[test]
    fn test_chain_cache_get_by_score() {
        let chain = ChainCache::builder()
            .link(ChainLink::new(MokaMemoryBackend::new(), 100, false, "high"))
            .link(ChainLink::new(MokaMemoryBackend::new(), 50, true, "low"))
            .build();

        assert!(chain.get_by_score(100).is_some());
        assert!(chain.get_by_score(50).is_some());
        assert!(chain.get_by_score(75).is_none());
    }

    #[test]
    fn test_chain_cache_highest_lowest_backend() {
        // Add low first to verify sorting works
        let chain = ChainCache::builder()
            .link(ChainLink::new(MokaMemoryBackend::new(), 50, true, "low"))
            .link(ChainLink::new(MokaMemoryBackend::new(), 100, false, "high"))
            .build();

        let highest = chain.highest_score_backend().unwrap();
        assert_eq!(highest.score(), 100);
        assert_eq!(highest.name(), "high");

        let lowest = chain.lowest_score_backend().unwrap();
        assert_eq!(lowest.score(), 50);
        assert_eq!(lowest.name(), "low");
    }

    #[test]
    fn test_chain_cache_highest_lowest_empty() {
        let chain = ChainCache::new(vec![]);
        assert!(chain.highest_score_backend().is_none());
        assert!(chain.lowest_score_backend().is_none());
    }

    #[test]
    fn test_chain_cache_persistent_filters() {
        let chain = ChainCache::builder()
            .link(ChainLink::new(MokaMemoryBackend::new(), 100, false, "high"))
            .link(ChainLink::new(MokaMemoryBackend::new(), 50, true, "low"))
            .build();

        let persistent = chain.persistent_backends();
        assert_eq!(persistent.len(), 1);
        assert_eq!(persistent[0].name(), "low");

        let non_persistent = chain.non_persistent_backends();
        assert_eq!(non_persistent.len(), 1);
        assert_eq!(non_persistent[0].name(), "high");
    }

    #[test]
    fn test_chain_cache_links_accessor() {
        let chain = ChainCache::builder()
            .link(ChainLink::new(MokaMemoryBackend::new(), 100, false, "high"))
            .build();

        let links = chain.links();
        assert_eq!(links.len(), 1);
        assert_eq!(links[0].name(), "high");
    }

    // ========================================================================
    // Builder tests
    // ========================================================================

    #[test]
    fn test_builder_link_method() {
        let link = ChainLink::new(MokaMemoryBackend::new(), 100, false, "moka");
        let chain = ChainCache::builder().link(link).build();
        assert_eq!(chain.len(), 1);
    }

    #[test]
    fn test_builder_links_method() {
        let links = vec![
            ChainLink::new(MokaMemoryBackend::new(), 100, false, "high"),
            ChainLink::new(MokaMemoryBackend::new(), 50, true, "low"),
        ];
        let chain = ChainCache::builder().links(links).build();
        assert_eq!(chain.len(), 2);
        // Verify sorting by score descending
        assert_eq!(chain.links()[0].score(), 100);
        assert_eq!(chain.links()[1].score(), 50);
    }

    #[tokio::test]
    async fn test_builder_default_time_to_live() {
        let chain = ChainCache::builder()
            .backend(MokaMemoryBackend::new())
            .default_time_to_live(Duration::from_secs(60))
            .build();

        // set with None should use default_ttl
        chain.set("key", b"value".to_vec(), None).await.unwrap();
        let value = chain.get("key").await.unwrap();
        assert_eq!(value, Some(b"value".to_vec()));
    }

    #[test]
    fn test_builder_disable_backfill() {
        let chain = ChainCache::builder()
            .backend(MokaMemoryBackend::new())
            .enable_backfill()
            .disable_backfill()
            .build();

        assert_eq!(chain.len(), 1);
    }

    // ========================================================================
    // UnifiedCache trait tests (get_bytes / set_bytes)
    // ========================================================================

    #[tokio::test]
    async fn test_chain_cache_get_bytes_set_bytes() {
        use crate::UnifiedCache;
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        chain.set_bytes("key", b"value".to_vec(), None).await.unwrap();
        let value = chain.get_bytes("key").await.unwrap();
        assert_eq!(value, Some(b"value".to_vec()));
    }

    #[tokio::test]
    async fn test_chain_cache_get_bytes_missing() {
        use crate::UnifiedCache;
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        let value = chain.get_bytes("missing").await.unwrap();
        assert!(value.is_none());
    }

    // ========================================================================
    // CacheWriter tests
    // ========================================================================

    #[tokio::test]
    async fn test_chain_cache_clear() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        chain.set("key", b"value".to_vec(), None).await.unwrap();
        assert!(chain.exists("key").await.unwrap());

        chain.clear().await.unwrap();
        assert!(!chain.exists("key").await.unwrap());
    }

    #[tokio::test]
    async fn test_chain_cache_clear_empty() {
        let chain = ChainCache::new(vec![]);
        assert!(chain.clear().await.is_ok());
    }

    #[tokio::test]
    async fn test_chain_cache_expire() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        chain.set("key", b"value".to_vec(), None).await.unwrap();
        // Moka doesn't support per-entry TTL updates, returns false
        let result = chain.expire("key", Duration::from_secs(60)).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_chain_cache_expire_missing_key() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        let result = chain.expire("missing", Duration::from_secs(60)).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_chain_cache_set_empty_chain_error() {
        let chain = ChainCache::new(vec![]);
        let result = chain.set("key", b"value".to_vec(), None).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_chain_cache_delete_empty_chain() {
        let chain = ChainCache::new(vec![]);
        assert!(chain.delete("key").await.is_ok());
    }

    #[tokio::test]
    async fn test_chain_cache_set_with_explicit_ttl() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        chain
            .set("key", b"value".to_vec(), Some(Duration::from_secs(60)))
            .await
            .unwrap();
        let value = chain.get("key").await.unwrap();
        assert_eq!(value, Some(b"value".to_vec()));
    }

    #[tokio::test]
    async fn test_chain_cache_multi_backend_set_writes_all() {
        let high = MokaMemoryBackend::new();
        let low = MokaMemoryBackend::new();

        let high_ref = high.clone();
        let low_ref = low.clone();

        let chain = ChainCache::builder()
            .link(ChainLink::new(high, 100, false, "high"))
            .link(ChainLink::new(low, 50, true, "low"))
            .build();

        chain.set("key", b"value".to_vec(), None).await.unwrap();

        // Both backends should have the value
        assert_eq!(high_ref.get("key").await.unwrap(), Some(b"value".to_vec()));
        assert_eq!(low_ref.get("key").await.unwrap(), Some(b"value".to_vec()));
    }

    #[tokio::test]
    async fn test_chain_cache_delete_removes_from_all() {
        let high = MokaMemoryBackend::new();
        let low = MokaMemoryBackend::new();

        let high_ref = high.clone();
        let low_ref = low.clone();

        let chain = ChainCache::builder()
            .link(ChainLink::new(high, 100, false, "high"))
            .link(ChainLink::new(low, 50, true, "low"))
            .build();

        chain.set("key", b"value".to_vec(), None).await.unwrap();
        chain.delete("key").await.unwrap();

        assert!(high_ref.get("key").await.unwrap().is_none());
        assert!(low_ref.get("key").await.unwrap().is_none());
    }

    // ========================================================================
    // Backfill behavior tests
    // ========================================================================

    #[tokio::test]
    async fn test_chain_cache_backfill_populates_higher() {
        let high = MokaMemoryBackend::new();
        let low = MokaMemoryBackend::new();

        let high_ref = high.clone();
        let low_ref = low.clone();

        let chain = ChainCache::builder()
            .link(ChainLink::new(high, 100, false, "high"))
            .link(ChainLink::new(low, 50, true, "low"))
            .enable_backfill()
            .build();

        // Set value only in low backend (bypass chain)
        low_ref.set("key", b"low_value".to_vec(), None).await.unwrap();

        // Verify high doesn't have it yet
        assert!(high_ref.get("key").await.unwrap().is_none());

        // Get from chain - should find in low and backfill to high
        let value = chain.get("key").await.unwrap();
        assert_eq!(value, Some(b"low_value".to_vec()));

        // Verify high now has the value (backfilled)
        let high_value = high_ref.get("key").await.unwrap();
        assert_eq!(high_value, Some(b"low_value".to_vec()));
    }

    #[tokio::test]
    async fn test_chain_cache_no_backfill_when_disabled() {
        let high = MokaMemoryBackend::new();
        let low = MokaMemoryBackend::new();

        let high_ref = high.clone();
        let low_ref = low.clone();

        let chain = ChainCache::builder()
            .link(ChainLink::new(high, 100, false, "high"))
            .link(ChainLink::new(low, 50, true, "low"))
            .build(); // backfill disabled by default

        // Set value only in low backend (bypass chain)
        low_ref.set("key", b"low_value".to_vec(), None).await.unwrap();

        // Get from chain - should find in low but NOT backfill to high
        let value = chain.get("key").await.unwrap();
        assert_eq!(value, Some(b"low_value".to_vec()));

        // Verify high still doesn't have the value
        assert!(high_ref.get("key").await.unwrap().is_none());
    }

    // ========================================================================
    // CacheReader trait tests
    // ========================================================================

    #[tokio::test]
    async fn test_chain_cache_ttl_len_capacity() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        chain.set("key", b"value".to_vec(), None).await.unwrap();

        // ttl - Moka returns None for per-entry TTL
        let ttl = chain.ttl("key").await.unwrap();
        assert!(ttl.is_none());

        // len (CacheReader trait) - Moka's entry_count is approximate
        let len = CacheReader::len(&chain).await.unwrap();
        assert!(len <= 100, "len should be reasonable after single insert");

        // capacity
        let capacity = chain.capacity().await.unwrap();
        assert!(capacity > 0);
    }

    #[tokio::test]
    async fn test_chain_cache_reader_empty() {
        let chain = ChainCache::new(vec![]);

        assert_eq!(CacheReader::len(&chain).await.unwrap(), 0);
        assert!(CacheReader::is_empty(&chain).await.unwrap());
        assert_eq!(chain.capacity().await.unwrap(), 0);

        let ttl = chain.ttl("key").await.unwrap();
        assert!(ttl.is_none());
    }

    #[tokio::test]
    async fn test_chain_cache_stats() {
        let chain = ChainCache::builder()
            .link(ChainLink::new(MokaMemoryBackend::new(), 100, false, "high"))
            .link(ChainLink::new(MokaMemoryBackend::new(), 50, true, "low"))
            .build();

        let stats = chain.stats().await.unwrap();
        assert_eq!(stats.get("type"), Some(&"chain".to_string()));
        assert_eq!(stats.get("backend_count"), Some(&"2".to_string()));
        assert_eq!(stats.get("backend_0_name"), Some(&"high".to_string()));
        assert_eq!(stats.get("backend_0_score"), Some(&"100".to_string()));
        assert_eq!(stats.get("backend_1_name"), Some(&"low".to_string()));
        assert_eq!(stats.get("backend_1_score"), Some(&"50".to_string()));
    }

    #[tokio::test]
    async fn test_chain_cache_stats_empty() {
        let chain = ChainCache::new(vec![]);
        let stats = chain.stats().await.unwrap();
        assert_eq!(stats.get("type"), Some(&"chain".to_string()));
        assert_eq!(stats.get("backend_count"), Some(&"0".to_string()));
    }

    // ========================================================================
    // CacheConnector trait tests
    // ========================================================================

    #[tokio::test]
    async fn test_chain_cache_health_check() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        assert!(chain.health_check().await.is_ok());
    }

    #[tokio::test]
    async fn test_chain_cache_health_check_empty() {
        let chain = ChainCache::new(vec![]);
        assert!(chain.health_check().await.is_ok());
    }

    #[tokio::test]
    async fn test_chain_cache_shutdown() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        // Should not panic
        chain.shutdown().await;
    }

    #[test]
    fn test_chain_cache_backend_kind() {
        let chain = ChainCache::builder().backend(MokaMemoryBackend::new()).build();

        assert_eq!(chain.backend_kind(), BackendKind::Chain);
    }
}