dbnexus 0.1.3

An enterprise-grade database abstraction layer for Rust with built-in permission control and connection pooling
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
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
// Copyright (c) 2026 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

//! 性能指标收集模块
//!
//! 提供全面的性能指标收集功能,包括:
//! - **延迟指标**: P50、P90、P95、P99 延迟百分位
//! - **吞吐量指标**: 查询/秒、事务/秒
//! - **延迟分布**: 直方图统计
//! - **连接指标**: 连接获取延迟、连接池使用率
//! - **事务指标**: 事务持续时间、事务成功率

use parking_lot::RwLock;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

/// 最大延迟样本数(滑动窗口大小)
const MAX_LATENCY_SAMPLES: usize = 10000;

/// 延迟百分位数据
#[derive(Debug, Clone, Default)]
pub struct LatencyPercentiles {
    /// P50 延迟(纳秒)
    pub p50_ns: u64,
    /// P75 延迟(纳秒)
    pub p75_ns: u64,
    /// P90 延迟(纳秒)
    pub p90_ns: u64,
    /// P95 延迟(纳秒)
    pub p95_ns: u64,
    /// P99 延迟(纳秒)
    pub p99_ns: u64,
    /// P99.9 延迟(纳秒)
    pub p999_ns: u64,
    /// 最小延迟(纳秒)
    pub min_ns: u64,
    /// 最大延迟(纳秒)
    pub max_ns: u64,
    /// 样本数量
    pub sample_count: u64,
}

impl LatencyPercentiles {
    /// 获取 P50 延迟
    pub fn p50(&self) -> Duration {
        Duration::from_nanos(self.p50_ns)
    }

    /// 获取 P75 延迟
    pub fn p75(&self) -> Duration {
        Duration::from_nanos(self.p75_ns)
    }

    /// 获取 P90 延迟
    pub fn p90(&self) -> Duration {
        Duration::from_nanos(self.p90_ns)
    }

    /// 获取 P95 延迟
    pub fn p95(&self) -> Duration {
        Duration::from_nanos(self.p95_ns)
    }

    /// 获取 P99 延迟
    pub fn p99(&self) -> Duration {
        Duration::from_nanos(self.p99_ns)
    }

    /// 获取 P99.9 延迟
    pub fn p999(&self) -> Duration {
        Duration::from_nanos(self.p999_ns)
    }

    /// 获取最小延迟
    pub fn min(&self) -> Duration {
        Duration::from_nanos(self.min_ns)
    }

    /// 获取最大延迟
    pub fn max(&self) -> Duration {
        Duration::from_nanos(self.max_ns)
    }
}

/// 延迟直方图桶
#[derive(Debug)]
pub struct LatencyHistogram {
    /// 桶边界(毫秒)
    buckets: Vec<u64>,
    /// 每个桶的计数
    counts: Vec<AtomicU64>,
    /// 总样本数
    total: AtomicU64,
}

impl LatencyHistogram {
    /// 创建新的延迟直方图
    ///
    /// # Arguments
    ///
    /// * `bucket_boundaries` - 桶边界定义(毫秒),如 [1, 5, 10, 50, 100, 500, 1000]
    pub fn new(bucket_boundaries: Vec<u64>) -> Self {
        let counts: Vec<_> = (0..bucket_boundaries.len() + 1).map(|_| AtomicU64::new(0)).collect();

        Self {
            buckets: bucket_boundaries,
            counts,
            total: AtomicU64::new(0),
        }
    }

    /// 记录一次延迟
    pub fn record(&self, duration: Duration) {
        let latency_ms = duration.as_millis() as u64;
        let mut bucket_idx = 0;

        for (idx, boundary) in self.buckets.iter().enumerate() {
            if latency_ms <= *boundary {
                bucket_idx = idx;
                break;
            }
            bucket_idx = idx + 1;
        }

        self.counts[bucket_idx].fetch_add(1, Ordering::SeqCst);
        self.total.fetch_add(1, Ordering::SeqCst);
    }

