Kontingente, Zähler der Nutzung und Super-Keys ohne Einschränkungen
- Kontingente begrenzen Token und Anfragen je Stunde, Tag, Woche, Monat und insgesamt (Kalenderzeiträume in Ortszeit), dazu Gültigkeit, Nutzungszeiten und Modelle; Keys werden einem Kontingent zugeordnet, ohne sind sie unbegrenzt - Eine Anfrage zählt beim Start (Prüfen und Zählen in einer Transaktion) und wird zurückgebucht, wenn sie die Engine nicht erreicht; ihre Token werden nach der Antwort gebucht; 429 bei ausgeschöpftem Kontingent, 403 sonst - usage_counters führt den Verbrauch je Key und Kontingent und Zeitraum; usage prune löscht alte Einzeleinträge, ohne die Kontingentstände zu ändern - Super-Keys haben kein Kontingent, übergehen Modellbeschränkungen, exklusive Nutzung und Modellzeitfenster und verdrängen notfalls gepinnte Modelle - CLI: quota create/list/show/remove, key create --quota, key quota, usage prune - Unit-Tests und tests/multispark/quota_test.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aab87f38e5
commit
ab4803e264
9 files changed
+1167
-50
No files matched your search
+190
-6
@@ -2,6 +2,7 @@ mod config;
|
||||
mod db;
|
||||
mod engines;
|
||||
mod forward;
|
||||
mod quota;
|
||||
mod routes;
|
||||
mod schedule;
|
||||
mod scheduler;
|
||||
@@ -13,8 +14,9 @@ use clap::{Args, Parser, Subcommand};
|
||||
|
||||
use crate::{
|
||||
config::Config,
|
||||
db::Db,
|
||||
db::{Db, Scope},
|
||||
engines::Engine,
|
||||
quota::{Limits, Period, Quota},
|
||||
routes::AppState,
|
||||
schedule::{Entry, Kind, TimeSpec, Weekly},
|
||||
scheduler::Scheduler,
|
||||
@@ -39,6 +41,67 @@ enum Command {
|
||||
/// 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<u64>,
|
||||
#[arg(long)]
|
||||
tokens_day: Option<u64>,
|
||||
#[arg(long)]
|
||||
tokens_week: Option<u64>,
|
||||
#[arg(long)]
|
||||
tokens_month: Option<u64>,
|
||||
#[arg(long)]
|
||||
tokens_total: Option<u64>,
|
||||
#[arg(long)]
|
||||
requests_hour: Option<u64>,
|
||||
#[arg(long)]
|
||||
requests_day: Option<u64>,
|
||||
#[arg(long)]
|
||||
requests_week: Option<u64>,
|
||||
#[arg(long)]
|
||||
requests_month: Option<u64>,
|
||||
#[arg(long)]
|
||||
requests_total: Option<u64>,
|
||||
}
|
||||
|
||||
#[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<Vec<String>>,
|
||||
#[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)]
|
||||
@@ -47,11 +110,17 @@ enum KeyCommand {
|
||||
Create {
|
||||
name: String,
|
||||
/// Super-Key: darf unabhängig von allen Einschränkungen immer alles
|
||||
#[arg(long = "super")]
|
||||
#[arg(long = "super", conflicts_with = "quota")]
|
||||
is_super: bool,
|
||||
/// Kontingent, gegen das der Key abgerechnet wird; ohne ist er unbegrenzt
|
||||
#[arg(long)]
|
||||
quota: Option<i64>,
|
||||
},
|
||||
/// 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
|
||||
@@ -119,20 +188,61 @@ async fn main() -> Result<()> {
|
||||
|
||||
match cli.command {
|
||||
Command::Serve => serve(config, db).await,
|
||||
Command::Key(KeyCommand::Create { name, is_super }) => {
|
||||
let (id, key) = db.create_key(&name, is_super)?;
|
||||
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 kind = if k.is_super { "super" } else { "" };
|
||||
println!("{:>4} {:<24} {}… {} {state:<10} {kind}", k.id, k.name, k.prefix, k.created_at);
|
||||
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}");
|
||||
@@ -281,6 +391,80 @@ async fn add_entry(config: Config, db: Arc<Db>, cmd: ScheduleCommand) -> Result<
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn quota_command(config: Config, db: Arc<Db>, 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<u64>| 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<Db>) -> Result<()> {
|
||||
let sched = Scheduler::new(config.nodes, config.scheduler, db.clone())?;
|
||||
sched.spawn_reconciler();
|
||||
|
||||
Reference in new issue
Block a user