diff --git a/api/monitor/service.py b/api/monitor/service.py index 4a5c6e7..e456926 100644 --- a/api/monitor/service.py +++ b/api/monitor/service.py @@ -19,7 +19,9 @@ """Task CRUD and dashboard queries for the monitoring layer.""" import asyncio +import os import re +import time from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Sequence, Tuple from urllib.parse import parse_qs, urlparse @@ -1451,6 +1453,72 @@ async def mark_events_read(session: AsyncSession, task_id: Optional[int] = None) # --------------------------------------------------------------------------- +# --------------------------------------------------------------------------- +# 账号池状态(外部服务) +# --------------------------------------------------------------------------- +# +# 报表要在博主名字后面带上「账号正常 / 账号异常 / 账号安全待提升」这类状态,数据来自 +# 另一套账号池服务。**由后端去取,不让浏览器直连**:token 不该发到前端,而且跨域也麻烦。 +# +# 地址和 token 走环境变量;没配就静默跳过(报表照常出,只是没有状态)。 +# 缓存 60 秒:报表会被反复刷新,而账号状态是分钟级的。 + +_ACCOUNT_STATUS_TTL_SECONDS = 60.0 +_account_status_cache: Optional[Tuple[float, Dict[str, str]]] = None + + +def _reset_account_status_cache() -> None: + """测试钩子:丢掉缓存,避免用例之间互相污染。""" + global _account_status_cache + _account_status_cache = None + + +async def _fetch_account_pool() -> List[Dict[str, Any]]: + url = os.getenv("MC_ACCOUNT_POOL_URL", "").strip() + if not url: + return [] + token = os.getenv("MC_ACCOUNT_POOL_TOKEN", "").strip() + headers = {"X-Account-Token": token} if token else {} + async with httpx.AsyncClient(timeout=3.0) as client: + response = await client.get(url, headers=headers) + response.raise_for_status() + return (response.json() or {}).get("accounts") or [] + + +async def account_status_map() -> Dict[str, str]: + """昵称 → 账号状态。取不到就返回空 dict —— 报表不能因为外部服务挂了而打不开。""" + global _account_status_cache + + now = time.monotonic() + if ( + _account_status_cache is not None + and now - _account_status_cache[0] < _ACCOUNT_STATUS_TTL_SECONDS + ): + return _account_status_cache[1] + + try: + accounts = await _fetch_account_pool() + except Exception as exc: # noqa: BLE001 - 外部服务,任何失败都只降级 + print(f"[monitor.matrix] 账号池读取失败,本次不带状态:{exc}", flush=True) + # 失败不清空旧缓存:服务抖一下不该让报表上的状态全消失。 + return _account_status_cache[1] if _account_status_cache else {} + + merged: Dict[str, List[str]] = {} + for account in accounts: + nickname = (account.get("nickname") or "").strip() + status = (account.get("account_status") or "").strip() + if not nickname or not status: + continue + # 同名不同号时把状态并起来,别静默只留一个。 + bucket = merged.setdefault(nickname, []) + if status not in bucket: + bucket.append(status) + + statuses = {name: " / ".join(values) for name, values in merged.items()} + _account_status_cache = (now, statuses) + return statuses + + async def daily_tag_matrix( session: AsyncSession, platform: str, @@ -1674,6 +1742,12 @@ async def daily_tag_matrix( creators = [{"hash": hash_, "name": name} for hash_, name in known.items()] creators.sort(key=lambda item: item["name"]) + # 账号池状态只有抖音那套池子有;取不到就是空串,前端不加括号。 + if platform == adapters.PLATFORM_DY: + statuses = await account_status_map() + for creator in creators: + creator["account_status"] = statuses.get(creator["name"].strip(), "") + return { "platform": platform, "days": days, diff --git a/api/reports/matrix.html b/api/reports/matrix.html index b15890c..a61c0ee 100644 --- a/api/reports/matrix.html +++ b/api/reports/matrix.html @@ -458,12 +458,16 @@ for (const creator of data.creators) { const tr = document.createElement('tr'); const th = document.createElement('th'); - th.textContent = creator.name; - th.title = creator.name; + // 账号池给的状态挂在名字后面的括号里,例如「周周逛苏州(账号异常)」。 + const label = creator.account_status + ? creator.name + '(' + creator.account_status + ')' + : creator.name; + th.textContent = label; + th.title = label; tr.appendChild(th); for (const day of data.dates) { const rowCells = data.cells[day] || {}; - tr.appendChild(cellNode(rowCells[creator.hash], day, creator.name)); + tr.appendChild(cellNode(rowCells[creator.hash], day, label)); } tbody.appendChild(tr); } diff --git a/tests/test_monitor_matrix.py b/tests/test_monitor_matrix.py index c68fa18..c30ee69 100644 --- a/tests/test_monitor_matrix.py +++ b/tests/test_monitor_matrix.py @@ -383,6 +383,49 @@ async def test_task_from_another_platform_is_rejected(db): assert data["dates"] == [] +@pytest.mark.asyncio +async def test_account_pool_status_is_attached_by_nickname(db, monkeypatch): + task_id = await _task() + now = get_current_timestamp() - 1000 + await _note(task_id, "n1", "博主A", now) + + async def fake_pool(): + return [ + {"nickname": "博主A", "account_status": "账号异常"}, + {"nickname": "别人", "account_status": "账号正常"}, + ] + + monkeypatch.setenv("MC_ACCOUNT_POOL_URL", "http://pool/api") + monkeypatch.setattr(service, "_fetch_account_pool", fake_pool) + service._reset_account_status_cache() + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["creators"][0]["account_status"] == "账号异常" + + +@pytest.mark.asyncio +async def test_account_pool_failure_does_not_break_the_report(db, monkeypatch): + task_id = await _task() + now = get_current_timestamp() - 1000 + await _note(task_id, "n1", "博主A", now) + + async def down(): + raise RuntimeError("pool is down") + + monkeypatch.setenv("MC_ACCOUNT_POOL_URL", "http://pool/api") + monkeypatch.setattr(service, "_fetch_account_pool", down) + service._reset_account_status_cache() + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + # 外部服务挂了,报表照出,只是没有状态 + assert data["dates"] + assert data["creators"][0]["account_status"] == "" + + @pytest.mark.asyncio async def test_endpoint_returns_the_long_shape(client): task_id = await _task()