    /// 获取直方图统计
    pub fn stats(&self) -> HistogramStats {
        let total = self.total.load(Ordering::SeqCst);

        let mut cumulative = 0u64;
        let mut bucket_stats = Vec::new();

        for (idx, boundary) in self.buckets.iter().enumerate() {
            let count = self.counts[idx].load(Ordering::SeqCst);
            cumulative += count;
            bucket_stats.push(HistogramBucket {
                boundary_ms: *boundary,
                count,
                cumulative_count: cumulative,
                percentile: if total > 0 {
                    (cumulative as f64 / total as f64) * 100.0
                } else {
                    0.0
                },
            });
        }

        // 溢出桶
        let overflow_count = self.counts[self.buckets.len()].load(Ordering::SeqCst);
        cumulative += overflow_count;
        bucket_stats.push(HistogramBucket {
            boundary_ms: u64::MAX,
            count: overflow_count,
            cumulative_count: cumulative,
            percentile: if total > 0 {
                (cumulative as f64 / total as f64) * 100.0
            } else {
                0.0
            },
        });

        HistogramStats {
            total_samples: total,
            buckets: bucket_stats,
        }
    }
}

/// 直方图桶统计
#[derive(Debug, Clone)]
pub struct HistogramBucket {
    /// 桶边界(毫秒)
    pub boundary_ms: u64,
    /// 桶内样本数
    pub count: u64,
    /// 累计样本数
    pub cumulative_count: u64,
    /// 累计百分比
    pub percentile: f64,
}

/// 直方图统计
#[derive(Debug, Clone)]
pub struct HistogramStats {
    /// 总样本数
    pub total_samples: u64,
    /// 桶统计
    pub buckets: Vec<HistogramBucket>,
}

/// 吞吐量统计
#[derive(Debug, Clone)]
pub struct ThroughputStats {
    /// 总操作数
    pub total_operations: u64,
    /// 成功操作数
    pub success_count: u64,
    /// 失败操作数
    pub failure_count: u64,
    /// 错误率
    pub error_rate: f64,
    /// 平均 QPS
    pub avg_qps: f64,
    /// 窗口 QPS
    pub window_qps: f64,
}

/// 查询统计信息(增强版)
#[derive(Debug, Clone)]
pub struct QueryStats {
    /// 查询次数
    pub count: u64,
    /// 错误次数
    pub error_count: u64,
    /// 延迟百分位
    pub latency_percentiles: LatencyPercentiles,
    /// 直方图统计
    pub histogram: HistogramStats,
    /// 吞吐量统计
    pub throughput: ThroughputStats,
}

impl QueryStats {
    /// 获取错误率
    pub fn error_rate(&self) -> f64 {
        if self.count == 0 {
            0.0
        } else {
            self.error_count as f64 / self.count as f64
        }
    }
}

/// 慢查询配置
#[derive(Debug, Clone)]
pub struct SlowQueryConfig {
    /// 慢查询阈值(毫秒)
    pub threshold_ms: u64,
    /// 是否记录慢查询
    pub enabled: bool,
}

/// 慢查询记录
#[derive(Debug, Clone)]
pub struct SlowQueryRecord {
    /// 查询类型
    pub query_type: String,
    /// 查询耗时
    pub duration_ms: u64,
    /// 记录时间
    pub timestamp: time::OffsetDateTime,
}

/// 连接获取统计
#[derive(Debug, Clone)]
pub struct ConnectionAcquireStats {
    /// 总尝试次数
    pub total_attempts: u64,
    /// 成功次数
    pub success_count: u64,
    /// 超时次数
    pub timeout_count: u64,
    /// 失败次数
    pub failure_count: u64,
    /// 超时率
    pub timeout_rate: f64,
}

/// 事务统计
#[derive(Debug, Clone)]
pub struct TransactionStats {
    /// 总事务数
    pub total_transactions: u64,
    /// 提交次数
    pub commit_count: u64,
    /// 回滚次数
    pub rollback_count: u64,
    /// 失败次数
    pub failure_count: u64,
    /// 成功率
    pub success_rate: f64,
}

/// 连接池指标
#[derive(Debug, Clone)]
pub struct PoolMetrics {
    /// 总连接数
    pub total: u64,
    /// 活跃连接数
    pub active: u64,
    /// 空闲连接数
    pub idle: u64,
}

impl PoolMetrics {
    /// 获取连接使用率
    pub fn utilization_rate(&self) -> f64 {
        if self.total == 0 {
            0.0
        } else {
            self.active as f64 / self.total as f64
        }
    }
}

/// 延迟样本存储(使用滑动窗口限制内存使用)
#[derive(Debug)]
struct LatencyStorage {
    /// 存储的延迟样本(滑动窗口,使用 VecDeque 实现)
    samples: VecDeque<u64>,
    /// 最小延迟
    min: u64,
    /// 最大延迟
    max: u64,
}

