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:
2026-11-09 17:39:03 +01:00
parent 2ec9eccde6
commit 6cb930d0b0
31 changed files with 1050 additions and 67 deletions

View File

@ -0,0 +1,162 @@
//! Zustand und Protokollierung je Anfrage: Correlation-ID, Zugriffsprotokoll
//! und Anfrage-Log.
//!
//! Protokolliert werden nur Metadaten (Methode, Pfad ohne Query, Status,
//! Zeiten, Name des Keys, Modellname). **Nie** protokolliert werden Header,
//! Bodys (Prompts, Antworten, Bilder), Keys und Fehlertexte der Engine.
use std::sync::{Arc, Mutex};
use std::time::Instant;
use axum::extract::{Request, State};
use axum::http::HeaderValue;
use axum::middleware::Next;
use axum::response::Response;
use nexus_store::RequestLogEntry;
use tracing::Instrument;
use crate::state::AppState;
/// Correlation-ID der Anfrage (`x-request-id`).
#[derive(Debug, Clone)]
pub struct RequestId(pub String);
/// Was die Handler über eine Anfrage herausfinden; die Middleware schreibt
/// es nach der Antwort ins Log.
#[derive(Debug, Default, Clone)]
pub struct AccessInfo {
pub key_id: Option<i64>,
pub key_name: Option<String>,
pub model: Option<String>,
pub wait_ms: Option<u64>,
}
pub type AccessSlot = Arc<Mutex<AccessInfo>>;
/// Längste Zeichenzahl eines Modellnamens im Log.
const MAX_LOGGED_MODEL_CHARS: usize = 100;
/// Kürzt Texte, die vom Client stammen, bevor sie ins Log gehen.
pub fn clip(text: &str) -> String {
text.chars().take(MAX_LOGGED_MODEL_CHARS).collect()
}
/// Übernimmt eine vom Client mitgeschickte ID nur, wenn sie harmlos aussieht
/// (Buchstaben, Ziffern, `-`, `_`, `.`; höchstens 64 Zeichen).
fn accept_incoming(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}
fn new_id() -> String {
nexus_core::random_hex(8)
.map(|h| format!("req_{h}"))
.unwrap_or_else(|_| "req_unbekannt".to_string())
}
pub async fn observe(
State(state): State<Arc<AppState>>,
mut request: Request,
next: Next,
) -> Response {
let started = Instant::now();
let correlation = request
.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.filter(|v| accept_incoming(v))
.map(str::to_string)
.unwrap_or_else(new_id);
let method = request.method().to_string();
let path = request.uri().path().to_string();
let slot = AccessSlot::default();
request
.extensions_mut()
.insert(RequestId(correlation.clone()));
request.extensions_mut().insert(slot.clone());
let span = tracing::info_span!("request", korrelation = %correlation);
let mut response = next.run(request).instrument(span.clone()).await;
let latency_ms = started.elapsed().as_millis() as u64;
let status = response.status().as_u16();
if let Ok(value) = HeaderValue::from_str(&correlation) {
response.headers_mut().insert("x-request-id", value);
}
let info = slot.lock().unwrap_or_else(|e| e.into_inner()).clone();
span.in_scope(|| {
let key = info.key_name.as_deref();
let model = info.model.as_deref();
if status >= 500 {
tracing::error!(
method,
path,
status,
latency_ms,
key,
model,
wait_ms = info.wait_ms,
"Anfrage beantwortet"
);
} else if status >= 400 {
tracing::warn!(
method,
path,
status,
latency_ms,
key,
model,
wait_ms = info.wait_ms,
"Anfrage beantwortet"
);
} else {
tracing::info!(
method,
path,
status,
latency_ms,
key,
model,
wait_ms = info.wait_ms,
"Anfrage beantwortet"
);
}
if info.key_id.is_some() {
let entry = RequestLogEntry {
correlation: correlation.clone(),
api_key_id: info.key_id,
model: info.model.clone(),
status,
wait_ms: info.wait_ms,
latency_ms: Some(latency_ms),
};
if let Err(e) = state.store().log_request(&entry) {
tracing::error!(fehler = %e, "Anfrage-Log konnte nicht geschrieben werden");
}
}
});
response
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nur_harmlose_ids_werden_uebernommen() {
assert!(accept_incoming("abc-123_x.y"));
assert!(!accept_incoming(""));
assert!(!accept_incoming("mit leerzeichen"));
assert!(!accept_incoming("zeile\nzwei"));
assert!(!accept_incoming(&"a".repeat(65)));
}
#[test]
fn clip_kuerzt_lange_namen() {
assert_eq!(clip(&"x".repeat(500)).chars().count(), 100);
assert_eq!(clip("kurz"), "kurz");
}
}

