//! 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, AdapterError> { Ok(vec![]) } async fn start(&self, _p: &ProfileSpec) -> Result { 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, state: Arc, /// 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> = 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 { 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); }