impl LatencyStorage {
    fn new() -> Self {
        Self {
            samples: VecDeque::with_capacity(MAX_LATENCY_SAMPLES),
            min: u64::MAX,
            max: 0,
        }
    }

    fn record(&mut self, latency_ns: u64) {
        // 使用滑动窗口:如果达到最大容量,移除最旧的样本
        if self.samples.len() >= MAX_LATENCY_SAMPLES {
            self.samples.pop_front();
        }
        self.samples.push_back(latency_ns);

        if latency_ns < self.min {
            self.min = latency_ns;
        }
        if latency_ns > self.max {
            self.max = latency_ns;
        }
    }

    fn percentiles(&self) -> LatencyPercentiles {
        if self.samples.is_empty() {
            return LatencyPercentiles::default();
        }

        let mut sorted: Vec<_> = self.samples.iter().cloned().collect();
        sorted.sort();

        let len = sorted.len();
        let p50_idx = (len as f64 * 0.50) as usize;
        let p75_idx = (len as f64 * 0.75) as usize;
        let p90_idx = (len as f64 * 0.90) as usize;
        let p95_idx = (len as f64 * 0.95) as usize;
        let p99_idx = (len as f64 * 0.99) as usize;
        let p999_idx = (len as f64 * 0.999) as usize;

        LatencyPercentiles {
            p50_ns: sorted[p50_idx],
            p75_ns: sorted[p75_idx],
            p90_ns: sorted[p90_idx],
            p95_ns: sorted[p95_idx],
            p99_ns: sorted[p99_idx],
            p999_ns: sorted[p999_idx],
            min_ns: self.min,
            max_ns: self.max,
            sample_count: self.samples.len() as u64,
        }
    }

    fn clear(&mut self) {
        self.samples.clear();
        self.min = u64::MAX;
        self.max = 0;
    }
}

/// Metrics 收集器(增强版)
///
/// 提供全面的性能指标收集功能
#[derive(Clone)]
pub struct MetricsCollector {
    /// 按查询类型分类的指标
    query_metrics: Arc<RwLock<HashMap<String, Arc<QueryMetricsInner>>>>,

    /// 连接池总连接数
    pool_total: Arc<AtomicU64>,
    /// 连接池活跃连接数
    pool_active: Arc<AtomicU64>,
    /// 连接池空闲连接数
    pool_idle: Arc<AtomicU64>,

    /// 连接错误计数
    connection_errors: Arc<AtomicU64>,
    /// 查询错误计数
    query_errors: Arc<AtomicU64>,

    /// 连接获取指标
    connection_acquire: Arc<RwLock<ConnectionAcquireMetricsInner>>,
    /// 事务指标
    transaction: Arc<RwLock<TransactionMetricsInner>>,

    /// 慢查询记录(最近 N 条)
    slow_queries: Arc<RwLock<VecDeque<SlowQueryRecord>>>,
    /// 慢查询配置
    slow_query_config: Arc<RwLock<SlowQueryConfig>>,
    /// 慢查询最大记录数
    max_slow_queries: usize,

    /// 启动时间
    start_time: Instant,
}

struct QueryMetricsInner {
    /// 延迟存储
    latency: RwLock<LatencyStorage>,
    /// 直方图
    histogram: LatencyHistogram,
    /// 吞吐量跟踪器
    throughput: ThroughputTrackerInner,
    /// 错误计数
    error_count: AtomicU64,
}

struct ThroughputTrackerInner {
    success_count: AtomicU64,
    failure_count: AtomicU64,
    bytes_total: AtomicU64,
    last_record_time: AtomicU64,
}

impl ThroughputTrackerInner {
    fn new() -> Self {
        Self {
            success_count: AtomicU64::new(0),
            failure_count: AtomicU64::new(0),
            bytes_total: AtomicU64::new(0),
            last_record_time: AtomicU64::new(0),
        }
    }

    fn record_success(&self, bytes: Option<u64>) {
        let now = Instant::now().elapsed().as_secs();
        self.success_count.fetch_add(1, Ordering::SeqCst);
        self.last_record_time.store(now, Ordering::SeqCst);
        if let Some(b) = bytes {
            self.bytes_total.fetch_add(b, Ordering::SeqCst);
        }
    }

    fn record_failure(&self) {
        self.failure_count.fetch_add(1, Ordering::SeqCst);
    }

