Files
nexus/crates/nexus-api/src/lib.rs

91 lines
2.7 KiB
Rust

//! OpenAI-kompatible HTTP-API und Gateway-Endpunkte (Spezifikation, Abschnitt 7).
//!
//! Stand M2.3: `GET /v1/models`, `GET /v1/models/{id}`,
//! `POST /v1/chat/completions` (mit SSE-Streaming), `GET /gateway/v1/health`,
//! API-Key-Authentifizierung und das OpenAI-Fehlerformat. Weitere Endpunkte
//! (Completions, Embeddings, Bilder) und die Gateway-Verwaltung folgen später.
//!
//! Es gibt noch keinen Scheduler (M3): Eine Instanz startet bei der ersten
//! Anfrage und läuft bis zum Beenden des Gateways. Ressourcenplanung,
//! Verdrängung und Idle-Timeouts fehlen.
mod access;
mod auth;
mod chat;
mod error;
mod metrics;
mod models;
mod runtime;
mod state;
mod tap;
mod usage;
use std::sync::Arc;
use axum::Router;
use axum::extract::DefaultBodyLimit;
use axum::http::StatusCode;
use axum::middleware;
use axum::response::IntoResponse;
use axum::routing::{get, post};
pub use error::ApiError;
pub use metrics::Metrics;
pub use runtime::{Ensured, Runtime, RuntimeError};
pub use state::AppState;
/// Größtes erlaubtes Anfragen-Datenvolumen (Bilder und lange Verläufe).
const MAX_BODY_BYTES: usize = 32 * 1024 * 1024;
/// Baut den Router des Gateways.
pub fn router(state: Arc<AppState>) -> Router {
Router::new()
.route("/v1/models", get(models::list))
.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(
state.clone(),
access::observe,
))
.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 }))
}
async fn not_found() -> ApiError {
ApiError::new(
StatusCode::NOT_FOUND,
"invalid_request_error",
"unknown_url",
"Unbekannte Adresse.",
)
}