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:
2026-11-09 17:27:46 +01:00
parent ada5745c53
commit 4d53d5afa3
35 changed files with 3434 additions and 21 deletions

View File

@ -0,0 +1,21 @@
[package]
name = "nexus-api"
description = "Nexus: OpenAI-kompatible HTTP-API und Gateway-Endpunkte"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
axum.workspace = true
nexus-adapter.workspace = true
nexus-core.workspace = true
nexus-store.workspace = true
reqwest.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tokio.workspace = true
[dev-dependencies]
async-trait.workspace = true
futures-util = "0.3"
tokio = { workspace = true, features = ["test-util"] }

View File

@ -0,0 +1,25 @@
# nexus-api
OpenAI-kompatible HTTP-API und Gateway-Endpunkte (Spezifikation, Abschnitt 7). Axum, ohne TLS (Zugang nur intern oder über Tailscale).
**Version:** wie der Workspace (`0.1.0-dev`). **Stand M2.3.**
## Endpunkte
| Endpunkt | Auth | Beschreibung |
| --- | --- | --- |
| `GET /v1/models` | Key | Freigegebene Modelle, die der Key sehen darf, auch ungeladene. Lädt nichts. |
| `GET /v1/models/{id}` | Key | Ein Modell; unbekannt oder nicht erlaubt ist 404. |
| `POST /v1/chat/completions` | Key | Startet das Modell bei Bedarf und reicht Anfrage und Antwort durch, auch als SSE-Stream (ungepuffert). |
| `GET /gateway/v1/health` | nein | `{"status":"ok","version":...}` |
Noch nicht vorhanden: Completions, Embeddings, Responses, Bilder und die Gateway-Verwaltung unter `/gateway/v1/`.
## Verhalten
- **Auth:** `Authorization: Bearer <key>`. Fehlt der Key oder ist er falsch oder gesperrt: 401 mit Code `invalid_api_key`. Geprüft wird vor jedem Modellstart.
- **Fehlerformat:** OpenAI (`{"error":{"message","type","param","code"}}`). Jede Antwort trägt `x-request-id`. Startfehler (503) verraten keine Pfade oder Logzeilen; Details stehen im Log des Gateways.
- **Rechte je Key:** erlaubte Modelle (`*` oder Liste). Nicht erlaubte Modelle antworten wie unbekannte (404), damit ihre Existenz nicht verraten wird.
- **Priorität:** `X-Gateway-Priority: low|normal|high` darf die Höchstpriorität des Keys nicht überschreiten (403, Code `priority_not_permitted`); ungültige Werte sind 400. **Die Priorität wirkt noch nicht auf die Einplanung** (kommt mit dem Scheduler, M3).
- **Instanzen (`Runtime`):** eine Instanz je Modell, gestartet bei der ersten Anfrage. Gleichzeitige Anfragen für dasselbe Modell lösen nur einen Ladevorgang aus. Beim Herunterfahren werden alle Instanzen beendet. **Kein Scheduler:** keine Ressourcenplanung, keine Verdrängung, kein Idle-Timeout; zwei große Modelle auf derselben GPU werden nicht verhindert.
## Tests
`cargo test -p nexus-api`: 14 Integrationstests gegen einen Attrappen-Server (Auth, Fehlerformat, Weiterleitung, Streaming mit Zeitprüfung, einmaliges Laden bei 6 gleichzeitigen Anfragen, Priorität, Herunterfahren). Dazu `tests/sdk/` (Python, offizielles OpenAI-SDK gegen ein echtes `nexus serve`).

View 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)
}

View 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())
}

View 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()
}
}

View 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
}

View 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))
}
}

View 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}");
}
}
}
}

View 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())
}
}

View File

