"""能力池诊断、自动选号和租约分配。""" from __future__ import annotations import os from datetime import datetime, timedelta from typing import Any from fastapi import HTTPException from sqlalchemy import func, select from sqlalchemy.orm import Session from ...models import ( Account, AccountCommodityState, AccountEvent, AccountLease, PlatformFulfillmentTask, User, ) from ..account_capability_service import ( AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED, AVAILABILITY_NOT_OPEN, OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE, allocation_availability, ) from ..account_query_filters import ( active_collab_order_exists, active_lease_exists, assigned_to_pool_filter, automatable_account_filter, cookie_present_filter, role_change_ready_filter, valid_ck_filter, ) from ..account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC from ..account_work_queue import ( active_account_work_count, enqueue_account_work, ) from ..douyu_account_state import DouyuLiveAccountState from . import classification from .account_selector import ( AccountCandidate, CapabilityCandidate, capability_candidate_rows, capability_refresh_candidate_accounts, lease_account, ) from .common import ( DEFAULT_CAPABILITY_CANDIDATE_LIMIT, LOCAL_CACHE_MISS_RETRY_SECONDS, LOCAL_LEASE_CONFLICT_RETRY_SECONDS, LOCAL_STOCK_RETRY_SECONDS, SCOPE_ELITE, TARGET_PLATFORM, _exchange_gate, _jsonable, _now, ) from .outbox import _emit_order_site_binding_state from .repository import _load_task from .runtime import ( _append_event, _apply_task_lease_policy, _lease_duration_minutes, ) from .views import get_task_detail def _cached_capability_state( candidate: CapabilityCandidate, *, commodity_id: str, ) -> DouyuLiveAccountState: """把新鲜本地能力快照转换成统一的履约状态,不访问斗鱼官网。""" account = candidate.account state = candidate.state availability = allocation_availability( state.account_eligibility, state.offer_state, ) if availability == AVAILABILITY_AVAILABLE: reason = "" elif availability == AVAILABILITY_LIMITED: reason = "该账号已达此商品兑换上限" elif availability == AVAILABILITY_NOT_OPEN: reason = ( f"限时兑换未开始,开始于 {state.available_from.isoformat()}" if state.available_from else "活动尚未开放兑换" ) else: reason = str(state.blocking_reason or "") return DouyuLiveAccountState( account_id=int(account.id), account_name=account.nickname or account.username or f"#{account.id}", checked_at=state.observed_at or _now(), ck_verdict="valid", ck_message="本地能力快照关联账号 CK 有效", elite_opened=account.elite_opened, points=account.points, limited_ids=frozenset(), role_change_available_at=account.role_change_available_at, commodity_availability={commodity_id: availability}, commodity_blocking_reasons=({commodity_id: reason} if reason else {}), ) def _capability_availability_counts( db: Session, *, commodity_id: str, scope: str, now: datetime, ) -> dict[str, Any]: base = db.query(AccountCommodityState).filter( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == scope, AccountCommodityState.commodity_id == commodity_id, AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until > now, ) eligibility_rows = ( base.with_entities( AccountCommodityState.account_eligibility, func.count(AccountCommodityState.id), ) .group_by(AccountCommodityState.account_eligibility) .all() ) offer_rows = ( db.query( AccountCommodityState.offer_state, func.count(AccountCommodityState.id) ) .filter( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == scope, AccountCommodityState.commodity_id == commodity_id, AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until > now, ) .group_by(AccountCommodityState.offer_state) .all() ) stock_rows = ( db.query( AccountCommodityState.stock_state, func.count(AccountCommodityState.id) ) .filter( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == scope, AccountCommodityState.commodity_id == commodity_id, AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until > now, ) .group_by(AccountCommodityState.stock_state) .all() ) eligible_account_ids = ( select(AccountCommodityState.account_id) .where( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == scope, AccountCommodityState.commodity_id == commodity_id, AccountCommodityState.account_eligibility == "eligible", AccountCommodityState.offer_state.in_( (OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE) ), AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until > now, ) .distinct() ) account_base = db.query(Account).filter(Account.id.in_(eligible_account_ids)) eligible_accounts = int(account_base.count()) role_ready_accounts = int( account_base.filter(role_change_ready_filter(now)).count() ) leased_accounts = int(account_base.filter(active_lease_exists()).count()) collab_accounts = int(account_base.filter(active_collab_order_exists()).count()) allocatable_accounts = int( account_base.filter( cookie_present_filter(), valid_ck_filter(), automatable_account_filter(), assigned_to_pool_filter(), role_change_ready_filter(now), ~active_lease_exists(), ~active_collab_order_exists(), ).count() ) next_role_ready_at = ( account_base.filter( Account.role_change_available_at.isnot(None), Account.role_change_available_at > now, ) .with_entities(func.min(Account.role_change_available_at)) .scalar() ) return { **{f"eligibility:{key}": int(count or 0) for key, count in eligibility_rows}, **{f"offer:{key}": int(count or 0) for key, count in offer_rows}, **{f"stock:{key}": int(count or 0) for key, count in stock_rows}, "account:eligible": eligible_accounts, "account:roleReady": role_ready_accounts, "account:roleCooldown": max(0, eligible_accounts - role_ready_accounts), "account:leased": leased_accounts, "account:activeCollab": collab_accounts, "account:allocatable": allocatable_accounts, "account:nextRoleReadyAt": _jsonable(next_role_ready_at), } def _local_allocation_retry_at( db: Session, *, task: PlatformFulfillmentTask, now: datetime, availability_counts: dict[str, int], lease_conflict: bool, ) -> tuple[datetime, str]: """按本地状态决定下一轮时间,避免永久无库存任务每 45 秒占槽。""" if lease_conflict: return ( now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), "lease_conflict", ) next_open_at = ( db.query(func.min(AccountCommodityState.available_from)) .filter( AccountCommodityState.platform == TARGET_PLATFORM, AccountCommodityState.scope == (task.scope or SCOPE_ELITE), AccountCommodityState.commodity_id == task.commodity_id, AccountCommodityState.offer_state == OFFER_STATE_BEFORE, AccountCommodityState.available_from.isnot(None), AccountCommodityState.available_from > now, ) .scalar() ) if next_open_at is not None: return next_open_at + timedelta(seconds=5), "commodity_not_open" if availability_counts.get(f"offer:{OFFER_STATE_BEFORE}"): return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open" has_capability_rows = any( int(value or 0) for key, value in availability_counts.items() if key.startswith(("eligibility:", "offer:", "stock:")) ) if has_capability_rows: if int(availability_counts.get("account:allocatable") or 0) > 0: return ( now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), "lease_conflict", ) if int(availability_counts.get("account:roleCooldown") or 0) > 0: return ( now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "account_role_cooldown", ) if int(availability_counts.get("account:eligible") or 0) > 0: return ( now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "account_pool_busy", ) return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "no_eligible_account" return now + timedelta( seconds=LOCAL_CACHE_MISS_RETRY_SECONDS ), "capability_cache_miss" def _seed_capability_refresh( db: Session, *, task: PlatformFulfillmentTask, now: datetime, ) -> int: """能力池不足时只入队独立同步槽,不在分配线程里请求官网。""" try: seed_limit = int( os.getenv("PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT", "20") ) except ValueError: seed_limit = 20 seed_limit = max(1, min(seed_limit, 100)) try: target_pending = max( 1, int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")), ) except ValueError: target_pending = 60 pending = active_account_work_count( db, work_types=ACCOUNT_SYNC_WORK_TYPES, ) headroom = max(0, target_pending - pending) if headroom <= 0: return 0 accounts = capability_refresh_candidate_accounts( db, commodity_ids=[task.commodity_id], scope=task.scope or SCOPE_ELITE, limit=min(seed_limit, headroom), now=now, ) for account in accounts: enqueue_account_work( db, account_id=int(account.id), work_type=WORK_STOREHOME_SYNC, priority=20, due_at=now, reason=f"履约任务 #{task.id} 缺少商品能力快照", payload={ "commodity_id": task.commodity_id, "platform_task_id": int(task.id), }, ) return len(accounts) def _allocate_task_from_capability( db: Session, *, task: PlatformFulfillmentTask, current: User, ) -> dict[str, Any]: """只用本地能力索引选号;外部资格查询留给独立同步队列。""" moment = _now() required_points = int(task.required_points or 0) try: candidate_limit = int( os.getenv( "PLATFORM_FULFILLMENT_CAPABILITY_CANDIDATE_LIMIT", str(DEFAULT_CAPABILITY_CANDIDATE_LIMIT), ) ) except ValueError: 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( db, limit=candidate_limit, required_points=required_points, commodity_id=task.commodity_id, scope=task.scope or SCOPE_ELITE, now=moment, allow_before_open=is_presale, ) recent_exchange_ids: set[int] = set() if capability_candidates: candidate_ids = [int(item.account.id) for item in capability_candidates] since = moment - timedelta(days=365) recent_exchange_ids = { int(account_id) for (account_id,) in ( db.query(AccountEvent.account_id) .filter( AccountEvent.account_id.in_(candidate_ids), AccountEvent.event_type == "exchange", AccountEvent.subject_key == task.commodity_id, AccountEvent.occurred_at >= since, ) .distinct() .all() ) } diagnostics: list[dict[str, Any]] = [] qualified: list[tuple[CapabilityCandidate, DouyuLiveAccountState]] = [] for candidate in capability_candidates: account_id = int(candidate.account.id) if account_id in recent_exchange_ids: diagnostics.append( { "accountId": account_id, "accountName": candidate.account.nickname or candidate.account.username, "reasons": ["365 天内已有该商品兑换事件"], "source": "capability", } ) continue qualified.append( ( candidate, _cached_capability_state( candidate, commodity_id=task.commodity_id, ), ) ) qualified.sort( key=lambda item: ( item[1].readiness_rank(required_points=required_points), int(item[1].points or 0), int(item[0].account.id), ) ) selected: CapabilityCandidate | None = None selected_state: DouyuLiveAccountState | None = None lease = None lease_duration_minutes = _lease_duration_minutes(db) for candidate, cached_state in qualified: account = candidate.account candidate_model = AccountCandidate( account_id=int(account.id), username=str(account.username or ""), nickname=str(account.nickname or ""), points=int(cached_state.points or 0), gold_balance=account.gold_balance, points_expire_at=account.points_expire_at, role_change_available_at=account.role_change_available_at, ) lease = lease_account( db, candidate=candidate_model, holder_user_id=current.id, task_id=task.id, commodity_id=task.commodity_id, ttl_minutes=lease_duration_minutes, commit=False, ) if lease is not None: selected = candidate selected_state = cached_state break diagnostics.append( { "accountId": int(account.id), "accountName": cached_state.account_name, "reasons": ["账号刚被其他任务占用"], "source": "capability", } ) if selected is None or selected_state is None or lease is None: availability_counts = _capability_availability_counts( db, commodity_id=task.commodity_id, scope=task.scope or SCOPE_ELITE, now=moment, ) retry_at, retry_reason = _local_allocation_retry_at( db, task=task, now=moment, availability_counts=availability_counts, lease_conflict=bool(qualified), ) refresh_queued = ( _seed_capability_refresh(db, task=task, now=moment) if retry_reason in { "capability_cache_miss", "account_role_cooldown", "account_pool_busy", } else 0 ) if retry_reason == "commodity_not_open": task.issue_code = "commodity_not_open" task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号" elif retry_reason == "capability_cache_miss": task.issue_code = "capability_cache_miss" task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新" elif retry_reason == "lease_conflict": task.issue_code = "account_lease_conflict" task.last_error = "已找到候选账号,但刚被其他任务占用" elif retry_reason == "account_role_cooldown": task.issue_code = "account_role_cooldown" task.last_error = ( "已有具备兑换资格的账号,但都处于斗鱼换绑冷却期;" "后台正在继续补充未绑定角色的可用账号" ) elif retry_reason == "account_pool_busy": task.issue_code = "account_pool_busy" task.last_error = ( "已有具备兑换资格的账号,但当前被租约或外部协作单占用;" "后台正在继续补充可用账号" ) else: task.issue_code = "no_eligible_account" task.last_error = "本地能力池暂无可用账号" task.execution_status = "ready" task.next_allocate_at = retry_at task.updated_at = moment _append_event( db, task.id, "account_allocation_failed", detail={ "candidateCount": len(capability_candidates), "matchingMode": "capability", "strategy": "local_capability", "capabilityCandidates": len(capability_candidates), "availabilityCounts": availability_counts, "retryAt": _jsonable(retry_at), "retryReason": retry_reason, "refreshQueued": refresh_queued, "diagnostics": diagnostics[:20], }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) selected_account = selected.account 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 = moment _apply_task_lease_policy(db, task, lease=lease) _append_event( db, task.id, "account_allocated", actor_type="user", actor_id=current.id, detail={ "accountId": selected_account.id, "accountName": selected_state.account_name, "points": selected_state.points, "eliteOpened": selected_state.elite_opened, "softReasons": soft_reasons, "exchangeStatus": task.exchange_status, "allocationStrategy": "local_capability", "capabilityObservedAt": _jsonable(selected.state.observed_at), "capabilityValidUntil": _jsonable(selected.state.valid_until), }, ) _emit_order_site_binding_state(db, task.id) db.commit() return get_task_detail(db, task.id) def prepare_manual_allocation( db: Session, *, task_id: int, current: User, ) -> dict[str, Any]: """在短请求内完成人工选号校验,并把任务标记为立即可领取。 真正的官网账号检测由后台 auto allocator 执行。这样 API 请求不会在多次外部 HTTP 调用期间一直持有数据库事务,也不会因为重复点击占满连接池。 """ task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") if not task.commodity_id or not task.required_points: raise HTTPException(status_code=409, detail="请先完成商品映射") 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) if task.execution_status != "ready": raise HTTPException(status_code=409, detail="只有待分配任务可以重新选号") task.next_allocate_at = _now() task.updated_at = _now() db.flush() return get_task_detail(db, task.id) def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]: task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") if not task.commodity_id or not task.required_points: raise HTTPException(status_code=409, detail="请先完成商品映射") 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) # 阶段 5:生产选号只允许读取本地能力索引。官网查询由 # account_sync_queue/商品能力补货完成,绑码与兑换前各自实时复核。 return _allocate_task_from_capability( db, task=task, current=current, )