litellm-rs 0.4.16

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! Cache system trait definitions
//!
//! Provides unified cache interface supporting multiple cache backends

use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Core cache trait
///
/// Defines unified cache operation interface
#[allow(async_fn_in_trait)]
pub trait Cache<K, V>: Send + Sync
where
    K: Send + Sync,
    V: Send + Sync,
{
    /// Error
    type Error: std::error::Error + Send + Sync + 'static;

    /// Get
    async fn get(&self, key: &K) -> Result<Option<V>, Self::Error>;

    /// Settings
    async fn set(&self, key: &K, value: V, ttl: Duration) -> Result<(), Self::Error>;

    /// Delete
    async fn delete(&self, key: &K) -> Result<bool, Self::Error>;

    /// Check
    async fn exists(&self, key: &K) -> Result<bool, Self::Error>;

    /// Settings
    async fn expire(&self, key: &K, ttl: Duration) -> Result<bool, Self::Error>;

    /// Get
    async fn ttl(&self, key: &K) -> Result<Option<Duration>, Self::Error>;

    /// Clear all cache
    async fn clear(&self) -> Result<(), Self::Error>;

    /// Get
    async fn size(&self) -> Result<usize, Self::Error>;

    /// Get
    async fn get_many(&self, keys: &[K]) -> Result<Vec<Option<V>>, Self::Error> {
        let mut results = Vec::with_capacity(keys.len());
        for key in keys {
            results.push(self.get(key).await?);
        }
        Ok(results)
    }

    /// Settings
    async fn set_many(&self, items: &[(K, V, Duration)]) -> Result<(), Self::Error>
    where
        K: Clone,
        V: Clone,
    {
        for (key, value, ttl) in items {
            self.set(key, value.clone(), *ttl).await?;
        }
        Ok(())
    }
}

/// Cache key trait
///
/// Defines operations that cache keys must support
pub trait CacheKey: Send + Sync + Clone + std::fmt::Debug + std::hash::Hash + Eq {
    /// Serialize key to string
    fn to_cache_key(&self) -> String;

    /// Deserialize key from string
    fn from_cache_key(s: &str) -> Result<Self, CacheError>
    where
        Self: Sized;
}

/// Cache value trait
///
/// Defines operations that cache values must support
pub trait CacheValue: Send + Sync + Clone + std::fmt::Debug {
    /// Serialize to bytes
    fn to_bytes(&self) -> Result<Vec<u8>, CacheError>;

    /// Deserialize from bytes
    fn from_bytes(bytes: &[u8]) -> Result<Self, CacheError>
    where
        Self: Sized;
}

/// Implementation of CacheKey for String
impl CacheKey for String {
    fn to_cache_key(&self) -> String {
        self.clone()
    }

    fn from_cache_key(s: &str) -> Result<Self, CacheError> {
        Ok(s.to_string())
    }
}

