kaccy-db 0.2.0

Database layer for Kaccy Protocol - PostgreSQL, Redis, and distributed 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
//! Prometheus metrics for database operations
//!
//! Provides metrics for:
//! - Connection pool (active connections, wait time, utilization)
//! - Cache operations (hit rate, miss rate, latency)
//! - Query performance (duration, error rate, slow queries)
//! - Repository operations (calls, errors, latency)

use lazy_static::lazy_static;
use prometheus::{
    Histogram, HistogramOpts, HistogramVec, IntCounterVec, IntGauge, IntGaugeVec, Opts, Registry,
    TextEncoder,
};
use std::time::Instant;

lazy_static! {
    /// Global Prometheus registry
    pub static ref REGISTRY: Registry = Registry::new();

    // ============================================================
    // Connection Pool Metrics
    // ============================================================

    /// Active database connections
    pub static ref POOL_CONNECTIONS_ACTIVE: IntGaugeVec = IntGaugeVec::new(
        Opts::new("kaccy_db_pool_connections_active", "Number of active database connections"),
        &["pool_name"]
    ).unwrap();

    /// Idle database connections
    pub static ref POOL_CONNECTIONS_IDLE: IntGaugeVec = IntGaugeVec::new(
        Opts::new("kaccy_db_pool_connections_idle", "Number of idle database connections"),
        &["pool_name"]
    ).unwrap();

    /// Total pool size
    pub static ref POOL_SIZE: IntGaugeVec = IntGaugeVec::new(
        Opts::new("kaccy_db_pool_size", "Total connection pool size"),
        &["pool_name"]
    ).unwrap();

    /// Connection acquisition attempts
    pub static ref POOL_ACQUIRE_TOTAL: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_pool_acquire_total", "Total connection acquisition attempts"),
        &["pool_name", "status"]
    ).unwrap();

    /// Connection acquisition duration
    pub static ref POOL_ACQUIRE_DURATION: HistogramVec = HistogramVec::new(
        HistogramOpts::new(
            "kaccy_db_pool_acquire_duration_seconds",
            "Connection acquisition duration in seconds"
        ).buckets(vec![0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0]),
        &["pool_name"]
    ).unwrap();

    /// Pool connection timeouts
    pub static ref POOL_TIMEOUT_TOTAL: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_pool_timeout_total", "Total connection acquisition timeouts"),
        &["pool_name"]
    ).unwrap();

    // ============================================================
    // Cache Metrics
    // ============================================================

    /// Cache hits
    pub static ref CACHE_HITS: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_cache_hits_total", "Total cache hits"),
        &["cache_type"]
    ).unwrap();

    /// Cache misses
    pub static ref CACHE_MISSES: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_cache_misses_total", "Total cache misses"),
        &["cache_type"]
    ).unwrap();

    /// Cache errors
    pub static ref CACHE_ERRORS: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_cache_errors_total", "Total cache errors"),
        &["cache_type", "operation"]
    ).unwrap();

    /// Cache operation duration
    pub static ref CACHE_OPERATION_DURATION: HistogramVec = HistogramVec::new(
        HistogramOpts::new(
            "kaccy_db_cache_operation_duration_seconds",
            "Cache operation duration in seconds"
        ).buckets(vec![0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1]),
        &["cache_type", "operation"]
    ).unwrap();

    /// Cache size (number of keys)
    pub static ref CACHE_SIZE: IntGaugeVec = IntGaugeVec::new(
        Opts::new("kaccy_db_cache_size", "Number of keys in cache"),
        &["cache_type"]
    ).unwrap();

    /// Cache evictions
    pub static ref CACHE_EVICTIONS: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_cache_evictions_total", "Total cache evictions"),
        &["cache_type"]
    ).unwrap();

    // ============================================================
    // Query Metrics
    // ============================================================

    /// Total queries executed
    pub static ref QUERY_TOTAL: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_query_total", "Total database queries executed"),
        &["query_type", "status"]
    ).unwrap();

    /// Query duration
    pub static ref QUERY_DURATION: HistogramVec = HistogramVec::new(
        HistogramOpts::new(
            "kaccy_db_query_duration_seconds",
            "Query execution duration in seconds"
        ).buckets(vec![0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0]),
        &["query_type"]
    ).unwrap();

    /// Slow queries (>1s)
    pub static ref QUERY_SLOW_TOTAL: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_query_slow_total", "Total slow queries (>1s)"),
        &["query_type"]
    ).unwrap();

    /// Query errors
    pub static ref QUERY_ERRORS: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_query_errors_total", "Total query errors"),
        &["query_type", "error_type"]
    ).unwrap();

    /// Active queries
    pub static ref QUERY_ACTIVE: IntGaugeVec = IntGaugeVec::new(
        Opts::new("kaccy_db_query_active", "Number of currently executing queries"),
        &["query_type"]
    ).unwrap();

    // ============================================================
    // Repository Metrics
    // ============================================================

    /// Repository operation calls
    pub static ref REPO_OPERATION_TOTAL: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_repo_operation_total", "Total repository operation calls"),
        &["repository", "operation", "status"]
    ).unwrap();

    /// Repository operation duration
    pub static ref REPO_OPERATION_DURATION: HistogramVec = HistogramVec::new(
        HistogramOpts::new(
            "kaccy_db_repo_operation_duration_seconds",
            "Repository operation duration in seconds"
        ).buckets(vec![0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0]),
        &["repository", "operation"]
    ).unwrap();

    // ============================================================
    // Transaction Metrics
    // ============================================================

    /// Transaction operations
    pub static ref TRANSACTION_TOTAL: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_transaction_total", "Total transaction operations"),
        &["operation", "status"]
    ).unwrap();

    /// Transaction duration
    pub static ref TRANSACTION_DURATION: HistogramVec = HistogramVec::new(
        HistogramOpts::new(
            "kaccy_db_transaction_duration_seconds",
            "Transaction duration in seconds"
        ).buckets(vec![0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 30.0]),
        &["operation"]
    ).unwrap();

    /// Active transactions
    pub static ref TRANSACTION_ACTIVE: IntGauge = IntGauge::new(
        "kaccy_db_transaction_active",
        "Number of active transactions"
    ).unwrap();

    // ============================================================
    // Replica Metrics
    // ============================================================

    /// Replica health status
    pub static ref REPLICA_HEALTH: IntGaugeVec = IntGaugeVec::new(
        Opts::new("kaccy_db_replica_health", "Replica health status (1=healthy, 0=unhealthy)"),
        &["replica_id"]
    ).unwrap();

    /// Replica lag in bytes
    pub static ref REPLICA_LAG_BYTES: IntGaugeVec = IntGaugeVec::new(
        Opts::new("kaccy_db_replica_lag_bytes", "Replica replication lag in bytes"),
        &["replica_id"]
    ).unwrap();

    /// Replica queries routed
    pub static ref REPLICA_QUERIES: IntCounterVec = IntCounterVec::new(
        Opts::new("kaccy_db_replica_queries_total", "Total queries routed to replica"),
        &["replica_id"]
    ).unwrap();
}