    fn throughput(&self, elapsed_secs: u64) -> ThroughputStats {
        let success = self.success_count.load(Ordering::SeqCst);
        let failure = self.failure_count.load(Ordering::SeqCst);
        let total = success + failure;
        let avg_qps = if elapsed_secs > 0 {
            total as f64 / elapsed_secs as f64
        } else {
            total as f64
        };

        ThroughputStats {
            total_operations: total,
            success_count: success,
            failure_count: failure,
            error_rate: if total > 0 { failure as f64 / total as f64 } else { 0.0 },
            avg_qps,
            window_qps: 0.0,
        }
    }

    fn total_operations(&self) -> u64 {
        self.success_count.load(Ordering::SeqCst) + self.failure_count.load(Ordering::SeqCst)
    }
}

struct ConnectionAcquireMetricsInner {
    total_attempts: AtomicU64,
    success_count: AtomicU64,
    timeout_count: AtomicU64,
    failure_count: AtomicU64,
}

impl ConnectionAcquireMetricsInner {
    fn new() -> Self {
        Self {
            total_attempts: AtomicU64::new(0),
            success_count: AtomicU64::new(0),
            timeout_count: AtomicU64::new(0),
            failure_count: AtomicU64::new(0),
        }
    }

    fn record_success(&self) {
        self.total_attempts.fetch_add(1, Ordering::SeqCst);
        self.success_count.fetch_add(1, Ordering::SeqCst);
    }

    fn record_timeout(&self) {
        self.total_attempts.fetch_add(1, Ordering::SeqCst);
        self.timeout_count.fetch_add(1, Ordering::SeqCst);
    }

    fn record_failure(&self) {
        self.total_attempts.fetch_add(1, Ordering::SeqCst);
        self.failure_count.fetch_add(1, Ordering::SeqCst);
    }

    fn stats(&self) -> ConnectionAcquireStats {
        let total = self.total_attempts.load(Ordering::SeqCst);
        ConnectionAcquireStats {
            total_attempts: total,
            success_count: self.success_count.load(Ordering::SeqCst),
            timeout_count: self.timeout_count.load(Ordering::SeqCst),
            failure_count: self.failure_count.load(Ordering::SeqCst),
            timeout_rate: if total > 0 {
                self.timeout_count.load(Ordering::SeqCst) as f64 / total as f64
            } else {
                0.0
            },
        }
    }
}

struct TransactionMetricsInner {
    total_transactions: AtomicU64,
    commit_count: AtomicU64,
    rollback_count: AtomicU64,
    failure_count: AtomicU64,
}

impl TransactionMetricsInner {
    fn new() -> Self {
        Self {
            total_transactions: AtomicU64::new(0),
            commit_count: AtomicU64::new(0),
            rollback_count: AtomicU64::new(0),
            failure_count: AtomicU64::new(0),
        }
    }

    fn record_commit(&self) {
        self.total_transactions.fetch_add(1, Ordering::SeqCst);
        self.commit_count.fetch_add(1, Ordering::SeqCst);
    }

    fn record_rollback(&self) {
        self.total_transactions.fetch_add(1, Ordering::SeqCst);
        self.rollback_count.fetch_add(1, Ordering::SeqCst);
    }

    fn record_failure(&self) {
        self.total_transactions.fetch_add(1, Ordering::SeqCst);
        self.failure_count.fetch_add(1, Ordering::SeqCst);
    }

    fn stats(&self) -> TransactionStats {
        let total = self.total_transactions.load(Ordering::SeqCst);
        TransactionStats {
            total_transactions: total,
            commit_count: self.commit_count.load(Ordering::SeqCst),
            rollback_count: self.rollback_count.load(Ordering::SeqCst),
            failure_count: self.failure_count.load(Ordering::SeqCst),
            success_rate: if total > 0 {
                (self.commit_count.load(Ordering::SeqCst) as f64 / total as f64) * 100.0
            } else {
                0.0
            },
        }
    }
}

impl Default for MetricsCollector {
    fn default() -> Self {
        Self::new()
    }
}

