kaccy-core 0.2.0

Core business logic for Kaccy Protocol - batching, fee optimization, and transaction management
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
//! Prometheus-compatible metrics collection
//!
//! Provides metrics collection and aggregation for monitoring and observability.
//! Supports counters, gauges, histograms, and summaries compatible with Prometheus.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

/// Metric types supported
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MetricType {
    /// Monotonically increasing value
    Counter,
    /// Value that can increase or decrease
    Gauge,
    /// Distribution of values in configurable buckets
    Histogram,
    /// Sliding-window percentile summary
    Summary,
}

/// Counter metric - monotonically increasing value
#[derive(Debug)]
pub struct Counter {
    /// Atomic counter value
    value: AtomicU64,
    /// Help text describing what this counter measures
    help: String,
    /// Label key-value pairs for this metric instance
    labels: HashMap<String, String>,
}

impl Counter {
    /// Create a new counter with the given help text
    pub fn new(help: impl Into<String>) -> Self {
        Self {
            value: AtomicU64::new(0),
            help: help.into(),
            labels: HashMap::new(),
        }
    }

    /// Attach label key-value pairs to this counter
    pub fn with_labels(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = labels;
        self
    }

    /// Increment counter by 1
    pub fn inc(&self) {
        self.value.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment counter by n
    pub fn add(&self, n: u64) {
        self.value.fetch_add(n, Ordering::Relaxed);
    }

    /// Get current value
    pub fn get(&self) -> u64 {
        self.value.load(Ordering::Relaxed)
    }

    /// Reset counter to zero
    pub fn reset(&self) {
        self.value.store(0, Ordering::Relaxed);
    }
}

/// Gauge metric - value that can go up or down
#[derive(Debug)]
pub struct Gauge {
    /// Current gauge value
    value: Arc<RwLock<f64>>,
    /// Help text describing what this gauge measures
    help: String,
    /// Label key-value pairs for this metric instance
    labels: HashMap<String, String>,
}

impl Gauge {
    /// Create a new gauge with the given help text
    pub fn new(help: impl Into<String>) -> Self {
        Self {
            value: Arc::new(RwLock::new(0.0)),
            help: help.into(),
            labels: HashMap::new(),
        }
    }

    /// Attach label key-value pairs to this gauge
    pub fn with_labels(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = labels;
        self
    }

    /// Set gauge to specific value
    pub fn set(&self, val: f64) {
        *self.value.write().unwrap() = val;
    }

    /// Increment gauge
    pub fn inc(&self) {
        *self.value.write().unwrap() += 1.0;
    }

    /// Decrement gauge
    pub fn dec(&self) {
        *self.value.write().unwrap() -= 1.0;
    }

    /// Add to gauge
    pub fn add(&self, val: f64) {
        *self.value.write().unwrap() += val;
    }

    /// Subtract from gauge
    pub fn sub(&self, val: f64) {
        *self.value.write().unwrap() -= val;
    }

    /// Get current value
    pub fn get(&self) -> f64 {
        *self.value.read().unwrap()
    }
}

/// Histogram - tracks distribution of values with configurable buckets
#[derive(Debug)]
pub struct Histogram {
    /// Upper bounds of each histogram bucket
    buckets: Vec<f64>,
    /// Number of observations in each bucket
    counts: Vec<AtomicU64>,
    /// Sum of all observed values
    sum: Arc<RwLock<f64>>,
    /// Total number of observations
    count: AtomicU64,
    /// Help text describing what this histogram measures
    help: String,
    /// Label key-value pairs for this metric instance
    labels: HashMap<String, String>,
}

impl Histogram {
    /// Create histogram with default buckets
    pub fn new(help: impl Into<String>) -> Self {
        Self::with_buckets(
            help,
            vec![
                0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
            ],
        )
    }

    /// Create histogram with custom buckets
    pub fn with_buckets(help: impl Into<String>, buckets: Vec<f64>) -> Self {
        let counts = buckets.iter().map(|_| AtomicU64::new(0)).collect();

        Self {
            buckets,
            counts,
            sum: Arc::new(RwLock::new(0.0)),
            count: AtomicU64::new(0),
            help: help.into(),
            labels: HashMap::new(),
        }
    }

    /// Attach label key-value pairs to this histogram
    pub fn with_labels(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = labels;
        self
    }

    /// Observe a value
    pub fn observe(&self, val: f64) {
        // Update sum and count
        *self.sum.write().unwrap() += val;
        self.count.fetch_add(1, Ordering::Relaxed);

        // Update bucket counts
        for (i, &bucket) in self.buckets.iter().enumerate() {
            if val <= bucket {
                self.counts[i].fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    /// Get histogram statistics
    pub fn stats(&self) -> HistogramStats {
        let sum = *self.sum.read().unwrap();
        let count = self.count.load(Ordering::Relaxed);

        let buckets: Vec<_> = self
            .buckets
            .iter()
            .zip(self.counts.iter())
            .map(|(&le, count)| BucketCount {
                le,
                count: count.load(Ordering::Relaxed),
            })
            .collect();

        HistogramStats {
            sum,
            count,
            buckets,
        }
    }
}

/// Snapshot of histogram statistics
#[derive(Debug, Clone, Serialize)]
pub struct HistogramStats {
    /// Sum of all observed values
    pub sum: f64,
    /// Total number of observations
    pub count: u64,
    /// Per-bucket observation counts
    pub buckets: Vec<BucketCount>,
}

/// Count of observations up to an inclusive bucket boundary
#[derive(Debug, Clone, Serialize)]
pub struct BucketCount {
    /// Bucket upper bound (less than or equal to)
    pub le: f64,
    /// Cumulative count of observations in this bucket
    pub count: u64,
}

/// Summary - tracks percentiles of observed values
#[derive(Debug)]
pub struct Summary {
    /// Sliding window of recent observed values
    observations: Arc<RwLock<Vec<f64>>>,
    /// Maximum age of observations before cleanup
    max_age: Duration,
    /// Maximum number of observations to retain
    max_observations: usize,
    /// Help text describing what this summary measures
    help: String,
    /// Label key-value pairs for this metric instance
    labels: HashMap<String, String>,
    /// Timestamp of the last cleanup pass
    last_cleanup: Arc<RwLock<Instant>>,
}

impl Summary {
    /// Create a new summary with the given help text
    pub fn new(help: impl Into<String>) -> Self {
        Self {
            observations: Arc::new(RwLock::new(Vec::new())),
            max_age: Duration::from_secs(600), // 10 minutes
            max_observations: 1000,
            help: help.into(),
            labels: HashMap::new(),
            last_cleanup: Arc::new(RwLock::new(Instant::now())),
        }
    }

    /// Attach label key-value pairs to this summary
    pub fn with_labels(mut self, labels: HashMap<String, String>) -> Self {
        self.labels = labels;
        self
    }

    /// Observe a value
    pub fn observe(&self, val: f64) {
        let mut obs = self.observations.write().unwrap();

        // Add observation
        obs.push(val);

        // Limit number of observations
        if obs.len() > self.max_observations {
            obs.remove(0);
        }

        drop(obs);
        self.cleanup_if_needed();
    }

    /// Get percentile value
    pub fn percentile(&self, p: f64) -> Option<f64> {
        let mut obs = self.observations.read().unwrap().clone();

        if obs.is_empty() {
            return None;
        }

        obs.sort_by(|a, b| a.partial_cmp(b).unwrap());

        let index = ((p / 100.0) * obs.len() as f64) as usize;
        let index = index.min(obs.len() - 1);

        Some(obs[index])
    }

    /// Get summary statistics
    pub fn stats(&self) -> SummaryStats {
        let obs = self.observations.read().unwrap();

        let count = obs.len() as u64;
        let sum: f64 = obs.iter().sum();

        drop(obs);

        SummaryStats {
            count,
            sum,
            p50: self.percentile(50.0).unwrap_or(0.0),
            p90: self.percentile(90.0).unwrap_or(0.0),
            p99: self.percentile(99.0).unwrap_or(0.0),
        }
    }

    fn cleanup_if_needed(&self) {
        let last = *self.last_cleanup.read().unwrap();

        if last.elapsed() > self.max_age {
            self.observations.write().unwrap().clear();
            *self.last_cleanup.write().unwrap() = Instant::now();
        }
    }
}

/// Snapshot of summary statistics
#[derive(Debug, Clone, Serialize)]
pub struct SummaryStats {
    /// Total number of observations in the window
    pub count: u64,
    /// Sum of all observations in the window
    pub sum: f64,
    /// 50th percentile (median)
    pub p50: f64,
    /// 90th percentile
    pub p90: f64,
    /// 99th percentile
    pub p99: f64,
}

/// Metrics registry
#[derive(Debug, Default)]
pub struct MetricsRegistry {
    /// Registered counters by name
    counters: Arc<RwLock<HashMap<String, Arc<Counter>>>>,
    /// Registered gauges by name
    gauges: Arc<RwLock<HashMap<String, Arc<Gauge>>>>,
    /// Registered histograms by name
    histograms: Arc<RwLock<HashMap<String, Arc<Histogram>>>>,
    /// Registered summaries by name
    summaries: Arc<RwLock<HashMap<String, Arc<Summary>>>>,
}

impl MetricsRegistry {
    /// Create a new empty metrics registry
    pub fn new() -> Self {
        Self::default()
    }

    /// Register or get counter
    pub fn counter(&self, name: &str, help: &str) -> Arc<Counter> {
        let mut counters = self.counters.write().unwrap();
        counters
            .entry(name.to_string())
            .or_insert_with(|| Arc::new(Counter::new(help)))
            .clone()
    }

    /// Register or get gauge
    pub fn gauge(&self, name: &str, help: &str) -> Arc<Gauge> {
        let mut gauges = self.gauges.write().unwrap();
        gauges
            .entry(name.to_string())
            .or_insert_with(|| Arc::new(Gauge::new(help)))
            .clone()
    }

    /// Register or get histogram
    pub fn histogram(&self, name: &str, help: &str) -> Arc<Histogram> {
        let mut histograms = self.histograms.write().unwrap();
        histograms
            .entry(name.to_string())
            .or_insert_with(|| Arc::new(Histogram::new(help)))
            .clone()
    }

    /// Register or get summary
    pub fn summary(&self, name: &str, help: &str) -> Arc<Summary> {
        let mut summaries = self.summaries.write().unwrap();
        summaries
            .entry(name.to_string())
            .or_insert_with(|| Arc::new(Summary::new(help)))
            .clone()
    }

    /// Export metrics in Prometheus text format
    pub fn export_prometheus(&self) -> String {
        let mut output = String::new();

        // Export counters
        for (name, counter) in self.counters.read().unwrap().iter() {
            output.push_str(&format!("# HELP {} {}\n", name, counter.help));
            output.push_str(&format!("# TYPE {} counter\n", name));
            output.push_str(&format!("{} {}\n", name, counter.get()));
        }

        // Export gauges
        for (name, gauge) in self.gauges.read().unwrap().iter() {
            output.push_str(&format!("# HELP {} {}\n", name, gauge.help));
            output.push_str(&format!("# TYPE {} gauge\n", name));
            output.push_str(&format!("{} {}\n", name, gauge.get()));
        }

        // Export histograms
        for (name, histogram) in self.histograms.read().unwrap().iter() {
            output.push_str(&format!("# HELP {} {}\n", name, histogram.help));
            output.push_str(&format!("# TYPE {} histogram\n", name));

            let stats = histogram.stats();
            for bucket in stats.buckets {
                output.push_str(&format!(
                    "{}_bucket{{le=\"{}\"}} {}\n",
                    name, bucket.le, bucket.count
                ));
            }
            output.push_str(&format!("{}_sum {}\n", name, stats.sum));
            output.push_str(&format!("{}_count {}\n", name, stats.count));
        }

        // Export summaries
        for (name, summary) in self.summaries.read().unwrap().iter() {
            output.push_str(&format!("# HELP {} {}\n", name, summary.help));
            output.push_str(&format!("# TYPE {} summary\n", name));

            let stats = summary.stats();
            output.push_str(&format!("{}{{quantile=\"0.5\"}} {}\n", name, stats.p50));
            output.push_str(&format!("{}{{quantile=\"0.9\"}} {}\n", name, stats.p90));
            output.push_str(&format!("{}{{quantile=\"0.99\"}} {}\n", name, stats.p99));
            output.push_str(&format!("{}_sum {}\n", name, stats.sum));
            output.push_str(&format!("{}_count {}\n", name, stats.count));
        }

        output
    }

    /// Get all metrics as JSON
    pub fn export_json(&self) -> serde_json::Value {
        serde_json::json!({
            "counters": self.counters.read().unwrap().iter()
                .map(|(k, v)| (k.clone(), v.get()))
                .collect::<HashMap<_, _>>(),
            "gauges": self.gauges.read().unwrap().iter()
                .map(|(k, v)| (k.clone(), v.get()))
                .collect::<HashMap<_, _>>(),
            "histograms": self.histograms.read().unwrap().iter()
                .map(|(k, v)| (k.clone(), v.stats()))
                .collect::<HashMap<_, _>>(),
            "summaries": self.summaries.read().unwrap().iter()
                .map(|(k, v)| (k.clone(), v.stats()))
                .collect::<HashMap<_, _>>(),
        })
    }
}

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

    #[test]
    fn test_counter_basic() {
        let counter = Counter::new("test counter");

        assert_eq!(counter.get(), 0);

        counter.inc();
        assert_eq!(counter.get(), 1);

        counter.add(10);
        assert_eq!(counter.get(), 11);

        counter.reset();
        assert_eq!(counter.get(), 0);
    }

    #[test]
    fn test_gauge_basic() {
        let gauge = Gauge::new("test gauge");

        gauge.set(10.0);
        assert_eq!(gauge.get(), 10.0);

        gauge.inc();
        assert_eq!(gauge.get(), 11.0);

        gauge.dec();
        assert_eq!(gauge.get(), 10.0);

        gauge.add(5.5);
        assert_eq!(gauge.get(), 15.5);

        gauge.sub(2.5);
        assert_eq!(gauge.get(), 13.0);
    }

    #[test]
    fn test_histogram_basic() {
        let histogram = Histogram::new("test histogram");

        histogram.observe(0.1);
        histogram.observe(0.5);
        histogram.observe(1.5);
        histogram.observe(5.5);

        let stats = histogram.stats();
        assert_eq!(stats.count, 4);
        assert!((stats.sum - 7.6).abs() < 0.01);
    }

    #[test]
    fn test_histogram_buckets() {
        let histogram = Histogram::with_buckets("test", vec![1.0, 5.0, 10.0]);

        histogram.observe(0.5);
        histogram.observe(3.0);
        histogram.observe(7.0);
        histogram.observe(15.0);

        let stats = histogram.stats();

        // 0.5 <= 1.0
        assert_eq!(stats.buckets[0].count, 1);
        // 0.5, 3.0 <= 5.0
        assert_eq!(stats.buckets[1].count, 2);
        // 0.5, 3.0, 7.0 <= 10.0
        assert_eq!(stats.buckets[2].count, 3);
    }

    #[test]
    fn test_summary_basic() {
        let summary = Summary::new("test summary");

        for i in 1..=100 {
            summary.observe(i as f64);
        }

        let stats = summary.stats();
        assert_eq!(stats.count, 100);

        // Median should be around 50
        assert!((stats.p50 - 50.0).abs() < 5.0);
        // P90 should be around 90
        assert!((stats.p90 - 90.0).abs() < 5.0);
        // P99 should be around 99
        assert!((stats.p99 - 99.0).abs() < 5.0);
    }

    #[test]
    fn test_registry() {
        let registry = MetricsRegistry::new();

        let counter = registry.counter("requests_total", "Total requests");
        counter.inc();
        counter.inc();

        let gauge = registry.gauge("active_connections", "Active connections");
        gauge.set(42.0);

        // Get same counter again
        let counter2 = registry.counter("requests_total", "Total requests");
        assert_eq!(counter.get(), counter2.get());
        assert_eq!(counter2.get(), 2);
    }

    #[test]
    fn test_prometheus_export() {
        let registry = MetricsRegistry::new();

        let counter = registry.counter("http_requests_total", "Total HTTP requests");
        counter.add(100);

        let gauge = registry.gauge("memory_usage_bytes", "Memory usage");
        gauge.set(1024.0);

        let output = registry.export_prometheus();

        assert!(output.contains("http_requests_total 100"));
        assert!(output.contains("memory_usage_bytes 1024"));
        assert!(output.contains("# TYPE http_requests_total counter"));
        assert!(output.contains("# TYPE memory_usage_bytes gauge"));
    }

    #[test]
    fn test_json_export() {
        let registry = MetricsRegistry::new();

        let counter = registry.counter("test_counter", "Test");
        counter.add(42);

        let json = registry.export_json();

        assert_eq!(json["counters"]["test_counter"], 42);
    }
}