oxcache 0.1.4

A high-performance multi-level cache library for Rust with L1 (memory) and L2 (Redis) caching.
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
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
//! Copyright (c) 2025-2026, Kirky.X
//!
//! MIT License
//!
//! 该模块定义了缓存系统的指标收集和监控功能。
//! 通过 `metrics` 或 `l1-moka` feature 控制启用/禁用。

use dashmap::DashMap;
use once_cell::sync::Lazy;
use serde::Serialize;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tracing::{span, Level};

/// 原子计数器集合
///
/// 使用原子操作实现无锁的指标计数,大幅提升性能
#[derive(Debug)]
pub struct AtomicCounters {
    /// L1缓存命中次数
    pub l1_get_hits: AtomicU64,
    /// L1缓存未命中次数
    pub l1_get_misses: AtomicU64,
    /// L2缓存命中次数
    pub l2_get_hits: AtomicU64,
    /// L2缓存未命中次数
    pub l2_get_misses: AtomicU64,
    /// L1缓存设置次数
    pub l1_set_total: AtomicU64,
    /// L2缓存设置次数
    pub l2_set_total: AtomicU64,
    /// L1缓存删除次数
    pub l1_delete_total: AtomicU64,
    /// L2缓存删除次数
    pub l2_delete_total: AtomicU64,
    /// 总操作次数
    pub total_operations: AtomicU64,
    /// L1 缓存项数量
    pub l1_items: AtomicU64,
    /// L1 缓存容量使用(字节)
    pub l1_capacity_used: AtomicU64,
    /// 预取操作次数
    pub prefetch_total: AtomicU64,
    /// 压缩操作次数
    pub compression_total: AtomicU64,
    /// 压缩节省的字节数
    pub compression_bytes_saved: AtomicU64,
}

impl Default for AtomicCounters {
    fn default() -> Self {
        Self {
            l1_get_hits: AtomicU64::new(0),
            l1_get_misses: AtomicU64::new(0),
            l2_get_hits: AtomicU64::new(0),
            l2_get_misses: AtomicU64::new(0),
            l1_set_total: AtomicU64::new(0),
            l2_set_total: AtomicU64::new(0),
            l1_delete_total: AtomicU64::new(0),
            l2_delete_total: AtomicU64::new(0),
            total_operations: AtomicU64::new(0),
            l1_items: AtomicU64::new(0),
            l1_capacity_used: AtomicU64::new(0),
            prefetch_total: AtomicU64::new(0),
            compression_total: AtomicU64::new(0),
            compression_bytes_saved: AtomicU64::new(0),
        }
    }
}

/// 指标收集器
///
/// 用于收集和存储缓存系统的各种运行时指标
/// 优化版本:高频指标使用原子计数器,低频指标使用DashMap
#[derive(Clone, Debug, Default)]
pub struct Metrics {
    /// 原子计数器(高频指标,无锁)
    pub counters: Arc<AtomicCounters>,
    /// 请求总数统计(低频指标,保留DashMap用于动态服务名)
    /// key: "service:layer:op:result"
    pub requests_total: Arc<DashMap<String, u64>>,
    /// L2健康状态
    pub l2_health_status: Arc<DashMap<String, u8>>,
    /// WAL条目数
    pub wal_entries: Arc<DashMap<String, usize>>,
    /// 操作耗时(简单的累积时间和计数,用于计算平均值,更复杂的直方图建议使用OpenTelemetry Metrics)
    /// key: "service:layer:op" -> (total_duration_secs, count)
    pub operation_duration: Arc<DashMap<String, (f64, u64)>>,
    /// 批量写入缓冲区大小
    pub batch_buffer_size: Arc<DashMap<String, usize>>,
    /// 批量写入成功率
    pub batch_success_rate: Arc<DashMap<String, f64>>,
    /// 批量写入吞吐量 (ops/sec)
    pub batch_throughput: Arc<DashMap<String, f64>>,
}

/// 全局指标实例
pub static GLOBAL_METRICS: Lazy<Metrics> = Lazy::new(Metrics::default);

impl Metrics {
    /// 记录请求指标(优化版本)
    ///
    /// 对于高频操作(L1/L2 get/set/delete),使用原子计数器
    /// 对于其他操作,使用HashMap
    ///
    /// # 参数
    ///
    /// * `service` - 服务名称
    /// * `layer` - 缓存层(L1/L2)
    /// * `op` - 操作类型(get/set/delete)
    /// * `result` - 操作结果(attempt/hit/miss)
    pub fn record_request(&self, service: &str, layer: &str, op: &str, result: &str) {
        let span = span!(Level::INFO, "cache_request", service, layer, op, result);
        let _enter = span.enter();

        // 使用原子计数器处理高频指标
        match (layer, op, result) {
            ("L1", "get", "hit") => {
                self.counters.l1_get_hits.fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            ("L1", "get", "miss") => {
                self.counters.l1_get_misses.fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            ("L2", "get", "hit") => {
                self.counters.l2_get_hits.fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            ("L2", "get", "miss") => {
                self.counters.l2_get_misses.fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            ("L1", "set", "attempt") => {
                self.counters.l1_set_total.fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            ("L2", "set", "attempt") => {
                self.counters.l2_set_total.fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            ("L1", "delete", "attempt") => {
                self.counters
                    .l1_delete_total
                    .fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            ("L2", "delete", "attempt") => {
                self.counters
                    .l2_delete_total
                    .fetch_add(1, Ordering::Relaxed);
                self.counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
                return;
            }
            _ => {}
        }

        // 其他操作使用DashMap(无锁)
        let key = format!("{}:{}:{}:{}", service, layer, op, result);
        self.requests_total
            .entry(key)
            .and_modify(|v| *v += 1)
            .or_insert(1);
    }

    /// 记录操作耗时
    pub fn record_duration(&self, service: &str, layer: &str, op: &str, duration_secs: f64) {
        let key = format!("{}:{}:{}", service, layer, op);
        self.operation_duration
            .entry(key)
            .and_modify(|entry| {
                entry.0 += duration_secs;
                entry.1 += 1;
            })
            .or_insert((duration_secs, 1));
    }

    /// 设置健康状态
    ///
    /// # 参数
    ///
    /// * `service` - 服务名称
    /// * `status` - 健康状态码(0: 不健康, 1: 健康, 2: 恢复中)
    pub fn set_health(&self, service: &str, status: u8) {
        self.l2_health_status.insert(service.to_string(), status);
    }

    /// 设置WAL大小
    ///
    /// # 参数
    ///
    /// * `service` - 服务名称
    /// * `size` - WAL条目数量
    pub fn set_wal_size(&self, service: &str, size: usize) {
        self.wal_entries.insert(service.to_string(), size);
    }

    /// 设置批量写入缓冲区大小
    pub fn set_batch_buffer_size(&self, service: &str, size: usize) {
        self.batch_buffer_size.insert(service.to_string(), size);
    }

    /// 设置批量写入成功率
    pub fn set_batch_success_rate(&self, service: &str, rate: f64) {
        self.batch_success_rate.insert(service.to_string(), rate);
    }

    /// 设置批量写入吞吐量
    pub fn set_batch_throughput(&self, service: &str, throughput: f64) {
        self.batch_throughput
            .insert(service.to_string(), throughput);
    }

    /// 获取原子计数器的值
    pub fn get_counters(&self) -> (u64, u64, u64, u64, u64, u64, u64, u64, u64) {
        (
            self.counters.l1_get_hits.load(Ordering::Relaxed),
            self.counters.l1_get_misses.load(Ordering::Relaxed),
            self.counters.l2_get_hits.load(Ordering::Relaxed),
            self.counters.l2_get_misses.load(Ordering::Relaxed),
            self.counters.l1_set_total.load(Ordering::Relaxed),
            self.counters.l2_set_total.load(Ordering::Relaxed),
            self.counters.l1_delete_total.load(Ordering::Relaxed),
            self.counters.l2_delete_total.load(Ordering::Relaxed),
            self.counters.total_operations.load(Ordering::Relaxed),
        )
    }
}

/// 获取指标字符串
///
/// 将所有指标格式化为字符串返回,用于监控系统采集
///
/// # 返回值
///
/// 返回包含所有指标的字符串
///
/// # 注意
///
/// DashMap 无锁,无需担心死锁
#[cfg(any(feature = "metrics", feature = "l1-moka"))]
pub fn get_metrics_string() -> String {
    let metrics = &GLOBAL_METRICS;
    let mut output = String::new();

    // 输出原子计数器(高频指标,无锁)
    let counters = metrics.get_counters();
    output.push_str(&format!("cache_l1_get_hits_total {}\n", counters.0));
    output.push_str(&format!("cache_l1_get_misses_total {}\n", counters.1));
    output.push_str(&format!("cache_l2_get_hits_total {}\n", counters.2));
    output.push_str(&format!("cache_l2_get_misses_total {}\n", counters.3));
    output.push_str(&format!("cache_l1_set_total {}\n", counters.4));
    output.push_str(&format!("cache_l2_set_total {}\n", counters.5));
    output.push_str(&format!("cache_l1_delete_total {}\n", counters.6));
    output.push_str(&format!("cache_l2_delete_total {}\n", counters.7));
    output.push_str(&format!("cache_operations_total {}\n", counters.8));

    // DashMap 无锁迭代
    let requests: &DashMap<String, u64> = &metrics.requests_total;
    for entry in requests.iter() {
        let (key, value): (&String, &u64) = entry.pair();
        output.push_str(&format!(
            "cache_requests_total{{labels=\"{}\"}} {}\n",
            key, value
        ));
    }

    let health_status: &DashMap<String, u8> = &metrics.l2_health_status;
    for entry in health_status.iter() {
        let (key, value): (&String, &u8) = entry.pair();
        output.push_str(&format!(
            "cache_l2_health_status{{service=\"{}\"}} {}\n",
            key, value
        ));
    }

    let wal_entries: &DashMap<String, usize> = &metrics.wal_entries;
    for entry in wal_entries.iter() {
        let (key, value): (&String, &usize) = entry.pair();
        output.push_str(&format!(
            "cache_wal_entries{{service=\"{}\"}} {}\n",
            key, value
        ));
    }

    let durations: &DashMap<String, (f64, u64)> = &metrics.operation_duration;
    for entry in durations.iter() {
        let (key, (total_duration, count)): (&String, &(f64, u64)) = entry.pair();
        if *count > 0 {
            let parts: Vec<&str> = key.split(':').collect();
            if parts.len() >= 3 {
                let service = parts[0];
                let layer = parts[1];
                let op = parts[2];
                let avg_duration = total_duration / *count as f64;
                output.push_str(&format!(
                            "cache_operation_duration_seconds{{service=\"{}\",layer=\"{}\",op=\"{}\"}} {}\n",
                            service,
                            layer,
                            op,
                            avg_duration
                        ));
            }
        }
    }

    let buffer_sizes: &DashMap<String, usize> = &metrics.batch_buffer_size;
    for entry in buffer_sizes.iter() {
        let (key, value): (&String, &usize) = entry.pair();
        output.push_str(&format!(
            "cache_batch_buffer_size{{service=\"{}\"}} {}\n",
            key, value
        ));
    }

    let success_rates: &DashMap<String, f64> = &metrics.batch_success_rate;
    for entry in success_rates.iter() {
        let (key, value): (&String, &f64) = entry.pair();
        output.push_str(&format!(
            "cache_batch_success_rate{{service=\"{}\"}} {}\n",
            key, value
        ));
    }

    let throughputs: &DashMap<String, f64> = &metrics.batch_throughput;
    for entry in throughputs.iter() {
        let (key, value): (&String, &f64) = entry.pair();
        output.push_str(&format!(
            "cache_batch_throughput{{service=\"{}\"}} {}\n",
            key, value
        ));
    }

    output
}

/// 当 metrics 和 l1-moka 功能都禁用时的空实现
#[cfg(not(any(feature = "metrics", feature = "l1-moka")))]
#[derive(Debug, Clone, Default)]
pub struct Metrics;

#[cfg(not(any(feature = "metrics", feature = "l1-moka")))]
impl Metrics {
    /// 记录请求指标(空实现)
    pub fn record_request(&self, _service: &str, _layer: &str, _op: &str, _result: &str) {}

    /// 记录操作耗时(空实现)
    pub fn record_duration(&self, _service: &str, _layer: &str, _op: &str, _duration_secs: f64) {}

    /// 设置健康状态(空实现)
    pub fn set_health(&self, _service: &str, _status: u8) {}

    /// 设置WAL大小(空实现)
    pub fn set_wal_size(&self, _service: &str, _size: usize) {}

    /// 设置批量写入缓冲区大小(空实现)
    pub fn set_batch_buffer_size(&self, _service: &str, _size: usize) {}

    /// 设置批量写入成功率(空实现)
    pub fn set_batch_success_rate(&self, _service: &str, _rate: f64) {}

    /// 设置批量写入吞吐量(空实现)
    pub fn set_batch_throughput(&self, _service: &str, _throughput: f64) {}

    /// 获取原子计数器的值(返回全0)
    pub fn get_counters(&self) -> (u64, u64, u64, u64, u64, u64, u64, u64, u64) {
        (0, 0, 0, 0, 0, 0, 0, 0, 0)
    }
}

#[cfg(not(any(feature = "metrics", feature = "l1-moka")))]
lazy_static! {
    /// 全局空指标实例
    pub static ref GLOBAL_METRICS: Metrics = Metrics;
}

#[cfg(not(any(feature = "metrics", feature = "l1-moka")))]
/// 当 metrics 功能禁用时返回空字符串
pub fn get_metrics_string() -> String {
    String::new()
}

// ============================================================================
// Enhanced Statistics (enhanced-stats feature)
// ============================================================================

/// 缓存统计快照
///
/// 包含缓存系统的详细统计信息,用于监控和报告。
#[derive(Debug, Clone, Default, Serialize)]
#[cfg(any(feature = "enhanced-stats", feature = "metrics"))]
pub struct CacheStats {
    /// L1 命中次数
    pub l1_hits: u64,
    /// L1 未命中次数
    pub l1_misses: u64,
    /// L2 命中次数
    pub l2_hits: u64,
    /// L2 未命中次数
    pub l2_misses: u64,
    /// L1 设置次数
    pub l1_sets: u64,
    /// L2 设置次数
    pub l2_sets: u64,
    /// L1 删除次数
    pub l1_deletes: u64,
    /// L2 删除次数
    pub l2_deletes: u64,
    /// 总操作次数
    pub total_operations: u64,
    /// L1 缓存项数量
    pub l1_item_count: u64,
    /// L1 容量使用(字节)
    pub l1_capacity_used: u64,
    /// 预取操作次数
    pub prefetch_count: u64,
    /// 压缩操作次数
    pub compression_count: u64,
    /// 压缩节省的字节数
    pub compression_bytes_saved: u64,
    /// 快照创建时间戳
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

#[cfg(any(feature = "enhanced-stats", feature = "metrics"))]
impl CacheStats {
    /// 计算 L1 命中率
    pub fn l1_hit_rate(&self) -> f64 {
        let total = self.l1_hits + self.l1_misses;
        if total == 0 {
            0.0
        } else {
            self.l1_hits as f64 / total as f64
        }
    }

    /// 计算 L2 命中率
    pub fn l2_hit_rate(&self) -> f64 {
        let total = self.l2_hits + self.l2_misses;
        if total == 0 {
            0.0
        } else {
            self.l2_hits as f64 / total as f64
        }
    }

    /// 计算总体命中率
    pub fn overall_hit_rate(&self) -> f64 {
        let total = self.l1_hits + self.l1_misses + self.l2_hits + self.l2_misses;
        if total == 0 {
            0.0
        } else {
            (self.l1_hits + self.l2_hits) as f64 / total as f64
        }
    }

    /// 获取命中率百分比字符串
    pub fn l1_hit_rate_percent(&self) -> String {
        format!("{:.2}%", self.l1_hit_rate() * 100.0)
    }

    /// 获取 L2 命中率百分比字符串
    pub fn l2_hit_rate_percent(&self) -> String {
        format!("{:.2}%", self.l2_hit_rate() * 100.0)
    }

    /// 获取总体命中率百分比字符串
    pub fn overall_hit_rate_percent(&self) -> String {
        format!("{:.2}%", self.overall_hit_rate() * 100.0)
    }

    /// 导出为 Prometheus 格式
    pub fn export_prometheus(&self) -> String {
        let mut output = String::new();

        // 计数器指标
        output.push_str("# Cache Statistics\n");
        output.push_str(&format!("# Generated at: {}\n", self.timestamp));

        output.push_str(&format!("cache_l1_hits_total {}\n", self.l1_hits));
        output.push_str(&format!("cache_l1_misses_total {}\n", self.l1_misses));
        output.push_str(&format!("cache_l2_hits_total {}\n", self.l2_hits));
        output.push_str(&format!("cache_l2_misses_total {}\n", self.l2_misses));
        output.push_str(&format!("cache_l1_sets_total {}\n", self.l1_sets));
        output.push_str(&format!("cache_l2_sets_total {}\n", self.l2_sets));
        output.push_str(&format!("cache_l1_deletes_total {}\n", self.l1_deletes));
        output.push_str(&format!("cache_l2_deletes_total {}\n", self.l2_deletes));
        output.push_str(&format!(
            "cache_operations_total {}\n",
            self.total_operations
        ));

        // 计算并导出命中率
        output.push_str(&format!("cache_l1_hit_rate {}\n", self.l1_hit_rate()));
        output.push_str(&format!("cache_l2_hit_rate {}\n", self.l2_hit_rate()));
        output.push_str(&format!(
            "cache_overall_hit_rate {}\n",
            self.overall_hit_rate()
        ));

        // 容量指标
        output.push_str(&format!("cache_l1_item_count {}\n", self.l1_item_count));
        output.push_str(&format!(
            "cache_l1_capacity_used_bytes {}\n",
            self.l1_capacity_used
        ));

        // 压缩指标
        output.push_str(&format!("cache_prefetch_total {}\n", self.prefetch_count));
        output.push_str(&format!(
            "cache_compression_total {}\n",
            self.compression_count
        ));
        output.push_str(&format!(
            "cache_compression_bytes_saved {}\n",
            self.compression_bytes_saved
        ));

        output
    }

    /// 导出为 JSON 格式
    pub fn export_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

#[cfg(any(feature = "enhanced-stats", feature = "metrics"))]
impl Metrics {
    /// 创建统计快照
    pub fn snapshot(&self) -> CacheStats {
        let counters = &self.counters;
        CacheStats {
            l1_hits: counters.l1_get_hits.load(Ordering::Relaxed),
            l1_misses: counters.l1_get_misses.load(Ordering::Relaxed),
            l2_hits: counters.l2_get_hits.load(Ordering::Relaxed),
            l2_misses: counters.l2_get_misses.load(Ordering::Relaxed),
            l1_sets: counters.l1_set_total.load(Ordering::Relaxed),
            l2_sets: counters.l2_set_total.load(Ordering::Relaxed),
            l1_deletes: counters.l1_delete_total.load(Ordering::Relaxed),
            l2_deletes: counters.l2_delete_total.load(Ordering::Relaxed),
            total_operations: counters.total_operations.load(Ordering::Relaxed),
            l1_item_count: counters.l1_items.load(Ordering::Relaxed),
            l1_capacity_used: counters.l1_capacity_used.load(Ordering::Relaxed),
            prefetch_count: counters.prefetch_total.load(Ordering::Relaxed),
            compression_count: counters.compression_total.load(Ordering::Relaxed),
            compression_bytes_saved: counters.compression_bytes_saved.load(Ordering::Relaxed),
            timestamp: chrono::Utc::now(),
        }
    }

    /// 重置所有统计
    pub fn reset(&self) {
        let counters = &self.counters;
        counters.l1_get_hits.store(0, Ordering::Relaxed);
        counters.l1_get_misses.store(0, Ordering::Relaxed);
        counters.l2_get_hits.store(0, Ordering::Relaxed);
        counters.l2_get_misses.store(0, Ordering::Relaxed);
        counters.l1_set_total.store(0, Ordering::Relaxed);
        counters.l2_set_total.store(0, Ordering::Relaxed);
        counters.l1_delete_total.store(0, Ordering::Relaxed);
        counters.l2_delete_total.store(0, Ordering::Relaxed);
        counters.total_operations.store(0, Ordering::Relaxed);
        counters.l1_items.store(0, Ordering::Relaxed);
        counters.l1_capacity_used.store(0, Ordering::Relaxed);
        counters.prefetch_total.store(0, Ordering::Relaxed);
        counters.compression_total.store(0, Ordering::Relaxed);
        counters.compression_bytes_saved.store(0, Ordering::Relaxed);

        // 清空 DashMap
        self.requests_total.clear();
        self.operation_duration.clear();
        self.batch_buffer_size.clear();
        self.batch_success_rate.clear();
        self.batch_throughput.clear();
    }

    /// 获取命中率
    pub fn hit_rate(&self) -> f64 {
        let counters = &self.counters;
        let hits = counters.l1_get_hits.load(Ordering::Relaxed)
            + counters.l2_get_hits.load(Ordering::Relaxed);
        let misses = counters.l1_get_misses.load(Ordering::Relaxed)
            + counters.l2_get_misses.load(Ordering::Relaxed);
        let total = hits + misses;
        if total == 0 {
            1.0
        } else {
            hits as f64 / total as f64
        }
    }

    /// 获取命中率百分比
    pub fn hit_rate_percent(&self) -> String {
        format!("{:.2}%", self.hit_rate() * 100.0)
    }

    /// 记录预取操作
    pub fn record_prefetch(&self) {
        self.counters.prefetch_total.fetch_add(1, Ordering::Relaxed);
    }

    /// 记录压缩操作
    pub fn record_compression(&self, bytes_saved: u64) {
        self.counters
            .compression_total
            .fetch_add(1, Ordering::Relaxed);
        self.counters
            .compression_bytes_saved
            .fetch_add(bytes_saved, Ordering::Relaxed);
    }

    /// 设置 L1 缓存项数量
    pub fn set_l1_item_count(&self, count: u64) {
        self.counters.l1_items.store(count, Ordering::Relaxed);
    }

    /// 设置 L1 容量使用
    pub fn set_l1_capacity_used(&self, bytes: u64) {
        self.counters
            .l1_capacity_used
            .store(bytes, Ordering::Relaxed);
    }

    /// 导出 Prometheus 格式
    pub fn export_prometheus(&self) -> String {
        self.snapshot().export_prometheus()
    }

    /// 导出 JSON 格式
    pub fn export_json(&self) -> Result<String, serde_json::Error> {
        self.snapshot().export_json()
    }
}

/// 获取增强统计快照(全局)
#[cfg(any(feature = "enhanced-stats", feature = "metrics"))]
pub fn get_enhanced_stats() -> CacheStats {
    GLOBAL_METRICS.snapshot()
}

/// 导出 Prometheus 格式(全局)
#[cfg(any(feature = "enhanced-stats", feature = "metrics"))]
pub fn export_prometheus_format() -> String {
    GLOBAL_METRICS.export_prometheus()
}

/// 导出 JSON 格式(全局)
#[cfg(any(feature = "enhanced-stats", feature = "metrics"))]
pub fn export_json_format() -> Result<String, serde_json::Error> {
    GLOBAL_METRICS.export_json()
}