litellm-rs 0.1.1

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! Health checking system
//!
//! This module provides comprehensive health checking for all system components.

#![allow(dead_code)]

use crate::storage::StorageLayer;
use crate::utils::error::Result;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tracing::{debug, error};

/// Health checker for monitoring system component health
#[derive(Debug)]
pub struct HealthChecker {
    /// Storage layer for health data
    storage: Arc<StorageLayer>,
    /// Component health status
    component_health: Arc<RwLock<HashMap<String, ComponentHealth>>>,
    /// Overall health status
    overall_health: Arc<RwLock<HealthStatus>>,
    /// Whether health checking is active
    active: Arc<RwLock<bool>>,
}

/// Overall system health status
#[derive(Debug, Clone, serde::Serialize)]
pub struct HealthStatus {
    /// Whether the system is overall healthy
    pub overall_healthy: bool,
    /// Timestamp of last health check
    pub last_check: chrono::DateTime<chrono::Utc>,
    /// Individual component health
    pub components: HashMap<String, ComponentHealth>,
    /// System uptime
    pub uptime_seconds: u64,
    /// Health check summary
    pub summary: HealthSummary,
}

/// Individual component health
#[derive(Debug, Clone, serde::Serialize)]
pub struct ComponentHealth {
    /// Component name
    pub name: String,
    /// Whether the component is healthy
    pub healthy: bool,
    /// Health status message
    pub status: String,
    /// Last check timestamp
    pub last_check: chrono::DateTime<chrono::Utc>,
    /// Response time for health check
    pub response_time_ms: u64,
    /// Error message (if unhealthy)
    pub error: Option<String>,
    /// Additional metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Health check summary
#[derive(Debug, Clone, serde::Serialize)]
pub struct HealthSummary {
    /// Total number of components
    pub total_components: usize,
    /// Number of healthy components
    pub healthy_components: usize,
    /// Number of unhealthy components
    pub unhealthy_components: usize,
    /// Health percentage
    pub health_percentage: f64,
}

/// Health check configuration for a component
#[derive(Debug, Clone)]
pub struct HealthCheckConfig {
    /// Component name
    pub name: String,
    /// Check interval
    pub interval: Duration,
    /// Timeout for health check
    pub timeout: Duration,
    /// Number of retries
    pub retries: u32,
    /// Whether this component is critical
    pub critical: bool,
}

impl HealthChecker {
    /// Create a new health checker
    pub async fn new(storage: Arc<StorageLayer>) -> Result<Self> {
        Ok(Self {
            storage,
            component_health: Arc::new(RwLock::new(HashMap::new())),
            overall_health: Arc::new(RwLock::new(HealthStatus {
                overall_healthy: true,
                last_check: chrono::Utc::now(),
                components: HashMap::new(),
                uptime_seconds: 0,
                summary: HealthSummary {
                    total_components: 0,
                    healthy_components: 0,
                    unhealthy_components: 0,
                    health_percentage: 100.0,
                },
            })),
            active: Arc::new(RwLock::new(false)),
        })
    }

    /// Start health checking
    pub async fn start(&self) -> Result<()> {
        debug!("Starting health checker");

        *self.active.write().await = true;

        // Start health check tasks
        self.start_health_check_tasks().await;

        Ok(())
    }

    /// Stop health checking
    pub async fn stop(&self) -> Result<()> {
        debug!("Stopping health checker");
        *self.active.write().await = false;
        Ok(())
    }

    /// Get current health status
    pub async fn get_status(&self) -> Result<HealthStatus> {
        let status = self.overall_health.read().await.clone();
        Ok(status)
    }

