"""斗鱼账号供给库存、目标缺口和定向补货入队。""" from __future__ import annotations import os from dataclasses import dataclass from datetime import UTC, datetime, timedelta from sqlalchemy import and_, case, func, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from ..models import ( Account, AccountCommodityState, AccountSupplySnapshot, AccountSupplyTarget, AccountSyncState, ) from .account_query_filters import ( active_collab_order_exists, active_lease_exists, assigned_to_pool_filter, automatable_account_filter, cookie_present_filter, fresh_eligible_state_filter, role_change_ready_filter, valid_ck_filter, ) from .account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC from .account_value import is_high_value_expr from .account_work_queue import ( SUPPLY_REASON_PREFIX, active_account_work_count, active_account_work_exists, enqueue_account_work, ) VALUE_HIGH = "high_value" VALUE_ORDINARY = "ordinary" VALID_VALUES = frozenset({VALUE_HIGH, VALUE_ORDINARY}) DEFAULT_SUPPLY_TARGETS = ( { "scope": "elite", "value_class": VALUE_HIGH, # 2026-11-22:旧 30/20/10/3 只适合功能验证,无法覆盖当前十余客服、 # 每小时 200+ 次领取峰值和 24 小时约 220 个 CK 流失。默认改为生产基线。 "target_covered": 2000, "target_available": 300, "target_allocatable": 200, "safety_buffer": 60, }, { "scope": "elite", "value_class": VALUE_ORDINARY, "target_covered": 1800, "target_available": 200, "target_allocatable": 150, "safety_buffer": 60, }, ) DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS = 15 * 60 @dataclass(frozen=True) class SupplyInventory: target_id: int scope: str commodity_id: str value_class: str covered: int available: int allocatable: int target_covered: int target_available: int target_allocatable: int safety_buffer: int covered_shortage: int available_shortage: int allocatable_shortage: int @property def needs_replenishment(self) -> bool: return bool( self.covered_shortage or self.available_shortage or self.allocatable_shortage ) @dataclass(frozen=True) class SupplyReplenishmentResult: targets: int queued: int shortages: int refreshable_shortages: int = 0 capacity_shortages: int = 0 pending_sync: int = 0 pending_supply: int = 0 total_headroom: int = 0 supply_headroom: int = 0 total_cap: int = 0 supply_cap: int = 0 def _value_filter(value_class: str, *, now: datetime): high_value = is_high_value_expr(now=now) if value_class == VALUE_HIGH: return high_value if value_class == VALUE_ORDINARY: return ~high_value raise ValueError(f"不支持的账号价值分类: {value_class}") def _base_account_filter(): """供给池的账号准入:有 CK 且 CK 判定有效即可用。 不再要求 ``ck_checked_at`` 在 24 小时内。CK 的“新鲜度”只是巡检优先级, 不是可用性门槛:有效 CK 即使一天前检测的,也可以先拿去用;真的失效了 由同步/登录失败把它打回 invalid,再进入重登或首次登录队列。 """ return and_( cookie_present_filter(), valid_ck_filter(), automatable_account_filter(), ) def _base_account_query( db: Session, *, now: datetime, value_class: str, ): return ( db.query(Account) .filter(_base_account_filter()) .filter(_value_filter(value_class, now=now)) ) def _allocatable_filter(now: datetime): return and_( ~active_lease_exists(), ~active_collab_order_exists(), assigned_to_pool_filter(), role_change_ready_filter(now), ) def _fresh_eligible_filter(now: datetime): return fresh_eligible_state_filter(now, allow_before_open=True) def _commodity_query( db: Session, *, now: datetime, target: AccountSupplyTarget, ): query = ( _base_account_query( db, now=now, value_class=target.value_class, ) .join( AccountCommodityState, AccountCommodityState.account_id == Account.id, ) .filter( AccountCommodityState.platform == target.platform, AccountCommodityState.scope == target.scope, AccountCommodityState.commodity_id == target.commodity_id, AccountCommodityState.observed_at.isnot(None), ) ) return query def _global_state_exists_for(*, platform: str, scope: str): return ( select(AccountCommodityState.id) .where( AccountCommodityState.account_id == Account.id, AccountCommodityState.platform == platform, AccountCommodityState.scope == scope, AccountCommodityState.observed_at.isnot(None), ) .exists() ) def _global_inventory_totals( db: Session, *, platform: str, scope: str, now: datetime, ) -> dict[str, tuple[int, int, int]]: """一次算出某作用域下高价值/普通的覆盖、可兑换和可分配数量。 全局目标不指定 commodity_id,因此不能用 ``ix_account_commodity_match`` 的 commodity_id 前缀。固定拆成两条 SQL: 1. accounts + EXISTS:计算 covered; 2. account_commodity_states JOIN accounts:同时计算 available/allocatable。 第二条走 ``ix_account_commodity_global_available``,避免先物化全部商品状态。 """ value_class = case( (is_high_value_expr(now=now), VALUE_HIGH), else_=VALUE_ORDINARY, ) base_filter = _base_account_filter() covered_rows = ( db.query(value_class, func.count(Account.id)) .select_from(Account) .filter( base_filter, _global_state_exists_for(platform=platform, scope=scope), ) .group_by(value_class) .all() ) totals = { VALUE_HIGH: [0, 0, 0], VALUE_ORDINARY: [0, 0, 0], } for class_name, covered in covered_rows: totals[str(class_name)][0] = int(covered or 0) allocatable_account = case( (_allocatable_filter(now), Account.id), else_=None, ) available_rows = ( db.query( value_class, func.count(func.distinct(Account.id)), func.count(func.distinct(allocatable_account)), ) .select_from(Account) .join( AccountCommodityState, AccountCommodityState.account_id == Account.id, ) .filter( base_filter, AccountCommodityState.platform == platform, AccountCommodityState.scope == scope, _fresh_eligible_filter(now), ) .group_by(value_class) .all() ) for class_name, available, allocatable in available_rows: bucket = totals[str(class_name)] bucket[1] = int(available or 0) bucket[2] = int(allocatable or 0) return { class_name: (values[0], values[1], values[2]) for class_name, values in totals.items() } def _inventory_from_counts( target: AccountSupplyTarget, *, covered: int, available: int, allocatable: int, ) -> SupplyInventory: return SupplyInventory( target_id=int(target.id), scope=target.scope, commodity_id=target.commodity_id, value_class=target.value_class, covered=covered, available=available, allocatable=allocatable, target_covered=int(target.target_covered or 0), target_available=int(target.target_available or 0), target_allocatable=int(target.target_allocatable or 0), safety_buffer=int(target.safety_buffer or 0), covered_shortage=max( 0, int(target.target_covered or 0) + int(target.safety_buffer or 0) - covered, ), available_shortage=max( 0, int(target.target_available or 0) + int(target.safety_buffer or 0) - available, ), allocatable_shortage=max( 0, int(target.target_allocatable or 0) + int(target.safety_buffer or 0) - allocatable, ), ) def evaluate_supply_target( db: Session, target: AccountSupplyTarget, *, now: datetime | None = None, ) -> SupplyInventory: """计算一条供给目标的 covered / available / allocatable 库存。""" moment = now or datetime.now(UTC) if target.value_class not in VALID_VALUES: raise ValueError(f"不支持的账号价值分类: {target.value_class}") if target.commodity_id: base = _commodity_query(db, now=moment, target=target) covered = base.count() available_query = base.filter(_fresh_eligible_filter(moment)) available = available_query.count() allocatable = available_query.filter(_allocatable_filter(moment)).count() else: totals = _global_inventory_totals( db, platform=target.platform, scope=target.scope, now=moment, ) covered, available, allocatable = totals[target.value_class] return _inventory_from_counts( target, covered=covered, available=available, allocatable=allocatable, ) def evaluate_supply_targets( db: Session, *, now: datetime | None = None, ) -> list[SupplyInventory]: moment = now or datetime.now(UTC) targets = ( db.query(AccountSupplyTarget) .filter(AccountSupplyTarget.enabled.is_(True)) .order_by( AccountSupplyTarget.platform.asc(), AccountSupplyTarget.scope.asc(), AccountSupplyTarget.value_class.asc(), AccountSupplyTarget.commodity_id.asc(), ) .all() ) global_totals: dict[tuple[str, str], dict[str, tuple[int, int, int]]] = {} inventories: list[SupplyInventory] = [] for target in targets: if target.commodity_id: inventories.append(evaluate_supply_target(db, target, now=moment)) continue key = (target.platform, target.scope) if key not in global_totals: global_totals[key] = _global_inventory_totals( db, platform=target.platform, scope=target.scope, now=moment, ) covered, available, allocatable = global_totals[key][target.value_class] inventories.append( _inventory_from_counts( target, covered=covered, available=available, allocatable=allocatable, ) ) return inventories def _enabled_supply_targets(db: Session) -> list[AccountSupplyTarget]: return ( db.query(AccountSupplyTarget) .filter(AccountSupplyTarget.enabled.is_(True)) .order_by( AccountSupplyTarget.platform.asc(), AccountSupplyTarget.scope.asc(), AccountSupplyTarget.value_class.asc(), AccountSupplyTarget.commodity_id.asc(), ) .all() ) def supply_snapshot_max_age_seconds() -> int: raw = os.getenv( "ACCOUNT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS", str(DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS), ) try: return max(30, int(raw)) except ValueError: return DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS def refresh_supply_snapshots( db: Session, *, now: datetime | None = None, ) -> list[SupplyInventory]: """重算并持久化供给快照;只由后台作业或明确的回源路径调用。""" moment = now or datetime.now(UTC) inventories = evaluate_supply_targets(db, now=moment) existing = { int(row.target_id): row for row in db.query(AccountSupplySnapshot) .filter( AccountSupplySnapshot.target_id.in_( [item.target_id for item in inventories] ) ) .all() } if inventories else {} for inventory in inventories: row = existing.get(inventory.target_id) if row is None: row = AccountSupplySnapshot( target_id=inventory.target_id, covered=inventory.covered, available=inventory.available, allocatable=inventory.allocatable, checked_at=moment, ) try: with db.begin_nested(): db.add(row) db.flush() except IntegrityError: row = ( db.query(AccountSupplySnapshot) .filter( AccountSupplySnapshot.target_id == inventory.target_id ) .one() ) row.covered = inventory.covered row.available = inventory.available row.allocatable = inventory.allocatable row.checked_at = moment row.updated_at = moment if inventories: db.commit() return inventories def load_supply_snapshot_inventories( db: Session, *, now: datetime | None = None, refresh_if_stale: bool = True, ) -> list[SupplyInventory]: """优先读快照;缺失或超过有效期时回源一次并刷新快照。""" moment = now or datetime.now(UTC) targets = _enabled_supply_targets(db) if not targets: return [] snapshots = { int(row.target_id): row for row in db.query(AccountSupplySnapshot) .filter( AccountSupplySnapshot.target_id.in_( [int(target.id) for target in targets] ) ) .all() } fresh_after = moment - timedelta(seconds=supply_snapshot_max_age_seconds()) if all( int(target.id) in snapshots and snapshots[int(target.id)].checked_at >= fresh_after for target in targets ): return [ _inventory_from_counts( target, covered=int(snapshots[int(target.id)].covered or 0), available=int(snapshots[int(target.id)].available or 0), allocatable=int(snapshots[int(target.id)].allocatable or 0), ) for target in targets ] if refresh_if_stale: return refresh_supply_snapshots(db, now=moment) return evaluate_supply_targets(db, now=moment) def upsert_supply_target( db: Session, *, platform: str = "douyu", scope: str, commodity_id: str, value_class: str, target_covered: int, target_available: int, target_allocatable: int, safety_buffer: int, enabled: bool, updated_by: int | None, ) -> AccountSupplyTarget: """新增或更新一条供给目标。""" if value_class not in VALID_VALUES: raise ValueError(f"不支持的账号价值分类: {value_class}") for name, value in ( ("target_covered", target_covered), ("target_available", target_available), ("target_allocatable", target_allocatable), ("safety_buffer", safety_buffer), ): if int(value) < 0: raise ValueError(f"{name} 不能为负数") target = ( db.query(AccountSupplyTarget) .filter( AccountSupplyTarget.platform == platform, AccountSupplyTarget.scope == scope, AccountSupplyTarget.commodity_id == commodity_id, AccountSupplyTarget.value_class == value_class, ) .first() ) if target is None: target = AccountSupplyTarget( platform=platform, scope=scope, commodity_id=commodity_id, value_class=value_class, ) db.add(target) target.target_covered = int(target_covered) target.target_available = int(target_available) target.target_allocatable = int(target_allocatable) target.safety_buffer = int(safety_buffer) target.enabled = bool(enabled) target.updated_by = updated_by target.updated_at = datetime.now(UTC) try: with db.begin_nested(): db.flush() except IntegrityError: target = ( db.query(AccountSupplyTarget) .filter( AccountSupplyTarget.platform == platform, AccountSupplyTarget.scope == scope, AccountSupplyTarget.commodity_id == commodity_id, AccountSupplyTarget.value_class == value_class, ) .one() ) db.commit() return target def ensure_default_supply_targets(db: Session) -> int: """Bootstrap conservative supply targets when none have ever been configured.""" enabled = os.getenv("DOUYU_DEFAULT_SUPPLY_TARGETS_ENABLED", "true").strip().lower() if enabled in {"0", "false", "no", "off"}: return 0 if db.query(AccountSupplyTarget.id).first() is not None: return 0 created = 0 for spec in DEFAULT_SUPPLY_TARGETS: target = AccountSupplyTarget( platform="douyu", scope=str(spec["scope"]), commodity_id="", value_class=str(spec["value_class"]), target_covered=int(spec["target_covered"]), target_available=int(spec["target_available"]), target_allocatable=int(spec["target_allocatable"]), safety_buffer=int(spec["safety_buffer"]), enabled=True, ) db.add(target) created += 1 try: db.commit() except IntegrityError: db.rollback() return 0 return created def update_supply_target( db: Session, target: AccountSupplyTarget, *, target_covered: int, target_available: int, target_allocatable: int, safety_buffer: int, enabled: bool, updated_by: int | None, ) -> AccountSupplyTarget: return upsert_supply_target( db, platform=target.platform, scope=target.scope, commodity_id=target.commodity_id, value_class=target.value_class, target_covered=target_covered, target_available=target_available, target_allocatable=target_allocatable, safety_buffer=safety_buffer, enabled=enabled, updated_by=updated_by, ) def _sync_candidate_query( db: Session, *, target: AccountSupplyTarget, now: datetime, ): query = _base_account_query( db, now=now, value_class=target.value_class, ) if target.commodity_id: state_exists = ( select(AccountCommodityState.id) .where( AccountCommodityState.account_id == Account.id, AccountCommodityState.platform == target.platform, AccountCommodityState.scope == target.scope, AccountCommodityState.commodity_id == target.commodity_id, AccountCommodityState.valid_until.isnot(None), AccountCommodityState.valid_until > now, ) .exists() ) else: state_exists = ( select(AccountSyncState.id) .where( AccountSyncState.account_id == Account.id, AccountSyncState.platform == target.platform, AccountSyncState.domain == "storehome", AccountSyncState.status == "success", AccountSyncState.valid_until.isnot(None), AccountSyncState.valid_until > now, ) .exists() ) return ( query.filter( ~state_exists, ~active_account_work_exists(work_type=WORK_STOREHOME_SYNC), assigned_to_pool_filter(), ~active_lease_exists(), ~active_collab_order_exists(), role_change_ready_filter(now), ) .order_by( case((Account.role_bind_status == "unbound", 0), else_=1), Account.overview_queried_at.is_(None).desc(), Account.overview_queried_at.asc(), Account.id.asc(), ) ) def _sync_total_target() -> int: """同步队列总水位;订单补货和通用供给共享的硬上限。""" try: return max(1, int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "120"))) except ValueError: return 120 def _supply_queue_target() -> int: """通用供给补货自己的保留水位,不被订单补货占用。""" try: return max(1, int(os.getenv("ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING", "50"))) except ValueError: return 50 def enqueue_supply_replenishment( db: Session, *, now: datetime | None = None, max_per_target: int = 50, ) -> SupplyReplenishmentResult: """按本地目标缺口定向入队 storehome 同步,不发起外部请求。""" moment = now or datetime.now(UTC) inventories = load_supply_snapshot_inventories(db, now=moment) total_cap = _sync_total_target() supply_cap = _supply_queue_target() total_pending = active_account_work_count( db, work_types=ACCOUNT_SYNC_WORK_TYPES, ) supply_pending = active_account_work_count( db, work_types=ACCOUNT_SYNC_WORK_TYPES, reason_prefix=SUPPLY_REASON_PREFIX, ) # 供给有自己的保留水位,同时不能突破队列总水位。 # 旧逻辑用“总 pending”去减供给的 20,订单补货一忙,供给永远排队 0。 total_headroom = max(0, total_cap - total_pending) supply_headroom = max(0, supply_cap - supply_pending) headroom = min(total_headroom, supply_headroom) queued = 0 shortages = 0 refreshable_shortages = 0 capacity_shortages = 0 for inventory in inventories: if not inventory.needs_replenishment: continue shortages += 1 # 覆盖/可兑换缺口可以靠刷新账号能力解决;只有可分配缺口 # 是租约/协作/冷却造成的,刷新能力解决不了,不能占补货队列。 missing = max( inventory.covered_shortage, inventory.available_shortage, ) if missing <= 0: capacity_shortages += 1 continue refreshable_shortages += 1 if headroom <= 0: continue target = db.get(AccountSupplyTarget, inventory.target_id) if target is None: continue limit = max(1, min(int(max_per_target), missing, headroom)) account_ids = [ int(account_id) for (account_id,) in ( _sync_candidate_query( db, target=target, now=moment, ) .with_entities(Account.id) .limit(limit) .all() ) ] for account_id in account_ids: enqueue_account_work( db, account_id=account_id, work_type=WORK_STOREHOME_SYNC, priority=35, due_at=moment, reason=( f"供给短缺: {target.scope}/{target.commodity_id or 'all'}" f"/{target.value_class}" ), ) queued += 1 headroom -= 1 if queued: db.commit() return SupplyReplenishmentResult( targets=len(inventories), queued=queued, shortages=shortages, refreshable_shortages=refreshable_shortages, capacity_shortages=capacity_shortages, pending_sync=total_pending, pending_supply=supply_pending, total_headroom=total_headroom, supply_headroom=supply_headroom, total_cap=total_cap, supply_cap=supply_cap, ) __all__ = [ "VALUE_HIGH", "VALUE_ORDINARY", "SupplyInventory", "SupplyReplenishmentResult", "enqueue_supply_replenishment", "ensure_default_supply_targets", "evaluate_supply_target", "evaluate_supply_targets", "load_supply_snapshot_inventories", "refresh_supply_snapshots", "update_supply_target", "upsert_supply_target", ]