优化(账号自动化): 履约保护登录配额与重登优先级

This commit is contained in:
yml
2026-11-25 22:13:21 +08:00
parent 0943b7a362
commit 9bdd2f4e1a
25 changed files with 1510 additions and 193 deletions
+388 -30
View File
@@ -3,9 +3,10 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, date, datetime
from datetime import UTC, date, datetime, timedelta
from zoneinfo import ZoneInfo
from sqlalchemy import and_, func, or_, select
from sqlalchemy.orm import Session
from ..models import (
@@ -15,7 +16,10 @@ from ..models import (
LoginQuotaUsage,
LoginTask,
)
from .account_value import is_high_value_account
from .account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS
from .account_protection_service import ProtectionSnapshot, load_protection_snapshot
from .account_query_filters import automation_account_filter
from .account_value import is_high_value_account, is_high_value_expr
from .douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
CATEGORY_ALL = "all"
@@ -23,12 +27,33 @@ CATEGORY_MANUAL = "manual_login"
CATEGORY_ONBOARDING = "onboarding"
CATEGORY_RELOGIN_HIGH = "relogin_high_value"
CATEGORY_RELOGIN_ORDINARY = "relogin_ordinary"
#: 履约保护目标(预售/协作单/生效租约绑定账号)的失效重登:独立分类与配额保护,
#: 不被全库普通重登吃干当天登录次数。
CATEGORY_RELOGIN_PROTECTED = "relogin_protected"
CATEGORY_ACCOUNT_CHECK = "account_check"
#: 租约 CK 续期:账号**已经有 CK**,只是租约到期前提前登录续一次。
#: 必须和「首次登录」分开 —— 两者触发方式都是 automation,但预算归属不同,
#: 页面标签也不同(曾经被显示成"自动化·首次登录",排查时非常误导)。
CATEGORY_LEASE_REFRESH = "lease_refresh"
_MANUAL_BYPASS_CATEGORIES = frozenset(
{
CATEGORY_MANUAL,
CATEGORY_ACCOUNT_CHECK,
}
)
_REFRESH_LOOKAHEAD = timedelta(hours=24)
# 自动化登录优先级(数值越小优先级越高):
# P0 履约保护失效重登 > P1 履约快过期续期 > P2 高价值重登 > P3 普通重登 > P4 首次登录
_TIER_BY_CATEGORY: dict[str, int] = {
CATEGORY_RELOGIN_PROTECTED: 0,
CATEGORY_LEASE_REFRESH: 1,
CATEGORY_RELOGIN_HIGH: 2,
CATEGORY_RELOGIN_ORDINARY: 3,
CATEGORY_ONBOARDING: 4,
}
BUSINESS_TZ = ZoneInfo("Asia/Shanghai")
@@ -53,6 +78,7 @@ def classify_login_category(
trigger_source: str = "manual",
now: datetime | None = None,
category: str = "",
protected: bool = False,
) -> str:
# 调用方显式指定分类时优先用它(例如租约 CK 续期)。
if category:
@@ -60,6 +86,8 @@ def classify_login_category(
if mode == "check":
return CATEGORY_ACCOUNT_CHECK
if mode == "relogin":
if protected:
return CATEGORY_RELOGIN_PROTECTED
return (
CATEGORY_RELOGIN_HIGH
if is_high_value_account(account, now=now)
@@ -166,13 +194,305 @@ def _category_limit(setting: LoginQuotaSetting, category: str) -> int:
CATEGORY_ONBOARDING: int(setting.onboarding_daily_limit),
CATEGORY_RELOGIN_HIGH: int(setting.relogin_high_value_daily_limit),
CATEGORY_RELOGIN_ORDINARY: int(setting.relogin_ordinary_daily_limit),
CATEGORY_RELOGIN_PROTECTED: int(
getattr(setting, "relogin_protected_daily_limit", setting.daily_attempt_limit)
),
CATEGORY_LEASE_REFRESH: int(
getattr(setting, "lease_refresh_daily_limit", setting.daily_attempt_limit)
),
CATEGORY_MANUAL: int(setting.manual_daily_limit),
CATEGORY_ACCOUNT_CHECK: int(setting.manual_daily_limit),
# 租约续期本质是「提前重登」,借用普通重登的日预算。
CATEGORY_LEASE_REFRESH: int(setting.relogin_ordinary_daily_limit),
}.get(category, int(setting.daily_attempt_limit))
def _available_today_filter(
*,
per_account_limit: int,
quota_day: date,
):
in_flight = (
select(LoginAttempt.id)
.where(
LoginAttempt.account_id == Account.id,
LoginAttempt.status.in_(("pending", "running")),
)
.correlate(Account)
.exists()
)
used_today = (
select(func.count(LoginAttempt.id))
.where(
LoginAttempt.account_id == Account.id,
LoginAttempt.quota_day == quota_day,
LoginAttempt.status != "skipped",
)
.correlate(Account)
.scalar_subquery()
)
return and_(~in_flight, used_today < per_account_limit)
def _count_available_today(
query,
*,
per_account_limit: int,
quota_day: date,
) -> int:
if per_account_limit <= 0:
return 0
return int(
query.filter(
_available_today_filter(
per_account_limit=per_account_limit,
quota_day=quota_day,
)
).count()
or 0
)
def _pending_protected_invalid_query(
db: Session,
*,
protection: ProtectionSnapshot,
now: datetime,
):
relogin_ids = protection.relogin_ids
if not relogin_ids:
return db.query(Account.id).filter(Account.id == -1)
return db.query(Account.id).filter(
Account.id.in_(relogin_ids),
Account.ck_check_status == "invalid",
automation_account_filter(cookie_operable=True),
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(
Account.relogin_next_at.is_(None),
Account.relogin_next_at <= now,
),
)
def _pending_protected_expiring_query(
db: Session,
*,
protection: ProtectionSnapshot,
now: datetime,
):
relogin_ids = protection.relogin_ids
if not relogin_ids:
return db.query(Account.id).filter(Account.id == -1)
cutoff = now + _REFRESH_LOOKAHEAD
return db.query(Account.id).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 <= now,
),
)
def _pending_inventory_relogin_query(
db: Session,
*,
protection: ProtectionSnapshot,
now: datetime,
):
excluded_ids = protection.monitored_ids
query = db.query(Account.id).filter(
Account.ck_check_status == "invalid",
automation_account_filter(cookie_operable=True),
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(
Account.relogin_next_at.is_(None),
Account.relogin_next_at <= now,
),
)
if excluded_ids:
query = query.filter(~Account.id.in_(excluded_ids))
return query
def _pending_inventory_relogin_counts(
db: Session,
*,
protection: ProtectionSnapshot,
setting: LoginQuotaSetting,
quota_day: date,
now: datetime,
) -> tuple[int, int]:
per_account_limit = int(setting.per_account_daily_limit)
query = _pending_inventory_relogin_query(
db,
protection=protection,
now=now,
)
high = _count_available_today(
query.filter(is_high_value_expr(now=now)),
per_account_limit=per_account_limit,
quota_day=quota_day,
)
ordinary = _count_available_today(
query.filter(~is_high_value_expr(now=now)),
per_account_limit=per_account_limit,
quota_day=quota_day,
)
return high, ordinary
def _tier_reserve_needed(
db: Session,
*,
tier: int,
protection: ProtectionSnapshot,
setting: LoginQuotaSetting,
quota_day: date,
now: datetime,
) -> tuple[int, str]:
"""计算比当前请求优先级更高的类别还需要预留多少全局名额。"""
if tier <= 0:
return 0, ""
per_account_limit = int(setting.per_account_daily_limit)
if per_account_limit <= 0:
return 0, ""
def _remaining_cat(category: str) -> int:
return max(
0,
_category_limit(setting, category)
- _category_daily_total(db, quota_day, category),
)
p0_pending = _count_available_today(
_pending_protected_invalid_query(db, protection=protection, now=now),
per_account_limit=per_account_limit,
quota_day=quota_day,
)
reserved = min(p0_pending, _remaining_cat(CATEGORY_RELOGIN_PROTECTED))
if tier == 1:
return reserved, "履约保护失效账号"
p1_pending = _count_available_today(
_pending_protected_expiring_query(db, protection=protection, now=now),
per_account_limit=per_account_limit,
quota_day=quota_day,
)
reserved += min(p1_pending, _remaining_cat(CATEGORY_LEASE_REFRESH))
if tier == 2:
return reserved, "履约保护与快过期账号"
p2_pending, p3_pending = _pending_inventory_relogin_counts(
db,
protection=protection,
setting=setting,
quota_day=quota_day,
now=now,
)
reserved += min(p2_pending, _remaining_cat(CATEGORY_RELOGIN_HIGH))
if tier == 3:
return reserved, "履约保护与高价值账号"
reserved += min(p3_pending, _remaining_cat(CATEGORY_RELOGIN_ORDINARY))
return reserved, "高优先级重登账号"
def get_login_quota_usage_summary(
db: Session,
*,
now: datetime | None = None,
) -> dict[str, object]:
"""返回今日/本小时全局及各优先级分类的登录配额使用与积压情况。"""
moment = now or datetime.now(UTC)
quota_day, quota_hour = _bucket(moment)
setting = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first()
if setting is None:
setting = LoginQuotaSetting(id=1)
protection = load_protection_snapshot(db)
per_account_limit = int(setting.per_account_daily_limit)
p0_pending = _count_available_today(
_pending_protected_invalid_query(db, protection=protection, now=moment),
per_account_limit=per_account_limit,
quota_day=quota_day,
)
p1_pending = _count_available_today(
_pending_protected_expiring_query(db, protection=protection, now=moment),
per_account_limit=per_account_limit,
quota_day=quota_day,
)
p2_pending, p3_pending = _pending_inventory_relogin_counts(
db,
protection=protection,
setting=setting,
quota_day=quota_day,
now=moment,
)
p4_pending = int(
db.query(func.count(Account.id))
.filter(
Account.auto_managed.is_(True),
Account.status == "imported",
Account.username != "",
Account.password != "",
or_(Account.cookie.is_(None), Account.cookie == ""),
)
.scalar()
or 0
)
specs = [
("P0", CATEGORY_RELOGIN_PROTECTED, "履约保护失效重登", p0_pending),
("P1", CATEGORY_LEASE_REFRESH, "履约快过期续期", p1_pending),
("P2", CATEGORY_RELOGIN_HIGH, "高价值重登", p2_pending),
("P3", CATEGORY_RELOGIN_ORDINARY, "普通重登", p3_pending),
("P4", CATEGORY_ONBOARDING, "首次登录", p4_pending),
("人工", CATEGORY_MANUAL, "人工登录", 0),
]
categories = []
for priority, category, label, pending in specs:
limit = _category_limit(setting, category)
used = _category_daily_total(db, quota_day, category)
categories.append(
{
"priority": priority,
"category": category,
"label": label,
"limit": limit,
"used": used,
"remaining": max(0, limit - used),
"pending": pending,
}
)
daily_limit = int(setting.daily_attempt_limit)
daily_used = _daily_total(db, quota_day)
hourly_limit = int(setting.hourly_attempt_limit)
hourly_used = _hourly_total(db, quota_day, quota_hour)
return {
"quota_day": quota_day.isoformat(),
"quota_hour": quota_hour,
"daily_limit": daily_limit,
"daily_used": daily_used,
"daily_remaining": max(0, daily_limit - daily_used),
"hourly_limit": hourly_limit,
"hourly_used": hourly_used,
"hourly_remaining": max(0, hourly_limit - hourly_used),
"categories": categories,
}
def reserve_login_attempt(
db: Session,
*,
@@ -187,18 +507,24 @@ def reserve_login_attempt(
moment = now or datetime.now(UTC)
quota_day, quota_hour = _bucket(moment)
setting = _setting(db)
protection = None
is_protected = False
if mode == "relogin" and not category:
protection = load_protection_snapshot(db)
is_protected = int(account.id) in protection.relogin_ids
resolved_category = classify_login_category(
account,
mode=mode,
trigger_source=trigger_source,
now=moment,
category=category,
protected=is_protected,
)
if not setting.enabled:
category = classify_login_category(
account,
mode=mode,
trigger_source=trigger_source,
now=moment,
category=category,
)
attempt = LoginAttempt(
account_id=int(account.id),
batch_id=batch_id[:64],
category=category,
category=resolved_category,
trigger_source=trigger_source[:16],
created_by=created_by,
started_at=moment,
@@ -209,6 +535,9 @@ def reserve_login_attempt(
db.flush()
return QuotaDecision(True, attempt=attempt)
if resolved_category not in _MANUAL_BYPASS_CATEGORIES and protection is None:
protection = load_protection_snapshot(db)
in_flight = (
db.query(LoginTask.id)
.filter(
@@ -233,35 +562,59 @@ def reserve_login_attempt(
.filter(
LoginAttempt.account_id == account.id,
LoginAttempt.quota_day == quota_day,
LoginAttempt.status != "skipped",
)
.count()
)
if account_day_count >= int(setting.per_account_daily_limit):
return QuotaDecision(False, reason="该账号已达到今日登录尝试上限")
if _daily_total(db, quota_day) >= int(setting.daily_attempt_limit):
daily_used = _daily_total(db, quota_day)
daily_limit = int(setting.daily_attempt_limit)
if daily_used >= daily_limit:
return QuotaDecision(False, reason="全局每日登录尝试预算已用完")
if _hourly_total(db, quota_day, quota_hour) >= int(
setting.hourly_attempt_limit
):
hourly_used = _hourly_total(db, quota_day, quota_hour)
hourly_limit = int(setting.hourly_attempt_limit)
if hourly_used >= hourly_limit:
return QuotaDecision(False, reason="全局每小时登录尝试预算已用完")
category = classify_login_category(
account,
mode=mode,
trigger_source=trigger_source,
now=moment,
category=category,
)
if _category_daily_total(db, quota_day, category) >= _category_limit(
setting, category
if resolved_category not in _MANUAL_BYPASS_CATEGORIES:
assert protection is not None
tier = (
0
if is_protected and resolved_category != CATEGORY_LEASE_REFRESH
else _TIER_BY_CATEGORY.get(resolved_category, 4)
)
reserved_needed, target_label = _tier_reserve_needed(
db,
tier=tier,
protection=protection,
setting=setting,
quota_day=quota_day,
now=moment,
)
if reserved_needed > 0:
if (daily_limit - daily_used) <= reserved_needed:
return QuotaDecision(
False,
reason=f"全局每日登录尝试预算已预留给{target_label}",
)
if (hourly_limit - hourly_used) <= reserved_needed:
return QuotaDecision(
False,
reason=f"全局每小时登录尝试预算已预留给{target_label}",
)
if _category_daily_total(db, quota_day, resolved_category) >= _category_limit(
setting, resolved_category
):
return QuotaDecision(False, reason=f"{category} 今日登录预算已用完")
return QuotaDecision(False, reason=f"{resolved_category} 今日登录预算已用完")
attempt = LoginAttempt(
account_id=int(account.id),
batch_id=batch_id[:64],
category=category,
category=resolved_category,
trigger_source=trigger_source[:16],
created_by=created_by,
started_at=moment,
@@ -269,7 +622,7 @@ def reserve_login_attempt(
quota_day=quota_day,
)
db.add(attempt)
for usage_category in (CATEGORY_ALL, category):
for usage_category in (CATEGORY_ALL, resolved_category):
usage = _usage_row(
db,
quota_day=quota_day,
@@ -289,7 +642,7 @@ def finish_login_attempt(
failure_kind: str = "",
now: datetime | None = None,
) -> None:
if attempt.status in {"success", "failed", "error", "stopped"}:
if attempt.status in {"success", "failed", "error", "stopped", "skipped"}:
return
moment = now or datetime.now(UTC)
attempt.status = status[:16]
@@ -307,7 +660,10 @@ def finish_login_attempt(
quota_hour=quota_hour,
category=usage_category,
)
if status == "success":
if status == "skipped":
# 本轮未真正发出登录请求:退还预扣的 attempt_count,也不记入失败。
usage.attempt_count = max(0, int(usage.attempt_count or 0) - 1)
elif status == "success":
usage.success_count = int(usage.success_count or 0) + 1
elif status in {"failed", "error"}:
usage.failure_count = int(usage.failure_count or 0) + 1
@@ -346,10 +702,12 @@ __all__ = [
"CATEGORY_ONBOARDING",
"CATEGORY_RELOGIN_HIGH",
"CATEGORY_RELOGIN_ORDINARY",
"CATEGORY_RELOGIN_PROTECTED",
"QuotaDecision",
"classify_login_category",
"cleanup_orphan_login_attempts",
"finish_login_attempt",
"get_login_quota_usage_summary",
"login_concurrency_limit",
"reserve_login_attempt",
]