feat(usage): POST /usage 访客工具使用上报(含未登录) — tool格式校验+同机同工具10min去重+每IP 10min 300条限流; /admin/usage 返回guest聚合(次数/最近时间)
This commit is contained in:
1 parent
cd0bcc2516
commit
66966f6990
1 file changed
+47
@@ -907,6 +907,45 @@ def log_usage(machine: str, tool: str):
|
||||
pass
|
||||
|
||||
|
||||
# ---- 前端工具使用上报(未登录访客也统计):10 分钟同机同工具去重 + 每 IP 限流防刷 ----
|
||||
_USE_SEEN: dict = {} # "<machine|ip>|<tool>" -> last report ts
|
||||
_USE_IP: dict = {} # ip -> [recent ts...]
|
||||
_USE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def usage_track(payload: dict, handler) -> tuple:
|
||||
"""POST /usage:任意访客(含未登录)上报工具使用,落 usage.db。
|
||||
10 分钟内同一机器+同一工具只计一次(防刷新刷量);每 IP 10 分钟上限 300 条。"""
|
||||
tool = str(payload.get("tool") or "").strip()
|
||||
if not tool or len(tool) > 64 or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9\-_.]*", tool):
|
||||
return 400, {"code": 400, "message": "无效 tool"}
|
||||
machine = str(payload.get("machine_id") or "").strip()
|
||||
if machine and not MACHINE_RE.match(machine):
|
||||
machine = ""
|
||||
try:
|
||||
ip = (handler.headers.get("X-Real-IP") or "").strip() or handler.client_address[0]
|
||||
except Exception:
|
||||
ip = ""
|
||||
now = time.time()
|
||||
key = f"{machine or ip}|{tool}"
|
||||
with _USE_LOCK:
|
||||
if len(_USE_SEEN) > 20000: # 修剪过期键,防内存膨胀
|
||||
for k in [k for k, t in _USE_SEEN.items() if now - t >= 600]:
|
||||
_USE_SEEN.pop(k, None)
|
||||
last = _USE_SEEN.get(key)
|
||||
if last is not None and now - last < 600:
|
||||
return 200, {"code": 200, "message": "ok", "data": {"dup": 1}}
|
||||
recent = [t for t in _USE_IP.get(ip, []) if now - t < 600]
|
||||
if len(recent) >= 300:
|
||||
_USE_IP[ip] = recent
|
||||
return 200, {"code": 200, "message": "ok", "data": {"capped": 1}}
|
||||
recent.append(now)
|
||||
_USE_IP[ip] = recent
|
||||
_USE_SEEN[key] = now
|
||||
log_usage(machine, tool)
|
||||
return 200, {"code": 200, "message": "ok", "data": {"ok": 1}}
|
||||
|
||||
|
||||
def _dir_size(path: str) -> int:
|
||||
total = 0
|
||||
for root, _dirs, files in os.walk(path):
|
||||
@@ -1301,12 +1340,15 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
by_tool = conn.execute("SELECT tool, COUNT(*) c FROM usage WHERE at>? GROUP BY tool ORDER BY c DESC LIMIT 30", (since,)).fetchall()
|
||||
by_user = conn.execute("SELECT username, COUNT(*) c, MAX(at) last FROM usage WHERE at>? AND username!='' GROUP BY username ORDER BY c DESC LIMIT 50", (since,)).fetchall()
|
||||
total = conn.execute("SELECT COUNT(*) FROM usage WHERE at>?", (since,)).fetchone()[0]
|
||||
# 未登录访客(username 为空)聚合:访客的功能使用也统计并展示
|
||||
g = conn.execute("SELECT COUNT(*) c, MAX(at) last FROM usage WHERE at>? AND username=''", (since,)).fetchone()
|
||||
conn.close()
|
||||
return 200, {"code": 200, "message": "ok", "data": {
|
||||
"days": days,
|
||||
"total": total,
|
||||
"by_tool": [{"tool": t, "count": c} for t, c in by_tool],
|
||||
"by_user": [{"username": u, "count": c, "last": int(l or 0)} for u, c, l in by_user],
|
||||
"guest": {"count": int(g[0] or 0), "last": int(g[1] or 0)},
|
||||
}}
|
||||
|
||||
return 404, {"code": 404, "message": "unknown admin api"}
|
||||
@@ -2793,6 +2835,11 @@ class Handler(BaseHTTPRequestHandler):
|
||||
status, body = hub_report(payload)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path == "/usage":
|
||||
payload = self._read_payload() or {}
|
||||
status, body = usage_track(payload, self)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path.startswith("/admin"):
|
||||
self._handle_admin("POST")
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user