feat(douyu): 隔离充值会话并阻止同账号并发充值

This commit is contained in:
yml
2026-11-19 20:40:43 +08:00
parent 66a310ec98
commit 62cb0a41ec
6 changed files with 866 additions and 157 deletions
+8 -4
View File
@@ -62,7 +62,9 @@ from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
from ..services.douyu_service import (
DOUYU_CONFIG_FIELDS,
DOUYU_HANDBOOK_TASK_TYPES,
DOUYU_ACTIVE_TASK_STATUSES,
SUPPORTED_DOUYU_TASK_TYPES,
DouyuActivePaymentError,
apply_douyu_config_defaults,
cleanup_orphan_douyu_tasks,
cookie_holding_filter,
@@ -294,8 +296,8 @@ def _require_task_account_access(
def _require_batch_owner(db: Session, current: User, batch_id: str) -> None:
"""客服只能停止或订阅自己创建的任务批次。"""
if _can_view_all(current):
"""除超级管理员外,只能停止或订阅自己创建的任务批次。"""
if current.role == "super_admin":
return
exists = (
db.query(DouyuTask.id)
@@ -819,7 +821,7 @@ async def create_task_batch(
cleanup_orphan_douyu_tasks(
db,
active_batch_ids=douyu_batch_registry.active_ids(),
statuses=("pending", "running"),
statuses=DOUYU_ACTIVE_TASK_STATUSES,
message="任务已中断(无执行器接管)",
)
@@ -833,6 +835,8 @@ async def create_task_batch(
req.payload,
platform_task_id=req.platform_task_id,
)
except DouyuActivePaymentError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if count == 0:
@@ -976,7 +980,7 @@ def cleanup_orphan_tasks(
cleaned = cleanup_orphan_douyu_tasks(
db,
active_batch_ids=douyu_batch_registry.active_ids(),
statuses=("pending", "running"),
statuses=DOUYU_ACTIVE_TASK_STATUSES,
message="任务已中断(无执行器接管)",
)
return {
+65
View File
@@ -139,6 +139,15 @@ DOUYU_CONFIG_DEFAULTS = {
DOUYU_CONFIG_FIELDS = tuple(DOUYU_CONFIG_DEFAULTS.keys())
DOUYU_ACTIVE_TASK_STATUSES = ("planned", "pending", "running")
DOUYU_ACTIVE_PAYMENT_TASK_TYPES = (
"create_elite_qr",
"create_esports_qr",
"create_gold_qr",
)
class DouyuActivePaymentError(ValueError):
"""同一账号已有未结束的充值任务。"""
def douyu_config_value(field: str, value):
@@ -252,6 +261,61 @@ def visible_douyu_task_accounts(db: Session, account_ids: list[int]) -> list[Acc
)
def _lock_payment_accounts(
db: Session,
accounts: list[Account],
task_type: str,
) -> None:
"""串行化同一账号的充值任务创建,并拒绝并行充值。
只锁账号行还不够:MySQL 默认 REPEATABLE READ 下,普通查询可能继续读取
旧快照。冲突任务查询同样使用 ``FOR UPDATE``,保证等待锁的事务能看到前一个
请求刚提交的任务。
"""
if task_type not in DOUYU_ACTIVE_PAYMENT_TASK_TYPES or not accounts:
return
account_ids = sorted({account.id for account in accounts})
locked_ids = {
account_id
for (account_id,) in (
db.query(Account.id)
.filter(Account.id.in_(account_ids))
.order_by(Account.id.asc())
.with_for_update()
.all()
)
}
if locked_ids != set(account_ids):
raise ValueError("部分斗鱼账号不存在,请刷新后重试")
conflict = (
db.query(DouyuTask)
.filter(
DouyuTask.account_id.in_(account_ids),
DouyuTask.status.in_(DOUYU_ACTIVE_TASK_STATUSES),
DouyuTask.task_type.in_(DOUYU_ACTIVE_PAYMENT_TASK_TYPES),
)
.order_by(DouyuTask.id.desc())
.with_for_update()
.first()
)
if conflict is None:
return
account = next(
(item for item in accounts if item.id == conflict.account_id),
None,
)
label = (
(account.nickname or account.username or account.uid or f"#{account.id}")
if account is not None
else f"#{conflict.account_id}"
)
raise DouyuActivePaymentError(
f"账号 {label} 已有充值任务处理中(批次 {conflict.batch_id}),"
"请先完成或停止该充值"
)
def update_account_profile_from_cookie(account: Account, cookie: str) -> None:
"""从 Cookie 回填 uid/nickname。"""
profile = DouyuActivityClient.profile_from_cookie(cookie)
@@ -284,6 +348,7 @@ def create_douyu_planned_tasks(
raise ValueError("该任务不属于当前工作台")
accounts = visible_douyu_task_accounts(db, account_ids)
_lock_payment_accounts(db, accounts, task_type)
if (
task_type in {"refresh_goods", "refresh_esports_goods", "refresh_xpd_goods"}
and accounts