scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
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
//! # Prometheus Metrics Export for SciRS2 v0.2.0
//!
//! This module provides Prometheus metrics collection and export capabilities.
//! It enables monitoring of SciRS2 applications with industry-standard tools.
//!
//! # Features
//!
//! - **Custom Metrics**: Counters, gauges, histograms, and summaries
//! - **Automatic Registration**: Automatic metrics registration with global registry
//! - **HTTP Export**: Expose metrics via HTTP endpoint
//! - **Performance Counters**: Track computation performance
//! - **Memory Metrics**: Monitor memory usage
//!
//! # Example
//!
//! ```rust,no_run
//! use scirs2_core::profiling::prometheus_metrics::{MetricsRegistry, register_counter};
//!
//! // Create a counter
//! let counter = register_counter(
//!     "scirs2_operations_total",
//!     "Total number of operations"
//! ).expect("Failed to register counter");
//!
//! // Increment the counter
//! counter.inc();
//!
//! // Export metrics
//! let metrics = MetricsRegistry::gather();
//! println!("{}", metrics);
//! ```

#[cfg(feature = "profiling_prometheus")]
use crate::CoreResult;
#[cfg(feature = "profiling_prometheus")]
use prometheus::{
    Counter, CounterVec, Encoder, Gauge, GaugeVec, Histogram, HistogramOpts, HistogramVec, Opts,
    Registry, TextEncoder,
};
#[cfg(feature = "profiling_prometheus")]
use std::sync::Arc;

/// Global metrics registry
#[cfg(feature = "profiling_prometheus")]
static REGISTRY: once_cell::sync::Lazy<Arc<Registry>> =
    once_cell::sync::Lazy::new(|| Arc::new(Registry::new()));

/// Metrics registry wrapper
#[cfg(feature = "profiling_prometheus")]
pub struct MetricsRegistry;

#[cfg(feature = "profiling_prometheus")]
impl MetricsRegistry {
    /// Get the global registry
    pub fn global() -> Arc<Registry> {
        REGISTRY.clone()
    }

    /// Gather all metrics in Prometheus text format
    pub fn gather() -> String {
        let encoder = TextEncoder::new();
        let metric_families = REGISTRY.gather();
        let mut buffer = Vec::new();

        encoder
            .encode(&metric_families, &mut buffer)
            .expect("Failed to encode metrics");

        String::from_utf8(buffer).expect("Failed to convert metrics to string")
    }

    /// Reset all metrics
    pub fn reset() {
        // Create a new registry (note: this doesn't actually reset, just for API compatibility)
        // In practice, individual metrics should be reset
    }
}

/// Register a counter metric
#[cfg(feature = "profiling_prometheus")]
pub fn register_counter(name: &str, help: &str) -> CoreResult<Counter> {
    let opts = Opts::new(name, help);
    let counter = Counter::with_opts(opts).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to create counter: {}",
            e
        )))
    })?;

    REGISTRY.register(Box::new(counter.clone())).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to register counter: {}",
            e
        )))
    })?;

    Ok(counter)
}

/// Register a counter vector metric
#[cfg(feature = "profiling_prometheus")]
pub fn register_counter_vec(
    name: &str,
    help: &str,
    label_names: &[&str],
) -> CoreResult<CounterVec> {
    let opts = Opts::new(name, help);
    let counter_vec = CounterVec::new(opts, label_names).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to create counter vec: {}",
            e
        )))
    })?;

    REGISTRY
        .register(Box::new(counter_vec.clone()))
        .map_err(|e| {
            crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
                "Failed to register counter vec: {}",
                e
            )))
        })?;

    Ok(counter_vec)
}

/// Register a gauge metric
#[cfg(feature = "profiling_prometheus")]
pub fn register_gauge(name: &str, help: &str) -> CoreResult<Gauge> {
    let opts = Opts::new(name, help);
    let gauge = Gauge::with_opts(opts).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to create gauge: {}",
            e
        )))
    })?;

    REGISTRY.register(Box::new(gauge.clone())).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to register gauge: {}",
            e
        )))
    })?;

    Ok(gauge)
}

/// Register a gauge vector metric
#[cfg(feature = "profiling_prometheus")]
pub fn register_gauge_vec(name: &str, help: &str, label_names: &[&str]) -> CoreResult<GaugeVec> {
    let opts = Opts::new(name, help);
    let gauge_vec = GaugeVec::new(opts, label_names).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to create gauge vec: {}",
            e
        )))
    })?;

    REGISTRY
        .register(Box::new(gauge_vec.clone()))
        .map_err(|e| {
            crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
                "Failed to register gauge vec: {}",
                e
            )))
        })?;

    Ok(gauge_vec)
}

/// Register a histogram metric
#[cfg(feature = "profiling_prometheus")]
pub fn register_histogram(name: &str, help: &str, buckets: Vec<f64>) -> CoreResult<Histogram> {
    let opts = HistogramOpts::new(name, help).buckets(buckets);
    let histogram = Histogram::with_opts(opts).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to create histogram: {}",
            e
        )))
    })?;

    REGISTRY
        .register(Box::new(histogram.clone()))
        .map_err(|e| {
            crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
                "Failed to register histogram: {}",
                e
            )))
        })?;

    Ok(histogram)
}

