things3-core 1.3.0

Core library for Things 3 database access and data models
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! Observability module for structured logging and metrics collection
//!
//! This module provides comprehensive observability features including:
//! - Structured logging with tracing
//! - Metrics collection for performance monitoring
//! - Health check endpoints
//! - Log aggregation and filtering

use std::collections::HashMap;
// Removed unused import
use std::time::{Duration, Instant};

// Simplified metrics - in a real application, this would use proper metrics types
// Simplified OpenTelemetry - in a real application, this would use proper OpenTelemetry
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, error, info, instrument, warn, Level};
use tracing_subscriber::{
    fmt::{self, format::FmtSpan},
    layer::SubscriberExt,
    util::SubscriberInitExt,
    EnvFilter,
};

/// Error types for observability operations
#[derive(Error, Debug)]
pub enum ObservabilityError {
    #[error("Failed to initialize tracing: {0}")]
    TracingInit(String),

    #[error("Failed to initialize metrics: {0}")]
    MetricsInit(String),

    #[error("Failed to initialize OpenTelemetry: {0}")]
    OpenTelemetryInit(String),

    #[error("Health check failed: {0}")]
    HealthCheckFailed(String),
}

/// Result type for observability operations
pub type Result<T> = std::result::Result<T, ObservabilityError>;

/// Configuration for observability features
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObservabilityConfig {
    /// Log level (trace, debug, info, warn, error)
    pub log_level: String,

    /// Enable JSON logging format
    pub json_logs: bool,

    /// Enable OpenTelemetry tracing
    pub enable_tracing: bool,

    /// Jaeger endpoint for tracing
    pub jaeger_endpoint: Option<String>,

    /// OTLP endpoint for tracing
    pub otlp_endpoint: Option<String>,

    /// Enable metrics collection
    pub enable_metrics: bool,

    /// Prometheus metrics port
    pub metrics_port: u16,

    /// Health check port
    pub health_port: u16,

    /// Service name for tracing
    pub service_name: String,

    /// Service version
    pub service_version: String,
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self {
            log_level: "info".to_string(),
            json_logs: false,
            enable_tracing: true,
            jaeger_endpoint: None,
            otlp_endpoint: None,
            enable_metrics: true,
            metrics_port: 9090,
            health_port: 8080,
            service_name: "things3-cli".to_string(),
            service_version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }
}

/// Metrics collector for Things 3 operations
#[derive(Debug, Clone)]
pub struct ThingsMetrics {
    // Database operation metrics
    pub db_operations_total: u64,
    pub db_operation_duration: f64,
    pub db_connection_pool_size: u64,
    pub db_connection_pool_active: u64,

    // Task operation metrics
    pub tasks_created_total: u64,
    pub tasks_updated_total: u64,
    pub tasks_deleted_total: u64,
    pub tasks_completed_total: u64,

    // Search operation metrics
    pub search_operations_total: u64,
    pub search_duration: f64,
    pub search_results_count: u64,

    // Export operation metrics
    pub export_operations_total: u64,
    pub export_duration: f64,
    pub export_file_size: u64,

    // Error metrics
    pub errors_total: u64,
    pub error_rate: f64,

    // Performance metrics
    pub memory_usage: u64,
    pub cpu_usage: f64,
    pub cache_hit_rate: f64,
    pub cache_size: u64,
}

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

impl ThingsMetrics {
    /// Create new metrics instance
    #[must_use]
    pub fn new() -> Self {
        Self {
            db_operations_total: 0,
            db_operation_duration: 0.0,
            db_connection_pool_size: 0,
            db_connection_pool_active: 0,

            tasks_created_total: 0,
            tasks_updated_total: 0,
            tasks_deleted_total: 0,
            tasks_completed_total: 0,

            search_operations_total: 0,
            search_duration: 0.0,
            search_results_count: 0,

            export_operations_total: 0,
            export_duration: 0.0,
            export_file_size: 0,

            errors_total: 0,
            error_rate: 0.0,

            memory_usage: 0,
            cpu_usage: 0.0,
            cache_hit_rate: 0.0,
            cache_size: 0,
        }
    }
}

/// Health check status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
    pub status: String,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub version: String,
    pub uptime: Duration,
    pub checks: HashMap<String, CheckResult>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckResult {
    pub status: String,
    pub message: Option<String>,
    pub duration_ms: u64,
}

/// Observability manager
#[derive(Debug)]
pub struct ObservabilityManager {
    config: ObservabilityConfig,
    #[allow(dead_code)]
    metrics: ThingsMetrics,
    // Simplified tracer - in a real application, this would use proper OpenTelemetry
    start_time: Instant,
}

