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
//! AWS S3 cache backend implementation
//!
//! Provides a cache backend using AWS S3 for persistent, distributed caching.

#[cfg(feature = "s3")]
mod implementation {
    use async_trait::async_trait;
    use aws_sdk_s3::Client;
    use aws_sdk_s3::primitives::ByteStream;
    use aws_sdk_s3::types::Object as S3Object;
    use serde::{Serialize, de::DeserializeOwned};
    use std::time::Duration;
    use tracing::{debug, error, warn};

    use crate::core::cache::cloud::{CacheMetadata, CloudCache, CloudCacheConfig};
    use crate::core::cache::types::CacheKey;
    use crate::utils::error::gateway_error::{GatewayError, Result};

    /// S3 cache configuration
    #[derive(Debug, Clone, Default)]
    pub struct S3CacheConfig {
        /// Base cloud cache config
        pub base: CloudCacheConfig,
        /// AWS region
        pub region: Option<String>,
        /// Custom endpoint URL (for LocalStack, MinIO, etc.)
        pub endpoint_url: Option<String>,
        /// Storage class for cache objects
        pub storage_class: S3StorageClass,
    }

    /// S3 storage class options
    #[derive(Debug, Clone, Copy, Default)]
    pub enum S3StorageClass {
        #[default]
        Standard,
        StandardIa,
        OnezoneIa,
        IntelligentTiering,
        Glacier,
        GlacierIr,
    }

