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:
222
crates/nexus-store/src/keys.rs
Normal file
222
crates/nexus-store/src/keys.rs
Normal file
@ -0,0 +1,222 @@
|
||||
//! API-Keys: erzeugen, prüfen, auflisten.
|
||||
|
||||
use nexus_core::{Error, Priority, Result, generate_api_key, hash_api_key};
|
||||
use rusqlite::OptionalExtension;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Store, db};
|
||||
|
||||
/// Rechte eines Keys, gespeichert als JSON in `api_key.rechte`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rights {
|
||||
/// Erlaubte Modell-Namen; `*` erlaubt alle.
|
||||
pub models: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for Rights {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
models: vec!["*".to_string()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rights {
|
||||
pub fn allows(&self, model: &str) -> bool {
|
||||
self.models.iter().any(|m| m == "*" || m == model)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ApiKeyRecord {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub rights: Rights,
|
||||
pub default_priority: Priority,
|
||||
pub max_priority: Priority,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
fn priority(text: &str) -> Result<Priority> {
|
||||
Priority::parse(text)
|
||||
.ok_or_else(|| Error::Db(format!("ungültige Priorität \"{text}\" in der Datenbank")))
|
||||
}
|
||||
|
||||
fn record(row: &rusqlite::Row<'_>) -> rusqlite::Result<(i64, String, String, String, String, i64)> {
|
||||
Ok((
|
||||
row.get(0)?,
|
||||
row.get(1)?,
|
||||
row.get(2)?,
|
||||
row.get(3)?,
|
||||
row.get(4)?,
|
||||
row.get(5)?,
|
||||
))
|
||||
}
|
||||
|
||||
fn build(raw: (i64, String, String, String, String, i64)) -> Result<ApiKeyRecord> {
|
||||
let (id, name, rights, default, max, active) = raw;
|
||||
let rights = serde_json::from_str(&rights)
|
||||
.map_err(|e| Error::Db(format!("Rechte von Key \"{name}\" unlesbar: {e}")))?;
|
||||
Ok(ApiKeyRecord {
|
||||
id,
|
||||
name,
|
||||
rights,
|
||||
default_priority: priority(&default)?,
|
||||
max_priority: priority(&max)?,
|
||||
active: active == 1,
|
||||
})
|
||||
}
|
||||
|
||||
const COLUMNS: &str = "id, name, rechte, standard_prioritaet, max_prioritaet, aktiv";
|
||||
|
||||
impl Store {
|
||||
/// Legt einen Key an und gibt ihn **einmalig** im Klartext zurück; in der
|
||||
/// Datenbank steht nur der Hash.
|
||||
pub fn create_api_key(
|
||||
&self,
|
||||
name: &str,
|
||||
rights: &Rights,
|
||||
default_priority: Priority,
|
||||
max_priority: Priority,
|
||||
) -> Result<String> {
|
||||
if name.trim().is_empty() {
|
||||
return Err(Error::Db("Key-Name darf nicht leer sein".to_string()));
|
||||
}
|
||||
if default_priority > max_priority {
|
||||
return Err(Error::Db(
|
||||
"Standardpriorität darf nicht über der Höchstpriorität liegen".to_string(),
|
||||
));
|
||||
}
|
||||
let key = generate_api_key()?;
|
||||
let rights_json = serde_json::to_string(rights).map_err(|e| Error::Db(e.to_string()))?;
|
||||
self.connection()
|
||||
.execute(
|
||||
"INSERT INTO api_key (name, hash, rechte, standard_prioritaet, max_prioritaet) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
(
|
||||
name,
|
||||
hash_api_key(&key),
|
||||
rights_json,
|
||||
default_priority.as_str(),
|
||||
max_priority.as_str(),
|
||||
),
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// Sucht einen aktiven Key anhand des Klartexts.
|
||||
pub fn find_api_key(&self, key: &str) -> Result<Option<ApiKeyRecord>> {
|
||||
let raw = self
|
||||
.connection()
|
||||
.query_row(
|
||||
&format!("SELECT {COLUMNS} FROM api_key WHERE hash = ?1 AND aktiv = 1"),
|
||||
[hash_api_key(key)],
|
||||
record,
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)?;
|
||||
raw.map(build).transpose()
|
||||
}
|
||||
|
||||
pub fn list_api_keys(&self) -> Result<Vec<ApiKeyRecord>> {
|
||||
let mut stmt = self
|
||||
.connection()
|
||||
.prepare(&format!("SELECT {COLUMNS} FROM api_key ORDER BY name"))
|
||||
.map_err(db)?;
|
||||
let rows = stmt.query_map([], record).map_err(db)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(build(row.map_err(db)?)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Schaltet einen Key ein oder aus. Liefert `false`, wenn es ihn nicht gibt.
|
||||
pub fn set_api_key_active(&self, name: &str, active: bool) -> Result<bool> {
|
||||
let changed = self
|
||||
.connection()
|
||||
.execute(
|
||||
"UPDATE api_key SET aktiv = ?1 WHERE name = ?2",
|
||||
(active as i64, name),
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(changed > 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn key_wird_angelegt_gefunden_und_nur_als_hash_gespeichert() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let key = store
|
||||
.create_api_key("test", &Rights::default(), Priority::Normal, Priority::High)
|
||||
.unwrap();
|
||||
let found = store.find_api_key(&key).unwrap().expect("gefunden");
|
||||
assert_eq!(found.name, "test");
|
||||
assert_eq!(found.max_priority, Priority::High);
|
||||
assert!(found.rights.allows("irgendein-modell"));
|
||||
|
||||
let gespeichert: String = store
|
||||
.connection()
|
||||
.query_row("SELECT hash FROM api_key", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_ne!(gespeichert, key);
|
||||
assert!(!gespeichert.contains(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falscher_oder_deaktivierter_key_wird_nicht_gefunden() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let key = store
|
||||
.create_api_key("a", &Rights::default(), Priority::Normal, Priority::Normal)
|
||||
.unwrap();
|
||||
assert!(store.find_api_key("nx-falsch").unwrap().is_none());
|
||||
assert!(store.set_api_key_active("a", false).unwrap());
|
||||
assert!(store.find_api_key(&key).unwrap().is_none());
|
||||
assert!(!store.set_api_key_active("gibt-es-nicht", false).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standardprioritaet_ueber_hoechstprioritaet_wird_abgelehnt() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let err = store
|
||||
.create_api_key("a", &Rights::default(), Priority::High, Priority::Normal)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("Höchstpriorität"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rechte_pruefen_modellnamen() {
|
||||
let r = Rights {
|
||||
models: vec!["bonsai".to_string()],
|
||||
};
|
||||
assert!(r.allows("bonsai"));
|
||||
assert!(!r.allows("anderes"));
|
||||
assert!(Rights::default().allows("x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doppelter_name_wird_abgelehnt_und_liste_ist_sortiert() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
for n in ["b", "a"] {
|
||||
store
|
||||
.create_api_key(n, &Rights::default(), Priority::Low, Priority::Low)
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
store
|
||||
.create_api_key("a", &Rights::default(), Priority::Low, Priority::Low)
|
||||
.is_err()
|
||||
);
|
||||
let names: Vec<_> = store
|
||||
.list_api_keys()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|k| k.name)
|
||||
.collect();
|
||||
assert_eq!(names, ["a", "b"]);
|
||||
}
|
||||
}
|
||||
@ -10,13 +10,19 @@ use std::path::Path;
|
||||
use nexus_core::{Error, Result};
|
||||
use rusqlite::Connection;
|
||||
|
||||
mod keys;
|
||||
mod registry;
|
||||
|
||||
pub use keys::{ApiKeyRecord, Rights};
|
||||
pub use registry::{ModelEntry, NewLlm, StartPlan};
|
||||
|
||||
/// Alle Migrationen in Reihenfolge. Index 0 ergibt Schema-Version 1.
|
||||
const MIGRATIONS: &[&str] = &[include_str!("../migrations/0001_init.sql")];
|
||||
|
||||
/// Schema-Version, die dieses Crate erzeugt.
|
||||
pub const LATEST_SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64;
|
||||
|
||||
fn db(e: rusqlite::Error) -> Error {
|
||||
pub(crate) fn db(e: rusqlite::Error) -> Error {
|
||||
Error::Db(e.to_string())
|
||||
}
|
||||
|
||||
@ -49,6 +55,10 @@ impl Store {
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
pub(crate) fn transaction(&mut self) -> rusqlite::Result<rusqlite::Transaction<'_>> {
|
||||
self.conn.transaction()
|
||||
}
|
||||
|
||||
fn migrate(&mut self) -> Result<()> {
|
||||
let current = self.schema_version()?;
|
||||
if current > LATEST_SCHEMA_VERSION {
|
||||
|
||||
287
crates/nexus-store/src/registry.rs
Normal file
287
crates/nexus-store/src/registry.rs
Normal file
@ -0,0 +1,287 @@
|
||||
//! Registry: Modelle, Artifacts, Profile und die Wahl des Startprofils.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use nexus_core::{Error, Result};
|
||||
use rusqlite::OptionalExtension;
|
||||
|
||||
use crate::{Store, db};
|
||||
|
||||
/// Name der Engine-Zeile für llama.cpp.
|
||||
pub const LLAMA_CPP: &str = "llama.cpp";
|
||||
|
||||
/// Eingabe für `register_llm`: ein Sprachmodell mit einem Startprofil.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NewLlm {
|
||||
pub name: String,
|
||||
pub path: PathBuf,
|
||||
pub quantization: Option<String>,
|
||||
pub size_bytes: Option<i64>,
|
||||
pub gpus: Vec<u32>,
|
||||
pub context: Option<u32>,
|
||||
pub vram_mb: Option<i64>,
|
||||
pub ram_mb: Option<i64>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ModelEntry {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// Alles, was zum Starten einer Instanz nötig ist.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StartPlan {
|
||||
pub model: String,
|
||||
pub engine_name: String,
|
||||
pub model_path: PathBuf,
|
||||
pub gpus: Vec<u32>,
|
||||
pub context: Option<u32>,
|
||||
pub extra_args: Vec<String>,
|
||||
}
|
||||
|
||||
fn parse_gpus(text: &str) -> Result<Vec<u32>> {
|
||||
text.split(',')
|
||||
.map(|g| {
|
||||
g.trim()
|
||||
.parse::<u32>()
|
||||
.map_err(|_| Error::Db(format!("ungültige GPU-Liste \"{text}\"")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Store {
|
||||
/// Legt Engine (falls nötig), Modell, Artifact und Profil in einem Schritt
|
||||
/// an. Scheitert, wenn es den Modellnamen schon gibt.
|
||||
pub fn register_llm(&mut self, new: &NewLlm) -> Result<()> {
|
||||
if new.name.trim().is_empty() {
|
||||
return Err(Error::Db("Modellname darf nicht leer sein".to_string()));
|
||||
}
|
||||
if new.gpus.is_empty() {
|
||||
return Err(Error::Db("mindestens eine GPU angeben".to_string()));
|
||||
}
|
||||
let gpus = new
|
||||
.gpus
|
||||
.iter()
|
||||
.map(u32::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let tx = self.transaction().map_err(db)?;
|
||||
tx.execute(
|
||||
"INSERT OR IGNORE INTO engine (name, art, modus) VALUES (?1, ?1, 'managed')",
|
||||
[LLAMA_CPP],
|
||||
)
|
||||
.map_err(db)?;
|
||||
let engine_id: i64 = tx
|
||||
.query_row("SELECT id FROM engine WHERE name = ?1", [LLAMA_CPP], |r| {
|
||||
r.get(0)
|
||||
})
|
||||
.map_err(db)?;
|
||||
tx.execute(
|
||||
"INSERT INTO model (name, art, freigegeben) VALUES (?1, 'llm', ?2)",
|
||||
(&new.name, new.enabled as i64),
|
||||
)
|
||||
.map_err(db)?;
|
||||
let model_id = tx.last_insert_rowid();
|
||||
tx.execute(
|
||||
"INSERT INTO artifact (model_id, engine_id, pfad, quantisierung, groesse_bytes) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
(
|
||||
model_id,
|
||||
engine_id,
|
||||
new.path.display().to_string(),
|
||||
&new.quantization,
|
||||
new.size_bytes,
|
||||
),
|
||||
)
|
||||
.map_err(db)?;
|
||||
let artifact_id = tx.last_insert_rowid();
|
||||
tx.execute(
|
||||
"INSERT INTO profile (artifact_id, gpus, vram_mb, ram_mb, kontext) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
(artifact_id, gpus, new.vram_mb, new.ram_mb, new.context),
|
||||
)
|
||||
.map_err(db)?;
|
||||
tx.commit().map_err(db)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn list_models(&self, only_enabled: bool) -> Result<Vec<ModelEntry>> {
|
||||
let sql = if only_enabled {
|
||||
"SELECT name, art, freigegeben FROM model WHERE freigegeben = 1 ORDER BY name"
|
||||
} else {
|
||||
"SELECT name, art, freigegeben FROM model ORDER BY name"
|
||||
};
|
||||
let mut stmt = self.connection().prepare(sql).map_err(db)?;
|
||||
let rows = stmt
|
||||
.query_map([], |r| {
|
||||
Ok(ModelEntry {
|
||||
name: r.get(0)?,
|
||||
kind: r.get(1)?,
|
||||
enabled: r.get::<_, i64>(2)? == 1,
|
||||
})
|
||||
})
|
||||
.map_err(db)?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>().map_err(db)
|
||||
}
|
||||
|
||||
/// Gibt ein Modell frei oder sperrt es. `false`, wenn es das Modell nicht gibt.
|
||||
pub fn set_model_enabled(&self, name: &str, enabled: bool) -> Result<bool> {
|
||||
let changed = self
|
||||
.connection()
|
||||
.execute(
|
||||
"UPDATE model SET freigegeben = ?1 WHERE name = ?2",
|
||||
(enabled as i64, name),
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(changed > 0)
|
||||
}
|
||||
|
||||
/// Wählt für ein freigegebenes Modell das Profil mit dem niedrigsten
|
||||
/// `rang`. `None`, wenn das Modell fehlt, gesperrt ist oder kein Profil hat.
|
||||
pub fn start_plan(&self, model: &str) -> Result<Option<StartPlan>> {
|
||||
let row = self
|
||||
.connection()
|
||||
.query_row(
|
||||
"SELECT e.name, a.pfad, p.gpus, p.kontext, p.parameter
|
||||
FROM model m
|
||||
JOIN artifact a ON a.model_id = m.id
|
||||
JOIN engine e ON e.id = a.engine_id AND e.aktiv = 1
|
||||
JOIN profile p ON p.artifact_id = a.id
|
||||
WHERE m.name = ?1 AND m.freigegeben = 1
|
||||
ORDER BY p.rang, p.id LIMIT 1",
|
||||
[model],
|
||||
|r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, Option<u32>>(3)?,
|
||||
r.get::<_, String>(4)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)?;
|
||||
let Some((engine_name, path, gpus, context, parameter)) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let params: serde_json::Value = serde_json::from_str(¶meter)
|
||||
.map_err(|e| Error::Db(format!("Profilparameter von \"{model}\" unlesbar: {e}")))?;
|
||||
let extra_args = params
|
||||
.get("args")
|
||||
.and_then(|a| a.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.as_str().map(str::to_string))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Ok(Some(StartPlan {
|
||||
model: model.to_string(),
|
||||
engine_name,
|
||||
model_path: PathBuf::from(path),
|
||||
gpus: parse_gpus(&gpus)?,
|
||||
context,
|
||||
extra_args,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn neu(name: &str) -> NewLlm {
|
||||
NewLlm {
|
||||
name: name.to_string(),
|
||||
path: PathBuf::from(format!("/srv/models/{name}.gguf")),
|
||||
quantization: Some("Q4_0".to_string()),
|
||||
size_bytes: Some(100),
|
||||
gpus: vec![0, 1],
|
||||
context: Some(4096),
|
||||
vram_mb: Some(2000),
|
||||
ram_mb: Some(500),
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modell_wird_registriert_und_startplan_ist_vollstaendig() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
store.register_llm(&neu("bonsai")).unwrap();
|
||||
let plan = store.start_plan("bonsai").unwrap().expect("Plan");
|
||||
assert_eq!(plan.engine_name, "llama.cpp");
|
||||
assert_eq!(plan.model_path, PathBuf::from("/srv/models/bonsai.gguf"));
|
||||
assert_eq!(plan.gpus, vec![0, 1]);
|
||||
assert_eq!(plan.context, Some(4096));
|
||||
assert!(plan.extra_args.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zweites_modell_nutzt_dieselbe_engine_und_doppelter_name_scheitert() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
store.register_llm(&neu("a")).unwrap();
|
||||
store.register_llm(&neu("b")).unwrap();
|
||||
let engines: i64 = store
|
||||
.connection()
|
||||
.query_row("SELECT COUNT(*) FROM engine", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(engines, 1);
|
||||
assert!(store.register_llm(&neu("a")).is_err());
|
||||
// Die gescheiterte Registrierung hat nichts halb angelegt.
|
||||
let artifacts: i64 = store
|
||||
.connection()
|
||||
.query_row("SELECT COUNT(*) FROM artifact", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(artifacts, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gesperrte_und_unbekannte_modelle_haben_keinen_startplan() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
store.register_llm(&neu("a")).unwrap();
|
||||
assert!(store.start_plan("unbekannt").unwrap().is_none());
|
||||
assert!(store.set_model_enabled("a", false).unwrap());
|
||||
assert!(store.start_plan("a").unwrap().is_none());
|
||||
assert!(!store.set_model_enabled("gibt-es-nicht", true).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn liste_kennt_freigegebene_und_alle_modelle() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
store.register_llm(&neu("a")).unwrap();
|
||||
let mut gesperrt = neu("b");
|
||||
gesperrt.enabled = false;
|
||||
store.register_llm(&gesperrt).unwrap();
|
||||
assert_eq!(store.list_models(true).unwrap().len(), 1);
|
||||
assert_eq!(store.list_models(false).unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profil_mit_niedrigerem_rang_gewinnt_und_args_werden_gelesen() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
store.register_llm(&neu("a")).unwrap();
|
||||
let c = store.connection();
|
||||
let artifact: i64 = c
|
||||
.query_row("SELECT id FROM artifact", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
c.execute(
|
||||
"INSERT INTO profile (artifact_id, gpus, parameter, kontext, rang) VALUES (?1, '1', '{\"args\":[\"--flash-attn\"]}', 2048, -1)",
|
||||
[artifact],
|
||||
)
|
||||
.unwrap();
|
||||
let plan = store.start_plan("a").unwrap().unwrap();
|
||||
assert_eq!(plan.gpus, vec![1]);
|
||||
assert_eq!(plan.context, Some(2048));
|
||||
assert_eq!(plan.extra_args, vec!["--flash-attn".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profil_ohne_gpu_wird_nicht_registriert() {
|
||||
let mut store = Store::open_in_memory().unwrap();
|
||||
let mut n = neu("a");
|
||||
n.gpus.clear();
|
||||
assert!(store.register_llm(&n).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user