feat(automation): 增加租约 CK 到期前刷新
- 保护组新增 lease_bound,覆盖全部生效履约/协作租约 - 新增 lease_ck_refresh 作业,提前 24h 为有效 CK 续期 - 已失效重登仍由 ck_relogin 处理 - 失败按类型设置退避,避免每轮重复撞 - 补充保护组、选行、作业执行测试
This commit is contained in:
@@ -22,6 +22,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import (
|
||||
Account,
|
||||
AccountLease,
|
||||
AutomationJob,
|
||||
DouyuExternalOrder,
|
||||
PlatformFulfillmentTask,
|
||||
@@ -55,6 +56,14 @@ GROUP_DEFINITIONS: dict[str, dict[str, Any]] = {
|
||||
"probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES,
|
||||
"auto_relogin": True,
|
||||
},
|
||||
"lease_bound": {
|
||||
"label": "生效租约账号",
|
||||
"description": "当前所有生效的直播履约/协作租约账号,优先 CK 巡检和到期前刷新",
|
||||
"enabled": True,
|
||||
"target_count": 0,
|
||||
"probe_interval_minutes": 30,
|
||||
"auto_relogin": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -136,6 +145,19 @@ def _collab_account_ids(db: Session) -> set[int]:
|
||||
return {int(row[0]) for row in rows if row[0] is not None}
|
||||
|
||||
|
||||
def _lease_account_ids(db: Session) -> set[int]:
|
||||
rows = (
|
||||
db.query(AccountLease.account_id)
|
||||
.filter(
|
||||
AccountLease.status == "active",
|
||||
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
|
||||
)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {int(row[0]) for row in rows if row[0] is not None}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProtectionSnapshot:
|
||||
groups: dict[str, dict[str, Any]]
|
||||
@@ -189,6 +211,7 @@ def load_protection_snapshot(
|
||||
group_account_ids={
|
||||
"presale_bound": frozenset(_presale_account_ids(db)),
|
||||
"collab_bound": frozenset(_collab_account_ids(db)),
|
||||
"lease_bound": frozenset(_lease_account_ids(db)),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ from .jobs.douyu_tasks_retention import (
|
||||
from .jobs.douyu_tasks_retention import (
|
||||
run_douyu_tasks_retention,
|
||||
)
|
||||
from .jobs.lease_ck_refresh import JOB_KEY as LEASE_CK_REFRESH_KEY
|
||||
from .jobs.lease_ck_refresh import run_lease_ck_refresh
|
||||
from .jobs.platform_fulfillment_lease_reaper import (
|
||||
JOB_KEY as PLATFORM_FULFILLMENT_LEASE_REAPER_KEY,
|
||||
)
|
||||
@@ -84,6 +86,7 @@ __all__ = [
|
||||
"CK_HEALTH_KEY",
|
||||
"CK_RELOGIN_KEY",
|
||||
"DOUYU_TASKS_RETENTION_KEY",
|
||||
"LEASE_CK_REFRESH_KEY",
|
||||
"PLATFORM_FULFILLMENT_LEASE_REAPER_KEY",
|
||||
"POINTS_EXPIRE_KEY",
|
||||
"JobSpec",
|
||||
@@ -104,6 +107,7 @@ __all__ = [
|
||||
"run_douyu_tasks_retention",
|
||||
"run_due_jobs",
|
||||
"run_job_now",
|
||||
"run_lease_ck_refresh",
|
||||
"run_platform_fulfillment_lease_reaper",
|
||||
"run_points_expire_check",
|
||||
"scheduler_status",
|
||||
@@ -226,6 +230,20 @@ def register_default_jobs() -> None:
|
||||
run=run_ck_relogin,
|
||||
)
|
||||
)
|
||||
register_job(
|
||||
JobSpec(
|
||||
key=LEASE_CK_REFRESH_KEY,
|
||||
title="租约 CK 到期前刷新",
|
||||
# 只处理仍有效、但预测 24h 内到期的生效租约账号;提前续 CK,
|
||||
# 不参与普通失效重登的批次。
|
||||
interval_seconds=600,
|
||||
run_interval_seconds=600,
|
||||
batch_size=10,
|
||||
concurrency=3,
|
||||
run=run_lease_ck_refresh,
|
||||
default_enabled=True,
|
||||
)
|
||||
)
|
||||
register_job(
|
||||
JobSpec(
|
||||
key=CK_HEALTH_KEY,
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""租约账号 CK 到期前刷新(P1)。
|
||||
|
||||
`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但租约账号如果等到
|
||||
失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前
|
||||
24 小时**,对仍持有有效 CK 的生效租约账号做一次主动登录,延长 CK 生命周期。
|
||||
|
||||
范围:
|
||||
|
||||
- `account_leases.status=active` 且 purpose 为 `platform_fulfillment` / `douyu_collab`;
|
||||
- `ck_check_status=valid`、有 Cookie、可自动管理、没有在途登录;
|
||||
- 预测到期时间 <= now + 24h(`ck_expected_expires_at` 或 `cookie_updated_at + 7d`);
|
||||
- 失败分型为人工的账号、仍在退避窗口内的账号不碰。
|
||||
|
||||
作业只负责“提前续 CK”,不替代 `ck_relogin` 的失效重登;两者共用登录配额和
|
||||
登录任务审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....models import Account, AccountLease, AutomationJob, User
|
||||
from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS
|
||||
from ...account_query_filters import automation_account_filter
|
||||
from ...login_automation import run_login_batch_with_fallback
|
||||
|
||||
JOB_KEY = "lease_ck_refresh"
|
||||
TITLE = "租约 CK 到期前刷新"
|
||||
REFRESH_BEFORE = timedelta(hours=24)
|
||||
|
||||
|
||||
def _system_user_id(db: Session) -> int | None:
|
||||
row = (
|
||||
db.query(User.id)
|
||||
.filter(User.role == "super_admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if row:
|
||||
return int(row[0])
|
||||
row = db.query(User.id).order_by(User.id.asc()).first()
|
||||
return int(row[0]) if row else None
|
||||
|
||||
|
||||
def due_lease_account_query(
|
||||
db: Session,
|
||||
now: datetime | None = None,
|
||||
):
|
||||
"""到期前 24h 的租约账号查询(执行和测试共用)。"""
|
||||
moment = now or datetime.now(UTC)
|
||||
cutoff = moment + REFRESH_BEFORE
|
||||
return (
|
||||
db.query(Account)
|
||||
.join(AccountLease, AccountLease.account_id == Account.id)
|
||||
.filter(
|
||||
AccountLease.status == "active",
|
||||
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
|
||||
Account.ck_check_status == "valid",
|
||||
Account.cookie_updated_at.isnot(None),
|
||||
automation_account_filter(cookie_operable=True),
|
||||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||||
tuple(sorted(MANUAL_KINDS))
|
||||
),
|
||||
or_(
|
||||
Account.ck_expected_expires_at <= cutoff,
|
||||
Account.cookie_updated_at <= cutoff - DEFAULT_CK_LIFETIME,
|
||||
),
|
||||
or_(
|
||||
Account.relogin_next_at.is_(None),
|
||||
Account.relogin_next_at <= moment,
|
||||
),
|
||||
)
|
||||
.order_by(Account.cookie_updated_at.asc(), Account.id.asc())
|
||||
)
|
||||
|
||||
|
||||
def select_due_lease_accounts(
|
||||
db: Session,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
limit: int = 10,
|
||||
) -> list[Account]:
|
||||
return due_lease_account_query(db, now=now).limit(max(1, int(limit))).all()
|
||||
|
||||
|
||||
def run_lease_ck_refresh(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
system_user_id = _system_user_id(db)
|
||||
if system_user_id is None:
|
||||
return {
|
||||
"scanned": 0,
|
||||
"success": 0,
|
||||
"failed": 0,
|
||||
"message": "库里没有可用用户,无法以系统身份发起租约 CK 刷新",
|
||||
}
|
||||
|
||||
batch_size = max(1, int(job.batch_size or 10))
|
||||
accounts = select_due_lease_accounts(db, now=now, limit=batch_size)
|
||||
if not accounts:
|
||||
return {
|
||||
"scanned": 0,
|
||||
"success": 0,
|
||||
"failed": 0,
|
||||
"message": "没有 24h 内到期的租约账号需要刷新",
|
||||
}
|
||||
|
||||
account_ids = [int(account.id) for account in accounts]
|
||||
outcome = run_login_batch_with_fallback(
|
||||
db,
|
||||
account_ids=account_ids,
|
||||
mode="login",
|
||||
created_by=system_user_id,
|
||||
concurrency=max(1, min(int(job.concurrency or 3), 8)),
|
||||
max_total_time=240,
|
||||
)
|
||||
_settle_outcome(accounts, outcome, now=now)
|
||||
db.commit()
|
||||
retry = len(outcome.failed_ids) - _manual_count(outcome)
|
||||
return {
|
||||
"scanned": len(account_ids),
|
||||
"success": len(outcome.success_ids),
|
||||
"failed": len(outcome.failed_ids),
|
||||
"retry": max(0, retry),
|
||||
"manual": _manual_count(outcome),
|
||||
"skipped": len(outcome.skipped_ids),
|
||||
"fallbackUsed": outcome.fallback_used,
|
||||
"batchIds": list(outcome.batch_ids) + list(outcome.fallback_batch_ids),
|
||||
"message": (
|
||||
f"租约 CK 到期前刷新 {len(account_ids)} 条,"
|
||||
f"成功 {len(outcome.success_ids)},失败 {len(outcome.failed_ids)}"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _manual_count(outcome) -> int:
|
||||
return sum(
|
||||
1
|
||||
for account_id in outcome.failed_ids
|
||||
if outcome.failure_kinds.get(account_id) in MANUAL_KINDS
|
||||
)
|
||||
|
||||
|
||||
def _settle_outcome(accounts: list[Account], outcome, *, now: datetime) -> None:
|
||||
"""成功清退避,失败按类型设置下次重试,避免每 10 分钟撞一次。"""
|
||||
by_id = {int(account.id): account for account in accounts}
|
||||
for account_id in outcome.success_ids:
|
||||
account = by_id.get(int(account_id))
|
||||
if account is None:
|
||||
continue
|
||||
account.relogin_failure_kind = ""
|
||||
account.relogin_last_error = ""
|
||||
account.relogin_attempts = 0
|
||||
account.relogin_next_at = None
|
||||
for account_id in outcome.failed_ids:
|
||||
account = by_id.get(int(account_id))
|
||||
if account is None:
|
||||
continue
|
||||
kind = str(outcome.failure_kinds.get(account_id) or "unknown")
|
||||
account.relogin_failure_kind = kind
|
||||
account.relogin_attempts = int(account.relogin_attempts or 0) + 1
|
||||
if kind in MANUAL_KINDS:
|
||||
account.relogin_next_at = None
|
||||
elif kind == "email_quota":
|
||||
account.relogin_next_at = now + timedelta(hours=12)
|
||||
else:
|
||||
account.relogin_next_at = now + timedelta(hours=1)
|
||||
Reference in New Issue
Block a user