gouqi 0.20.0

Rust interface for Jira
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
//! Comprehensive observability infrastructure
//!
//! This module provides a unified observability system that combines metrics collection,
//! caching performance monitoring, request tracing, and health monitoring into a single
//! coherent system for production deployment.

#[cfg(any(feature = "metrics", feature = "cache"))]
use std::sync::Arc;
#[cfg(feature = "metrics")]
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tracing::info;

#[cfg(feature = "cache")]
use crate::cache::{Cache, CacheStats};
#[cfg(feature = "metrics")]
use crate::metrics::{METRICS, MetricsCollector, MetricsSnapshot};

/// Central observability coordinator
pub struct ObservabilitySystem {
    #[cfg(feature = "metrics")]
    metrics: &'static dyn MetricsCollector,
    #[cfg(feature = "cache")]
    cache: Option<Arc<dyn Cache>>,
    health_checker: HealthChecker,
}

impl std::fmt::Debug for ObservabilitySystem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ObservabilitySystem")
            .field("metrics_enabled", &cfg!(feature = "metrics"))
            .field("cache_enabled", &cfg!(feature = "cache"))
            .field("health_checker", &self.health_checker)
            .finish()
    }
}

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

impl ObservabilitySystem {
    /// Create a new observability system
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "metrics")]
            metrics: &*METRICS,
            #[cfg(feature = "cache")]
            cache: None,
            health_checker: HealthChecker::new(),
        }
    }

    /// Create observability system with cache monitoring
    #[cfg(feature = "cache")]
    pub fn with_cache(cache: Arc<dyn Cache>) -> Self {
        Self {
            #[cfg(feature = "metrics")]
            metrics: &*METRICS,
            cache: Some(cache),
            health_checker: HealthChecker::new(),
        }
    }

    /// Get comprehensive system health status
    pub fn health_status(&self) -> HealthStatus {
        let mut health = HealthStatus {
            status: "healthy".to_string(),
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            metrics: self.get_metrics_health(),
            cache: self.get_cache_health(),
            memory_usage: self.get_memory_usage(),
            uptime: self.health_checker.uptime(),
            request_count: 0,
        };

        #[cfg(feature = "metrics")]
        {
            let snapshot = self.metrics.get_snapshot();
            health.request_count = snapshot.request_count;

            // Mark unhealthy if error rate is too high
            if snapshot.success_rate < 90.0 && snapshot.request_count > 100 {
                health.status = "degraded".to_string();
            }

            if snapshot.success_rate < 50.0 && snapshot.request_count > 50 {
                health.status = "unhealthy".to_string();
            }
        }

        health
    }

    /// Get detailed observability report
    pub fn get_observability_report(&self) -> ObservabilityReport {
        ObservabilityReport {
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            health: self.health_status(),
            #[cfg(feature = "metrics")]
            metrics: Some(self.metrics.get_snapshot()),
            #[cfg(not(feature = "metrics"))]
            metrics: None,
            #[cfg(feature = "cache")]
            cache_stats: self.cache.as_ref().map(|c| c.stats()),
            #[cfg(not(feature = "cache"))]
            cache_stats: None,
            system_info: SystemInfo::collect(),
        }
    }

    /// Record a request for observability tracking
    #[cfg(feature = "metrics")]
    pub fn record_request(&self, method: &str, endpoint: &str, duration: Duration, success: bool) {
        self.metrics
            .record_request(method, endpoint, duration, success);

        if !success {
            self.health_checker.record_error();
        } else {
            self.health_checker.record_success();
        }
    }

    /// Cleanup expired data and optimize performance
    pub fn cleanup(&self) {
        #[cfg(feature = "cache")]
        if let Some(cache) = &self.cache {
            cache.cleanup_expired();
        }

        info!("Observability system cleanup completed");
    }

    /// Reset all metrics and counters
    pub fn reset(&self) {
        #[cfg(feature = "metrics")]
        self.metrics.reset();

        self.health_checker.reset();

        info!("Observability system reset");
    }

    fn get_metrics_health(&self) -> MetricsHealth {
        #[cfg(feature = "metrics")]
        {
            let snapshot = self.metrics.get_snapshot();
            MetricsHealth {
                enabled: true,
                total_requests: snapshot.request_count,
                error_rate: if snapshot.request_count > 0 {
                    (snapshot.error_count as f64 / snapshot.request_count as f64) * 100.0
                } else {
                    0.0
                },
                avg_response_time: snapshot.avg_duration_ms,
            }
        }

        #[cfg(not(feature = "metrics"))]
        MetricsHealth {
            enabled: false,
            total_requests: 0,
            error_rate: 0.0,
            avg_response_time: 0,
        }
    }

    fn get_cache_health(&self) -> CacheHealth {
        #[cfg(feature = "cache")]
        if let Some(cache) = &self.cache {
            let stats = cache.stats();
            return CacheHealth {
                enabled: true,
                total_entries: stats.total_entries,
                active_entries: stats.active_entries,
                hit_rate: if (stats.total_entries) > 0 {
                    (stats.active_entries as f64 / stats.total_entries as f64) * 100.0
                } else {
                    0.0
                },
                memory_usage: stats.total_size_bytes,
            };
        }

        CacheHealth {
            enabled: false,
            total_entries: 0,
            active_entries: 0,
            hit_rate: 0.0,
            memory_usage: 0,
        }
    }

    fn get_memory_usage(&self) -> MemoryUsage {
        // Basic memory usage estimation
        // In a real implementation, you'd use system APIs to get actual memory usage
        MemoryUsage {
            total_mb: 0,     // Would be filled by system info
            used_mb: 0,      // Would be filled by system info
            available_mb: 0, // Would be filled by system info
        }
    }
}

