Files
live-hub-py/web/backend/services/automation/jobs/lease_ck_refresh.py
T
yml da85373884 修复(账号自动化): 租约 CK 续期不再冒充「首次登录」,补齐等待预算
排查「首次登录都关掉了为什么还在一直登录」时发现:

- 真正在跑登录的是 lease_ck_refresh(租约 CK 续期,每 600 秒一轮),
  account_onboarding 确实已关;两者都显示成「自动化·首次登录」,所以很难分辨
- 根因是分类逻辑:trigger_source=automation 一律落 onboarding。但租约续期的
  账号本来就有 CK,只是租约到期前提前续一次,不是首次登录
- 这批租约账号全部「等待验证码超时」失败,因为生产跑的还是旧镜像(60 秒
  等待窗口),而且 lease_ck_refresh 的单账号总时长硬编码 240 秒,连新的
  900 秒等待窗口都会被掐断

改动:

- 新增 lease_refresh 分类:页面显示「自动化·租约CK续期」,日预算归到普通
  重登(不再占用「首次登录」的 150/天额度)
- lease_ck_refresh 单账号总时长 240 → 1800 秒,覆盖实测 8~13 分钟的投递延迟
- 登录预算建议的成功率样本纳入 lease_refresh

验证:1728 passed / 6 skipped,前端 tsc -b 通过,pyright 生产代码 0 错误
2026-11-25 20:04:59 +08:00

180 lines
6.5 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.
"""租约账号 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
from ...login_quota_service import CATEGORY_LEASE_REFRESH
JOB_KEY = "lease_ck_refresh"
# 单账号总时长上限:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟),
# 否则等待会被掐断成"等待验证码超时",租约账号一批批地失败。
LEASE_MAX_TOTAL_TIME = 1800
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=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)