"""租约账号 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)