View File

@ -8,6 +8,7 @@ use axum::http::request::Parts;
use nexus_core::Priority;
use nexus_store::ApiKeyRecord;
use crate::access::AccessSlot;
use crate::error::ApiError;
use crate::state::AppState;
@ -28,12 +29,25 @@ impl FromRequestParts<Arc<AppState>> for Authed {
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::trim)
.filter(|t| !t.is_empty())
.ok_or_else(ApiError::invalid_key)?;
.ok_or_else(|| {
tracing::warn!("Anfrage ohne API-Key");
ApiError::invalid_key()
})?;
match state.store().find_api_key(token) {
Ok(Some(key)) => Ok(Authed(key)),
Ok(None) => Err(ApiError::invalid_key()),
Ok(Some(key)) => {
if let Some(slot) = parts.extensions.get::<AccessSlot>() {
let mut info = slot.lock().unwrap_or_else(|e| e.into_inner());
info.key_id = Some(key.id);
info.key_name = Some(key.name.clone());
}
Ok(Authed(key))
}
Ok(None) => {
tracing::warn!("Ungültiger oder gesperrter API-Key");
Err(ApiError::invalid_key())
}
Err(e) => {
eprintln!("FEHLER Key-Prüfung: {e}");
tracing::error!(fehler = %e, "Key-Prüfung fehlgeschlagen");
Err(ApiError::internal())
}
}

View File

