use std::{ sync::Mutex, time::{SystemTime, UNIX_EPOCH}, }; use anyhow::{Result, bail}; use chrono::{DateTime, Local}; use rand::RngCore; use rusqlite::{Connection, OptionalExtension, params}; use sha2::{Digest, Sha256}; use crate::{ quota::{Counter, Denial, Limits, Period, Quota}, schedule::{self, Entry, Kind, TimeSpec, Weekly}, }; /// SQLite-Datenbank. Die Zugriffe sind kurz, deshalb genügt eine Verbindung hinter einem Mutex. pub struct Db { conn: Mutex, /// Laut Konfiguration immer Administrator (first_admin) pub(crate) config_admin: std::sync::OnceLock, } #[derive(Clone, Debug, serde::Serialize)] pub struct ApiKey { pub id: i64, /// Inhaber; ohne Inhaber hat ihn der Betreiber auf dem Server angelegt pub user_id: Option, pub name: String, pub prefix: String, pub revoked: bool, /// Super-Keys dürfen unabhängig von allen Einschränkungen immer alles pub is_super: bool, /// Kontingent, gegen das der Key abgerechnet wird; ohne ist er unbegrenzt pub quota_id: Option, } /// Ein angemeldeter Key #[derive(Clone, Debug)] pub struct Caller { pub key_id: i64, pub is_super: bool, pub quota_id: Option, /// Inhaber des Keys pub user_id: Option, pub is_admin: bool, /// Gruppen des Inhabers pub groups: Vec, } #[derive(Default)] pub struct Usage { pub key_id: i64, pub engine: &'static str, pub model: Option, pub path: String, pub status: u16, pub prompt_tokens: Option, pub completion_tokens: Option, pub duration_ms: u64, pub quota_id: Option, pub user_id: Option, /// Der Client hat die Antwort nicht vollständig erhalten; dann werden keine Token gebucht. pub aborted: bool, /// Beginn einer gezählten Anfrage; ihre Token werden den Zeiträumen dieses Zeitpunkts gebucht pub counted_at: Option>, } /// Wessen Verbrauch gezählt wird #[derive(Clone, Copy)] pub enum Scope { Key(i64), /// Kontingent und Benutzer: Die Grenzen eines Gruppenkontingents gelten je Mitglied. /// Keys ohne Inhaber zählen unter Benutzer 0. Quota(i64, i64), /// Alle Anfragen zusammen, für das öffentliche Dashboard System, } impl Scope { fn parts(self) -> (&'static str, i64, i64) { match self { Scope::Key(id) => ("key", id, 0), Scope::Quota(id, user) => ("quota", id, user), Scope::System => ("system", 0, 0), } } } 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 { 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 schedule ( id INTEGER PRIMARY KEY, kind TEXT NOT NULL, node TEXT, engine TEXT, model TEXT, subjects TEXT, valid_from INTEGER, valid_until INTEGER, days TEXT, time_start TEXT, time_end TEXT, every INTEGER NOT NULL DEFAULT 1, note TEXT NOT NULL, created_at INTEGER NOT NULL, created_by INTEGER ); CREATE TABLE IF NOT EXISTS pool_out ( node TEXT PRIMARY KEY, reason TEXT NOT NULL, since INTEGER NOT NULL, by_user TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS quotas ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, valid_from INTEGER, valid_until INTEGER, days TEXT, time_start TEXT, time_end TEXT, models TEXT, tokens_hour INTEGER, tokens_day INTEGER, tokens_week INTEGER, tokens_month INTEGER, tokens_total INTEGER, requests_hour INTEGER, requests_day INTEGER, requests_week INTEGER, requests_month INTEGER, requests_total INTEGER, note TEXT NOT NULL, created_at INTEGER NOT NULL, shared INTEGER NOT NULL DEFAULT 0 ); -- Verbrauch je Key bzw. Kontingent und Zeitraum (z. B. day:2026-11-20). Die Zähler -- bleiben erhalten, wenn alte Einträge in usage gelöscht werden. CREATE TABLE IF NOT EXISTS usage_counters ( scope TEXT NOT NULL, scope_id INTEGER NOT NULL, user_id INTEGER NOT NULL DEFAULT 0, period TEXT NOT NULL, requests INTEGER NOT NULL DEFAULT 0, prompt_tokens INTEGER NOT NULL DEFAULT 0, completion_tokens INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (scope, scope_id, user_id, period) ); CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL UNIQUE, email TEXT, role TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1, blocked INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS groups ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, owner_id INTEGER REFERENCES users(id), created_at INTEGER NOT NULL ); -- Über den Benutzernamen, damit auch Personen ohne Konto Mitglied sein können CREATE TABLE IF NOT EXISTS group_members ( group_id INTEGER NOT NULL REFERENCES groups(id), username TEXT NOT NULL, added_at INTEGER NOT NULL, PRIMARY KEY (group_id, username) ); CREATE INDEX IF NOT EXISTS usage_ts ON usage (ts); -- Aufzeichnungen für Debugging; die Einträge sind verschlüsselt, der Schlüssel der -- Aufzeichnung liegt mit dem Hauptschlüssel verschlüsselt in wrapped_key. CREATE TABLE IF NOT EXISTS recordings ( id INTEGER PRIMARY KEY, key_id INTEGER NOT NULL REFERENCES api_keys(id), user_id INTEGER NOT NULL REFERENCES users(id), count INTEGER NOT NULL, reserved INTEGER NOT NULL, written INTEGER NOT NULL, started_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, ended_at INTEGER, end_reason TEXT, ready_until INTEGER, downloaded_at INTEGER, deleted_at INTEGER, wrapped_key BLOB ); CREATE TABLE IF NOT EXISTS recording_entries ( recording_id INTEGER NOT NULL REFERENCES recordings(id), seq INTEGER NOT NULL, ts INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (recording_id, seq) ); -- Benachrichtigungen, bis es einen Mailversand gibt CREATE TABLE IF NOT EXISTS outbox ( id INTEGER PRIMARY KEY, ts INTEGER NOT NULL, to_addr TEXT, subject TEXT NOT NULL, body TEXT NOT NULL, sent_at INTEGER ); -- Proben der Auslastung je Rechner für das öffentliche Dashboard CREATE TABLE IF NOT EXISTS utilization ( ts INTEGER NOT NULL, node TEXT NOT NULL, budget_mb INTEGER, used_mb INTEGER NOT NULL, loaded INTEGER NOT NULL, in_flight INTEGER NOT NULL, waiting INTEGER NOT NULL, PRIMARY KEY (ts, node) ); -- Sitzungen der Verwaltungs-API; gespeichert ist nur der Hash des Tokens CREATE TABLE IF NOT EXISTS sessions ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), token_hash TEXT NOT NULL UNIQUE, prefix TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER, note TEXT NOT NULL ); 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 );", )?; migrate(&conn)?; Ok(Self { conn: Mutex::new(conn), config_admin: Default::default() }) } pub(crate) 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, actor: &str, name: &str, is_super: bool, quota_id: Option, user_id: Option, ) -> Result<(i64, String)> { if is_super && quota_id.is_some() { bail!("Super-Keys haben kein Kontingent"); } if let Some(id) = quota_id && self.quota(id)?.is_none() { bail!("kein Kontingent mit ID {id}"); } 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, is_super, quota_id, user_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", params![name, hash_key(&key), prefix, now(), is_super, quota_id, user_id], )?; let id = conn.last_insert_rowid(); drop(conn); let owner = match user_id { Some(u) => self.user(u)?.map(|u| u.username).unwrap_or_else(|| format!("#{u}")), None => "den Betreiber".into(), }; let kind = match (is_super, quota_id) { (true, _) => "Super-Key".to_string(), (false, Some(q)) => format!("Kontingent »{}«", self.quota(q)?.map(|q| q.name).unwrap_or_default()), (false, None) => "unbegrenzt".into(), }; self.audit(actor, "key.create", &format!("Key »{name}« (#{id}) für {owner}, {kind}"))?; Ok((id, key)) } pub fn list_keys(&self) -> Result> { let conn = self.conn(); let mut stmt = conn.prepare( "SELECT id, name, prefix, revoked_at IS NOT NULL, is_super, quota_id, user_id 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)?, revoked: r.get(3)?, is_super: r.get(4)?, quota_id: r.get(5)?, user_id: r.get(6)?, }) })? .collect::>()?; Ok(keys) } pub fn revoke_key(&self, actor: &str, id: i64) -> Result { let name = self.key(id)?.map(|k| k.name).unwrap_or_default(); 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(actor, "key.revoke", &format!("Key »{name}« (#{id})"))?; } Ok(changed > 0) } /// Prüft einen Key. Widerrufene Keys gelten nicht, ebenso wenig Keys gesperrter oder /// deaktivierter Benutzer; der Fehler nennt den Grund. pub fn authenticate(&self, key: &str) -> Result> { type Row = (i64, bool, Option, Option, Option, Option, Option, Option); let row: Option = self .conn() .query_row( "SELECT k.id, k.is_super, k.quota_id, k.user_id, u.username, u.role, u.active, u.blocked FROM api_keys k LEFT JOIN users u ON u.id = k.user_id WHERE k.key_hash = ?1 AND k.revoked_at IS NULL", params![hash_key(key)], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?)), ) .optional()?; let Some((key_id, is_super, quota_id, user_id, username, role, active, blocked)) = row else { return Ok(Err("ungültiger oder widerrufener API-Key")); }; if blocked == Some(true) { return Ok(Err("der Benutzer dieses Keys ist gesperrt")); } if active == Some(false) { return Ok(Err("das Konto dieses Keys ist deaktiviert")); } let groups = match &username { Some(name) => self.groups_of(name)?.into_iter().map(|g| g.id).collect(), None => Vec::new(), }; Ok(Ok(Caller { key_id, is_super, quota_id, user_id, is_admin: role.as_deref() == Some("admin"), groups })) } pub fn key(&self, id: i64) -> Result> { Ok(self.list_keys()?.into_iter().find(|k| k.id == id)) } 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, quota_id, user_id, aborted) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)", params![ now(), u.key_id, u.engine, u.model, u.path, u.status, u.prompt_tokens, u.completion_tokens, u.duration_ms, u.quota_id, u.user_id, u.aborted ], )?; Ok(()) } pub fn model_memory(&self, node: &str, engine: &str, model: &str) -> Result> { 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()?) } /// Größte Messung des Modells auf irgendeinem Rechner pub fn model_memory_any(&self, engine: &str, model: &str) -> Result> { Ok(self.conn().query_row( "SELECT max(mb) FROM model_memory WHERE engine = ?1 AND model = ?2", params![engine, model], |r| r.get(0), )?) } 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 add_schedule(&self, actor: &str, e: &Entry) -> Result { let conn = self.conn(); conn.execute( "INSERT INTO schedule (kind, note, created_at, created_by) VALUES (?1, ?2, ?3, ?4)", params![e.kind_name(), e.note, now(), e.created_by], )?; let id = conn.last_insert_rowid(); drop(conn); self.write_schedule(id, e)?; self.audit( actor, "schedule.add", &format!("{} {}, {} (#{id})", e.kind_label(), e.subject(), e.time.describe()), )?; Ok(id) } pub fn update_schedule(&self, actor: &str, e: &Entry) -> Result<()> { self.write_schedule(e.id, e)?; self.audit( actor, "schedule.update", &format!("{} {}, {} (#{})", e.kind_label(), e.subject(), e.time.describe(), e.id), ) } /// Art, Gegenstand, Zeit und Anmerkung eines bestehenden Eintrags setzen fn write_schedule(&self, id: i64, e: &Entry) -> Result<()> { let (days, start, end, every) = match &e.time.weekly { Some(w) => ( Some(schedule::days_str(&w.days)), Some(w.start.format("%H:%M").to_string()), Some(w.end.format("%H:%M").to_string()), w.every, ), None => (None, None, None, 1), }; let (node, engine, model, subjects) = match &e.kind { Kind::Pin { node, engine, model } => (Some(node), Some(engine), Some(model), None), Kind::Exclusive { keys, users, groups } => { let subjects = serde_json::json!({ "keys": keys, "users": users, "groups": groups }); (None, None, None, Some(subjects.to_string())) } Kind::Window { models } => (None, None, None, Some(serde_json::to_string(models)?)), Kind::Maintenance { node } => (Some(node), None, None, None), }; self.conn().execute( "UPDATE schedule SET kind = ?2, node = ?3, engine = ?4, model = ?5, subjects = ?6, valid_from = ?7, valid_until = ?8, days = ?9, time_start = ?10, time_end = ?11, every = ?12, note = ?13 WHERE id = ?1", params![id, e.kind_name(), node, engine, model, subjects, e.time.from, e.time.until, days, start, end, every, e.note], )?; Ok(()) } pub fn list_schedule(&self) -> Result> { let conn = self.conn(); let mut stmt = conn.prepare( "SELECT id, kind, node, engine, model, subjects, valid_from, valid_until, days, time_start, time_end, note, every, created_by FROM schedule ORDER BY id", )?; type Row = ( i64, String, Option, Option, Option, Option, Option, Option, Option, Option, Option, String, u32, Option, ); let rows = stmt.query_map([], |r| { Ok(( r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?, r.get(10)?, r.get(11)?, r.get(12)?, r.get(13)?, )) })?; let mut list = Vec::new(); for row in rows { let (id, kind, node, engine, model, subjects, from, until, days, start, end, note, every, created_by): Row = row?; let subjects = subjects.unwrap_or_else(|| "[]".into()); let kind = match kind.as_str() { "pin" => Kind::Pin { node: node.unwrap_or_default(), engine: engine.unwrap_or_default(), model: model.unwrap_or_default(), }, "exklusiv" => { // Früher eine Liste von Keys, jetzt Keys, Benutzer und Gruppen let v: serde_json::Value = serde_json::from_str(&subjects)?; let ids = |v: Option<&serde_json::Value>| -> Vec { v.and_then(serde_json::Value::as_array) .map(|a| a.iter().filter_map(serde_json::Value::as_i64).collect()) .unwrap_or_default() }; if v.is_array() { Kind::Exclusive { keys: ids(Some(&v)), users: Vec::new(), groups: Vec::new() } } else { Kind::Exclusive { keys: ids(v.get("keys")), users: ids(v.get("users")), groups: ids(v.get("groups")) } } } "fenster" => Kind::Window { models: serde_json::from_str(&subjects)? }, "wartung" => Kind::Maintenance { node: node.unwrap_or_default() }, other => anyhow::bail!("Zeitplan-Eintrag {id}: unbekannte Art {other}"), }; let weekly = match (days, start, end) { (Some(days), Some(start), Some(end)) => { let (start, end) = schedule::parse_time_range(&format!("{start}-{end}"))?; Some(Weekly { days: schedule::parse_days(&days)?, start, end, every }) } _ => None, }; list.push(Entry { id, kind, time: TimeSpec { from, until, weekly }, note, created_by }); } Ok(list) } pub fn remove_schedule(&self, actor: &str, id: i64) -> Result { let changed = self.conn().execute("DELETE FROM schedule WHERE id = ?1", params![id])?; if changed > 0 { self.audit(actor, "schedule.remove", &format!("Eintrag #{id}"))?; } Ok(changed > 0) } /// Rechner von Hand aus dem Pool nehmen; bleibt so bis pool_in pub fn pool_out(&self, actor: &str, node: &str, reason: &str) -> Result<()> { self.conn().execute( "INSERT INTO pool_out (node, reason, since, by_user) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (node) DO UPDATE SET reason = ?2", params![node, reason, now(), actor], )?; let why = if reason.is_empty() { String::new() } else { format!(": {reason}") }; self.audit(actor, "node.out", &format!("{node} aus dem Pool genommen{why}")) } /// Liefert, ob der Rechner herausgenommen war pub fn pool_in(&self, actor: &str, node: &str) -> Result { let changed = self.conn().execute("DELETE FROM pool_out WHERE node = ?1", params![node])?; if changed > 0 { self.audit(actor, "node.in", &format!("{node} wieder im Pool"))?; } Ok(changed > 0) } pub fn pool_out_list(&self) -> Result> { let conn = self.conn(); let mut stmt = conn.prepare("SELECT node, reason, since, by_user FROM pool_out ORDER BY node")?; let rows = stmt.query_map([], |r| Ok(PoolOut { node: r.get(0)?, reason: r.get(1)?, since: r.get(2)?, by: r.get(3)? }))?; Ok(rows.collect::>()?) } pub fn set_key_quota(&self, actor: &str, key_id: i64, quota_id: Option) -> Result<()> { if let Some(id) = quota_id && self.quota(id)?.is_none() { bail!("kein Kontingent mit ID {id}"); } let changed = self.conn().execute( "UPDATE api_keys SET quota_id = ?1 WHERE id = ?2 AND is_super = 0", params![quota_id, key_id], )?; if changed == 0 { bail!("kein Key mit ID {key_id}, oder es ist ein Super-Key"); } let quota = match quota_id { Some(q) => format!("Kontingent »{}«", self.quota(q)?.map(|q| q.name).unwrap_or_default()), None => "unbegrenzt".into(), }; self.audit(actor, "key.quota", &format!("Key #{key_id}: {quota}")) } pub fn create_quota(&self, actor: &str, q: &Quota) -> Result { let (days, start, end, every) = match &q.time.weekly { Some(w) => ( Some(schedule::days_str(&w.days)), Some(w.start.format("%H:%M").to_string()), Some(w.end.format("%H:%M").to_string()), w.every, ), None => (None, None, None, 1), }; let models = q.models.as_ref().map(serde_json::to_string).transpose()?; let limits: Vec> = Period::ALL .iter() .map(|p| q.tokens.get(*p)) .chain(Period::ALL.iter().map(|p| q.requests.get(*p))) .collect(); let conn = self.conn(); conn.execute( "INSERT INTO quotas (name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, created_at, owner_id, group_id, user_id, shared, every) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24)", params![ q.name, q.time.from, q.time.until, days, start, end, models, limits[0], limits[1], limits[2], limits[3], limits[4], limits[5], limits[6], limits[7], limits[8], limits[9], q.note, now(), q.owner_id, q.group_id, q.user_id, q.shared, every ], )?; let id = conn.last_insert_rowid(); drop(conn); let target = match (q.group_id, q.user_id) { (Some(g), _) => format!(" für Gruppe {}", self.group(g)?.map(|g| g.name).unwrap_or_default()), (_, Some(u)) => format!(" für {}", self.user(u)?.map(|u| u.username).unwrap_or_default()), _ => String::new(), }; self.audit(actor, "quota.create", &format!("Kontingent »{}« (#{id}){target}: {}", q.name, q.describe()))?; Ok(id) } fn quotas_where(&self, filter: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { let conn = self.conn(); let mut stmt = conn.prepare(&format!( "SELECT id, name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, owner_id, group_id, user_id, shared, every FROM quotas {filter} ORDER BY id" ))?; let mut rows = stmt.query(args)?; let mut list = Vec::new(); while let Some(r) = rows.next()? { let weekly = match (r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, Option>(6)?) { (Some(days), Some(start), Some(end)) => { let (start, end) = schedule::parse_time_range(&format!("{start}-{end}"))?; Some(Weekly { days: schedule::parse_days(&days)?, start, end, every: r.get(23)? }) } _ => None, }; let models: Option = r.get(7)?; let (mut tokens, mut requests) = (Limits::default(), Limits::default()); for (i, p) in Period::ALL.iter().enumerate() { tokens.set(*p, r.get(8 + i)?); requests.set(*p, r.get(13 + i)?); } list.push(Quota { id: r.get(0)?, name: r.get(1)?, time: TimeSpec { from: r.get(2)?, until: r.get(3)?, weekly }, models: models.map(|m| serde_json::from_str(&m)).transpose()?, tokens, requests, note: r.get(18)?, owner_id: r.get(19)?, group_id: r.get(20)?, user_id: r.get(21)?, shared: r.get(22)?, }); } Ok(list) } pub fn quota(&self, id: i64) -> Result> { Ok(self.quotas_where("WHERE id = ?1", &[&id])?.pop()) } pub fn list_quotas(&self) -> Result> { self.quotas_where("", &[]) } /// Nur ein Kontingent, an dem keine Keys mehr hängen, kann entfernt werden. pub fn remove_quota(&self, actor: &str, id: i64) -> Result<()> { let name = self.quota(id)?.map(|q| q.name).unwrap_or_default(); let conn = self.conn(); let keys: i64 = conn.query_row("SELECT count(*) FROM api_keys WHERE quota_id = ?1", params![id], |r| r.get(0))?; if keys > 0 { bail!("am Kontingent {id} hängen noch {keys} Keys"); } if conn.execute("DELETE FROM quotas WHERE id = ?1", params![id])? == 0 { bail!("kein Kontingent mit ID {id}"); } conn.execute("DELETE FROM usage_counters WHERE scope = 'quota' AND scope_id = ?1", params![id])?; drop(conn); self.audit(actor, "quota.remove", &format!("Kontingent »{name}« (#{id})")) } /// Verbrauch in den Zeiträumen, in die t fällt fn counters(conn: &Connection, scope: Scope, t: DateTime) -> Result> { let (scope, id, user) = scope.parts(); let mut stmt = conn.prepare_cached( "SELECT requests, prompt_tokens, completion_tokens FROM usage_counters WHERE scope = ?1 AND scope_id = ?2 AND user_id = ?3 AND period = ?4", )?; Period::ALL .iter() .map(|p| { let c = stmt .query_row(params![scope, id, user, p.key(t)], |r| { Ok(Counter { requests: r.get(0)?, prompt_tokens: r.get(1)?, completion_tokens: r.get(2)? }) }) .optional()? .unwrap_or_default(); Ok((*p, c)) }) .collect() } pub fn usage_of(&self, scope: Scope, t: DateTime) -> Result> { Self::counters(&self.conn(), scope, t) } /// Verbrauch eines Kontingents je Benutzer in einem Zeitraum pub fn quota_usage_by_user(&self, quota_id: i64, period: Period, t: DateTime) -> Result> { let conn = self.conn(); let mut stmt = conn.prepare( "SELECT user_id, requests, prompt_tokens, completion_tokens FROM usage_counters WHERE scope = 'quota' AND scope_id = ?1 AND period = ?2 ORDER BY user_id", )?; let rows = stmt .query_map(params![quota_id, period.key(t)], |r| { Ok((r.get(0)?, Counter { requests: r.get(1)?, prompt_tokens: r.get(2)?, completion_tokens: r.get(3)? })) })? .collect::>()?; Ok(rows) } /// Addiert (oder bei negativen Werten subtrahiert) in allen Zeiträumen von t. fn add(conn: &Connection, scope: Scope, t: DateTime, requests: i64, prompt: i64, completion: i64) -> Result<()> { let (scope, id, user) = scope.parts(); let mut stmt = conn.prepare_cached( "INSERT INTO usage_counters (scope, scope_id, user_id, period, requests, prompt_tokens, completion_tokens) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT (scope, scope_id, user_id, period) DO UPDATE SET requests = requests + excluded.requests, prompt_tokens = prompt_tokens + excluded.prompt_tokens, completion_tokens = completion_tokens + excluded.completion_tokens", )?; for p in Period::ALL { stmt.execute(params![scope, id, user, p.key(t), requests, prompt, completion])?; } Ok(()) } /// Wo eine Anfrage gezählt wird: im System, beim Key und beim Kontingent je Person. Ein /// gemeinsames Gruppenkontingent zählt zusätzlich im Topf der Gruppe (Benutzer 0). fn scopes(conn: &Connection, key_id: i64, user_id: Option, quota_id: Option) -> Result> { let user = user_id.unwrap_or(0); let mut scopes = vec![Scope::System, Scope::Key(key_id)]; if let Some(q) = quota_id { scopes.push(Scope::Quota(q, user)); let shared: bool = conn .query_row("SELECT shared FROM quotas WHERE id = ?1", params![q], |r| r.get(0)) .optional()? .unwrap_or(false); if shared && user != 0 { scopes.push(Scope::Quota(q, 0)); } } Ok(scopes) } /// Prüft das Kontingent und zählt die Anfrage, in einer Transaktion, damit gleichzeitige /// Anfragen die Grenzen nicht gemeinsam überschreiten. `quota` ist None für Keys ohne /// Kontingent und für Super-Keys; gezählt wird beim Key trotzdem. pub fn begin_request( &self, key_id: i64, user_id: Option, quota: Option<&Quota>, t: DateTime, ) -> Result> { let mut conn = self.conn(); let tx = conn.transaction()?; if let Some(q) = quota && let Err(denial) = q.check_usage(&Self::counters(&tx, Scope::Quota(q.id, if q.shared { 0 } else { user_id.unwrap_or(0) }), t)?, t) { return Ok(Err(denial)); } for scope in Self::scopes(&tx, key_id, user_id, quota.map(|q| q.id))? { Self::add(&tx, scope, t, 1, 0, 0)?; } tx.commit()?; Ok(Ok(())) } /// Nimmt eine gezählte Anfrage zurück, die die Engine nie erreicht hat (z. B. Modell nicht ladbar). pub fn refund_request(&self, key_id: i64, user_id: Option, quota_id: Option, t: DateTime) -> Result<()> { let mut conn = self.conn(); let tx = conn.transaction()?; for scope in Self::scopes(&tx, key_id, user_id, quota_id)? { Self::add(&tx, scope, t, -1, 0, 0)?; } Ok(tx.commit()?) } /// Bucht die Token einer beendeten Anfrage in die Zeiträume ihres Beginns. pub fn book_tokens( &self, key_id: i64, user_id: Option, quota_id: Option, t: DateTime, prompt: u64, completion: u64, ) -> Result<()> { let mut conn = self.conn(); let tx = conn.transaction()?; for scope in Self::scopes(&tx, key_id, user_id, quota_id)? { Self::add(&tx, scope, t, 0, prompt as i64, completion as i64)?; } Ok(tx.commit()?) } /// Löscht Einzeleinträge der Nutzung, die älter als `days` Tage sind. Die Zähler der /// Kontingente und Keys bleiben unberührt. pub fn prune_usage(&self, actor: &str, days: u32) -> Result { let cutoff = now() - i64::from(days) * 86_400; let deleted = self.conn().execute("DELETE FROM usage WHERE ts < ?1", params![cutoff])?; self.audit(actor, "usage.prune", &format!("{deleted} Einträge älter als {days} Tage gelöscht"))?; Ok(deleted) } /// Die letzten Einträge des Audit-Logs, neueste zuerst pub fn audit_log(&self, limit: u32) -> Result> { let conn = self.conn(); let mut stmt = conn.prepare("SELECT ts, actor, action, detail FROM audit_log ORDER BY id DESC LIMIT ?1")?; let rows = stmt .query_map(params![limit], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))? .collect::>()?; Ok(rows) } 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(()) } } fn has_column(conn: &Connection, table: &str, column: &str) -> Result { let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?; let names: Vec = stmt.query_map([], |r| r.get(1))?.collect::>()?; Ok(names.iter().any(|n| n == column)) } /// Ältere Datenbanken auf den aktuellen Stand bringen fn migrate(conn: &Connection) -> Result<()> { if !has_column(conn, "users", "password_hash")? { conn.execute("ALTER TABLE users ADD COLUMN password_hash TEXT", [])?; } if !has_column(conn, "api_keys", "is_super")? { conn.execute("ALTER TABLE api_keys ADD COLUMN is_super INTEGER NOT NULL DEFAULT 0", [])?; } if !has_column(conn, "api_keys", "quota_id")? { conn.execute("ALTER TABLE api_keys ADD COLUMN quota_id INTEGER REFERENCES quotas(id)", [])?; } if !has_column(conn, "usage", "quota_id")? { conn.execute("ALTER TABLE usage ADD COLUMN quota_id INTEGER", [])?; } if !has_column(conn, "usage", "user_id")? { conn.execute("ALTER TABLE usage ADD COLUMN user_id INTEGER", [])?; } if !has_column(conn, "usage", "aborted")? { conn.execute("ALTER TABLE usage ADD COLUMN aborted INTEGER NOT NULL DEFAULT 0", [])?; } if !has_column(conn, "api_keys", "user_id")? { conn.execute("ALTER TABLE api_keys ADD COLUMN user_id INTEGER REFERENCES users(id)", [])?; } for table in ["schedule", "quotas"] { if !has_column(conn, table, "every")? { conn.execute(&format!("ALTER TABLE {table} ADD COLUMN every INTEGER NOT NULL DEFAULT 1"), [])?; } } if !has_column(conn, "schedule", "created_by")? { conn.execute("ALTER TABLE schedule ADD COLUMN created_by INTEGER", [])?; } if !has_column(conn, "quotas", "shared")? { conn.execute("ALTER TABLE quotas ADD COLUMN shared INTEGER NOT NULL DEFAULT 0", [])?; } for column in ["owner_id", "group_id", "user_id"] { if !has_column(conn, "quotas", column)? { conn.execute(&format!("ALTER TABLE quotas ADD COLUMN {column} INTEGER"), [])?; } } // Die Zähler bekamen mit den Gruppenkontingenten eine Spalte für den Benutzer, die zum // Primärschlüssel gehört; SQLite kann den nur durch Neuanlegen ändern. if !has_column(conn, "usage_counters", "user_id")? { conn.execute_batch( "ALTER TABLE usage_counters RENAME TO usage_counters_old; CREATE TABLE usage_counters ( scope TEXT NOT NULL, scope_id INTEGER NOT NULL, user_id INTEGER NOT NULL DEFAULT 0, period TEXT NOT NULL, requests INTEGER NOT NULL DEFAULT 0, prompt_tokens INTEGER NOT NULL DEFAULT 0, completion_tokens INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (scope, scope_id, user_id, period) ); INSERT INTO usage_counters (scope, scope_id, user_id, period, requests, prompt_tokens, completion_tokens) SELECT scope, scope_id, 0, period, requests, prompt_tokens, completion_tokens FROM usage_counters_old; DROP TABLE usage_counters_old;", )?; } // Pins lagen bis zum gemeinsamen Zeitplan in einer eigenen Tabelle. let has_pins: bool = conn.query_row( "SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = 'pins'", [], |r| r.get(0), )?; if has_pins { conn.execute_batch( "INSERT INTO schedule (kind, node, engine, model, valid_from, valid_until, days, time_start, time_end, note, created_at) SELECT 'pin', node, engine, model, valid_from, valid_until, days, time_start, time_end, note, created_at FROM pins; DROP TABLE pins;", )?; } Ok(()) } /// Ein von Hand aus dem Pool genommener Rechner #[derive(Clone, Debug, serde::Serialize)] pub struct PoolOut { pub node: String, pub reason: String, pub since: i64, pub by: String, }