feat(report): 博主名字后面带上账号池的账号状态
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

账号池服务(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 条(新增:按昵称附加状态、外部服务挂掉时报表照出)。
This commit is contained in:
butubb
2026-10-22 14:35:59 +08:00
parent 4a15c1485c
commit 4665dac667
3 changed files with 124 additions and 3 deletions
+74
View File
@@ -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,
+7 -3
View File
@@ -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);
}
+43
View File
@@ -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()