impl ObservabilityManager {
    /// Create a new observability manager
    ///
    /// # Errors
    /// Returns an error if the observability manager cannot be created
    pub fn new(config: ObservabilityConfig) -> Result<Self> {
        let metrics = ThingsMetrics::new();
        let start_time = Instant::now();

        Ok(Self {
            config,
            metrics,
            start_time,
        })
    }

    /// Initialize observability features
    ///
    /// # Errors
    /// Returns an error if observability features cannot be initialized
    #[instrument(skip(self))]
    pub fn initialize(&mut self) -> Result<()> {
        // Only log initialization messages if tracing is enabled
        if self.config.enable_tracing {
            info!("Initializing observability features");
        }

        // Initialize tracing
        self.init_tracing()?;

        // Initialize metrics
        Self::init_metrics();

        // Initialize OpenTelemetry if enabled
        if self.config.enable_tracing {
            Self::init_opentelemetry();
        }

        // Only log success message if tracing is enabled
        if self.config.enable_tracing {
            info!("Observability features initialized successfully");
        }
        Ok(())
    }

    /// Initialize structured logging
    fn init_tracing(&self) -> Result<()> {
        let _log_level = self
            .config
            .log_level
            .parse::<Level>()
            .map_err(|e| ObservabilityError::TracingInit(format!("Invalid log level: {e}")))?;

        let filter = EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| EnvFilter::new(&self.config.log_level));

        let registry = tracing_subscriber::registry().with(filter);

        if self.config.json_logs {
            let json_layer = fmt::layer()
                .json()
                .with_current_span(true)
                .with_span_list(true)
                .with_target(true)
                .with_thread_ids(true)
                .with_thread_names(true)
                .with_file(true)
                .with_line_number(true);

            registry.with(json_layer).init();
        } else {
            let fmt_layer = fmt::layer()
                .with_target(true)
                .with_thread_ids(true)
                .with_thread_names(true)
                .with_file(true)
                .with_line_number(true)
                .with_span_events(FmtSpan::CLOSE);

            registry.with(fmt_layer).init();
        }

        // Only log initialization message if tracing is enabled
        if self.config.enable_tracing {
            info!("Tracing initialized with level: {}", self.config.log_level);
        }
        Ok(())
    }

    /// Initialize metrics collection
    fn init_metrics() {
        // For now, use a simple metrics implementation
        // In a real implementation, this would set up a proper metrics recorder
        // Note: This is a static method, so we can't check enable_tracing here
        // But metrics initialization messages are typically not critical
        // If needed, this could be made an instance method
    }

    /// Initialize OpenTelemetry tracing
    fn init_opentelemetry() {
        // Simplified OpenTelemetry implementation
        // In a real implementation, this would set up proper tracing
        // Note: This method is only called when enable_tracing is true,
        // so logging here would be safe, but we skip it to be extra cautious
    }

    /// Get health status
    #[must_use]
    pub fn health_status(&self) -> HealthStatus {
        let mut checks = HashMap::new();

        // Database health check
        checks.insert(
            "database".to_string(),
            CheckResult {
                status: "healthy".to_string(),
                message: Some("Database connection is healthy".to_string()),
                duration_ms: 0, // TODO: Implement actual health check
            },
        );

        // Memory health check
        checks.insert(
            "memory".to_string(),
            CheckResult {
                status: "healthy".to_string(),
                message: Some("Memory usage is within normal limits".to_string()),
                duration_ms: 0, // TODO: Implement actual health check
            },
        );

        HealthStatus {
            status: "healthy".to_string(),
            timestamp: chrono::Utc::now(),
            version: self.config.service_version.clone(),
            uptime: self.start_time.elapsed(),
            checks,
        }
    }

    /// Record a database operation
    #[instrument(skip(self, f))]
    pub fn record_db_operation<F, R>(&self, operation: &str, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let start = Instant::now();
        let result = f();
        let duration = start.elapsed();

        // In a real implementation, this would update metrics atomically
        debug!(
            operation = operation,
            duration_ms = duration.as_millis(),
            "Database operation completed"
        );

        result
    }

    /// Record a task operation
    #[instrument(skip(self))]
    pub fn record_task_operation(&self, operation: &str, count: u64) {
        // In a real implementation, this would update metrics atomically
        info!(
            operation = operation,
            count = count,
            "Task operation recorded"
        );
    }

    /// Record a search operation
    #[instrument(skip(self, f))]
    pub fn record_search_operation<F, R>(&self, query: &str, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let start = Instant::now();
        let result = f();
        let duration = start.elapsed();

        // In a real implementation, this would update metrics atomically
        debug!(
            query = query,
            duration_ms = duration.as_millis(),
            "Search operation completed"
        );

        result
    }

    /// Record an error
    #[instrument(skip(self))]
    pub fn record_error(&self, error_type: &str, error_message: &str) {
        // In a real implementation, this would update metrics atomically
        error!(
            error_type = error_type,
            error_message = error_message,
            "Error recorded"
        );
    }

    /// Update performance metrics
    #[instrument(skip(self))]
    pub fn update_performance_metrics(
        &self,
        memory_usage: u64,
        cpu_usage: f64,
        cache_hit_rate: f64,
        cache_size: u64,
    ) {
        // In a real implementation, this would update metrics atomically
        debug!(
            memory_usage = memory_usage,
            cpu_usage = cpu_usage,
            cache_hit_rate = cache_hit_rate,
            cache_size = cache_size,
            "Performance metrics updated"
        );
    }
}

