llm-cost-ops 0.1.1

Core library for cost operations on LLM deployments
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
// Health check system for monitoring service health

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::RwLock;

use super::config::HealthConfig;

/// Health status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
    /// Service is healthy
    Healthy,

    /// Service is degraded but functional
    Degraded,

    /// Service is unhealthy
    Unhealthy,
}

impl std::fmt::Display for HealthStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HealthStatus::Healthy => write!(f, "healthy"),
            HealthStatus::Degraded => write!(f, "degraded"),
            HealthStatus::Unhealthy => write!(f, "unhealthy"),
        }
    }
}

/// Component health check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentHealth {
    pub name: String,
    pub status: HealthStatus,
    pub message: Option<String>,
    pub last_check: chrono::DateTime<chrono::Utc>,
    pub check_duration_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<HashMap<String, serde_json::Value>>,
}

impl ComponentHealth {
    /// Create a healthy component result
    pub fn healthy(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: HealthStatus::Healthy,
            message: None,
            last_check: chrono::Utc::now(),
            check_duration_ms: 0,
            details: None,
        }
    }

    /// Create a degraded component result
    pub fn degraded(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: HealthStatus::Degraded,
            message: Some(message.into()),
            last_check: chrono::Utc::now(),
            check_duration_ms: 0,
            details: None,
        }
    }

    /// Create an unhealthy component result
    pub fn unhealthy(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: HealthStatus::Unhealthy,
            message: Some(message.into()),
            last_check: chrono::Utc::now(),
            check_duration_ms: 0,
            details: None,
        }
    }

    /// Add details
    pub fn with_details(mut self, details: HashMap<String, serde_json::Value>) -> Self {
        self.details = Some(details);
        self
    }

    /// Add a single detail
    pub fn with_detail(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        let mut details = self.details.unwrap_or_default();
        details.insert(key.into(), value);
        self.details = Some(details);
        self
    }

    /// Set check duration
    pub fn with_duration(mut self, duration_ms: u64) -> Self {
        self.check_duration_ms = duration_ms;
        self
    }
}

/// Health check trait
#[async_trait]
pub trait HealthCheck: Send + Sync {
    /// Name of the component being checked
    fn name(&self) -> &str;

    /// Perform the health check
    async fn check(&self) -> ComponentHealth;

    /// Check if this is a critical component
    fn is_critical(&self) -> bool {
        false
    }
}

