fix(douyu): 修复斗鱼链路 P0/P1 隐患并增强 P2 运维队列可观测性

This commit is contained in:
yml
2026-11-29 14:10:24 +08:00
parent be7146a9ef
commit d12d9e02b3
51 changed files with 2510 additions and 561 deletions
+136 -43
View File
@@ -25,6 +25,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..database import release_idle_session
from ..models import (
Account,
AccountEvent,
@@ -52,6 +53,7 @@ from .account_events_service import (
from .account_exchange_sync_service import sync_exchange_records
from .account_query_filters import ACTIVE_COLLAB_STATUSES
from .account_sync_runner import WORK_STOREHOME_SYNC
from .account_sync_service import lock_account_row
from .account_work_queue import enqueue_account_work
from .audit_service import record_account_action, record_audit
from .binding_ownership import role_names_match
@@ -203,6 +205,22 @@ from .platform_fulfillment.account_selector import (
)
def _detached_account_snapshot(account: Account) -> Account:
"""构造脱离 ORM 会话的轻量账号快照,供无数据库连接的外网探针读取。"""
return Account(
id=account.id,
uid=account.uid,
username=account.username,
nickname=account.nickname,
cookie=account.cookie,
elite_opened=account.elite_opened,
esports_opened=account.esports_opened,
points=account.points,
points_expire_at=account.points_expire_at,
gold_balance=account.gold_balance,
)
def _probe_with_client(
account: Account,
*,
@@ -235,15 +253,21 @@ def _probe_with_client(
"legacy_act_alias": legacy_act_alias,
}
)
result = probe_account(
account,
config_info,
client=active_client,
session_checker=None if caller_supplied_client else check_douyu_cookie,
with_gold=True,
with_goods=with_goods,
use_cache=not caller_supplied_client,
)
try:
result = probe_account(
account,
config_info,
client=active_client,
session_checker=None if caller_supplied_client else check_douyu_cookie,
with_gold=True,
with_goods=with_goods,
use_cache=not caller_supplied_client,
)
finally:
if not caller_supplied_client and isinstance(
active_client, DouyuActivityClient
):
active_client.close()
elite = result.get("elite") or {}
role = (result.get("roles") or {}).get("elite") or {}
identity = result.get("identity") or {}
@@ -1043,6 +1067,7 @@ def update_order(
client=client,
with_goods=True,
)
lock_account_row(db, int(account.id))
_ensure_order_account_lease(
db,
current,
@@ -1137,17 +1162,31 @@ def set_account(
if account is None:
raise CollabError("斗鱼账号不存在", code="account_not_found")
previous_account_id = int(order.account_id or 0)
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
config = resolve_config(db)
manual_id = str(config.manual_id or "")
rid = str(config.rid or "")
bind_act_alias = str(config.bind_act_alias or "")
confirm_act_alias = str(config.confirm_act_alias or "")
legacy_act_alias = str(config.legacy_act_alias or "")
account_snapshot = _detached_account_snapshot(account)
release_idle_session(db)
probe = _probe_with_client(
account,
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
account_snapshot,
manual_id=manual_id,
rid=rid,
act_alias=bind_act_alias,
confirm_act_alias=confirm_act_alias,
legacy_act_alias=legacy_act_alias,
client=client,
with_goods=True,
)
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
lock_account_row(db, int(account.id))
_ensure_order_account_lease(
db,
current,
@@ -1208,17 +1247,36 @@ def verify_order(
)
if account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
config = resolve_config(db)
manual_id = str(config.manual_id or "")
rid = str(config.rid or "")
bind_act_alias = str(config.bind_act_alias or "")
confirm_act_alias = str(config.confirm_act_alias or "")
legacy_act_alias = str(config.legacy_act_alias or "")
account_snapshot = _detached_account_snapshot(account)
release_idle_session(db)
probe = _probe_with_client(
account,
manual_id=str(config.manual_id or ""),
rid=str(config.rid or ""),
act_alias=str(config.bind_act_alias or ""),
confirm_act_alias=str(config.confirm_act_alias or ""),
legacy_act_alias=str(config.legacy_act_alias or ""),
account_snapshot,
manual_id=manual_id,
rid=rid,
act_alias=bind_act_alias,
confirm_act_alias=confirm_act_alias,
legacy_act_alias=legacy_act_alias,
client=client,
with_goods=True,
)
reloaded_order = db.get(DouyuExternalOrder, order_id)
if reloaded_order is None:
raise CollabError("订单不存在", status_code=404, code="order_not_found")
reloaded_account = db.get(Account, account_id)
if reloaded_account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
order = reloaded_order
account = reloaded_account
current = db.get(User, current_id) or current
apply_probe_snapshot(
db,
current,
@@ -1757,11 +1815,19 @@ def list_order_exchange_records(
error_text = ""
if refresh:
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
try:
raw_records = _load_exchange_records_for_orders(db, [order], client=client)
synced_at = _now()
except Exception as exc: # noqa: BLE001
error_text = str(exc)
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
if account.id is not None:
lock_account_row(db, int(account.id))
record_account_query(
db,
account,
@@ -1864,18 +1930,22 @@ def _load_exchange_records_for_orders(
)
if account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
config = resolve_config(db)
active_client = client or _client_for_account(account)
result = sync_exchange_records(
db,
account,
active_client,
config_mapping(config),
source="douyu_collab.activity",
scopes=("elite",),
limit=ACTIVITY_RECORD_FETCH_LIMIT,
max_pages=ACTIVITY_RECORD_MAX_PAGES,
)
config_map = config_mapping(resolve_config(db))
active_client = client or _client_for_account(_detached_account_snapshot(account))
try:
result = sync_exchange_records(
db,
account,
active_client,
config_map,
source="douyu_collab.activity",
scopes=("elite",),
limit=ACTIVITY_RECORD_FETCH_LIMIT,
max_pages=ACTIVITY_RECORD_MAX_PAGES,
)
finally:
if client is None and isinstance(active_client, DouyuActivityClient):
active_client.close()
return [
dict(record)
for record in (result.get("records") or {}).get("elite", [])
@@ -1901,6 +1971,9 @@ def query_activity(
)
if account is None:
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
order_id = int(order.id)
account_id = int(account.id)
current_id = int(current.id)
errors: list[str] = []
probe: dict[str, Any] = {}
loaded_records: list[dict[str, Any]] = []
@@ -1912,8 +1985,13 @@ def query_activity(
)
except Exception as exc: # noqa: BLE001
errors.append(f"兑换记录: {exc}")
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
else:
loaded_records = [dict(record) for record in records]
if account.id is not None:
lock_account_row(db, int(account.id))
if record_query_error:
errors.append(f"兑换记录: {record_query_error}")
manual_score = _to_int(order.points_balance)
@@ -1924,16 +2002,26 @@ def query_activity(
points_message = _text(order.points_check_message)
threshold = normalize_threshold(order.points_threshold)
else:
config = resolve_config(db)
active_client = client or _client_for_account(account)
probe = probe_account(
account,
config,
client=active_client,
session_checker=None,
with_gold=True,
with_elite_role=False,
)
config_map = config_mapping(resolve_config(db))
account_snapshot = _detached_account_snapshot(account)
active_client = client or _client_for_account(account_snapshot)
release_idle_session(db)
try:
probe = probe_account(
account_snapshot,
config_map,
client=active_client,
session_checker=None,
with_gold=True,
with_elite_role=False,
)
finally:
if client is None and isinstance(active_client, DouyuActivityClient):
active_client.close()
order = db.get(DouyuExternalOrder, order_id) or order
account = db.get(Account, account_id) or account
current = db.get(User, current_id) or current
lock_account_row(db, int(account.id))
elite = (probe.get("elite") or {}).get("raw") or {}
gold = {
"gold": (probe.get("gold") or {}).get("balance"),
@@ -2187,11 +2275,16 @@ def query_activity_batch(
_load_exchange_records_for_orders(db, account_orders),
"",
)
if (db.info or {}).get("managed_request_session"):
# 逐账号持久化官方同步快照并归还连接,避免下一个账号拉取期间占着事务
db.commit()
except Exception as exc: # noqa: BLE001 - 账号级错误复用到同账号订单
db.rollback()
records_by_account[account_key] = ([], str(exc))
results: list[dict[str, Any]] = []
for order in orders:
order = db.get(DouyuExternalOrder, int(order.id)) or order
if order.account_id:
account_key = ("id", int(order.account_id))
else: