litellm-rs 0.6.0

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
//! User management database operations
//!
//! Stores user-management domain objects as JSON snapshots in the
//! `um_users`, `um_teams`, and `um_organizations` tables created by
//! migration `m20240301_000001_create_user_management_tables`.

use crate::core::user_management::{Organization, Team, User};
use crate::utils::error::gateway_error::{GatewayError, Result};
use sea_orm::{ConnectionTrait, DbBackend, Statement, Value};
use tracing::debug;

use super::types::{DatabaseBackendType, SeaOrmDatabase};

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

impl SeaOrmDatabase {
    /// Return the sea_orm DbBackend matching the live connection.
    fn db_backend(&self) -> DbBackend {
        match self.backend_type {
            DatabaseBackendType::PostgreSQL => DbBackend::Postgres,
            DatabaseBackendType::SQLite => DbBackend::Sqlite,
        }
    }

    /// Return the positional placeholder for parameter `n` (1-based).
    ///
    /// SQLite uses `?`; PostgreSQL uses `$N`.
    fn ph(&self, n: usize) -> String {
        match self.backend_type {
            DatabaseBackendType::PostgreSQL => format!("${}", n),
            DatabaseBackendType::SQLite => "?".to_string(),
        }
    }

    fn deserialize<T: serde::de::DeserializeOwned>(data: &str) -> Result<T> {
        serde_json::from_str(data).map_err(|e| GatewayError::Internal(e.to_string()))
    }

    fn serialize<T: serde::Serialize>(value: &T) -> Result<String> {
        serde_json::to_string(value).map_err(|e| GatewayError::Internal(e.to_string()))
    }
}

// ---------------------------------------------------------------------------
// User operations
// ---------------------------------------------------------------------------