/// Register all metrics with the Prometheus registry
pub fn register_metrics() -> Result<(), prometheus::Error> {
    // Pool metrics
    REGISTRY.register(Box::new(POOL_CONNECTIONS_ACTIVE.clone()))?;
    REGISTRY.register(Box::new(POOL_CONNECTIONS_IDLE.clone()))?;
    REGISTRY.register(Box::new(POOL_SIZE.clone()))?;
    REGISTRY.register(Box::new(POOL_ACQUIRE_TOTAL.clone()))?;
    REGISTRY.register(Box::new(POOL_ACQUIRE_DURATION.clone()))?;
    REGISTRY.register(Box::new(POOL_TIMEOUT_TOTAL.clone()))?;

    // Cache metrics
    REGISTRY.register(Box::new(CACHE_HITS.clone()))?;
    REGISTRY.register(Box::new(CACHE_MISSES.clone()))?;
    REGISTRY.register(Box::new(CACHE_ERRORS.clone()))?;
    REGISTRY.register(Box::new(CACHE_OPERATION_DURATION.clone()))?;
    REGISTRY.register(Box::new(CACHE_SIZE.clone()))?;
    REGISTRY.register(Box::new(CACHE_EVICTIONS.clone()))?;

    // Query metrics
    REGISTRY.register(Box::new(QUERY_TOTAL.clone()))?;
    REGISTRY.register(Box::new(QUERY_DURATION.clone()))?;
    REGISTRY.register(Box::new(QUERY_SLOW_TOTAL.clone()))?;
    REGISTRY.register(Box::new(QUERY_ERRORS.clone()))?;
    REGISTRY.register(Box::new(QUERY_ACTIVE.clone()))?;

    // Repository metrics
    REGISTRY.register(Box::new(REPO_OPERATION_TOTAL.clone()))?;
    REGISTRY.register(Box::new(REPO_OPERATION_DURATION.clone()))?;

    // Transaction metrics
    REGISTRY.register(Box::new(TRANSACTION_TOTAL.clone()))?;
    REGISTRY.register(Box::new(TRANSACTION_DURATION.clone()))?;
    REGISTRY.register(Box::new(TRANSACTION_ACTIVE.clone()))?;

    // Replica metrics
    REGISTRY.register(Box::new(REPLICA_HEALTH.clone()))?;
    REGISTRY.register(Box::new(REPLICA_LAG_BYTES.clone()))?;
    REGISTRY.register(Box::new(REPLICA_QUERIES.clone()))?;

    Ok(())
}

/// Encode metrics in Prometheus text format
pub fn gather_metrics() -> Result<String, prometheus::Error> {
    let encoder = TextEncoder::new();
    let metric_families = REGISTRY.gather();
    encoder.encode_to_string(&metric_families)
}

/// Timer for measuring operation duration
pub struct MetricsTimer {
    start: Instant,
    histogram: Option<Histogram>,
}

impl MetricsTimer {
    /// Create a new timer
    pub fn new(histogram: Histogram) -> Self {
        Self {
            start: Instant::now(),
            histogram: Some(histogram),
        }
    }

