hchevva commited on
Commit
1b985c6
·
verified ·
1 Parent(s): 2279af9

Create rate_limit.py

Browse files
Files changed (1) hide show
  1. core/rate_limit.py +50 -0
core/rate_limit.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import os, json, datetime
3
+ from pathlib import Path
4
+ from typing import Tuple
5
+ from .config import settings
6
+
7
+ def _today_key() -> str:
8
+ return datetime.date.today().isoformat()
9
+
10
+ def _redis_client():
11
+ if not settings.redis_url:
12
+ return None
13
+ try:
14
+ from redis import Redis
15
+ return Redis.from_url(settings.redis_url, decode_responses=True)
16
+ except Exception:
17
+ return None
18
+
19
+ def check_and_increment_global_ai_cap() -> Tuple[bool, dict]:
20
+ limit = settings.max_ai_summaries_per_day
21
+ day = _today_key()
22
+
23
+ r = _redis_client()
24
+ if r:
25
+ key = f"toxrai:ai_summaries:{day}"
26
+ val = r.incr(key)
27
+ if val == 1:
28
+ r.expire(key, 60 * 60 * 24 * 2)
29
+ return (val <= limit), {"store": "redis", "day": day, "count": int(val), "limit": limit}
30
+
31
+ # fallback: file (may reset on restart if no persistent volume)
32
+ path = Path("/data/toxrai_limits.json") if os.path.isdir("/data") else Path(".toxrai_limits.json")
33
+ data = {}
34
+ if path.exists():
35
+ try:
36
+ data = json.loads(path.read_text(encoding="utf-8") or "{}")
37
+ except Exception:
38
+ data = {}
39
+
40
+ data.setdefault("ai_summaries", {})
41
+ data["ai_summaries"].setdefault(day, 0)
42
+ data["ai_summaries"][day] += 1
43
+
44
+ try:
45
+ path.write_text(json.dumps(data, indent=2), encoding="utf-8")
46
+ except Exception:
47
+ pass
48
+
49
+ count = int(data["ai_summaries"][day])
50
+ return (count <= limit), {"store": "file", "path": str(path), "day": day, "count": count, "limit": limit}