impl SeaOrmDatabase {
    /// Retrieve a user management user by their string ID.
    pub(crate) async fn get_legacy_user_by_id(&self, user_id: &str) -> Result<Option<User>> {
        debug!("um: get_user {}", user_id);
        let sql = format!("SELECT data FROM um_users WHERE user_id = {}", self.ph(1));
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [Value::String(Some(Box::new(user_id.to_owned())))],
        );
        match self.db.query_one(stmt).await.map_err(GatewayError::from)? {
            None => Ok(None),
            Some(row) => {
                let data: String = row.try_get("", "data").map_err(GatewayError::from)?;
                Ok(Some(Self::deserialize(&data)?))
            }
        }
    }

    /// Retrieve a user management user by their email address.
    pub(crate) async fn get_legacy_user_by_email(&self, email: &str) -> Result<Option<User>> {
        debug!("um: get_user_by_email {}", email);
        let sql = format!("SELECT data FROM um_users WHERE email = {}", self.ph(1));
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [Value::String(Some(Box::new(email.to_owned())))],
        );
        match self.db.query_one(stmt).await.map_err(GatewayError::from)? {
            None => Ok(None),
            Some(row) => {
                let data: String = row.try_get("", "data").map_err(GatewayError::from)?;
                Ok(Some(Self::deserialize(&data)?))
            }
        }
    }

    /// Retrieve a user management user by the canonical username preserved in
    /// its JSON metadata.
    pub(crate) async fn get_legacy_user_by_canonical_username(
        &self,
        username: &str,
    ) -> Result<Option<User>> {
        debug!("um: get_user_by_canonical_username {}", username);
        let predicate = match self.backend_type {
            DatabaseBackendType::PostgreSQL => {
                format!(
                    "data::jsonb -> 'metadata' ->> 'canonical_username' = {}",
                    self.ph(1)
                )
            }
            DatabaseBackendType::SQLite => {
                format!(
                    "json_extract(data, '$.metadata.canonical_username') = {}",
                    self.ph(1)
                )
            }
        };
        let sql = format!("SELECT data FROM um_users WHERE {}", predicate);
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [Value::String(Some(Box::new(username.to_owned())))],
        );
        match self.db.query_one(stmt).await.map_err(GatewayError::from)? {
            None => Ok(None),
            Some(row) => {
                let data: String = row.try_get("", "data").map_err(GatewayError::from)?;
                Ok(Some(Self::deserialize(&data)?))
            }
        }
    }

    /// Retrieve a user management user by their string ID.
    pub async fn get_user(&self, user_id: &str) -> Result<Option<User>> {
        if let Some(user) = self.get_legacy_user_by_id(user_id).await? {
            return Ok(Some(user));
        }

        let Ok(user_uuid) = uuid::Uuid::parse_str(user_id) else {
            return Ok(None);
        };
        self.sync_legacy_user_from_canonical(user_uuid).await?;
        self.get_legacy_user_by_id(user_id).await
    }

    /// Retrieve a user management user by their email address.
    pub async fn get_user_by_email(&self, email: &str) -> Result<Option<User>> {
        if let Some(user) = self.get_legacy_user_by_email(email).await? {
            return Ok(Some(user));
        }

        if let Some(user) = self.find_canonical_user_by_email(email).await? {
            self.sync_legacy_user_from_canonical(user.id()).await?;
        }
        self.get_legacy_user_by_email(email).await
    }

    /// Persist a new user management user to the database.
    ///
    /// Named `um_create_user` to avoid colliding with the existing
    /// `create_user` method which operates on a different `User` type.
    pub async fn um_create_user(&self, user: &User) -> Result<()> {
        debug!("um: um_create_user {}", user.user_id);
        let data = Self::serialize(user)?;
        let sql = format!(
            "INSERT INTO um_users (user_id, email, data, spend) VALUES ({}, {}, {}, {})",
            self.ph(1),
            self.ph(2),
            self.ph(3),
            self.ph(4),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::String(Some(Box::new(user.user_id.clone()))),
                Value::String(Some(Box::new(user.email.clone()))),
                Value::String(Some(Box::new(data))),
                Value::Double(Some(user.spend)),
            ],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        let _ = self.persist_legacy_user(user).await?;
        Ok(())
    }

    /// Persist all mutable fields of a user management user (full update).
    pub async fn update_user(&self, user: &User) -> Result<()> {
        debug!("um: update_user {}", user.user_id);
        let data = Self::serialize(user)?;
        let sql = format!(
            "UPDATE um_users SET email = {}, data = {}, spend = {} WHERE user_id = {}",
            self.ph(1),
            self.ph(2),
            self.ph(3),
            self.ph(4),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::String(Some(Box::new(user.email.clone()))),
                Value::String(Some(Box::new(data))),
                Value::Double(Some(user.spend)),
                Value::String(Some(Box::new(user.user_id.clone()))),
            ],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        Ok(())
    }

    /// Remove a user management user from the database by their string ID.
    pub async fn delete_user(&self, user_id: &str) -> Result<()> {
        debug!("um: delete_user {}", user_id);
        let sql = format!("DELETE FROM um_users WHERE user_id = {}", self.ph(1));
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [Value::String(Some(Box::new(user_id.to_owned())))],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        Ok(())
    }

    /// Add `cost` to the recorded spend for the given user ID.
    pub async fn update_user_spend(&self, user_id: &str, cost: f64) -> Result<()> {
        debug!("um: update_user_spend {} += {}", user_id, cost);
        let sql = format!(
            "UPDATE um_users SET spend = spend + {} WHERE user_id = {}",
            self.ph(1),
            self.ph(2),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::Double(Some(cost)),
                Value::String(Some(Box::new(user_id.to_owned()))),
            ],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        Ok(())
    }

    /// List user management users with offset-based pagination.
    pub async fn list_users(&self, offset: u32, limit: u32) -> Result<Vec<User>> {
        debug!("um: list_users offset={} limit={}", offset, limit);
        let sql = format!(
            "SELECT data FROM um_users ORDER BY created_at ASC LIMIT {} OFFSET {}",
            self.ph(1),
            self.ph(2),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::BigUnsigned(Some(limit as u64)),
                Value::BigUnsigned(Some(offset as u64)),
            ],
        );
        let rows = self.db.query_all(stmt).await.map_err(GatewayError::from)?;
        rows.into_iter()
            .map(|row| {
                let data: String = row.try_get("", "data").map_err(GatewayError::from)?;
                Self::deserialize(&data)
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Team operations (user_management::Team — distinct from core::models::Team)
// ---------------------------------------------------------------------------

impl SeaOrmDatabase {
    /// Retrieve a team by its string ID.
    pub async fn get_team(&self, team_id: &str) -> Result<Option<Team>> {
        debug!("um: get_team {}", team_id);
        let sql = format!("SELECT data FROM um_teams WHERE team_id = {}", self.ph(1));
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [Value::String(Some(Box::new(team_id.to_owned())))],
        );
        match self.db.query_one(stmt).await.map_err(GatewayError::from)? {
            None => Ok(None),
            Some(row) => {
                let data: String = row.try_get("", "data").map_err(GatewayError::from)?;
                Ok(Some(Self::deserialize(&data)?))
            }
        }
    }

    /// Persist a new team to the database.
    pub async fn create_team(&self, team: &Team) -> Result<()> {
        debug!("um: create_team {}", team.team_id);
        let data = Self::serialize(team)?;
        let sql = format!(
            "INSERT INTO um_teams (team_id, data, spend) VALUES ({}, {}, {})",
            self.ph(1),
            self.ph(2),
            self.ph(3),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::String(Some(Box::new(team.team_id.clone()))),
                Value::String(Some(Box::new(data))),
                Value::Double(Some(team.spend)),
            ],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        Ok(())
    }

    /// Persist all mutable fields of a team (full update).
    pub async fn update_team(&self, team: &Team) -> Result<()> {
        debug!("um: update_team {}", team.team_id);
        let data = Self::serialize(team)?;
        let sql = format!(
            "UPDATE um_teams SET data = {}, spend = {} WHERE team_id = {}",
            self.ph(1),
            self.ph(2),
            self.ph(3),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::String(Some(Box::new(data))),
                Value::Double(Some(team.spend)),
                Value::String(Some(Box::new(team.team_id.clone()))),
            ],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        Ok(())
    }

    /// Add `cost` to the recorded spend for the given team ID.
    pub async fn update_team_spend(&self, team_id: &str, cost: f64) -> Result<()> {
        debug!("um: update_team_spend {} += {}", team_id, cost);
        let sql = format!(
            "UPDATE um_teams SET spend = spend + {} WHERE team_id = {}",
            self.ph(1),
            self.ph(2),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::Double(Some(cost)),
                Value::String(Some(Box::new(team_id.to_owned()))),
            ],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        Ok(())
    }

    /// List teams with offset-based pagination.
    pub async fn list_teams(&self, offset: u32, limit: u32) -> Result<Vec<Team>> {
        debug!("um: list_teams offset={} limit={}", offset, limit);
        let sql = format!(
            "SELECT data FROM um_teams ORDER BY created_at ASC LIMIT {} OFFSET {}",
            self.ph(1),
            self.ph(2),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::BigUnsigned(Some(limit as u64)),
                Value::BigUnsigned(Some(offset as u64)),
            ],
        );
        let rows = self.db.query_all(stmt).await.map_err(GatewayError::from)?;
        rows.into_iter()
            .map(|row| {
                let data: String = row.try_get("", "data").map_err(GatewayError::from)?;
                Self::deserialize(&data)
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Organization operations
// ---------------------------------------------------------------------------

impl SeaOrmDatabase {
    /// Persist a new organization to the database.
    pub async fn create_organization(&self, organization: &Organization) -> Result<()> {
        debug!("um: create_organization {}", organization.organization_id);
        let data = Self::serialize(organization)?;
        let sql = format!(
            "INSERT INTO um_organizations (organization_id, data, spend) VALUES ({}, {}, {})",
            self.ph(1),
            self.ph(2),
            self.ph(3),
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [
                Value::String(Some(Box::new(organization.organization_id.clone()))),
                Value::String(Some(Box::new(data))),
                Value::Double(Some(organization.spend)),
            ],
        );
        self.db.execute(stmt).await.map_err(GatewayError::from)?;
        Ok(())
    }

    /// Retrieve an organization by its string ID.
    pub async fn get_organization(&self, organization_id: &str) -> Result<Option<Organization>> {
        debug!("um: get_organization {}", organization_id);
        let sql = format!(
            "SELECT data FROM um_organizations WHERE organization_id = {}",
            self.ph(1)
        );
        let stmt = Statement::from_sql_and_values(
            self.db_backend(),
            &sql,
            [Value::String(Some(Box::new(organization_id.to_owned())))],
        );
        match self.db.query_one(stmt).await.map_err(GatewayError::from)? {
            None => Ok(None),
            Some(row) => {
                let data: String = row.try_get("", "data").map_err(GatewayError::from)?;
                Ok(Some(Self::deserialize(&data)?))
            }
        }
    }
}