feat: Tageskontingent und Notfall-Eskalation (#6)
- Quota (app/quota.py): Anfragen pro Nutzer/Tag (usage-Tabelle), DAILY_REQUEST_LIMIT, pro Nutzer via prefs uebersteuerbar; 429 (REST) bzw. error-Event (WS); Metrik - Notfall (app/safety/emergency.py): heuristische Erkennung (de/en); Log im Store (emergency_events) + optionaler Webhook (best-effort) + X-Emergency/emergency-Event; Metrik emergency_total; Notfaelle umgehen das Kontingent - verdrahtet in chat/speak/transcribe + WS-Turns - Tests: 64 gruen (+6); Doku aktualisiert (README, BEDIENUNGSANLEITUNG, Architektur, .env.example) Hinweis: Notfall-Erkennung ist eine Heuristik (kein Lebensretter); erkannte Texte sind sensibel -> DSGVO beachten. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
parent
6422444017
commit
1eb79c1f09
14 changed files with 378 additions and 2 deletions
40
app/quota.py
Normal file
40
app/quota.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
"""Pro-Nutzer-Tageskontingent (Kostenkontrolle).
|
||||
|
||||
Limit aus Settings (`daily_request_limit`), pro Nutzer ueber `prefs.daily_request_limit`
|
||||
ueberschreibbar. 0 bedeutet unbegrenzt.
|
||||
"""
|
||||
|
||||
from app.config import settings, Settings
|
||||
from app.metrics import metrics
|
||||
|
||||
|
||||
class QuotaExceededError(Exception):
|
||||
def __init__(self, limit: int, count: int):
|
||||
self.limit = limit
|
||||
self.count = count
|
||||
super().__init__(f"Daily request limit reached ({count}/{limit})")
|
||||
|
||||
|
||||
def effective_limit(user, cfg: Settings = settings) -> int:
|
||||
pref = user.prefs.get("daily_request_limit") if user and user.prefs else None
|
||||
if pref is not None:
|
||||
try:
|
||||
return int(pref)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return cfg.daily_request_limit
|
||||
|
||||
|
||||
def enforce_quota(user, store, cfg: Settings = settings) -> None:
|
||||
"""Wirft QuotaExceededError, wenn das Tageslimit erreicht ist."""
|
||||
limit = effective_limit(user, cfg)
|
||||
if limit and limit > 0:
|
||||
count = store.get_request_count(user.id)
|
||||
if count >= limit:
|
||||
metrics.inc("quota_exceeded_total")
|
||||
raise QuotaExceededError(limit, count)
|
||||
|
||||
|
||||
def record_usage(user, store, units: int = 0) -> None:
|
||||
store.add_usage(user.id, units)
|
||||
metrics.inc("turns_total")
|
||||
Loading…
Add table
Add a link
Reference in a new issue