发布(0.4.1): 优化分配性能与客服数据边界

修复分配页皮肤查询并发慢查询;客服导入账号严格限制为本人名下;分配概览改用真实归属数量;标题区展示版本并提示刷新。
This commit is contained in:
yml
2026-11-26 21:19:11 +08:00
parent 174ae23ac1
commit 7dfc9d725e
15 changed files with 409 additions and 106 deletions
+5 -2
View File
@@ -41,7 +41,7 @@ from .routers import (
)
from .schemas import AppInfo
from .session import SessionRenewalMiddleware
from .version import get_app_version
from .version import get_app_version, get_frontend_release_id
@asynccontextmanager
@@ -203,7 +203,10 @@ async def health():
@app.get("/api/app-info", response_model=AppInfo)
def app_info():
return AppInfo(version=get_app_version())
return AppInfo(
version=get_app_version(),
release_id=get_frontend_release_id(),
)
# ---- 生产环境:serve 前端静态文件 ----
+109 -52
View File
@@ -1,5 +1,7 @@
import csv
import io
import threading
import time
from datetime import UTC, datetime
from typing import Any
@@ -88,11 +90,18 @@ from ..services.login_failure import classify_failure, failure_kind_label
router = APIRouter(prefix="/api/accounts", tags=["账号管理"])
_ASSIGNMENT_SKIN_CACHE_SECONDS = 60.0
_assignment_skin_cache_lock = threading.Lock()
_assignment_skin_cache: tuple[float, int, list[dict[str, Any]]] | None = None
def _visible_accounts_query(db: Session, current: User):
"""返回当前用户可见的斗鱼账号查询。"""
query = db.query(Account)
if user_has_permission(current, "account:view_all"):
if (
current.role != "support"
and user_has_permission(current, "account:view_all")
):
return query
if user_has_permission(current, "account:view_assigned"):
return query.filter(Account.assigned_to == current.id)
@@ -125,6 +134,79 @@ def _assignment_support_target(db: Session, user_id: int) -> User:
return target
def _assignment_skin_options(
db: Session,
*,
now: datetime,
) -> list[dict[str, Any]]:
"""候选皮肤列表只查能力快照,不提前 JOIN 账号占用。
“某皮肤有多少账号可发”的完整口径由正式候选查询负责;选项接口只需要
提供可选择的商品。把归属、租约和预售 EXISTS 放进这里会让 GROUP BY
对几十万商品状态逐行做相关子查询,生产实测单条 SQL 可跑数分钟。
"""
global _assignment_skin_cache
engine_key = id(db.get_bind().engine)
cached = _assignment_skin_cache
if (
cached is not None
and cached[1] == engine_key
and time.monotonic() - cached[0] < _ASSIGNMENT_SKIN_CACHE_SECONDS
):
return [dict(item) for item in cached[2]]
with _assignment_skin_cache_lock:
cached = _assignment_skin_cache
if (
cached is not None
and cached[1] == engine_key
and time.monotonic() - cached[0] < _ASSIGNMENT_SKIN_CACHE_SECONDS
):
return [dict(item) for item in cached[2]]
rows = (
db.query(
AccountCommodityState.commodity_id,
func.max(AccountCommodityState.commodity_name).label(
"commodity_name"
),
AccountCommodityState.scope,
func.count(AccountCommodityState.id).label("account_count"),
)
.filter(
AccountCommodityState.platform == "douyu",
AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
AccountCommodityState.offer_state.in_(
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
.group_by(
AccountCommodityState.commodity_id,
AccountCommodityState.scope,
)
.order_by(
func.count(AccountCommodityState.id).desc(),
func.max(AccountCommodityState.commodity_name).asc(),
)
.limit(200)
.all()
)
result = [
{
"commodity_id": str(commodity_id),
"commodity_name": str(commodity_name or commodity_id),
"scope": str(scope or "elite"),
"account_count": int(account_count or 0),
}
for commodity_id, commodity_name, scope, account_count in rows
]
_assignment_skin_cache = (time.monotonic(), engine_key, result)
return [dict(item) for item in result]
def _query_str(value) -> str:
"""把查询参数安全地取成字符串。
@@ -187,7 +269,11 @@ def _filter_accounts_query(
query = query.filter(Account.cookie.isnot(None), Account.cookie != "")
if _query_bool(assignable_only):
query = query.filter(_assignable_account_filter())
if _query_bool(assigned_only) and user_has_permission(current, "account:view_all"):
if (
_query_bool(assigned_only)
and current.role != "support"
and user_has_permission(current, "account:view_all")
):
query = query.filter(Account.assigned_to.isnot(None))
# 归属筛选:未分配 / 已分配,再叠加「指定客服」。与其它条件(标签、CK、
# 搜索…)是**同时生效**的,这正是「综合筛选」的用法。
@@ -902,7 +988,10 @@ def accounts_summary(
):
"""账号管理统计,避免前端为了卡片统计拉全量账号。"""
query = db.query(Account)
if not user_has_permission(current, "account:view_all"):
if (
current.role == "support"
or not user_has_permission(current, "account:view_all")
):
if user_has_permission(current, "account:view_assigned"):
query = query.filter(Account.assigned_to == current.id)
else:
@@ -1445,35 +1534,37 @@ def assignments_summary(
db: Session = Depends(get_db),
current: User = Depends(require_permission("account:assign")),
):
"""分配概览:每个客服分到了多少**可分配账号**(当前 Cookie 已通过新鲜 CK 检测)。
未检测、检测失败或旧结论的账号必须先重登/复检,放进分配池只会让客服以为能跑任务,
所以列表、全量分配与这里的统计统一用 `_assignable_account_filter()`。
"""
"""分配概览:统计真实归属数量,另由候选池接口统计新鲜可分配数量。"""
results = (
db.query(User.id, User.username, func.count(Account.id).label("count"))
.outerjoin(
Account,
and_(
Account.assigned_to == User.id,
_assignable_account_filter(),
),
Account.assigned_to == User.id,
)
.filter(User.role == "support", User.is_active.is_(True))
.group_by(User.id, User.username)
.order_by(func.count(Account.id).desc())
.all()
)
active_support_ids = select(User.id).where(
User.role == "support",
User.is_active.is_(True),
)
total_unassigned = (
db.query(func.count(Account.id))
.filter(Account.assigned_to.is_(None))
.scalar()
) or 0
total_orphaned = (
db.query(func.count(Account.id))
.filter(
Account.assigned_to.is_(None),
_assignable_account_filter(),
Account.assigned_to.isnot(None),
~Account.assigned_to.in_(active_support_ids),
)
.scalar()
) or 0
total_assigned = sum(int(cnt or 0) for _, _, cnt in results)
total_accounts = total_assigned + total_unassigned
total_accounts = total_assigned + total_unassigned + total_orphaned
return {
"support_users": [
{"id": uid, "username": uname, "assigned_count": int(cnt or 0)}
@@ -1481,6 +1572,7 @@ def assignments_summary(
],
"unassigned_count": total_unassigned,
"assigned_count": total_assigned,
"orphaned_count": total_orphaned,
"total_count": total_accounts,
}
@@ -1539,46 +1631,11 @@ def assignment_options(
),
}
skin_rows = (
db.query(
AccountCommodityState.commodity_id,
func.max(AccountCommodityState.commodity_name).label("commodity_name"),
AccountCommodityState.scope,
func.count(func.distinct(AccountCommodityState.account_id)).label(
"account_count"
),
)
.join(Account, Account.id == AccountCommodityState.account_id)
.filter(
AccountCommodityState.platform == "douyu",
AccountCommodityState.account_eligibility
== ACCOUNT_ELIGIBILITY_ELIGIBLE,
AccountCommodityState.offer_state.in_(
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
*base_filters,
~has_lease,
~in_collab,
)
.group_by(AccountCommodityState.commodity_id, AccountCommodityState.scope)
.order_by(func.count(func.distinct(AccountCommodityState.account_id)).desc())
.limit(200)
.all()
)
skins = _assignment_skin_options(db, now=now)
return {
"occupancy": occupancy,
"presets": presets,
"skins": [
{
"commodity_id": str(commodity_id),
"commodity_name": str(commodity_name or commodity_id),
"scope": str(scope or "elite"),
"account_count": int(account_count or 0),
}
for commodity_id, commodity_name, scope, account_count in skin_rows
],
"skins": skins,
}
+2 -1
View File
@@ -298,7 +298,8 @@ async def supplier_recharge_callback(request: Request, db: Session = Depends(get
def _can_view_all(user: User) -> bool:
return user_has_permission(user, "account:view_all")
"""客服始终只能看自己名下账号,额外权限也不能突破这个角色边界。"""
return user.role != "support" and user_has_permission(user, "account:view_all")
def _visible_task_accounts_query(db: Session, current: User):
+1
View File
@@ -2030,6 +2030,7 @@ class PlatformInfo(BaseModel):
# ---- 通用 ----
class AppInfo(BaseModel):
version: str
release_id: str = ""
class MessageResponse(BaseModel):
+20
View File
@@ -1,5 +1,6 @@
"""应用版本信息。"""
import hashlib
import tomllib
from functools import lru_cache
from importlib.metadata import PackageNotFoundError
@@ -22,3 +23,22 @@ def get_app_version() -> str:
return package_version("live-hub-py")
except PackageNotFoundError:
return "0.0.0"
@lru_cache(maxsize=1)
def get_frontend_release_id() -> str:
"""当前前端构建的稳定标识。
Vite 的 index.html 引用带内容哈希的 JS/CSS 文件,因此构建产物变化时
index.html 也会变化。只升级 pyproject 版本不足以识别同版本重新部署,
所以把它和版本号组合成 release_id,供前端判断是否需要刷新。
"""
version = get_app_version()
index_path = (
Path(__file__).resolve().parents[2] / "web" / "frontend" / "dist" / "index.html"
)
try:
digest = hashlib.sha256(index_path.read_bytes()).hexdigest()[:12]
except OSError:
digest = "source"
return f"{version}+{digest}"