From 4665dac667c98e444838c92a9d5bfc749adaaefa Mon Sep 17 00:00:00 2001 From: butubb Date: Thu, 22 Oct 2026 14:35:59 +0800 Subject: [PATCH] =?UTF-8?q?feat(report):=20=E5=8D=9A=E4=B8=BB=E5=90=8D?= =?UTF-8?q?=E5=AD=97=E5=90=8E=E9=9D=A2=E5=B8=A6=E4=B8=8A=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E6=B1=A0=E7=9A=84=E8=B4=A6=E5=8F=B7=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 账号池服务(192.168.20.220:18050 的 /api/account_pool/accounts)返回每个号的 `nickname` 和 `account_status`(账号正常 / 账号异常 / 作品异常 / 账号安全待提升)。 报表按昵称匹配,在名字后面加括号显示:`周周逛苏州(账号异常)`。 **由后端去取,浏览器不直连** —— token 不该下发到前端,跨域也麻烦。地址和 token 走 环境变量 `MC_ACCOUNT_POOL_URL` / `MC_ACCOUNT_POOL_TOKEN`(已加到服务器 .env, 不进仓库);没配就静默跳过。 细节: * 缓存 60 秒 —— 报表会被反复刷新,而账号状态是分钟级的;刷新一次就多打一次外部 接口没有意义; * 外部服务失败时**保留上一份缓存**,没有缓存就返回空;报表本身绝不能因此打不开; * 同名不同号时把状态并起来(`A / B`),不静默只留一个; * 只在抖音平台附加 —— 那套池子管的是抖音号,小红书同名账号不该被误标。 测试 16 条(新增:按昵称附加状态、外部服务挂掉时报表照出)。 --- api/monitor/service.py | 74 ++++++++++++++++++++++++++++++++++++ api/reports/matrix.html | 10 +++-- tests/test_monitor_matrix.py | 43 +++++++++++++++++++++ 3 files changed, 124 insertions(+), 3 deletions(-) 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()