fix(douyu): 补全账号能力目录并回收失效租约
This commit is contained in:
@@ -127,8 +127,11 @@ def register_default_jobs() -> None:
|
||||
key=ACCOUNT_CAPABILITY_REFRESH_KEY,
|
||||
title="履约商品能力补充刷新",
|
||||
# 只刷新有 pending 履约需求且能力快照已过期的账号。
|
||||
# 2026-11-22:作业本身只做本地候选筛选,外部请求交给独立
|
||||
# account_sync_queue。每分钟补到有界水位,避免需求补货被通用
|
||||
# 供给作业挤占,也避免一次塞入数百条积压。
|
||||
interval_seconds=3600,
|
||||
run_interval_seconds=5 * 60,
|
||||
run_interval_seconds=60,
|
||||
batch_size=100,
|
||||
concurrency=3,
|
||||
run=run_account_capability_refresh,
|
||||
@@ -218,5 +221,6 @@ def register_default_jobs() -> None:
|
||||
batch_size=500,
|
||||
concurrency=1,
|
||||
run=run_platform_fulfillment_lease_reaper,
|
||||
default_enabled=True,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -10,34 +10,37 @@ from __future__ import annotations
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....models import (
|
||||
Account,
|
||||
AccountCommodityState,
|
||||
AutomationJob,
|
||||
PlatformFulfillmentSetting,
|
||||
PlatformFulfillmentTask,
|
||||
)
|
||||
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 ...platform_fulfillment.account_selector import (
|
||||
capability_refresh_candidate_accounts,
|
||||
)
|
||||
from ...account_sync_runner import WORK_STOREHOME_SYNC
|
||||
from ...account_work_queue import enqueue_account_work
|
||||
|
||||
JOB_KEY = "account_capability_refresh"
|
||||
|
||||
|
||||
def _base_query(db: Session, now: datetime):
|
||||
def _pending_demand_rows(
|
||||
db: Session,
|
||||
now: datetime,
|
||||
) -> list[tuple[str, int]]:
|
||||
"""返回待分配商品及订单数,按缺口大小排序。"""
|
||||
pending_commodities_query = (
|
||||
select(PlatformFulfillmentTask.commodity_id)
|
||||
select(
|
||||
PlatformFulfillmentTask.commodity_id,
|
||||
func.count(PlatformFulfillmentTask.id).label("waiting"),
|
||||
)
|
||||
.where(
|
||||
PlatformFulfillmentTask.execution_status == "ready",
|
||||
PlatformFulfillmentTask.account_id.is_(None),
|
||||
@@ -45,7 +48,6 @@ def _base_query(db: Session, now: datetime):
|
||||
PlatformFulfillmentTask.target_platform == "douyu",
|
||||
PlatformFulfillmentTask.scope == "elite",
|
||||
)
|
||||
.distinct()
|
||||
)
|
||||
match_started_at = (
|
||||
db.query(PlatformFulfillmentSetting.order_match_started_at)
|
||||
@@ -56,34 +58,59 @@ def _base_query(db: Session, now: datetime):
|
||||
pending_commodities_query = pending_commodities_query.where(
|
||||
PlatformFulfillmentTask.paid_at >= match_started_at
|
||||
)
|
||||
pending_commodities = pending_commodities_query
|
||||
# JOIN 比相关 EXISTS 更容易使用商品能力索引。当前生产账号池约 3 万,
|
||||
# 原写法会按账号逐个探测商品状态,慢查询实测扫描 40 万行。
|
||||
statement = (
|
||||
pending_commodities_query
|
||||
.group_by(PlatformFulfillmentTask.commodity_id)
|
||||
.order_by(func.count(PlatformFulfillmentTask.id).desc())
|
||||
)
|
||||
return list(db.execute(statement).all())
|
||||
|
||||
|
||||
def _queue_target_pending() -> int:
|
||||
import os
|
||||
|
||||
try:
|
||||
return max(1, int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")))
|
||||
except ValueError:
|
||||
return 60
|
||||
|
||||
|
||||
def _build_select_query(
|
||||
db: Session,
|
||||
job: AutomationJob,
|
||||
now: datetime | None = None,
|
||||
*,
|
||||
batch_limit: int | None = None,
|
||||
):
|
||||
moment = now or datetime.now(UTC)
|
||||
demand_rows = _pending_demand_rows(db, moment)
|
||||
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
|
||||
if not commodity_ids:
|
||||
return db.query(Account).filter(Account.id == -1)
|
||||
batch = max(
|
||||
1,
|
||||
min(
|
||||
int(batch_limit if batch_limit is not None else job.batch_size or 100),
|
||||
100,
|
||||
),
|
||||
)
|
||||
candidates = capability_refresh_candidate_accounts(
|
||||
db,
|
||||
commodity_ids=commodity_ids,
|
||||
scope="elite",
|
||||
limit=batch,
|
||||
now=moment,
|
||||
)
|
||||
if not candidates:
|
||||
return db.query(Account).filter(Account.id == -1)
|
||||
rank = {int(account.id): index for index, account in enumerate(candidates)}
|
||||
return (
|
||||
db.query(Account)
|
||||
.join(
|
||||
AccountCommodityState,
|
||||
AccountCommodityState.account_id == Account.id,
|
||||
.filter(Account.id.in_(tuple(rank)))
|
||||
.order_by(
|
||||
case(rank, value=Account.id),
|
||||
Account.id.asc(),
|
||||
)
|
||||
.filter(
|
||||
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,
|
||||
),
|
||||
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(),
|
||||
)
|
||||
.distinct()
|
||||
)
|
||||
|
||||
|
||||
@@ -92,17 +119,7 @@ def build_select_query(
|
||||
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)
|
||||
)
|
||||
return _build_select_query(db, job, now)
|
||||
|
||||
|
||||
def run_account_capability_refresh(
|
||||
@@ -110,14 +127,41 @@ def run_account_capability_refresh(
|
||||
job: AutomationJob,
|
||||
) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
accounts = build_select_query(db, job, now).all()
|
||||
pending = active_account_work_count(
|
||||
db,
|
||||
work_types=ACCOUNT_SYNC_WORK_TYPES,
|
||||
)
|
||||
headroom = max(0, _queue_target_pending() - pending)
|
||||
if headroom <= 0:
|
||||
return {
|
||||
"scanned": 0,
|
||||
"success": 0,
|
||||
"invalid": 0,
|
||||
"skipped": pending,
|
||||
"message": (
|
||||
f"账号同步队列仍有 {pending} 条待处理,本轮不继续补货,"
|
||||
"先交给独立同步槽消化"
|
||||
),
|
||||
"detail": {"queued": 0, "pending": pending, "headroom": 0},
|
||||
}
|
||||
demand_rows = _pending_demand_rows(db, now)
|
||||
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
|
||||
accounts = _build_select_query(
|
||||
db,
|
||||
job,
|
||||
now,
|
||||
batch_limit=headroom,
|
||||
).all()
|
||||
for account in accounts:
|
||||
enqueue_account_work(
|
||||
db,
|
||||
account_id=int(account.id),
|
||||
work_type=WORK_STOREHOME_SYNC,
|
||||
priority=40,
|
||||
reason="履约商品能力过期,等待补货刷新",
|
||||
priority=10,
|
||||
reason=(
|
||||
"待履约商品补货: "
|
||||
+ ",".join(commodity_ids[:5])
|
||||
)[:255],
|
||||
due_at=now,
|
||||
)
|
||||
db.commit()
|
||||
@@ -128,11 +172,16 @@ def run_account_capability_refresh(
|
||||
"invalid": 0,
|
||||
"skipped": 0,
|
||||
"message": (
|
||||
f"本轮筛选 {len(accounts)} 个到期账号,新入队 {queued} 个"
|
||||
f"本轮筛选 {len(accounts)} 个待补货账号,新入队 {queued} 个"
|
||||
if accounts
|
||||
else "当前履约商品没有到期待刷新的账号能力"
|
||||
else "当前履约商品没有可补充的新鲜 CK 候选账号"
|
||||
),
|
||||
"detail": {"queued": queued},
|
||||
"detail": {
|
||||
"queued": queued,
|
||||
"pending": pending,
|
||||
"headroom": headroom,
|
||||
"commodities": commodity_ids[:20],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,15 +2,16 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....models import AccountLease, AutomationJob, PlatformFulfillmentTask
|
||||
from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask
|
||||
from ...platform_fulfillment.account_selector import (
|
||||
expire_platform_fulfillment_leases,
|
||||
)
|
||||
from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes
|
||||
|
||||
JOB_KEY = "platform_fulfillment_lease_reaper"
|
||||
|
||||
@@ -22,6 +23,36 @@ def run_platform_fulfillment_lease_reaper(
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
moment = now or datetime.now(UTC)
|
||||
stale_binding_cutoff = moment - timedelta(
|
||||
minutes=binding_failed_lease_ttl_minutes()
|
||||
)
|
||||
stale_binding_leases = (
|
||||
db.query(AccountLease)
|
||||
.join(
|
||||
PlatformFulfillmentTask,
|
||||
PlatformFulfillmentTask.lease_id == AccountLease.id,
|
||||
)
|
||||
.join(Account, Account.id == AccountLease.account_id)
|
||||
.filter(
|
||||
AccountLease.purpose == "platform_fulfillment",
|
||||
AccountLease.status == "active",
|
||||
AccountLease.expires_at.is_(None),
|
||||
PlatformFulfillmentTask.execution_status == "manual_required",
|
||||
PlatformFulfillmentTask.issue_code == "binding_failed",
|
||||
PlatformFulfillmentTask.updated_at <= stale_binding_cutoff,
|
||||
Account.role_bind_status == "unbound",
|
||||
)
|
||||
.order_by(AccountLease.id.asc())
|
||||
.limit(max(1, int(job.batch_size or 500)))
|
||||
.all()
|
||||
)
|
||||
for lease in stale_binding_leases:
|
||||
# 2026-11-22:扫码超时不等于正常人工处理。账号只保留一段可刷新
|
||||
# 二维码的宽限期,否则未绑定账号会被历史任务永久占住。
|
||||
lease.expires_at = moment
|
||||
lease.updated_at = moment
|
||||
if stale_binding_leases:
|
||||
db.flush()
|
||||
candidate_leases = (
|
||||
db.query(AccountLease)
|
||||
.filter(
|
||||
@@ -87,6 +118,9 @@ def run_platform_fulfillment_lease_reaper(
|
||||
for task in rows:
|
||||
if task.execution_status in {"completed", "cancelled"}:
|
||||
continue
|
||||
task.account_id = None
|
||||
task.lease_id = None
|
||||
task.bind_task_id = None
|
||||
task.execution_status = "manual_required"
|
||||
task.issue_code = "lease_expired"
|
||||
task.last_error = "账号租约已过期,请重新分配账号"
|
||||
@@ -97,6 +131,7 @@ def run_platform_fulfillment_lease_reaper(
|
||||
return {
|
||||
"scanned": expired,
|
||||
"expired": expired,
|
||||
"stale_binding_recovered": len(stale_binding_leases),
|
||||
"affected_tasks": affected,
|
||||
"message": f"直播账号履约租约回收 {expired} 条",
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user