"""斗鱼账号平台运行状态与覆盖率快照。""" from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import Any from sqlalchemy import case, func from sqlalchemy.orm import Session from ..models import ( Account, AccountCommodityState, AccountSyncState, AccountWorkItem, ) from .account_capability_service import AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED from .account_supply_service import evaluate_supply_targets def account_platform_status( db: Session, *, now: datetime | None = None, ) -> dict[str, Any]: moment = now or datetime.now(UTC) in_24h = moment + timedelta(hours=24) in_72h = moment + timedelta(hours=72) account_counts = dict( db.query(Account.ck_check_status, func.count(Account.id)) .group_by(Account.ck_check_status) .all() ) total_accounts = int(db.query(func.count(Account.id)).scalar() or 0) cookie_accounts = int( db.query(func.count(Account.id)) .filter(Account.cookie.isnot(None), Account.cookie != "") .scalar() or 0 ) expiring_24h = int( db.query(func.count(Account.id)) .filter( Account.ck_check_status == "valid", Account.ck_expected_expires_at.isnot(None), Account.ck_expected_expires_at > moment, Account.ck_expected_expires_at <= in_24h, ) .scalar() or 0 ) expiring_72h = int( db.query(func.count(Account.id)) .filter( Account.ck_check_status == "valid", Account.ck_expected_expires_at.isnot(None), Account.ck_expected_expires_at > moment, Account.ck_expected_expires_at <= in_72h, ) .scalar() or 0 ) predicted_expired = int( db.query(func.count(Account.id)) .filter( Account.ck_check_status == "valid", Account.ck_expected_expires_at.isnot(None), Account.ck_expected_expires_at <= moment, ) .scalar() or 0 ) queue_rows = ( db.query( AccountWorkItem.work_type, AccountWorkItem.status, func.count(AccountWorkItem.id), func.min(AccountWorkItem.due_at), ) .group_by(AccountWorkItem.work_type, AccountWorkItem.status) .all() ) work_queue: dict[str, dict[str, Any]] = {} for work_type, status, count, oldest_due in queue_rows: bucket = work_queue.setdefault(str(work_type), {}) bucket[str(status)] = int(count or 0) if status == "pending": bucket["oldest_pending_due_at"] = oldest_due sync_rows = ( db.query( AccountSyncState.domain, AccountSyncState.status, func.count(AccountSyncState.id), ) .group_by(AccountSyncState.domain, AccountSyncState.status) .all() ) sync_domains: dict[str, dict[str, Any]] = {} for domain, status, count in sync_rows: bucket = sync_domains.setdefault(str(domain), {}) bucket[str(status)] = int(count or 0) fresh_rows = ( db.query(AccountSyncState.domain, func.count(AccountSyncState.id)) .filter( AccountSyncState.status == "success", AccountSyncState.valid_until.isnot(None), AccountSyncState.valid_until > moment, ) .group_by(AccountSyncState.domain) .all() ) for domain, count in fresh_rows: sync_domains.setdefault(str(domain), {})["fresh"] = int(count or 0) commodity_rows = ( db.query( AccountCommodityState.availability, func.count(AccountCommodityState.id), func.sum( case( ( AccountCommodityState.valid_until > moment, 1, ), else_=0, ) ), ) .filter(AccountCommodityState.platform == "douyu") .group_by(AccountCommodityState.availability) .all() ) commodities = { str(availability): { "total": int(total or 0), "fresh": int(fresh or 0), } for availability, total, fresh in commodity_rows } fresh_available = int(commodities.get(AVAILABILITY_AVAILABLE, {}).get("fresh", 0)) fresh_limited = int(commodities.get(AVAILABILITY_LIMITED, {}).get("fresh", 0)) inventories = evaluate_supply_targets(db, now=moment) supply_targets: list[dict[str, Any]] = [] alerts: list[dict[str, Any]] = [] for item in inventories: shortage = max( item.covered_shortage, item.available_shortage, item.allocatable_shortage, ) supply_targets.append( { "target_id": item.target_id, "scope": item.scope, "commodity_id": item.commodity_id, "value_class": item.value_class, "target_covered": item.target_covered, "target_available": item.target_available, "target_allocatable": item.target_allocatable, "safety_buffer": item.safety_buffer, "covered": item.covered, "available": item.available, "allocatable": item.allocatable, "covered_shortage": item.covered_shortage, "available_shortage": item.available_shortage, "allocatable_shortage": item.allocatable_shortage, "needs_replenishment": item.needs_replenishment, } ) if not item.needs_replenishment: continue critical = ( (item.target_available > 0 and item.available <= 0) or (item.target_allocatable > 0 and item.allocatable <= 0) ) alerts.append( { "code": "supply_shortage", "severity": "critical" if critical else "warning", "scope": item.scope, "commodity_id": item.commodity_id, "value_class": item.value_class, "shortage": shortage, "message": ( f"{item.scope}/{item.commodity_id or 'all'}/" f"{item.value_class} 库存短缺 {shortage}" ), } ) if not inventories: alerts.append( { "code": "supply_targets_missing", "severity": "warning", "message": "尚未配置启用的账号供给目标", } ) if expiring_24h: alerts.append( { "code": "ck_expiring_24h", "severity": "warning", "count": expiring_24h, "message": f"未来 24 小时预计有 {expiring_24h} 个 CK 到期", } ) overdue_work = int( db.query(func.count(AccountWorkItem.id)) .filter( AccountWorkItem.status == "pending", AccountWorkItem.due_at < moment, ) .scalar() or 0 ) if overdue_work: alerts.append( { "code": "account_work_overdue", "severity": "warning", "count": overdue_work, "message": f"账号内部工作队列有 {overdue_work} 项待处理已过期", } ) return { "checked_at": moment, "accounts": { "total": total_accounts, "with_cookie": cookie_accounts, "ck_valid": int(account_counts.get("valid", 0)), "ck_invalid": int(account_counts.get("invalid", 0)), "ck_error": int(account_counts.get("error", 0)), "ck_unchecked": int(account_counts.get("", 0) or 0), "ck_expiring_24h": expiring_24h, "ck_expiring_72h": expiring_72h, "ck_predicted_expired": predicted_expired, }, "work_queue": work_queue, "sync_domains": sync_domains, "commodities": { "by_availability": commodities, "fresh_available": fresh_available, "fresh_limited": fresh_limited, }, "supply_targets": supply_targets, "alerts": alerts, } __all__ = ["account_platform_status"]