/// Health monitoring component
#[derive(Debug)]
struct HealthChecker {
    start_time: std::time::Instant,
    error_count: std::sync::atomic::AtomicU64,
    success_count: std::sync::atomic::AtomicU64,
}

impl HealthChecker {
    fn new() -> Self {
        Self {
            start_time: std::time::Instant::now(),
            error_count: std::sync::atomic::AtomicU64::new(0),
            success_count: std::sync::atomic::AtomicU64::new(0),
        }
    }

    fn uptime(&self) -> u64 {
        self.start_time.elapsed().as_secs()
    }

    fn record_error(&self) {
        self.error_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    fn record_success(&self) {
        self.success_count
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    fn reset(&self) {
        self.error_count
            .store(0, std::sync::atomic::Ordering::Relaxed);
        self.success_count
            .store(0, std::sync::atomic::Ordering::Relaxed);
    }
}

/// Comprehensive health status
#[derive(Debug, Serialize, Deserialize)]
pub struct HealthStatus {
    pub status: String,
    pub timestamp: u64,
    pub metrics: MetricsHealth,
    pub cache: CacheHealth,
    pub memory_usage: MemoryUsage,
    pub uptime: u64,
    pub request_count: u64,
}

/// Metrics health information
#[derive(Debug, Serialize, Deserialize)]
pub struct MetricsHealth {
    pub enabled: bool,
    pub total_requests: u64,
    pub error_rate: f64,
    pub avg_response_time: u64,
}

/// Cache health information
#[derive(Debug, Serialize, Deserialize)]
pub struct CacheHealth {
    pub enabled: bool,
    pub total_entries: usize,
    pub active_entries: usize,
    pub hit_rate: f64,
    pub memory_usage: usize,
}

/// Memory usage information
#[derive(Debug, Serialize, Deserialize)]
pub struct MemoryUsage {
    pub total_mb: u64,
    pub used_mb: u64,
    pub available_mb: u64,
}

/// Complete observability report
#[derive(Debug, Serialize, Deserialize)]
pub struct ObservabilityReport {
    pub timestamp: u64,
    pub health: HealthStatus,
    #[cfg(feature = "metrics")]
    pub metrics: Option<MetricsSnapshot>,
    #[cfg(not(feature = "metrics"))]
    pub metrics: Option<()>,
    #[cfg(feature = "cache")]
    pub cache_stats: Option<CacheStats>,
    #[cfg(not(feature = "cache"))]
    pub cache_stats: Option<()>,
    pub system_info: SystemInfo,
}

/// System information
#[derive(Debug, Serialize, Deserialize)]
pub struct SystemInfo {
    pub os: String,
    pub architecture: String,
    pub rust_version: String,
    pub library_version: String,
}

impl SystemInfo {
    fn collect() -> Self {
        Self {
            os: std::env::consts::OS.to_string(),
            architecture: std::env::consts::ARCH.to_string(),
            rust_version: std::env::var("RUSTC_VERSION").unwrap_or_else(|_| "unknown".to_string()),
            library_version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }
}

/// Observability configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObservabilityConfig {
    /// Enable comprehensive logging
    pub enable_tracing: bool,
    /// Enable metrics collection
    pub enable_metrics: bool,
    /// Enable response caching
    pub enable_caching: bool,
    /// Health check interval in seconds
    pub health_check_interval: u64,
    /// Maximum error rate before marking unhealthy
    pub max_error_rate: f64,
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self {
            enable_tracing: true,
            enable_metrics: cfg!(feature = "metrics"),
            enable_caching: cfg!(feature = "cache"),
            health_check_interval: 30,
            max_error_rate: 10.0,
        }
    }
}

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

    #[test]
    fn test_observability_system_creation() {
        let obs = ObservabilitySystem::new();
        let health = obs.health_status();
        assert_eq!(health.status, "healthy");
        assert!(health.uptime < u64::MAX);
    }

    #[test]
    fn test_health_status_serialization() {
        let obs = ObservabilitySystem::new();
        let health = obs.health_status();

        let json = serde_json::to_string(&health).unwrap();
        let deserialized: HealthStatus = serde_json::from_str(&json).unwrap();

        assert_eq!(health.status, deserialized.status);
    }

    #[test]
    fn test_observability_report() {
        let obs = ObservabilitySystem::new();
        let report = obs.get_observability_report();

        assert!(report.timestamp > 0);
        assert_eq!(report.health.status, "healthy");
        assert_eq!(
            report.system_info.library_version,
            env!("CARGO_PKG_VERSION")
        );
    }

    #[test]
    fn test_system_info() {
        let info = SystemInfo::collect();
        assert!(!info.os.is_empty());
        assert!(!info.architecture.is_empty());
        assert!(!info.library_version.is_empty());
    }

    #[test]
    fn test_observability_config_defaults() {
        let config = ObservabilityConfig::default();
        assert!(config.enable_tracing);
        assert_eq!(config.health_check_interval, 30);
        assert_eq!(config.max_error_rate, 10.0);
    }
}