优化(登录预算与任务): 建议上限封顶2000、错误中文化及补全跳过触发来源
This commit is contained in:
@@ -34,6 +34,13 @@ from ..services.execution_jobs import (
|
||||
request_execution_cancel,
|
||||
)
|
||||
from ..services.login_failure import classify_failure, failure_kind_label
|
||||
from ..services.login_quota_service import (
|
||||
AUTOMATED_CATEGORIES,
|
||||
CATEGORY_ACCOUNT_CHECK,
|
||||
CATEGORY_MANUAL,
|
||||
humanize_login_message,
|
||||
infer_category_from_message,
|
||||
)
|
||||
from ..services.login_service import batch_registry
|
||||
|
||||
router = APIRouter(prefix="/api/login", tags=["登录任务"])
|
||||
@@ -278,22 +285,47 @@ def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
||||
accounts_map[int(row[0])] = row
|
||||
|
||||
# 登录任务记录本身不带来源;来源在 LoginAttempt(人工/自动化/首次登录/重登)。
|
||||
# 已跳过的任务不会创建 LoginAttempt,需要按同批次 LoginAttempt / ExecutionJob / 消息文案补全来源与分类。
|
||||
batch_ids = {str(t.attempt_batch_id or t.batch_id or "") for t in rows}
|
||||
batch_ids.discard("")
|
||||
attempt_map: dict[tuple[str, int], LoginAttempt] = {}
|
||||
if batch_ids and account_ids:
|
||||
batch_fallback_map: dict[str, tuple[str, str]] = {}
|
||||
if batch_ids:
|
||||
for attempt in (
|
||||
db.query(LoginAttempt)
|
||||
.filter(
|
||||
LoginAttempt.batch_id.in_(batch_ids),
|
||||
LoginAttempt.account_id.in_(account_ids),
|
||||
)
|
||||
.filter(LoginAttempt.batch_id.in_(batch_ids))
|
||||
.order_by(LoginAttempt.id.asc())
|
||||
.all()
|
||||
):
|
||||
attempt_map[(str(attempt.batch_id or ""), int(attempt.account_id))] = (
|
||||
attempt
|
||||
)
|
||||
b_id = str(attempt.batch_id or "")
|
||||
if int(attempt.account_id) in account_ids:
|
||||
attempt_map[(b_id, int(attempt.account_id))] = attempt
|
||||
if b_id and b_id not in batch_fallback_map:
|
||||
batch_fallback_map[b_id] = (
|
||||
str(attempt.trigger_source or ""),
|
||||
str(attempt.category or ""),
|
||||
)
|
||||
|
||||
missing_batch_ids = batch_ids - set(batch_fallback_map.keys())
|
||||
job_origin_map: dict[str, tuple[str, str]] = {}
|
||||
if missing_batch_ids:
|
||||
for job_batch_id, payload in (
|
||||
db.query(ExecutionJob.batch_id, ExecutionJob.payload_json)
|
||||
.filter(ExecutionJob.batch_id.in_(missing_batch_ids))
|
||||
.all()
|
||||
):
|
||||
payload_dict = payload if isinstance(payload, dict) else {}
|
||||
job_trigger = str(payload_dict.get("trigger_source") or "")
|
||||
job_mode = str(payload_dict.get("mode") or "")
|
||||
if job_mode == "check":
|
||||
job_category = CATEGORY_ACCOUNT_CHECK
|
||||
elif job_trigger == "manual":
|
||||
job_category = CATEGORY_MANUAL
|
||||
else:
|
||||
job_category = ""
|
||||
if job_trigger or job_category:
|
||||
job_origin_map[str(job_batch_id or "")] = (job_trigger, job_category)
|
||||
|
||||
creator_ids = {
|
||||
int(value)
|
||||
for value in [
|
||||
@@ -318,6 +350,29 @@ def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
||||
account = accounts_map.get(int(t.account_id))
|
||||
batch_id = str(t.attempt_batch_id or t.batch_id or "")
|
||||
attempt = attempt_map.get((batch_id, int(t.account_id)))
|
||||
raw_message = (t.attempt_message if attempt_status else "") or t.message or ""
|
||||
display_message = humanize_login_message(raw_message)
|
||||
|
||||
if attempt is not None:
|
||||
trigger_source = str(attempt.trigger_source or "")
|
||||
category = str(attempt.category or "")
|
||||
else:
|
||||
batch_trigger, batch_category = batch_fallback_map.get(batch_id, ("", ""))
|
||||
job_trigger, job_category = job_origin_map.get(batch_id, ("", ""))
|
||||
inferred_category = infer_category_from_message(raw_message)
|
||||
category = inferred_category or batch_category or job_category
|
||||
trigger_source = batch_trigger or job_trigger
|
||||
if not trigger_source:
|
||||
if category in AUTOMATED_CATEGORIES:
|
||||
trigger_source = "automation"
|
||||
elif category in {CATEGORY_MANUAL, CATEGORY_ACCOUNT_CHECK}:
|
||||
trigger_source = "manual"
|
||||
elif (
|
||||
"今日登录预算" in display_message
|
||||
or "每小时登录尝试预算" in display_message
|
||||
):
|
||||
trigger_source = "automation"
|
||||
|
||||
result.append(
|
||||
LoginTaskOut(
|
||||
id=t.id,
|
||||
@@ -333,13 +388,11 @@ def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
||||
cookie_updated_at=(account[7] if account else None),
|
||||
status=attempt_status or t.status,
|
||||
cookie="",
|
||||
message=(t.attempt_message if attempt_status else "")
|
||||
or t.message
|
||||
or "",
|
||||
message=display_message,
|
||||
created_by=t.created_by,
|
||||
created_by_username=creator_map.get(int(t.created_by), ""),
|
||||
trigger_source=(str(attempt.trigger_source or "") if attempt else ""),
|
||||
category=(str(attempt.category or "") if attempt else ""),
|
||||
trigger_source=trigger_source,
|
||||
category=category,
|
||||
created_at=t.created_at,
|
||||
finished_at=t.attempt_at or t.finished_at,
|
||||
)
|
||||
@@ -412,10 +465,18 @@ def get_task_logs(
|
||||
)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="登录任务不存在")
|
||||
items = [
|
||||
(
|
||||
{**entry, "message": humanize_login_message(entry.get("message"))}
|
||||
if isinstance(entry, dict) and "message" in entry
|
||||
else entry
|
||||
)
|
||||
for entry in (task.logs or [])
|
||||
]
|
||||
return {
|
||||
"task_id": int(task.id),
|
||||
"account_id": int(task.account_id),
|
||||
"items": task.logs or [],
|
||||
"items": items,
|
||||
}
|
||||
|
||||
|
||||
@@ -523,7 +584,8 @@ def export_tasks(
|
||||
for task in rows:
|
||||
attempt_status = task.attempt_status or ""
|
||||
effective = attempt_status or task.status or ""
|
||||
message = (task.attempt_message if attempt_status else "") or task.message or ""
|
||||
raw_message = (task.attempt_message if attempt_status else "") or task.message or ""
|
||||
message = humanize_login_message(raw_message)
|
||||
kind = classify_failure(message) if effective in {"failed", "error"} else ""
|
||||
username, tag, owner = info.get(task.account_id, ("", "", ""))
|
||||
writer.writerow(
|
||||
|
||||
@@ -23,12 +23,13 @@ MIN_RECENT_SAMPLE = 20
|
||||
DEFAULT_SUCCESS_RATE = 70.0
|
||||
MIN_EFFECTIVE_SUCCESS_RATE = 35.0
|
||||
MIN_DAILY_ATTEMPTS = 50
|
||||
MAX_DAILY_ATTEMPTS = 5000
|
||||
MAX_DAILY_ATTEMPTS = 2000
|
||||
MAX_MANUAL_RESERVE = 200
|
||||
ASSUMED_ACTIVE_HOURS = 12
|
||||
|
||||
|
||||
def _fit_priority_budgets(limits: list[int], available: int) -> list[int]:
|
||||
"""把 P0-P3 预算压进全局可用名额,按优先级从低到高削减。"""
|
||||
"""把 P0-P4 预算压进全局可用名额,按优先级从低到高削减。"""
|
||||
fitted = list(limits)
|
||||
excess = max(0, sum(fitted) - max(0, int(available)))
|
||||
for index in range(len(fitted) - 1, -1, -1):
|
||||
@@ -219,7 +220,11 @@ def recommend_login_budget(
|
||||
expected_daily_invalid + recovery_pressure + onboarding_pressure
|
||||
)
|
||||
core_attempts = math.ceil(required_success / effective_rate)
|
||||
manual_reserve = max(30, math.ceil(core_attempts * 0.1))
|
||||
# 人工预留按每日总预算(而非未封顶需求)比例计算并设上限,避免大库存时挤占 P0-P3 自动化预算。
|
||||
raw_manual_reserve = min(
|
||||
MAX_MANUAL_RESERVE,
|
||||
max(30, math.ceil(min(MAX_DAILY_ATTEMPTS, core_attempts) * 0.1)),
|
||||
)
|
||||
onboarding_attempts = math.ceil(onboarding_pressure / effective_rate)
|
||||
nonprotected_relogin_pressure_high = (
|
||||
nonprotected_valid_high / CK_AVERAGE_LIFETIME_DAYS
|
||||
@@ -257,35 +262,36 @@ def recommend_login_budget(
|
||||
),
|
||||
)
|
||||
|
||||
raw_relogin_limits = [
|
||||
raw_priority_limits = [
|
||||
relogin_protected_limit,
|
||||
lease_refresh_limit,
|
||||
relogin_high_limit,
|
||||
relogin_ordinary_limit,
|
||||
onboarding_attempts,
|
||||
]
|
||||
planned_attempts = (
|
||||
sum(raw_relogin_limits) + onboarding_attempts + manual_reserve
|
||||
)
|
||||
planned_attempts = sum(raw_priority_limits) + raw_manual_reserve
|
||||
daily_attempts = min(
|
||||
MAX_DAILY_ATTEMPTS,
|
||||
max(
|
||||
MIN_DAILY_ATTEMPTS,
|
||||
core_attempts + manual_reserve,
|
||||
core_attempts + raw_manual_reserve,
|
||||
planned_attempts,
|
||||
),
|
||||
)
|
||||
available_relogin_attempts = max(
|
||||
0,
|
||||
daily_attempts - onboarding_attempts - manual_reserve,
|
||||
manual_reserve = min(
|
||||
raw_manual_reserve,
|
||||
max(30, math.ceil(daily_attempts * 0.1)),
|
||||
)
|
||||
available_auto_attempts = max(0, daily_attempts - manual_reserve)
|
||||
(
|
||||
relogin_protected_limit,
|
||||
lease_refresh_limit,
|
||||
relogin_high_limit,
|
||||
relogin_ordinary_limit,
|
||||
onboarding_attempts,
|
||||
) = _fit_priority_budgets(
|
||||
raw_relogin_limits,
|
||||
available_relogin_attempts,
|
||||
raw_priority_limits,
|
||||
available_auto_attempts,
|
||||
)
|
||||
hourly_attempts = max(1, math.ceil(daily_attempts / ASSUMED_ACTIVE_HOURS))
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
import re
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import and_, func, or_, select
|
||||
@@ -57,14 +58,104 @@ _TIER_BY_CATEGORY: dict[str, int] = {
|
||||
CATEGORY_ONBOARDING: 4,
|
||||
}
|
||||
|
||||
CATEGORY_LABELS: dict[str, str] = {
|
||||
CATEGORY_ONBOARDING: "首次登录",
|
||||
CATEGORY_RELOGIN_HIGH: "高价值重登",
|
||||
CATEGORY_RELOGIN_ORDINARY: "普通重登",
|
||||
CATEGORY_RELOGIN_PROTECTED: "履约保护重登",
|
||||
CATEGORY_LEASE_REFRESH: "履约快过期续期",
|
||||
CATEGORY_MANUAL: "人工登录",
|
||||
"manual": "人工登录",
|
||||
CATEGORY_ACCOUNT_CHECK: "账号检测",
|
||||
}
|
||||
|
||||
AUTOMATED_CATEGORIES: frozenset[str] = frozenset(
|
||||
{
|
||||
CATEGORY_ONBOARDING,
|
||||
CATEGORY_RELOGIN_HIGH,
|
||||
CATEGORY_RELOGIN_ORDINARY,
|
||||
CATEGORY_RELOGIN_PROTECTED,
|
||||
CATEGORY_LEASE_REFRESH,
|
||||
}
|
||||
)
|
||||
|
||||
_HTTP_POOL_RE = re.compile(
|
||||
r"HTTPS?ConnectionPool\([^\n]*?(?=(?:(旧 Cookie 已保留)|$))"
|
||||
)
|
||||
_QUOTA_KEY_RE = re.compile(
|
||||
r"(relogin_protected|lease_refresh|relogin_high_value|relogin_ordinary|onboarding|manual_login|account_check|all)\s*今日登录预算已用完"
|
||||
)
|
||||
|
||||
BUSINESS_TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
|
||||
def category_label(category: str | None) -> str:
|
||||
"""将登录分类 key 映射为中文展示名。"""
|
||||
key = (category or "").strip()
|
||||
if key == CATEGORY_ALL:
|
||||
return "全局"
|
||||
return CATEGORY_LABELS.get(key, key)
|
||||
|
||||
|
||||
def infer_category_from_message(message: str | None) -> str:
|
||||
"""从跳过或失败文案中提取登录分类 key(兼容历史原始英文 key 与中文标签)。"""
|
||||
text = message or ""
|
||||
if not text:
|
||||
return ""
|
||||
for key, label in CATEGORY_LABELS.items():
|
||||
if key == "manual":
|
||||
continue
|
||||
if key in text or f"{label}今日登录预算已用完" in text:
|
||||
return key
|
||||
return ""
|
||||
|
||||
|
||||
def humanize_login_message(message: str | None) -> str:
|
||||
"""把历史或底层英文登录错误、跳过原因整理为可读中文。"""
|
||||
text = str(message or "")
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
text = _QUOTA_KEY_RE.sub(
|
||||
lambda match: f"{category_label(match.group(1))}今日登录预算已用完",
|
||||
text,
|
||||
)
|
||||
text = text.replace("极验 slide 验证失败: forbidden", "极验滑块验证失败: 触发风控拦截")
|
||||
text = text.replace("极验 slide 验证失败: fail", "极验滑块验证失败: 滑块未通过")
|
||||
text = text.replace("极验 slide 验证失败:", "极验滑块验证失败:")
|
||||
text = text.replace("极验 slide 验证失败", "极验滑块验证失败")
|
||||
|
||||
if (
|
||||
"HTTPSConnectionPool(" in text
|
||||
or "HTTPConnectionPool(" in text
|
||||
or "Max retries exceeded" in text
|
||||
):
|
||||
lower = text.lower()
|
||||
if "proxyerror" in lower or "unable to connect to proxy" in lower:
|
||||
network_reason = "代理连接失败"
|
||||
elif "timed out" in lower or "timeouterror" in lower:
|
||||
network_reason = "网络或代理请求超时"
|
||||
elif "ssl" in lower:
|
||||
network_reason = "SSL 安全连接失败"
|
||||
elif "max retries exceeded" in lower:
|
||||
network_reason = "网络连接失败(重试次数超限)"
|
||||
else:
|
||||
network_reason = "网络连接异常"
|
||||
if _HTTP_POOL_RE.search(text):
|
||||
text = _HTTP_POOL_RE.sub(network_reason, text)
|
||||
else:
|
||||
text = text.replace("Max retries exceeded", "网络连接失败(重试次数超限)")
|
||||
|
||||
text = text.replace("Read timed out", "网络读取超时")
|
||||
return text
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class QuotaDecision:
|
||||
allowed: bool
|
||||
reason: str = ""
|
||||
attempt: LoginAttempt | None = None
|
||||
category: str = ""
|
||||
|
||||
|
||||
def _bucket(now: datetime | None = None) -> tuple[date, int]:
|
||||
@@ -620,7 +711,12 @@ def reserve_login_attempt(
|
||||
if _category_daily_total(db, quota_day, resolved_category) >= _category_limit(
|
||||
setting, resolved_category
|
||||
):
|
||||
return QuotaDecision(False, reason=f"{resolved_category} 今日登录预算已用完")
|
||||
label = category_label(resolved_category)
|
||||
return QuotaDecision(
|
||||
False,
|
||||
reason=f"{label}今日登录预算已用完",
|
||||
category=resolved_category,
|
||||
)
|
||||
|
||||
attempt = LoginAttempt(
|
||||
account_id=int(account.id),
|
||||
@@ -707,7 +803,9 @@ def cleanup_orphan_login_attempts(
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AUTOMATED_CATEGORIES",
|
||||
"CATEGORY_ACCOUNT_CHECK",
|
||||
"CATEGORY_LABELS",
|
||||
"CATEGORY_LEASE_REFRESH",
|
||||
"CATEGORY_MANUAL",
|
||||
"CATEGORY_ONBOARDING",
|
||||
@@ -715,10 +813,13 @@ __all__ = [
|
||||
"CATEGORY_RELOGIN_ORDINARY",
|
||||
"CATEGORY_RELOGIN_PROTECTED",
|
||||
"QuotaDecision",
|
||||
"category_label",
|
||||
"classify_login_category",
|
||||
"cleanup_orphan_login_attempts",
|
||||
"finish_login_attempt",
|
||||
"get_login_quota_usage_summary",
|
||||
"humanize_login_message",
|
||||
"infer_category_from_message",
|
||||
"login_concurrency_limit",
|
||||
"reserve_login_attempt",
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user