"""履约保护账号 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, AutomationJob, User from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS from ...account_protection_service import load_protection_snapshot from ...account_query_filters import automation_account_filter from ...login_automation import run_login_batch_with_fallback from ...login_quota_service import CATEGORY_LEASE_REFRESH JOB_KEY = "lease_ck_refresh" # 单账号总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。 LEASE_MAX_TOTAL_TIME = 300 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 protection = load_protection_snapshot(db) relogin_ids = protection.relogin_ids if not relogin_ids: return db.query(Account).filter(Account.id == -1) return ( db.query(Account) .filter( Account.id.in_(relogin_ids), 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.ck_expected_expires_at.is_(None).asc(), Account.ck_expected_expires_at.asc(), 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=LEASE_MAX_TOTAL_TIME, # 这些账号**有 CK**,是租约到期前提前续期,不是首次登录。 # 不显式指定分类的话会被判成 onboarding,页面显示成"自动化·首次登录", # 还把租约续期的量算进「首次登录」的日预算里。 category=CATEGORY_LEASE_REFRESH, ) _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)