File size: 5,923 Bytes
ddebc3e
 
 
 
 
 
 
d14d5aa
 
ddebc3e
 
d14d5aa
 
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d14d5aa
 
 
c377b27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d14d5aa
c377b27
d14d5aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""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",
]