feat: JSON-Logging mit Correlation-ID, Anfrage-Log und Audit (M2.4)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
194
crates/nexus-store/src/logs.rs
Normal file
194
crates/nexus-store/src/logs.rs
Normal file
@ -0,0 +1,194 @@
|
||||
//! Anfrage-Log und Audit-Log. Beide enthalten nie Prompts, Antworten oder
|
||||
//! Schlüssel, nur Metadaten.
|
||||
|
||||
use nexus_core::{Result, now_iso8601};
|
||||
|
||||
use crate::{Store, db};
|
||||
|
||||
/// Eine Zeile des Anfrage-Logs.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RequestLogEntry {
|
||||
pub correlation: String,
|
||||
pub api_key_id: Option<i64>,
|
||||
/// Name des Modells; wird zur ID aufgelöst, falls es das Modell gibt.
|
||||
pub model: Option<String>,
|
||||
pub status: u16,
|
||||
/// Zeit bis ein Modell bereit war (Laden, später auch Warteschlange).
|
||||
pub wait_ms: Option<u64>,
|
||||
/// Zeit bis zum Beginn der Antwort.
|
||||
pub latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
/// Eine gelesene Zeile des Anfrage-Logs.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RequestLogRow {
|
||||
pub time: String,
|
||||
pub correlation: String,
|
||||
pub api_key_id: Option<i64>,
|
||||
pub model_id: Option<i64>,
|
||||
pub status: i64,
|
||||
pub wait_ms: Option<i64>,
|
||||
pub latency_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AuditRow {
|
||||
pub time: String,
|
||||
pub actor: String,
|
||||
pub action: String,
|
||||
pub target: Option<String>,
|
||||
}
|
||||
|
||||
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)",
|
||||
(
|
||||
now_iso8601(),
|
||||
&entry.correlation,
|
||||
entry.api_key_id,
|
||||
&entry.model,
|
||||
entry.status,
|
||||
entry.wait_ms.map(|v| v as i64),
|
||||
entry.latency_ms.map(|v| v as i64),
|
||||
),
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Die letzten `limit` Anfragen, neueste zuerst.
|
||||
pub fn recent_requests(&self, limit: u32) -> Result<Vec<RequestLogRow>> {
|
||||
let mut stmt = self
|
||||
.connection()
|
||||
.prepare(
|
||||
"SELECT zeit, korrelation, api_key_id, model_id, status, wartezeit_ms, latenz_ms
|
||||
FROM anfrage_log ORDER BY id DESC LIMIT ?1",
|
||||
)
|
||||
.map_err(db)?;
|
||||
let rows = stmt
|
||||
.query_map([limit], |r| {
|
||||
Ok(RequestLogRow {
|
||||
time: r.get(0)?,
|
||||
correlation: r.get(1)?,
|
||||
api_key_id: r.get(2)?,
|
||||
model_id: r.get(3)?,
|
||||
status: r.get(4)?,
|
||||
wait_ms: r.get(5)?,
|
||||
latency_ms: r.get(6)?,
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>().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<()> {
|
||||
self.connection()
|
||||
.execute(
|
||||
"INSERT INTO audit (zeit, akteur, aktion, ziel) VALUES (?1, ?2, ?3, ?4)",
|
||||
(now_iso8601(), actor, action, target),
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Die letzten `limit` Audit-Einträge, neueste zuerst.
|
||||
pub fn recent_audit(&self, limit: u32) -> Result<Vec<AuditRow>> {
|
||||
let mut stmt = self
|
||||
.connection()
|
||||
.prepare("SELECT zeit, akteur, aktion, ziel FROM audit ORDER BY id DESC LIMIT ?1")
|
||||
.map_err(db)?;
|
||||
let rows = stmt
|
||||
.query_map([limit], |r| {
|
||||
Ok(AuditRow {
|
||||
time: r.get(0)?,
|
||||
actor: r.get(1)?,
|
||||
action: r.get(2)?,
|
||||
target: r.get(3)?,
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>().map_err(db)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{NewLlm, Rights};
|
||||
use nexus_core::Priority;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn eintrag(model: Option<&str>, key: Option<i64>) -> RequestLogEntry {
|
||||
RequestLogEntry {
|
||||
correlation: "req_abc".to_string(),
|
||||
api_key_id: key,
|
||||
model: model.map(str::to_string),
|
||||
status: 200,
|
||||
wait_ms: Some(300),
|
||||
latency_ms: Some(320),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anfrage_wird_mit_aufgeloester_modell_id_gespeichert() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
store
|
||||
.register_llm(&NewLlm {
|
||||
name: "bonsai".to_string(),
|
||||
path: PathBuf::from("/m/b.gguf"),
|
||||
quantization: None,
|
||||
size_bytes: None,
|
||||
gpus: vec![0],
|
||||
context: None,
|
||||
vram_mb: None,
|
||||
ram_mb: None,
|
||||
enabled: true,
|
||||
})
|
||||
.unwrap();
|
||||
let key = store
|
||||
.create_api_key("k", &Rights::default(), Priority::Normal, Priority::Normal)
|
||||
.unwrap();
|
||||
let key_id = store.find_api_key(&key).unwrap().unwrap().id;
|
||||
|
||||
store
|
||||
.log_request(&eintrag(Some("bonsai"), Some(key_id)))
|
||||
.unwrap();
|
||||
let rows = store.recent_requests(10).unwrap();
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].correlation, "req_abc");
|
||||
assert_eq!(rows[0].api_key_id, Some(key_id));
|
||||
assert!(rows[0].model_id.is_some());
|
||||
assert_eq!(
|
||||
(rows[0].status, rows[0].wait_ms, rows[0].latency_ms),
|
||||
(200, Some(300), Some(320))
|
||||
);
|
||||
assert!(rows[0].time.ends_with('Z'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbekanntes_modell_und_fehlender_key_ergeben_leere_felder() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
store
|
||||
.log_request(&eintrag(Some("gibt-es-nicht"), None))
|
||||
.unwrap();
|
||||
let row = &store.recent_requests(1).unwrap()[0];
|
||||
assert_eq!(row.model_id, None);
|
||||
assert_eq!(row.api_key_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audit_haelt_akteur_aktion_und_ziel_fest_neueste_zuerst() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
store.audit("cli", "key.create", Some("meinkey")).unwrap();
|
||||
store.audit("cli", "model.add", None).unwrap();
|
||||
let rows = store.recent_audit(10).unwrap();
|
||||
assert_eq!(rows[0].action, "model.add");
|
||||
assert_eq!(rows[1].target.as_deref(), Some("meinkey"));
|
||||
assert_eq!(rows[1].actor, "cli");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user