优化(账号自动化): 完善受保护账号重登筛选与登录配额分配
This commit is contained in:
@@ -166,3 +166,37 @@ def test_onboarding_job_is_registered_but_default_off():
|
||||
assert spec.default_enabled is False
|
||||
assert "首次登录" in spec.title
|
||||
assert spec.batch_size == 20
|
||||
|
||||
|
||||
def test_selector_prioritizes_protected_missing_cookie_and_allows_captcha(db):
|
||||
from web.backend.models import PlatformFulfillmentTask
|
||||
|
||||
ordinary = _account("onboarding-ordinary-first")
|
||||
protected_plain = _account("onboarding-protected-plain")
|
||||
protected_captcha = _account(
|
||||
"onboarding-protected-captcha",
|
||||
relogin_failure_kind="captcha",
|
||||
)
|
||||
db.add_all([ordinary, protected_plain, protected_captcha])
|
||||
db.flush()
|
||||
for index, acc in enumerate((protected_plain, protected_captcha)):
|
||||
db.add(
|
||||
PlatformFulfillmentTask(
|
||||
source_order_id=f"onb-order-{index}",
|
||||
source_order_item_id=f"onb-item-{index}",
|
||||
sale_mode="presale",
|
||||
account_id=acc.id,
|
||||
binding_status="bound",
|
||||
execution_status="bound",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
rows = job.build_select_query(db, _job()).all()
|
||||
|
||||
assert [row.id for row in rows] == [
|
||||
protected_plain.id,
|
||||
protected_captcha.id,
|
||||
ordinary.id,
|
||||
]
|
||||
assert job.count_pending_onboarding(db) == 3
|
||||
|
||||
@@ -707,3 +707,80 @@ def test_p2_high_value_claims_before_aged_p3_ordinary_while_p0_wins_all(db):
|
||||
)
|
||||
|
||||
assert [item.account_id for item in claimed] == [p0.id, p2.id, p3.id]
|
||||
|
||||
|
||||
def test_protected_missing_cookie_and_prior_day_exhausted_reserve_p0_quota(db):
|
||||
from web.backend.models import LoginAttempt, LoginQuotaSetting
|
||||
from web.backend.services.login_quota_service import (
|
||||
CATEGORY_RELOGIN_PROTECTED,
|
||||
get_login_quota_usage_summary,
|
||||
reserve_login_attempt,
|
||||
)
|
||||
|
||||
no_cookie = _account("p0-nocookie", ck_status="")
|
||||
no_cookie.cookie = ""
|
||||
no_cookie.cookie_updated_at = None
|
||||
no_cookie.status = "imported"
|
||||
|
||||
error_ck = _account("p0-error", ck_status="error")
|
||||
|
||||
prior_email = _account("p0-prior-email", ck_status="invalid")
|
||||
prior_email.relogin_attempts = 2
|
||||
prior_email.relogin_failure_kind = "email_code"
|
||||
prior_email.status = "manual"
|
||||
|
||||
credential_broken = _account("p0-cred", ck_status="invalid")
|
||||
credential_broken.relogin_attempts = 2
|
||||
credential_broken.relogin_failure_kind = "credential"
|
||||
credential_broken.status = "manual"
|
||||
|
||||
db.add_all([no_cookie, error_ck, prior_email, credential_broken])
|
||||
db.flush()
|
||||
for acc in (no_cookie, error_ck, prior_email, credential_broken):
|
||||
db.add(_presale_task(acc))
|
||||
db.add(_health_job())
|
||||
db.add(
|
||||
LoginQuotaSetting(
|
||||
id=1,
|
||||
daily_attempt_limit=100,
|
||||
hourly_attempt_limit=50,
|
||||
per_account_daily_limit=2,
|
||||
relogin_protected_daily_limit=50,
|
||||
enabled=True,
|
||||
)
|
||||
)
|
||||
from web.backend.services.account_query_filters import quota_day_for
|
||||
|
||||
yesterday = quota_day_for(NOW - timedelta(days=1))
|
||||
for acc in (prior_email, credential_broken):
|
||||
db.add(
|
||||
LoginAttempt(
|
||||
account_id=acc.id,
|
||||
batch_id="prev-day",
|
||||
category=CATEGORY_RELOGIN_PROTECTED,
|
||||
trigger_source="automation",
|
||||
started_at=NOW - timedelta(days=1),
|
||||
finished_at=NOW - timedelta(days=1),
|
||||
status="failed",
|
||||
failure_kind=acc.relogin_failure_kind,
|
||||
quota_day=yesterday,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
summary = get_login_quota_usage_summary(db, now=NOW)
|
||||
by_cat = {row["category"]: row for row in summary["categories"]}
|
||||
assert by_cat[CATEGORY_RELOGIN_PROTECTED]["pending"] == 3
|
||||
|
||||
decision = reserve_login_attempt(
|
||||
db,
|
||||
account=no_cookie,
|
||||
mode="login",
|
||||
trigger_source="automation",
|
||||
batch_id="b-prot-login",
|
||||
created_by=None,
|
||||
now=NOW,
|
||||
)
|
||||
assert decision.allowed
|
||||
assert decision.attempt is not None
|
||||
assert decision.attempt.category == CATEGORY_RELOGIN_PROTECTED
|
||||
|
||||
@@ -645,6 +645,105 @@ class TestSelection(_Base):
|
||||
ids = self._ids(job)
|
||||
assert ids == [both.id, one_suit.id, plain.id]
|
||||
|
||||
def test_protected_missing_cookie_and_error_ck_are_selected_and_claimed(self):
|
||||
job = self.job(batch_size=10)
|
||||
no_cookie_plain = self.protect(
|
||||
self.make_account("prot-no-ck", cookie="", ck_check_status="")
|
||||
)
|
||||
no_cookie_captcha = self.protect(
|
||||
self.make_account(
|
||||
"prot-no-ck-cap",
|
||||
cookie="",
|
||||
ck_check_status="",
|
||||
relogin_failure_kind="captcha",
|
||||
)
|
||||
)
|
||||
error_ck = self.protect(
|
||||
self.make_account("prot-error-ck", ck_check_status="error")
|
||||
)
|
||||
unchecked_with_cookie = self.protect(
|
||||
self.make_account("prot-unchecked-with-ck", ck_check_status="")
|
||||
)
|
||||
ordinary_no_cookie = self.make_account(
|
||||
"ordinary-no-ck", cookie="", ck_check_status=""
|
||||
)
|
||||
|
||||
ids = self._ids(job)
|
||||
|
||||
assert no_cookie_plain.id in ids
|
||||
assert no_cookie_captcha.id in ids
|
||||
assert error_ck.id in ids
|
||||
assert unchecked_with_cookie.id not in ids
|
||||
assert ordinary_no_cookie.id not in ids
|
||||
|
||||
def test_protected_prior_day_exhausted_recovers_on_new_day_and_caps_same_day(self):
|
||||
from web.backend.services.account_query_filters import quota_day_for
|
||||
|
||||
job = self.job(batch_size=10)
|
||||
now = datetime.now(UTC)
|
||||
yesterday = quota_day_for(now - timedelta(days=1))
|
||||
today = quota_day_for(now)
|
||||
|
||||
email_recover = self.protect(
|
||||
self.make_account(
|
||||
"prot-prior-email",
|
||||
relogin_attempts=2,
|
||||
relogin_failure_kind="email_code",
|
||||
)
|
||||
)
|
||||
same_day_exhausted = self.protect(
|
||||
self.make_account(
|
||||
"prot-same-day-exhausted",
|
||||
relogin_attempts=2,
|
||||
relogin_failure_kind="email_code",
|
||||
)
|
||||
)
|
||||
credential_broken = self.protect(
|
||||
self.make_account(
|
||||
"prot-credential",
|
||||
relogin_attempts=2,
|
||||
relogin_failure_kind="credential",
|
||||
)
|
||||
)
|
||||
for idx, (acc, qday) in enumerate(
|
||||
[
|
||||
(email_recover, yesterday),
|
||||
(credential_broken, yesterday),
|
||||
(same_day_exhausted, today),
|
||||
(same_day_exhausted, today),
|
||||
]
|
||||
):
|
||||
self.session.add(
|
||||
LoginAttempt(
|
||||
account_id=acc.id,
|
||||
batch_id=f"hist-{idx}",
|
||||
category="relogin_protected",
|
||||
trigger_source="automation",
|
||||
started_at=now - timedelta(days=1 if qday == yesterday else 0),
|
||||
finished_at=now - timedelta(days=1 if qday == yesterday else 0),
|
||||
status="failed",
|
||||
failure_kind=acc.relogin_failure_kind,
|
||||
quota_day=qday,
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
ids = self._ids(job)
|
||||
assert email_recover.id in ids
|
||||
assert same_day_exhausted.id not in ids
|
||||
assert credential_broken.id not in ids
|
||||
|
||||
reset = ck_relogin._reconcile_protected_new_day_attempts(
|
||||
self.session,
|
||||
accounts=[email_recover],
|
||||
protection=load_protection_snapshot(self.session),
|
||||
max_attempts=2,
|
||||
now=now,
|
||||
)
|
||||
assert reset == 1
|
||||
assert email_recover.relogin_attempts == 0
|
||||
assert email_recover.status == "invalid"
|
||||
|
||||
|
||||
class TestSettlement(_Base):
|
||||
"""结算:成功清零;失败按分型决定重试还是转人工。
|
||||
@@ -1078,3 +1177,33 @@ class TestSettlementVisibility(_Base):
|
||||
assert counters["valid"] == 1 and counters["invalid"] == 0
|
||||
assert account.relogin_failure_kind == ""
|
||||
assert account.relogin_next_at is None
|
||||
|
||||
def test_protected_captcha_retry_failures_do_not_trip_global_circuit(self):
|
||||
protected = self.protect(
|
||||
self.make_account("prot-cap-retry", relogin_failure_kind="captcha")
|
||||
)
|
||||
ordinary = self.make_account("ord-ok")
|
||||
fail_task = self.make_attempt(
|
||||
protected,
|
||||
attempt_status="failed",
|
||||
attempt_message="极验验证失败: slide",
|
||||
)
|
||||
ok_task = self.make_attempt(ordinary, attempt_status="success")
|
||||
now = datetime.now(UTC)
|
||||
|
||||
counters = ck_relogin.settle_results(
|
||||
self.session,
|
||||
{protected.id: (protected, fail_task), ordinary.id: (ordinary, ok_task)},
|
||||
[protected.id, ordinary.id],
|
||||
now=now,
|
||||
max_attempts=2,
|
||||
protected_captcha_retry_ids={protected.id},
|
||||
)
|
||||
paused, hard_failures, _ = ck_relogin.evaluate_failure_circuit(
|
||||
counters,
|
||||
{"failure_pause_min_scanned": 1, "failure_pause_ratio": 40},
|
||||
)
|
||||
|
||||
assert counters["protected_captcha_failures"] == 1
|
||||
assert hard_failures == 0
|
||||
assert paused is False
|
||||
|
||||
@@ -171,3 +171,38 @@ def test_protected_inventory_is_allocated_once_within_daily_budget(db):
|
||||
assert recommended["relogin_protected_daily_limit"] >= 50
|
||||
assert recommended["lease_refresh_daily_limit"] >= 50
|
||||
assert allocated <= recommended["daily_attempt_limit"]
|
||||
|
||||
|
||||
def test_protected_without_cookie_and_captcha_included_in_protected_backlog(db):
|
||||
now = datetime.now(UTC)
|
||||
missing_cookie = _account(
|
||||
"budget-prot-nocookie",
|
||||
cookie="",
|
||||
ck_check_status="",
|
||||
status="imported",
|
||||
)
|
||||
captcha_account = _account(
|
||||
"budget-prot-captcha",
|
||||
ck_check_status="invalid",
|
||||
status="manual",
|
||||
)
|
||||
captcha_account.relogin_failure_kind = "captcha"
|
||||
db.add_all([missing_cookie, captcha_account])
|
||||
db.flush()
|
||||
for idx, acc in enumerate((missing_cookie, captcha_account)):
|
||||
db.add(
|
||||
PlatformFulfillmentTask(
|
||||
source_order_id=f"budget-prot-order-{idx}",
|
||||
source_order_item_id=f"budget-prot-item-{idx}",
|
||||
sale_mode="presale",
|
||||
account_id=acc.id,
|
||||
binding_status="bound",
|
||||
execution_status="bound",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
recommendation = recommend_login_budget(db, now=now)
|
||||
|
||||
assert recommendation["basis"]["protected_invalid_backlog"] == 2
|
||||
assert recommendation["recommended"]["relogin_protected_daily_limit"] >= 100
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import and_, func, or_, select
|
||||
|
||||
@@ -12,6 +13,7 @@ from ..models import (
|
||||
AccountEvent,
|
||||
AccountLease,
|
||||
DouyuExternalOrder,
|
||||
LoginAttempt,
|
||||
LoginTask,
|
||||
User,
|
||||
)
|
||||
@@ -34,6 +36,31 @@ ACTIVE_COLLAB_STATUSES: tuple[str, ...] = (
|
||||
POOL_OWNER_ROLES: tuple[str, ...] = ("super_admin", "operation", "support")
|
||||
CK_FRESH_SECONDS = 24 * 60 * 60
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = ("pending", "running")
|
||||
BUSINESS_TZ = ZoneInfo("Asia/Shanghai")
|
||||
PROTECTED_NON_RECOVERABLE_KINDS: tuple[str, ...] = tuple(
|
||||
sorted(kind for kind in MANUAL_KINDS if kind != "captcha")
|
||||
)
|
||||
|
||||
|
||||
def quota_day_for(now: datetime | None = None):
|
||||
"""按业务时区(Asia/Shanghai)换算自然日,与登录预算分桶一致。"""
|
||||
moment = now or datetime.now(UTC)
|
||||
aware = moment if moment.tzinfo else moment.replace(tzinfo=UTC)
|
||||
return aware.astimezone(BUSINESS_TZ).date()
|
||||
|
||||
|
||||
def in_flight_login_exists():
|
||||
"""SQL 子查询:账号是否存在在途登录或检测任务。"""
|
||||
return (
|
||||
select(LoginTask.id)
|
||||
.where(LoginTask.account_id == Account.id)
|
||||
.where(
|
||||
func.coalesce(LoginTask.attempt_status, "").in_(
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
)
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
|
||||
|
||||
def pool_owner_ids():
|
||||
@@ -54,17 +81,7 @@ def cookie_holding_filter():
|
||||
|
||||
def cookie_operable_filter():
|
||||
"""持有 CK,且该账号没有在途登录/检测尝试。"""
|
||||
in_flight = (
|
||||
select(LoginTask.id)
|
||||
.where(LoginTask.account_id == Account.id)
|
||||
.where(
|
||||
func.coalesce(LoginTask.attempt_status, "").in_(
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
)
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
return and_(cookie_holding_filter(), ~in_flight)
|
||||
return and_(cookie_holding_filter(), ~in_flight_login_exists())
|
||||
|
||||
|
||||
def valid_ck_filter(*, checked_since: datetime | None = None):
|
||||
@@ -119,6 +136,126 @@ def relogin_failure_kind_filter(
|
||||
)
|
||||
|
||||
|
||||
def protected_relogin_eligible_filter(
|
||||
*,
|
||||
protected_ids: set[int] | frozenset[int],
|
||||
max_attempts: int,
|
||||
now: datetime | None = None,
|
||||
cookie_operable: bool = True,
|
||||
due_only: bool = True,
|
||||
suppressed_ids: set[int] | frozenset[int] = frozenset(),
|
||||
):
|
||||
"""履约保护账号(P0)自动恢复准入条件。
|
||||
|
||||
覆盖 CK 失效(invalid)、检测异常(error)和缺 CK(without_cookie),
|
||||
仅排除永久人工问题(credential / must_bind_mobile);昨日已达上限的保护账号
|
||||
在进入新自然日后重新获得当日尝试额度。
|
||||
"""
|
||||
ids = sorted({int(value) for value in protected_ids})
|
||||
if not ids:
|
||||
return Account.id == -1
|
||||
cap = max(1, int(max_attempts))
|
||||
moment = now or datetime.now(UTC)
|
||||
quota_day = quota_day_for(moment)
|
||||
attempts_today = (
|
||||
select(func.count(LoginAttempt.id))
|
||||
.where(
|
||||
LoginAttempt.account_id == Account.id,
|
||||
LoginAttempt.quota_day == quota_day,
|
||||
LoginAttempt.status != "skipped",
|
||||
)
|
||||
.correlate(Account)
|
||||
.scalar_subquery()
|
||||
)
|
||||
has_prior_day_attempt = (
|
||||
select(LoginAttempt.id)
|
||||
.where(
|
||||
LoginAttempt.account_id == Account.id,
|
||||
LoginAttempt.quota_day < quota_day,
|
||||
LoginAttempt.status != "skipped",
|
||||
)
|
||||
.correlate(Account)
|
||||
.exists()
|
||||
)
|
||||
filters = [
|
||||
Account.id.in_(ids),
|
||||
automatable_account_filter(),
|
||||
Account.username != "",
|
||||
Account.password != "",
|
||||
or_(
|
||||
Account.ck_check_status.in_(("invalid", "error")),
|
||||
Account.cookie.is_(None),
|
||||
Account.cookie == "",
|
||||
),
|
||||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||||
PROTECTED_NON_RECOVERABLE_KINDS
|
||||
),
|
||||
attempts_today < cap,
|
||||
or_(Account.relogin_attempts < cap, has_prior_day_attempt),
|
||||
]
|
||||
if cookie_operable:
|
||||
filters.append(~in_flight_login_exists())
|
||||
if due_only:
|
||||
filters.append(
|
||||
or_(
|
||||
Account.relogin_next_at.is_(None),
|
||||
Account.relogin_next_at <= moment,
|
||||
)
|
||||
)
|
||||
suppressed = sorted({int(value) for value in suppressed_ids})
|
||||
if suppressed:
|
||||
filters.append(~Account.id.in_(suppressed))
|
||||
return and_(*filters)
|
||||
|
||||
|
||||
def relogin_eligible_account_filter(
|
||||
*,
|
||||
protected_ids: set[int] | frozenset[int],
|
||||
max_attempts: int,
|
||||
now: datetime | None = None,
|
||||
cookie_operable: bool = True,
|
||||
due_only: bool = True,
|
||||
suppressed_ids: set[int] | frozenset[int] = frozenset(),
|
||||
):
|
||||
"""CK 自动重登全库候选准入条件(P0 履约保护 + 普通/高价值库存)。"""
|
||||
cap = max(1, int(max_attempts))
|
||||
moment = now or datetime.now(UTC)
|
||||
ordinary_filters = [
|
||||
Account.ck_check_status == "invalid",
|
||||
automation_account_filter(cookie_operable=cookie_operable),
|
||||
Account.relogin_attempts < cap,
|
||||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||||
tuple(sorted(MANUAL_KINDS))
|
||||
),
|
||||
]
|
||||
if due_only:
|
||||
ordinary_filters.append(
|
||||
or_(
|
||||
Account.relogin_next_at.is_(None),
|
||||
Account.relogin_next_at <= moment,
|
||||
)
|
||||
)
|
||||
suppressed = sorted({int(value) for value in suppressed_ids})
|
||||
if suppressed:
|
||||
ordinary_filters.append(~Account.id.in_(suppressed))
|
||||
ordinary = and_(*ordinary_filters)
|
||||
|
||||
ids = sorted({int(value) for value in protected_ids})
|
||||
if not ids:
|
||||
return ordinary
|
||||
return or_(
|
||||
and_(~Account.id.in_(ids), ordinary),
|
||||
protected_relogin_eligible_filter(
|
||||
protected_ids=ids,
|
||||
max_attempts=cap,
|
||||
now=moment,
|
||||
cookie_operable=cookie_operable,
|
||||
due_only=due_only,
|
||||
suppressed_ids=suppressed,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def assigned_to_pool_filter():
|
||||
return or_(
|
||||
Account.assigned_to.is_(None),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,6 +12,7 @@ from sqlalchemy.orm import Session
|
||||
from ..models import Account, LoginAttempt, LoginQuotaSetting
|
||||
from .account_lifecycle import MANUAL_KINDS, MANUAL_STATES
|
||||
from .account_protection_service import load_protection_snapshot
|
||||
from .account_query_filters import protected_relogin_eligible_filter
|
||||
from .account_value import is_high_value_expr
|
||||
|
||||
CK_AVERAGE_LIFETIME_DAYS = 7.38
|
||||
@@ -164,7 +165,19 @@ def recommend_login_budget(
|
||||
valid_query.filter(Account.id.in_(protected_ids)).count() or 0
|
||||
)
|
||||
protected_invalid = int(
|
||||
invalid_query.filter(Account.id.in_(protected_ids)).count() or 0
|
||||
db.query(func.count(Account.id))
|
||||
.filter(
|
||||
protected_relogin_eligible_filter(
|
||||
protected_ids=protected_ids,
|
||||
max_attempts=2,
|
||||
now=moment,
|
||||
cookie_operable=False,
|
||||
due_only=False,
|
||||
suppressed_ids=protection.suppressed_relogin_ids,
|
||||
)
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
nonprotected_valid_high = int(
|
||||
_count_high_value(
|
||||
@@ -234,10 +247,8 @@ def recommend_login_budget(
|
||||
nonprotected_relogin_attempts - relogin_high_limit,
|
||||
)
|
||||
relogin_protected_limit = max(
|
||||
50,
|
||||
math.ceil(
|
||||
(protected_invalid / RELOGIN_RECOVERY_DAYS) / effective_rate
|
||||
),
|
||||
100,
|
||||
math.ceil((protected_invalid * 2) / effective_rate),
|
||||
)
|
||||
lease_refresh_limit = max(
|
||||
50,
|
||||
|
||||
@@ -20,7 +20,7 @@ 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,
|
||||
relogin_failure_kind_filter,
|
||||
protected_relogin_eligible_filter,
|
||||
)
|
||||
from .account_value import is_high_value_account, is_high_value_expr
|
||||
from .douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
@@ -102,6 +102,8 @@ def classify_login_category(
|
||||
or not account.cookie
|
||||
or account.cookie_updated_at is None
|
||||
):
|
||||
if protected and trigger_source == "automation":
|
||||
return CATEGORY_RELOGIN_PROTECTED
|
||||
return CATEGORY_ONBOARDING
|
||||
return CATEGORY_MANUAL
|
||||
|
||||
@@ -261,21 +263,15 @@ def _pending_protected_invalid_query(
|
||||
now: datetime,
|
||||
max_attempts: int = 2,
|
||||
):
|
||||
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),
|
||||
relogin_failure_kind_filter(
|
||||
protected_ids=relogin_ids,
|
||||
protected_relogin_eligible_filter(
|
||||
protected_ids=protection.relogin_ids,
|
||||
max_attempts=max_attempts,
|
||||
),
|
||||
or_(
|
||||
Account.relogin_next_at.is_(None),
|
||||
Account.relogin_next_at <= now,
|
||||
),
|
||||
now=now,
|
||||
cookie_operable=True,
|
||||
due_only=True,
|
||||
suppressed_ids=protection.suppressed_relogin_ids,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -524,7 +520,7 @@ def reserve_login_attempt(
|
||||
setting = _setting(db)
|
||||
protection = None
|
||||
is_protected = False
|
||||
if mode == "relogin" and not category:
|
||||
if not category and (mode == "relogin" or trigger_source == "automation"):
|
||||
protection = load_protection_snapshot(db)
|
||||
is_protected = int(account.id) in protection.relogin_ids
|
||||
resolved_category = classify_login_category(
|
||||
|
||||
Reference in New Issue
Block a user