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:
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