    impl S3StorageClass {
        /// Get the S3 storage class string
        pub fn as_str(&self) -> &'static str {
            match self {
                S3StorageClass::Standard => "STANDARD",
                S3StorageClass::StandardIa => "STANDARD_IA",
                S3StorageClass::OnezoneIa => "ONEZONE_IA",
                S3StorageClass::IntelligentTiering => "INTELLIGENT_TIERING",
                S3StorageClass::Glacier => "GLACIER",
                S3StorageClass::GlacierIr => "GLACIER_IR",
            }
        }
    }

    impl S3CacheConfig {
        /// Create a new S3 cache configuration
        pub fn new(bucket: impl Into<String>) -> Self {
            Self {
                base: CloudCacheConfig::new(bucket),
                ..Default::default()
            }
        }

        /// Set the AWS region
        pub fn region(mut self, region: impl Into<String>) -> Self {
            self.region = Some(region.into());
            self
        }

        /// Set a custom endpoint URL
        pub fn endpoint_url(mut self, url: impl Into<String>) -> Self {
            self.endpoint_url = Some(url.into());
            self
        }

        /// Set the storage class
        pub fn storage_class(mut self, class: S3StorageClass) -> Self {
            self.storage_class = class;
            self
        }

        /// Set the key prefix
        pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
            self.base.prefix = prefix.into();
            self
        }

        /// Set the default TTL
        pub fn default_ttl(mut self, ttl: Duration) -> Self {
            self.base.default_ttl = ttl;
            self
        }

        /// Create from environment variables
        pub fn from_env() -> Option<Self> {
            let bucket = std::env::var("S3_CACHE_BUCKET").ok()?;
            Some(Self {
                base: CloudCacheConfig::new(bucket),
                region: std::env::var("AWS_REGION").ok(),
                endpoint_url: std::env::var("S3_ENDPOINT_URL").ok(),
                storage_class: S3StorageClass::default(),
            })
        }
    }

    /// AWS S3 cache backend
    pub struct S3Cache {
        client: Client,
        config: S3CacheConfig,
    }

    impl S3Cache {
        /// Create a new S3 cache
        pub async fn new(config: S3CacheConfig) -> Result<Self> {
            let mut aws_config_builder =
                aws_config::defaults(aws_config::BehaviorVersion::latest());

            if let Some(ref region) = config.region {
                aws_config_builder =
                    aws_config_builder.region(aws_config::Region::new(region.clone()));
            }

            let aws_config = aws_config_builder.load().await;

            let mut s3_config = aws_sdk_s3::config::Builder::from(&aws_config);

            if let Some(ref endpoint) = config.endpoint_url {
                s3_config = s3_config.endpoint_url(endpoint).force_path_style(true);
            }

            let client = Client::from_conf(s3_config.build());

            Ok(Self { client, config })
        }

        /// Create from environment variables
        pub async fn from_env() -> Result<Self> {
            let config = S3CacheConfig::from_env().ok_or_else(|| {
                GatewayError::Config("S3_CACHE_BUCKET not set in environment".to_string())
            })?;
            Self::new(config).await
        }

        /// Build the full S3 key for a cache key
        fn build_key(&self, key: &CacheKey) -> String {
            format!("{}{}", self.config.base.prefix, key.as_str())
        }

        /// Build the metadata key for a cache key
        fn build_metadata_key(&self, key: &CacheKey) -> String {
            format!("{}{}._meta", self.config.base.prefix, key.as_str())
        }
    }

    #[async_trait]
    impl CloudCache for S3Cache {
        async fn get<T: DeserializeOwned + Send>(&self, key: &CacheKey) -> Result<Option<T>> {
            let s3_key = self.build_key(key);
            let meta_key = self.build_metadata_key(key);
            debug!(key = %s3_key, "Reading from S3 cache");

            // First check metadata for expiration
            match self
                .client
                .get_object()
                .bucket(&self.config.base.bucket)
                .key(&meta_key)
                .send()
                .await
            {
                Ok(meta_response) => {
                    let meta_bytes = meta_response
                        .body
                        .collect()
                        .await
                        .map_err(|e| {
                            GatewayError::Internal(format!("Failed to read metadata: {}", e))
                        })?
                        .into_bytes();

                    let metadata: CacheMetadata =
                        serde_json::from_slice(&meta_bytes).map_err(|e| {
                            GatewayError::Internal(format!("Failed to parse metadata: {}", e))
                        })?;

                    if metadata.is_expired() {
                        debug!(key = %s3_key, "Cache entry expired");
                        // Clean up expired entry in background
                        let _ = self.delete(key).await;
                        return Ok(None);
                    }
                }
                Err(err) => {
                    let err_str = err.to_string();
                    if err_str.contains("NoSuchKey") || err_str.contains("404") {
                        debug!(key = %s3_key, "Cache miss - no metadata");
                        return Ok(None);
                    }
                    warn!(key = %s3_key, error = %err, "Failed to read metadata");
                    return Ok(None);
                }
            }

            // Read the actual value
            match self
                .client
                .get_object()
                .bucket(&self.config.base.bucket)
                .key(&s3_key)
                .send()
                .await
            {
                Ok(response) => {
                    let bytes = response
                        .body
                        .collect()
                        .await
                        .map_err(|e| GatewayError::Internal(format!("Failed to read body: {}", e)))?
                        .into_bytes();

                    let value: T = serde_json::from_slice(&bytes).map_err(|e| {
                        GatewayError::Internal(format!("Failed to deserialize: {}", e))
                    })?;

                    debug!(key = %s3_key, "S3 cache hit");
                    Ok(Some(value))
                }
                Err(err) => {
                    let err_str = err.to_string();
                    if err_str.contains("NoSuchKey") || err_str.contains("404") {
                        debug!(key = %s3_key, "Cache miss");
                        Ok(None)
                    } else {
                        error!(key = %s3_key, error = %err, "Failed to read from S3");
                        Err(GatewayError::Internal(format!("S3 read error: {}", err)))
                    }
                }
            }
        }

        async fn set<T: Serialize + Send + Sync>(
            &self,
            key: &CacheKey,
            value: &T,
            ttl: Duration,
        ) -> Result<()> {
            let s3_key = self.build_key(key);
            let meta_key = self.build_metadata_key(key);
            debug!(key = %s3_key, ttl_secs = ttl.as_secs(), "Writing to S3 cache");

            // Serialize the value
            let bytes = serde_json::to_vec(value)
                .map_err(|e| GatewayError::Internal(format!("Failed to serialize: {}", e)))?;

            // Create metadata
            let metadata = CacheMetadata::new(ttl, bytes.len(), false);
            let meta_bytes = serde_json::to_vec(&metadata).map_err(|e| {
                GatewayError::Internal(format!("Failed to serialize metadata: {}", e))
            })?;

            // Write the value
            self.client
                .put_object()
                .bucket(&self.config.base.bucket)
                .key(&s3_key)
                .body(ByteStream::from(bytes))
                .storage_class(self.config.storage_class.as_str().parse().map_err(|e| {
                    GatewayError::Config(format!("Invalid S3 storage class: {}", e))
                })?)
                .content_type("application/json")
                .send()
                .await
                .map_err(|e| GatewayError::Internal(format!("Failed to write to S3: {}", e)))?;

            // Write metadata
            self.client
                .put_object()
                .bucket(&self.config.base.bucket)
                .key(&meta_key)
                .body(ByteStream::from(meta_bytes))
                .content_type("application/json")
                .send()
                .await
                .map_err(|e| GatewayError::Internal(format!("Failed to write metadata: {}", e)))?;

            debug!(key = %s3_key, "S3 cache write successful");
            Ok(())
        }

        async fn delete(&self, key: &CacheKey) -> Result<bool> {
            let s3_key = self.build_key(key);
            let meta_key = self.build_metadata_key(key);
            debug!(key = %s3_key, "Deleting from S3 cache");

            // Delete both the value and metadata
            let value_result = self
                .client
                .delete_object()
                .bucket(&self.config.base.bucket)
                .key(&s3_key)
                .send()
                .await;

            let meta_result = self
                .client
                .delete_object()
                .bucket(&self.config.base.bucket)
                .key(&meta_key)
                .send()
                .await;

            // S3 delete doesn't error if key doesn't exist
            if value_result.is_err() && meta_result.is_err() {
                return Ok(false);
            }

            debug!(key = %s3_key, "S3 cache delete successful");
            Ok(true)
        }

        async fn exists(&self, key: &CacheKey) -> Result<bool> {
            let s3_key = self.build_key(key);

            match self
                .client
                .head_object()
                .bucket(&self.config.base.bucket)
                .key(&s3_key)
                .send()
                .await
            {
                Ok(_) => Ok(true),
                Err(err) => {
                    let err_str = err.to_string();
                    if err_str.contains("NotFound") || err_str.contains("404") {
                        Ok(false)
                    } else {
                        Err(GatewayError::Internal(format!("S3 head error: {}", err)))
                    }
                }
            }
        }

        async fn list_keys(&self, prefix: &str) -> Result<Vec<String>> {
            let full_prefix = format!("{}{}", self.config.base.prefix, prefix);

            let response = self
                .client
                .list_objects_v2()
                .bucket(&self.config.base.bucket)
                .prefix(&full_prefix)
                .send()
                .await
                .map_err(|e| GatewayError::Internal(format!("Failed to list objects: {}", e)))?;

            let mut keys = Vec::new();
            for obj in response.contents().iter() {
                let obj: &S3Object = obj;
                if let Some(k) = obj.key() {
                    let key = k
                        .strip_prefix(&self.config.base.prefix)
                        .unwrap_or(k)
                        .to_string();
                    if !key.ends_with("._meta") {
                        keys.push(key);
                    }
                }
            }

            Ok(keys)
        }

        async fn clear(&self) -> Result<()> {
            warn!("Clearing all S3 cache entries");

            let keys = self.list_keys("").await?;

            for key in keys {
                let cache_key = CacheKey::new(key);
                let _ = self.delete(&cache_key).await;
            }

            Ok(())
        }

        fn name(&self) -> &'static str {
            "s3"
        }
    }

    impl std::fmt::Debug for S3Cache {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("S3Cache")
                .field("bucket", &self.config.base.bucket)
                .field("prefix", &self.config.base.prefix)
                .field("region", &self.config.region)
                .finish()
        }
    }
}