/// Implementation of CacheValue for all types that implement Serialize + DeserializeOwned
impl<T> CacheValue for T
where
    T: Serialize + for<'de> Deserialize<'de> + Send + Sync + Clone + std::fmt::Debug,
{
    fn to_bytes(&self) -> Result<Vec<u8>, CacheError> {
        rmp_serde::to_vec(self).map_err(CacheError::Serialization)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, CacheError> {
        rmp_serde::from_slice(bytes).map_err(CacheError::Deserialization)
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    /// Cache hit count
    pub hits: u64,
    /// Cache miss count
    pub misses: u64,
    /// Current key count
    pub key_count: usize,
    /// Used memory amount (bytes)
    pub memory_usage: usize,
    /// Hit rate
    pub hit_rate: f64,
}

impl CacheStats {
    pub fn new() -> Self {
        Self {
            hits: 0,
            misses: 0,
            key_count: 0,
            memory_usage: 0,
            hit_rate: 0.0,
        }
    }

    pub fn calculate_hit_rate(&mut self) {
        let total = self.hits + self.misses;
        if total > 0 {
            self.hit_rate = self.hits as f64 / total as f64;
        }
    }
}

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

/// Cache trait with statistics functionality
#[allow(async_fn_in_trait)]
pub trait CacheWithStats<K, V>: Cache<K, V>
where
    K: Send + Sync,
    V: Send + Sync,
{
    /// Get
    async fn stats(&self) -> Result<CacheStats, Self::Error>;

    /// Reset statistics
    async fn reset_stats(&self) -> Result<(), Self::Error>;
}

/// Cache event types
#[derive(Debug, Clone)]
pub enum CacheEvent<K, V> {
    /// Cache hit
    Hit { key: K },
    /// Cache miss
    Miss { key: K },
    /// Settings
    Set { key: K, value: V },
    /// Delete
    Delete { key: K },
    /// Cache expiration
    Expire { key: K },
    /// Cache clear
    Clear,
}

/// Cache event listener
#[allow(async_fn_in_trait)]
pub trait CacheEventListener<K, V>: Send + Sync
where
    K: Send + Sync,
    V: Send + Sync,
{
    /// Handle
    async fn on_event(&self, event: CacheEvent<K, V>);
}

/// Error
#[derive(Debug, thiserror::Error)]
pub enum CacheError {
    #[error("Connection failed: {0}")]
    Connection(String),

    #[error("Serialization failed: {0}")]
    Serialization(#[from] rmp_serde::encode::Error),

    #[error("Deserialization failed: {0}")]
    Deserialization(rmp_serde::decode::Error),

    #[error("Key not found: {key}")]
    KeyNotFound { key: String },

    #[error("Cache is full")]
    CacheFull,

    #[error("Invalid TTL: {ttl_ms}ms")]
    InvalidTTL { ttl_ms: u64 },

    #[error("Cache operation timeout")]
    Timeout,

    #[error("Cache backend error: {0}")]
    Backend(String),

    #[error("Other cache error: {0}")]
    Other(String),
}

impl CacheError {
    pub fn connection(msg: impl Into<String>) -> Self {
        Self::Connection(msg.into())
    }

    pub fn key_not_found(key: impl Into<String>) -> Self {
        Self::KeyNotFound { key: key.into() }
    }

    pub fn backend(msg: impl Into<String>) -> Self {
        Self::Backend(msg.into())
    }

    pub fn other(msg: impl Into<String>) -> Self {
        Self::Other(msg.into())
    }
}

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

    // ==================== CacheKey Tests ====================

    #[test]
    fn test_string_cache_key_to_cache_key() {
        let key = "my-cache-key".to_string();
        assert_eq!(key.to_cache_key(), "my-cache-key");
    }

    #[test]
    fn test_string_cache_key_from_cache_key() {
        let key = String::from_cache_key("restored-key").unwrap();
        assert_eq!(key, "restored-key");
    }

    #[test]
    fn test_string_cache_key_roundtrip() {
        let original = "test-key-123".to_string();
        let serialized = original.to_cache_key();
        let restored = String::from_cache_key(&serialized).unwrap();
        assert_eq!(original, restored);
    }

    // ==================== CacheValue Tests ====================

    #[test]
    fn test_cache_value_to_bytes_string() {
        let value = "hello world".to_string();
        let bytes = value.to_bytes();
        assert!(bytes.is_ok());
        assert!(!bytes.unwrap().is_empty());
    }

    #[test]
    fn test_cache_value_from_bytes_string() {
        let value = "test value".to_string();
        let bytes = value.to_bytes().unwrap();
        let restored = String::from_bytes(&bytes).unwrap();
        assert_eq!(value, restored);
    }

    #[test]
    fn test_cache_value_roundtrip_integer() {
        let value: i32 = 42;
        let bytes = value.to_bytes().unwrap();
        let restored = i32::from_bytes(&bytes).unwrap();
        assert_eq!(value, restored);
    }

    #[test]
    fn test_cache_value_roundtrip_complex() {
        #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
        struct TestData {
            id: u64,
            name: String,
            active: bool,
        }

        let value = TestData {
            id: 123,
            name: "test".to_string(),
            active: true,
        };
        let bytes = value.to_bytes().unwrap();
        let restored = TestData::from_bytes(&bytes).unwrap();
        assert_eq!(value, restored);
    }

    // ==================== CacheStats Tests ====================

    #[test]
    fn test_cache_stats_new() {
        let stats = CacheStats::new();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
        assert_eq!(stats.key_count, 0);
        assert_eq!(stats.memory_usage, 0);
        assert!((stats.hit_rate - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cache_stats_default() {
        let stats = CacheStats::default();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
    }

    #[test]
    fn test_cache_stats_calculate_hit_rate_zero_total() {
        let mut stats = CacheStats::new();
        stats.calculate_hit_rate();
        assert!((stats.hit_rate - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cache_stats_calculate_hit_rate_all_hits() {
        let mut stats = CacheStats::new();
        stats.hits = 100;
        stats.misses = 0;
        stats.calculate_hit_rate();
        assert!((stats.hit_rate - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cache_stats_calculate_hit_rate_all_misses() {
        let mut stats = CacheStats::new();
        stats.hits = 0;
        stats.misses = 100;
        stats.calculate_hit_rate();
        assert!((stats.hit_rate - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_cache_stats_calculate_hit_rate_mixed() {
        let mut stats = CacheStats::new();
        stats.hits = 75;
        stats.misses = 25;
        stats.calculate_hit_rate();
        assert!((stats.hit_rate - 0.75).abs() < 0.001);
    }

    #[test]
    fn test_cache_stats_clone() {
        let mut stats = CacheStats::new();
        stats.hits = 10;
        stats.key_count = 5;
        let cloned = stats.clone();
        assert_eq!(stats.hits, cloned.hits);
        assert_eq!(stats.key_count, cloned.key_count);
    }

    #[test]
    fn test_cache_stats_debug() {
        let stats = CacheStats::new();
        let debug = format!("{:?}", stats);
        assert!(debug.contains("CacheStats"));
    }

    // ==================== CacheEvent Tests ====================

    #[test]
    fn test_cache_event_hit() {
        let event: CacheEvent<String, i32> = CacheEvent::Hit {
            key: "key1".to_string(),
        };
        assert!(matches!(event, CacheEvent::Hit { key } if key == "key1"));
    }

    #[test]
    fn test_cache_event_miss() {
        let event: CacheEvent<String, i32> = CacheEvent::Miss {
            key: "key2".to_string(),
        };
        assert!(matches!(event, CacheEvent::Miss { key } if key == "key2"));
    }

    #[test]
    fn test_cache_event_set() {
        let event = CacheEvent::Set {
            key: "key3".to_string(),
            value: 42,
        };
        assert!(matches!(event, CacheEvent::Set { key, value } if key == "key3" && value == 42));
    }

    #[test]
    fn test_cache_event_delete() {
        let event: CacheEvent<String, i32> = CacheEvent::Delete {
            key: "key4".to_string(),
        };
        assert!(matches!(event, CacheEvent::Delete { key } if key == "key4"));
    }

    #[test]
    fn test_cache_event_expire() {
        let event: CacheEvent<String, i32> = CacheEvent::Expire {
            key: "key5".to_string(),
        };
        assert!(matches!(event, CacheEvent::Expire { key } if key == "key5"));
    }

    #[test]
    fn test_cache_event_clear() {
        let event: CacheEvent<String, i32> = CacheEvent::Clear;
        assert!(matches!(event, CacheEvent::Clear));
    }

    #[test]
    fn test_cache_event_clone() {
        let event = CacheEvent::Set {
            key: "key".to_string(),
            value: 100,
        };
        let cloned = event.clone();
        assert!(matches!(cloned, CacheEvent::Set { key, value } if key == "key" && value == 100));
    }

    // ==================== CacheError Tests ====================

    #[test]
    fn test_cache_error_connection() {
        let err = CacheError::connection("Redis connection failed");
        assert!(matches!(err, CacheError::Connection(_)));
        assert!(err.to_string().contains("Connection failed"));
    }

    #[test]
    fn test_cache_error_key_not_found() {
        let err = CacheError::key_not_found("missing-key");
        assert!(matches!(err, CacheError::KeyNotFound { .. }));
        assert!(err.to_string().contains("Key not found"));
        assert!(err.to_string().contains("missing-key"));
    }

    #[test]
    fn test_cache_error_cache_full() {
        let err = CacheError::CacheFull;
        assert!(err.to_string().contains("Cache is full"));
    }

    #[test]
    fn test_cache_error_invalid_ttl() {
        let err = CacheError::InvalidTTL { ttl_ms: 0 };
        assert!(err.to_string().contains("Invalid TTL"));
    }

    #[test]
    fn test_cache_error_timeout() {
        let err = CacheError::Timeout;
        assert!(err.to_string().contains("timeout"));
    }

    #[test]
    fn test_cache_error_backend() {
        let err = CacheError::backend("Backend failure");
        assert!(matches!(err, CacheError::Backend(_)));
        assert!(err.to_string().contains("Backend"));
    }

    #[test]
    fn test_cache_error_other() {
        let err = CacheError::other("Some other error");
        assert!(matches!(err, CacheError::Other(_)));
    }

    #[test]
    fn test_cache_error_display() {
        let err = CacheError::connection("test error");
        let display = format!("{}", err);
        assert!(!display.is_empty());
    }

    #[test]
    fn test_cache_error_debug() {
        let err = CacheError::CacheFull;
        let debug = format!("{:?}", err);
        assert!(debug.contains("CacheFull"));
    }
}