elif_orm/connection/
statistics.rs1use crate::backends::DatabasePoolStats;
6use std::time::Instant;
7
8#[derive(Debug, Clone)]
10pub struct ExtendedPoolStats {
11 pub pool_stats: DatabasePoolStats,
12 pub acquire_count: u64,
13 pub acquire_errors: u64,
14 pub created_at: Instant,
15}
16
17impl ExtendedPoolStats {
18 pub fn error_rate(&self) -> f64 {
20 if self.acquire_count > 0 {
21 (self.acquire_errors as f64 / self.acquire_count as f64) * 100.0
22 } else {
23 0.0
24 }
25 }
26
27 pub fn uptime(&self) -> std::time::Duration {
29 self.created_at.elapsed()
30 }
31
32 pub fn success_rate(&self) -> f64 {
34 100.0 - self.error_rate()
35 }
36
37 pub fn utilization(&self) -> f64 {
39 if self.pool_stats.total_connections > 0 {
40 (self.pool_stats.active_connections as f64 / self.pool_stats.total_connections as f64)
41 * 100.0
42 } else {
43 0.0
44 }
45 }
46
47 pub fn is_under_stress(&self, threshold: f64) -> bool {
49 self.utilization() > threshold
50 }
51
52 pub fn has_concerning_error_rate(&self, threshold: f64) -> bool {
54 self.error_rate() > threshold
55 }
56}
57
58#[derive(Debug, Default)]
60pub struct PoolStatsAggregator {
61 pools: std::collections::HashMap<String, ExtendedPoolStats>,
62}
63
64impl PoolStatsAggregator {
65 pub fn new() -> Self {
66 Self {
67 pools: std::collections::HashMap::new(),
68 }
69 }
70
71 pub fn update_stats(&mut self, pool_name: String, stats: ExtendedPoolStats) {
73 self.pools.insert(pool_name, stats);
74 }
75
76 pub fn get_stats(&self, pool_name: &str) -> Option<&ExtendedPoolStats> {
78 self.pools.get(pool_name)
79 }
80
81 pub fn pool_names(&self) -> Vec<&String> {
83 self.pools.keys().collect()
84 }
85
86 pub fn aggregate_stats(&self) -> AggregatedStats {
88 let mut total_connections = 0;
89 let mut total_active = 0;
90 let mut total_idle = 0;
91 let mut total_acquires = 0;
92 let mut total_errors = 0;
93
94 for stats in self.pools.values() {
95 total_connections += stats.pool_stats.total_connections;
96 total_active += stats.pool_stats.active_connections;
97 total_idle += stats.pool_stats.idle_connections;
98 total_acquires += stats.acquire_count;
99 total_errors += stats.acquire_errors;
100 }
101
102 let error_rate = if total_acquires > 0 {
103 (total_errors as f64 / total_acquires as f64) * 100.0
104 } else {
105 0.0
106 };
107
108 let utilization = if total_connections > 0 {
109 (total_active as f64 / total_connections as f64) * 100.0
110 } else {
111 0.0
112 };
113
114 AggregatedStats {
115 pool_count: self.pools.len(),
116 total_connections,
117 total_active,
118 total_idle,
119 total_acquires,
120 total_errors,
121 error_rate,
122 utilization,
123 }
124 }
125}
126
127#[derive(Debug, Clone)]
129pub struct AggregatedStats {
130 pub pool_count: usize,
131 pub total_connections: u32,
132 pub total_active: u32,
133 pub total_idle: u32,
134 pub total_acquires: u64,
135 pub total_errors: u64,
136 pub error_rate: f64,
137 pub utilization: f64,
138}