Files
live-hub-py/web/backend/services/automation/jobs/account_capability_refresh.py
T

112 lines
3.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""按直播履约需求刷新账号商品能力。
全量资料补全仍由 ``account_overview_refresh`` 负责;本作业只处理“有 pending
任务、但对应商品能力快照已经过期”的账号,避免为了秒匹配把两万多个账号
无条件轮询一遍。
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import exists, or_, select
from sqlalchemy.orm import Session
from ....models import (
Account,
AccountCommodityState,
AccountLease,
AutomationJob,
PlatformFulfillmentTask,
)
from ...account_lifecycle import MANUAL_STATES
from ...douyu_service import cookie_operable_filter
from .account_overview_refresh import run_refresh_for_accounts
JOB_KEY = "account_capability_refresh"
def _base_query(db: Session, now: datetime):
pending_commodities = (
select(PlatformFulfillmentTask.commodity_id)
.where(
PlatformFulfillmentTask.execution_status == "ready",
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.commodity_id != "",
)
.distinct()
)
stale_demand_state = exists(
select(AccountCommodityState.id).where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == "elite",
AccountCommodityState.commodity_id.in_(pending_commodities),
or_(
AccountCommodityState.valid_until.is_(None),
AccountCommodityState.valid_until <= now,
AccountCommodityState.next_check_at.is_(None),
AccountCommodityState.next_check_at <= now,
),
)
)
active_lease = exists(
select(AccountLease.id).where(
AccountLease.active_account_id == Account.id,
)
)
return db.query(Account).filter(
cookie_operable_filter(),
Account.auto_managed.is_(True),
Account.status.notin_(MANUAL_STATES),
Account.ck_check_status == "valid",
stale_demand_state,
~active_lease,
)
def build_select_query(
db: Session,
job: AutomationJob,
now: datetime | None = None,
):
moment = now or datetime.now(UTC)
batch = max(1, int(job.batch_size or 100))
return (
_base_query(db, moment)
.order_by(
Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(),
Account.id.asc(),
)
.limit(batch)
)
def run_account_capability_refresh(
db: Session,
job: AutomationJob,
) -> dict[str, Any]:
now = datetime.now(UTC)
accounts = build_select_query(db, job, now).all()
return run_refresh_for_accounts(
db,
job,
accounts,
now=now,
# 精确剩余量要完整评估 accounts × commodity EXISTS,生产实测单次约
# 1.3 秒、扫描 38 万行;它只用于展示,直接省略,避免每轮制造慢查询。
remaining_count=None,
source="capability_demand_refresh",
log_label="capability",
empty_message="当前履约商品没有到期待刷新的账号能力",
)
__all__ = [
"JOB_KEY",
"build_select_query",
"run_account_capability_refresh",
]