#[cfg(feature = "s3")]
pub use implementation::*;

// Stub implementation when feature is disabled
#[cfg(not(feature = "s3"))]
mod stub {
    use crate::utils::error::gateway_error::{GatewayError, Result};

    /// S3 cache configuration (stub)
    #[derive(Debug, Clone, Default)]
    pub struct S3CacheConfig {
        pub bucket: String,
    }

    impl S3CacheConfig {
        pub fn new(bucket: impl Into<String>) -> Self {
            Self {
                bucket: bucket.into(),
            }
        }

        pub fn from_env() -> Option<Self> {
            None
        }
    }

    /// S3 cache (stub)
    #[derive(Debug)]
    pub struct S3Cache;

    impl S3Cache {
        pub async fn new(_config: S3CacheConfig) -> Result<Self> {
            Err(GatewayError::Config(
                "S3 cache support not enabled. Enable the 's3' feature.".to_string(),
            ))
        }

        pub async fn from_env() -> Result<Self> {
            Err(GatewayError::Config(
                "S3 cache support not enabled. Enable the 's3' feature.".to_string(),
            ))
        }
    }
}

#[cfg(not(feature = "s3"))]
pub use stub::*;

#[cfg(all(test, feature = "s3"))]
mod tests {
    use super::*;

    #[test]
    fn test_s3_cache_config_builder() {
        let config = S3CacheConfig::new("my-bucket")
            .region("us-east-1")
            .prefix("cache/")
            .storage_class(S3StorageClass::StandardIa);

        assert_eq!(config.base.bucket, "my-bucket");
        assert_eq!(config.region, Some("us-east-1".to_string()));
        assert_eq!(config.base.prefix, "cache/");
    }

    #[test]
    fn test_s3_storage_class() {
        assert_eq!(S3StorageClass::Standard.as_str(), "STANDARD");
        assert_eq!(S3StorageClass::StandardIa.as_str(), "STANDARD_IA");
        assert_eq!(S3StorageClass::Glacier.as_str(), "GLACIER");
    }
}