feat: OpenAI-kompatible API mit Keys, Registry und serve-Befehl (M2.3)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
65
crates/nexus-api/src/auth.rs
Normal file
65
crates/nexus-api/src/auth.rs
Normal file
@ -0,0 +1,65 @@
|
||||
//! API-Key-Prüfung über den Header `Authorization: Bearer <key>`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::http::request::Parts;
|
||||
use nexus_core::Priority;
|
||||
use nexus_store::ApiKeyRecord;
|
||||
|
||||
use crate::error::ApiError;
|
||||
use crate::state::AppState;
|
||||
|
||||
/// Ein erfolgreich geprüfter Key.
|
||||
pub struct Authed(pub ApiKeyRecord);
|
||||
|
||||
impl FromRequestParts<Arc<AppState>> for Authed {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &Arc<AppState>,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let token = parts
|
||||
.headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
.ok_or_else(ApiError::invalid_key)?;
|
||||
match state.store().find_api_key(token) {
|
||||
Ok(Some(key)) => Ok(Authed(key)),
|
||||
Ok(None) => Err(ApiError::invalid_key()),
|
||||
Err(e) => {
|
||||
eprintln!("FEHLER Key-Prüfung: {e}");
|
||||
Err(ApiError::internal())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Liest den optionalen Header `X-Gateway-Priority` und prüft ihn gegen die
|
||||
/// Höchstpriorität des Keys. Ohne Header gilt die Standardpriorität.
|
||||
pub fn requested_priority(
|
||||
headers: &axum::http::HeaderMap,
|
||||
key: &ApiKeyRecord,
|
||||
) -> Result<Priority, ApiError> {
|
||||
let Some(raw) = headers.get("x-gateway-priority") else {
|
||||
return Ok(key.default_priority);
|
||||
};
|
||||
let text = raw
|
||||
.to_str()
|
||||
.map_err(|_| ApiError::bad_request("X-Gateway-Priority ist kein Text."))?;
|
||||
let priority = Priority::parse(text).ok_or_else(|| {
|
||||
ApiError::bad_request("X-Gateway-Priority muss \"low\", \"normal\" oder \"high\" sein.")
|
||||
})?;
|
||||
if priority > key.max_priority {
|
||||
return Err(ApiError::priority_not_permitted(
|
||||
priority.as_str(),
|
||||
key.max_priority.as_str(),
|
||||
));
|
||||
}
|
||||
Ok(priority)
|
||||
}
|
||||
73
crates/nexus-api/src/chat.rs
Normal file
73
crates/nexus-api/src/chat.rs
Normal file
@ -0,0 +1,73 @@
|
||||
//! `POST /v1/chat/completions`: prüft Key und Modell, startet bei Bedarf die
|
||||
//! Instanz und reicht Anfrage und Antwort durch (auch als SSE-Stream).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::{Body, Bytes};
|
||||
use axum::extract::State;
|
||||
use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE};
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::Response;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::auth::{Authed, requested_priority};
|
||||
use crate::error::ApiError;
|
||||
use crate::state::AppState;
|
||||
|
||||
pub async fn completions(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Authed(key): Authed,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Result<Response, ApiError> {
|
||||
let _priority = requested_priority(&headers, &key)?;
|
||||
|
||||
let request: Value = serde_json::from_slice(&body)
|
||||
.map_err(|e| ApiError::bad_request(format!("Der Body ist kein gültiges JSON: {e}")))?;
|
||||
let model = request
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| ApiError::bad_request("Das Feld \"model\" fehlt."))?
|
||||
.to_string();
|
||||
|
||||
if !key.rights.allows(&model) {
|
||||
return Err(ApiError::model_not_found(&model));
|
||||
}
|
||||
let plan = state
|
||||
.store()
|
||||
.start_plan(&model)
|
||||
.map_err(|e| {
|
||||
eprintln!("FEHLER Startplan für \"{model}\": {e}");
|
||||
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 upstream = state
|
||||
.http
|
||||
.post(format!("{}/v1/chat/completions", endpoint.base_url))
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("FEHLER Weiterleitung an {}: {e}", endpoint.base_url);
|
||||
ApiError::upstream()
|
||||
})?;
|
||||
|
||||
let status =
|
||||
StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
|
||||
let mut response = Response::builder().status(status);
|
||||
for name in [CONTENT_TYPE, CACHE_CONTROL] {
|
||||
if let Some(value) = upstream.headers().get(&name) {
|
||||
response = response.header(name, value);
|
||||
}
|
||||
}
|
||||
response
|
||||
.body(Body::from_stream(upstream.bytes_stream()))
|
||||
.map_err(|_| ApiError::internal())
|
||||
}
|
||||
114
crates/nexus-api/src/error.rs
Normal file
114
crates/nexus-api/src/error.rs
Normal file
@ -0,0 +1,114 @@
|
||||
use axum::Json;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde_json::json;
|
||||
|
||||
/// Fehler im OpenAI-Format: `{"error": {"message", "type", "param", "code"}}`.
|
||||
#[derive(Debug)]
|
||||
pub struct ApiError {
|
||||
status: StatusCode,
|
||||
kind: &'static str,
|
||||
code: &'static str,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
pub fn new(
|
||||
status: StatusCode,
|
||||
kind: &'static str,
|
||||
code: &'static str,
|
||||
message: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
status,
|
||||
kind,
|
||||
code,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self) -> StatusCode {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn invalid_key() -> Self {
|
||||
Self::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"invalid_request_error",
|
||||
"invalid_api_key",
|
||||
"Fehlender oder ungültiger API-Key. Erwartet wird der Header \"Authorization: Bearer <key>\".",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn model_not_found(model: &str) -> Self {
|
||||
Self::new(
|
||||
StatusCode::NOT_FOUND,
|
||||
"invalid_request_error",
|
||||
"model_not_found",
|
||||
format!(
|
||||
"Das Modell \"{model}\" existiert nicht oder ist für diesen Key nicht freigegeben."
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn bad_request(message: impl Into<String>) -> Self {
|
||||
Self::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"invalid_request_error",
|
||||
"invalid_request",
|
||||
message,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn priority_not_permitted(requested: &str, max: &str) -> Self {
|
||||
Self::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"permission_error",
|
||||
"priority_not_permitted",
|
||||
format!(
|
||||
"Die Priorität \"{requested}\" ist für diesen Key nicht erlaubt (höchstens \"{max}\")."
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn engine_unavailable() -> Self {
|
||||
Self::new(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"server_error",
|
||||
"engine_unavailable",
|
||||
"Das Modell konnte nicht gestartet werden. Details stehen im Log des Gateways.",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn upstream() -> Self {
|
||||
Self::new(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"server_error",
|
||||
"upstream_error",
|
||||
"Die Engine hat nicht geantwortet.",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn internal() -> Self {
|
||||
Self::new(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"server_error",
|
||||
"internal_error",
|
||||
"Interner Fehler. Details stehen im Log des Gateways.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let body = json!({
|
||||
"error": {
|
||||
"message": self.message,
|
||||
"type": self.kind,
|
||||
"param": null,
|
||||
"code": self.code,
|
||||
}
|
||||
});
|
||||
(self.status, Json(body)).into_response()
|
||||
}
|
||||
}
|
||||
71
crates/nexus-api/src/lib.rs
Normal file
71
crates/nexus-api/src/lib.rs
Normal file
@ -0,0 +1,71 @@
|
||||
//! 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 auth;
|
||||
mod chat;
|
||||
mod error;
|
||||
mod models;
|
||||
mod runtime;
|
||||
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::routing::{get, post};
|
||||
|
||||
pub use error::ApiError;
|
||||
pub use runtime::{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))
|
||||
.fallback(not_found)
|
||||
.layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
|
||||
.layer(middleware::from_fn(request_id))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
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.",
|
||||
)
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
48
crates/nexus-api/src/models.rs
Normal file
48
crates/nexus-api/src/models.rs
Normal file
@ -0,0 +1,48 @@
|
||||
//! `GET /v1/models` und `GET /v1/models/{id}`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::auth::Authed;
|
||||
use crate::error::ApiError;
|
||||
use crate::state::AppState;
|
||||
|
||||
fn entry(name: &str) -> Value {
|
||||
json!({ "id": name, "object": "model", "created": 0, "owned_by": "nexus" })
|
||||
}
|
||||
|
||||
/// Auch Modelle, die gerade nicht geladen sind, erscheinen im Katalog.
|
||||
pub async fn list(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Authed(key): Authed,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let models = state.store().list_models(true).map_err(|e| {
|
||||
eprintln!("FEHLER Modellliste: {e}");
|
||||
ApiError::internal()
|
||||
})?;
|
||||
let data: Vec<Value> = models
|
||||
.iter()
|
||||
.filter(|m| key.rights.allows(&m.name))
|
||||
.map(|m| entry(&m.name))
|
||||
.collect();
|
||||
Ok(Json(json!({ "object": "list", "data": data })))
|
||||
}
|
||||
|
||||
pub async fn retrieve(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Authed(key): Authed,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<Value>, ApiError> {
|
||||
let models = state.store().list_models(true).map_err(|e| {
|
||||
eprintln!("FEHLER Modellliste: {e}");
|
||||
ApiError::internal()
|
||||
})?;
|
||||
if key.rights.allows(&id) && models.iter().any(|m| m.name == id) {
|
||||
Ok(Json(entry(&id)))
|
||||
} else {
|
||||
Err(ApiError::model_not_found(&id))
|
||||
}
|
||||
}
|
||||
112
crates/nexus-api/src/runtime.rs
Normal file
112
crates/nexus-api/src/runtime.rs
Normal file
@ -0,0 +1,112 @@
|
||||
//! Einfache Instanzverwaltung für M2: eine Instanz je Modell, gestartet bei
|
||||
//! der ersten Anfrage, beendet beim Herunterfahren. Der Scheduler (M3) ersetzt
|
||||
//! das durch Ressourcenplanung, Verdrängung und Idle-Timeouts.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use nexus_adapter::{AdapterError, Endpoint, Engine, Health, InstanceHandle, ProfileSpec};
|
||||
use nexus_store::StartPlan;
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RuntimeError {
|
||||
#[error("unbekannte Engine \"{0}\"")]
|
||||
UnknownEngine(String),
|
||||
#[error("Start von \"{model}\" fehlgeschlagen: {source}")]
|
||||
Start {
|
||||
model: String,
|
||||
#[source]
|
||||
source: AdapterError,
|
||||
},
|
||||
}
|
||||
|
||||
struct Running {
|
||||
engine: Arc<dyn Engine>,
|
||||
handle: InstanceHandle,
|
||||
}
|
||||
|
||||
type Slot = Arc<AsyncMutex<Option<Running>>>;
|
||||
|
||||
pub struct Runtime {
|
||||
engines: HashMap<String, Arc<dyn Engine>>,
|
||||
slots: Mutex<HashMap<String, Slot>>,
|
||||
stop_grace: Duration,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
pub fn new(engines: HashMap<String, Arc<dyn Engine>>) -> Self {
|
||||
Self {
|
||||
engines,
|
||||
slots: Mutex::new(HashMap::new()),
|
||||
stop_grace: Duration::from_secs(10),
|
||||
}
|
||||
}
|
||||
|
||||
fn slot(&self, model: &str) -> Slot {
|
||||
self.slots
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.entry(model.to_string())
|
||||
.or_default()
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Stellt sicher, dass für das Modell eine bereite Instanz läuft, und
|
||||
/// liefert deren Adresse. Gleichzeitige Anfragen für dasselbe Modell
|
||||
/// lösen nur **einen** Ladevorgang aus: Wer zuerst kommt, startet, die
|
||||
/// anderen warten auf den Schlüssel `slot`.
|
||||
pub async fn ensure(&self, plan: &StartPlan) -> Result<Endpoint, RuntimeError> {
|
||||
let engine = self
|
||||
.engines
|
||||
.get(&plan.engine_name)
|
||||
.cloned()
|
||||
.ok_or_else(|| RuntimeError::UnknownEngine(plan.engine_name.clone()))?;
|
||||
let slot = self.slot(&plan.model);
|
||||
let mut guard = slot.lock().await;
|
||||
|
||||
if let Some(running) = guard.as_ref() {
|
||||
if running.engine.health(&running.handle).await != Health::Gone {
|
||||
return Ok(running.engine.endpoint(&running.handle));
|
||||
}
|
||||
*guard = None;
|
||||
}
|
||||
|
||||
let spec = ProfileSpec {
|
||||
model_alias: plan.model.clone(),
|
||||
model_path: plan.model_path.clone(),
|
||||
gpus: plan.gpus.clone(),
|
||||
context: plan.context,
|
||||
extra_args: plan.extra_args.clone(),
|
||||
};
|
||||
let handle = engine
|
||||
.start(&spec)
|
||||
.await
|
||||
.map_err(|source| RuntimeError::Start {
|
||||
model: plan.model.clone(),
|
||||
source,
|
||||
})?;
|
||||
let endpoint = engine.endpoint(&handle);
|
||||
*guard = Some(Running { engine, handle });
|
||||
Ok(endpoint)
|
||||
}
|
||||
|
||||
/// Beendet alle laufenden Instanzen.
|
||||
pub async fn shutdown(&self) {
|
||||
let slots: Vec<Slot> = self
|
||||
.slots
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.values()
|
||||
.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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
crates/nexus-api/src/state.rs
Normal file
31
crates/nexus-api/src/state.rs
Normal file
@ -0,0 +1,31 @@
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
use nexus_store::Store;
|
||||
|
||||
use crate::runtime::Runtime;
|
||||
|
||||
/// Gemeinsamer Zustand aller Anfragen.
|
||||
pub struct AppState {
|
||||
store: Mutex<Store>,
|
||||
pub runtime: Runtime,
|
||||
pub http: reqwest::Client,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(store: Store, runtime: Runtime) -> Arc<Self> {
|
||||
let http = reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(5))
|
||||
.build()
|
||||
.expect("HTTP-Client konnte nicht gebaut werden");
|
||||
Arc::new(Self {
|
||||
store: Mutex::new(store),
|
||||
runtime,
|
||||
http,
|
||||
})
|
||||
}
|
||||
|
||||
/// Zugriff auf die Datenbank. Nie über ein `await` hinweg halten.
|
||||
pub fn store(&self) -> MutexGuard<'_, Store> {
|
||||
self.store.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user