优化(登录预算与任务): 建议上限封顶2000、错误中文化及补全跳过触发来源
This commit is contained in:
+21
-5
@@ -838,12 +838,21 @@ class DouyuLogin:
|
|||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
err_str = str(e)
|
err_str = str(e)
|
||||||
|
lower_err = err_str.lower()
|
||||||
|
if "proxyerror" in lower_err or "unable to connect to proxy" in lower_err:
|
||||||
|
friendly_err = "代理连接失败"
|
||||||
|
elif "timed out" in lower_err or "timeouterror" in lower_err:
|
||||||
|
friendly_err = "网络或代理请求超时"
|
||||||
|
elif "max retries exceeded" in lower_err:
|
||||||
|
friendly_err = "网络连接失败(重试次数超限)"
|
||||||
|
else:
|
||||||
|
friendly_err = self._truncate_error(err_str)
|
||||||
# 所有网络/代理异常都直接上抛,由 login 换新代理
|
# 所有网络/代理异常都直接上抛,由 login 换新代理
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"极验验证异常: {self._truncate_error(err_str)},回到 login 换新代理"
|
f"极验验证异常: {self._truncate_error(err_str)},回到 login 换新代理"
|
||||||
)
|
)
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"极验验证异常: {self._truncate_error(err_str)}"
|
f"极验验证异常: {friendly_err}"
|
||||||
) from e
|
) from e
|
||||||
|
|
||||||
def _solve_slide(
|
def _solve_slide(
|
||||||
@@ -877,10 +886,17 @@ class DouyuLogin:
|
|||||||
validate = validate or str(result.get("validate") or "")
|
validate = validate or str(result.get("validate") or "")
|
||||||
success = success or result.get("success") == 1
|
success = success or result.get("success") == 1
|
||||||
if not success or not validate:
|
if not success or not validate:
|
||||||
message = (
|
raw_message = (
|
||||||
result.get("message") if isinstance(result, dict) else "slide 验证失败"
|
result.get("message") if isinstance(result, dict) else ""
|
||||||
) or "slide 验证失败"
|
) or ""
|
||||||
raise ValueError(f"极验 slide 验证失败: {message}")
|
normalized = str(raw_message).strip().lower()
|
||||||
|
if normalized == "forbidden":
|
||||||
|
message = "触发风控拦截(forbidden)"
|
||||||
|
elif normalized == "fail":
|
||||||
|
message = "滑块未通过"
|
||||||
|
else:
|
||||||
|
message = str(raw_message or "滑块验证失败")
|
||||||
|
raise ValueError(f"极验滑块验证失败: {message}")
|
||||||
if use_challenge != challenge:
|
if use_challenge != challenge:
|
||||||
logger.info(
|
logger.info(
|
||||||
"极验 slide 换发新 challenge: 旧={}... 新={}...",
|
"极验 slide 换发新 challenge: 旧={}... 新={}...",
|
||||||
|
|||||||
@@ -206,3 +206,72 @@ def test_protected_without_cookie_and_captcha_included_in_protected_backlog(db):
|
|||||||
|
|
||||||
assert recommendation["basis"]["protected_invalid_backlog"] == 2
|
assert recommendation["basis"]["protected_invalid_backlog"] == 2
|
||||||
assert recommendation["recommended"]["relogin_protected_daily_limit"] >= 100
|
assert recommendation["recommended"]["relogin_protected_daily_limit"] >= 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_large_inventory_caps_daily_budget_at_2000_and_preserves_priority_order(db):
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
accounts = [
|
||||||
|
*[
|
||||||
|
_account(f"large-valid-ordinary-{i}", ck_check_status="valid", status="active")
|
||||||
|
for i in range(600)
|
||||||
|
],
|
||||||
|
*[
|
||||||
|
_account(
|
||||||
|
f"large-invalid-high-{i}",
|
||||||
|
points=400,
|
||||||
|
ck_check_status="invalid",
|
||||||
|
status="invalid",
|
||||||
|
)
|
||||||
|
for i in range(400)
|
||||||
|
],
|
||||||
|
*[
|
||||||
|
_account(f"large-invalid-ord-{i}", ck_check_status="invalid", status="invalid")
|
||||||
|
for i in range(900)
|
||||||
|
],
|
||||||
|
*[
|
||||||
|
_account(
|
||||||
|
f"large-imported-{i}",
|
||||||
|
cookie="",
|
||||||
|
ck_check_status="",
|
||||||
|
status="imported",
|
||||||
|
)
|
||||||
|
for i in range(1500)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
protected = _account(
|
||||||
|
"large-protected-invalid",
|
||||||
|
ck_check_status="invalid",
|
||||||
|
status="invalid",
|
||||||
|
)
|
||||||
|
accounts.append(protected)
|
||||||
|
db.add_all(accounts)
|
||||||
|
db.flush()
|
||||||
|
db.add(
|
||||||
|
PlatformFulfillmentTask(
|
||||||
|
source_order_id="large-protected-order",
|
||||||
|
source_order_item_id="large-protected-item",
|
||||||
|
sale_mode="presale",
|
||||||
|
account_id=protected.id,
|
||||||
|
binding_status="bound",
|
||||||
|
execution_status="bound",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
recommendation = recommend_login_budget(db, now=now)
|
||||||
|
recommended = recommendation["recommended"]
|
||||||
|
allocated = (
|
||||||
|
recommended["relogin_protected_daily_limit"]
|
||||||
|
+ recommended["lease_refresh_daily_limit"]
|
||||||
|
+ recommended["relogin_high_value_daily_limit"]
|
||||||
|
+ recommended["relogin_ordinary_daily_limit"]
|
||||||
|
+ recommended["onboarding_daily_limit"]
|
||||||
|
+ recommended["manual_daily_limit"]
|
||||||
|
)
|
||||||
|
|
||||||
|
assert recommended["daily_attempt_limit"] <= 2000
|
||||||
|
assert allocated <= recommended["daily_attempt_limit"]
|
||||||
|
assert recommended["manual_daily_limit"] <= 200
|
||||||
|
assert recommended["relogin_protected_daily_limit"] >= 100
|
||||||
|
assert recommended["relogin_high_value_daily_limit"] > 0
|
||||||
|
assert recommended["relogin_ordinary_daily_limit"] > 0
|
||||||
|
|||||||
@@ -411,3 +411,209 @@ class TestDeleteGuard:
|
|||||||
assert res["success"] is True
|
assert res["success"] is True
|
||||||
assert not self._exists(self.success_history)
|
assert not self._exists(self.success_history)
|
||||||
assert self._account_cookie(self.account.id) == "valid-ck-1"
|
assert self._account_cookie(self.account.id) == "valid-ck-1"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSkippedTaskOriginAndChineseMessages:
|
||||||
|
def setup_method(self):
|
||||||
|
self.engine = get_test_engine()
|
||||||
|
database_module.SessionLocal.configure(bind=self.engine)
|
||||||
|
self.session = make_test_session(self.engine)
|
||||||
|
|
||||||
|
self.user = User(username="skip-admin", password_hash="h", role="super_admin")
|
||||||
|
self.session.add(self.user)
|
||||||
|
self.session.flush()
|
||||||
|
|
||||||
|
self.acc_auto = Account(
|
||||||
|
username="skip-auto-acc",
|
||||||
|
password="p",
|
||||||
|
email="skip-auto@example.com",
|
||||||
|
email_password="ep",
|
||||||
|
status="invalid",
|
||||||
|
ck_check_status="invalid",
|
||||||
|
)
|
||||||
|
self.acc_manual = Account(
|
||||||
|
username="skip-manual-acc",
|
||||||
|
password="p",
|
||||||
|
email="skip-manual@example.com",
|
||||||
|
email_password="ep",
|
||||||
|
status="invalid",
|
||||||
|
ck_check_status="invalid",
|
||||||
|
)
|
||||||
|
self.acc_geetest = Account(
|
||||||
|
username="geetest-acc",
|
||||||
|
password="p",
|
||||||
|
email="geetest@example.com",
|
||||||
|
email_password="ep",
|
||||||
|
status="invalid",
|
||||||
|
ck_check_status="invalid",
|
||||||
|
)
|
||||||
|
self.session.add_all([self.acc_auto, self.acc_manual, self.acc_geetest])
|
||||||
|
self.session.flush()
|
||||||
|
|
||||||
|
from web.backend.models import ExecutionJob
|
||||||
|
|
||||||
|
# 整批被跳过且无 LoginAttempt 的自动化批次(历史英文前缀消息)
|
||||||
|
self.session.add(
|
||||||
|
LoginTask(
|
||||||
|
batch_id="auto-skip-batch",
|
||||||
|
account_id=self.acc_auto.id,
|
||||||
|
created_by=self.user.id,
|
||||||
|
status="skipped",
|
||||||
|
attempt_status="skipped",
|
||||||
|
attempt_batch_id="auto-skip-batch",
|
||||||
|
attempt_message="未执行:relogin_ordinary 今日登录预算已用完",
|
||||||
|
message="未执行:relogin_ordinary 今日登录预算已用完",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# 人工批次触发但因全局预算被跳过(有 ExecutionJob、无 LoginAttempt)
|
||||||
|
self.session.add(
|
||||||
|
ExecutionJob(
|
||||||
|
job_type="login_batch",
|
||||||
|
lane_scope="auth",
|
||||||
|
batch_id="manual-skip-batch",
|
||||||
|
payload_json={"trigger_source": "manual", "mode": "login"},
|
||||||
|
available_at=datetime.now(UTC),
|
||||||
|
created_by=self.user.id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.session.add(
|
||||||
|
LoginTask(
|
||||||
|
batch_id="manual-skip-batch",
|
||||||
|
account_id=self.acc_manual.id,
|
||||||
|
created_by=self.user.id,
|
||||||
|
status="skipped",
|
||||||
|
attempt_status="skipped",
|
||||||
|
attempt_batch_id="manual-skip-batch",
|
||||||
|
attempt_message="未执行:全局每日登录尝试预算已用完",
|
||||||
|
message="未执行:全局每日登录尝试预算已用完",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# 历史极验英文失败文案
|
||||||
|
self.session.add(
|
||||||
|
LoginTask(
|
||||||
|
batch_id="geetest-batch",
|
||||||
|
account_id=self.acc_geetest.id,
|
||||||
|
created_by=self.user.id,
|
||||||
|
status="failed",
|
||||||
|
attempt_status="failed",
|
||||||
|
attempt_batch_id="geetest-batch",
|
||||||
|
attempt_message="重新登录失败: 极验 slide 验证失败: forbidden(旧 Cookie 已保留)",
|
||||||
|
message="重新登录失败: 极验 slide 验证失败: forbidden(旧 Cookie 已保留)",
|
||||||
|
logs=[
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": (
|
||||||
|
"重新登录失败: 极验验证异常: HTTPSConnectionPool(host='api.geetest.com', port=443): "
|
||||||
|
"Max retries exceeded with url: /get.php (Caused by ReadTimeoutError('Read timed out.'))(旧 Cookie 已保留)"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.session.commit()
|
||||||
|
|
||||||
|
def teardown_method(self):
|
||||||
|
self.session.close()
|
||||||
|
|
||||||
|
def _fresh(self):
|
||||||
|
return sessionmaker(bind=self.engine)()
|
||||||
|
|
||||||
|
def test_skipped_tasks_recover_origin_and_chinese_messages(self):
|
||||||
|
from web.backend.routers.login import get_task_logs
|
||||||
|
from web.backend.services.login_quota_service import humanize_login_message
|
||||||
|
|
||||||
|
db = self._fresh()
|
||||||
|
try:
|
||||||
|
items = list_tasks(db=db, current=self.user)
|
||||||
|
by_username = {item.account_username: item for item in items}
|
||||||
|
|
||||||
|
auto_item = by_username["skip-auto-acc"]
|
||||||
|
assert auto_item.trigger_source == "automation"
|
||||||
|
assert auto_item.category == "relogin_ordinary"
|
||||||
|
assert auto_item.message == "未执行:普通重登今日登录预算已用完"
|
||||||
|
|
||||||
|
manual_item = by_username["skip-manual-acc"]
|
||||||
|
assert manual_item.trigger_source == "manual"
|
||||||
|
assert manual_item.category == "manual_login"
|
||||||
|
assert manual_item.message == "未执行:全局每日登录尝试预算已用完"
|
||||||
|
|
||||||
|
geetest_item = by_username["geetest-acc"]
|
||||||
|
assert "触发风控拦截" in geetest_item.message
|
||||||
|
assert "slide" not in geetest_item.message
|
||||||
|
assert "forbidden" not in geetest_item.message
|
||||||
|
|
||||||
|
logs = get_task_logs(task_id=geetest_item.id, db=db, current=self.user)
|
||||||
|
assert "网络或代理请求超时" in logs["items"][0]["message"]
|
||||||
|
assert "HTTPSConnectionPool" not in logs["items"][0]["message"]
|
||||||
|
|
||||||
|
assert (
|
||||||
|
humanize_login_message("极验 slide 验证失败: fail(旧 Cookie 已保留)")
|
||||||
|
== "极验滑块验证失败: 滑块未通过(旧 Cookie 已保留)"
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
def test_reserve_login_attempt_uses_chinese_category_label_when_exhausted(self):
|
||||||
|
from web.backend.models import LoginQuotaSetting, LoginQuotaUsage
|
||||||
|
from web.backend.services.login_quota_service import (
|
||||||
|
CATEGORY_ALL,
|
||||||
|
CATEGORY_RELOGIN_ORDINARY,
|
||||||
|
BUSINESS_TZ,
|
||||||
|
reserve_login_attempt,
|
||||||
|
)
|
||||||
|
|
||||||
|
db = self._fresh()
|
||||||
|
try:
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
quota_day = now.astimezone(BUSINESS_TZ).date()
|
||||||
|
quota_hour = now.astimezone(BUSINESS_TZ).hour
|
||||||
|
db.add(
|
||||||
|
LoginQuotaSetting(
|
||||||
|
id=1,
|
||||||
|
enabled=True,
|
||||||
|
daily_attempt_limit=2000,
|
||||||
|
hourly_attempt_limit=500,
|
||||||
|
per_account_daily_limit=3,
|
||||||
|
onboarding_daily_limit=100,
|
||||||
|
relogin_high_value_daily_limit=200,
|
||||||
|
relogin_ordinary_daily_limit=1,
|
||||||
|
manual_daily_limit=100,
|
||||||
|
relogin_protected_daily_limit=100,
|
||||||
|
lease_refresh_daily_limit=50,
|
||||||
|
login_concurrency=3,
|
||||||
|
failure_pause_ratio=40,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.add_all(
|
||||||
|
[
|
||||||
|
LoginQuotaUsage(
|
||||||
|
quota_day=quota_day,
|
||||||
|
quota_hour=quota_hour,
|
||||||
|
category=CATEGORY_RELOGIN_ORDINARY,
|
||||||
|
attempt_count=1,
|
||||||
|
),
|
||||||
|
LoginQuotaUsage(
|
||||||
|
quota_day=quota_day,
|
||||||
|
quota_hour=quota_hour,
|
||||||
|
category=CATEGORY_ALL,
|
||||||
|
attempt_count=1,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
acc = db.query(Account).filter(Account.username == "skip-auto-acc").one()
|
||||||
|
decision = reserve_login_attempt(
|
||||||
|
db,
|
||||||
|
account=acc,
|
||||||
|
mode="relogin",
|
||||||
|
batch_id="quota-check-batch",
|
||||||
|
trigger_source="automation",
|
||||||
|
created_by=self.user.id,
|
||||||
|
now=now,
|
||||||
|
)
|
||||||
|
assert decision.allowed is False
|
||||||
|
assert decision.reason == "普通重登今日登录预算已用完"
|
||||||
|
assert decision.category == CATEGORY_RELOGIN_ORDINARY
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|||||||
@@ -34,6 +34,13 @@ from ..services.execution_jobs import (
|
|||||||
request_execution_cancel,
|
request_execution_cancel,
|
||||||
)
|
)
|
||||||
from ..services.login_failure import classify_failure, failure_kind_label
|
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
|
from ..services.login_service import batch_registry
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/login", tags=["登录任务"])
|
router = APIRouter(prefix="/api/login", tags=["登录任务"])
|
||||||
@@ -278,22 +285,47 @@ def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
|||||||
accounts_map[int(row[0])] = row
|
accounts_map[int(row[0])] = row
|
||||||
|
|
||||||
# 登录任务记录本身不带来源;来源在 LoginAttempt(人工/自动化/首次登录/重登)。
|
# 登录任务记录本身不带来源;来源在 LoginAttempt(人工/自动化/首次登录/重登)。
|
||||||
|
# 已跳过的任务不会创建 LoginAttempt,需要按同批次 LoginAttempt / ExecutionJob / 消息文案补全来源与分类。
|
||||||
batch_ids = {str(t.attempt_batch_id or t.batch_id or "") for t in rows}
|
batch_ids = {str(t.attempt_batch_id or t.batch_id or "") for t in rows}
|
||||||
batch_ids.discard("")
|
batch_ids.discard("")
|
||||||
attempt_map: dict[tuple[str, int], LoginAttempt] = {}
|
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 (
|
for attempt in (
|
||||||
db.query(LoginAttempt)
|
db.query(LoginAttempt)
|
||||||
.filter(
|
.filter(LoginAttempt.batch_id.in_(batch_ids))
|
||||||
LoginAttempt.batch_id.in_(batch_ids),
|
|
||||||
LoginAttempt.account_id.in_(account_ids),
|
|
||||||
)
|
|
||||||
.order_by(LoginAttempt.id.asc())
|
.order_by(LoginAttempt.id.asc())
|
||||||
.all()
|
.all()
|
||||||
):
|
):
|
||||||
attempt_map[(str(attempt.batch_id or ""), int(attempt.account_id))] = (
|
b_id = str(attempt.batch_id or "")
|
||||||
attempt
|
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 = {
|
creator_ids = {
|
||||||
int(value)
|
int(value)
|
||||||
for value in [
|
for value in [
|
||||||
@@ -318,6 +350,29 @@ def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
|||||||
account = accounts_map.get(int(t.account_id))
|
account = accounts_map.get(int(t.account_id))
|
||||||
batch_id = str(t.attempt_batch_id or t.batch_id or "")
|
batch_id = str(t.attempt_batch_id or t.batch_id or "")
|
||||||
attempt = attempt_map.get((batch_id, int(t.account_id)))
|
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(
|
result.append(
|
||||||
LoginTaskOut(
|
LoginTaskOut(
|
||||||
id=t.id,
|
id=t.id,
|
||||||
@@ -333,13 +388,11 @@ def _serialize_tasks(db: Session, rows) -> list[LoginTaskOut]:
|
|||||||
cookie_updated_at=(account[7] if account else None),
|
cookie_updated_at=(account[7] if account else None),
|
||||||
status=attempt_status or t.status,
|
status=attempt_status or t.status,
|
||||||
cookie="",
|
cookie="",
|
||||||
message=(t.attempt_message if attempt_status else "")
|
message=display_message,
|
||||||
or t.message
|
|
||||||
or "",
|
|
||||||
created_by=t.created_by,
|
created_by=t.created_by,
|
||||||
created_by_username=creator_map.get(int(t.created_by), ""),
|
created_by_username=creator_map.get(int(t.created_by), ""),
|
||||||
trigger_source=(str(attempt.trigger_source or "") if attempt else ""),
|
trigger_source=trigger_source,
|
||||||
category=(str(attempt.category or "") if attempt else ""),
|
category=category,
|
||||||
created_at=t.created_at,
|
created_at=t.created_at,
|
||||||
finished_at=t.attempt_at or t.finished_at,
|
finished_at=t.attempt_at or t.finished_at,
|
||||||
)
|
)
|
||||||
@@ -412,10 +465,18 @@ def get_task_logs(
|
|||||||
)
|
)
|
||||||
if task is None:
|
if task is None:
|
||||||
raise HTTPException(status_code=404, detail="登录任务不存在")
|
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 {
|
return {
|
||||||
"task_id": int(task.id),
|
"task_id": int(task.id),
|
||||||
"account_id": int(task.account_id),
|
"account_id": int(task.account_id),
|
||||||
"items": task.logs or [],
|
"items": items,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -523,7 +584,8 @@ def export_tasks(
|
|||||||
for task in rows:
|
for task in rows:
|
||||||
attempt_status = task.attempt_status or ""
|
attempt_status = task.attempt_status or ""
|
||||||
effective = attempt_status or task.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 ""
|
kind = classify_failure(message) if effective in {"failed", "error"} else ""
|
||||||
username, tag, owner = info.get(task.account_id, ("", "", ""))
|
username, tag, owner = info.get(task.account_id, ("", "", ""))
|
||||||
writer.writerow(
|
writer.writerow(
|
||||||
|
|||||||
@@ -23,12 +23,13 @@ MIN_RECENT_SAMPLE = 20
|
|||||||
DEFAULT_SUCCESS_RATE = 70.0
|
DEFAULT_SUCCESS_RATE = 70.0
|
||||||
MIN_EFFECTIVE_SUCCESS_RATE = 35.0
|
MIN_EFFECTIVE_SUCCESS_RATE = 35.0
|
||||||
MIN_DAILY_ATTEMPTS = 50
|
MIN_DAILY_ATTEMPTS = 50
|
||||||
MAX_DAILY_ATTEMPTS = 5000
|
MAX_DAILY_ATTEMPTS = 2000
|
||||||
|
MAX_MANUAL_RESERVE = 200
|
||||||
ASSUMED_ACTIVE_HOURS = 12
|
ASSUMED_ACTIVE_HOURS = 12
|
||||||
|
|
||||||
|
|
||||||
def _fit_priority_budgets(limits: list[int], available: int) -> list[int]:
|
def _fit_priority_budgets(limits: list[int], available: int) -> list[int]:
|
||||||
"""把 P0-P3 预算压进全局可用名额,按优先级从低到高削减。"""
|
"""把 P0-P4 预算压进全局可用名额,按优先级从低到高削减。"""
|
||||||
fitted = list(limits)
|
fitted = list(limits)
|
||||||
excess = max(0, sum(fitted) - max(0, int(available)))
|
excess = max(0, sum(fitted) - max(0, int(available)))
|
||||||
for index in range(len(fitted) - 1, -1, -1):
|
for index in range(len(fitted) - 1, -1, -1):
|
||||||
@@ -219,7 +220,11 @@ def recommend_login_budget(
|
|||||||
expected_daily_invalid + recovery_pressure + onboarding_pressure
|
expected_daily_invalid + recovery_pressure + onboarding_pressure
|
||||||
)
|
)
|
||||||
core_attempts = math.ceil(required_success / effective_rate)
|
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)
|
onboarding_attempts = math.ceil(onboarding_pressure / effective_rate)
|
||||||
nonprotected_relogin_pressure_high = (
|
nonprotected_relogin_pressure_high = (
|
||||||
nonprotected_valid_high / CK_AVERAGE_LIFETIME_DAYS
|
nonprotected_valid_high / CK_AVERAGE_LIFETIME_DAYS
|
||||||
@@ -257,35 +262,36 @@ def recommend_login_budget(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
raw_relogin_limits = [
|
raw_priority_limits = [
|
||||||
relogin_protected_limit,
|
relogin_protected_limit,
|
||||||
lease_refresh_limit,
|
lease_refresh_limit,
|
||||||
relogin_high_limit,
|
relogin_high_limit,
|
||||||
relogin_ordinary_limit,
|
relogin_ordinary_limit,
|
||||||
|
onboarding_attempts,
|
||||||
]
|
]
|
||||||
planned_attempts = (
|
planned_attempts = sum(raw_priority_limits) + raw_manual_reserve
|
||||||
sum(raw_relogin_limits) + onboarding_attempts + manual_reserve
|
|
||||||
)
|
|
||||||
daily_attempts = min(
|
daily_attempts = min(
|
||||||
MAX_DAILY_ATTEMPTS,
|
MAX_DAILY_ATTEMPTS,
|
||||||
max(
|
max(
|
||||||
MIN_DAILY_ATTEMPTS,
|
MIN_DAILY_ATTEMPTS,
|
||||||
core_attempts + manual_reserve,
|
core_attempts + raw_manual_reserve,
|
||||||
planned_attempts,
|
planned_attempts,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
available_relogin_attempts = max(
|
manual_reserve = min(
|
||||||
0,
|
raw_manual_reserve,
|
||||||
daily_attempts - onboarding_attempts - manual_reserve,
|
max(30, math.ceil(daily_attempts * 0.1)),
|
||||||
)
|
)
|
||||||
|
available_auto_attempts = max(0, daily_attempts - manual_reserve)
|
||||||
(
|
(
|
||||||
relogin_protected_limit,
|
relogin_protected_limit,
|
||||||
lease_refresh_limit,
|
lease_refresh_limit,
|
||||||
relogin_high_limit,
|
relogin_high_limit,
|
||||||
relogin_ordinary_limit,
|
relogin_ordinary_limit,
|
||||||
|
onboarding_attempts,
|
||||||
) = _fit_priority_budgets(
|
) = _fit_priority_budgets(
|
||||||
raw_relogin_limits,
|
raw_priority_limits,
|
||||||
available_relogin_attempts,
|
available_auto_attempts,
|
||||||
)
|
)
|
||||||
hourly_attempts = max(1, math.ceil(daily_attempts / ASSUMED_ACTIVE_HOURS))
|
hourly_attempts = max(1, math.ceil(daily_attempts / ASSUMED_ACTIVE_HOURS))
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, date, datetime, timedelta
|
from datetime import UTC, date, datetime, timedelta
|
||||||
|
import re
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
from sqlalchemy import and_, func, or_, select
|
from sqlalchemy import and_, func, or_, select
|
||||||
@@ -57,14 +58,104 @@ _TIER_BY_CATEGORY: dict[str, int] = {
|
|||||||
CATEGORY_ONBOARDING: 4,
|
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")
|
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)
|
@dataclass(frozen=True)
|
||||||
class QuotaDecision:
|
class QuotaDecision:
|
||||||
allowed: bool
|
allowed: bool
|
||||||
reason: str = ""
|
reason: str = ""
|
||||||
attempt: LoginAttempt | None = None
|
attempt: LoginAttempt | None = None
|
||||||
|
category: str = ""
|
||||||
|
|
||||||
|
|
||||||
def _bucket(now: datetime | None = None) -> tuple[date, int]:
|
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(
|
if _category_daily_total(db, quota_day, resolved_category) >= _category_limit(
|
||||||
setting, resolved_category
|
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(
|
attempt = LoginAttempt(
|
||||||
account_id=int(account.id),
|
account_id=int(account.id),
|
||||||
@@ -707,7 +803,9 @@ def cleanup_orphan_login_attempts(
|
|||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
"AUTOMATED_CATEGORIES",
|
||||||
"CATEGORY_ACCOUNT_CHECK",
|
"CATEGORY_ACCOUNT_CHECK",
|
||||||
|
"CATEGORY_LABELS",
|
||||||
"CATEGORY_LEASE_REFRESH",
|
"CATEGORY_LEASE_REFRESH",
|
||||||
"CATEGORY_MANUAL",
|
"CATEGORY_MANUAL",
|
||||||
"CATEGORY_ONBOARDING",
|
"CATEGORY_ONBOARDING",
|
||||||
@@ -715,10 +813,13 @@ __all__ = [
|
|||||||
"CATEGORY_RELOGIN_ORDINARY",
|
"CATEGORY_RELOGIN_ORDINARY",
|
||||||
"CATEGORY_RELOGIN_PROTECTED",
|
"CATEGORY_RELOGIN_PROTECTED",
|
||||||
"QuotaDecision",
|
"QuotaDecision",
|
||||||
|
"category_label",
|
||||||
"classify_login_category",
|
"classify_login_category",
|
||||||
"cleanup_orphan_login_attempts",
|
"cleanup_orphan_login_attempts",
|
||||||
"finish_login_attempt",
|
"finish_login_attempt",
|
||||||
"get_login_quota_usage_summary",
|
"get_login_quota_usage_summary",
|
||||||
|
"humanize_login_message",
|
||||||
|
"infer_category_from_message",
|
||||||
"login_concurrency_limit",
|
"login_concurrency_limit",
|
||||||
"reserve_login_attempt",
|
"reserve_login_attempt",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -824,6 +824,9 @@ export default function AutomationPage() {
|
|||||||
>
|
>
|
||||||
{budgetRecommendation ? (
|
{budgetRecommendation ? (
|
||||||
<>
|
<>
|
||||||
|
<Text type="secondary" style={{ display: "block", marginBottom: 12 }}>
|
||||||
|
建议每日总预算上限 2,000 次,优先保障 P0 履约保护重登 > P1 续期 > P2 高价值 > P3 普通重登 > P4 首次登录。
|
||||||
|
</Text>
|
||||||
<Row gutter={[16, 12]} style={{ marginBottom: 16 }}>
|
<Row gutter={[16, 12]} style={{ marginBottom: 16 }}>
|
||||||
<Col xs={12} md={8} lg={4}>
|
<Col xs={12} md={8} lg={4}>
|
||||||
<Text type="secondary">有效账号</Text>
|
<Text type="secondary">有效账号</Text>
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ const LOGIN_CATEGORY_LABELS: Record<string, string> = {
|
|||||||
relogin_ordinary: '普通重登',
|
relogin_ordinary: '普通重登',
|
||||||
relogin_protected: '履约保护重登',
|
relogin_protected: '履约保护重登',
|
||||||
manual: '人工登录',
|
manual: '人工登录',
|
||||||
|
manual_login: '人工登录',
|
||||||
account_check: '账号检测',
|
account_check: '账号检测',
|
||||||
lease_refresh: '履约快过期续期',
|
lease_refresh: '履约快过期续期',
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user