mod config; mod db; mod engines; mod forward; mod quota; mod routes; mod schedule; mod scheduler; use std::{path::PathBuf, sync::Arc, time::Duration}; use anyhow::{Context, Result, bail}; use clap::{Args, Parser, Subcommand}; use crate::{ config::Config, db::{Db, Scope}, engines::Engine, quota::{Limits, Period, Quota}, routes::AppState, schedule::{Entry, Kind, TimeSpec, Weekly}, scheduler::Scheduler, }; #[derive(Parser)] #[command(version, about = "Omega AI Proxy")] struct Cli { #[arg(short, long, default_value = "config.toml")] config: PathBuf, #[command(subcommand)] command: Command, } #[derive(Subcommand)] enum Command { /// Proxy starten Serve, /// API-Keys verwalten #[command(subcommand)] Key(KeyCommand), /// Zeitplan: Pins, exklusive Nutzung und Modellzeitfenster #[command(subcommand)] Schedule(ScheduleCommand), /// Kontingente: wie viel Keys nutzen dürfen #[command(subcommand)] Quota(QuotaCommand), /// Gespeicherte Nutzung #[command(subcommand)] Usage(UsageCommand), } /// Höchstwerte je Zeitraum (Kalenderzeiträume in Ortszeit); ohne Angabe unbegrenzt #[derive(Args)] struct LimitArgs { #[arg(long)] tokens_hour: Option, #[arg(long)] tokens_day: Option, #[arg(long)] tokens_week: Option, #[arg(long)] tokens_month: Option, #[arg(long)] tokens_total: Option, #[arg(long)] requests_hour: Option, #[arg(long)] requests_day: Option, #[arg(long)] requests_week: Option, #[arg(long)] requests_month: Option, #[arg(long)] requests_total: Option, } #[derive(Subcommand)] #[allow(clippy::large_enum_variant)] enum QuotaCommand { /// Kontingent anlegen; --from/--until begrenzen die Gültigkeit, --weekly/--time die Nutzungszeiten Create { name: String, #[command(flatten)] limits: LimitArgs, /// Nur diese Modelle, als engine/modell, z. B. "ollama/qwen3:0.6b,vllm/qwen2.5-0.5b" #[arg(long, value_delimiter = ',')] models: Option>, #[command(flatten)] time: TimeArgs, }, List, /// Verbrauch je Zeitraum Show { id: i64 }, /// Kontingent entfernen; es dürfen keine Keys mehr daran hängen Remove { id: i64 }, } #[derive(Subcommand)] enum UsageCommand { /// Einzeleinträge löschen, die älter als N Tage sind; die Zähler der Kontingente bleiben Prune { #[arg(long)] older_than_days: u32, }, } #[derive(Subcommand)] enum KeyCommand { /// Neuen Key anlegen; er wird nur einmal angezeigt Create { name: String, /// Super-Key: darf unabhängig von allen Einschränkungen immer alles #[arg(long = "super", conflicts_with = "quota")] is_super: bool, /// Kontingent, gegen das der Key abgerechnet wird; ohne ist er unbegrenzt #[arg(long)] quota: Option, }, /// Keys mit Verbrauch heute und insgesamt List, Revoke { id: i64 }, /// Kontingent eines Keys ändern: ID oder "none" für unbegrenzt Quota { id: i64, quota: String }, } /// Wann ein Eintrag gilt; ohne Angaben dauerhaft #[derive(Args)] struct TimeArgs { /// Beginn, z. B. "2026-11-24 08:00", "2026-11-24" oder "+10m" #[arg(long)] from: Option, /// Ende, Format wie --from #[arg(long)] until: Option, /// Wochentage, z. B. "mo,mi" oder "mo-fr" #[arg(long, requires = "time")] weekly: Option, /// Uhrzeit für --weekly, z. B. "08:00-11:15" oder über Mitternacht "22:00-02:00" #[arg(long, requires = "weekly")] time: Option, /// Anmerkung, z. B. die Lehrveranstaltung #[arg(long, default_value = "")] note: String, } #[derive(Subcommand)] enum ScheduleCommand { /// Modell pinnen: garantiert im Speicher, wird nie verdrängt Pin { /// Engine und Modell, z. B. ollama/qwen3:0.6b, llamacpp/qwen3-0.6b, vllm/qwen2.5-0.5b model: String, /// Rechner; nur nötig, wenn mehrere das Modell anbieten #[arg(long)] node: Option, #[command(flatten)] time: TimeArgs, }, /// Exklusive Nutzung: nur diese Keys dürfen das System nutzen Exclusive { /// Key-IDs, z. B. "3,4" #[arg(long, value_delimiter = ',', required = true)] keys: Vec, #[command(flatten)] time: TimeArgs, }, /// Modellzeitfenster: nur diese Modelle sind verfügbar Window { /// Modelle als engine/modell, z. B. "ollama/qwen3:0.6b,vllm/qwen2.5-0.5b" #[arg(long, value_delimiter = ',', required = true)] models: Vec, #[command(flatten)] time: TimeArgs, }, List, Remove { id: i64 }, } #[tokio::main] async fn main() -> Result<()> { tracing_subscriber::fmt() .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), ) .init(); let cli = Cli::parse(); let config = Config::load(&cli.config)?; let db = Arc::new(Db::open(&config.database)?); match cli.command { Command::Serve => serve(config, db).await, Command::Key(KeyCommand::Create { name, is_super, quota }) => { let (id, key) = db.create_key(&name, is_super, quota)?; let kind = if is_super { "Super-Key" } else { "Key" }; println!("{kind} {id} ({name}): {key}"); Ok(()) } Command::Key(KeyCommand::List) => { let now = chrono::Local::now(); let quotas = db.list_quotas()?; println!( "{:>4} {:<20} {:<17} {:<10} {:<24} {:>10} {:>8} {:>12} {:>8}", "ID", "Name", "Präfix", "Zustand", "Kontingent", "Token heute", "Anfr. heute", "Token gesamt", "Anfr. ges." ); for k in db.list_keys()? { let state = if k.revoked { "widerrufen" } else { "aktiv" }; let quota = match (k.is_super, k.quota_id) { (true, _) => "Super-Key".to_string(), (false, None) => "unbegrenzt".to_string(), (false, Some(id)) => quotas .iter() .find(|q| q.id == id) .map(|q| format!("{} (#{id})", q.name)) .unwrap_or_else(|| format!("#{id} fehlt")), }; let usage = db.usage_of(Scope::Key(k.id), now)?; let get = |p: Period| usage.iter().find(|(q, _)| *q == p).map(|(_, c)| *c).unwrap_or_default(); let (day, total) = (get(Period::Day), get(Period::Total)); println!( "{:>4} {:<20} {}… {state:<10} {quota:<24} {:>10} {:>8} {:>12} {:>8}", k.id, k.name, k.prefix, day.tokens(), day.requests, total.tokens(), total.requests ); } Ok(()) } Command::Key(KeyCommand::Quota { id, quota }) => { let quota = match quota.as_str() { "none" => None, id => Some(id.parse().context("Kontingent als ID oder \"none\" angeben")?), }; db.set_key_quota(id, quota)?; println!("Key {id}: Kontingent {}", quota.map(|q| format!("#{q}")).unwrap_or("unbegrenzt".into())); Ok(()) } Command::Quota(cmd) => quota_command(config, db, cmd).await, Command::Usage(UsageCommand::Prune { older_than_days }) => { let deleted = db.prune_usage(older_than_days)?; println!("{deleted} Einträge gelöscht; die Zähler der Kontingente und Keys bleiben erhalten"); Ok(()) } Command::Key(KeyCommand::Revoke { id }) => { if !db.revoke_key(id)? { bail!("kein aktiver Key mit ID {id}"); } println!("Key {id} widerrufen"); Ok(()) } Command::Schedule(ScheduleCommand::List) => { let now = chrono::Local::now(); for e in db.list_schedule()? { let state = if e.active_at(now) { "aktiv" } else { "" }; println!( "{:>4} {:<8} {:<40} {:<50} {:<6} {}", e.id, e.kind_name(), e.subject(), e.time.describe(), state, e.note ); } Ok(()) } Command::Schedule(ScheduleCommand::Remove { id }) => { if !db.remove_schedule(id)? { bail!("kein Eintrag mit ID {id}"); } println!("Eintrag {id} entfernt"); Ok(()) } Command::Schedule(cmd) => add_entry(config, db, cmd).await, } } fn time_spec(args: &TimeArgs, now: chrono::DateTime) -> Result { let from = args.from.as_deref().map(|s| schedule::parse_when(s, now)).transpose()?; let until = args.until.as_deref().map(|s| schedule::parse_when(s, now)).transpose()?; if let (Some(f), Some(u)) = (from, until) && f >= u { bail!("--until muss nach --from liegen"); } if until.is_some_and(|u| u <= now) { bail!("der Zeitraum liegt in der Vergangenheit"); } let weekly = match (&args.weekly, &args.time) { (Some(days), Some(time)) => { let (start, end) = schedule::parse_time_range(time)?; Some(Weekly { days: schedule::parse_days(days)?, start, end }) } _ => None, }; Ok(TimeSpec { from: from.map(|t| t.timestamp()), until: until.map(|t| t.timestamp()), weekly }) } /// "ollama/qwen3" -> (Engine, "ollama", "qwen3:latest") fn parse_model(s: &str) -> Result<(Engine, String, String)> { let (engine_name, model) = s.split_once('/').context("Modell als engine/modell angeben, z. B. ollama/qwen3:0.6b")?; let engine = Engine::parse(engine_name).with_context(|| format!("unbekannte Engine {engine_name} (ollama, llamacpp, vllm)"))?; Ok((engine, engine_name.to_string(), engines::normalize_model(engine, model))) } /// Legt einen Eintrag an, nachdem er gegen den ganzen Zeitplan geprüft wurde. async fn add_entry(config: Config, db: Arc, cmd: ScheduleCommand) -> Result<()> { let now = chrono::Local::now(); // Der Scheduler fragt die Engines, welche Modelle es wo gibt. let sched = Scheduler::new(config.nodes, config.scheduler, db.clone())?; sched.reconcile().await; let (kind, time) = match cmd { ScheduleCommand::Pin { model, node, time } => { let (engine, engine_name, model) = parse_model(&model)?; let offering = sched.nodes_offering(engine, &model); let node = match node { Some(name) => { let i = sched.node_index(&name).with_context(|| format!("unbekannter Rechner {name}"))?; if !offering.contains(&i) { bail!("{name} bietet {engine_name}/{model} nicht an"); } i } None => match offering.as_slice() { [] => bail!("{engine_name}/{model} wird auf keinem Rechner angeboten"), [i] => *i, several => bail!( "{engine_name}/{model} gibt es auf mehreren Rechnern ({}); bitte --node angeben", several.iter().map(|&i| sched.nodes[i].name.as_str()).collect::>().join(", ") ), }, }; if sched.budget(node).is_none() { bail!("Speicher von {} unbekannt: Agent nicht erreichbar", sched.nodes[node].name); } let node = sched.nodes[node].name.clone(); (Kind::Pin { node, engine: engine_name, model }, time) } ScheduleCommand::Exclusive { keys, time } => { let known = db.list_keys()?; for id in &keys { if !known.iter().any(|k| k.id == *id && !k.revoked) { bail!("kein aktiver Key mit ID {id}"); } } (Kind::Exclusive { keys }, time) } ScheduleCommand::Window { models, time } => { let mut normalized = Vec::new(); for m in &models { let (engine, engine_name, model) = parse_model(m)?; if sched.nodes_offering(engine, &model).is_empty() { bail!("{engine_name}/{model} wird auf keinem Rechner angeboten"); } normalized.push(format!("{engine_name}/{model}")); } (Kind::Window { models: normalized }, time) } ScheduleCommand::List | ScheduleCommand::Remove { .. } => unreachable!("in main behandelt"), }; let entry = Entry { id: 0, kind, time: time_spec(&time, now)?, note: time.note }; let mut all = db.list_schedule()?; all.push(entry.clone()); schedule::check_conflicts( &all, now, |e| match &e.kind { Kind::Pin { node, engine, model } => match (sched.node_index(node), Engine::parse(engine)) { (Some(n), Some(engine)) => sched.need_mb(n, engine, model), _ => 0, }, _ => 0, }, |name| sched.node_index(name).and_then(|n| sched.budget(n)).unwrap_or(0), ) .context("Eintrag passt nicht in den Zeitplan")?; let id = db.add_schedule(&entry)?; let size = match &entry.kind { Kind::Pin { node, engine, model } => match (sched.node_index(node), Engine::parse(engine)) { (Some(n), Some(engine)) => format!(" ({} MB)", sched.need_mb(n, engine, model)), _ => String::new(), }, _ => String::new(), }; println!("Eintrag {id}: {} {}{size}, {}", entry.kind_name(), entry.subject(), entry.time.describe()); Ok(()) } async fn quota_command(config: Config, db: Arc, cmd: QuotaCommand) -> Result<()> { let now = chrono::Local::now(); match cmd { QuotaCommand::Create { name, limits, models, time } => { let models = match models { None => None, Some(models) => { // Der Scheduler fragt die Engines, welche Modelle es gibt. let sched = Scheduler::new(config.nodes, config.scheduler, db.clone())?; sched.reconcile().await; let mut normalized = Vec::new(); for m in &models { let (engine, engine_name, model) = parse_model(m)?; if sched.nodes_offering(engine, &model).is_empty() { bail!("{engine_name}/{model} wird auf keinem Rechner angeboten"); } normalized.push(format!("{engine_name}/{model}")); } Some(normalized) } }; let tokens = Limits { hour: limits.tokens_hour, day: limits.tokens_day, week: limits.tokens_week, month: limits.tokens_month, total: limits.tokens_total, }; let requests = Limits { hour: limits.requests_hour, day: limits.requests_day, week: limits.requests_week, month: limits.requests_month, total: limits.requests_total, }; let quota = Quota { id: 0, name, time: time_spec(&time, now)?, models, tokens, requests, note: time.note }; let id = db.create_quota("a)?; println!("Kontingent {id}: {}: {}", quota.name, quota.describe()); Ok(()) } QuotaCommand::List => { let keys = db.list_keys()?; for q in db.list_quotas()? { let n = keys.iter().filter(|k| k.quota_id == Some(q.id) && !k.revoked).count(); println!("{:>4} {:<24} {n} Keys {}", q.id, q.name, q.describe()); } Ok(()) } QuotaCommand::Show { id } => { let q = db.quota(id)?.with_context(|| format!("kein Kontingent mit ID {id}"))?; println!("{} (#{id}): {}", q.name, q.describe()); println!("{:<10} {:>12} {:>12} {:>10} {:>10} endet", "Zeitraum", "Token", "Grenze", "Anfragen", "Grenze"); for (p, c) in db.usage_of(Scope::Quota(id), now)? { let limit = |l: Option| l.map(|v| v.to_string()).unwrap_or("-".into()); let end = p.end(now).map(|t| t.format("%d.%m.%Y %H:%M").to_string()).unwrap_or_default(); println!( "{:<10} {:>12} {:>12} {:>10} {:>10} {end}", p.id(), c.tokens(), limit(q.tokens.get(p)), c.requests, limit(q.requests.get(p)) ); } Ok(()) } QuotaCommand::Remove { id } => { db.remove_quota(id)?; println!("Kontingent {id} entfernt"); Ok(()) } } } async fn serve(config: Config, db: Arc) -> Result<()> { let sched = Scheduler::new(config.nodes, config.scheduler, db.clone())?; sched.spawn_reconciler(); sched.spawn_schedule_watcher(); let http = reqwest::Client::builder() .connect_timeout(Duration::from_secs(5)) .build()?; let app = routes::router(AppState { db, sched, http }); let listener = tokio::net::TcpListener::bind(&config.listen).await?; tracing::info!("Omega AI Proxy lauscht auf {}", config.listen); axum::serve(listener, app).await?; Ok(()) }