230 lines
6.9 KiB
Rust
230 lines
6.9 KiB
Rust
//! Attrappen-Engine: erfüllt den Vertrag ohne Prozesse. Für Scheduler- und
|
|
//! Vertragstests ohne GPU. Ein grüner Test gegen diese Attrappe heißt „verhält
|
|
//! sich wie gebaut“, nicht „Gesamtweg läuft“.
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::Mutex;
|
|
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
|
use std::time::Duration;
|
|
|
|
use async_trait::async_trait;
|
|
|
|
use crate::engine::Engine;
|
|
use crate::types::{
|
|
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Health, InstanceHandle,
|
|
Mode, ProfileSpec, Protocol, Result, Usage,
|
|
};
|
|
|
|
/// Einstellbares Verhalten der Attrappe.
|
|
#[derive(Debug, Clone)]
|
|
pub struct MockConfig {
|
|
pub start_delay: Duration,
|
|
/// Wenn gesetzt, scheitert jeder Start mit dieser Meldung.
|
|
pub fail_start: Option<String>,
|
|
pub vram_mb: u64,
|
|
pub ram_mb: u64,
|
|
pub artifacts: Vec<DiscoveredArtifact>,
|
|
}
|
|
|
|
impl Default for MockConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
start_delay: Duration::ZERO,
|
|
fail_start: None,
|
|
vram_mb: 1024,
|
|
ram_mb: 512,
|
|
artifacts: Vec::new(),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct MockEngine {
|
|
config: MockConfig,
|
|
next_id: AtomicU64,
|
|
starts: AtomicUsize,
|
|
alive: Mutex<HashMap<u64, bool>>,
|
|
}
|
|
|
|
impl MockEngine {
|
|
pub fn new(config: MockConfig) -> Self {
|
|
Self {
|
|
config,
|
|
next_id: AtomicU64::new(1),
|
|
starts: AtomicUsize::new(0),
|
|
alive: Mutex::new(HashMap::new()),
|
|
}
|
|
}
|
|
|
|
/// Wie oft `start` aufgerufen wurde (auch gescheiterte Starts).
|
|
pub fn start_count(&self) -> usize {
|
|
self.starts.load(Ordering::SeqCst)
|
|
}
|
|
|
|
/// Anzahl der Instanzen, die gerade laufen.
|
|
pub fn running(&self) -> usize {
|
|
self.alive.lock().unwrap().values().filter(|a| **a).count()
|
|
}
|
|
|
|
/// Simuliert den Absturz einer Instanz.
|
|
pub fn crash(&self, instance: &InstanceHandle) {
|
|
if let Some(alive) = self.alive.lock().unwrap().get_mut(&instance.id) {
|
|
*alive = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl Engine for MockEngine {
|
|
fn describe(&self) -> EngineInfo {
|
|
EngineInfo {
|
|
name: "mock".to_string(),
|
|
mode: Mode::Managed,
|
|
capabilities: Capabilities {
|
|
chat: true,
|
|
completions: true,
|
|
embeddings: true,
|
|
streaming: true,
|
|
tool_calling: false,
|
|
images: false,
|
|
},
|
|
}
|
|
}
|
|
|
|
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>> {
|
|
Ok(self.config.artifacts.clone())
|
|
}
|
|
|
|
async fn start(&self, profile: &ProfileSpec) -> Result<InstanceHandle> {
|
|
self.starts.fetch_add(1, Ordering::SeqCst);
|
|
if profile.gpus.is_empty() {
|
|
return Err(AdapterError::InvalidProfile(
|
|
"keine GPU angegeben".to_string(),
|
|
));
|
|
}
|
|
tokio::time::sleep(self.config.start_delay).await;
|
|
if let Some(message) = &self.config.fail_start {
|
|
return Err(AdapterError::Spawn(message.clone()));
|
|
}
|
|
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
|
|
self.alive.lock().unwrap().insert(id, true);
|
|
Ok(InstanceHandle {
|
|
id,
|
|
pid: None,
|
|
port: 40000 + id as u16,
|
|
})
|
|
}
|
|
|
|
async fn stop(&self, instance: &InstanceHandle, _grace: Duration) -> Result<()> {
|
|
self.alive.lock().unwrap().remove(&instance.id);
|
|
Ok(())
|
|
}
|
|
|
|
async fn health(&self, instance: &InstanceHandle) -> Health {
|
|
match self.alive.lock().unwrap().get(&instance.id) {
|
|
Some(true) => Health::Ready,
|
|
_ => Health::Gone,
|
|
}
|
|
}
|
|
|
|
fn endpoint(&self, instance: &InstanceHandle) -> Endpoint {
|
|
Endpoint {
|
|
base_url: format!("http://127.0.0.1:{}", instance.port),
|
|
protocol: Protocol::OpenAi,
|
|
upstream_model: None,
|
|
}
|
|
}
|
|
|
|
async fn measure(&self, instance: &InstanceHandle) -> Usage {
|
|
match self.alive.lock().unwrap().get(&instance.id) {
|
|
Some(true) => Usage {
|
|
vram_mb: Some(self.config.vram_mb),
|
|
ram_mb: Some(self.config.ram_mb),
|
|
},
|
|
_ => Usage::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::path::PathBuf;
|
|
|
|
fn profile() -> ProfileSpec {
|
|
ProfileSpec {
|
|
model_alias: "m".to_string(),
|
|
model_path: PathBuf::from("/x.gguf"),
|
|
gpus: vec![0],
|
|
context: None,
|
|
extra_args: vec![],
|
|
}
|
|
}
|
|
|
|
#[tokio::test(start_paused = true)]
|
|
async fn start_wartet_die_ladezeit_ab_und_instanz_ist_bereit() {
|
|
let engine = MockEngine::new(MockConfig {
|
|
start_delay: Duration::from_secs(5),
|
|
..MockConfig::default()
|
|
});
|
|
let t0 = tokio::time::Instant::now();
|
|
let inst = engine.start(&profile()).await.unwrap();
|
|
assert!(t0.elapsed() >= Duration::from_secs(5));
|
|
assert_eq!(engine.health(&inst).await, Health::Ready);
|
|
assert_eq!(engine.running(), 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn stop_ist_idempotent_und_danach_gone() {
|
|
let engine = MockEngine::new(MockConfig::default());
|
|
let inst = engine.start(&profile()).await.unwrap();
|
|
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
|
|
engine.stop(&inst, Duration::from_secs(1)).await.unwrap();
|
|
assert_eq!(engine.health(&inst).await, Health::Gone);
|
|
assert_eq!(engine.measure(&inst).await, Usage::default());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn absturz_wird_als_gone_gemeldet() {
|
|
let engine = MockEngine::new(MockConfig::default());
|
|
let inst = engine.start(&profile()).await.unwrap();
|
|
engine.crash(&inst);
|
|
assert_eq!(engine.health(&inst).await, Health::Gone);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn gescheiterter_start_wird_gezaehlt_und_liefert_fehler() {
|
|
let engine = MockEngine::new(MockConfig {
|
|
fail_start: Some("kein VRAM".to_string()),
|
|
..MockConfig::default()
|
|
});
|
|
let err = engine.start(&profile()).await.unwrap_err();
|
|
assert!(matches!(err, AdapterError::Spawn(_)));
|
|
assert_eq!(engine.start_count(), 1);
|
|
assert_eq!(engine.running(), 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn messung_liefert_eingestellte_werte() {
|
|
let engine = MockEngine::new(MockConfig {
|
|
vram_mb: 4000,
|
|
ram_mb: 800,
|
|
..MockConfig::default()
|
|
});
|
|
let inst = engine.start(&profile()).await.unwrap();
|
|
let usage = engine.measure(&inst).await;
|
|
assert_eq!(usage.vram_mb, Some(4000));
|
|
assert_eq!(usage.ram_mb, Some(800));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn profil_ohne_gpu_wird_abgelehnt() {
|
|
let engine = MockEngine::new(MockConfig::default());
|
|
let mut p = profile();
|
|
p.gpus.clear();
|
|
assert!(matches!(
|
|
engine.start(&p).await,
|
|
Err(AdapterError::InvalidProfile(_))
|
|
));
|
|
}
|
|
}
|