diff --git a/crates/nexus-api/tests/api.rs b/crates/nexus-api/tests/api.rs index ba0eded..b2670da 100644 --- a/crates/nexus-api/tests/api.rs +++ b/crates/nexus-api/tests/api.rs @@ -225,6 +225,7 @@ async fn gateway(delay_ms: u64, fail: bool) -> Gateway { "nur-bonsai", &Rights { models: vec!["bonsai".to_string()], + metrics: false, }, Priority::Normal, Priority::Normal, diff --git a/crates/nexus-store/migrations/0002_logging.sql b/crates/nexus-store/migrations/0002_logging.sql new file mode 100644 index 0000000..1bcf9aa --- /dev/null +++ b/crates/nexus-store/migrations/0002_logging.sql @@ -0,0 +1,6 @@ +-- Logging und Metriken (0.1.3): Gesamtdauer, Engine, Instanz und ob die +-- Antwort vorzeitig abbrach (Client weg). Die Token-Spalten gab es schon. +ALTER TABLE anfrage_log ADD COLUMN dauer_ms INTEGER; +ALTER TABLE anfrage_log ADD COLUMN engine TEXT; +ALTER TABLE anfrage_log ADD COLUMN instanz_id INTEGER; +ALTER TABLE anfrage_log ADD COLUMN abgebrochen INTEGER NOT NULL DEFAULT 0; diff --git a/crates/nexus-store/src/keys.rs b/crates/nexus-store/src/keys.rs index 2b97e56..e6a1624 100644 --- a/crates/nexus-store/src/keys.rs +++ b/crates/nexus-store/src/keys.rs @@ -11,12 +11,16 @@ use crate::{Store, db}; pub struct Rights { /// Erlaubte Modell-Namen; `*` erlaubt alle. pub models: Vec, + /// Darf `GET /gateway/v1/metrics` lesen. Ältere Keys ohne dieses Feld: nein. + #[serde(default)] + pub metrics: bool, } impl Default for Rights { fn default() -> Self { Self { models: vec!["*".to_string()], + metrics: false, } } } @@ -192,6 +196,7 @@ mod tests { fn rechte_pruefen_modellnamen() { let r = Rights { models: vec!["bonsai".to_string()], + metrics: false, }; assert!(r.allows("bonsai")); assert!(!r.allows("anderes")); diff --git a/crates/nexus-store/src/lib.rs b/crates/nexus-store/src/lib.rs index 92d9b0e..41e85d3 100644 --- a/crates/nexus-store/src/lib.rs +++ b/crates/nexus-store/src/lib.rs @@ -19,7 +19,10 @@ pub use logs::{AuditRow, RequestLogEntry, RequestLogRow}; pub use registry::{ModelEntry, NewLlm, StartPlan}; /// Alle Migrationen in Reihenfolge. Index 0 ergibt Schema-Version 1. -const MIGRATIONS: &[&str] = &[include_str!("../migrations/0001_init.sql")]; +const MIGRATIONS: &[&str] = &[ + include_str!("../migrations/0001_init.sql"), + include_str!("../migrations/0002_logging.sql"), +]; /// Schema-Version, die dieses Crate erzeugt. pub const LATEST_SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64; @@ -173,6 +176,29 @@ mod tests { assert_eq!(anzahl, 1); } + #[test] + fn datenbank_der_version_1_wird_mit_ihren_daten_auf_2_gehoben() { + let ordner = Testordner::neu(); + let pfad = ordner.0.join("nexus.db"); + { + // Eine Datenbank, wie sie Version 0.1.0 bis 0.1.2 angelegt haben. + let conn = rusqlite::Connection::open(&pfad).unwrap(); + conn.execute_batch(MIGRATIONS[0]).unwrap(); + conn.pragma_update(None, "user_version", 1).unwrap(); + conn.execute( + "INSERT INTO anfrage_log (zeit, korrelation, status) VALUES ('2026-11-09T10:00:00Z', 'req_alt', 200)", + [], + ) + .unwrap(); + } + let store = Store::open(&pfad).unwrap(); + assert_eq!(store.schema_version().unwrap(), 2); + let alt = &store.recent_requests(10).unwrap()[0]; + assert_eq!(alt.correlation, "req_alt"); + assert_eq!(alt.tokens_out, None); + assert!(!alt.aborted); + } + #[test] fn neuere_datenbank_wird_abgelehnt() { let ordner = Testordner::neu(); diff --git a/crates/nexus-store/src/logs.rs b/crates/nexus-store/src/logs.rs index b8e11c3..e063f61 100644 --- a/crates/nexus-store/src/logs.rs +++ b/crates/nexus-store/src/logs.rs @@ -17,6 +17,16 @@ pub struct RequestLogEntry { pub wait_ms: Option, /// Zeit bis zum Beginn der Antwort. pub latency_ms: Option, + /// Gesamtdauer bis zum Ende der Antwort (bei Streaming das Ende des Streams). + pub duration_ms: Option, + /// Aus der `usage`-Angabe der Engine; `None`, wenn sie keine liefert. + pub tokens_in: Option, + pub tokens_out: Option, + /// Name der Engine und Nummer der Instanz, die geantwortet hat. + pub engine: Option, + pub instance_id: Option, + /// Die Antwort wurde nicht zu Ende geliefert (Client getrennt). + pub aborted: bool, } /// Eine gelesene Zeile des Anfrage-Logs. @@ -29,6 +39,12 @@ pub struct RequestLogRow { pub status: i64, pub wait_ms: Option, pub latency_ms: Option, + pub duration_ms: Option, + pub tokens_in: Option, + pub tokens_out: Option, + pub engine: Option, + pub instance_id: Option, + pub aborted: bool, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -43,8 +59,9 @@ impl Store { pub fn log_request(&self, entry: &RequestLogEntry) -> Result<()> { self.connection() .execute( - "INSERT INTO anfrage_log (zeit, korrelation, api_key_id, model_id, status, wartezeit_ms, latenz_ms) - VALUES (?1, ?2, ?3, (SELECT id FROM model WHERE name = ?4), ?5, ?6, ?7)", + "INSERT INTO anfrage_log (zeit, korrelation, api_key_id, model_id, status, wartezeit_ms, latenz_ms, + dauer_ms, tokens_ein, tokens_aus, engine, instanz_id, abgebrochen) + VALUES (?1, ?2, ?3, (SELECT id FROM model WHERE name = ?4), ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)", ( now_iso8601(), &entry.correlation, @@ -53,6 +70,12 @@ impl Store { entry.status, entry.wait_ms.map(|v| v as i64), entry.latency_ms.map(|v| v as i64), + entry.duration_ms.map(|v| v as i64), + entry.tokens_in.map(|v| v as i64), + entry.tokens_out.map(|v| v as i64), + &entry.engine, + entry.instance_id.map(|v| v as i64), + entry.aborted as i64, ), ) .map_err(db)?; @@ -64,7 +87,8 @@ impl Store { let mut stmt = self .connection() .prepare( - "SELECT zeit, korrelation, api_key_id, model_id, status, wartezeit_ms, latenz_ms + "SELECT zeit, korrelation, api_key_id, model_id, status, wartezeit_ms, latenz_ms, + dauer_ms, tokens_ein, tokens_aus, engine, instanz_id, abgebrochen FROM anfrage_log ORDER BY id DESC LIMIT ?1", ) .map_err(db)?; @@ -78,12 +102,42 @@ impl Store { status: r.get(4)?, wait_ms: r.get(5)?, latency_ms: r.get(6)?, + duration_ms: r.get(7)?, + tokens_in: r.get(8)?, + tokens_out: r.get(9)?, + engine: r.get(10)?, + instance_id: r.get(11)?, + aborted: r.get::<_, i64>(12)? != 0, }) }) .map_err(db)?; rows.collect::>>().map_err(db) } + /// Löscht Anfrage-Log-Zeilen, die älter als `days` Tage sind. Liefert die + /// Zahl der gelöschten Zeilen. `0` Tage löscht nichts (unbegrenzt). + pub fn purge_requests_older_than(&self, days: u32) -> Result { + self.purge("anfrage_log", days) + } + + /// Wie `purge_requests_older_than`, für das Audit-Log. + pub fn purge_audit_older_than(&self, days: u32) -> Result { + self.purge("audit", days) + } + + fn purge(&self, table: &str, days: u32) -> Result { + if days == 0 { + return Ok(0); + } + // `zeit` ist ISO 8601 in UTC und sortiert deshalb als Text. + let sql = format!( + "DELETE FROM {table} WHERE zeit < strftime('%Y-%m-%dT%H:%M:%SZ', 'now', ?1)" + ); + self.connection() + .execute(&sql, [format!("-{days} days")]) + .map_err(db) + } + /// Hält eine administrative Aktion fest (Spezifikation, Abschnitt 9). /// `target` nennt das Ziel, zum Beispiel einen Key-Namen, nie den Key. pub fn audit(&self, actor: &str, action: &str, target: Option<&str>) -> Result<()> { @@ -131,6 +185,12 @@ mod tests { status: 200, wait_ms: Some(300), latency_ms: Some(320), + duration_ms: Some(900), + tokens_in: Some(12), + tokens_out: Some(34), + engine: Some("llama.cpp".to_string()), + instance_id: Some(1), + aborted: false, } } @@ -192,4 +252,45 @@ mod tests { assert_eq!(rows[1].target.as_deref(), Some("meinkey")); assert_eq!(rows[1].actor, "cli"); } + + #[test] + fn aufbewahrung_loescht_nur_alte_zeilen_und_null_tage_nichts() { + let store = Store::open_in_memory().unwrap(); + store.log_request(&eintrag(None, None)).unwrap(); + store.log_request(&eintrag(None, None)).unwrap(); + store.audit("cli", "a", None).unwrap(); + // Eine Zeile künstlich altern lassen. + store + .connection() + .execute( + "UPDATE anfrage_log SET zeit = '2020-01-01T00:00:00Z' WHERE id = 1", + [], + ) + .unwrap(); + store + .connection() + .execute("UPDATE audit SET zeit = '2020-01-01T00:00:00Z'", []) + .unwrap(); + assert_eq!(store.purge_requests_older_than(0).unwrap(), 0); + assert_eq!(store.purge_audit_older_than(0).unwrap(), 0); + assert_eq!(store.purge_requests_older_than(90).unwrap(), 1); + assert_eq!(store.recent_requests(10).unwrap().len(), 1); + assert_eq!(store.purge_audit_older_than(90).unwrap(), 1); + assert!(store.recent_audit(10).unwrap().is_empty()); + } + + #[test] + fn tokens_engine_und_dauer_werden_gespeichert() { + let store = Store::open_in_memory().unwrap(); + let mut e = eintrag(None, None); + e.aborted = true; + store.log_request(&e).unwrap(); + let row = &store.recent_requests(1).unwrap()[0]; + assert_eq!(row.tokens_in, Some(12)); + assert_eq!(row.tokens_out, Some(34)); + assert_eq!(row.duration_ms, Some(900)); + assert_eq!(row.engine.as_deref(), Some("llama.cpp")); + assert_eq!(row.instance_id, Some(1)); + assert!(row.aborted); + } } diff --git a/crates/nexus/src/admin.rs b/crates/nexus/src/admin.rs index 77553b9..870f2e8 100644 --- a/crates/nexus/src/admin.rs +++ b/crates/nexus/src/admin.rs @@ -52,7 +52,7 @@ fn key_create(args: &[String]) -> Result<(), String> { "models", "config", ], - &[], + &["metrics"], )?; let name = flags.require("name")?; let default = priority(&flags, "default-priority", Priority::Normal)?; @@ -73,7 +73,15 @@ fn key_create(args: &[String]) -> Result<(), String> { let config = load_config(&flags)?; let store = open_store(&config)?; let key = store - .create_api_key(name, &Rights { models }, default, max) + .create_api_key( + name, + &Rights { + models, + metrics: flags.has("metrics"), + }, + default, + max, + ) .map_err(|e| e.to_string())?; audit(&store, "key.create", name)?; println!("Key \"{name}\" angelegt. Er wird nur jetzt angezeigt, danach nie wieder:\n");