refactor(douyu): 统一账号准入与本地查询链路

This commit is contained in:
yml
2026-11-22 19:31:32 +08:00
parent e652d30283
commit d78437c6ac
14 changed files with 592 additions and 548 deletions
+79 -214
View File
@@ -14,8 +14,6 @@
from __future__ import annotations
from collections.abc import Callable, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import TimeoutError as FutureTimeoutError
from datetime import UTC, datetime, timedelta
from typing import Any
from unicodedata import normalize as unicode_normalize
@@ -45,12 +43,6 @@ from ..permissions import user_has_permission
from .account_binding import (
binding_channel,
binding_role_from_result,
can_change_role,
role_change_available_at,
)
from .account_capability_service import (
AVAILABILITY_AVAILABLE,
classify_goods_items,
)
from .account_events_service import (
CATEGORY_OPS,
@@ -58,6 +50,10 @@ from .account_events_service import (
EVENT_LEASE_ACQUIRED,
emit,
)
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_work_queue import enqueue_account_work
from .audit_service import record_account_action, record_audit
from .business_events import record_account_query
from .collab_common import apply_order_visibility, count_archived
@@ -75,7 +71,6 @@ from .douyu_account_probe import (
persist_probe_result,
probe_account,
)
from .douyu_activity_query import query_exchange_records
from .douyu_goods_service import (
serialize_live_goods as _serialize_live_goods,
)
@@ -106,15 +101,7 @@ STATUS_ROLE_ERROR = "role_error"
STATUS_FAILED = "failed"
STATUS_VOID = "void"
LEASE_PURPOSE_DOUYU_COLLAB = "douyu_collab"
COLLAB_LEASE_STATUSES: tuple[str, ...] = (
STATUS_INCOMPLETE,
STATUS_TO_RECHARGE,
STATUS_RECHARGED,
STATUS_SCRIPTED,
STATUS_POINTS_ERROR,
STATUS_ROLE_ERROR,
STATUS_FAILED,
)
COLLAB_LEASE_STATUSES = ACTIVE_COLLAB_STATUSES
ORDER_STATUSES: tuple[str, ...] = (
STATUS_INCOMPLETE,
@@ -150,9 +137,7 @@ STATUS_FLOW: tuple[str, ...] = (
SOURCE_TYPE_PLATFORM_FULFILLMENT = "platform_fulfillment"
ACCOUNT_REPLACE_ROLES = frozenset({"super_admin", "operation"})
ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT = 8
ACCOUNT_RECOMMEND_CONCURRENCY = 8
ACCOUNT_RECOMMEND_TIMEOUT_SECONDS = 20
ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT = 20
PLATFORM_TAKEOVER_BLOCKING_TASK_TYPES = frozenset(
{
"lock_goods",
@@ -628,24 +613,6 @@ def unlink_account(
return order
def _recommendation_account_snapshot(account: Account) -> Account:
"""复制探针所需的标量字段,避免工作线程访问 SQLAlchemy Session。"""
return Account(
id=int(account.id),
username=str(account.username or ""),
password="",
email="",
email_password="",
cookie=str(account.cookie or ""),
uid=str(account.uid or ""),
nickname=str(account.nickname or ""),
elite_opened=account.elite_opened,
points=account.points,
gold_balance=account.gold_balance,
points_expire_at=account.points_expire_at,
)
def recommend_accounts(
db: Session,
current: User,
@@ -659,9 +626,11 @@ def recommend_accounts(
scan_limit: int | None = None,
client_factory: Callable[[Account], Any] | None = None,
) -> dict[str, Any]:
"""推荐可绑定/可换绑账号;只读探测,不创建租约。"""
"""从本地账号与能力投影推荐账号,不访问斗鱼官网。"""
_assert_account_replace_permission(current)
_assert_account_replaceable(order)
# 保留参数兼容旧调用;实时校验统一放到“使用此账号”的 set_account()。
del client_factory
name, cid, points = _resolve_gift(
db,
@@ -678,9 +647,10 @@ def recommend_accounts(
1,
min(
int(scan_limit or ACCOUNT_RECOMMEND_DEFAULT_SCAN_LIMIT),
ACCOUNT_RECOMMEND_CONCURRENCY,
100,
),
)
now = _now()
candidates_by_id: dict[int, Account] = {}
if cid:
for account in capability_candidate_accounts(
@@ -691,21 +661,44 @@ def recommend_accounts(
scope="elite",
):
candidates_by_id[int(account.id)] = account
for account in live_candidate_accounts(
db,
limit=effective_scan_limit,
required_points=required,
commodity_id=cid,
prefer_unbound=True,
empty_only=not include_rebindable,
):
candidates_by_id.setdefault(int(account.id), account)
if not candidates_by_id:
refresh_seeds = live_candidate_accounts(
db,
limit=effective_scan_limit,
required_points=required,
commodity_id=cid,
prefer_unbound=True,
empty_only=not include_rebindable,
)
for account in refresh_seeds:
enqueue_account_work(
db,
account_id=int(account.id),
work_type=WORK_STOREHOME_SYNC,
priority=20,
due_at=now,
reason=f"外部协作单推荐缺少商品能力: {cid}",
payload={"commodity_id": cid, "order_id": int(order.id)},
)
if refresh_seeds:
db.commit()
else:
for account in live_candidate_accounts(
db,
limit=effective_scan_limit,
required_points=required,
commodity_id="",
prefer_unbound=True,
empty_only=not include_rebindable,
):
candidates_by_id.setdefault(int(account.id), account)
candidates = [
account
for account in candidates_by_id.values()
if (not order.account_id or int(account.id) != int(order.account_id))
and (include_rebindable or account.role_bind_status == "unbound")
and account.ck_check_status == "valid"
]
candidates.sort(
key=lambda account: (
@@ -717,109 +710,23 @@ def recommend_accounts(
)
candidates = candidates[:effective_scan_limit]
config = resolve_config(db)
config_info = config_mapping(
{
"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 ""),
}
)
output: list[dict[str, Any]] = []
scanned = 0
result_limit = max(1, min(int(limit), 10))
def inspect_candidate(account: Account) -> tuple[Account, dict[str, Any]] | None:
try:
active_client = (
client_factory(account)
if client_factory
else activity_client(
str(account.cookie or ""),
logger_callback=lambda message: logger.debug(
"[douyu-collab] recommend account={} {}",
account.id,
message,
),
)
)
probe = probe_account(
account,
config_info,
client=active_client,
session_checker=(
None if client_factory is not None else check_douyu_cookie
),
with_elite=True,
with_eligibility=False,
with_limited_goods=bool(cid),
with_gold=False,
with_goods=False,
with_elite_role=True,
use_cache=client_factory is None,
)
return account, probe
except Exception as exc: # noqa: BLE001 - 单账号失败继续扫描
logger.info(
"[douyu-collab] 推荐账号跳过 account_id={} error={}",
account.id,
exc,
)
return None
def accept_candidate(account: Account, probe: dict[str, Any]) -> None:
session = probe.get("session") or {}
if str(session.get("status") or "") != SESSION_VALID:
return
role = (probe.get("roles") or {}).get("elite") or {}
role_status = str(role.get("status") or ROLE_UNKNOWN)
bind_info = (
role.get("bind_info") if isinstance(role.get("bind_info"), dict) else None
)
for account in candidates:
role_status = str(account.role_bind_status or ROLE_UNKNOWN)
if role_status == ROLE_UNBOUND:
match_type = "empty"
match_label = "未绑定"
elif role_status == ROLE_BOUND and can_change_role(bind_info):
elif role_status == ROLE_BOUND:
if not include_rebindable:
return
continue
match_type = "rebind"
match_label = "可换绑"
else:
return
eligibility = probe.get("eligibility") or {}
limited_ids = {
str(item)
for item in eligibility.get("limited_ids") or []
if str(item)
}
if cid and cid in limited_ids:
return
if cid:
assessments = classify_goods_items(
[
item
for item in eligibility.get("storehome_goods") or []
if isinstance(item, dict)
]
)
assessment = assessments.get(str(cid))
if assessments and (
assessment is None
or assessment.availability != AVAILABILITY_AVAILABLE
):
return
elite = probe.get("elite") or {}
live_points = _to_int(eligibility.get("points"))
if live_points is None:
live_points = _to_int(elite.get("manual_score"))
elite_opened = bool(elite.get("opened"))
ready = bool(
elite_opened and live_points is not None and live_points >= required
)
continue
elite_opened = account.elite_opened is True
live_points = _to_int(account.points)
ready = bool(elite_opened and live_points is not None and live_points >= required)
reasons = [
"未绑定角色,可直接绑定"
if match_type == "empty"
@@ -829,24 +736,19 @@ def recommend_accounts(
reasons.append("精英宝典未开通")
if live_points is None or live_points < required:
reasons.append(f"积分不足({live_points or 0}/{required})")
identity = probe.get("identity") or {}
output.append(
{
"account_id": int(account.id),
# 后续“使用此账号”会按内部 username 反查,不能用接口返回的展示昵称。
# 后续“使用此账号”按内部 username 反查,不能用展示昵称。
"account_username": str(account.username or ""),
"account_uid": str(identity.get("uid") or account.uid or ""),
"account_uid": str(account.uid or ""),
"account_nickname": str(
identity.get("nickname")
or account.nickname
or account.username
or ""
account.nickname or account.username or ""
),
"ck_status": CK_VALID,
"role_status": role_status,
"bind_game_role": str(role.get("role_name") or ""),
"role_change_available_at": role_change_available_at(bind_info),
"bind_game_role": str(account.game_name or ""),
"role_change_available_at": account.role_change_available_at,
"points": live_points,
"elite_opened": elite_opened,
"match_type": match_type,
@@ -855,38 +757,8 @@ def recommend_accounts(
"reasons": reasons,
}
)
snapshots = [_recommendation_account_snapshot(account) for account in candidates]
if snapshots:
executor = ThreadPoolExecutor(
max_workers=min(ACCOUNT_RECOMMEND_CONCURRENCY, len(snapshots))
)
futures = {
executor.submit(inspect_candidate, account): account
for account in snapshots
}
scanned = len(futures)
try:
for future in as_completed(
futures,
timeout=ACCOUNT_RECOMMEND_TIMEOUT_SECONDS,
):
result = future.result()
if result is not None:
accept_candidate(*result)
if len(output) >= result_limit:
break
except FutureTimeoutError:
logger.warning(
"[douyu-collab] 推荐账号实时校验超时,已返回当前结果 scanned={} "
"timeout={}s",
scanned,
ACCOUNT_RECOMMEND_TIMEOUT_SECONDS,
)
finally:
for future in futures:
future.cancel()
executor.shutdown(wait=False, cancel_futures=True)
if len(output) >= result_limit:
break
output.sort(
key=lambda item: (
@@ -898,9 +770,13 @@ def recommend_accounts(
)
selected = output[: max(1, min(int(limit), 10))]
message = (
f"找到 {len(selected)} 个可用账号,未绑定账号优先"
f"从本地能力池找到 {len(selected)} 个可用账号,未绑定账号优先"
if selected
else "当前没有找到未绑定或已过换绑冷却的可用账号"
else (
f"本地暂无 {cid} 的新鲜商品能力,已加入后台刷新队列"
if cid
else "本地暂未找到未绑定或已过换绑冷却的可用账号"
)
)
if not include_rebindable:
message += ";当前仅搜索未绑定账号"
@@ -910,7 +786,7 @@ def recommend_accounts(
"commodity_id": cid,
"required_points": points,
"include_rebindable": bool(include_rebindable),
"scanned": scanned,
"scanned": len(candidates),
"candidates": selected,
"message": message,
}
@@ -2771,32 +2647,21 @@ def _load_exchange_records_for_orders(
raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found")
config = resolve_config(db)
active_client = client or _client_for_account(account)
cutoffs = [
item.scripted_at - timedelta(seconds=ACTIVITY_RECORD_TIME_SKEW_SECONDS)
for item in orders
if item.scripted_at is not None
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,
)
return [
dict(record)
for record in (result.get("records") or {}).get("elite", [])
if isinstance(record, dict)
]
not_before = min(cutoffs) if cutoffs else None
records: list[dict[str, Any]] = []
for page in range(ACTIVITY_RECORD_MAX_PAGES):
page_records = query_exchange_records(
active_client,
manual_id=str(config.manual_id or ""),
limit=ACTIVITY_RECORD_FETCH_LIMIT,
offset=page * ACTIVITY_RECORD_FETCH_LIMIT,
)
records.extend(page_records)
if len(page_records) < ACTIVITY_RECORD_FETCH_LIMIT:
break
if not_before is not None:
page_times = [
record_time
for record in page_records
if (record_time := _exchange_record_time(record)) is not None
]
if page_times and max(page_times) < not_before:
break
return records
def query_activity(