feat: Grundgerüst mit Konfiguration, SQLite-Schema und Selbsttest (M2.1)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
11
crates/nexus-core/Cargo.toml
Normal file
11
crates/nexus-core/Cargo.toml
Normal file
@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "nexus-core"
|
||||
description = "Nexus: gemeinsame Typen, Fehler und Konfiguration"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
toml.workspace = true
|
||||
10
crates/nexus-core/README.md
Normal file
10
crates/nexus-core/README.md
Normal file
@ -0,0 +1,10 @@
|
||||
# nexus-core
|
||||
|
||||
Gemeinsame Typen, Fehler und Konfiguration. Keine Abhängigkeit zu Datenbank oder Netzwerk.
|
||||
|
||||
**Version:** wie der Workspace (`0.1.0-dev`). **Schnittstelle:**
|
||||
- `Config` (`from_toml`, `load`, `validate`, `db_path`): Felder `listen` und `data_dir`, Standardwerte, unbekannte Felder werden abgelehnt, keine Geheimnisse.
|
||||
- `Error` (`Config`, `Io`, `Db`) und `Result`.
|
||||
- `VERSION`.
|
||||
|
||||
**Tests:** `cargo test -p nexus-core` (Einheitentests für Standardwerte, Fehlerfälle, Datei lesen).
|
||||
105
crates/nexus-core/src/config.rs
Normal file
105
crates/nexus-core/src/config.rs
Normal file
@ -0,0 +1,105 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Konfiguration des Gateways. Enthält keine Geheimnisse.
|
||||
///
|
||||
/// Alle Felder haben Standardwerte; unbekannte Felder werden abgelehnt,
|
||||
/// damit Tippfehler auffallen.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// Adresse, auf der das Gateway lauscht, zum Beispiel `127.0.0.1:8080`.
|
||||
pub listen: String,
|
||||
/// Ordner für Datenbank, Logs und Ergebnisse.
|
||||
pub data_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
listen: "127.0.0.1:8080".to_string(),
|
||||
data_dir: PathBuf::from("data"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Liest die Konfiguration aus TOML-Text und prüft sie.
|
||||
pub fn from_toml(text: &str) -> Result<Self> {
|
||||
let config: Config = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;
|
||||
config.validate()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Liest die Konfiguration aus einer Datei.
|
||||
pub fn load(path: &Path) -> Result<Self> {
|
||||
let text = std::fs::read_to_string(path).map_err(|source| Error::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
Self::from_toml(&text)
|
||||
}
|
||||
|
||||
/// Prüft die Werte, die sich ohne Zugriff auf das System prüfen lassen.
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
self.listen.parse::<SocketAddr>().map_err(|e| {
|
||||
Error::Config(format!("listen \"{}\" ist keine Adresse: {e}", self.listen))
|
||||
})?;
|
||||
if self.data_dir.as_os_str().is_empty() {
|
||||
return Err(Error::Config("data_dir darf nicht leer sein".to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pfad der SQLite-Datenbank.
|
||||
pub fn db_path(&self) -> PathBuf {
|
||||
self.data_dir.join("nexus.db")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn leere_konfiguration_nutzt_standardwerte() {
|
||||
let c = Config::from_toml("").unwrap();
|
||||
assert_eq!(c, Config::default());
|
||||
assert_eq!(c.listen, "127.0.0.1:8080");
|
||||
assert_eq!(c.db_path(), PathBuf::from("data/nexus.db"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn werte_werden_uebernommen() {
|
||||
let c = Config::from_toml("listen = \"0.0.0.0:9000\"\ndata_dir = \"/srv/nexus\"").unwrap();
|
||||
assert_eq!(c.listen, "0.0.0.0:9000");
|
||||
assert_eq!(c.db_path(), PathBuf::from("/srv/nexus/nexus.db"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbekanntes_feld_wird_abgelehnt() {
|
||||
let err = Config::from_toml("lisen = \"127.0.0.1:1\"").unwrap_err();
|
||||
assert!(matches!(err, Error::Config(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ungueltige_adresse_wird_abgelehnt() {
|
||||
let err = Config::from_toml("listen = \"nirgendwo\"").unwrap_err();
|
||||
assert!(err.to_string().contains("keine Adresse"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leeres_datenverzeichnis_wird_abgelehnt() {
|
||||
assert!(Config::from_toml("data_dir = \"\"").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fehlende_datei_ist_ein_io_fehler() {
|
||||
let err = Config::load(Path::new("/nicht/vorhanden/config.toml")).unwrap_err();
|
||||
assert!(matches!(err, Error::Io { .. }));
|
||||
}
|
||||
}
|
||||
23
crates/nexus-core/src/error.rs
Normal file
23
crates/nexus-core/src/error.rs
Normal file
@ -0,0 +1,23 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Fehler, die mehrere Nexus-Crates gemeinsam verwenden.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// Die Konfiguration fehlt, ist unlesbar oder ungültig.
|
||||
#[error("Konfiguration: {0}")]
|
||||
Config(String),
|
||||
|
||||
/// Ein Dateizugriff ist fehlgeschlagen.
|
||||
#[error("Dateizugriff auf {path}: {source}")]
|
||||
Io {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
|
||||
/// Ein Datenbankfehler (Text, damit dieses Crate ohne Datenbank auskommt).
|
||||
#[error("Datenbank: {0}")]
|
||||
Db(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
12
crates/nexus-core/src/lib.rs
Normal file
12
crates/nexus-core/src/lib.rs
Normal file
@ -0,0 +1,12 @@
|
||||
//! Gemeinsame Typen, Fehler und Konfiguration für alle Nexus-Crates.
|
||||
//!
|
||||
//! Dieses Crate hat keine Abhängigkeit zu Datenbank oder Netzwerk.
|
||||
|
||||
mod config;
|
||||
mod error;
|
||||
|
||||
pub use config::Config;
|
||||
pub use error::{Error, Result};
|
||||
|
||||
/// Version des Nexus-Workspaces.
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
10
crates/nexus-store/Cargo.toml
Normal file
10
crates/nexus-store/Cargo.toml
Normal file
@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "nexus-store"
|
||||
description = "Nexus: SQLite-Speicher mit Migrationen"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
nexus-core.workspace = true
|
||||
rusqlite.workspace = true
|
||||
12
crates/nexus-store/README.md
Normal file
12
crates/nexus-store/README.md
Normal file
@ -0,0 +1,12 @@
|
||||
# nexus-store
|
||||
|
||||
SQLite-Speicher mit Migrationen. Datenmodell siehe `docs/m1-spezifikation.md`, Abschnitt 5.
|
||||
|
||||
**Version:** wie der Workspace (`0.1.0-dev`). **Schnittstelle:**
|
||||
- `Store::open(pfad)` und `Store::open_in_memory()`: öffnen und automatisch migrieren (WAL, Fremdschlüssel an).
|
||||
- `schema_version()`, `integrity_check()`, `connection()`.
|
||||
- `LATEST_SCHEMA_VERSION`. Eine Datenbank mit neuerer Schema-Version wird abgelehnt.
|
||||
|
||||
**Migrationen:** `migrations/NNNN_name.sql`, nur vorwärts, Stand in `PRAGMA user_version`. Neue Migration = neue Datei und ein Eintrag in `MIGRATIONS`.
|
||||
|
||||
**Tests:** `cargo test -p nexus-store` (Migration, erneutes Öffnen, Fremdschlüssel, Prüfregeln, Eindeutigkeit).
|
||||
128
crates/nexus-store/migrations/0001_init.sql
Normal file
128
crates/nexus-store/migrations/0001_init.sql
Normal file
@ -0,0 +1,128 @@
|
||||
-- Nexus Datenmodell, Stand M2.1 (siehe docs/m1-spezifikation.md, Abschnitt 5).
|
||||
-- Zeiten sind UTC im Format ISO 8601 als Text.
|
||||
-- Ein Worker (`local`) ist im MVP fest; die Spalte worker_id bereitet die
|
||||
-- spätere Trennung von Gateway und Worker vor (Abschnitt 13).
|
||||
|
||||
CREATE TABLE worker (
|
||||
id TEXT PRIMARY KEY
|
||||
) STRICT;
|
||||
INSERT INTO worker (id) VALUES ('local');
|
||||
|
||||
CREATE TABLE engine (
|
||||
id INTEGER PRIMARY KEY,
|
||||
worker_id TEXT NOT NULL DEFAULT 'local' REFERENCES worker (id),
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
art TEXT NOT NULL,
|
||||
modus TEXT NOT NULL CHECK (modus IN ('managed', 'external', 'attached')),
|
||||
rezept TEXT,
|
||||
basis_url TEXT,
|
||||
version TEXT,
|
||||
aktiv INTEGER NOT NULL DEFAULT 1 CHECK (aktiv IN (0, 1))
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE model (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
art TEXT NOT NULL CHECK (art IN ('llm', 'embedding', 'bild')),
|
||||
freigegeben INTEGER NOT NULL DEFAULT 0 CHECK (freigegeben IN (0, 1))
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE artifact (
|
||||
id INTEGER PRIMARY KEY,
|
||||
model_id INTEGER NOT NULL REFERENCES model (id) ON DELETE CASCADE,
|
||||
engine_id INTEGER NOT NULL REFERENCES engine (id),
|
||||
pfad TEXT NOT NULL,
|
||||
quantisierung TEXT,
|
||||
groesse_bytes INTEGER
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE profile (
|
||||
id INTEGER PRIMARY KEY,
|
||||
artifact_id INTEGER NOT NULL REFERENCES artifact (id) ON DELETE CASCADE,
|
||||
gpus TEXT NOT NULL,
|
||||
parameter TEXT NOT NULL DEFAULT '{}',
|
||||
vram_mb INTEGER,
|
||||
ram_mb INTEGER,
|
||||
kontext INTEGER,
|
||||
rang INTEGER NOT NULL DEFAULT 0
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE instance (
|
||||
id INTEGER PRIMARY KEY,
|
||||
profile_id INTEGER NOT NULL REFERENCES profile (id),
|
||||
worker_id TEXT NOT NULL DEFAULT 'local' REFERENCES worker (id),
|
||||
zustand TEXT NOT NULL CHECK (zustand IN ('startend', 'bereit', 'entladend', 'beendet', 'fehler')),
|
||||
pid INTEGER,
|
||||
port INTEGER,
|
||||
gpus TEXT NOT NULL,
|
||||
gestartet TEXT,
|
||||
zuletzt_genutzt TEXT,
|
||||
aktive_jobs INTEGER NOT NULL DEFAULT 0 CHECK (aktive_jobs >= 0)
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE api_key (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
hash TEXT NOT NULL UNIQUE,
|
||||
rechte TEXT NOT NULL DEFAULT '{}',
|
||||
standard_prioritaet TEXT NOT NULL DEFAULT 'normal' CHECK (standard_prioritaet IN ('high', 'normal', 'low')),
|
||||
max_prioritaet TEXT NOT NULL DEFAULT 'normal' CHECK (max_prioritaet IN ('high', 'normal', 'low')),
|
||||
aktiv INTEGER NOT NULL DEFAULT 1 CHECK (aktiv IN (0, 1))
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE benutzer (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
passwort_hash TEXT NOT NULL,
|
||||
rolle TEXT NOT NULL CHECK (rolle IN ('admin', 'nutzer')),
|
||||
aktiv INTEGER NOT NULL DEFAULT 1 CHECK (aktiv IN (0, 1))
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE job (
|
||||
id INTEGER PRIMARY KEY,
|
||||
art TEXT NOT NULL,
|
||||
zustand TEXT NOT NULL CHECK (zustand IN ('wartend', 'laufend', 'fertig', 'abgebrochen', 'fehlgeschlagen')),
|
||||
prioritaet TEXT NOT NULL CHECK (prioritaet IN ('high', 'normal', 'low')),
|
||||
api_key_id INTEGER REFERENCES api_key (id),
|
||||
model_id INTEGER REFERENCES model (id),
|
||||
profile_id INTEGER REFERENCES profile (id),
|
||||
korrelation TEXT NOT NULL,
|
||||
erstellt TEXT NOT NULL,
|
||||
gestartet TEXT,
|
||||
beendet TEXT,
|
||||
fehler TEXT
|
||||
) STRICT;
|
||||
CREATE INDEX job_zustand ON job (zustand, prioritaet, erstellt);
|
||||
|
||||
CREATE TABLE workflow (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
engine_id INTEGER NOT NULL REFERENCES engine (id),
|
||||
datei TEXT NOT NULL,
|
||||
parameter_schema TEXT NOT NULL DEFAULT '{}',
|
||||
freigegeben INTEGER NOT NULL DEFAULT 0 CHECK (freigegeben IN (0, 1))
|
||||
) STRICT;
|
||||
|
||||
-- Audit und Anfrage-Log enthalten nie Prompts, Antworten oder Schlüssel.
|
||||
CREATE TABLE audit (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zeit TEXT NOT NULL,
|
||||
akteur TEXT NOT NULL,
|
||||
aktion TEXT NOT NULL,
|
||||
ziel TEXT,
|
||||
korrelation TEXT
|
||||
) STRICT;
|
||||
|
||||
CREATE TABLE anfrage_log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zeit TEXT NOT NULL,
|
||||
korrelation TEXT NOT NULL,
|
||||
api_key_id INTEGER REFERENCES api_key (id),
|
||||
model_id INTEGER REFERENCES model (id),
|
||||
status INTEGER NOT NULL,
|
||||
wartezeit_ms INTEGER,
|
||||
latenz_ms INTEGER,
|
||||
tokens_ein INTEGER,
|
||||
tokens_aus INTEGER
|
||||
) STRICT;
|
||||
CREATE INDEX anfrage_log_zeit ON anfrage_log (zeit);
|
||||
259
crates/nexus-store/src/lib.rs
Normal file
259
crates/nexus-store/src/lib.rs
Normal file
@ -0,0 +1,259 @@
|
||||
//! SQLite-Speicher für Nexus: Datei öffnen, Migrationen anwenden, prüfen.
|
||||
//!
|
||||
//! Die Migrationen liegen in `migrations/` und sind nur vorwärts gerichtet.
|
||||
//! Der Stand steht in `PRAGMA user_version`. Wer eine ältere Datenbank öffnet,
|
||||
//! bekommt sie automatisch auf den neuesten Stand; eine Datenbank von einer
|
||||
//! neueren Version wird abgelehnt.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use nexus_core::{Error, Result};
|
||||
use rusqlite::Connection;
|
||||
|
||||
/// 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 {
|
||||
Error::Db(e.to_string())
|
||||
}
|
||||
|
||||
/// Geöffnete Datenbank mit angewendeten Migrationen.
|
||||
pub struct Store {
|
||||
conn: Connection,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
/// Öffnet (und erzeugt bei Bedarf) die Datenbankdatei und migriert sie.
|
||||
/// Der Ordner der Datei muss existieren.
|
||||
pub fn open(path: &Path) -> Result<Self> {
|
||||
let conn = Connection::open(path).map_err(db)?;
|
||||
conn.pragma_update(None, "journal_mode", "WAL")
|
||||
.map_err(db)?;
|
||||
Self::prepare(conn)
|
||||
}
|
||||
|
||||
/// Öffnet eine Datenbank nur im Speicher (für Tests).
|
||||
pub fn open_in_memory() -> Result<Self> {
|
||||
Self::prepare(Connection::open_in_memory().map_err(db)?)
|
||||
}
|
||||
|
||||
fn prepare(conn: Connection) -> Result<Self> {
|
||||
conn.pragma_update(None, "foreign_keys", "ON").map_err(db)?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))
|
||||
.map_err(db)?;
|
||||
let mut store = Self { conn };
|
||||
store.migrate()?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
fn migrate(&mut self) -> Result<()> {
|
||||
let current = self.schema_version()?;
|
||||
if current > LATEST_SCHEMA_VERSION {
|
||||
return Err(Error::Db(format!(
|
||||
"Datenbank hat Schema-Version {current}, dieses Programm kennt nur {LATEST_SCHEMA_VERSION}"
|
||||
)));
|
||||
}
|
||||
for (index, sql) in MIGRATIONS.iter().enumerate() {
|
||||
let version = index as i64 + 1;
|
||||
if version <= current {
|
||||
continue;
|
||||
}
|
||||
let tx = self.conn.transaction().map_err(db)?;
|
||||
tx.execute_batch(sql).map_err(db)?;
|
||||
tx.pragma_update(None, "user_version", version)
|
||||
.map_err(db)?;
|
||||
tx.commit().map_err(db)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Aktuelle Schema-Version der geöffneten Datenbank.
|
||||
pub fn schema_version(&self) -> Result<i64> {
|
||||
self.conn
|
||||
.pragma_query_value(None, "user_version", |row| row.get(0))
|
||||
.map_err(db)
|
||||
}
|
||||
|
||||
/// Führt SQLites Integritätsprüfung und die Fremdschlüsselprüfung aus.
|
||||
pub fn integrity_check(&self) -> Result<()> {
|
||||
let result: String = self
|
||||
.conn
|
||||
.pragma_query_value(None, "integrity_check", |row| row.get(0))
|
||||
.map_err(db)?;
|
||||
if result != "ok" {
|
||||
return Err(Error::Db(format!("Integritätsprüfung: {result}")));
|
||||
}
|
||||
let mut stmt = self.conn.prepare("PRAGMA foreign_key_check").map_err(db)?;
|
||||
let broken = stmt.query_map([], |_| Ok(())).map_err(db)?.count();
|
||||
if broken > 0 {
|
||||
return Err(Error::Db(format!("{broken} Fremdschlüssel verletzt")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Zugriff auf die Verbindung für Abfragen anderer Module.
|
||||
pub fn connection(&self) -> &Connection {
|
||||
&self.conn
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
static ZAEHLER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Eigener Testordner ohne Zusatz-Abhängigkeit; wird am Ende entfernt.
|
||||
struct Testordner(std::path::PathBuf);
|
||||
|
||||
impl Testordner {
|
||||
fn neu() -> Self {
|
||||
let n = ZAEHLER.fetch_add(1, Ordering::SeqCst);
|
||||
let pfad =
|
||||
std::env::temp_dir().join(format!("nexus-store-test-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&pfad).unwrap();
|
||||
Self(pfad)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Testordner {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn engine_einfuegen(store: &Store) -> i64 {
|
||||
store
|
||||
.connection()
|
||||
.execute(
|
||||
"INSERT INTO engine (name, art, modus) VALUES ('llama.cpp', 'llm', 'managed')",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
store.connection().last_insert_rowid()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neue_datenbank_hat_neueste_version() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
assert_eq!(store.schema_version().unwrap(), LATEST_SCHEMA_VERSION);
|
||||
store.integrity_check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erneutes_oeffnen_aendert_nichts_und_behaelt_daten() {
|
||||
let ordner = Testordner::neu();
|
||||
let pfad = ordner.0.join("nexus.db");
|
||||
{
|
||||
let store = Store::open(&pfad).unwrap();
|
||||
engine_einfuegen(&store);
|
||||
}
|
||||
let store = Store::open(&pfad).unwrap();
|
||||
assert_eq!(store.schema_version().unwrap(), LATEST_SCHEMA_VERSION);
|
||||
let anzahl: i64 = store
|
||||
.connection()
|
||||
.query_row("SELECT COUNT(*) FROM engine", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(anzahl, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neuere_datenbank_wird_abgelehnt() {
|
||||
let ordner = Testordner::neu();
|
||||
let pfad = ordner.0.join("nexus.db");
|
||||
{
|
||||
let store = Store::open(&pfad).unwrap();
|
||||
store
|
||||
.connection()
|
||||
.pragma_update(None, "user_version", LATEST_SCHEMA_VERSION + 1)
|
||||
.unwrap();
|
||||
}
|
||||
let err = Store::open(&pfad).err().expect("muss scheitern");
|
||||
assert!(err.to_string().contains("Schema-Version"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_worker_local_existiert() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let id: String = store
|
||||
.connection()
|
||||
.query_row("SELECT id FROM worker", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(id, "local");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modell_artifact_profil_kette_funktioniert() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let c = store.connection();
|
||||
let engine = engine_einfuegen(&store);
|
||||
c.execute(
|
||||
"INSERT INTO model (name, art, freigegeben) VALUES ('bonsai', 'llm', 1)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
let model = c.last_insert_rowid();
|
||||
c.execute(
|
||||
"INSERT INTO artifact (model_id, engine_id, pfad, quantisierung) VALUES (?1, ?2, '/srv/models/gguf/Bonsai-1.7B-Q1_0.gguf', 'Q1_0')",
|
||||
(model, engine),
|
||||
)
|
||||
.unwrap();
|
||||
let artifact = c.last_insert_rowid();
|
||||
c.execute(
|
||||
"INSERT INTO profile (artifact_id, gpus, vram_mb, ram_mb, kontext) VALUES (?1, '0', 1024, 2048, 4096)",
|
||||
[artifact],
|
||||
)
|
||||
.unwrap();
|
||||
store.integrity_check().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fremdschluessel_werden_erzwungen() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let err = store.connection().execute(
|
||||
"INSERT INTO artifact (model_id, engine_id, pfad) VALUES (999, 999, 'x')",
|
||||
[],
|
||||
);
|
||||
assert!(err.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_regeln_lehnen_ungueltige_werte_ab() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let c = store.connection();
|
||||
assert!(
|
||||
c.execute(
|
||||
"INSERT INTO engine (name, art, modus) VALUES ('x', 'llm', 'unbekannt')",
|
||||
[]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
c.execute("INSERT INTO model (name, art) VALUES ('m', 'audio')", [])
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
c.execute(
|
||||
"INSERT INTO api_key (name, hash, max_prioritaet) VALUES ('k', 'h', 'vip')",
|
||||
[]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_hash_ist_eindeutig() {
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
let c = store.connection();
|
||||
c.execute("INSERT INTO api_key (name, hash) VALUES ('a', 'h1')", [])
|
||||
.unwrap();
|
||||
assert!(
|
||||
c.execute("INSERT INTO api_key (name, hash) VALUES ('b', 'h1')", [])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
14
crates/nexus/Cargo.toml
Normal file
14
crates/nexus/Cargo.toml
Normal file
@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "nexus"
|
||||
description = "Nexus: AI Gateway für srv04"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "nexus"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
nexus-core.workspace = true
|
||||
nexus-store.workspace = true
|
||||
11
crates/nexus/README.md
Normal file
11
crates/nexus/README.md
Normal file
@ -0,0 +1,11 @@
|
||||
# nexus (Binary)
|
||||
|
||||
Verdrahtung und Befehlszeile. Stand M2.1: `nexus version`, `nexus selftest [--config PFAD]` (oder `NEXUS_CONFIG`).
|
||||
|
||||
Der Selbsttest prüft Konfiguration, Datenverzeichnis (beschreibbar), Datenbank (Migration) und Integrität. Er legt Datenverzeichnis und Datenbank bei Bedarf an, startet keine Engines und ändert nichts außerhalb des Datenverzeichnisses. Rezepte und Engines kommen mit den Adaptern (M2.2).
|
||||
|
||||
Exit-Code 0 bei Erfolg, 1 bei fehlgeschlagener Prüfung, 2 bei falschem Aufruf.
|
||||
|
||||
**Bauen für srv04:** `cargo build --release --target x86_64-unknown-linux-musl -p nexus` (statisches Binary, Entscheidung #1039).
|
||||
|
||||
**Tests:** `cargo test -p nexus`.
|
||||
79
crates/nexus/src/main.rs
Normal file
79
crates/nexus/src/main.rs
Normal file
@ -0,0 +1,79 @@
|
||||
//! Nexus: AI Gateway für srv04.
|
||||
//!
|
||||
//! Stand M2.1: `version` und `selftest`. Der Server kommt mit M2.3.
|
||||
|
||||
mod selftest;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
const HILFE: &str = "\
|
||||
Nexus – AI Gateway für srv04
|
||||
|
||||
Aufruf:
|
||||
nexus version Version anzeigen
|
||||
nexus selftest [--config PFAD] Konfiguration, Datenverzeichnis und Datenbank prüfen
|
||||
nexus help Diese Hilfe
|
||||
|
||||
Die Konfiguration kann auch über die Umgebungsvariable NEXUS_CONFIG angegeben werden.
|
||||
";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
match args.first().map(String::as_str) {
|
||||
Some("version") | Some("--version") => {
|
||||
println!("nexus {}", nexus_core::VERSION);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Some("selftest") => run_selftest(&args[1..]),
|
||||
Some("help") | Some("--help") | None => {
|
||||
print!("{HILFE}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Some(other) => {
|
||||
eprintln!("Unbekannter Befehl: {other}\n");
|
||||
eprint!("{HILFE}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_selftest(args: &[String]) -> ExitCode {
|
||||
let config = match config_path(args) {
|
||||
Ok(path) => path,
|
||||
Err(message) => {
|
||||
eprintln!("{message}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let checks = selftest::run(config.as_deref());
|
||||
let mut failed = 0;
|
||||
for c in &checks {
|
||||
match &c.result {
|
||||
Ok(detail) => println!("ok {}: {detail}", c.name),
|
||||
Err(detail) => {
|
||||
failed += 1;
|
||||
println!("FEHLER {}: {detail}", c.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if failed == 0 {
|
||||
println!("Selbsttest bestanden ({} Prüfungen).", checks.len());
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
println!(
|
||||
"Selbsttest fehlgeschlagen ({failed} von {} Prüfungen).",
|
||||
checks.len()
|
||||
);
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
|
||||
/// Ermittelt den Konfigurationspfad: `--config`, sonst `NEXUS_CONFIG`.
|
||||
fn config_path(args: &[String]) -> Result<Option<PathBuf>, String> {
|
||||
match args {
|
||||
[] => Ok(std::env::var_os("NEXUS_CONFIG").map(PathBuf::from)),
|
||||
[flag, path] if flag == "--config" => Ok(Some(PathBuf::from(path))),
|
||||
_ => Err("Aufruf: nexus selftest [--config PFAD]".to_string()),
|
||||
}
|
||||
}
|
||||
168
crates/nexus/src/selftest.rs
Normal file
168
crates/nexus/src/selftest.rs
Normal file
@ -0,0 +1,168 @@
|
||||
//! `nexus selftest`: prüft Konfiguration, Datenverzeichnis und Datenbank.
|
||||
//!
|
||||
//! Der Selbsttest legt bei Bedarf das Datenverzeichnis und die Datenbank an
|
||||
//! und wendet Migrationen an. Er startet keine Engines und verändert nichts
|
||||
//! außerhalb des Datenverzeichnisses. Prüfungen von Rezepten und Engines
|
||||
//! kommen mit den Adaptern.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use nexus_core::{Config, Error};
|
||||
use nexus_store::{LATEST_SCHEMA_VERSION, Store};
|
||||
|
||||
/// Ergebnis einer einzelnen Prüfung.
|
||||
#[derive(Debug)]
|
||||
pub struct Check {
|
||||
pub name: &'static str,
|
||||
pub result: Result<String, String>,
|
||||
}
|
||||
|
||||
impl Check {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.result.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn check(name: &'static str, result: Result<String, Error>) -> Check {
|
||||
Check {
|
||||
name,
|
||||
result: result.map_err(|e| e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Führt alle Prüfungen aus. Ohne `config_path` gelten die Standardwerte;
|
||||
/// mit angegebenem, aber fehlendem Pfad schlägt die Prüfung fehl.
|
||||
pub fn run(config_path: Option<&Path>) -> Vec<Check> {
|
||||
let mut checks = Vec::new();
|
||||
|
||||
let config = match config_path {
|
||||
Some(path) => Config::load(path),
|
||||
None => Ok(Config::default()),
|
||||
};
|
||||
let config_check = check(
|
||||
"Konfiguration",
|
||||
config
|
||||
.as_ref()
|
||||
.map(|c| format!("listen {}", c.listen))
|
||||
.map_err(clone_error),
|
||||
);
|
||||
let config = match config {
|
||||
Ok(c) => c,
|
||||
Err(_) => {
|
||||
checks.push(config_check);
|
||||
return checks;
|
||||
}
|
||||
};
|
||||
checks.push(config_check);
|
||||
|
||||
let dir_check = check("Datenverzeichnis", prepare_data_dir(&config));
|
||||
let dir_ok = dir_check.ok();
|
||||
checks.push(dir_check);
|
||||
if !dir_ok {
|
||||
return checks;
|
||||
}
|
||||
|
||||
match Store::open(&config.db_path()) {
|
||||
Ok(store) => {
|
||||
checks.push(check(
|
||||
"Datenbank",
|
||||
store
|
||||
.schema_version()
|
||||
.map(|v| format!("Schema-Version {v} (neueste: {LATEST_SCHEMA_VERSION})")),
|
||||
));
|
||||
checks.push(check(
|
||||
"Integrität",
|
||||
store.integrity_check().map(|()| "ok".to_string()),
|
||||
));
|
||||
}
|
||||
Err(e) => checks.push(check("Datenbank", Err(e))),
|
||||
}
|
||||
checks
|
||||
}
|
||||
|
||||
fn clone_error(e: &Error) -> Error {
|
||||
Error::Config(e.to_string())
|
||||
}
|
||||
|
||||
fn prepare_data_dir(config: &Config) -> Result<String, Error> {
|
||||
let dir = &config.data_dir;
|
||||
std::fs::create_dir_all(dir).map_err(|source| Error::Io {
|
||||
path: dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
let probe = dir.join(".selftest-probe");
|
||||
std::fs::write(&probe, b"ok").map_err(|source| Error::Io {
|
||||
path: probe.clone(),
|
||||
source,
|
||||
})?;
|
||||
std::fs::remove_file(&probe).map_err(|source| Error::Io {
|
||||
path: probe,
|
||||
source,
|
||||
})?;
|
||||
Ok(format!("{} ist beschreibbar", dir.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
static ZAEHLER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
fn testordner() -> std::path::PathBuf {
|
||||
let n = ZAEHLER.fetch_add(1, Ordering::SeqCst);
|
||||
let p = std::env::temp_dir().join(format!("nexus-selftest-{}-{n}", std::process::id()));
|
||||
std::fs::create_dir_all(&p).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
fn konfig_schreiben(ordner: &Path, text: &str) -> std::path::PathBuf {
|
||||
let pfad = ordner.join("config.toml");
|
||||
std::fs::write(&pfad, text).unwrap();
|
||||
pfad
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gueltige_konfiguration_besteht_alle_pruefungen() {
|
||||
let ordner = testordner();
|
||||
let daten = ordner.join("daten");
|
||||
let konfig = konfig_schreiben(&ordner, &format!("data_dir = \"{}\"", daten.display()));
|
||||
let checks = run(Some(&konfig));
|
||||
assert_eq!(checks.len(), 4, "{checks:?}");
|
||||
assert!(checks.iter().all(Check::ok), "{checks:?}");
|
||||
assert!(daten.join("nexus.db").exists());
|
||||
let _ = std::fs::remove_dir_all(&ordner);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fehlende_konfigurationsdatei_schlaegt_fehl_und_bricht_ab() {
|
||||
let checks = run(Some(Path::new("/nicht/vorhanden.toml")));
|
||||
assert_eq!(checks.len(), 1);
|
||||
assert!(!checks[0].ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ungueltige_konfiguration_schlaegt_fehl() {
|
||||
let ordner = testordner();
|
||||
let konfig = konfig_schreiben(&ordner, "listen = \"nirgendwo\"");
|
||||
let checks = run(Some(&konfig));
|
||||
assert!(!checks[0].ok());
|
||||
let _ = std::fs::remove_dir_all(&ordner);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nicht_beschreibbares_datenverzeichnis_schlaegt_fehl() {
|
||||
let ordner = testordner();
|
||||
// Eine Datei statt eines Ordners macht das Anlegen unmöglich.
|
||||
let blocker = ordner.join("datei");
|
||||
std::fs::write(&blocker, b"x").unwrap();
|
||||
let konfig = konfig_schreiben(
|
||||
&ordner,
|
||||
&format!("data_dir = \"{}\"", blocker.join("unter").display()),
|
||||
);
|
||||
let checks = run(Some(&konfig));
|
||||
assert_eq!(checks.len(), 2, "{checks:?}");
|
||||
assert!(!checks[1].ok());
|
||||
let _ = std::fs::remove_dir_all(&ordner);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user