feat(online): /relay/online 端点 + 90s内存窗口 + admin/usage 返回online

This commit is contained in:
jinghui committed 2026-11-12 12:52:51 +08:00
1 parent 6cae4e9cf9
commit 853d9d3c8c
1 file changed
+41
+41
View File
@@ -946,6 +946,41 @@ def usage_track(payload: dict, handler) -> tuple:
return 200, {"code": 200, "message": "ok", "data": {"ok": 1}}
# ---- 在线统计:仅未登录访客,前端停留满 1 分钟才开始心跳 ----
ONLINE_WINDOW = 90.0 # 心跳每 30s 一次(后台标签被节流为 60s),超 90s 无心跳判离线
_ONLINE: dict = {} # machine_id -> 最近心跳时间戳(进程内存)
_ONLINE_LOCK = threading.Lock()
def online_beat(payload: dict) -> tuple:
"""POST /online:访客在线心跳。
- guest=true(未登录)→ 记为在线;guest=false(已登录)→ 移出统计。
- 「停留超过 1 分钟才算在线」由前端控制:打开满 60s 才发首次心跳。
"""
machine = str(payload.get("machine_id") or "").strip()
if not machine or not MACHINE_RE.match(machine):
return 400, {"code": 400, "message": "无效 machine_id"}
guest = bool(payload.get("guest"))
now = time.time()
with _ONLINE_LOCK:
if guest:
_ONLINE[machine] = now
else:
_ONLINE.pop(machine, None) # 登录用户不统计
if len(_ONLINE) > 5000: # 防内存膨胀:修剪过期
for k in [k for k, t in _ONLINE.items() if now - t > ONLINE_WINDOW]:
_ONLINE.pop(k, None)
count = sum(1 for t in _ONLINE.values() if now - t <= ONLINE_WINDOW)
return 200, {"code": 200, "message": "ok", "data": {"online": count}}
def online_count() -> int:
now = time.time()
with _ONLINE_LOCK:
return sum(1 for t in _ONLINE.values() if now - t <= ONLINE_WINDOW)
def _dir_size(path: str) -> int:
total = 0
for root, _dirs, files in os.walk(path):
@@ -1349,6 +1384,7 @@ def admin_api(method: str, sub: str, payload: dict, handler):
"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)},
"online": online_count(),
}}
return 404, {"code": 404, "message": "unknown admin api"}
@@ -2840,6 +2876,11 @@ class Handler(BaseHTTPRequestHandler):
status, body = usage_track(payload, self)
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
return
if parsed.path == "/online":
payload = self._read_payload() or {}
status, body = online_beat(payload)
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