Files
live-hub-py/web/backend/services/login_quota_service.py
T

714 lines
22 KiB
Python

"""登录尝试流水和数据库级登录预算。"""
from __future__ import annotations
from dataclasses import dataclass
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 (
Account,
LoginAttempt,
LoginQuotaSetting,
LoginQuotaUsage,
LoginTask,
)
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"
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")
@dataclass(frozen=True)
class QuotaDecision:
allowed: bool
reason: str = ""
attempt: LoginAttempt | None = None
def _bucket(now: datetime | None = None) -> tuple[date, int]:
moment = now or datetime.now(UTC)
aware = moment if moment.tzinfo else moment.replace(tzinfo=UTC)
local = aware.astimezone(BUSINESS_TZ)
return local.date(), local.hour
def classify_login_category(
account: Account,
*,
mode: str,
trigger_source: str = "manual",
now: datetime | None = None,
category: str = "",
protected: bool = False,
) -> str:
# 调用方显式指定分类时优先用它(例如租约 CK 续期)。
if category:
return 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)
else CATEGORY_RELOGIN_ORDINARY
)
if (
trigger_source == "automation"
or account.status == "imported"
or not account.cookie
or account.cookie_updated_at is None
):
return CATEGORY_ONBOARDING
return CATEGORY_MANUAL
def _setting(db: Session) -> LoginQuotaSetting:
row = (
db.query(LoginQuotaSetting)
.filter(LoginQuotaSetting.id == 1)
.with_for_update()
.first()
)
if row is None:
row = LoginQuotaSetting(id=1)
db.add(row)
db.flush()
return row
def login_concurrency_limit(db: Session) -> int:
"""读取数据库配置的登录并发上限;未初始化时使用保守默认值。"""
setting = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first()
if setting is None or not setting.enabled:
return 3
return max(1, min(int(setting.login_concurrency or 3), 10))
def _usage_row(
db: Session,
*,
quota_day: date,
quota_hour: int,
category: str,
) -> LoginQuotaUsage:
row = (
db.query(LoginQuotaUsage)
.filter(
LoginQuotaUsage.quota_day == quota_day,
LoginQuotaUsage.quota_hour == quota_hour,
LoginQuotaUsage.category == category,
)
.first()
)
if row is None:
row = LoginQuotaUsage(
quota_day=quota_day,
quota_hour=quota_hour,
category=category,
)
db.add(row)
db.flush()
return row
def _daily_total(db: Session, quota_day: date) -> int:
rows = (
db.query(LoginQuotaUsage.attempt_count)
.filter(
LoginQuotaUsage.quota_day == quota_day,
LoginQuotaUsage.category == CATEGORY_ALL,
)
.all()
)
return sum(int(value or 0) for (value,) in rows)
def _hourly_total(db: Session, quota_day: date, quota_hour: int) -> int:
value = (
db.query(LoginQuotaUsage.attempt_count)
.filter(
LoginQuotaUsage.quota_day == quota_day,
LoginQuotaUsage.quota_hour == quota_hour,
LoginQuotaUsage.category == CATEGORY_ALL,
)
.scalar()
)
return int(value or 0)
def _category_daily_total(db: Session, quota_day: date, category: str) -> int:
rows = (
db.query(LoginQuotaUsage.attempt_count)
.filter(
LoginQuotaUsage.quota_day == quota_day,
LoginQuotaUsage.category == category,
)
.all()
)
return sum(int(value or 0) for (value,) in rows)
def _category_limit(setting: LoginQuotaSetting, category: str) -> int:
return {
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),
}.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,
*,
account: Account,
mode: str,
trigger_source: str,
batch_id: str,
created_by: int | None,
now: datetime | None = None,
category: str = "",
) -> QuotaDecision:
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:
attempt = LoginAttempt(
account_id=int(account.id),
batch_id=batch_id[:64],
category=resolved_category,
trigger_source=trigger_source[:16],
created_by=created_by,
started_at=moment,
status="pending",
quota_day=quota_day,
)
db.add(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(
LoginTask.account_id == account.id,
LoginTask.attempt_status.in_(LOGIN_ATTEMPT_IN_FLIGHT_STATUSES),
)
.first()
)
in_flight_attempt = (
db.query(LoginAttempt.id)
.filter(
LoginAttempt.account_id == account.id,
LoginAttempt.status.in_(("pending", "running")),
)
.first()
)
if in_flight is not None or in_flight_attempt is not None:
return QuotaDecision(False, reason="该账号已有登录任务在执行")
account_day_count = (
db.query(LoginAttempt.id)
.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="该账号已达到今日登录尝试上限")
daily_used = _daily_total(db, quota_day)
daily_limit = int(setting.daily_attempt_limit)
if daily_used >= daily_limit:
return QuotaDecision(False, reason="全局每日登录尝试预算已用完")
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="全局每小时登录尝试预算已用完")
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"{resolved_category} 今日登录预算已用完")
attempt = LoginAttempt(
account_id=int(account.id),
batch_id=batch_id[:64],
category=resolved_category,
trigger_source=trigger_source[:16],
created_by=created_by,
started_at=moment,
status="pending",
quota_day=quota_day,
)
db.add(attempt)
for usage_category in (CATEGORY_ALL, resolved_category):
usage = _usage_row(
db,
quota_day=quota_day,
quota_hour=quota_hour,
category=usage_category,
)
usage.attempt_count = int(usage.attempt_count or 0) + 1
db.flush()
return QuotaDecision(True, attempt=attempt)
def finish_login_attempt(
db: Session,
attempt: LoginAttempt,
*,
status: str,
failure_kind: str = "",
now: datetime | None = None,
) -> None:
if attempt.status in {"success", "failed", "error", "stopped", "skipped"}:
return
moment = now or datetime.now(UTC)
attempt.status = status[:16]
attempt.failure_kind = failure_kind[:16]
attempt.finished_at = moment
attempt.duration_ms = max(
0,
int((moment - attempt.started_at).total_seconds() * 1000),
)
quota_day, quota_hour = _bucket(attempt.started_at)
for usage_category in (CATEGORY_ALL, attempt.category):
usage = _usage_row(
db,
quota_day=quota_day,
quota_hour=quota_hour,
category=usage_category,
)
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
db.flush()
def cleanup_orphan_login_attempts(
db: Session,
*,
now: datetime | None = None,
) -> int:
"""服务重启后把遗留的尝试流水收敛为 interrupted。"""
moment = now or datetime.now(UTC)
attempts = (
db.query(LoginAttempt)
.filter(LoginAttempt.status.in_(("pending", "running")))
.all()
)
for attempt in attempts:
finish_login_attempt(
db,
attempt,
status="failed",
failure_kind="interrupted",
now=moment,
)
if attempts:
db.commit()
return len(attempts)
__all__ = [
"CATEGORY_ACCOUNT_CHECK",
"CATEGORY_LEASE_REFRESH",
"CATEGORY_MANUAL",
"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",
]