feat(douyu): 隔离充值会话并阻止同账号并发充值
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user