Update app/control/account/runtime.py
Browse files
app/control/account/runtime.py
CHANGED
|
@@ -100,3 +100,55 @@ __all__ = [
|
|
| 100 |
"set_refresh_scheduler_leader",
|
| 101 |
"reconcile_refresh_runtime",
|
| 102 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
"set_refresh_scheduler_leader",
|
| 101 |
"reconcile_refresh_runtime",
|
| 102 |
]
|
| 103 |
+
import threading
|
| 104 |
+
from collections import deque
|
| 105 |
+
from app.control.account.models import AuditLogRecord, QuotaDistributionSummary
|
| 106 |
+
|
| 107 |
+
class InMemoryAuditor:
|
| 108 |
+
def __init__(self, max_logs: int = 2000):
|
| 109 |
+
# 限制最大长度为 2000 条,超出自动弹出旧数据,完美保护免费版
|
| 110 |
+
self._logs = deque(maxlen=max_logs)
|
| 111 |
+
self._lock = threading.Lock()
|
| 112 |
+
|
| 113 |
+
def record(self, log: AuditLogRecord):
|
| 114 |
+
with self._lock:
|
| 115 |
+
self._logs.append(log)
|
| 116 |
+
|
| 117 |
+
def get_logs(self, page: int = 1, page_size: int = 50) -> list[AuditLogRecord]:
|
| 118 |
+
with self._lock:
|
| 119 |
+
# 复制一份并逆序,让最新生成的日志排在最前面
|
| 120 |
+
all_logs = list(self._logs)
|
| 121 |
+
all_logs.reverse()
|
| 122 |
+
start = (page - 1) * page_size
|
| 123 |
+
return all_logs[start:start + page_size]
|
| 124 |
+
|
| 125 |
+
def get_distribution(self, quota_type: str) -> QuotaDistributionSummary:
|
| 126 |
+
with self._lock:
|
| 127 |
+
all_logs = list(self._logs)
|
| 128 |
+
|
| 129 |
+
# 过滤指定类型的额度数据(如 fast 或 console)
|
| 130 |
+
filtered = [l for l in all_logs if l.quota_type == quota_type]
|
| 131 |
+
total = len(filtered)
|
| 132 |
+
success = sum(1 for l in filtered if l.status == "SUCCESS")
|
| 133 |
+
|
| 134 |
+
ips: dict[str, int] = {}
|
| 135 |
+
uas: dict[str, int] = {}
|
| 136 |
+
for l in filtered:
|
| 137 |
+
ips[l.device_ip] = ips.get(l.device_ip, 0) + 1
|
| 138 |
+
uas[l.user_agent] = uas.get(l.user_agent, 0) + 1
|
| 139 |
+
|
| 140 |
+
# 提取调用频次前 5 的分布明细
|
| 141 |
+
top_ips = dict(sorted(ips.items(), key=lambda x: x[1], reverse=True)[:5])
|
| 142 |
+
top_uas = dict(sorted(uas.items(), key=lambda x: x[1], reverse=True)[:5])
|
| 143 |
+
|
| 144 |
+
return QuotaDistributionSummary(
|
| 145 |
+
quota_type=quota_type,
|
| 146 |
+
total_calls=total,
|
| 147 |
+
success_calls=success,
|
| 148 |
+
fail_calls=total - success,
|
| 149 |
+
top_ips=top_ips,
|
| 150 |
+
top_user_agents=top_uas
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# 全局单例,供路由层和数据面公用
|
| 154 |
+
global_auditor = InMemoryAuditor(max_logs=2000)
|