/// Overall system health
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemHealth {
    pub status: HealthStatus,
    pub version: String,
    pub uptime_seconds: u64,
    pub components: Vec<ComponentHealth>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

impl SystemHealth {
    /// Determine overall status from components
    pub fn determine_status(components: &[ComponentHealth], critical_names: &[String]) -> HealthStatus {
        let mut has_degraded = false;

        for component in components {
            // Check if component is critical
            let is_critical = critical_names.contains(&component.name);

            match component.status {
                HealthStatus::Unhealthy if is_critical => {
                    // Critical component unhealthy = system unhealthy
                    return HealthStatus::Unhealthy;
                }
                HealthStatus::Unhealthy => {
                    // Non-critical component unhealthy = degraded
                    has_degraded = true;
                }
                HealthStatus::Degraded => {
                    has_degraded = true;
                }
                HealthStatus::Healthy => {}
            }
        }

        if has_degraded {
            HealthStatus::Degraded
        } else {
            HealthStatus::Healthy
        }
    }
}

/// Health checker manager
pub struct HealthChecker {
    checks: Arc<RwLock<Vec<Arc<dyn HealthCheck>>>>,
    config: HealthConfig,
    start_time: Instant,
    critical_components: Arc<RwLock<Vec<String>>>,
}

impl HealthChecker {
    /// Create a new health checker
    pub fn new(config: HealthConfig) -> Self {
        Self {
            checks: Arc::new(RwLock::new(Vec::new())),
            config,
            start_time: Instant::now(),
            critical_components: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Register a health check
    pub async fn register(&self, check: Arc<dyn HealthCheck>) {
        let mut checks = self.checks.write().await;

        // If this is a critical check, add to critical list
        if check.is_critical() {
            let mut critical = self.critical_components.write().await;
            critical.push(check.name().to_string());
        }

        checks.push(check);
    }

    /// Mark a component as critical
    pub async fn mark_critical(&self, component_name: impl Into<String>) {
        let mut critical = self.critical_components.write().await;
        let name = component_name.into();
        if !critical.contains(&name) {
            critical.push(name);
        }
    }

    /// Perform all health checks
    pub async fn check_health(&self) -> SystemHealth {
        let checks = self.checks.read().await.clone();
        let critical = self.critical_components.read().await.clone();

        // Run all checks concurrently
        let check_futures: Vec<_> = checks
            .iter()
            .map(|check| async move {
                let start = Instant::now();
                let mut result = check.check().await;
                result.check_duration_ms = start.elapsed().as_millis() as u64;
                result
            })
            .collect();

        let components = futures::future::join_all(check_futures).await;

        let status = SystemHealth::determine_status(&components, &critical);

        SystemHealth {
            status,
            version: env!("CARGO_PKG_VERSION").to_string(),
            uptime_seconds: self.start_time.elapsed().as_secs(),
            components,
            timestamp: chrono::Utc::now(),
        }
    }

    /// Check liveness (basic check that service is running)
    pub async fn check_liveness(&self) -> HealthStatus {
        // Liveness is just a ping - if we can respond, we're alive
        HealthStatus::Healthy
    }

    /// Check readiness (service is ready to accept traffic)
    pub async fn check_readiness(&self) -> HealthStatus {
        let health = self.check_health().await;

        // Ready if not unhealthy (degraded is acceptable for readiness)
        match health.status {
            HealthStatus::Healthy | HealthStatus::Degraded => HealthStatus::Healthy,
            HealthStatus::Unhealthy => HealthStatus::Unhealthy,
        }
    }

    /// Get configuration
    pub fn config(&self) -> &HealthConfig {
        &self.config
    }
}

/// Database health check
pub struct DatabaseHealthCheck {
    name: String,
    critical: bool,
}

impl DatabaseHealthCheck {
    pub fn new(name: impl Into<String>, critical: bool) -> Self {
        Self {
            name: name.into(),
            critical,
        }
    }
}

#[async_trait]
impl HealthCheck for DatabaseHealthCheck {
    fn name(&self) -> &str {
        &self.name
    }

    async fn check(&self) -> ComponentHealth {
        // In a real implementation, this would check database connectivity
        // For now, we'll simulate it
        ComponentHealth::healthy(&self.name)
            .with_detail("type", serde_json::json!("database"))
    }

    fn is_critical(&self) -> bool {
        self.critical
    }
}

/// Cache health check
pub struct CacheHealthCheck {
    name: String,
    critical: bool,
}

impl CacheHealthCheck {
    pub fn new(name: impl Into<String>, critical: bool) -> Self {
        Self {
            name: name.into(),
            critical,
        }
    }
}

#[async_trait]
impl HealthCheck for CacheHealthCheck {
    fn name(&self) -> &str {
        &self.name
    }

    async fn check(&self) -> ComponentHealth {
        ComponentHealth::healthy(&self.name)
            .with_detail("type", serde_json::json!("cache"))
    }

    fn is_critical(&self) -> bool {
        self.critical
    }
}

/// External service health check
pub struct ExternalServiceHealthCheck {
    name: String,
    endpoint: String,
    critical: bool,
}

impl ExternalServiceHealthCheck {
    pub fn new(name: impl Into<String>, endpoint: impl Into<String>, critical: bool) -> Self {
        Self {
            name: name.into(),
            endpoint: endpoint.into(),
            critical,
        }
    }
}

#[async_trait]
impl HealthCheck for ExternalServiceHealthCheck {
    fn name(&self) -> &str {
        &self.name
    }

    async fn check(&self) -> ComponentHealth {
        // In a real implementation, this would check the external service
        ComponentHealth::healthy(&self.name)
            .with_detail("type", serde_json::json!("external_service"))
            .with_detail("endpoint", serde_json::json!(&self.endpoint))
    }

    fn is_critical(&self) -> bool {
        self.critical
    }
}

/// Custom function-based health check
pub struct FunctionHealthCheck<F>
where
    F: Fn() -> ComponentHealth + Send + Sync,
{
    name: String,
    check_fn: F,
    critical: bool,
}

impl<F> FunctionHealthCheck<F>
where
    F: Fn() -> ComponentHealth + Send + Sync,
{
    pub fn new(name: impl Into<String>, check_fn: F, critical: bool) -> Self {
        Self {
            name: name.into(),
            check_fn,
            critical,
        }
    }
}

#[async_trait]
impl<F> HealthCheck for FunctionHealthCheck<F>
where
    F: Fn() -> ComponentHealth + Send + Sync,
{
    fn name(&self) -> &str {
        &self.name
    }

    async fn check(&self) -> ComponentHealth {
        (self.check_fn)()
    }

    fn is_critical(&self) -> bool {
        self.critical
    }
}

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

    #[test]
    fn test_health_status_display() {
        assert_eq!(HealthStatus::Healthy.to_string(), "healthy");
        assert_eq!(HealthStatus::Degraded.to_string(), "degraded");
        assert_eq!(HealthStatus::Unhealthy.to_string(), "unhealthy");
    }

    #[test]
    fn test_component_health_creation() {
        let health = ComponentHealth::healthy("test");
        assert_eq!(health.name, "test");
        assert_eq!(health.status, HealthStatus::Healthy);
        assert!(health.message.is_none());

        let degraded = ComponentHealth::degraded("test", "some issue");
        assert_eq!(degraded.status, HealthStatus::Degraded);
        assert_eq!(degraded.message, Some("some issue".to_string()));

        let unhealthy = ComponentHealth::unhealthy("test", "critical issue");
        assert_eq!(unhealthy.status, HealthStatus::Unhealthy);
        assert_eq!(unhealthy.message, Some("critical issue".to_string()));
    }

    #[test]
    fn test_component_health_with_details() {
        let mut details = HashMap::new();
        details.insert("key".to_string(), serde_json::json!("value"));

        let health = ComponentHealth::healthy("test").with_details(details);
        assert!(health.details.is_some());
        assert_eq!(
            health.details.unwrap().get("key"),
            Some(&serde_json::json!("value"))
        );
    }

    #[test]
    fn test_system_health_determine_status() {
        let components = vec![
            ComponentHealth::healthy("db"),
            ComponentHealth::healthy("cache"),
        ];

        let status = SystemHealth::determine_status(&components, &vec![]);
        assert_eq!(status, HealthStatus::Healthy);

        let components = vec![
            ComponentHealth::healthy("db"),
            ComponentHealth::degraded("cache", "slow"),
        ];

        let status = SystemHealth::determine_status(&components, &vec![]);
        assert_eq!(status, HealthStatus::Degraded);

        let components = vec![
            ComponentHealth::unhealthy("db", "down"),
            ComponentHealth::healthy("cache"),
        ];

        let critical = vec!["db".to_string()];
        let status = SystemHealth::determine_status(&components, &critical);
        assert_eq!(status, HealthStatus::Unhealthy);
    }

    #[tokio::test]
    async fn test_health_checker_creation() {
        let config = HealthConfig::default();
        let checker = HealthChecker::new(config);

        let health = checker.check_health().await;
        assert_eq!(health.status, HealthStatus::Healthy);
        assert_eq!(health.components.len(), 0);
    }

    #[tokio::test]
    async fn test_health_checker_register() {
        let config = HealthConfig::default();
        let checker = HealthChecker::new(config);

        let db_check = Arc::new(DatabaseHealthCheck::new("database", true));
        checker.register(db_check).await;

        let health = checker.check_health().await;
        assert_eq!(health.components.len(), 1);
        assert_eq!(health.components[0].name, "database");
    }

    #[tokio::test]
    async fn test_health_checker_liveness() {
        let config = HealthConfig::default();
        let checker = HealthChecker::new(config);

        let status = checker.check_liveness().await;
        assert_eq!(status, HealthStatus::Healthy);
    }

    #[tokio::test]
    async fn test_health_checker_readiness() {
        let config = HealthConfig::default();
        let checker = HealthChecker::new(config);

        let status = checker.check_readiness().await;
        assert_eq!(status, HealthStatus::Healthy);
    }

    #[tokio::test]
    async fn test_database_health_check() {
        let check = DatabaseHealthCheck::new("test_db", true);
        assert_eq!(check.name(), "test_db");
        assert!(check.is_critical());

        let health = check.check().await;
        assert_eq!(health.status, HealthStatus::Healthy);
    }

    #[tokio::test]
    async fn test_cache_health_check() {
        let check = CacheHealthCheck::new("test_cache", false);
        assert_eq!(check.name(), "test_cache");
        assert!(!check.is_critical());

        let health = check.check().await;
        assert_eq!(health.status, HealthStatus::Healthy);
    }

    #[tokio::test]
    async fn test_external_service_health_check() {
        let check = ExternalServiceHealthCheck::new(
            "external_api",
            "https://api.example.com",
            true,
        );
        assert_eq!(check.name(), "external_api");
        assert!(check.is_critical());

        let health = check.check().await;
        assert_eq!(health.status, HealthStatus::Healthy);
    }

    #[tokio::test]
    async fn test_function_health_check() {
        let check = FunctionHealthCheck::new(
            "custom",
            || ComponentHealth::healthy("custom"),
            false,
        );

        let health = check.check().await;
        assert_eq!(health.status, HealthStatus::Healthy);
    }

    #[tokio::test]
    async fn test_mark_critical() {
        let config = HealthConfig::default();
        let checker = HealthChecker::new(config);

        checker.mark_critical("database").await;

        let critical = checker.critical_components.read().await;
        assert!(critical.contains(&"database".to_string()));
    }
}