优化(账号自动化): 完善受保护账号重登筛选与登录配额分配
This commit is contained in:
@@ -5,11 +5,13 @@ from __future__ import annotations
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy import and_, case, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....models import Account, AutomationJob, LoginTask
|
||||
from ...account_lifecycle import MANUAL_KINDS, MANUAL_STATES, STATUS_MANUAL
|
||||
from ...account_protection_service import load_protection_snapshot
|
||||
from ...account_query_filters import protected_relogin_eligible_filter
|
||||
from ...login_automation import run_login_batch_with_fallback, system_user_id
|
||||
|
||||
JOB_KEY = "account_onboarding"
|
||||
@@ -26,50 +28,61 @@ def _in_flight_login_exists():
|
||||
)
|
||||
|
||||
|
||||
def _onboarding_eligibility_filter(db: Session, *, now: datetime | None = None):
|
||||
protection = load_protection_snapshot(db)
|
||||
ordinary = and_(
|
||||
Account.auto_managed.is_(True),
|
||||
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
|
||||
# 缺账号/密码的账号首登必失败,不能占样本名额。
|
||||
Account.username != "",
|
||||
Account.password != "",
|
||||
# 已经判定为极验/凭证问题的普通账号不再自动首登。
|
||||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||||
tuple(sorted(MANUAL_KINDS))
|
||||
),
|
||||
or_(Account.cookie.is_(None), Account.cookie == ""),
|
||||
~_in_flight_login_exists(),
|
||||
)
|
||||
relogin_ids = protection.relogin_ids
|
||||
if not relogin_ids:
|
||||
return ordinary, protection
|
||||
protected = and_(
|
||||
or_(Account.cookie.is_(None), Account.cookie == ""),
|
||||
protected_relogin_eligible_filter(
|
||||
protected_ids=relogin_ids,
|
||||
max_attempts=2,
|
||||
now=now,
|
||||
cookie_operable=True,
|
||||
due_only=True,
|
||||
suppressed_ids=protection.suppressed_relogin_ids,
|
||||
),
|
||||
)
|
||||
return or_(ordinary, protected), protection
|
||||
|
||||
|
||||
def build_select_query(
|
||||
db: Session,
|
||||
job: AutomationJob,
|
||||
*,
|
||||
limit: int | None = None,
|
||||
):
|
||||
"""未登录、自动托管、没有在途登录尝试的账号。"""
|
||||
query = (
|
||||
db.query(Account)
|
||||
.filter(
|
||||
Account.auto_managed.is_(True),
|
||||
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
|
||||
# 缺账号/密码的账号首登必失败,不能占样本名额。
|
||||
Account.username != "",
|
||||
Account.password != "",
|
||||
# 已经判定为极验/凭证问题的账号不再自动首登。
|
||||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||||
tuple(sorted(MANUAL_KINDS))
|
||||
),
|
||||
or_(Account.cookie.is_(None), Account.cookie == ""),
|
||||
~_in_flight_login_exists(),
|
||||
"""未登录、自动托管、没有在途登录尝试的账号(履约保护目标优先)。"""
|
||||
eligibility, protection = _onboarding_eligibility_filter(db)
|
||||
ordering = []
|
||||
if protection.relogin_ids:
|
||||
ordering.append(
|
||||
case((Account.id.in_(protection.relogin_ids), 0), else_=1)
|
||||
)
|
||||
.order_by(Account.id.asc())
|
||||
)
|
||||
ordering.append(Account.id.asc())
|
||||
query = db.query(Account).filter(eligibility).order_by(*ordering)
|
||||
batch = max(1, int(limit if limit is not None else job.batch_size or 20))
|
||||
return query.limit(batch)
|
||||
|
||||
|
||||
def count_pending_onboarding(db: Session) -> int:
|
||||
eligibility, _ = _onboarding_eligibility_filter(db)
|
||||
return int(
|
||||
db.query(func.count(Account.id))
|
||||
.filter(
|
||||
Account.auto_managed.is_(True),
|
||||
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
|
||||
Account.username != "",
|
||||
Account.password != "",
|
||||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||||
tuple(sorted(MANUAL_KINDS))
|
||||
),
|
||||
or_(Account.cookie.is_(None), Account.cookie == ""),
|
||||
~_in_flight_login_exists(),
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
db.query(func.count(Account.id)).filter(eligibility).scalar() or 0
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import case, func, or_
|
||||
from sqlalchemy import case, func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....database import WorkerSessionLocal
|
||||
@@ -45,8 +45,8 @@ from ...account_protection_service import (
|
||||
load_protection_snapshot,
|
||||
)
|
||||
from ...account_query_filters import (
|
||||
automation_account_filter,
|
||||
relogin_failure_kind_filter,
|
||||
quota_day_for,
|
||||
relogin_eligible_account_filter,
|
||||
)
|
||||
from ...account_value import is_high_value_expr, value_tier_expr
|
||||
from ...account_work_queue import (
|
||||
@@ -172,36 +172,16 @@ def _eligible_account_query(
|
||||
due_only: bool,
|
||||
):
|
||||
"""自动重登的账号级准入条件,执行、补货和计数共用同一套语义。"""
|
||||
query = (
|
||||
db.query(Account)
|
||||
.filter(Account.ck_check_status == "invalid")
|
||||
.filter(
|
||||
automation_account_filter(cookie_operable=cookie_operable)
|
||||
)
|
||||
# 停用/归档的账号一律不碰(生命周期状态机,见 account_lifecycle)。
|
||||
.filter(Account.relogin_attempts < max_attempts)
|
||||
# 已判定需要人工的类型不再自动重试。空值用 coalesce 兜住历史值。
|
||||
.filter(
|
||||
relogin_failure_kind_filter(
|
||||
protected_ids=protection.relogin_ids,
|
||||
max_attempts=max_attempts,
|
||||
)
|
||||
return db.query(Account).filter(
|
||||
relogin_eligible_account_filter(
|
||||
protected_ids=protection.relogin_ids,
|
||||
max_attempts=max_attempts,
|
||||
now=now,
|
||||
cookie_operable=cookie_operable,
|
||||
due_only=due_only,
|
||||
suppressed_ids=protection.suppressed_relogin_ids,
|
||||
)
|
||||
)
|
||||
if due_only:
|
||||
query = query.filter(
|
||||
or_(
|
||||
Account.relogin_next_at.is_(None),
|
||||
Account.relogin_next_at <= _cutoff(now),
|
||||
)
|
||||
)
|
||||
if protection.suppressed_relogin_ids:
|
||||
# 保护组可以分别关闭自动重登。账号同时属于任一已开启自动重登的组时,
|
||||
# 仍按允许处理;只有完全被抑制的账号才排除。
|
||||
query = query.filter(
|
||||
~Account.id.in_(protection.suppressed_relogin_ids)
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def _pending_relogin_work_count(
|
||||
@@ -436,6 +416,7 @@ def settle_fresh_results(
|
||||
now: datetime,
|
||||
max_attempts: int = 2,
|
||||
expected_account_ids: list[int] | tuple[int, ...] | None = None,
|
||||
protected_captcha_retry_ids: set[int] | frozenset[int] | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""在**新会话(新事务)**里读回批次结果并结算。
|
||||
|
||||
@@ -467,6 +448,7 @@ def settle_fresh_results(
|
||||
settle_account_ids,
|
||||
now=now,
|
||||
max_attempts=max_attempts,
|
||||
protected_captcha_retry_ids=protected_captcha_retry_ids,
|
||||
)
|
||||
session.commit()
|
||||
return counters
|
||||
@@ -531,13 +513,16 @@ def evaluate_failure_circuit(
|
||||
counters: dict[str, int],
|
||||
config: dict[str, Any],
|
||||
) -> tuple[bool, int, float]:
|
||||
"""评估硬失败率;预算跳过和邮箱配额满都不属于真实失败样本。"""
|
||||
"""评估硬失败率;预算跳过、邮箱配额满与保护账号极验二次重试不触发全局熔断。"""
|
||||
scanned = max(0, int(counters.get("scanned", 0) or 0))
|
||||
skipped = max(0, int(counters.get("skipped", 0) or 0))
|
||||
attempted = max(0, scanned - skipped)
|
||||
protected_captcha_failures = max(
|
||||
0, int(counters.get("protected_captcha_failures", 0) or 0)
|
||||
)
|
||||
attempted = max(0, scanned - skipped - protected_captcha_failures)
|
||||
invalid = max(0, int(counters.get("invalid", 0) or 0))
|
||||
email_quota = max(0, int(counters.get("email_quota", 0) or 0))
|
||||
hard_failures = max(0, invalid - email_quota)
|
||||
hard_failures = max(0, invalid - email_quota - protected_captcha_failures)
|
||||
minimum = max(
|
||||
1,
|
||||
int(
|
||||
@@ -756,7 +741,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
now,
|
||||
max_attempts=max_attempts,
|
||||
protection=protection,
|
||||
limit=adaptive.batch_size,
|
||||
limit=max(adaptive.batch_size, len(protection.relogin_ids)),
|
||||
account_ids_filter=protection.relogin_ids,
|
||||
)
|
||||
work_items = _claim_relogin_work(
|
||||
@@ -796,7 +781,6 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
"skipped": 0,
|
||||
"message": "没有到期的自动重登工作项",
|
||||
}
|
||||
db.commit()
|
||||
claimed_account_ids = [int(item.account_id) for item in work_items]
|
||||
account_map = {
|
||||
int(account.id): account
|
||||
@@ -809,6 +793,20 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
for account_id in claimed_account_ids
|
||||
if account_id in account_map
|
||||
]
|
||||
pre_captcha_retry_ids = frozenset(
|
||||
int(account.id)
|
||||
for account in accounts
|
||||
if int(account.id) in protection.relogin_ids
|
||||
and (account.relogin_failure_kind or "") == "captcha"
|
||||
)
|
||||
_reconcile_protected_new_day_attempts(
|
||||
db,
|
||||
accounts=accounts,
|
||||
protection=protection,
|
||||
max_attempts=max_attempts,
|
||||
now=now,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# 调度单位是**账号**(CK 在账号上);登录记录只是这次尝试的历史。
|
||||
account_ids = [account.id for account in accounts]
|
||||
@@ -845,6 +843,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
now=now,
|
||||
max_attempts=max_attempts,
|
||||
expected_account_ids=account_ids,
|
||||
protected_captcha_retry_ids=pre_captcha_retry_ids,
|
||||
)
|
||||
# 取码失败不再切 iframe 重跑:换通道 = 重新发信,斗鱼验证码是攒批投递的,
|
||||
# 重发会把邮件队列压更长、flush 更晚(实测每账号发信量 1.5 -> 3.3 封后,
|
||||
@@ -918,6 +917,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
"manual": counters["manual"],
|
||||
"retry": counters["retry"],
|
||||
"email_quota": counters["email_quota"],
|
||||
"protected_captcha_failures": counters.get("protected_captcha_failures", 0),
|
||||
"fallback_batch_id": fallback_batch_id,
|
||||
"fallback_success": fallback_success,
|
||||
"hard_failures": hard_failures,
|
||||
@@ -936,6 +936,42 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _reconcile_protected_new_day_attempts(
|
||||
db: Session,
|
||||
*,
|
||||
accounts: list[Account],
|
||||
protection: ProtectionSnapshot,
|
||||
max_attempts: int,
|
||||
now: datetime,
|
||||
) -> int:
|
||||
"""新自然日重新恢复前日耗尽次数的保护账号前,把账号累计计数对齐到今日已用次数。"""
|
||||
cap = max(1, int(max_attempts))
|
||||
quota_day = quota_day_for(now)
|
||||
reset_count = 0
|
||||
for account in accounts:
|
||||
if int(account.id) not in protection.relogin_ids:
|
||||
continue
|
||||
if int(account.relogin_attempts or 0) < cap:
|
||||
continue
|
||||
attempts_today = int(
|
||||
db.query(func.count(LoginAttempt.id))
|
||||
.filter(
|
||||
LoginAttempt.account_id == account.id,
|
||||
LoginAttempt.quota_day == quota_day,
|
||||
LoginAttempt.status != "skipped",
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
if attempts_today >= cap:
|
||||
continue
|
||||
account.relogin_attempts = attempts_today
|
||||
account.relogin_next_at = None
|
||||
sync_status(db, account, occurred_at=now)
|
||||
reset_count += 1
|
||||
return reset_count
|
||||
|
||||
|
||||
def settle_results(
|
||||
db: Session,
|
||||
fresh: dict[int, tuple[Account, LoginTask]],
|
||||
@@ -943,6 +979,7 @@ def settle_results(
|
||||
*,
|
||||
now: datetime,
|
||||
max_attempts: int = 2,
|
||||
protected_captcha_retry_ids: set[int] | frozenset[int] | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""批次跑完后结算:成功的清零,失败的按分型决定重试还是转人工。
|
||||
|
||||
@@ -964,8 +1001,10 @@ def settle_results(
|
||||
"retry": 0,
|
||||
"email_quota": 0,
|
||||
"skipped": 0,
|
||||
"protected_captcha_failures": 0,
|
||||
}
|
||||
protected_ids = load_protection_snapshot(db).relogin_ids
|
||||
pre_captcha_ids = frozenset(int(value) for value in (protected_captcha_retry_ids or ()))
|
||||
for account_id in account_ids:
|
||||
entry = fresh.get(account_id)
|
||||
if entry is None:
|
||||
@@ -1009,6 +1048,8 @@ def settle_results(
|
||||
|
||||
counters["invalid"] += 1
|
||||
kind = classify_failure(task.attempt_message)
|
||||
if kind == "captcha" and int(account.id) in pre_captcha_ids:
|
||||
counters["protected_captcha_failures"] += 1
|
||||
account.relogin_failure_kind = kind
|
||||
account.relogin_last_error = (task.attempt_message or "")[:500]
|
||||
account.relogin_attempts = int(account.relogin_attempts or 0) + 1
|
||||
|
||||
Reference in New Issue
Block a user