/// Register a histogram vector metric
#[cfg(feature = "profiling_prometheus")]
pub fn register_histogram_vec(
    name: &str,
    help: &str,
    label_names: &[&str],
    buckets: Vec<f64>,
) -> CoreResult<HistogramVec> {
    let opts = HistogramOpts::new(name, help).buckets(buckets);
    let histogram_vec = HistogramVec::new(opts, label_names).map_err(|e| {
        crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
            "Failed to create histogram vec: {}",
            e
        )))
    })?;

    REGISTRY
        .register(Box::new(histogram_vec.clone()))
        .map_err(|e| {
            crate::CoreError::ConfigError(crate::error::ErrorContext::new(format!(
                "Failed to register histogram vec: {}",
                e
            )))
        })?;

    Ok(histogram_vec)
}

/// Standard buckets for latency metrics (in seconds)
#[cfg(feature = "profiling_prometheus")]
pub fn latency_buckets() -> Vec<f64> {
    vec![
        0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
    ]
}

/// Standard buckets for size metrics (in bytes)
#[cfg(feature = "profiling_prometheus")]
pub fn size_buckets() -> Vec<f64> {
    vec![
        1024.0,
        10_240.0,
        102_400.0,
        1_048_576.0,
        10_485_760.0,
        104_857_600.0,
        1_073_741_824.0,
    ]
}

/// Pre-defined SciRS2 metrics
#[cfg(feature = "profiling_prometheus")]
pub struct SciRS2Metrics {
    /// Total number of operations
    pub operations_total: CounterVec,
    /// Operation duration histogram
    pub operation_duration: HistogramVec,
    /// Active operations gauge
    pub active_operations: GaugeVec,
    /// Memory usage gauge
    pub memory_usage_bytes: Gauge,
    /// Array size histogram
    pub array_size_bytes: Histogram,
    /// Error counter
    pub errors_total: CounterVec,
}

#[cfg(feature = "profiling_prometheus")]
impl SciRS2Metrics {
    /// Create and register standard SciRS2 metrics
    pub fn register() -> CoreResult<Self> {
        let operations_total = register_counter_vec(
            "scirs2_operations_total",
            "Total number of operations",
            &["operation", "module"],
        )?;

        let operation_duration = register_histogram_vec(
            "scirs2_operation_duration_seconds",
            "Duration of operations in seconds",
            &["operation", "module"],
            latency_buckets(),
        )?;

        let active_operations = register_gauge_vec(
            "scirs2_active_operations",
            "Number of active operations",
            &["operation", "module"],
        )?;

        let memory_usage_bytes =
            register_gauge("scirs2_memory_usage_bytes", "Current memory usage in bytes")?;

        let array_size_bytes = register_histogram(
            "scirs2_array_size_bytes",
            "Size of arrays in bytes",
            size_buckets(),
        )?;

        let errors_total = register_counter_vec(
            "scirs2_errors_total",
            "Total number of errors",
            &["error_type", "module"],
        )?;

        Ok(Self {
            operations_total,
            operation_duration,
            active_operations,
            memory_usage_bytes,
            array_size_bytes,
            errors_total,
        })
    }
}

/// Timer for measuring operation duration
#[cfg(feature = "profiling_prometheus")]
pub struct PrometheusTimer {
    histogram: Histogram,
    start: std::time::Instant,
}

#[cfg(feature = "profiling_prometheus")]
impl PrometheusTimer {
    /// Start a new timer
    pub fn start(histogram: Histogram) -> Self {
        Self {
            histogram,
            start: std::time::Instant::now(),
        }
    }

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

#[cfg(feature = "profiling_prometheus")]
impl Drop for PrometheusTimer {
    fn drop(&mut self) {
        let duration = self.start.elapsed();
        self.histogram.observe(duration.as_secs_f64());
    }
}

/// Macro for timing an operation with Prometheus
#[macro_export]
#[cfg(feature = "profiling_prometheus")]
macro_rules! prometheus_time {
    ($histogram:expr, $body:block) => {{
        let _timer = $crate::profiling::prometheus_metrics::PrometheusTimer::start($histogram);
        $body
    }};
}

/// Stub implementations when profiling_prometheus feature is disabled
#[cfg(not(feature = "profiling_prometheus"))]
pub struct MetricsRegistry;

#[cfg(not(feature = "profiling_prometheus"))]
impl MetricsRegistry {
    pub fn gather() -> String {
        String::new()
    }
}

#[cfg(test)]
#[cfg(feature = "profiling_prometheus")]
mod tests {
    use super::*;

    #[test]
    fn test_register_counter() {
        let counter = register_counter("test_counter", "Test counter");
        assert!(counter.is_ok());
    }

    #[test]
    fn test_register_gauge() {
        let gauge = register_gauge("test_gauge", "Test gauge");
        assert!(gauge.is_ok());
    }

    #[test]
    fn test_register_histogram() {
        let histogram = register_histogram("test_histogram", "Test histogram", latency_buckets());
        assert!(histogram.is_ok());
    }

    #[test]
    fn test_scirs2_metrics() {
        let metrics = SciRS2Metrics::register();
        assert!(metrics.is_ok());

        if let Ok(m) = metrics {
            m.operations_total
                .with_label_values(&["test", "core"])
                .inc();
            m.memory_usage_bytes.set(1024.0);
            m.array_size_bytes.observe(2048.0);
        }
    }

    #[test]
    fn test_prometheus_timer() {
        let histogram = register_histogram("test_timer", "Test timer", latency_buckets())
            .expect("Failed to register histogram");

        let timer = PrometheusTimer::start(histogram);
        std::thread::sleep(std::time::Duration::from_millis(10));
        timer.stop();
    }

    #[test]
    fn test_metrics_gather() {
        let _counter = register_counter("gather_test", "Test counter").expect("Failed to register");
        let metrics = MetricsRegistry::gather();
        assert!(!metrics.is_empty());
    }
}