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:
Stephan RehfeldandClaude Opus 5.5 committed 2026-11-20 13:19:03 +01:00
1 parent aab87f38e5
commit ab4803e264
9 files changed
+1167 -50

No files matched your search

+284 -16
View File
@@ -3,12 +3,16 @@ use std::{
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::Result;
use anyhow::{Result, bail};
use chrono::{DateTime, Local};
use rand::RngCore;
use rusqlite::{Connection, OptionalExtension, params};
use sha2::{Digest, Sha256};
use crate::schedule::{self, Entry, Kind, TimeSpec, Weekly};
use crate::{
quota::{Counter, Denial, Limits, Period, Quota},
schedule::{self, Entry, Kind, TimeSpec, Weekly},
};
/// SQLite-Datenbank. Die Zugriffe sind kurz, deshalb genügt eine Verbindung hinter einem Mutex.
pub struct Db {
@@ -19,10 +23,11 @@ pub struct ApiKey {
pub id: i64,
pub name: String,
pub prefix: String,
pub created_at: i64,
pub revoked: bool,
/// Super-Keys dürfen unabhängig von allen Einschränkungen immer alles
pub is_super: bool,
/// Kontingent, gegen das der Key abgerechnet wird; ohne ist er unbegrenzt
pub quota_id: Option<i64>,
}
/// Ein angemeldeter Key
@@ -30,6 +35,7 @@ pub struct ApiKey {
pub struct Caller {
pub key_id: i64,
pub is_super: bool,
pub quota_id: Option<i64>,
}
#[derive(Default)]
@@ -42,6 +48,25 @@ pub struct Usage {
pub prompt_tokens: Option<u64>,
pub completion_tokens: Option<u64>,
pub duration_ms: u64,
pub quota_id: Option<i64>,
/// Beginn einer gezählten Anfrage; ihre Token werden den Zeiträumen dieses Zeitpunkts gebucht
pub counted_at: Option<DateTime<Local>>,
}
/// Wessen Verbrauch gezählt wird
#[derive(Clone, Copy)]
pub enum Scope {
Key(i64),
Quota(i64),
}
impl Scope {
fn parts(self) -> (&'static str, i64) {
match self {
Scope::Key(id) => ("key", id),
Scope::Quota(id) => ("quota", id),
}
}
}
pub fn now() -> i64 {
@@ -103,6 +128,34 @@ impl Db {
note TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS quotas (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
valid_from INTEGER,
valid_until INTEGER,
days TEXT,
time_start TEXT,
time_end TEXT,
models TEXT,
tokens_hour INTEGER, tokens_day INTEGER, tokens_week INTEGER, tokens_month INTEGER,
tokens_total INTEGER,
requests_hour INTEGER, requests_day INTEGER, requests_week INTEGER,
requests_month INTEGER, requests_total INTEGER,
note TEXT NOT NULL,
created_at INTEGER NOT NULL
);
-- Verbrauch je Key bzw. Kontingent und Zeitraum (z. B. day:2026-11-20). Die Zähler
-- bleiben erhalten, wenn alte Einträge in usage gelöscht werden.
CREATE TABLE IF NOT EXISTS usage_counters (
scope TEXT NOT NULL,
scope_id INTEGER NOT NULL,
period TEXT NOT NULL,
requests INTEGER NOT NULL DEFAULT 0,
prompt_tokens INTEGER NOT NULL DEFAULT 0,
completion_tokens INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (scope, scope_id, period)
);
CREATE INDEX IF NOT EXISTS usage_ts ON usage (ts);
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY,
ts INTEGER NOT NULL,
@@ -120,26 +173,36 @@ impl Db {
}
/// Legt einen Key an und gibt ihn im Klartext zurück. Gespeichert wird nur der Hash.
pub fn create_key(&self, name: &str, is_super: bool) -> Result<(i64, String)> {
pub fn create_key(&self, name: &str, is_super: bool, quota_id: Option<i64>) -> Result<(i64, String)> {
if is_super && quota_id.is_some() {
bail!("Super-Keys haben kein Kontingent");
}
if let Some(id) = quota_id
&& self.quota(id)?.is_none()
{
bail!("kein Kontingent mit ID {id}");
}
let mut bytes = [0u8; 24];
rand::rng().fill_bytes(&mut bytes);
let key = format!("omega-{}", hex::encode(bytes));
let prefix = key[..14].to_string();
let conn = self.conn();
conn.execute(
"INSERT INTO api_keys (name, key_hash, prefix, created_at, is_super) VALUES (?1, ?2, ?3, ?4, ?5)",
params![name, hash_key(&key), prefix, now(), is_super],
"INSERT INTO api_keys (name, key_hash, prefix, created_at, is_super, quota_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![name, hash_key(&key), prefix, now(), is_super, quota_id],
)?;
let id = conn.last_insert_rowid();
drop(conn);
self.audit("cli", "key.create", &format!("id={id} name={name} super={is_super}"))?;
self.audit("cli", "key.create", &format!("id={id} name={name} super={is_super} quota={quota_id:?}"))?;
Ok((id, key))
}
pub fn list_keys(&self) -> Result<Vec<ApiKey>> {
let conn = self.conn();
let mut stmt = conn.prepare(
"SELECT id, name, prefix, created_at, revoked_at IS NOT NULL, is_super FROM api_keys ORDER BY id",
"SELECT id, name, prefix, revoked_at IS NOT NULL, is_super, quota_id
FROM api_keys ORDER BY id",
)?;
let keys = stmt
.query_map([], |r| {
@@ -147,9 +210,9 @@ impl Db {
id: r.get(0)?,
name: r.get(1)?,
prefix: r.get(2)?,
created_at: r.get(3)?,
revoked: r.get(4)?,
is_super: r.get(5)?,
revoked: r.get(3)?,
is_super: r.get(4)?,
quota_id: r.get(5)?,
})
})?
.collect::<Result<_, _>>()?;
@@ -172,9 +235,9 @@ impl Db {
Ok(self
.conn()
.query_row(
"SELECT id, is_super FROM api_keys WHERE key_hash = ?1 AND revoked_at IS NULL",
"SELECT id, is_super, quota_id FROM api_keys WHERE key_hash = ?1 AND revoked_at IS NULL",
params![hash_key(key)],
|r| Ok(Caller { key_id: r.get(0)?, is_super: r.get(1)? }),
|r| Ok(Caller { key_id: r.get(0)?, is_super: r.get(1)?, quota_id: r.get(2)? }),
)
.optional()?)
}
@@ -182,8 +245,8 @@ impl Db {
pub fn record_usage(&self, u: &Usage) -> Result<()> {
self.conn().execute(
"INSERT INTO usage (ts, key_id, engine, model, path, status, prompt_tokens,
completion_tokens, duration_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
completion_tokens, duration_ms, quota_id)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
params![
now(),
u.key_id,
@@ -193,7 +256,8 @@ impl Db {
u.status,
u.prompt_tokens,
u.completion_tokens,
u.duration_ms
u.duration_ms,
u.quota_id
],
)?;
Ok(())
@@ -344,6 +408,204 @@ impl Db {
Ok(changed > 0)
}
pub fn set_key_quota(&self, key_id: i64, quota_id: Option<i64>) -> Result<()> {
if let Some(id) = quota_id
&& self.quota(id)?.is_none()
{
bail!("kein Kontingent mit ID {id}");
}
let changed = self.conn().execute(
"UPDATE api_keys SET quota_id = ?1 WHERE id = ?2 AND is_super = 0",
params![quota_id, key_id],
)?;
if changed == 0 {
bail!("kein Key mit ID {key_id}, oder es ist ein Super-Key");
}
self.audit("cli", "key.quota", &format!("id={key_id} quota={quota_id:?}"))
}
pub fn create_quota(&self, q: &Quota) -> Result<i64> {
let (days, start, end) = match &q.time.weekly {
Some(w) => (
Some(schedule::days_str(&w.days)),
Some(w.start.format("%H:%M").to_string()),
Some(w.end.format("%H:%M").to_string()),
),
None => (None, None, None),
};
let models = q.models.as_ref().map(serde_json::to_string).transpose()?;
let limits: Vec<Option<u64>> = Period::ALL
.iter()
.map(|p| q.tokens.get(*p))
.chain(Period::ALL.iter().map(|p| q.requests.get(*p)))
.collect();
let conn = self.conn();
conn.execute(
"INSERT INTO quotas (name, valid_from, valid_until, days, time_start, time_end, models,
tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)",
params![
q.name, q.time.from, q.time.until, days, start, end, models, limits[0], limits[1], limits[2],
limits[3], limits[4], limits[5], limits[6], limits[7], limits[8], limits[9], q.note, now()
],
)?;
let id = conn.last_insert_rowid();
drop(conn);
self.audit("cli", "quota.create", &format!("id={id} {}: {}", q.name, q.describe()))?;
Ok(id)
}
fn quotas_where(&self, filter: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<Quota>> {
let conn = self.conn();
let mut stmt = conn.prepare(&format!(
"SELECT id, name, valid_from, valid_until, days, time_start, time_end, models, tokens_hour, tokens_day, tokens_week, tokens_month, tokens_total, requests_hour, requests_day, requests_week, requests_month, requests_total, note
FROM quotas {filter} ORDER BY id"
))?;
let mut rows = stmt.query(args)?;
let mut list = Vec::new();
while let Some(r) = rows.next()? {
let weekly = match (r.get::<_, Option<String>>(4)?, r.get::<_, Option<String>>(5)?, r.get::<_, Option<String>>(6)?) {
(Some(days), Some(start), Some(end)) => {
let (start, end) = schedule::parse_time_range(&format!("{start}-{end}"))?;
Some(Weekly { days: schedule::parse_days(&days)?, start, end })
}
_ => None,
};
let models: Option<String> = r.get(7)?;
let (mut tokens, mut requests) = (Limits::default(), Limits::default());
for (i, p) in Period::ALL.iter().enumerate() {
tokens.set(*p, r.get(8 + i)?);
requests.set(*p, r.get(13 + i)?);
}
list.push(Quota {
id: r.get(0)?,
name: r.get(1)?,
time: TimeSpec { from: r.get(2)?, until: r.get(3)?, weekly },
models: models.map(|m| serde_json::from_str(&m)).transpose()?,
tokens,
requests,
note: r.get(18)?,
});
}
Ok(list)
}
pub fn quota(&self, id: i64) -> Result<Option<Quota>> {
Ok(self.quotas_where("WHERE id = ?1", &[&id])?.pop())
}
pub fn list_quotas(&self) -> Result<Vec<Quota>> {
self.quotas_where("", &[])
}
/// Nur ein Kontingent, an dem keine Keys mehr hängen, kann entfernt werden.
pub fn remove_quota(&self, id: i64) -> Result<()> {
let conn = self.conn();
let keys: i64 = conn.query_row("SELECT count(*) FROM api_keys WHERE quota_id = ?1", params![id], |r| r.get(0))?;
if keys > 0 {
bail!("am Kontingent {id} hängen noch {keys} Keys");
}
if conn.execute("DELETE FROM quotas WHERE id = ?1", params![id])? == 0 {
bail!("kein Kontingent mit ID {id}");
}
conn.execute("DELETE FROM usage_counters WHERE scope = 'quota' AND scope_id = ?1", params![id])?;
drop(conn);
self.audit("cli", "quota.remove", &format!("id={id}"))
}
/// Verbrauch in den Zeiträumen, in die t fällt
fn counters(conn: &Connection, scope: Scope, t: DateTime<Local>) -> Result<Vec<(Period, Counter)>> {
let (scope, id) = scope.parts();
let mut stmt = conn.prepare_cached(
"SELECT requests, prompt_tokens, completion_tokens FROM usage_counters
WHERE scope = ?1 AND scope_id = ?2 AND period = ?3",
)?;
Period::ALL
.iter()
.map(|p| {
let c = stmt
.query_row(params![scope, id, p.key(t)], |r| {
Ok(Counter { requests: r.get(0)?, prompt_tokens: r.get(1)?, completion_tokens: r.get(2)? })
})
.optional()?
.unwrap_or_default();
Ok((*p, c))
})
.collect()
}
pub fn usage_of(&self, scope: Scope, t: DateTime<Local>) -> Result<Vec<(Period, Counter)>> {
Self::counters(&self.conn(), scope, t)
}
/// Addiert (oder bei negativen Werten subtrahiert) in allen Zeiträumen von t.
fn add(conn: &Connection, scope: Scope, t: DateTime<Local>, requests: i64, prompt: i64, completion: i64) -> Result<()> {
let (scope, id) = scope.parts();
let mut stmt = conn.prepare_cached(
"INSERT INTO usage_counters (scope, scope_id, period, requests, prompt_tokens, completion_tokens)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT (scope, scope_id, period) DO UPDATE SET
requests = requests + excluded.requests,
prompt_tokens = prompt_tokens + excluded.prompt_tokens,
completion_tokens = completion_tokens + excluded.completion_tokens",
)?;
for p in Period::ALL {
stmt.execute(params![scope, id, p.key(t), requests, prompt, completion])?;
}
Ok(())
}
fn scopes(key_id: i64, quota_id: Option<i64>) -> Vec<Scope> {
std::iter::once(Scope::Key(key_id)).chain(quota_id.map(Scope::Quota)).collect()
}
/// Prüft das Kontingent und zählt die Anfrage, in einer Transaktion, damit gleichzeitige
/// Anfragen die Grenzen nicht gemeinsam überschreiten. `quota` ist None für Keys ohne
/// Kontingent und für Super-Keys; gezählt wird beim Key trotzdem.
pub fn begin_request(&self, key_id: i64, quota: Option<&Quota>, t: DateTime<Local>) -> Result<Result<(), Denial>> {
let mut conn = self.conn();
let tx = conn.transaction()?;
if let Some(q) = quota
&& let Err(denial) = q.check_usage(&Self::counters(&tx, Scope::Quota(q.id), t)?, t)
{
return Ok(Err(denial));
}
for scope in Self::scopes(key_id, quota.map(|q| q.id)) {
Self::add(&tx, scope, t, 1, 0, 0)?;
}
tx.commit()?;
Ok(Ok(()))
}
/// Nimmt eine gezählte Anfrage zurück, die die Engine nie erreicht hat (z. B. Modell nicht ladbar).
pub fn refund_request(&self, key_id: i64, quota_id: Option<i64>, t: DateTime<Local>) -> Result<()> {
let mut conn = self.conn();
let tx = conn.transaction()?;
for scope in Self::scopes(key_id, quota_id) {
Self::add(&tx, scope, t, -1, 0, 0)?;
}
Ok(tx.commit()?)
}
/// Bucht die Token einer beendeten Anfrage in die Zeiträume ihres Beginns.
pub fn book_tokens(&self, key_id: i64, quota_id: Option<i64>, t: DateTime<Local>, prompt: u64, completion: u64) -> Result<()> {
let mut conn = self.conn();
let tx = conn.transaction()?;
for scope in Self::scopes(key_id, quota_id) {
Self::add(&tx, scope, t, 0, prompt as i64, completion as i64)?;
}
Ok(tx.commit()?)
}
/// Löscht Einzeleinträge der Nutzung, die älter als `days` Tage sind. Die Zähler der
/// Kontingente und Keys bleiben unberührt.
pub fn prune_usage(&self, days: u32) -> Result<usize> {
let cutoff = now() - i64::from(days) * 86_400;
let deleted = self.conn().execute("DELETE FROM usage WHERE ts < ?1", params![cutoff])?;
self.audit("cli", "usage.prune", &format!("older_than_days={days} deleted={deleted}"))?;
Ok(deleted)
}
pub fn audit(&self, actor: &str, action: &str, detail: &str) -> Result<()> {
self.conn().execute(
"INSERT INTO audit_log (ts, actor, action, detail) VALUES (?1, ?2, ?3, ?4)",
@@ -364,6 +626,12 @@ fn migrate(conn: &Connection) -> Result<()> {
if !has_column(conn, "api_keys", "is_super")? {
conn.execute("ALTER TABLE api_keys ADD COLUMN is_super INTEGER NOT NULL DEFAULT 0", [])?;
}
if !has_column(conn, "api_keys", "quota_id")? {
conn.execute("ALTER TABLE api_keys ADD COLUMN quota_id INTEGER REFERENCES quotas(id)", [])?;
}
if !has_column(conn, "usage", "quota_id")? {
conn.execute("ALTER TABLE usage ADD COLUMN quota_id INTEGER", [])?;
}
// Pins lagen bis zum gemeinsamen Zeitplan in einer eigenen Tabelle.
let has_pins: bool = conn.query_row(
"SELECT count(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = 'pins'",