fix(douyu): 修复斗鱼链路 P0/P1 隐患并增强 P2 运维队列可观测性
This commit is contained in:
@@ -11,8 +11,10 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from core.douyu import DouyuActivityClient, DouyuActivityError
|
||||
|
||||
from ..database import release_idle_session
|
||||
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
|
||||
from .account_exchange_sync_service import sync_exchange_records
|
||||
from .account_sync_service import lock_account_row
|
||||
from .binding_ownership import role_names_match, workbench_task_occupation_error
|
||||
from .business_events import record_exchange
|
||||
from .douyu_activity_query import (
|
||||
@@ -279,6 +281,8 @@ class GoodsMixin:
|
||||
score = int(goods.score) * (
|
||||
int(num) if isinstance(num, (int, float)) else 1
|
||||
)
|
||||
if account.id is not None:
|
||||
lock_account_row(db, int(account.id))
|
||||
record_exchange(
|
||||
db,
|
||||
account,
|
||||
@@ -374,156 +378,148 @@ class GoodsMixin:
|
||||
if not commodity_id:
|
||||
self._mark_task(db, task, "failed", "请选择兑换商品")
|
||||
return
|
||||
client = self._client(cookie)
|
||||
manual_id = str(config["manual_id"])
|
||||
rid = str(config.get("rid") or "")
|
||||
result: dict = {"commodity_id": commodity_id}
|
||||
|
||||
# ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ----
|
||||
manual_type = None
|
||||
try:
|
||||
user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||
manual_type = user_info.get("manual_type")
|
||||
except DouyuActivityError as exc:
|
||||
self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}")
|
||||
detail = None
|
||||
try:
|
||||
detail = client.query_goods_detail(
|
||||
manual_id=manual_id, commodity_id=commodity_id, rid=rid
|
||||
)["detail"]
|
||||
except DouyuActivityError as exc:
|
||||
self._push_log("warning", f"查询商品详情失败,按经典流程继续: {exc}")
|
||||
|
||||
batch_num_limit = None
|
||||
if detail and int(detail.get("batchExchange") or 0) > 0:
|
||||
try:
|
||||
batch_num_limit = client.batch_exchange_limit(
|
||||
manual_id=manual_id, commodity_id=commodity_id, rid=rid
|
||||
)["limit"]
|
||||
except DouyuActivityError as exc:
|
||||
self._push_log("warning", f"查询批量兑换上限失败: {exc}")
|
||||
|
||||
plan = DouyuActivityClient.resolve_exchange_plan(
|
||||
detail or {}, manual_type=manual_type, batch_num_limit=batch_num_limit
|
||||
)
|
||||
result["plan"] = plan
|
||||
if detail:
|
||||
result["detail"] = detail
|
||||
action = plan["action"]
|
||||
|
||||
def finish_failed(message: str) -> None:
|
||||
self._mark_task(
|
||||
db,
|
||||
task,
|
||||
"failed",
|
||||
message,
|
||||
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
|
||||
)
|
||||
|
||||
if action in ("blocked", "wait"):
|
||||
finish_failed(f"兑换失败: {plan['text']}")
|
||||
return
|
||||
|
||||
goods = (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id == commodity_id)
|
||||
.first()
|
||||
)
|
||||
goods_raw = goods.raw if goods else None
|
||||
name = (goods.name if goods else "") or commodity_id
|
||||
|
||||
if action == "subscribe":
|
||||
task_id = int(task.id)
|
||||
account_id = int(account.id)
|
||||
created_by = int(task.created_by)
|
||||
manual_id = str(config["manual_id"])
|
||||
rid = str(config.get("rid") or "")
|
||||
result: dict[str, Any] = {"commodity_id": commodity_id}
|
||||
client = self._client(cookie)
|
||||
# 锁单、退避睡眠和支付轮询耗时可能高达数分钟,期间释放干净的托管连接。
|
||||
release_idle_session(db)
|
||||
try:
|
||||
# ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ----
|
||||
manual_type = None
|
||||
try:
|
||||
client.subscribe_commodity(
|
||||
manual_id=manual_id, commodity_id=commodity_id
|
||||
)
|
||||
user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid)
|
||||
manual_type = user_info.get("manual_type")
|
||||
except DouyuActivityError as exc:
|
||||
finish_failed(f"预约到货失败: {exc}")
|
||||
return
|
||||
account.updated_at = datetime.now(UTC)
|
||||
self._mark_task(
|
||||
db,
|
||||
task,
|
||||
"success",
|
||||
f"已预约到货: {name} ({plan['text']})",
|
||||
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
|
||||
)
|
||||
return
|
||||
|
||||
if action == "pre_exchange":
|
||||
self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}")
|
||||
detail = None
|
||||
try:
|
||||
check = client.pre_exchange_check(
|
||||
manual_id=manual_id, commodity_id=commodity_id
|
||||
)
|
||||
user_status = int((check.get("data") or {}).get("userStatus") or 0)
|
||||
if user_status == 1 and not plan["pre_exchange"]:
|
||||
self._mark_task(
|
||||
db,
|
||||
task,
|
||||
"success",
|
||||
f"已预兑: {name},等待开放后继续兑换",
|
||||
{
|
||||
"commodity_id": commodity_id,
|
||||
"plan": plan,
|
||||
"detail": detail,
|
||||
"check": check,
|
||||
},
|
||||
)
|
||||
return
|
||||
confirm = client.confirm_pre_exchange(
|
||||
detail = client.query_goods_detail(
|
||||
manual_id=manual_id, commodity_id=commodity_id, rid=rid
|
||||
)
|
||||
)["detail"]
|
||||
except DouyuActivityError as exc:
|
||||
finish_failed(f"预兑失败: {exc}")
|
||||
self._push_log("warning", f"查询商品详情失败,按经典流程继续: {exc}")
|
||||
|
||||
batch_num_limit = None
|
||||
if detail and int(detail.get("batchExchange") or 0) > 0:
|
||||
try:
|
||||
batch_num_limit = client.batch_exchange_limit(
|
||||
manual_id=manual_id, commodity_id=commodity_id, rid=rid
|
||||
)["limit"]
|
||||
except DouyuActivityError as exc:
|
||||
self._push_log("warning", f"查询批量兑换上限失败: {exc}")
|
||||
|
||||
plan = DouyuActivityClient.resolve_exchange_plan(
|
||||
detail or {}, manual_type=manual_type, batch_num_limit=batch_num_limit
|
||||
)
|
||||
result["plan"] = plan
|
||||
if detail:
|
||||
result["detail"] = detail
|
||||
action = plan["action"]
|
||||
|
||||
def finish_failed(message: str) -> None:
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
self._mark_task(
|
||||
db,
|
||||
active_task,
|
||||
"failed",
|
||||
message,
|
||||
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
|
||||
)
|
||||
|
||||
if action in ("blocked", "wait"):
|
||||
finish_failed(f"兑换失败: {plan['text']}")
|
||||
return
|
||||
account.updated_at = datetime.now(UTC)
|
||||
self._mark_task(
|
||||
db,
|
||||
task,
|
||||
"success",
|
||||
f"预兑成功: {name},开放后可继续兑换",
|
||||
{
|
||||
"commodity_id": commodity_id,
|
||||
"plan": plan,
|
||||
"detail": detail,
|
||||
"check": check,
|
||||
"confirm": confirm,
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
# ---- 经典链路:锁单 -> 人类节奏等待 -> 支付(错误分类退避重试)----
|
||||
try:
|
||||
num = max(1, int(payload.get("num") or 1))
|
||||
except (TypeError, ValueError):
|
||||
num = 1
|
||||
num = min(num, int(plan.get("max_num") or 1))
|
||||
if action == "subscribe":
|
||||
try:
|
||||
client.subscribe_commodity(
|
||||
manual_id=manual_id, commodity_id=commodity_id
|
||||
)
|
||||
except DouyuActivityError as exc:
|
||||
finish_failed(f"预约到货失败: {exc}")
|
||||
return
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
active_account = db.get(Account, account_id) or account
|
||||
active_account.updated_at = datetime.now(UTC)
|
||||
self._mark_task(
|
||||
db,
|
||||
active_task,
|
||||
"success",
|
||||
f"已预约到货: {name} ({plan['text']})",
|
||||
{"commodity_id": commodity_id, "plan": plan, "detail": detail},
|
||||
)
|
||||
return
|
||||
|
||||
# 少量随机抖动(浏览器点击商品到锁单之间有人工间隔)
|
||||
self._push_log("info", f" 兑换 {name}: {plan['text']}")
|
||||
if not self._sleep_interruptible(
|
||||
random.uniform(*DOUYU_EXCHANGE_PRE_CREATE_JITTER)
|
||||
):
|
||||
self._mark_task(db, task, "stopped", "任务已停止", result)
|
||||
return
|
||||
try:
|
||||
locked = client.create_exchange_order(
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
commodity_id=commodity_id,
|
||||
num=num,
|
||||
)
|
||||
except DouyuActivityError as exc:
|
||||
# 锁单本身被频控时做一次长退避重试,避免无脑连打
|
||||
backoff = (
|
||||
DOUYU_EXCHANGE_RATE_LIMIT_BACKOFFS[0]
|
||||
if self._is_rate_limited_error(str(exc))
|
||||
else 3
|
||||
)
|
||||
self._push_log(
|
||||
"info", f" 锁定兑换商品失败({exc}),{backoff:.0f}s 后重试一次"
|
||||
)
|
||||
if not self._sleep_interruptible(backoff):
|
||||
self._mark_task(db, task, "stopped", "任务已停止", result)
|
||||
if action == "pre_exchange":
|
||||
try:
|
||||
check = client.pre_exchange_check(
|
||||
manual_id=manual_id, commodity_id=commodity_id
|
||||
)
|
||||
user_status = int((check.get("data") or {}).get("userStatus") or 0)
|
||||
if user_status == 1 and not plan["pre_exchange"]:
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
self._mark_task(
|
||||
db,
|
||||
active_task,
|
||||
"success",
|
||||
f"已预兑: {name},等待开放后继续兑换",
|
||||
{
|
||||
"commodity_id": commodity_id,
|
||||
"plan": plan,
|
||||
"detail": detail,
|
||||
"check": check,
|
||||
},
|
||||
)
|
||||
return
|
||||
confirm = client.confirm_pre_exchange(
|
||||
manual_id=manual_id, commodity_id=commodity_id, rid=rid
|
||||
)
|
||||
except DouyuActivityError as exc:
|
||||
finish_failed(f"预兑失败: {exc}")
|
||||
return
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
active_account = db.get(Account, account_id) or account
|
||||
active_account.updated_at = datetime.now(UTC)
|
||||
self._mark_task(
|
||||
db,
|
||||
active_task,
|
||||
"success",
|
||||
f"预兑成功: {name},开放后可继续兑换",
|
||||
{
|
||||
"commodity_id": commodity_id,
|
||||
"plan": plan,
|
||||
"detail": detail,
|
||||
"check": check,
|
||||
"confirm": confirm,
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
# ---- 经典链路:锁单 -> 人类节奏等待 -> 支付(错误分类退避重试)----
|
||||
try:
|
||||
num = max(1, int(payload.get("num") or 1))
|
||||
except (TypeError, ValueError):
|
||||
num = 1
|
||||
num = min(num, int(plan.get("max_num") or 1))
|
||||
|
||||
# 少量随机抖动(浏览器点击商品到锁单之间有人工间隔)
|
||||
self._push_log("info", f" 兑换 {name}: {plan['text']}")
|
||||
if not self._sleep_interruptible(
|
||||
random.uniform(*DOUYU_EXCHANGE_PRE_CREATE_JITTER)
|
||||
):
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
self._mark_task(db, active_task, "stopped", "任务已停止", result)
|
||||
return
|
||||
try:
|
||||
locked = client.create_exchange_order(
|
||||
@@ -532,103 +528,132 @@ class GoodsMixin:
|
||||
commodity_id=commodity_id,
|
||||
num=num,
|
||||
)
|
||||
except DouyuActivityError as exc2:
|
||||
finish_failed(f"锁定兑换商品失败: {exc2}")
|
||||
except DouyuActivityError as exc:
|
||||
# 锁单本身被频控时做一次长退避重试,避免无脑连打
|
||||
backoff = (
|
||||
DOUYU_EXCHANGE_RATE_LIMIT_BACKOFFS[0]
|
||||
if self._is_rate_limited_error(str(exc))
|
||||
else 3
|
||||
)
|
||||
self._push_log(
|
||||
"info", f" 锁定兑换商品失败({exc}),{backoff:.0f}s 后重试一次"
|
||||
)
|
||||
if not self._sleep_interruptible(backoff):
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
self._mark_task(db, active_task, "stopped", "任务已停止", result)
|
||||
return
|
||||
try:
|
||||
locked = client.create_exchange_order(
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
commodity_id=commodity_id,
|
||||
num=num,
|
||||
)
|
||||
except DouyuActivityError as exc2:
|
||||
finish_failed(f"锁定兑换商品失败: {exc2}")
|
||||
return
|
||||
result.update(
|
||||
{**locked, "lock_order": locked, "goods": goods_raw}
|
||||
)
|
||||
|
||||
# 锁单成功后按浏览器节奏(抓包实测 2.24s~4.2s)等待再支付
|
||||
delay = random.uniform(*DOUYU_EXCHANGE_LOCK_PAY_DELAY_RANGE)
|
||||
self._push_log(
|
||||
"info", f" 锁单成功(订单 {locked['order_id']}),{delay:.1f}s 后支付"
|
||||
)
|
||||
if not self._sleep_interruptible(delay):
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
self._mark_task(
|
||||
db, active_task, "stopped", "任务已停止,商品锁单仍可能有效", locked
|
||||
)
|
||||
return
|
||||
try:
|
||||
payment = self._pay_exchange_with_backoff(
|
||||
client,
|
||||
manual_id=manual_id,
|
||||
order_id=locked["order_id"],
|
||||
rid=rid,
|
||||
locked_at=locked["locked_at"],
|
||||
)
|
||||
except DouyuActivityError as exc:
|
||||
finish_failed(str(exc))
|
||||
return
|
||||
if payment is None:
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
self._mark_task(
|
||||
db, active_task, "stopped", "任务已停止,商品锁单仍可能有效", locked
|
||||
)
|
||||
return
|
||||
result.update(
|
||||
{**locked, "lock_order": locked, "goods": goods.raw if goods else None}
|
||||
)
|
||||
|
||||
# 锁单成功后按浏览器节奏(抓包实测 2.24s~4.2s)等待再支付
|
||||
delay = random.uniform(*DOUYU_EXCHANGE_LOCK_PAY_DELAY_RANGE)
|
||||
self._push_log(
|
||||
"info", f" 锁单成功(订单 {locked['order_id']}),{delay:.1f}s 后支付"
|
||||
)
|
||||
if not self._sleep_interruptible(delay):
|
||||
self._mark_task(
|
||||
db, task, "stopped", "任务已停止,商品锁单仍可能有效", locked
|
||||
result.update(
|
||||
{
|
||||
"order_id": locked["order_id"],
|
||||
"exchange_id": payment["exchange_id"],
|
||||
"commodity_image": payment["commodity_image"]
|
||||
or locked["commodity_image"],
|
||||
"exchange_num": payment["exchange_num"],
|
||||
"payment": payment,
|
||||
}
|
||||
)
|
||||
return
|
||||
try:
|
||||
payment = self._pay_exchange_with_backoff(
|
||||
active_task = db.get(DouyuTask, task_id) or task
|
||||
active_account = db.get(Account, account_id) or account
|
||||
active_account.updated_at = datetime.now(UTC)
|
||||
# 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功)
|
||||
points_refresh = None
|
||||
try:
|
||||
ctn = query_csrf(client)
|
||||
points_refresh = self._refresh_account_points(
|
||||
client, active_account, cookie, ctn=ctn
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
|
||||
self._push_log("warning", f"兑换后刷新积分失败: {exc}")
|
||||
# ⚠️ **只有这一条 success 是真的兑换**。同一个 handler 里还有三条
|
||||
# 「预约到货 / 已预兑 / 预兑确认」的 success —— 它们不消耗积分、也没换到东西,
|
||||
# 所以**不发事件**。旧收集器只按 status=="success" 收集,导致每预约一次
|
||||
# 就生成一条金额为空的 exchange,把 accounts 的 exchange_count 灌大。
|
||||
lock_account_row(db, account_id)
|
||||
record_exchange(
|
||||
db,
|
||||
active_account,
|
||||
task_id=active_task.id,
|
||||
name=name,
|
||||
score=locked.get("score"),
|
||||
commodity_id=commodity_id,
|
||||
order_id=str(locked.get("order_id") or ""),
|
||||
exchange_id=str(payment.get("exchange_id") or ""),
|
||||
game_name=active_account.game_name or "",
|
||||
game_channel=active_account.game_channel or "",
|
||||
points_after=(points_refresh or {}).get("points"),
|
||||
scope="elite",
|
||||
actor_id=created_by,
|
||||
)
|
||||
self._refresh_high_value_after_exchange(
|
||||
client,
|
||||
active_account,
|
||||
manual_id=manual_id,
|
||||
order_id=locked["order_id"],
|
||||
rid=rid,
|
||||
locked_at=locked["locked_at"],
|
||||
commodity_name=name,
|
||||
)
|
||||
except DouyuActivityError as exc:
|
||||
finish_failed(str(exc))
|
||||
return
|
||||
if payment is None:
|
||||
self._mark_task(
|
||||
db, task, "stopped", "任务已停止,商品锁单仍可能有效", locked
|
||||
db,
|
||||
active_task,
|
||||
"success",
|
||||
f"兑换成功: {name}",
|
||||
{
|
||||
"goods": goods_raw,
|
||||
"game_name": active_account.game_name or "",
|
||||
"game_channel": active_account.game_channel or "",
|
||||
"account_name": active_account.nickname
|
||||
or active_account.username
|
||||
or active_account.uid
|
||||
or f"#{active_account.id}",
|
||||
**result,
|
||||
**(points_refresh or {}),
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
result.update(
|
||||
{
|
||||
"order_id": locked["order_id"],
|
||||
"exchange_id": payment["exchange_id"],
|
||||
"commodity_image": payment["commodity_image"]
|
||||
or locked["commodity_image"],
|
||||
"exchange_num": payment["exchange_num"],
|
||||
"payment": payment,
|
||||
}
|
||||
)
|
||||
account.updated_at = datetime.now(UTC)
|
||||
# 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功)
|
||||
points_refresh = None
|
||||
try:
|
||||
ctn = query_csrf(client)
|
||||
points_refresh = self._refresh_account_points(
|
||||
client, account, cookie, ctn=ctn
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
|
||||
self._push_log("warning", f"兑换后刷新积分失败: {exc}")
|
||||
# ⚠️ **只有这一条 success 是真的兑换**。同一个 handler 里还有三条
|
||||
# 「预约到货 / 已预兑 / 预兑确认」的 success —— 它们不消耗积分、也没换到东西,
|
||||
# 所以**不发事件**。旧收集器只按 status=="success" 收集,导致每预约一次
|
||||
# 就生成一条金额为空的 exchange,把 accounts 的 exchange_count 灌大。
|
||||
record_exchange(
|
||||
db,
|
||||
account,
|
||||
task_id=task.id,
|
||||
name=name,
|
||||
score=locked.get("score"),
|
||||
commodity_id=commodity_id,
|
||||
order_id=str(locked.get("order_id") or ""),
|
||||
exchange_id=str(payment.get("exchange_id") or ""),
|
||||
game_name=account.game_name or "",
|
||||
game_channel=account.game_channel or "",
|
||||
points_after=(points_refresh or {}).get("points"),
|
||||
scope="elite",
|
||||
actor_id=int(task.created_by),
|
||||
)
|
||||
self._refresh_high_value_after_exchange(
|
||||
client,
|
||||
account,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
commodity_name=name,
|
||||
)
|
||||
self._mark_task(
|
||||
db,
|
||||
task,
|
||||
"success",
|
||||
f"兑换成功: {name}",
|
||||
{
|
||||
"goods": goods.raw if goods else None,
|
||||
"game_name": account.game_name or "",
|
||||
"game_channel": account.game_channel or "",
|
||||
"account_name": account.nickname
|
||||
or account.username
|
||||
or account.uid
|
||||
or f"#{account.id}",
|
||||
**result,
|
||||
**(points_refresh or {}),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
if isinstance(client, DouyuActivityClient):
|
||||
client.close()
|
||||
|
||||
def _execute_exchange_esports_goods(
|
||||
self,
|
||||
@@ -713,6 +738,8 @@ class GoodsMixin:
|
||||
and isinstance(after_points, (int, float))
|
||||
else None
|
||||
)
|
||||
if account.id is not None:
|
||||
lock_account_row(db, int(account.id))
|
||||
record_exchange(
|
||||
db,
|
||||
account,
|
||||
|
||||
Reference in New Issue
Block a user