    /// Check all components
    pub async fn check_all(&self) -> Result<HealthStatus> {
        debug!("Running comprehensive health check");

        let start_time = Instant::now();
        let mut components = HashMap::new();

        // Check storage layer
        let storage_health = self.check_storage().await;
        components.insert("storage".to_string(), storage_health);

        // Check database
        let database_health = self.check_database().await;
        components.insert("database".to_string(), database_health);

        // Check Redis
        let redis_health = self.check_redis().await;
        components.insert("redis".to_string(), redis_health);

        // Check file storage
        let file_storage_health = self.check_file_storage().await;
        components.insert("file_storage".to_string(), file_storage_health);

        // Check vector database (if configured)
        if self.storage.vector().is_some() {
            let vector_health = self.check_vector_database().await;
            components.insert("vector_database".to_string(), vector_health);
        }

        // Calculate overall health
        let healthy_components = components.values().filter(|c| c.healthy).count();
        let total_components = components.len();
        let overall_healthy = healthy_components == total_components;
        let health_percentage = (healthy_components as f64 / total_components as f64) * 100.0;

        let health_status = HealthStatus {
            overall_healthy,
            last_check: chrono::Utc::now(),
            components: components.clone(),
            uptime_seconds: start_time.elapsed().as_secs(),
            summary: HealthSummary {
                total_components,
                healthy_components,
                unhealthy_components: total_components - healthy_components,
                health_percentage,
            },
        };

        // Update stored health status
        {
            let mut stored_health = self.overall_health.write().await;
            *stored_health = health_status.clone();
        }

        {
            let mut stored_components = self.component_health.write().await;
            *stored_components = components;
        }

        Ok(health_status)
    }

    /// Check storage layer health
    async fn check_storage(&self) -> ComponentHealth {
        let start_time = Instant::now();

        match self.storage.health_check().await {
            Ok(storage_status) => ComponentHealth {
                name: "storage".to_string(),
                healthy: storage_status.overall,
                status: if storage_status.overall {
                    "healthy"
                } else {
                    "degraded"
                }
                .to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: None,
                metadata: serde_json::to_value(&storage_status)
                    .unwrap_or_default()
                    .as_object()
                    .map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
                    .unwrap_or_default(),
            },
            Err(e) => ComponentHealth {
                name: "storage".to_string(),
                healthy: false,
                status: "unhealthy".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: Some(e.to_string()),
                metadata: HashMap::new(),
            },
        }
    }

    /// Check database health
    async fn check_database(&self) -> ComponentHealth {
        let start_time = Instant::now();

        match self.storage.db().health_check().await {
            Ok(()) => {
                let stats = self.storage.db().stats();
                let mut metadata = HashMap::new();
                metadata.insert(
                    "pool_size".to_string(),
                    serde_json::Value::Number(stats.size.into()),
                );
                metadata.insert(
                    "idle_connections".to_string(),
                    serde_json::Value::Number(stats.idle.into()),
                );

                ComponentHealth {
                    name: "database".to_string(),
                    healthy: true,
                    status: "healthy".to_string(),
                    last_check: chrono::Utc::now(),
                    response_time_ms: start_time.elapsed().as_millis() as u64,
                    error: None,
                    metadata,
                }
            }
            Err(e) => ComponentHealth {
                name: "database".to_string(),
                healthy: false,
                status: "unhealthy".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: Some(e.to_string()),
                metadata: HashMap::new(),
            },
        }
    }

    /// Check Redis health
    async fn check_redis(&self) -> ComponentHealth {
        let start_time = Instant::now();

        match self.storage.redis().health_check().await {
            Ok(()) => ComponentHealth {
                name: "redis".to_string(),
                healthy: true,
                status: "healthy".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: None,
                metadata: HashMap::new(),
            },
            Err(e) => ComponentHealth {
                name: "redis".to_string(),
                healthy: false,
                status: "unhealthy".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: Some(e.to_string()),
                metadata: HashMap::new(),
            },
        }
    }

    /// Check file storage health
    async fn check_file_storage(&self) -> ComponentHealth {
        let start_time = Instant::now();

        match self.storage.files().health_check().await {
            Ok(()) => ComponentHealth {
                name: "file_storage".to_string(),
                healthy: true,
                status: "healthy".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: None,
                metadata: HashMap::new(),
            },
            Err(e) => ComponentHealth {
                name: "file_storage".to_string(),
                healthy: false,
                status: "unhealthy".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: Some(e.to_string()),
                metadata: HashMap::new(),
            },
        }
    }

    /// Check vector database health
    async fn check_vector_database(&self) -> ComponentHealth {
        let start_time = Instant::now();

        if let Some(vector_store) = self.storage.vector() {
            match vector_store.health_check().await {
                Ok(()) => ComponentHealth {
                    name: "vector_database".to_string(),
                    healthy: true,
                    status: "healthy".to_string(),
                    last_check: chrono::Utc::now(),
                    response_time_ms: start_time.elapsed().as_millis() as u64,
                    error: None,
                    metadata: HashMap::new(),
                },
                Err(e) => ComponentHealth {
                    name: "vector_database".to_string(),
                    healthy: false,
                    status: "unhealthy".to_string(),
                    last_check: chrono::Utc::now(),
                    response_time_ms: start_time.elapsed().as_millis() as u64,
                    error: Some(e.to_string()),
                    metadata: HashMap::new(),
                },
            }
        } else {
            ComponentHealth {
                name: "vector_database".to_string(),
                healthy: true,
                status: "not_configured".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: 0,
                error: None,
                metadata: HashMap::new(),
            }
        }
    }