@ -4,12 +4,13 @@
use std::sync::Arc;
use axum::body::{Body, Bytes};
use axum::extract::State;
use axum::extract::{Extension, State};
use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE};
use axum::http::{HeaderMap, StatusCode};
use axum::response::Response;
use serde_json::Value;
use crate::access::{AccessSlot, RequestId, clip};
use crate::auth::{Authed, requested_priority};
use crate::error::ApiError;
use crate::state::AppState;
@ -17,6 +18,8 @@ use crate::state::AppState;
pub async fn completions(
State(state): State<Arc<AppState>>,
Authed(key): Authed,
Extension(slot): Extension<AccessSlot>,
Extension(RequestId(correlation)): Extension<RequestId>,
headers: HeaderMap,
body: Bytes,
) -> Result<Response, ApiError> {
@ -30,6 +33,8 @@ pub async fn completions(
.ok_or_else(|| ApiError::bad_request("Das Feld \"model\" fehlt."))?
.to_string();
slot.lock().unwrap_or_else(|e| e.into_inner()).model = Some(clip(&model));
if !key.rights.allows(&model) {
return Err(ApiError::model_not_found(&model));
}
@ -37,25 +42,27 @@ pub async fn completions(
.store()
.start_plan(&model)
.map_err(|e| {
eprintln!("FEHLER Startplan für \"{model}\": {e}");
tracing::error!(fehler = %e, "Startplan nicht lesbar");
ApiError::internal()
})?
.ok_or_else(|| ApiError::model_not_found(&model))?;
let endpoint = state.runtime.ensure(&plan).await.map_err(|e| {
eprintln!("FEHLER {e}");
ApiError::engine_unavailable()
})?;
let waited = std::time::Instant::now();
let ensured = state.runtime.ensure(&plan).await;
slot.lock().unwrap_or_else(|e| e.into_inner()).wait_ms =
Some(waited.elapsed().as_millis() as u64);
let endpoint = ensured.map_err(|_| ApiError::engine_unavailable())?;
let upstream = state
.http
.post(format!("{}/v1/chat/completions", endpoint.base_url))
.header(CONTENT_TYPE, "application/json")
.header("x-request-id", &correlation)
.body(body)
.send()
.await
.map_err(|e| {
eprintln!("FEHLER Weiterleitung an {}: {e}", endpoint.base_url);
tracing::error!(ziel = %endpoint.base_url, fehler = %e, "Weiterleitung an die Engine fehlgeschlagen");
ApiError::upstream()
})?;

View File

@ -9,6 +9,7 @@
//! Anfrage und läuft bis zum Beenden des Gateways. Ressourcenplanung,
//! Verdrängung und Idle-Timeouts fehlen.
mod access;
mod auth;
mod chat;
mod error;
@ -19,10 +20,10 @@ mod state;
use std::sync::Arc;
use axum::Router;
use axum::extract::{DefaultBodyLimit, Request};
use axum::http::{HeaderValue, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::extract::DefaultBodyLimit;
use axum::http::StatusCode;
use axum::middleware;
use axum::response::IntoResponse;
use axum::routing::{get, post};
pub use error::ApiError;
@ -41,7 +42,10 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/gateway/v1/health", get(health))
.fallback(not_found)
.layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
.layer(middleware::from_fn(request_id))
.layer(middleware::from_fn_with_state(
state.clone(),
access::observe,
))
.with_state(state)
}
@ -57,15 +61,3 @@ async fn not_found() -> ApiError {
"Unbekannte Adresse.",
)
}
/// Hängt jeder Antwort eine `x-request-id` an.
async fn request_id(request: Request, next: Next) -> Response {
let id = nexus_core::random_hex(8)
.map(|h| format!("req_{h}"))
.unwrap_or_else(|_| "req_unbekannt".to_string());
let mut response = next.run(request).await;
if let Ok(value) = HeaderValue::from_str(&id) {
response.headers_mut().insert("x-request-id", value);
}
response
}

View File

@ -3,9 +3,10 @@
use std::sync::Arc;
use axum::Json;
use axum::extract::{Path, State};
use axum::extract::{Extension, Path, State};
use serde_json::{Value, json};
use crate::access::{AccessSlot, clip};
use crate::auth::Authed;
use crate::error::ApiError;
use crate::state::AppState;
@ -20,7 +21,7 @@ pub async fn list(
Authed(key): Authed,
) -> Result<Json<Value>, ApiError> {
let models = state.store().list_models(true).map_err(|e| {
eprintln!("FEHLER Modellliste: {e}");
tracing::error!(fehler = %e, "Modellliste nicht lesbar");
ApiError::internal()
})?;
let data: Vec<Value> = models
@ -34,10 +35,12 @@ pub async fn list(
pub async fn retrieve(
State(state): State<Arc<AppState>>,
Authed(key): Authed,
Extension(slot): Extension<AccessSlot>,
Path(id): Path<String>,
) -> Result<Json<Value>, ApiError> {
slot.lock().unwrap_or_else(|e| e.into_inner()).model = Some(clip(&id));
let models = state.store().list_models(true).map_err(|e| {
eprintln!("FEHLER Modellliste: {e}");
tracing::error!(fehler = %e, "Modellliste nicht lesbar");
ApiError::internal()
})?;
if key.rights.allows(&id) && models.iter().any(|m| m.name == id) {

View File

@ -70,9 +70,12 @@ impl Runtime {
if running.engine.health(&running.handle).await != Health::Gone {
return Ok(running.engine.endpoint(&running.handle));
}
tracing::warn!(model = %plan.model, instance_id = running.handle.id, "Instanz ist verschwunden, wird neu gestartet");
*guard = None;
}
tracing::info!(model = %plan.model, engine = %plan.engine_name, "Modell wird gestartet");
let started = std::time::Instant::now();
let spec = ProfileSpec {
model_alias: plan.model.clone(),
model_path: plan.model_path.clone(),
@ -80,14 +83,22 @@ impl Runtime {
context: plan.context,
extra_args: plan.extra_args.clone(),
};
let handle = engine
.start(&spec)
.await
.map_err(|source| RuntimeError::Start {
let handle = engine.start(&spec).await.map_err(|source| {
tracing::error!(model = %plan.model, fehler = %source, "Modellstart fehlgeschlagen");
RuntimeError::Start {
model: plan.model.clone(),
source,
})?;
}
})?;
let endpoint = engine.endpoint(&handle);
tracing::info!(
model = %plan.model,
instance_id = handle.id,
pid = handle.pid,
port = handle.port,
duration_ms = started.elapsed().as_millis() as u64,
"Modell bereit"
);
*guard = Some(Running { engine, handle });
Ok(endpoint)
}
@ -102,10 +113,13 @@ impl Runtime {
.cloned()
.collect();
for slot in slots {
if let Some(running) = slot.lock().await.take()
&& let Err(e) = running.engine.stop(&running.handle, self.stop_grace).await
{
eprintln!("FEHLER Beenden einer Instanz: {e}");
if let Some(running) = slot.lock().await.take() {
match running.engine.stop(&running.handle, self.stop_grace).await {
Ok(()) => tracing::info!(instance_id = running.handle.id, "Instanz beendet"),
Err(e) => {
tracing::error!(instance_id = running.handle.id, fehler = %e, "Beenden einer Instanz fehlgeschlagen")
}
}
}
}
}