impl MetricsCollector {
    /// 创建新的 Metrics 收集器
    pub fn new() -> Self {
        Self {
            query_metrics: Arc::new(RwLock::new(HashMap::new())),
            pool_total: Arc::new(AtomicU64::new(0)),
            pool_active: Arc::new(AtomicU64::new(0)),
            pool_idle: Arc::new(AtomicU64::new(0)),
            connection_errors: Arc::new(AtomicU64::new(0)),
            query_errors: Arc::new(AtomicU64::new(0)),
            connection_acquire: Arc::new(RwLock::new(ConnectionAcquireMetricsInner::new())),
            transaction: Arc::new(RwLock::new(TransactionMetricsInner::new())),
            slow_queries: Arc::new(RwLock::new(VecDeque::new())),
            slow_query_config: Arc::new(RwLock::new(SlowQueryConfig {
                threshold_ms: 1000,
                enabled: true,
            })),
            max_slow_queries: 100,
            start_time: Instant::now(),
        }
    }

    /// 记录一次查询
    pub fn record_query(&self, query_type: &str, duration: Duration, success: bool, bytes: Option<u64>) {
        let latency_ns = duration.as_nanos() as u64;
        let duration_ms = duration.as_millis() as u64;

        // 获取或创建指标
        let metrics = {
            let mut map = self.query_metrics.write();
            if let Some(m) = map.get(query_type) {
                m.clone()
            } else {
                let new_metrics = Arc::new(QueryMetricsInner {
                    latency: RwLock::new(LatencyStorage::new()),
                    histogram: LatencyHistogram::new(vec![1, 5, 10, 25, 50, 100, 250, 500, 1000, 5000]),
                    throughput: ThroughputTrackerInner::new(),
                    error_count: AtomicU64::new(0),
                });
                map.insert(query_type.to_string(), new_metrics.clone());
                new_metrics
            }
        };

        // 记录延迟
        metrics.latency.write().record(latency_ns);
        metrics.histogram.record(duration);

        // 记录吞吐量
        if success {
            metrics.throughput.record_success(bytes);
        } else {
            metrics.throughput.record_failure();
            metrics.error_count.fetch_add(1, Ordering::SeqCst);
            self.query_errors.fetch_add(1, Ordering::SeqCst);
        }

        // 检查是否为慢查询
        let config = self.slow_query_config.read();
        if config.enabled && duration_ms >= config.threshold_ms {
            let mut slow = self.slow_queries.write();
            slow.push_back(SlowQueryRecord {
                query_type: query_type.to_string(),
                duration_ms,
                timestamp: time::OffsetDateTime::now_utc(),
            });
            while slow.len() > self.max_slow_queries {
                slow.pop_front();
            }
        }
    }

    /// 获取查询类型统计
    pub fn get_query_stats(&self, query_type: &str) -> Option<QueryStats> {
        let map = self.query_metrics.read();
        map.get(query_type).map(|m| {
            let elapsed = self.start_time.elapsed().as_secs();
            let throughput = m.throughput.throughput(elapsed);
            let latency = m.latency.read().percentiles();
            let histogram = m.histogram.stats();

            QueryStats {
                count: m.throughput.total_operations(),
                error_count: m.error_count.load(Ordering::SeqCst),
                latency_percentiles: latency,
                histogram,
                throughput,
            }
        })
    }

    /// 获取所有查询统计
    pub fn all_query_stats(&self) -> HashMap<String, QueryStats> {
        let map = self.query_metrics.read();
        let elapsed = self.start_time.elapsed().as_secs();
        map.iter()
            .map(|(k, v)| {
                let throughput = v.throughput.throughput(elapsed);
                let latency = v.latency.read().percentiles();
                let histogram = v.histogram.stats();

                (
                    k.clone(),
                    QueryStats {
                        count: v.throughput.total_operations(),
                        error_count: v.error_count.load(Ordering::SeqCst),
                        latency_percentiles: latency,
                        histogram,
                        throughput,
                    },
                )
            })
            .collect()
    }

    /// 获取总吞吐量统计
    pub fn total_throughput(&self) -> ThroughputStats {
        let elapsed = self.start_time.elapsed().as_secs();
        let map = self.query_metrics.read();
        let mut total = ThroughputStats {
            total_operations: 0,
            success_count: 0,
            failure_count: 0,
            error_rate: 0.0,
            avg_qps: 0.0,
            window_qps: 0.0,
        };

        for (_, m) in map.iter() {
            let throughput = m.throughput.throughput(elapsed);
            total.total_operations += throughput.total_operations;
            total.success_count += throughput.success_count;
            total.failure_count += throughput.failure_count;
            total.avg_qps += throughput.avg_qps;
        }

        if total.total_operations > 0 {
            total.error_rate = total.failure_count as f64 / total.total_operations as f64;
        }

        total
    }

