Erster Stand des Omega AI Proxy
- Ollama-API an der Wurzel und llama-server (Router-Modus) unter /llamacpp, unverändert durchgereicht mit Streaming - API-Keys in SQLite, Verwaltung über die Kommandozeile - Verbuchung der Nutzung mit Token-Zahlen aus den Antworten - Speicherverwaltung: Laden und Entladen durch den Proxy, Messung des Speicherbedarfs, Warteschlange, Mindestverweildauer, Abgleich mit den Engines - Audit-Log für Keys und Modellwechsel - omega-agent meldet den belegten Speicher (nvidia-smi bzw. /proc/meminfo) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
c5d618ed09
16 files changed
+4289
No files matched your search
+202
@@ -0,0 +1,202 @@
|
||||
use std::{
|
||||
sync::Mutex,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use rand::RngCore;
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// SQLite-Datenbank. Die Zugriffe sind kurz, deshalb genügt eine Verbindung hinter einem Mutex.
|
||||
pub struct Db {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
pub struct ApiKey {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub prefix: String,
|
||||
pub created_at: i64,
|
||||
pub revoked: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Usage {
|
||||
pub key_id: i64,
|
||||
pub engine: &'static str,
|
||||
pub model: Option<String>,
|
||||
pub path: String,
|
||||
pub status: u16,
|
||||
pub prompt_tokens: Option<u64>,
|
||||
pub completion_tokens: Option<u64>,
|
||||
pub duration_ms: u64,
|
||||
}
|
||||
|
||||
pub fn now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn hash_key(key: &str) -> String {
|
||||
hex::encode(Sha256::digest(key.as_bytes()))
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn open(path: &str) -> Result<Self> {
|
||||
let conn = Connection::open(path)?;
|
||||
conn.execute_batch(
|
||||
"PRAGMA journal_mode = WAL;
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
key_hash TEXT NOT NULL UNIQUE,
|
||||
prefix TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS usage (
|
||||
id INTEGER PRIMARY KEY,
|
||||
ts INTEGER NOT NULL,
|
||||
key_id INTEGER NOT NULL REFERENCES api_keys(id),
|
||||
engine TEXT NOT NULL,
|
||||
model TEXT,
|
||||
path TEXT NOT NULL,
|
||||
status INTEGER NOT NULL,
|
||||
prompt_tokens INTEGER,
|
||||
completion_tokens INTEGER,
|
||||
duration_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS model_memory (
|
||||
node TEXT NOT NULL,
|
||||
engine TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
mb INTEGER NOT NULL,
|
||||
measured_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (node, engine, model)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
ts INTEGER NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
detail TEXT NOT NULL
|
||||
);",
|
||||
)?;
|
||||
Ok(Self { conn: Mutex::new(conn) })
|
||||
}
|
||||
|
||||
fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
|
||||
self.conn.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Legt einen Key an und gibt ihn im Klartext zurück. Gespeichert wird nur der Hash.
|
||||
pub fn create_key(&self, name: &str) -> Result<(i64, String)> {
|
||||
let mut bytes = [0u8; 24];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
let key = format!("omega-{}", hex::encode(bytes));
|
||||
let prefix = key[..14].to_string();
|
||||
let conn = self.conn();
|
||||
conn.execute(
|
||||
"INSERT INTO api_keys (name, key_hash, prefix, created_at) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![name, hash_key(&key), prefix, now()],
|
||||
)?;
|
||||
let id = conn.last_insert_rowid();
|
||||
drop(conn);
|
||||
self.audit("cli", "key.create", &format!("id={id} name={name}"))?;
|
||||
Ok((id, key))
|
||||
}
|
||||
|
||||
pub fn list_keys(&self) -> Result<Vec<ApiKey>> {
|
||||
let conn = self.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, name, prefix, created_at, revoked_at IS NOT NULL FROM api_keys ORDER BY id",
|
||||
)?;
|
||||
let keys = stmt
|
||||
.query_map([], |r| {
|
||||
Ok(ApiKey {
|
||||
id: r.get(0)?,
|
||||
name: r.get(1)?,
|
||||
prefix: r.get(2)?,
|
||||
created_at: r.get(3)?,
|
||||
revoked: r.get(4)?,
|
||||
})
|
||||
})?
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
pub fn revoke_key(&self, id: i64) -> Result<bool> {
|
||||
let changed = self.conn().execute(
|
||||
"UPDATE api_keys SET revoked_at = ?1 WHERE id = ?2 AND revoked_at IS NULL",
|
||||
params![now(), id],
|
||||
)?;
|
||||
if changed > 0 {
|
||||
self.audit("cli", "key.revoke", &format!("id={id}"))?;
|
||||
}
|
||||
Ok(changed > 0)
|
||||
}
|
||||
|
||||
/// Liefert die ID eines gültigen Keys.
|
||||
pub fn authenticate(&self, key: &str) -> Result<Option<i64>> {
|
||||
Ok(self
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT id FROM api_keys WHERE key_hash = ?1 AND revoked_at IS NULL",
|
||||
params![hash_key(key)],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn record_usage(&self, u: &Usage) -> Result<()> {
|
||||
self.conn().execute(
|
||||
"INSERT INTO usage (ts, key_id, engine, model, path, status, prompt_tokens,
|
||||
completion_tokens, duration_ms)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
params![
|
||||
now(),
|
||||
u.key_id,
|
||||
u.engine,
|
||||
u.model,
|
||||
u.path,
|
||||
u.status,
|
||||
u.prompt_tokens,
|
||||
u.completion_tokens,
|
||||
u.duration_ms
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn model_memory(&self, node: &str, engine: &str, model: &str) -> Result<Option<u64>> {
|
||||
Ok(self
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT mb FROM model_memory WHERE node = ?1 AND engine = ?2 AND model = ?3",
|
||||
params![node, engine, model],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn set_model_memory(&self, node: &str, engine: &str, model: &str, mb: u64) -> Result<()> {
|
||||
self.conn().execute(
|
||||
"INSERT INTO model_memory (node, engine, model, mb, measured_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT (node, engine, model) DO UPDATE SET mb = ?4, measured_at = ?5",
|
||||
params![node, engine, model, mb, now()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn audit(&self, actor: &str, action: &str, detail: &str) -> Result<()> {
|
||||
self.conn().execute(
|
||||
"INSERT INTO audit_log (ts, actor, action, detail) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![now(), actor, action, detail],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user