Grok3API / app /control /account /runtime.py
LifeVta's picture
Update app/control/account/runtime.py
d14d5aa verified
Raw History Blame Contribute Delete
5.92 kB
"""Account runtime singletons and hot-apply helpers.
These helpers expose the process-local account refresh runtime without making
callers import ``app.main``. Admin handlers use them to reconcile strategy and
scheduler state after hot config updates.
"""
import threading
from collections import deque
from typing import TYPE_CHECKING, Literal
from app.control.account.models import AuditLogRecord, QuotaDistributionSummary
if TYPE_CHECKING:
from .refresh import AccountRefreshService
from .scheduler import AccountRefreshScheduler
_refresh_service: "AccountRefreshService | None" = None
_refresh_scheduler: "AccountRefreshScheduler | None" = None
_refresh_scheduler_leader = False
def set_refresh_service(service: "AccountRefreshService | None") -> None:
"""Register the process-global account refresh service."""
global _refresh_service
_refresh_service = service
def get_refresh_service() -> "AccountRefreshService | None":
"""Return the registered account refresh service, if any."""
return _refresh_service
def set_refresh_scheduler(scheduler: "AccountRefreshScheduler | None") -> None:
"""Register the process-global account refresh scheduler."""
global _refresh_scheduler
_refresh_scheduler = scheduler
def get_refresh_scheduler() -> "AccountRefreshScheduler | None":
"""Return the registered account refresh scheduler, if any."""
return _refresh_scheduler
def set_refresh_scheduler_leader(is_leader: bool) -> None:
"""Record whether this worker currently owns the refresh scheduler lock."""
global _refresh_scheduler_leader
_refresh_scheduler_leader = bool(is_leader)
def is_refresh_scheduler_leader() -> bool:
"""Return True when this worker is the active refresh-scheduler leader."""
return _refresh_scheduler_leader
def reconcile_refresh_runtime(
enabled: bool | None = None,
) -> Literal["quota", "random"]:
"""Hot-apply refresh strategy and scheduler state for the current worker."""
from app.dataplane.account.selector import current_strategy, set_strategy
from app.platform.config.snapshot import config
from app.platform.logging.logger import logger
refresh_enabled = (
config.get_bool("account.refresh.enabled", False)
if enabled is None
else bool(enabled)
)
target_strategy: Literal["quota", "random"] = (
"quota" if refresh_enabled else "random"
)
previous_strategy = current_strategy()
if previous_strategy != target_strategy:
set_strategy(target_strategy)
scheduler_action = "unchanged"
scheduler = _refresh_scheduler
if scheduler is not None and _refresh_scheduler_leader:
if refresh_enabled:
if not scheduler.is_running():
scheduler.start()
scheduler_action = "started"
elif scheduler.is_running():
scheduler.stop()
scheduler_action = "stopped"
if previous_strategy != target_strategy or scheduler_action != "unchanged":
logger.info(
"account refresh runtime reconciled: previous_strategy={} strategy={} leader={} scheduler_action={}",
previous_strategy,
target_strategy,
_refresh_scheduler_leader,
scheduler_action,
)
return target_strategy
# ---------------------------------------------------------------------------
# In-Memory Auditor (Rolling queue to protect TiDB Serverless free quota)
# ---------------------------------------------------------------------------
class InMemoryAuditor:
def __init__(self, max_logs: int = 2000):
# 限制最大长度为 2000 条,超出自动弹出旧数据,完美保护免费版
self._logs = deque(maxlen=max_logs)
self._lock = threading.Lock()
def record(self, log: AuditLogRecord):
with self._lock:
self._logs.append(log)
def get_logs(self, page: int = 1, page_size: int = 50) -> list[AuditLogRecord]:
with self._lock:
# 复制一份并逆序,让最新生成的日志排在最前面
all_logs = list(self._logs)
all_logs.reverse()
start = (page - 1) * page_size
return all_logs[start:start + page_size]
def get_distribution(self, quota_type: str) -> QuotaDistributionSummary:
with self._lock:
all_logs = list(self._logs)
# 过滤指定类型的额度数据(如 fast 或 console)
filtered = [l for l in all_logs if l.quota_type == quota_type]
total = len(filtered)
success = sum(1 for l in filtered if l.status == "SUCCESS")
ips: dict[str, int] = {}
uas: dict[str, int] = {}
for l in filtered:
ips[l.device_ip] = ips.get(l.device_ip, 0) + 1
uas[l.user_agent] = uas.get(l.user_agent, 0) + 1
# 提取调用频次前 5 的分布明细
top_ips = dict(sorted(ips.items(), key=lambda x: x[1], reverse=True)[:5])
top_uas = dict(sorted(uas.items(), key=lambda x: x[1], reverse=True)[:5])
return QuotaDistributionSummary(
quota_type=quota_type,
total_calls=total,
success_calls=success,
fail_calls=total - success,
top_ips=top_ips,
top_user_agents=top_uas
)
# 全局单例,供路由层和数据面公用
global_auditor = InMemoryAuditor(max_logs=2000)
# ---------------------------------------------------------------------------
# Module Exports (Placed at the bottom)
# ---------------------------------------------------------------------------
__all__ = [
"get_refresh_service",
"set_refresh_service",
"get_refresh_scheduler",
"set_refresh_scheduler",
"is_refresh_scheduler_leader",
"set_refresh_scheduler_leader",
"reconcile_refresh_runtime",
"InMemoryAuditor",
"global_auditor",
]