    /// 获取慢查询记录
    pub fn slow_queries(&self) -> Vec<SlowQueryRecord> {
        self.slow_queries.read().iter().cloned().collect()
    }

    /// 设置慢查询阈值
    pub fn set_slow_query_threshold(&self, threshold_ms: u64) {
        let mut config = self.slow_query_config.write();
        config.threshold_ms = threshold_ms;
    }

    /// 启用/禁用慢查询记录
    pub fn set_slow_query_enabled(&self, enabled: bool) {
        let mut config = self.slow_query_config.write();
        config.enabled = enabled;
    }

    /// 记录连接错误
    pub fn record_connection_error(&self) {
        self.connection_errors.fetch_add(1, Ordering::SeqCst);
    }

    /// 获取连接错误计数
    pub fn connection_error_count(&self) -> u64 {
        self.connection_errors.load(Ordering::SeqCst)
    }

    /// 更新连接池状态
    pub fn update_pool_status(&self, total: u32, active: u32, idle: u32) {
        self.pool_total.store(total as u64, Ordering::SeqCst);
        self.pool_active.store(active as u64, Ordering::SeqCst);
        self.pool_idle.store(idle as u64, Ordering::SeqCst);
    }

    /// 获取连接池状态
    pub fn pool_status(&self) -> PoolMetrics {
        PoolMetrics {
            total: self.pool_total.load(Ordering::SeqCst),
            active: self.pool_active.load(Ordering::SeqCst),
            idle: self.pool_idle.load(Ordering::SeqCst),
        }
    }

    /// 记录连接获取成功
    pub fn record_connection_acquire_success(&self) {
        self.connection_acquire.write().record_success();
    }

    /// 记录连接获取超时
    pub fn record_connection_acquire_timeout(&self) {
        self.connection_acquire.write().record_timeout();
    }

    /// 记录连接获取失败
    pub fn record_connection_acquire_failure(&self) {
        self.connection_acquire.write().record_failure();
    }

    /// 获取连接获取统计
    pub fn connection_acquire_stats(&self) -> ConnectionAcquireStats {
        self.connection_acquire.read().stats()
    }

    /// 记录事务提交
    pub fn record_transaction_commit(&self) {
        self.transaction.write().record_commit();
    }

    /// 记录事务回滚
    pub fn record_transaction_rollback(&self) {
        self.transaction.write().record_rollback();
    }

    /// 记录事务失败
    pub fn record_transaction_failure(&self) {
        self.transaction.write().record_failure();
    }

    /// 获取事务统计
    pub fn transaction_stats(&self) -> TransactionStats {
        self.transaction.read().stats()
    }