    /// Create a timer without recording
    pub fn noop() -> Self {
        Self {
            start: Instant::now(),
            histogram: None,
        }
    }

    /// Stop the timer and record the duration
    pub fn observe(mut self) {
        if let Some(histogram) = self.histogram.take() {
            let duration = self.start.elapsed().as_secs_f64();
            histogram.observe(duration);
        }
    }

    /// Stop the timer and return the duration without recording
    pub fn elapsed(&self) -> std::time::Duration {
        self.start.elapsed()
    }
}

impl Drop for MetricsTimer {
    fn drop(&mut self) {
        if let Some(histogram) = self.histogram.take() {
            let duration = self.start.elapsed().as_secs_f64();
            histogram.observe(duration);
        }
    }
}

/// Helper to record pool statistics
pub fn record_pool_stats(pool_name: &str, size: u32, idle: u32) {
    POOL_SIZE.with_label_values(&[pool_name]).set(size as i64);
    POOL_CONNECTIONS_IDLE
        .with_label_values(&[pool_name])
        .set(idle as i64);
    POOL_CONNECTIONS_ACTIVE
        .with_label_values(&[pool_name])
        .set((size - idle) as i64);
}

/// Helper to record cache hit
pub fn record_cache_hit(cache_type: &str) {
    CACHE_HITS.with_label_values(&[cache_type]).inc();
}

/// Helper to record cache miss
pub fn record_cache_miss(cache_type: &str) {
    CACHE_MISSES.with_label_values(&[cache_type]).inc();
}

/// Helper to record cache error
pub fn record_cache_error(cache_type: &str, operation: &str) {
    CACHE_ERRORS
        .with_label_values(&[cache_type, operation])
        .inc();
}

/// Helper to calculate cache hit rate
pub fn cache_hit_rate(cache_type: &str) -> f64 {
    let hits = CACHE_HITS.with_label_values(&[cache_type]).get() as f64;
    let misses = CACHE_MISSES.with_label_values(&[cache_type]).get() as f64;
    let total = hits + misses;
    if total == 0.0 {
        0.0
    } else {
        hits / total
    }
}

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

    #[test]
    fn test_metrics_registration() {
        use prometheus::IntCounter;

        // Reset registry for testing
        let test_registry = Registry::new();

        // Test registering individual metrics
        let counter = IntCounter::new("test_counter", "Test counter").unwrap();
        assert!(test_registry.register(Box::new(counter)).is_ok());

        let gauge = IntGauge::new("test_gauge", "Test gauge").unwrap();
        assert!(test_registry.register(Box::new(gauge)).is_ok());
    }

    #[test]
    fn test_pool_stats_recording() {
        record_pool_stats("test_pool", 10, 5);

        assert_eq!(POOL_SIZE.with_label_values(&["test_pool"]).get(), 10);
        assert_eq!(
            POOL_CONNECTIONS_IDLE
                .with_label_values(&["test_pool"])
                .get(),
            5
        );
        assert_eq!(
            POOL_CONNECTIONS_ACTIVE
                .with_label_values(&["test_pool"])
                .get(),
            5
        );
    }

    #[test]
    fn test_cache_hit_rate() {
        let cache_type = "test_cache_hit_rate";

        // Initial hit rate should be 0
        assert_eq!(cache_hit_rate(cache_type), 0.0);

        // Record some hits and misses
        record_cache_hit(cache_type);
        record_cache_hit(cache_type);
        record_cache_hit(cache_type);
        record_cache_miss(cache_type);

        // Hit rate should be 3/4 = 0.75
        assert_eq!(cache_hit_rate(cache_type), 0.75);
    }

    #[test]
    fn test_cache_operations() {
        let cache_type = "test_cache_ops";

        // Record operations
        record_cache_hit(cache_type);
        record_cache_miss(cache_type);
        record_cache_error(cache_type, "get");

        // Verify counters
        assert_eq!(CACHE_HITS.with_label_values(&[cache_type]).get(), 1);
        assert_eq!(CACHE_MISSES.with_label_values(&[cache_type]).get(), 1);
        assert_eq!(
            CACHE_ERRORS.with_label_values(&[cache_type, "get"]).get(),
            1
        );
    }

    #[test]
    fn test_metrics_timer() {
        let histogram =
            Histogram::with_opts(HistogramOpts::new("test_timer", "Test timer")).unwrap();

        let timer = MetricsTimer::new(histogram.clone());
        std::thread::sleep(std::time::Duration::from_millis(10));
        timer.observe();

        // Histogram should have recorded a value
        assert!(histogram.get_sample_count() > 0);
    }

    #[test]
    fn test_metrics_timer_drop() {
        let histogram =
            Histogram::with_opts(HistogramOpts::new("test_timer_drop", "Test timer drop")).unwrap();

        {
            let _timer = MetricsTimer::new(histogram.clone());
            std::thread::sleep(std::time::Duration::from_millis(10));
            // Timer dropped here
        }

        // Histogram should have recorded a value on drop
        assert!(histogram.get_sample_count() > 0);
    }

    #[test]
    fn test_gather_metrics() {
        // This should not panic
        let result = gather_metrics();
        assert!(result.is_ok());
    }
}