feat: Metriken, Token-Auswertung und Protokollierung am Ende der Antwort (#1050)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 09:05:20 +01:00
parent b4a3957f8a
commit 2dc8f9193c
9 changed files with 942 additions and 17 deletions

View File

@ -13,9 +13,12 @@ mod access;
mod auth;
mod chat;
mod error;
mod metrics;
mod models;
mod runtime;
mod state;
mod tap;
mod usage;
use std::sync::Arc;
@ -27,7 +30,8 @@ use axum::response::IntoResponse;
use axum::routing::{get, post};
pub use error::ApiError;
pub use runtime::{Runtime, RuntimeError};
pub use metrics::Metrics;
pub use runtime::{Ensured, Runtime, RuntimeError};
pub use state::AppState;
/// Größtes erlaubtes Anfragen-Datenvolumen (Bilder und lange Verläufe).
@ -40,6 +44,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/models/{id}", get(models::retrieve))
.route("/v1/chat/completions", post(chat::completions))
.route("/gateway/v1/health", get(health))
.route("/gateway/v1/metrics", get(metrics_endpoint))
.fallback(not_found)
.layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
.layer(middleware::from_fn_with_state(
@ -49,6 +54,28 @@ pub fn router(state: Arc<AppState>) -> Router {
.with_state(state)
}
/// Metriken im Prometheus-Textformat; nur für Keys mit dem Recht `metrics`.
async fn metrics_endpoint(
axum::extract::State(state): axum::extract::State<Arc<AppState>>,
auth::Authed(key): auth::Authed,
) -> Result<impl IntoResponse, ApiError> {
if !key.rights.metrics {
return Err(ApiError::new(
StatusCode::FORBIDDEN,
"invalid_request_error",
"permission_denied",
"Dieser Key hat nicht das Recht \"metrics\".",
));
}
Ok((
[(
axum::http::header::CONTENT_TYPE,
"text/plain; version=0.0.4; charset=utf-8",
)],
state.runtime.metrics.render(),
))
}
async fn health() -> impl IntoResponse {
axum::Json(serde_json::json!({ "status": "ok", "version": nexus_core::VERSION }))
}