ares-server 0.7.5

A.R.E.S - Agentic Retrieval Enhanced Server: A production-grade agentic chatbot server with multi-provider LLM support, tool calling, RAG, and MCP integration
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
use crate::db::PostgresClient;
use crate::models::{ApiKey, Tenant, TenantContext, TenantTier};
use crate::types::{AppError, Result};
use chrono::{Datelike, TimeZone, Utc};
use sha2::{Digest, Sha256};
use sqlx::Row;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

pub struct TenantDb {
    postgres: Arc<PostgresClient>,
    monthly_cache: Arc<RwLock<HashMap<String, (i64, u64)>>>,
    daily_cache: Arc<RwLock<HashMap<String, (i64, u64)>>>,
}

impl TenantDb {
    pub fn new(postgres: Arc<PostgresClient>) -> Self {
        Self {
            postgres,
            monthly_cache: Arc::new(RwLock::new(HashMap::new())),
            daily_cache: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub fn pool(&self) -> &sqlx::PgPool {
        &self.postgres.pool
    }

    pub async fn create_tenant(&self, name: String, tier: TenantTier) -> Result<Tenant> {
        let id = uuid::Uuid::new_v4().to_string();
        let tenant = Tenant::new(id.clone(), name, tier);

        sqlx::query(
            "INSERT INTO tenants (id, name, tier, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)"
        )
        .bind(&tenant.id)
        .bind(&tenant.name)
        .bind(tenant.tier.as_str())
        .bind(tenant.created_at)
        .bind(tenant.updated_at)
        .execute(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to create tenant: {}", e)))?;

        Ok(tenant)
    }

    pub async fn list_tenants(&self) -> Result<Vec<Tenant>> {
        let rows = sqlx::query(
            "SELECT id, name, tier, created_at, updated_at FROM tenants ORDER BY created_at DESC",
        )
        .fetch_all(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to list tenants: {}", e)))?;

        let mut tenants = Vec::new();
        for row in rows {
            let tier_str: String = row.get(2);
            let tier = TenantTier::from_str(&tier_str).unwrap_or(TenantTier::Free);
            tenants.push(Tenant {
                id: row.get(0),
                name: row.get(1),
                tier,
                created_at: row.get(3),
                updated_at: row.get(4),
            });
        }

        Ok(tenants)
    }

    pub async fn get_tenant(&self, tenant_id: &str) -> Result<Option<Tenant>> {
        let row =
            sqlx::query("SELECT id, name, tier, created_at, updated_at FROM tenants WHERE id = $1")
                .bind(tenant_id)
                .fetch_optional(&self.postgres.pool)
                .await
                .map_err(|e| AppError::Database(format!("Failed to get tenant: {}", e)))?;

        if let Some(row) = row {
            let tier_str: String = row.get(2);
            let tier = TenantTier::from_str(&tier_str).unwrap_or(TenantTier::Free);
            Ok(Some(Tenant {
                id: row.get(0),
                name: row.get(1),
                tier,
                created_at: row.get(3),
                updated_at: row.get(4),
            }))
        } else {
            Ok(None)
        }
    }

    pub async fn create_api_key(&self, tenant_id: &str, name: String) -> Result<(ApiKey, String)> {
        let id = uuid::Uuid::new_v4().to_string();
        let raw_key = generate_api_key();
        let key_prefix = format!("ares_{}", &raw_key[..8]);

        let key_hash = hash_api_key(&raw_key);

        let api_key = ApiKey::new(id, tenant_id.to_string(), key_hash, key_prefix, name);

        sqlx::query(
            "INSERT INTO api_keys (id, tenant_id, key_hash, key_prefix, name, is_active, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"
        )
        .bind(&api_key.id)
        .bind(&api_key.tenant_id)
        .bind(&api_key.key_hash)
        .bind(&api_key.key_prefix)
        .bind(&api_key.name)
        .bind(api_key.is_active as i32)
        .bind(api_key.created_at)
        .bind(api_key.expires_at)
        .execute(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to create API key: {}", e)))?;

        Ok((api_key, raw_key))
    }

    pub async fn list_api_keys(&self, tenant_id: &str) -> Result<Vec<ApiKey>> {
        let rows = sqlx::query(
            "SELECT id, tenant_id, key_hash, key_prefix, name, is_active, created_at, expires_at FROM api_keys WHERE tenant_id = $1 ORDER BY created_at DESC"
        )
        .bind(tenant_id)
        .fetch_all(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to list API keys: {}", e)))?;

        let mut keys = Vec::new();
        for row in rows {
            let expires_at: Option<i64> = row.get(7);
            keys.push(ApiKey {
                id: row.get(0),
                tenant_id: row.get(1),
                key_hash: row.get(2),
                key_prefix: row.get(3),
                name: row.get(4),
                is_active: row.get::<i32, _>(5) != 0,
                created_at: row.get(6),
                expires_at,
            });
        }

        Ok(keys)
    }

    pub async fn verify_api_key(&self, raw_key: &str) -> Result<Option<TenantContext>> {
        let key_prefix = format!("ares_{}", &raw_key[5..13]);
        let row = sqlx::query(
            "SELECT ak.id, ak.tenant_id, ak.key_hash, ak.is_active, ak.expires_at, t.tier 
             FROM api_keys ak 
             JOIN tenants t ON ak.tenant_id = t.id 
             WHERE ak.key_prefix = $1",
        )
        .bind(key_prefix)
        .fetch_optional(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to lookup API key: {}", e)))?;

        if let Some(row) = row {
            let key_hash: String = row.get(2);
            let is_active: i32 = row.get(3);
            let expires_at: Option<i64> = row.get(4);
            let tier_str: String = row.get(5);

            if is_active == 0 {
                return Ok(None);
            }

            if let Some(exp) = expires_at {
                if Utc::now().timestamp() > exp {
                    return Ok(None);
                }
            }

            // Strip "ares_" prefix before hashing to match what create_api_key hashes
            let key_without_prefix = raw_key.strip_prefix("ares_").unwrap_or(raw_key);
            let input_hash = hash_api_key(key_without_prefix);
            if input_hash != key_hash {
                return Ok(None);
            }

            let tenant_id: String = row.get(1);
            let tier = TenantTier::from_str(&tier_str).unwrap_or(TenantTier::Free);

            Ok(Some(TenantContext::new(tenant_id, tier)))
        } else {
            Ok(None)
        }
    }

    pub async fn get_monthly_requests(&self, tenant_id: &str) -> Result<u64> {
        let cache_key = tenant_id.to_string();
        let now = Utc::now();
        let month_start = now
            .date_naive()
            .with_day(1)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();

        {
            let cache = self.monthly_cache.read().await;
            if let Some((cached_month, count)) = cache.get(&cache_key) {
                if *cached_month == month_start {
                    return Ok(*count);
                }
            }
        }

        let row = sqlx::query(
            "SELECT COALESCE(SUM(request_count)::bigint, 0) FROM monthly_usage_cache WHERE tenant_id = $1 AND usage_month >= $2"
        )
        .bind(tenant_id)
        .bind(month_start)
        .fetch_one(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to get monthly requests: {}", e)))?;

        let count: i64 = row.try_get::<i64, _>(0).unwrap_or(0);
        let count = count as u64;

        {
            let mut cache = self.monthly_cache.write().await;
            cache.insert(cache_key, (month_start, count));
        }

        Ok(count)
    }

    pub async fn get_daily_requests(&self, tenant_id: &str) -> Result<u64> {
        let cache_key = tenant_id.to_string();
        let today = Utc::now()
            .date_naive()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();

        {
            let cache = self.daily_cache.read().await;
            if let Some((cached_day, count)) = cache.get(&cache_key) {
                if *cached_day == today {
                    return Ok(*count);
                }
            }
        }

        let row = sqlx::query(
            "SELECT COALESCE(SUM(request_count)::bigint, 0) FROM daily_rate_limits WHERE tenant_id = $1 AND usage_date >= $2"
        )
        .bind(tenant_id)
        .bind(today)
        .fetch_one(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to get daily requests: {}", e)))?;

        let count: i64 = row.try_get::<i64, _>(0).unwrap_or(0);
        let count = count as u64;

        {
            let mut cache = self.daily_cache.write().await;
            cache.insert(cache_key, (today, count));
        }

        Ok(count)
    }

    pub async fn record_usage_event(
        &self,
        tenant_id: &str,
        requests: u64,
        tokens: u64,
    ) -> Result<()> {
        let now = Utc::now();
        let today = now
            .date_naive()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();
        let month_start = now
            .date_naive()
            .with_day(1)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();

        sqlx::query(
            "INSERT INTO usage_events (id, tenant_id, source, request_count, token_count, created_at) VALUES ($1, $2, 'http', $3, $4, $5)"
        )
        .bind(uuid::Uuid::new_v4().to_string())
        .bind(tenant_id)
        .bind(requests as i64)
        .bind(tokens as i64)
        .bind(now.timestamp())
        .execute(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to record usage event: {}", e)))?;

        sqlx::query(
            "INSERT INTO monthly_usage_cache (tenant_id, usage_month, request_count, token_count) VALUES ($1, $2, $3, $4)
             ON CONFLICT(tenant_id, usage_month) DO UPDATE SET 
             request_count = monthly_usage_cache.request_count + $5, token_count = monthly_usage_cache.token_count + $6"
        )
        .bind(tenant_id)
        .bind(month_start)
        .bind(requests as i64)
        .bind(tokens as i64)
        .bind(requests as i64)
        .bind(tokens as i64)
        .execute(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to update monthly cache: {}", e)))?;

        sqlx::query(
            "INSERT INTO daily_rate_limits (tenant_id, usage_date, request_count) VALUES ($1, $2, $3)
             ON CONFLICT(tenant_id, usage_date) DO UPDATE SET 
             request_count = daily_rate_limits.request_count + $4"
        )
        .bind(tenant_id)
        .bind(today)
        .bind(requests as i64)
        .bind(requests as i64)
        .execute(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to update daily limit: {}", e)))?;

        {
            let mut cache = self.monthly_cache.write().await;
            if let Some((month, count)) = cache.get_mut(tenant_id) {
                if *month == month_start {
                    *count += requests;
                }
            }
        }

        {
            let mut cache = self.daily_cache.write().await;
            if let Some((day, count)) = cache.get_mut(tenant_id) {
                if *day == today {
                    *count += requests;
                }
            }
        }

        Ok(())
    }

    pub async fn get_usage_summary(&self, tenant_id: &str) -> Result<UsageSummary> {
        let monthly_requests = self.get_monthly_requests(tenant_id).await?;
        let daily_requests = self.get_daily_requests(tenant_id).await?;

        let now = Utc::now();
        let month_start = now
            .date_naive()
            .with_day(1)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc()
            .timestamp();

        let row = sqlx::query(
            "SELECT COALESCE(SUM(token_count)::bigint, 0) FROM monthly_usage_cache WHERE tenant_id = $1 AND usage_month >= $2"
        )
        .bind(tenant_id)
        .bind(month_start)
        .fetch_one(&self.postgres.pool)
        .await
        .map_err(|e| AppError::Database(format!("Failed to get monthly tokens: {}", e)))?;

        let monthly_tokens: i64 = row.try_get::<i64, _>(0).unwrap_or(0);

        Ok(UsageSummary {
            monthly_requests,
            monthly_tokens: monthly_tokens as u64,
            daily_requests,
        })
    }

    pub async fn revoke_api_key(&self, tenant_id: &str, key_id: &str) -> Result<()> {
        let result =
            sqlx::query("UPDATE api_keys SET is_active = 0 WHERE id = $1 AND tenant_id = $2")
                .bind(key_id)
                .bind(tenant_id)
                .execute(&self.postgres.pool)
                .await
                .map_err(|e| AppError::Database(format!("Failed to revoke API key: {}", e)))?;

        if result.rows_affected() == 0 {
            return Err(AppError::NotFound(format!(
                "API key '{}' not found for tenant '{}'",
                key_id, tenant_id
            )));
        }
        Ok(())
    }

    pub async fn update_tenant_quota(&self, tenant_id: &str, tier: TenantTier) -> Result<()> {
        sqlx::query("UPDATE tenants SET tier = $1, updated_at = $2 WHERE id = $3")
            .bind(tier.as_str())
            .bind(Utc::now().timestamp())
            .bind(tenant_id)
            .execute(&self.postgres.pool)
            .await
            .map_err(|e| AppError::Database(format!("Failed to update tenant quota: {}", e)))?;

        Ok(())
    }
}

fn generate_api_key() -> String {
    let bytes: Vec<u8> = (0..32).map(|_| rand::random::<u8>()).collect();
    format!("ares_{}", hex::encode(bytes))
}

fn hash_api_key(raw_key: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(raw_key.as_bytes());
    hex::encode(hasher.finalize())
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UsageSummary {
    pub monthly_requests: u64,
    pub monthly_tokens: u64,
    pub daily_requests: u64,
}

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

    #[test]
    fn test_generate_api_key() {
        let key = generate_api_key();
        assert!(key.starts_with("ares_"));
        assert_eq!(key.len(), 69);
    }
}