@ -0,0 +1,494 @@
//! Integrationstests der HTTP-API.
//!
//! Das Gateway läuft in-process auf einem zufälligen Port. Statt einer echten
//! Engine antwortet ein kleiner Attrappen-Server im selben Test. Geprüft wird
//! das Verhalten der API (Auth, Fehlerformat, Weiterleitung, Streaming,
//! einmaliges Laden), nicht echte Modelle.
use std::collections::HashMap;
use std::convert::Infallible;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use axum::Router;
use axum::body::{Body, Bytes};
use axum::http::header::CONTENT_TYPE;
use axum::response::Response;
use axum::routing::post;
use futures_util::stream;
use nexus_adapter::{
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, Engine, EngineInfo, Health,
InstanceHandle, Mode, ProfileSpec, Protocol, Usage,
};
use nexus_api::{AppState, Runtime};
use nexus_core::Priority;
use nexus_store::{NewLlm, Rights, Store};
use serde_json::{Value, json};
/// Engine, die auf den Attrappen-Server zeigt und Starts und Stopps zählt.
struct FixedEngine {
port: u16,
starts: AtomicUsize,
stops: AtomicUsize,
delay: Duration,
fail: bool,
}
#[async_trait]
impl Engine for FixedEngine {
fn describe(&self) -> EngineInfo {
EngineInfo {
name: "fixed".to_string(),
mode: Mode::External,
capabilities: Capabilities::default(),
}
}
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>, AdapterError> {
Ok(vec![])
}
async fn start(&self, _p: &ProfileSpec) -> Result<InstanceHandle, AdapterError> {
self.starts.fetch_add(1, Ordering::SeqCst);
tokio::time::sleep(self.delay).await;
if self.fail {
return Err(AdapterError::Spawn("geheimes-detail".to_string()));
}
Ok(InstanceHandle {
id: 1,
pid: None,
port: self.port,
})
}
async fn stop(&self, _i: &InstanceHandle, _g: Duration) -> Result<(), AdapterError> {
self.stops.fetch_add(1, Ordering::SeqCst);
Ok(())
}
async fn health(&self, _i: &InstanceHandle) -> Health {
Health::Ready
}
fn endpoint(&self, i: &InstanceHandle) -> Endpoint {
Endpoint {
base_url: format!("http://127.0.0.1:{}", i.port),
protocol: Protocol::OpenAi,
}
}
async fn measure(&self, _i: &InstanceHandle) -> Usage {
Usage::default()
}
}
async fn serve(app: Router) -> u16 {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
port
}
/// Attrappen-Engine: Chat antwortet mit JSON oder, bei `stream: true`, mit drei
/// SSE-Stücken im Abstand von 200 ms (damit der Test Durchreichen von Puffern
/// unterscheiden kann).
async fn fake_backend() -> u16 {
async fn chat(body: Bytes) -> Response {
let req: Value = serde_json::from_slice(&body).unwrap();
if req["stream"] == true {
let parts = ["Hal", "lo", " Welt", "[DONE]"];
let stream = stream::unfold(0usize, move |i| async move {
let part = parts.get(i)?;
tokio::time::sleep(Duration::from_millis(200)).await;
let text = if *part == "[DONE]" {
"data: [DONE]\n\n".to_string()
} else {
format!(
"data: {}\n\n",
json!({"choices":[{"index":0,"delta":{"content":part}}]})
)
};
Some((Ok::<_, Infallible>(Bytes::from(text)), i + 1))
});
Response::builder()
.header(CONTENT_TYPE, "text/event-stream")
.body(Body::from_stream(stream))
.unwrap()
} else {
let answer = json!({
"id": "chatcmpl-1", "object": "chat.completion", "created": 1,
"model": req["model"],
"choices": [{"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "Hallo Welt"}}],
"usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3}
});
Response::builder()
.header(CONTENT_TYPE, "application/json")
.body(Body::from(answer.to_string()))
.unwrap()
}
}
serve(Router::new().route("/v1/chat/completions", post(chat))).await
}
struct Gateway {
base: String,
engine: Arc<FixedEngine>,
state: Arc<AppState>,
/// Key mit Zugriff auf alle Modelle, Priorität höchstens normal.
key: String,
/// Key nur für `bonsai`.
key_bonsai: String,
/// Key mit Höchstpriorität high.
key_vip: String,
client: reqwest::Client,
}
impl Gateway {
async fn get(&self, path: &str, key: Option<&str>) -> (u16, reqwest::header::HeaderMap, Value) {
let mut req = self.client.get(format!("{}{path}", self.base));
if let Some(k) = key {
req = req.bearer_auth(k);
}
let resp = req.send().await.unwrap();
let (status, headers) = (resp.status().as_u16(), resp.headers().clone());
let text = resp.text().await.unwrap();
(
status,
headers,
serde_json::from_str(&text).unwrap_or(Value::Null),
)
}
async fn chat(
&self,
key: Option<&str>,
extra_header: Option<(&str, &str)>,
body: &str,
) -> reqwest::Response {
let mut req = self
.client
.post(format!("{}/v1/chat/completions", self.base))
.header(CONTENT_TYPE, "application/json")
.body(body.to_string());
if let Some(k) = key {
req = req.bearer_auth(k);
}
if let Some((n, v)) = extra_header {
req = req.header(n, v);
}
req.send().await.unwrap()
}
}
fn chat_body(model: &str, stream: bool) -> String {
json!({"model": model, "stream": stream,
"messages": [{"role": "user", "content": "Hallo"}]})
.to_string()
}
async fn gateway(delay_ms: u64, fail: bool) -> Gateway {
let backend_port = fake_backend().await;
let engine = Arc::new(FixedEngine {
port: backend_port,
starts: AtomicUsize::new(0),
stops: AtomicUsize::new(0),
delay: Duration::from_millis(delay_ms),
fail,
});
let mut store = Store::open_in_memory().unwrap();
for (name, enabled) in [("bonsai", true), ("zweit", true), ("gesperrt", false)] {
store
.register_llm(&NewLlm {
name: name.to_string(),
path: PathBuf::from(format!("/m/{name}.gguf")),
quantization: None,
size_bytes: None,
gpus: vec![0],
context: None,
vram_mb: None,
ram_mb: None,
enabled,
})
.unwrap();
}
let key = store
.create_api_key(
"alle",
&Rights::default(),
Priority::Normal,
Priority::Normal,
)
.unwrap();
let key_bonsai = store
.create_api_key(
"nur-bonsai",
&Rights {
models: vec!["bonsai".to_string()],
},
Priority::Normal,
Priority::Normal,
)
.unwrap();
let key_vip = store
.create_api_key("vip", &Rights::default(), Priority::Normal, Priority::High)
.unwrap();
let mut engines: HashMap<String, Arc<dyn Engine>> = HashMap::new();
engines.insert("llama.cpp".to_string(), engine.clone());
let state = AppState::new(store, Runtime::new(engines));
let port = serve(nexus_api::router(state.clone())).await;
Gateway {
base: format!("http://127.0.0.1:{port}"),
engine,
state,
key,
key_bonsai,
key_vip,
client: reqwest::Client::new(),
}
}
fn error_code(body: &Value) -> &str {
body["error"]["code"].as_str().unwrap_or("")
}
#[tokio::test]
async fn health_braucht_keinen_key_und_antwortet_mit_request_id() {
let gw = gateway(0, false).await;
let (status, headers, body) = gw.get("/gateway/v1/health", None).await;
assert_eq!(status, 200);
assert_eq!(body["status"], "ok");
assert!(
headers["x-request-id"]
.to_str()
.unwrap()
.starts_with("req_")
);
}
#[tokio::test]
async fn fehlender_oder_falscher_key_gibt_401_im_openai_format() {
let gw = gateway(0, false).await;
for key in [None, Some("nx-falsch"), Some("")] {
let (status, headers, body) = gw.get("/v1/models", key).await;
assert_eq!(status, 401, "{key:?}");
assert_eq!(error_code(&body), "invalid_api_key");
assert_eq!(body["error"]["type"], "invalid_request_error");
assert!(headers.contains_key("x-request-id"));
}
let resp = gw
.chat(Some("nx-falsch"), None, &chat_body("bonsai", false))
.await;
assert_eq!(resp.status(), 401);
assert_eq!(
gw.engine.starts.load(Ordering::SeqCst),
0,
"kein Start ohne gültigen Key"
);
}
#[tokio::test]
async fn deaktivierter_key_wird_abgelehnt() {
let gw = gateway(0, false).await;
gw.state.store().set_api_key_active("alle", false).unwrap();
let (status, _, _) = gw.get("/v1/models", Some(&gw.key)).await;
assert_eq!(status, 401);
}
#[tokio::test]
async fn modellliste_zeigt_freigegebene_modelle_je_nach_rechten_auch_ungeladene() {
let gw = gateway(0, false).await;
let ids = |body: &Value| -> Vec<String> {
body["data"]
.as_array()
.unwrap()
.iter()
.map(|m| m["id"].as_str().unwrap().to_string())
.collect()
};
let (status, _, body) = gw.get("/v1/models", Some(&gw.key)).await;
assert_eq!(status, 200);
assert_eq!(body["object"], "list");
assert_eq!(ids(&body), ["bonsai", "zweit"]);
assert_eq!(body["data"][0]["object"], "model");
let (_, _, body) = gw.get("/v1/models", Some(&gw.key_bonsai)).await;
assert_eq!(ids(&body), ["bonsai"]);
assert_eq!(
gw.engine.starts.load(Ordering::SeqCst),
0,
"die Liste lädt nichts"
);
}
#[tokio::test]
async fn einzelnes_modell_abrufen() {
let gw = gateway(0, false).await;
let (status, _, body) = gw.get("/v1/models/bonsai", Some(&gw.key)).await;
assert_eq!(status, 200);
assert_eq!(body["id"], "bonsai");
for pfad in ["/v1/models/gesperrt", "/v1/models/gibt-es-nicht"] {
let (status, _, body) = gw.get(pfad, Some(&gw.key)).await;
assert_eq!(status, 404, "{pfad}");
assert_eq!(error_code(&body), "model_not_found");
}
let (status, _, _) = gw.get("/v1/models/zweit", Some(&gw.key_bonsai)).await;
assert_eq!(status, 404, "nicht freigegeben für diesen Key");
}
#[tokio::test]
async fn chat_ohne_streaming_startet_die_instanz_und_reicht_die_antwort_durch() {
let gw = gateway(0, false).await;
let resp = gw
.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await;
assert_eq!(resp.status(), 200);
assert_eq!(resp.headers()[CONTENT_TYPE], "application/json");
let body: Value = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
assert_eq!(body["choices"][0]["message"]["content"], "Hallo Welt");
assert_eq!(body["model"], "bonsai");
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 1);
// Zweite Anfrage nutzt die laufende Instanz.
gw.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await;
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn streaming_wird_stueckweise_durchgereicht_und_nicht_gepuffert() {
let gw = gateway(0, false).await;
let mut resp = gw
.chat(Some(&gw.key), None, &chat_body("bonsai", true))
.await;
assert_eq!(resp.status(), 200);
assert_eq!(resp.headers()[CONTENT_TYPE], "text/event-stream");
let t0 = Instant::now();
let mut chunks = Vec::new();
while let Some(chunk) = resp.chunk().await.unwrap() {
chunks.push((t0.elapsed(), String::from_utf8(chunk.to_vec()).unwrap()));
}
let all: String = chunks.iter().map(|(_, c)| c.as_str()).collect();
assert!(
all.contains("\"Hal\"") && all.contains("\"lo\"") && all.contains("\" Welt\""),
"{all}"
);
assert!(all.trim_end().ends_with("data: [DONE]"), "{all}");
let first = chunks.first().unwrap().0;
let last = chunks.last().unwrap().0;
assert!(
last - first >= Duration::from_millis(300),
"Stücke kamen nicht nacheinander an: {chunks:?}"
);
}
#[tokio::test]
async fn unbekanntes_oder_nicht_freigegebenes_modell_gibt_404_ohne_start() {
let gw = gateway(0, false).await;
for (key, model) in [
(&gw.key, "gibt-es-nicht"),
(&gw.key, "gesperrt"),
(&gw.key_bonsai, "zweit"),
] {
let resp = gw.chat(Some(key), None, &chat_body(model, false)).await;
assert_eq!(resp.status(), 404, "{model}");
let body: Value = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
assert_eq!(error_code(&body), "model_not_found");
}
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn ungueltige_anfragen_geben_400() {
let gw = gateway(0, false).await;
for body in ["kein json", "{}", "{\"model\": 5}"] {
let resp = gw.chat(Some(&gw.key), None, body).await;
assert_eq!(resp.status(), 400, "{body}");
let json: Value = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
assert_eq!(json["error"]["type"], "invalid_request_error");
}
}
#[tokio::test]
async fn startfehler_gibt_503_und_verraet_keine_details() {
let gw = gateway(0, true).await;
let resp = gw
.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await;
assert_eq!(resp.status(), 503);
let text = resp.text().await.unwrap();
assert!(!text.contains("geheimes-detail"), "{text}");
let body: Value = serde_json::from_str(&text).unwrap();
assert_eq!(error_code(&body), "engine_unavailable");
}
#[tokio::test]
async fn gleichzeitige_anfragen_loesen_nur_einen_ladevorgang_aus() {
let gw = Arc::new(gateway(300, false).await);
let mut tasks = Vec::new();
for _ in 0..6 {
let gw = gw.clone();
tasks.push(tokio::spawn(async move {
gw.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await
.status()
.as_u16()
}));
}
for t in tasks {
assert_eq!(t.await.unwrap(), 200);
}
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn prioritaets_header_wird_gegen_die_hoechstprioritaet_des_keys_geprueft() {
let gw = gateway(0, false).await;
let body = chat_body("bonsai", false);
let prio = |v: &'static str| Some(("X-Gateway-Priority", v));
let resp = gw.chat(Some(&gw.key), prio("high"), &body).await;
assert_eq!(resp.status(), 403);
let json: Value = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
assert_eq!(error_code(&json), "priority_not_permitted");
assert_eq!(
gw.engine.starts.load(Ordering::SeqCst),
0,
"abgelehnt vor dem Start"
);
assert_eq!(
gw.chat(Some(&gw.key_vip), prio("high"), &body)
.await
.status(),
200
);
assert_eq!(
gw.chat(Some(&gw.key), prio("low"), &body).await.status(),
200
);
assert_eq!(
gw.chat(Some(&gw.key), prio("vip"), &body).await.status(),
400
);
}
#[tokio::test]
async fn unbekannte_adresse_gibt_404_im_openai_format() {
let gw = gateway(0, false).await;
let (status, headers, body) = gw.get("/v1/gibt-es-nicht", Some(&gw.key)).await;
assert_eq!(status, 404);
assert_eq!(error_code(&body), "unknown_url");
assert!(headers.contains_key("x-request-id"));
}
#[tokio::test]
async fn herunterfahren_beendet_laufende_instanzen() {
let gw = gateway(0, false).await;
gw.chat(Some(&gw.key), None, &chat_body("bonsai", false))
.await;
gw.chat(Some(&gw.key), None, &chat_body("zweit", false))
.await;
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 2);
gw.state.runtime.shutdown().await;
assert_eq!(gw.engine.stops.load(Ordering::SeqCst), 2);
}