    /// Check external provider health
    async fn check_provider(&self, provider_name: &str, provider_url: &str) -> ComponentHealth {
        let start_time = Instant::now();

        // Simple HTTP health check
        match reqwest::Client::new()
            .get(provider_url)
            .timeout(Duration::from_secs(10))
            .send()
            .await
        {
            Ok(response) => {
                let healthy = response.status().is_success();
                ComponentHealth {
                    name: provider_name.to_string(),
                    healthy,
                    status: if healthy { "healthy" } else { "degraded" }.to_string(),
                    last_check: chrono::Utc::now(),
                    response_time_ms: start_time.elapsed().as_millis() as u64,
                    error: if healthy {
                        None
                    } else {
                        Some(format!("HTTP {}", response.status()))
                    },
                    metadata: {
                        let mut metadata = HashMap::new();
                        metadata.insert(
                            "status_code".to_string(),
                            serde_json::Value::Number(response.status().as_u16().into()),
                        );
                        metadata
                    },
                }
            }
            Err(e) => ComponentHealth {
                name: provider_name.to_string(),
                healthy: false,
                status: "unhealthy".to_string(),
                last_check: chrono::Utc::now(),
                response_time_ms: start_time.elapsed().as_millis() as u64,
                error: Some(e.to_string()),
                metadata: HashMap::new(),
            },
        }
    }

    /// Start background health check tasks
    async fn start_health_check_tasks(&self) {
        let health_checker = self.clone();

        // Main health check task
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(30));

            loop {
                interval.tick().await;

                if !*health_checker.active.read().await {
                    break;
                }

                if let Err(e) = health_checker.check_all().await {
                    error!("Health check failed: {}", e);
                }
            }
        });

        // Component-specific health checks can be added here
        // with different intervals for different components
    }

    /// Get component health by name
    pub async fn get_component_health(&self, component_name: &str) -> Option<ComponentHealth> {
        let components = self.component_health.read().await;
        components.get(component_name).cloned()
    }

    /// Check if a specific component is healthy
    pub async fn is_component_healthy(&self, component_name: &str) -> bool {
        if let Some(component) = self.get_component_health(component_name).await {
            component.healthy
        } else {
            false
        }
    }

    /// Get unhealthy components
    pub async fn get_unhealthy_components(&self) -> Vec<ComponentHealth> {
        let components = self.component_health.read().await;
        components
            .values()
            .filter(|component| !component.healthy)
            .cloned()
            .collect()
    }
}

impl Clone for HealthChecker {
    fn clone(&self) -> Self {
        Self {
            storage: self.storage.clone(),
            component_health: self.component_health.clone(),
            overall_health: self.overall_health.clone(),
            active: self.active.clone(),
        }
    }
}

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

    #[test]
    fn test_component_health_creation() {
        let health = ComponentHealth {
            name: "test_component".to_string(),
            healthy: true,
            status: "healthy".to_string(),
            last_check: chrono::Utc::now(),
            response_time_ms: 50,
            error: None,
            metadata: HashMap::new(),
        };

        assert!(health.healthy);
        assert_eq!(health.name, "test_component");
        assert_eq!(health.response_time_ms, 50);
    }

    #[test]
    fn test_health_summary_calculation() {
        let summary = HealthSummary {
            total_components: 5,
            healthy_components: 4,
            unhealthy_components: 1,
            health_percentage: 80.0,
        };

        assert_eq!(summary.total_components, 5);
        assert_eq!(summary.healthy_components, 4);
        assert_eq!(summary.health_percentage, 80.0);
    }

    #[test]
    fn test_health_check_config() {
        let config = HealthCheckConfig {
            name: "database".to_string(),
            interval: Duration::from_secs(30),
            timeout: Duration::from_secs(5),
            retries: 3,
            critical: true,
        };

        assert_eq!(config.name, "database");
        assert!(config.critical);
        assert_eq!(config.retries, 3);
    }
}