refactor(douyu): 完成阶段5旧链路清理
This commit is contained in:
@@ -10,7 +10,6 @@ from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
from loguru import logger
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -74,11 +73,10 @@ from ..douyu_account_probe import (
|
||||
persist_probe_result,
|
||||
probe_account,
|
||||
)
|
||||
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
|
||||
from ..douyu_account_state import DouyuLiveAccountState
|
||||
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
|
||||
from ..douyu_service import (
|
||||
SUPPORTED_DOUYU_TASK_TYPES,
|
||||
douyu_config_value,
|
||||
ensure_douyu_config,
|
||||
)
|
||||
from ..external_order_source import (
|
||||
@@ -91,12 +89,9 @@ from . import classification
|
||||
from .account_selector import (
|
||||
AccountCandidate,
|
||||
CapabilityCandidate,
|
||||
capability_candidate_accounts,
|
||||
capability_candidate_rows,
|
||||
capability_refresh_candidate_accounts,
|
||||
has_recent_exchange,
|
||||
lease_account,
|
||||
live_candidate_accounts,
|
||||
release_lease,
|
||||
)
|
||||
from .order_site_notifier import enqueue_order_site_binding_state
|
||||
@@ -117,7 +112,7 @@ BINDING_QR_TTL_SECONDS = int(
|
||||
os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "1260")
|
||||
)
|
||||
AUTO_SYNC_INTERVAL_SECONDS = 900.0
|
||||
DEFAULT_LIVE_CANDIDATE_LIMIT = 20
|
||||
DEFAULT_CAPABILITY_CANDIDATE_LIMIT = 20
|
||||
LOCAL_STOCK_RETRY_SECONDS = 5 * 60
|
||||
LOCAL_CACHE_MISS_RETRY_SECONDS = 2 * 60
|
||||
LOCAL_LEASE_CONFLICT_RETRY_SECONDS = 5
|
||||
@@ -138,11 +133,6 @@ def binding_failed_lease_ttl_minutes() -> int:
|
||||
return max(1, value)
|
||||
|
||||
|
||||
def _matching_mode() -> str:
|
||||
mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower()
|
||||
return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid"
|
||||
|
||||
|
||||
def _exchange_gate(
|
||||
state: DouyuLiveAccountState,
|
||||
commodity_id: str,
|
||||
@@ -2600,7 +2590,6 @@ def _allocate_task_from_capability(
|
||||
*,
|
||||
task: PlatformFulfillmentTask,
|
||||
current: User,
|
||||
mode: str,
|
||||
) -> dict[str, Any]:
|
||||
"""只用本地能力索引选号;外部资格查询留给独立同步队列。"""
|
||||
moment = _now()
|
||||
@@ -2608,12 +2597,12 @@ def _allocate_task_from_capability(
|
||||
try:
|
||||
candidate_limit = int(
|
||||
os.getenv(
|
||||
"PLATFORM_FULFILLMENT_LIVE_CANDIDATE_LIMIT",
|
||||
str(DEFAULT_LIVE_CANDIDATE_LIMIT),
|
||||
"PLATFORM_FULFILLMENT_CAPABILITY_CANDIDATE_LIMIT",
|
||||
str(DEFAULT_CAPABILITY_CANDIDATE_LIMIT),
|
||||
)
|
||||
)
|
||||
except ValueError:
|
||||
candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT
|
||||
candidate_limit = DEFAULT_CAPABILITY_CANDIDATE_LIMIT
|
||||
candidate_limit = max(1, min(candidate_limit, 100))
|
||||
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
|
||||
capability_candidates = capability_candidate_rows(
|
||||
@@ -2770,7 +2759,7 @@ def _allocate_task_from_capability(
|
||||
"account_allocation_failed",
|
||||
detail={
|
||||
"candidateCount": len(capability_candidates),
|
||||
"matchingMode": mode,
|
||||
"matchingMode": "capability",
|
||||
"strategy": "local_capability",
|
||||
"capabilityCandidates": len(capability_candidates),
|
||||
"availabilityCounts": availability_counts,
|
||||
@@ -2874,304 +2863,17 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
|
||||
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
|
||||
if not task.commodity_id or not task.required_points:
|
||||
raise HTTPException(status_code=409, detail="请先完成商品映射")
|
||||
required_points = int(task.required_points)
|
||||
if task.account_id and task.lease_id:
|
||||
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||
if lease and lease.status == "active":
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
mode = _matching_mode()
|
||||
if mode in {"hybrid", "capability"}:
|
||||
# 2026-11-22:分配热路径只读本地能力索引。官网资格刷新已经由独立
|
||||
# account_sync_queue 执行;绑码和兑换前仍有各自的实时校验,不应让
|
||||
# 一次选号串行探测 20 个账号并阻塞其他订单。
|
||||
return _allocate_task_from_capability(
|
||||
db,
|
||||
task=task,
|
||||
current=current,
|
||||
mode=mode,
|
||||
)
|
||||
|
||||
config = ensure_douyu_config(db)
|
||||
lease_duration_minutes = _lease_duration_minutes(db)
|
||||
manual_id = str(douyu_config_value("manual_id", config.manual_id))
|
||||
rid = str(douyu_config_value("rid", config.rid))
|
||||
act_alias = str(douyu_config_value("bind_act_alias", config.bind_act_alias))
|
||||
try:
|
||||
candidate_limit = int(
|
||||
os.getenv(
|
||||
"PLATFORM_FULFILLMENT_LIVE_CANDIDATE_LIMIT",
|
||||
str(DEFAULT_LIVE_CANDIDATE_LIMIT),
|
||||
)
|
||||
)
|
||||
except ValueError:
|
||||
candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT
|
||||
candidate_limit = max(1, min(candidate_limit, 100))
|
||||
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
|
||||
capability_candidates = (
|
||||
capability_candidate_accounts(
|
||||
db,
|
||||
limit=candidate_limit,
|
||||
required_points=required_points,
|
||||
commodity_id=task.commodity_id,
|
||||
scope=task.scope or SCOPE_ELITE,
|
||||
allow_not_open=is_presale,
|
||||
)
|
||||
if mode in {"hybrid", "capability"}
|
||||
else []
|
||||
)
|
||||
capability_first = bool(capability_candidates)
|
||||
candidates = capability_candidates
|
||||
if not candidates and mode != "capability":
|
||||
# hybrid 模式下能力索引为空或全部过期时,保留旧逻辑兜底。
|
||||
candidates = live_candidate_accounts(
|
||||
db,
|
||||
limit=candidate_limit,
|
||||
required_points=required_points,
|
||||
commodity_id=task.commodity_id,
|
||||
)
|
||||
diagnostics: list[dict[str, Any]] = []
|
||||
qualified: list[tuple[Account, DouyuLiveAccountState]] = []
|
||||
selected: AccountCandidate | None = None
|
||||
selected_state: DouyuLiveAccountState | None = None
|
||||
lease = None
|
||||
|
||||
def inspect_candidate(
|
||||
account: Account,
|
||||
*,
|
||||
source: str,
|
||||
) -> tuple[Account, DouyuLiveAccountState] | None:
|
||||
live_state = refresh_douyu_account_state(
|
||||
db,
|
||||
account,
|
||||
manual_id=manual_id,
|
||||
rid=rid,
|
||||
act_alias=act_alias,
|
||||
)
|
||||
limited = task.commodity_id in live_state.limited_ids
|
||||
recent_exchange = has_recent_exchange(
|
||||
db,
|
||||
account_id=int(account.id),
|
||||
commodity_id=task.commodity_id,
|
||||
)
|
||||
reasons = live_state.blocking_reasons(
|
||||
commodity_id=task.commodity_id,
|
||||
allow_not_open=is_presale,
|
||||
)
|
||||
if recent_exchange:
|
||||
reasons.append("365 天内已有该商品兑换事件")
|
||||
|
||||
if live_state.ck_verdict == "valid" and not live_state.error:
|
||||
try:
|
||||
availability = live_state.commodity_availability.get(
|
||||
task.commodity_id
|
||||
)
|
||||
blocking_reason = live_state.commodity_blocking_reasons.get(
|
||||
task.commodity_id,
|
||||
"",
|
||||
)
|
||||
if limited:
|
||||
availability = AVAILABILITY_LIMITED
|
||||
blocking_reason = "该账号已达此商品兑换上限"
|
||||
elif live_state.commodity_availability and availability is None:
|
||||
availability = AVAILABILITY_NOT_OFFERED
|
||||
blocking_reason = "官方商品列表本次未返回该商品,可能已下架"
|
||||
elif availability is None:
|
||||
availability = AVAILABILITY_AVAILABLE
|
||||
record_account_commodity_state(
|
||||
db,
|
||||
account,
|
||||
commodity_id=task.commodity_id,
|
||||
availability=availability,
|
||||
blocking_reason=blocking_reason,
|
||||
raw_status="1" if limited else "0",
|
||||
observed_at=live_state.checked_at,
|
||||
source="live_check",
|
||||
scope=task.scope or SCOPE_ELITE,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - 派生索引不能阻止本次选号
|
||||
logger.warning(
|
||||
"写入选号商品能力失败 account_id={} commodity_id={}: {}",
|
||||
account.id,
|
||||
task.commodity_id,
|
||||
exc,
|
||||
)
|
||||
if reasons:
|
||||
diagnostics.append(
|
||||
{
|
||||
"accountId": int(account.id),
|
||||
"accountName": live_state.account_name,
|
||||
"ck": live_state.ck_verdict,
|
||||
"eliteOpened": live_state.elite_opened,
|
||||
"points": live_state.points,
|
||||
"reasons": reasons,
|
||||
"source": source,
|
||||
}
|
||||
)
|
||||
return None
|
||||
return account, live_state
|
||||
|
||||
def inspect_batch(
|
||||
batch: list[Account],
|
||||
*,
|
||||
source: str,
|
||||
) -> None:
|
||||
# 能力索引已按成本排序,首个确认通过即可;旧兜底最多比较 3 个。
|
||||
for account in batch:
|
||||
inspected = inspect_candidate(account, source=source)
|
||||
if inspected is None:
|
||||
continue
|
||||
qualified.append(inspected)
|
||||
if source == "capability" or len(qualified) >= 3:
|
||||
return
|
||||
|
||||
if capability_candidates:
|
||||
inspect_batch(capability_candidates, source="capability")
|
||||
elif mode != "capability":
|
||||
inspect_batch(candidates, source="live")
|
||||
|
||||
if not qualified and capability_first and mode == "hybrid":
|
||||
checked_ids = {int(account.id) for account in capability_candidates}
|
||||
fallback_candidates = [
|
||||
account
|
||||
for account in live_candidate_accounts(
|
||||
db,
|
||||
limit=candidate_limit,
|
||||
required_points=required_points,
|
||||
commodity_id=task.commodity_id,
|
||||
)
|
||||
if int(account.id) not in checked_ids
|
||||
]
|
||||
candidates = [*candidates, *fallback_candidates]
|
||||
inspect_batch(fallback_candidates, source="live_fallback")
|
||||
|
||||
# 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号,
|
||||
# 其次是只需充值、只需开通、两者都需要的账号。
|
||||
qualified.sort(
|
||||
key=lambda item: (
|
||||
item[1].readiness_rank(required_points=required_points),
|
||||
int(item[1].points or 0),
|
||||
int(item[0].id),
|
||||
)
|
||||
)
|
||||
for account, live_state in qualified:
|
||||
candidate = AccountCandidate(
|
||||
account_id=int(account.id),
|
||||
username=str(account.username or ""),
|
||||
nickname=str(account.nickname or ""),
|
||||
points=int(live_state.points or 0),
|
||||
gold_balance=account.gold_balance,
|
||||
points_expire_at=account.points_expire_at,
|
||||
role_change_available_at=live_state.role_change_available_at,
|
||||
)
|
||||
lease = lease_account(
|
||||
db,
|
||||
candidate=candidate,
|
||||
holder_user_id=current.id,
|
||||
task_id=task.id,
|
||||
commodity_id=task.commodity_id,
|
||||
ttl_minutes=lease_duration_minutes,
|
||||
)
|
||||
if lease is not None:
|
||||
selected = candidate
|
||||
selected_state = live_state
|
||||
break
|
||||
diagnostics.append(
|
||||
{
|
||||
"accountId": int(account.id),
|
||||
"accountName": live_state.account_name,
|
||||
"ck": live_state.ck_verdict,
|
||||
"eliteOpened": live_state.elite_opened,
|
||||
"points": live_state.points,
|
||||
"reasons": ["账号刚被其他任务占用"],
|
||||
"source": "capability" if capability_first else "live",
|
||||
}
|
||||
)
|
||||
if selected is None or selected_state is None or lease is None:
|
||||
task.execution_status = "ready"
|
||||
task.next_allocate_at = _now() + timedelta(seconds=45)
|
||||
task.issue_code = "no_eligible_account"
|
||||
if not candidates:
|
||||
task.last_error = (
|
||||
"商品能力池暂无可用账号"
|
||||
if mode == "capability"
|
||||
else "没有带 CK、允许自动管理且未停用的斗鱼账号"
|
||||
)
|
||||
else:
|
||||
summary = ";".join(
|
||||
f"{item['accountName']}: {', '.join(item['reasons'][:3])}"
|
||||
for item in diagnostics[:5]
|
||||
)
|
||||
task.last_error = (
|
||||
f"已实时检测 {len(diagnostics)} 个账号,当前没有可用账号"
|
||||
+ (f"。{summary}" if summary else "")
|
||||
)[:500]
|
||||
task.updated_at = _now()
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
"account_allocation_failed",
|
||||
detail={
|
||||
"candidateCount": len(candidates),
|
||||
"matchingMode": mode,
|
||||
"capabilityCandidates": len(capability_candidates),
|
||||
"diagnostics": diagnostics,
|
||||
},
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
task.account_id = selected.account_id
|
||||
task.lease_id = lease.id
|
||||
task.operator_id = current.id
|
||||
task.execution_status = "allocated"
|
||||
task.next_allocate_at = None
|
||||
task.binding_status = "not_started"
|
||||
soft_reasons = selected_state.soft_requirement_reasons(
|
||||
required_points=required_points
|
||||
)
|
||||
gate_status, gate_issue, gate_message = _exchange_gate(
|
||||
selected_state,
|
||||
task.commodity_id,
|
||||
allow_not_open=is_presale,
|
||||
)
|
||||
if gate_status:
|
||||
task.exchange_status = gate_status
|
||||
task.issue_code = gate_issue
|
||||
task.last_error = gate_message
|
||||
elif selected_state.elite_opened is not True:
|
||||
task.exchange_status = "not_opened"
|
||||
task.issue_code = "elite_not_opened"
|
||||
task.last_error = "账号尚未开通精英宝典,可开通后继续"
|
||||
elif selected_state.points is None or selected_state.points < required_points:
|
||||
task.exchange_status = "points_short"
|
||||
task.issue_code = "points_short"
|
||||
task.last_error = "账号积分不足,可充值后继续"
|
||||
else:
|
||||
task.exchange_status = "eligible"
|
||||
task.issue_code = ""
|
||||
task.last_error = ""
|
||||
task.updated_at = _now()
|
||||
_apply_task_lease_policy(db, task, lease=lease)
|
||||
_append_event(
|
||||
# 阶段 5:生产选号只允许读取本地能力索引。官网查询由
|
||||
# account_sync_queue/商品能力补货完成,绑码与兑换前各自实时复核。
|
||||
return _allocate_task_from_capability(
|
||||
db,
|
||||
task.id,
|
||||
"account_allocated",
|
||||
actor_type="user",
|
||||
actor_id=current.id,
|
||||
detail={
|
||||
"accountId": selected.account_id,
|
||||
"accountName": selected.display_name,
|
||||
"points": selected.points,
|
||||
"eliteOpened": selected_state.elite_opened,
|
||||
"softReasons": soft_reasons,
|
||||
"exchangeStatus": task.exchange_status,
|
||||
},
|
||||
task=task,
|
||||
current=current,
|
||||
)
|
||||
_emit_order_site_binding_state(db, task.id)
|
||||
db.commit()
|
||||
return get_task_detail(db, task.id)
|
||||
|
||||
|
||||
def release_task_account(
|
||||
|
||||
Reference in New Issue
Block a user