    /// 获取运行时长
    pub fn uptime(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// 重置所有指标
    pub fn reset(&self) {
        self.pool_total.store(0, Ordering::SeqCst);
        self.pool_active.store(0, Ordering::SeqCst);
        self.pool_idle.store(0, Ordering::SeqCst);
        self.connection_errors.store(0, Ordering::SeqCst);
        self.query_errors.store(0, Ordering::SeqCst);

        let mut map = self.query_metrics.write();
        for metrics in map.values() {
            metrics.latency.write().clear();
            // 无法重置原子计数器,但它们会在下次统计时被覆盖
        }
        map.clear();

        let mut slow = self.slow_queries.write();
        slow.clear();

        let mut acquire = self.connection_acquire.write();
        *acquire = ConnectionAcquireMetricsInner::new();

        let mut txn = self.transaction.write();
        *txn = TransactionMetricsInner::new();
    }

    /// 导出为 Prometheus 格式
    pub fn export_prometheus(&self) -> String {
        // 优化:预分配缓冲区,减少字符串分配
        let mut output = String::with_capacity(2048);
        let now = time::OffsetDateTime::now_utc();

        let uptime_seconds = self.uptime().as_secs_f64();
        output.push_str("# TYPE dbnexus_uptime gauge\n");
        use std::fmt::Write;
        writeln!(output, "dbnexus_uptime_seconds {:.3}", uptime_seconds).unwrap();

        // 连接池指标
        output.push_str("# TYPE dbnexus_pool_connections gauge\n");
        writeln!(
            output,
            "dbnexus_pool_connections_total {}",
            self.pool_total.load(Ordering::SeqCst)
        )
        .unwrap();
        writeln!(
            output,
            "dbnexus_pool_connections_active {}",
            self.pool_active.load(Ordering::SeqCst)
        )
        .unwrap();
        writeln!(
            output,
            "dbnexus_pool_connections_idle {}",
            self.pool_idle.load(Ordering::SeqCst)
        )
        .unwrap();
        writeln!(
            output,
            "dbnexus_pool_connections_utilization {:.4}",
            self.pool_status().utilization_rate()
        )
        .unwrap();

        // 错误指标
        output.push_str("# TYPE dbnexus_errors counter\n");
        writeln!(
            output,
            "dbnexus_connection_errors_total {}",
            self.connection_errors.load(Ordering::SeqCst)
        )
        .unwrap();
        writeln!(
            output,
            "dbnexus_query_errors_total {}",
            self.query_errors.load(Ordering::SeqCst)
        )
        .unwrap();

        // 连接获取指标
        let acquire_stats = self.connection_acquire_stats();
        output.push_str("# TYPE dbnexus_connection_acquire counter\n");
        writeln!(
            output,
            "dbnexus_connection_acquire_total {}",
            acquire_stats.total_attempts
        )
        .unwrap();
        writeln!(
            output,
            "dbnexus_connection_acquire_timeout_total {}",
            acquire_stats.timeout_count
        )
        .unwrap();
        writeln!(
            output,
            "dbnexus_connection_acquire_failure_total {}",
            acquire_stats.failure_count
        )
        .unwrap();

        // 事务指标
        let txn_stats = self.transaction_stats();
        output.push_str("# TYPE dbnexus_transactions counter\n");
        writeln!(output, "dbnexus_transactions_total {}", txn_stats.total_transactions).unwrap();
        writeln!(output, "dbnexus_transactions_commit_total {}", txn_stats.commit_count).unwrap();
        writeln!(
            output,
            "dbnexus_transactions_rollback_total {}",
            txn_stats.rollback_count
        )
        .unwrap();
        writeln!(output, "dbnexus_transactions_failure_total {}", txn_stats.failure_count).unwrap();
        writeln!(
            output,
            "dbnexus_transactions_success_rate {:.2}",
            txn_stats.success_rate
        )
        .unwrap();

        // 查询指标
        let stats = self.all_query_stats();
        for (query_type, stat) in stats {
            let type_label = query_type.to_lowercase();

            // 使用 writeln! 替代 push_str + format!
            writeln!(
                output,
                "# TYPE dbnexus_queries_total counter\ndbnexus_queries_total{{type=\"{}\"}} {}",
                type_label, stat.count
            )
            .unwrap();

            output.push_str("# TYPE dbnexus_query_throughput gauge\n");
            writeln!(
                output,
                "dbnexus_query_throughput_qps{{type=\"{}\"}} {:.2}",
                type_label, stat.throughput.avg_qps
            )
            .unwrap();

            // 延迟百分位
            output.push_str("# TYPE dbnexus_query_latency_seconds gauge\n");
            let p50 = stat.latency_percentiles.p50().as_secs_f64();
            let p90 = stat.latency_percentiles.p90().as_secs_f64();
            let p95 = stat.latency_percentiles.p95().as_secs_f64();
            let p99 = stat.latency_percentiles.p99().as_secs_f64();

            writeln!(
                output,
                "dbnexus_query_latency_p50_seconds{{type=\"{}\"}} {:.6}",
                type_label, p50
            )
            .unwrap();
            writeln!(
                output,
                "dbnexus_query_latency_p90_seconds{{type=\"{}\"}} {:.6}",
                type_label, p90
            )
            .unwrap();
            writeln!(
                output,
                "dbnexus_query_latency_p95_seconds{{type=\"{}\"}} {:.6}",
                type_label, p95
            )
            .unwrap();
            writeln!(
                output,
                "dbnexus_query_latency_p99_seconds{{type=\"{}\"}} {:.6}",
                type_label, p99
            )
            .unwrap();
        }

        // 总吞吐量
        let total = self.total_throughput();
        output.push_str("# TYPE dbnexus_total_throughput gauge\n");
        writeln!(output, "dbnexus_total_qps {:.2}", total.avg_qps).unwrap();
        writeln!(output, "dbnexus_total_operations {}", total.total_operations).unwrap();
        writeln!(output, "dbnexus_error_rate {:.4}", total.error_rate).unwrap();

        output.push_str("# TYPE dbnexus_metrics_timestamp gauge\n");
        output.push_str(&format!("dbnexus_metrics_timestamp {}\n", now.unix_timestamp()));

        output
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// TEST-U-040: 延迟百分位计算测试
    #[test]
    fn test_latency_percentiles() {
        let collector = MetricsCollector::new();

        // 记录不同延迟
        for i in 1..=100 {
            collector.record_query("SELECT", Duration::from_millis(i), true, Some(100));
        }

        let stats = collector.get_query_stats("SELECT").unwrap();
        assert_eq!(stats.count, 100);

        // 验证 P50 大约为 50ms
        assert!(stats.latency_percentiles.p50_ns >= 49_000_000 && stats.latency_percentiles.p50_ns <= 51_000_000);
        // 验证 P99 大约为 99ms
        assert!(stats.latency_percentiles.p99_ns >= 98_000_000 && stats.latency_percentiles.p99_ns <= 100_000_000);
    }

    /// TEST-U-041: 延迟直方图测试
    #[test]
    fn test_latency_histogram() {
        let collector = MetricsCollector::new();

        // 记录不同延迟
        collector.record_query("SELECT", Duration::from_millis(5), true, None);
        collector.record_query("SELECT", Duration::from_millis(15), true, None);
        collector.record_query("SELECT", Duration::from_millis(75), true, None);
        collector.record_query("SELECT", Duration::from_millis(200), true, None);

        let stats = collector.get_query_stats("SELECT").unwrap();
        assert_eq!(stats.histogram.total_samples, 4);
    }

    /// TEST-U-042: 吞吐量测试
    #[test]
    fn test_throughput() {
        let collector = MetricsCollector::new();

        collector.record_query("SELECT", Duration::from_millis(10), true, Some(1024));
        collector.record_query("SELECT", Duration::from_millis(20), true, Some(2048));
        collector.record_query("INSERT", Duration::from_millis(50), false, None);

        let total = collector.total_throughput();
        assert_eq!(total.total_operations, 3);
        assert_eq!(total.success_count, 2);
        assert_eq!(total.failure_count, 1);
        assert!((total.error_rate - 0.333).abs() < 0.01);
    }

    /// TEST-U-043: 连接获取指标测试
    #[test]
    fn test_connection_acquire_metrics() {
        let collector = MetricsCollector::new();

        for _ in 0..50 {
            collector.record_connection_acquire_success();
        }
        for _ in 0..5 {
            collector.record_connection_acquire_timeout();
        }
        for _ in 0..3 {
            collector.record_connection_acquire_failure();
        }

        let stats = collector.connection_acquire_stats();
        assert_eq!(stats.success_count, 50);
        assert_eq!(stats.timeout_count, 5);
        assert_eq!(stats.failure_count, 3);
        assert_eq!(stats.total_attempts, 58);
    }

    /// TEST-U-044: 事务指标测试
    #[test]
    fn test_transaction_metrics() {
        let collector = MetricsCollector::new();

        for _ in 0..100 {
            collector.record_transaction_commit();
        }
        for _ in 0..20 {
            collector.record_transaction_rollback();
        }
        for _ in 0..5 {
            collector.record_transaction_failure();
        }

        let stats = collector.transaction_stats();
        assert_eq!(stats.commit_count, 100);
        assert_eq!(stats.rollback_count, 20);
        assert_eq!(stats.failure_count, 5);
        assert_eq!(stats.total_transactions, 125);
    }

    /// TEST-U-045: Prometheus 导出测试
    #[test]
    fn test_prometheus_export() {
        let collector = MetricsCollector::new();

        collector.record_query("SELECT", Duration::from_millis(10), true, Some(100));
        collector.record_query("INSERT", Duration::from_millis(50), false, None);

        let prometheus = collector.export_prometheus();

        assert!(prometheus.contains("dbnexus_uptime_seconds"));
        assert!(prometheus.contains("dbnexus_pool_connections_total"));
        assert!(prometheus.contains("dbnexus_queries_total"));
        assert!(prometheus.contains("dbnexus_total_qps"));
    }

    /// TEST-U-046: 慢查询记录测试
    #[test]
    fn test_slow_query_recording() {
        let collector = MetricsCollector::new();
        collector.set_slow_query_threshold(50);

        collector.record_query("SELECT", Duration::from_millis(100), true, None);

        let slow = collector.slow_queries();
        assert_eq!(slow.len(), 1);
        assert_eq!(slow[0].query_type, "SELECT");
        assert_eq!(slow[0].duration_ms, 100);
    }
}