// Simplified metrics implementation - in a real application, this would use
// a proper metrics library like prometheus or statsd

/// Macro for easy instrumentation
#[macro_export]
macro_rules! instrument_operation {
    ($operation:expr, $code:block) => {{
        let start = std::time::Instant::now();
        let result = $code;
        let duration = start.elapsed();

        tracing::debug!(
            operation = $operation,
            duration_ms = duration.as_millis(),
            "Operation completed"
        );

        result
    }};
}

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

    #[test]
    fn test_observability_config_default() {
        let config = ObservabilityConfig::default();
        assert_eq!(config.log_level, "info");
        assert!(!config.json_logs);
        assert!(config.enable_tracing);
        assert!(config.enable_metrics);
        assert_eq!(config.metrics_port, 9090);
        assert_eq!(config.health_port, 8080);
    }

    #[test]
    fn test_health_status() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();
        let health = manager.health_status();

        assert_eq!(health.status, "healthy");
        assert!(health.checks.contains_key("database"));
        assert!(health.checks.contains_key("memory"));
    }

    #[test]
    fn test_metrics_creation() {
        let _metrics = ThingsMetrics::new();
        // Test that metrics can be created without panicking
    }

    #[test]
    fn test_observability_config_creation() {
        let config = ObservabilityConfig {
            log_level: "debug".to_string(),
            json_logs: true,
            enable_tracing: true,
            jaeger_endpoint: Some("http://localhost:14268".to_string()),
            otlp_endpoint: Some("http://localhost:4317".to_string()),
            enable_metrics: true,
            metrics_port: 9091,
            health_port: 8081,
            service_name: "test-service".to_string(),
            service_version: "1.0.0".to_string(),
        };

        assert_eq!(config.log_level, "debug");
        assert!(config.json_logs);
        assert!(config.enable_tracing);
        assert_eq!(
            config.jaeger_endpoint,
            Some("http://localhost:14268".to_string())
        );
        assert_eq!(
            config.otlp_endpoint,
            Some("http://localhost:4317".to_string())
        );
        assert!(config.enable_metrics);
        assert_eq!(config.metrics_port, 9091);
        assert_eq!(config.health_port, 8081);
        assert_eq!(config.service_name, "test-service");
        assert_eq!(config.service_version, "1.0.0");
    }

    #[test]
    fn test_observability_config_serialization() {
        let config = ObservabilityConfig {
            log_level: "warn".to_string(),
            json_logs: false,
            enable_tracing: false,
            jaeger_endpoint: None,
            otlp_endpoint: None,
            enable_metrics: false,
            metrics_port: 9092,
            health_port: 8082,
            service_name: "serialization-test".to_string(),
            service_version: "2.0.0".to_string(),
        };

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: ObservabilityConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.log_level, "warn");
        assert!(!deserialized.json_logs);
        assert!(!deserialized.enable_tracing);
        assert_eq!(deserialized.jaeger_endpoint, None);
        assert_eq!(deserialized.otlp_endpoint, None);
        assert!(!deserialized.enable_metrics);
        assert_eq!(deserialized.metrics_port, 9092);
        assert_eq!(deserialized.health_port, 8082);
        assert_eq!(deserialized.service_name, "serialization-test");
        assert_eq!(deserialized.service_version, "2.0.0");
    }

    #[test]
    fn test_observability_config_clone() {
        let config = ObservabilityConfig::default();
        let cloned_config = config.clone();

        assert_eq!(cloned_config.log_level, config.log_level);
        assert_eq!(cloned_config.json_logs, config.json_logs);
        assert_eq!(cloned_config.enable_tracing, config.enable_tracing);
        assert_eq!(cloned_config.jaeger_endpoint, config.jaeger_endpoint);
        assert_eq!(cloned_config.otlp_endpoint, config.otlp_endpoint);
        assert_eq!(cloned_config.enable_metrics, config.enable_metrics);
        assert_eq!(cloned_config.metrics_port, config.metrics_port);
        assert_eq!(cloned_config.health_port, config.health_port);
        assert_eq!(cloned_config.service_name, config.service_name);
        assert_eq!(cloned_config.service_version, config.service_version);
    }

    #[test]
    fn test_things_metrics_creation() {
        let metrics = ThingsMetrics::new();

        assert_eq!(metrics.db_operations_total, 0);
        assert!((metrics.db_operation_duration - 0.0).abs() < f64::EPSILON);
        assert_eq!(metrics.db_connection_pool_size, 0);
        assert_eq!(metrics.db_connection_pool_active, 0);
        assert_eq!(metrics.tasks_created_total, 0);
        assert_eq!(metrics.tasks_updated_total, 0);
        assert_eq!(metrics.tasks_deleted_total, 0);
        assert_eq!(metrics.tasks_completed_total, 0);
        assert_eq!(metrics.search_operations_total, 0);
        assert!((metrics.search_duration - 0.0).abs() < f64::EPSILON);
        assert_eq!(metrics.search_results_count, 0);
        assert_eq!(metrics.export_operations_total, 0);
        assert!((metrics.export_duration - 0.0).abs() < f64::EPSILON);
        assert_eq!(metrics.export_file_size, 0);
        assert_eq!(metrics.errors_total, 0);
        assert!((metrics.error_rate - 0.0).abs() < f64::EPSILON);
        assert_eq!(metrics.memory_usage, 0);
        assert!((metrics.cpu_usage - 0.0).abs() < f64::EPSILON);
        assert!((metrics.cache_hit_rate - 0.0).abs() < f64::EPSILON);
        assert_eq!(metrics.cache_size, 0);
    }

    #[test]
    fn test_things_metrics_default() {
        let metrics = ThingsMetrics::default();
        let new_metrics = ThingsMetrics::new();

        assert_eq!(metrics.db_operations_total, new_metrics.db_operations_total);
        assert!(
            (metrics.db_operation_duration - new_metrics.db_operation_duration).abs()
                < f64::EPSILON
        );
        assert_eq!(metrics.tasks_created_total, new_metrics.tasks_created_total);
        assert_eq!(metrics.errors_total, new_metrics.errors_total);
    }

    #[test]
    fn test_things_metrics_clone() {
        let metrics = ThingsMetrics::new();
        let cloned_metrics = metrics.clone();

        assert_eq!(
            cloned_metrics.db_operations_total,
            metrics.db_operations_total
        );
        assert!(
            (cloned_metrics.db_operation_duration - metrics.db_operation_duration).abs()
                < f64::EPSILON
        );
        assert_eq!(
            cloned_metrics.tasks_created_total,
            metrics.tasks_created_total
        );
        assert_eq!(cloned_metrics.errors_total, metrics.errors_total);
    }

    #[test]
    fn test_health_status_creation() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();
        let health = manager.health_status();

        assert_eq!(health.status, "healthy");
        assert!(health.checks.contains_key("database"));
        assert!(health.checks.contains_key("memory"));
        assert_eq!(health.checks.len(), 2);
    }

    #[test]
    fn test_health_status_serialization() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();
        let health = manager.health_status();

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

        assert_eq!(deserialized.status, "healthy");
        assert!(deserialized.checks.contains_key("database"));
        assert!(deserialized.checks.contains_key("memory"));
        assert_eq!(deserialized.checks.len(), 2);
    }

    #[test]
    fn test_health_status_clone() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();
        let health = manager.health_status();
        let cloned_health = health.clone();

        assert_eq!(cloned_health.status, health.status);
        assert_eq!(cloned_health.checks.len(), health.checks.len());
        assert!(cloned_health.checks.contains_key("database"));
        assert!(cloned_health.checks.contains_key("memory"));
    }

    #[test]
    fn test_check_result_creation() {
        let check_result = CheckResult {
            status: "healthy".to_string(),
            message: Some("Test check passed".to_string()),
            duration_ms: 150,
        };

        assert_eq!(check_result.status, "healthy");
        assert_eq!(check_result.message, Some("Test check passed".to_string()));
        assert_eq!(check_result.duration_ms, 150);
    }

    #[test]
    fn test_check_result_without_message() {
        let check_result = CheckResult {
            status: "unhealthy".to_string(),
            message: None,
            duration_ms: 0,
        };

        assert_eq!(check_result.status, "unhealthy");
        assert_eq!(check_result.message, None);
        assert_eq!(check_result.duration_ms, 0);
    }

    #[test]
    fn test_check_result_serialization() {
        let check_result = CheckResult {
            status: "healthy".to_string(),
            message: Some("Database connection is healthy".to_string()),
            duration_ms: 250,
        };

        let json = serde_json::to_string(&check_result).unwrap();
        let deserialized: CheckResult = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.status, "healthy");
        assert_eq!(
            deserialized.message,
            Some("Database connection is healthy".to_string())
        );
        assert_eq!(deserialized.duration_ms, 250);
    }

    #[test]
    fn test_check_result_clone() {
        let check_result = CheckResult {
            status: "healthy".to_string(),
            message: Some("Test check passed".to_string()),
            duration_ms: 100,
        };
        let cloned_check = check_result.clone();

        assert_eq!(cloned_check.status, check_result.status);
        assert_eq!(cloned_check.message, check_result.message);
        assert_eq!(cloned_check.duration_ms, check_result.duration_ms);
    }

    #[test]
    fn test_observability_manager_creation() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();

        // Test that the manager was created successfully
        assert!(manager.start_time.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn test_observability_manager_creation_with_custom_config() {
        let config = ObservabilityConfig {
            log_level: "debug".to_string(),
            json_logs: true,
            enable_tracing: true,
            jaeger_endpoint: Some("http://localhost:14268".to_string()),
            otlp_endpoint: None,
            enable_metrics: true,
            metrics_port: 9091,
            health_port: 8081,
            service_name: "custom-service".to_string(),
            service_version: "1.2.3".to_string(),
        };

        let manager = ObservabilityManager::new(config).unwrap();
        assert!(manager.start_time.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn test_observability_manager_debug_formatting() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();

        let debug_str = format!("{manager:?}");
        assert!(debug_str.contains("ObservabilityManager"));
    }

    #[test]
    fn test_record_db_operation() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();

        let result = manager.record_db_operation("test_operation", || {
            // Simulate some work
            std::thread::sleep(std::time::Duration::from_millis(10));
            "operation_result"
        });

        assert_eq!(result, "operation_result");
    }

    #[test]
    fn test_record_task_operation() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();

        // This should not panic
        manager.record_task_operation("create_task", 5);
        manager.record_task_operation("update_task", 3);
        manager.record_task_operation("delete_task", 1);
    }

    #[test]
    fn test_record_search_operation() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();

        let result = manager.record_search_operation("test query", || {
            // Simulate search work
            std::thread::sleep(std::time::Duration::from_millis(5));
            vec!["result1", "result2"]
        });

        assert_eq!(result, vec!["result1", "result2"]);
    }

    #[test]
    fn test_record_error() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();

        // This should not panic
        manager.record_error("database_error", "Connection failed");
        manager.record_error("validation_error", "Invalid input");
        manager.record_error("timeout_error", "Operation timed out");
    }

    #[test]
    fn test_update_performance_metrics() {
        let config = ObservabilityConfig::default();
        let manager = ObservabilityManager::new(config).unwrap();

        // This should not panic
        manager.update_performance_metrics(1024, 0.5, 0.95, 512);
        manager.update_performance_metrics(2048, 0.75, 0.88, 1024);
        manager.update_performance_metrics(4096, 1.0, 0.92, 2048);
    }

    #[test]
    fn test_observability_error_variants() {
        let tracing_error = ObservabilityError::TracingInit("Test error".to_string());
        let metrics_error = ObservabilityError::MetricsInit("Test error".to_string());
        let otel_error = ObservabilityError::OpenTelemetryInit("Test error".to_string());
        let health_error = ObservabilityError::HealthCheckFailed("Test error".to_string());

        assert!(matches!(tracing_error, ObservabilityError::TracingInit(_)));
        assert!(matches!(metrics_error, ObservabilityError::MetricsInit(_)));
        assert!(matches!(
            otel_error,
            ObservabilityError::OpenTelemetryInit(_)
        ));
        assert!(matches!(
            health_error,
            ObservabilityError::HealthCheckFailed(_)
        ));
    }

    #[test]
    fn test_observability_error_display() {
        let tracing_error = ObservabilityError::TracingInit("Failed to initialize".to_string());
        let error_string = tracing_error.to_string();

        assert!(error_string.contains("Failed to initialize tracing"));
        assert!(error_string.contains("Failed to initialize"));
    }

    #[test]
    fn test_observability_error_debug() {
        let error = ObservabilityError::HealthCheckFailed("Database down".to_string());
        let debug_str = format!("{error:?}");

        assert!(debug_str.contains("HealthCheckFailed"));
        assert!(debug_str.contains("Database down"));
    }
}