优化(账号自动化): 履约保护登录配额与重登优先级

This commit is contained in:
yml
2026-11-25 22:13:21 +08:00
parent 0943b7a362
commit 9bdd2f4e1a
25 changed files with 1510 additions and 193 deletions
@@ -537,6 +537,10 @@
"20261125_0134_login_task_logs.py": {
"revision": "20261125_0134",
"sha256": "c21a4833874676b08a9156e20cfb89c2786aece628d998e8a1bf87a8d0b3cd4b"
},
"20261125_0135_protected_login_quota_limits.py": {
"revision": "20261125_0135",
"sha256": "8bc4b6a5e9952087e6a18f038f1cb4a054bf25feed311677c94ffcbd1b5711f2"
}
}
}
@@ -0,0 +1,56 @@
"""为履约保护失效重登与快过期续期新增独立的每日登录预算列。"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261125_0135"
down_revision: str | None = "20261125_0134"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "login_quota_settings"
def _column_exists(name: str) -> bool:
conn = op.get_bind()
count = conn.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.columns "
"WHERE table_schema = DATABASE() AND table_name = :table "
"AND column_name = :name"
),
{"table": TABLE, "name": name},
).scalar()
return bool(count)
def upgrade() -> None:
if not _column_exists("relogin_protected_daily_limit"):
op.add_column(
TABLE,
sa.Column(
"relogin_protected_daily_limit",
sa.Integer(),
nullable=False,
server_default="500",
),
)
if not _column_exists("lease_refresh_daily_limit"):
op.add_column(
TABLE,
sa.Column(
"lease_refresh_daily_limit",
sa.Integer(),
nullable=False,
server_default="300",
),
)
def downgrade() -> None:
if _column_exists("lease_refresh_daily_limit"):
op.drop_column(TABLE, "lease_refresh_daily_limit")
if _column_exists("relogin_protected_daily_limit"):
op.drop_column(TABLE, "relogin_protected_daily_limit")
+6
View File
@@ -3049,6 +3049,12 @@ class LoginQuotaSetting(Base):
relogin_ordinary_daily_limit: Mapped[int] = mapped_column(
Integer, nullable=False, default=500, server_default="500"
)
relogin_protected_daily_limit: Mapped[int] = mapped_column(
Integer, nullable=False, default=500, server_default="500"
)
lease_refresh_daily_limit: Mapped[int] = mapped_column(
Integer, nullable=False, default=300, server_default="300"
)
manual_daily_limit: Mapped[int] = mapped_column(
Integer, nullable=False, default=300, server_default="300"
)
+22 -4
View File
@@ -69,6 +69,8 @@ class LoginQuotaUpdate(BaseModel):
hourly_attempt_limit: int = Field(..., ge=1, le=100_000)
per_account_daily_limit: int = Field(..., ge=1, le=100)
onboarding_daily_limit: int = Field(..., ge=0, le=100_000)
relogin_protected_daily_limit: int = Field(default=500, ge=0, le=100_000)
lease_refresh_daily_limit: int = Field(default=300, ge=0, le=100_000)
relogin_high_value_daily_limit: int = Field(..., ge=0, le=100_000)
relogin_ordinary_daily_limit: int = Field(..., ge=0, le=100_000)
manual_daily_limit: int = Field(..., ge=0, le=100_000)
@@ -77,12 +79,21 @@ class LoginQuotaUpdate(BaseModel):
enabled: bool = True
def _login_quota_out(row: LoginQuotaSetting) -> dict[str, Any]:
return {
def _login_quota_out(
row: LoginQuotaSetting,
db: Session | None = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"daily_attempt_limit": int(row.daily_attempt_limit),
"hourly_attempt_limit": int(row.hourly_attempt_limit),
"per_account_daily_limit": int(row.per_account_daily_limit),
"onboarding_daily_limit": int(row.onboarding_daily_limit),
"relogin_protected_daily_limit": int(
getattr(row, "relogin_protected_daily_limit", 500)
),
"lease_refresh_daily_limit": int(
getattr(row, "lease_refresh_daily_limit", 300)
),
"relogin_high_value_daily_limit": int(
row.relogin_high_value_daily_limit
),
@@ -95,6 +106,11 @@ def _login_quota_out(row: LoginQuotaSetting) -> dict[str, Any]:
"enabled": bool(row.enabled),
"updated_at": row.updated_at.isoformat() if row.updated_at else None,
}
if db is not None:
from ..services.login_quota_service import get_login_quota_usage_summary
payload["usage"] = get_login_quota_usage_summary(db)
return payload
def _job_out(job: AutomationJob) -> dict[str, Any]:
@@ -228,7 +244,7 @@ def get_login_quota(
row = LoginQuotaSetting(id=1)
db.add(row)
db.commit()
return _login_quota_out(row)
return _login_quota_out(row, db=db)
@router.get("/login-quota/recommendation")
@@ -257,6 +273,8 @@ def update_login_quota(
"hourly_attempt_limit",
"per_account_daily_limit",
"onboarding_daily_limit",
"relogin_protected_daily_limit",
"lease_refresh_daily_limit",
"relogin_high_value_daily_limit",
"relogin_ordinary_daily_limit",
"manual_daily_limit",
@@ -275,7 +293,7 @@ def update_login_quota(
detail={"before": before, "after": _login_quota_out(row)},
)
db.commit()
return _login_quota_out(row)
return _login_quota_out(row, db=db)
@router.patch("/jobs/{key}")
+3 -3
View File
@@ -233,9 +233,9 @@ def register_default_jobs() -> None:
register_job(
JobSpec(
key=LEASE_CK_REFRESH_KEY,
title="租约 CK 到期前刷新",
# 只处理仍有效、但预测 24h 内到期的生效租约账号;提前续 CK,
# 不参与普通失效重登的批次。
title="履约 CK 到期前刷新",
# 处理仍有效、但预测 24h 内到期的全部履约保护账号(预售 / 协作单 / 生效租约),
# 提前续 CK,不参与普通失效重登的批次。
interval_seconds=600,
run_interval_seconds=600,
batch_size=10,
@@ -45,7 +45,7 @@ from ...account_protection_service import (
load_protection_snapshot,
)
from ...account_query_filters import automation_account_filter
from ...account_value import value_tier_expr
from ...account_value import is_high_value_expr, value_tier_expr
from ...account_work_queue import (
WORK_AGING_SECONDS,
active_account_work_exists,
@@ -74,9 +74,8 @@ RETRYABLE_KINDS = frozenset({"email_code", "interrupted", "network"})
# 退避阶梯(分钟):1h → 3h → 12h → 24h,超出取最后一级。
BACKOFF_MINUTES = (60, 180, 720, 1440)
# 自动重登时给 runner 的总时长上限。必须能覆盖斗鱼验证码邮件的最坏投递延迟
# (实测 8~13 分钟),否则等待会被掐断成失败;一轮跑不完的账号反正有退避。
AUTO_MAX_TOTAL_TIME = 1800
# 自动重登时给 runner 的总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。
AUTO_MAX_TOTAL_TIME = 300
# 邮箱配额打满后退避到次日零点,再叠加随机抖动,避免整点齐发。
QUOTA_JITTER_MINUTES = 30
@@ -226,18 +225,22 @@ def _enqueue_due_relogin_work(
max_attempts: int,
protection: ProtectionSnapshot,
limit: int,
account_ids_filter: frozenset[int] | None = None,
) -> int:
"""把已判定失效但尚未进入队列的账号补成持久工作项。"""
accounts = build_select_query(
query = build_select_query(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
apply_limit=False,
).filter(
~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN)
).limit(max(1, limit)).all()
).filter(~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN))
if account_ids_filter is not None:
if not account_ids_filter:
return 0
query = query.filter(Account.id.in_(account_ids_filter))
accounts = query.limit(max(1, limit)).all()
for account in accounts:
priority = 10 if int(account.id) in protection.relogin_ids else 30
enqueue_account_work(
@@ -314,6 +317,28 @@ def _claim_relogin_work(
limit: int,
) -> list[AccountWorkItem]:
"""从持久队列领取重登任务,而不是每轮重新从账号表直接选执行对象。"""
relogin_ids = protection.relogin_ids
if relogin_ids:
# 先把已在队列但优先级仍为普通档的保护账号同步到 10,
# 防止先失效、后进保护组的账号一直排在后面。
db.query(AccountWorkItem).filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.account_id.in_(relogin_ids),
AccountWorkItem.priority > 10,
).update({AccountWorkItem.priority: 10}, synchronize_session=False)
# 履约关系结束后必须收回上一轮提升过的优先级,否则历史保护账号会
# 一直以 P0 档排在普通库存前面。
demote_query = db.query(AccountWorkItem).filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.priority == 10,
)
if relogin_ids:
demote_query = demote_query.filter(
~AccountWorkItem.account_id.in_(relogin_ids)
)
demote_query.update({AccountWorkItem.priority: 30}, synchronize_session=False)
eligible_ids = build_select_query(
db,
job,
@@ -322,42 +347,58 @@ def _claim_relogin_work(
protection=protection,
apply_limit=False,
).with_entities(Account.id)
ordering: list[Any] = []
if relogin_ids:
# P0 履约保护目标绝对优先:即使普通账号已积压超 30 分钟,
# 也绝不允许通过 aging 插队到保护账号前面。
ordering.append(
case((AccountWorkItem.account_id.in_(relogin_ids), 0), else_=1)
)
# P2 高价值(第 1、2 档)优先于 P3 普通账号,aging 仅在同档内部防饿死。
ordering.extend(
[
case((is_high_value_expr(now=now), 0), else_=1),
case(
(
AccountWorkItem.due_at
<= now - timedelta(seconds=WORK_AGING_SECONDS),
0,
),
else_=1,
),
AccountWorkItem.priority.asc(),
AccountWorkItem.due_at.asc(),
AccountWorkItem.id.asc(),
]
)
account_ids = [
int(account_id)
for (account_id,) in (
db.query(AccountWorkItem.account_id)
.join(Account, Account.id == AccountWorkItem.account_id)
.filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.due_at <= now,
AccountWorkItem.account_id.in_(eligible_ids),
)
.order_by(
case(
(
AccountWorkItem.due_at
<= now - timedelta(seconds=WORK_AGING_SECONDS),
0,
),
else_=1,
),
AccountWorkItem.priority.asc(),
AccountWorkItem.due_at.asc(),
AccountWorkItem.id.asc(),
)
.order_by(*ordering)
.limit(max(1, limit))
.all()
)
]
if not account_ids:
return []
return claim_account_work(
claimed = claim_account_work(
db,
work_types=(WORK_LOGIN_RELOGIN,),
account_ids=tuple(account_ids),
limit=limit,
now=now,
)
order_index = {account_id: index for index, account_id in enumerate(account_ids)}
claimed.sort(key=lambda item: order_index.get(int(item.account_id), len(order_index)))
return claimed
def _load_batch_state(
@@ -486,8 +527,10 @@ 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)
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)
@@ -505,8 +548,8 @@ def evaluate_failure_circuit(
)
threshold = raw_ratio / 100 if raw_ratio > 1 else raw_ratio
threshold = max(0.0, min(threshold, 1.0))
ratio = hard_failures / scanned if scanned else 0.0
return scanned >= minimum and ratio > threshold, hard_failures, ratio
ratio = hard_failures / attempted if attempted else 0.0
return attempted >= minimum and ratio > threshold, hard_failures, ratio
def resolve_failure_circuit_config(
@@ -544,7 +587,7 @@ def _recent_relogin_success(
.filter(
LoginAttempt.quota_day >= start_day,
LoginAttempt.category.in_(
("relogin_high_value", "relogin_ordinary")
("relogin_high_value", "relogin_ordinary", "relogin_protected")
),
)
.group_by(LoginAttempt.status, LoginAttempt.failure_kind)
@@ -701,6 +744,17 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
now=now,
pending=pending,
)
if protection.relogin_ids:
# 先把尚未入队的到期履约保护账号补进队列,避免被既有普通积压挡住。
_enqueue_due_relogin_work(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
limit=adaptive.batch_size,
account_ids_filter=protection.relogin_ids,
)
work_items = _claim_relogin_work(
db,
job,
@@ -773,6 +827,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
concurrency=max(min(int(job.concurrency or 3), 8), 1),
mode="relogin",
trigger_source="automation",
batch_max_seconds=0.0,
)
batch_id = runner.batch_id
try:
@@ -839,6 +894,8 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
parts.append(f"硬失败 {hard_failures}({hard_failure_ratio:.0%})")
if paused:
parts.append("失败率过高,已自动暂停作业")
if counters.get("skipped"):
parts.append(f"预算/预检跳过 {counters['skipped']}")
if adaptive.action != "hold":
parts.append(
f"批量策略 {adaptive.previous_batch_size}->{adaptive.batch_size}"
@@ -850,7 +907,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
"invalid": counters["invalid"],
"relogin_started": counters["scanned"],
"relogin_success": counters["valid"],
"skipped": 0,
"skipped": counters.get("skipped", 0),
"message": ",".join(parts),
"detail": {
"batch_id": batch_id,
@@ -902,6 +959,7 @@ def settle_results(
"manual": 0,
"retry": 0,
"email_quota": 0,
"skipped": 0,
}
for account_id in account_ids:
entry = fresh.get(account_id)
@@ -917,7 +975,7 @@ def settle_results(
due_at=retry_at,
reason="自动重登未产生账号任务,重新排队",
)
counters["retry"] += 1
counters["skipped"] += 1
continue
account, task = entry
if task.attempt_status == "success":
@@ -925,6 +983,24 @@ def settle_results(
# 重登成功:清退避痕迹 + 重算状态(与人工登录成功同一套语义)
on_login_success(db, account, occurred_at=now)
continue
if task.attempt_status == "skipped":
counters["skipped"] += 1
# 被预算/槽位跳过不是失败:绝不加 relogin_attempts、不转人工,
# 只保留在队列中等待下一轮重试。
skip_message = task.attempt_message or "本轮未执行,留待下一轮"
delay = (
timedelta(hours=1)
if "今日登录尝试上限" in skip_message
else timedelta(minutes=5)
)
reschedule_account_work_type(
db,
account_id=int(account.id),
work_type=WORK_LOGIN_RELOGIN,
due_at=now + delay,
reason=skip_message,
)
continue
counters["invalid"] += 1
kind = classify_failure(task.attempt_message)
@@ -1,11 +1,12 @@
"""租约账号 CK 到期前刷新(P1)。
"""履约保护账号 CK 到期前刷新(P1)。
`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但租约账号如果等到
失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前
24 小时**,对仍持有有效 CK 的生效租约账号做一次主动登录,延长 CK 生命周期。
`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但履约保护账号如果
等到失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前
24 小时**,对仍持有有效 CK 的履约保护账号做一次主动登录,延长 CK 生命周期。
范围:
- 预售履约任务分配的账号、进行中的斗鱼外部协作单绑定账号;
- `account_leases.status=active` 且 purpose 为 `platform_fulfillment` / `douyu_collab`;
- `ck_check_status=valid`、有 Cookie、可自动管理、没有在途登录;
- 预测到期时间 <= now + 24h(`ck_expected_expires_at` 或 `cookie_updated_at + 7d`);
@@ -23,18 +24,18 @@ from typing import Any
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, User
from ....models import Account, AutomationJob, User
from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS
from ...account_protection_service import load_protection_snapshot
from ...account_query_filters import automation_account_filter
from ...login_automation import run_login_batch_with_fallback
from ...login_quota_service import CATEGORY_LEASE_REFRESH
JOB_KEY = "lease_ck_refresh"
# 单账号总时长上限:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟),
# 否则等待会被掐断成"等待验证码超时",租约账号一批批地失败。
LEASE_MAX_TOTAL_TIME = 1800
TITLE = "租约 CK 到期前刷新"
# 单账号总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。
LEASE_MAX_TOTAL_TIME = 300
TITLE = "履约 CK 到期前刷新"
REFRESH_BEFORE = timedelta(hours=24)
@@ -55,15 +56,17 @@ def due_lease_account_query(
db: Session,
now: datetime | None = None,
):
"""到期前 24h 的租约账号查询(执行和测试共用)。"""
"""到期前 24h 的履约保护账号查询(预售 / 协作单 / 生效租约共用)。"""
moment = now or datetime.now(UTC)
cutoff = moment + REFRESH_BEFORE
protection = load_protection_snapshot(db)
relogin_ids = protection.relogin_ids
if not relogin_ids:
return db.query(Account).filter(Account.id == -1)
return (
db.query(Account)
.join(AccountLease, AccountLease.account_id == Account.id)
.filter(
AccountLease.status == "active",
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
Account.id.in_(relogin_ids),
Account.ck_check_status == "valid",
Account.cookie_updated_at.isnot(None),
automation_account_filter(cookie_operable=True),
@@ -79,7 +82,12 @@ def due_lease_account_query(
Account.relogin_next_at <= moment,
),
)
.order_by(Account.cookie_updated_at.asc(), Account.id.asc())
.order_by(
Account.ck_expected_expires_at.is_(None).asc(),
Account.ck_expected_expires_at.asc(),
Account.cookie_updated_at.asc(),
Account.id.asc(),
)
)
+13 -5
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import os
import threading
from concurrent.futures import Future, ThreadPoolExecutor, wait
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
from datetime import UTC, datetime
from typing import Any
@@ -163,7 +163,7 @@ class ExecutionJobWorker:
self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1)
try:
future.result()
except Exception: # noqa: BLE001 - 结果已落库,这里只消费异常
except Exception: # noqa: BLE001, S110 - 结果已落库,这里只消费异常
pass
executors = self._executors
if not executors:
@@ -190,13 +190,21 @@ class ExecutionJobWorker:
jobs = []
executor = executors.get(lane)
for job in jobs:
if executor is None:
if executor is None or self._stop.is_set():
break
try:
future = executor.submit(self._run_job, job.id)
except RuntimeError:
break
self._inflight[lane] = self._inflight.get(lane, 0) + 1
futures[executor.submit(self._run_job, job.id)] = lane
futures[future] = lane
slots -= len(jobs)
if futures:
wait(list(futures), timeout=poll_seconds)
wait(
list(futures),
timeout=poll_seconds,
return_when=FIRST_COMPLETED,
)
else:
self._stop.wait(poll_seconds)
+11 -5
View File
@@ -21,9 +21,8 @@ FALLBACK_LOGIN_API = "iframe"
#: 1.5 封涨到 3.3 封,邮件延迟随即从 10 秒级恶化到 8~13 分钟,取码成功率反而
#: 从 100% 掉到 20% 左右。取码失败现在靠「补等迟到邮件 + 批次级退避重试」处理。
EMAIL_FALLBACK_KINDS: frozenset[str] = frozenset()
# 单账号总时长上限:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟),
# 否则等待会被预算掐断,账号白白失败。
DEFAULT_MAX_TOTAL_TIME = 1800
# 单账号总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。
DEFAULT_MAX_TOTAL_TIME = 300
DEFAULT_MAX_RETRIES = 5
@@ -233,7 +232,12 @@ def run_login_batch_with_fallback(
attempted = dict(primary)
attempted.update(fallback)
outcome.attempted_ids = sorted(attempted)
actually_attempted = [
account_id
for account_id, (status, _) in attempted.items()
if status != "skipped"
]
outcome.attempted_ids = sorted(actually_attempted)
outcome.success_ids = sorted(success_ids)
outcome.failed_ids = [
account_id
@@ -241,7 +245,9 @@ def run_login_batch_with_fallback(
if account_id not in success_ids
]
outcome.skipped_ids = [
account_id for account_id in ordered_ids if account_id not in attempted
account_id
for account_id in ordered_ids
if account_id not in attempted or attempted[account_id][0] == "skipped"
]
for account_id in outcome.failed_ids:
status, kind = attempted.get(account_id, ("", ""))
@@ -11,6 +11,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_value import is_high_value_expr
CK_AVERAGE_LIFETIME_DAYS = 7.38
@@ -25,6 +26,19 @@ MAX_DAILY_ATTEMPTS = 5000
ASSUMED_ACTIVE_HOURS = 12
def _fit_priority_budgets(limits: list[int], available: int) -> list[int]:
"""把 P0-P3 预算压进全局可用名额,按优先级从低到高削减。"""
fitted = list(limits)
excess = max(0, sum(fitted) - max(0, int(available)))
for index in range(len(fitted) - 1, -1, -1):
if excess <= 0:
break
cut = min(fitted[index], excess)
fitted[index] -= cut
excess -= cut
return fitted
def _automatable_accounts(db: Session):
return db.query(Account).filter(
Account.auto_managed.is_(True),
@@ -55,6 +69,7 @@ def _recent_login_outcomes(
"onboarding",
"relogin_high_value",
"relogin_ordinary",
"relogin_protected",
"lease_refresh",
)
),
@@ -83,6 +98,8 @@ def _current_quota(db: Session) -> dict[str, int]:
"hourly_attempt_limit": 100,
"per_account_daily_limit": 2,
"onboarding_daily_limit": 150,
"relogin_protected_daily_limit": 500,
"lease_refresh_daily_limit": 300,
"relogin_high_value_daily_limit": 300,
"relogin_ordinary_daily_limit": 500,
"manual_daily_limit": 300,
@@ -95,6 +112,12 @@ def _current_quota(db: Session) -> dict[str, int]:
"hourly_attempt_limit": int(row.hourly_attempt_limit),
"per_account_daily_limit": int(row.per_account_daily_limit),
"onboarding_daily_limit": int(row.onboarding_daily_limit),
"relogin_protected_daily_limit": int(
getattr(row, "relogin_protected_daily_limit", 500)
),
"lease_refresh_daily_limit": int(
getattr(row, "lease_refresh_daily_limit", 300)
),
"relogin_high_value_daily_limit": int(
row.relogin_high_value_daily_limit
),
@@ -134,6 +157,36 @@ def recommend_login_budget(
invalid_total = int(invalid_query.count() or 0)
invalid_high = _count_high_value(db, invalid_query)
invalid_ordinary = max(0, invalid_total - invalid_high)
protection = load_protection_snapshot(db)
protected_ids = protection.relogin_ids
if protected_ids:
protected_valid = int(
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
)
nonprotected_valid_high = int(
_count_high_value(
db,
valid_query.filter(~Account.id.in_(protected_ids)),
)
or 0
)
nonprotected_invalid_high = int(
_count_high_value(
db,
invalid_query.filter(~Account.id.in_(protected_ids)),
)
or 0
)
else:
protected_valid = 0
protected_invalid = 0
nonprotected_valid_high = valid_high
nonprotected_invalid_high = invalid_high
nonprotected_valid = max(0, valid_total - protected_valid)
nonprotected_invalid = max(0, invalid_total - protected_invalid)
imported_total = int(
_automatable_accounts(db).filter(Account.status == "imported").count() or 0
)
@@ -154,40 +207,76 @@ def recommend_login_budget(
)
core_attempts = math.ceil(required_success / effective_rate)
manual_reserve = max(30, math.ceil(core_attempts * 0.1))
relogin_success = math.ceil(
(
invalid_total / RELOGIN_RECOVERY_DAYS
+ valid_total / CK_AVERAGE_LIFETIME_DAYS
)
/ effective_rate
)
onboarding_attempts = math.ceil(onboarding_pressure / effective_rate)
daily_attempts = max(
MIN_DAILY_ATTEMPTS,
core_attempts + manual_reserve,
relogin_success + onboarding_attempts + manual_reserve,
nonprotected_relogin_pressure_high = (
nonprotected_valid_high / CK_AVERAGE_LIFETIME_DAYS
+ nonprotected_invalid_high / RELOGIN_RECOVERY_DAYS
)
daily_attempts = min(daily_attempts, MAX_DAILY_ATTEMPTS)
hourly_attempts = max(1, math.ceil(daily_attempts / ASSUMED_ACTIVE_HOURS))
relogin_pressure_high = (
valid_high / CK_AVERAGE_LIFETIME_DAYS
+ invalid_high / RELOGIN_RECOVERY_DAYS
)
relogin_pressure_total = (
valid_total / CK_AVERAGE_LIFETIME_DAYS
+ invalid_total / RELOGIN_RECOVERY_DAYS
nonprotected_relogin_pressure_total = (
nonprotected_valid / CK_AVERAGE_LIFETIME_DAYS
+ nonprotected_invalid / RELOGIN_RECOVERY_DAYS
)
high_share = (
relogin_pressure_high / relogin_pressure_total
if relogin_pressure_total > 0
nonprotected_relogin_pressure_high
/ nonprotected_relogin_pressure_total
if nonprotected_relogin_pressure_total > 0
else 0.5
)
nonprotected_relogin_attempts = math.ceil(
nonprotected_relogin_pressure_total / effective_rate
)
relogin_high_limit = max(
0,
math.ceil(relogin_success * high_share),
math.ceil(nonprotected_relogin_attempts * high_share),
)
relogin_ordinary_limit = max(0, relogin_success - relogin_high_limit)
relogin_ordinary_limit = max(
0,
nonprotected_relogin_attempts - relogin_high_limit,
)
relogin_protected_limit = max(
50,
math.ceil(
(protected_invalid / RELOGIN_RECOVERY_DAYS) / effective_rate
),
)
lease_refresh_limit = max(
50,
math.ceil(
(protected_valid / CK_AVERAGE_LIFETIME_DAYS) / effective_rate
),
)
raw_relogin_limits = [
relogin_protected_limit,
lease_refresh_limit,
relogin_high_limit,
relogin_ordinary_limit,
]
planned_attempts = (
sum(raw_relogin_limits) + onboarding_attempts + manual_reserve
)
daily_attempts = min(
MAX_DAILY_ATTEMPTS,
max(
MIN_DAILY_ATTEMPTS,
core_attempts + manual_reserve,
planned_attempts,
),
)
available_relogin_attempts = max(
0,
daily_attempts - onboarding_attempts - manual_reserve,
)
(
relogin_protected_limit,
lease_refresh_limit,
relogin_high_limit,
relogin_ordinary_limit,
) = _fit_priority_budgets(
raw_relogin_limits,
available_relogin_attempts,
)
hourly_attempts = max(1, math.ceil(daily_attempts / ASSUMED_ACTIVE_HOURS))
if sample < MIN_RECENT_SAMPLE or recent_success_rate < 70:
concurrency = 3
@@ -201,6 +290,8 @@ def recommend_login_budget(
"hourly_attempt_limit": hourly_attempts,
"per_account_daily_limit": 2,
"onboarding_daily_limit": onboarding_attempts,
"relogin_protected_daily_limit": relogin_protected_limit,
"lease_refresh_daily_limit": lease_refresh_limit,
"relogin_high_value_daily_limit": relogin_high_limit,
"relogin_ordinary_daily_limit": relogin_ordinary_limit,
"manual_daily_limit": manual_reserve,
@@ -217,6 +308,8 @@ def recommend_login_budget(
"invalid_backlog": invalid_total,
"invalid_high_value": invalid_high,
"invalid_ordinary": invalid_ordinary,
"protected_valid_accounts": protected_valid,
"protected_invalid_backlog": protected_invalid,
"imported_backlog": imported_total,
"recent_sample": sample,
"recent_success_rate": recent_success_rate,
+388 -30
View File
@@ -3,9 +3,10 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, date, datetime
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 (
@@ -15,7 +16,10 @@ from ..models import (
LoginQuotaUsage,
LoginTask,
)
from .account_value import is_high_value_account
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"
@@ -23,12 +27,33 @@ 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")
@@ -53,6 +78,7 @@ def classify_login_category(
trigger_source: str = "manual",
now: datetime | None = None,
category: str = "",
protected: bool = False,
) -> str:
# 调用方显式指定分类时优先用它(例如租约 CK 续期)。
if category:
@@ -60,6 +86,8 @@ def classify_login_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)
@@ -166,13 +194,305 @@ def _category_limit(setting: LoginQuotaSetting, category: str) -> int:
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),
# 租约续期本质是「提前重登」,借用普通重登的日预算。
CATEGORY_LEASE_REFRESH: int(setting.relogin_ordinary_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,
*,
@@ -187,18 +507,24 @@ def reserve_login_attempt(
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:
category = classify_login_category(
account,
mode=mode,
trigger_source=trigger_source,
now=moment,
category=category,
)
attempt = LoginAttempt(
account_id=int(account.id),
batch_id=batch_id[:64],
category=category,
category=resolved_category,
trigger_source=trigger_source[:16],
created_by=created_by,
started_at=moment,
@@ -209,6 +535,9 @@ def reserve_login_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(
@@ -233,35 +562,59 @@ def reserve_login_attempt(
.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="该账号已达到今日登录尝试上限")
if _daily_total(db, quota_day) >= int(setting.daily_attempt_limit):
daily_used = _daily_total(db, quota_day)
daily_limit = int(setting.daily_attempt_limit)
if daily_used >= daily_limit:
return QuotaDecision(False, reason="全局每日登录尝试预算已用完")
if _hourly_total(db, quota_day, quota_hour) >= int(
setting.hourly_attempt_limit
):
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="全局每小时登录尝试预算已用完")
category = classify_login_category(
account,
mode=mode,
trigger_source=trigger_source,
now=moment,
category=category,
)
if _category_daily_total(db, quota_day, category) >= _category_limit(
setting, category
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"{category} 今日登录预算已用完")
return QuotaDecision(False, reason=f"{resolved_category} 今日登录预算已用完")
attempt = LoginAttempt(
account_id=int(account.id),
batch_id=batch_id[:64],
category=category,
category=resolved_category,
trigger_source=trigger_source[:16],
created_by=created_by,
started_at=moment,
@@ -269,7 +622,7 @@ def reserve_login_attempt(
quota_day=quota_day,
)
db.add(attempt)
for usage_category in (CATEGORY_ALL, category):
for usage_category in (CATEGORY_ALL, resolved_category):
usage = _usage_row(
db,
quota_day=quota_day,
@@ -289,7 +642,7 @@ def finish_login_attempt(
failure_kind: str = "",
now: datetime | None = None,
) -> None:
if attempt.status in {"success", "failed", "error", "stopped"}:
if attempt.status in {"success", "failed", "error", "stopped", "skipped"}:
return
moment = now or datetime.now(UTC)
attempt.status = status[:16]
@@ -307,7 +660,10 @@ def finish_login_attempt(
quota_hour=quota_hour,
category=usage_category,
)
if status == "success":
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
@@ -346,10 +702,12 @@ __all__ = [
"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",
]
+15 -19
View File
@@ -245,8 +245,8 @@ def get_relogin_limits() -> tuple[int, int]:
"""读取客服 CK 重登的重试与总时长限制。"""
return (
_positive_env_int("COOKIE_RELOGIN_MAX_RETRIES", 5),
# 单账号总时长:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟)
_positive_env_int("COOKIE_RELOGIN_MAX_TOTAL_TIME", 1800),
# 单账号总时长:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待
_positive_env_int("COOKIE_RELOGIN_MAX_TOTAL_TIME", 300),
)
@@ -533,6 +533,7 @@ class LoginBatchRunner:
category: str = "",
batch_id: str | None = None,
log_sink: Callable[[dict[str, Any]], None] | None = None,
batch_max_seconds: float | None = None,
):
self.db = db
self.account_ids = account_ids
@@ -569,6 +570,7 @@ class LoginBatchRunner:
self._completed = 0
# 批次起点(单调时钟):每个账号开始执行前据此判断批次是否已超时。
self._batch_started_at = 0.0
self._batch_max_seconds_override = batch_max_seconds
# 逐账号日志走模块级 loguru sink(见文件头 _LOG_CONTEXT),
# 这里保证 sink 与刷新线程都已就绪。
_install_task_log_sink()
@@ -674,17 +676,7 @@ class LoginBatchRunner:
task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first()
if task is None:
return
now = datetime.now(UTC)
message = f"未执行:{reason}"
task.attempt_status = "skipped"
task.attempt_message = message
task.attempt_batch_id = self.batch_id
task.attempt_at = now
task.finished_at = now
if not task.account.cookie:
task.status = "skipped"
task.message = message
task.logs = [_task_log_entry("warning", f"本次登录未执行:{reason}")]
self._record_skipped_attempt(task, task.account, reason)
worker_db.commit()
finally:
worker_db.close()
@@ -739,16 +731,17 @@ class LoginBatchRunner:
self._mark_relogin_stopped(task_id, "任务已停止,旧 Cookie 已保留")
return
# 批次在执行任务队列里占着一个槽。斗鱼邮箱验证码是攒批投递的,等一封
# 验证码最长 25 分钟/账号,批次不设上限的话 10 个账号能占着槽位跑近
# 一小时,把同队列的斗鱼履约批次饿死(新建任务直接报「斗鱼任务繁忙」)。
# 所以每个账号**开始执行前**都看一次批次时长,超时就不再接新账号。
budget = _batch_max_seconds()
# 每个账号**开始执行前**检查批次时长,超时就不再接新账号,避免单批无限占槽。
budget = (
_batch_max_seconds()
if self._batch_max_seconds_override is None
else max(0.0, float(self._batch_max_seconds_override))
)
if budget > 0 and self._batch_started_at > 0:
elapsed = time.monotonic() - self._batch_started_at
if elapsed > budget:
reason = (
f"批次已达 {int(budget)}s 时长上限,本轮未执行"
f"批次已达 {int(budget)}s 时长预算,本轮未执行"
"(该账号留待下一轮)"
)
self._push_log("warning", reason)
@@ -1252,6 +1245,9 @@ def _settle_login_attempts(batch_id: str) -> None:
if task_status == "success" or task_status == "account_verified":
status = "success"
failure_kind = ""
elif task_status == "skipped":
status = "skipped"
failure_kind = ""
elif task_status in CHECK_STATUS_MESSAGES:
status = "failed"
failure_kind = (
+27
View File
@@ -1774,11 +1774,35 @@ export interface AutomationJobUpdate {
concurrency?: number;
}
export interface AutomationLoginQuotaCategoryUsage {
priority: string;
category: string;
label: string;
limit: number;
used: number;
remaining: number;
pending: number;
}
export interface AutomationLoginQuotaUsageSummary {
quota_day: string;
quota_hour: number;
daily_limit: number;
daily_used: number;
daily_remaining: number;
hourly_limit: number;
hourly_used: number;
hourly_remaining: number;
categories: AutomationLoginQuotaCategoryUsage[];
}
export interface AutomationLoginQuota {
daily_attempt_limit: number;
hourly_attempt_limit: number;
per_account_daily_limit: number;
onboarding_daily_limit: number;
relogin_protected_daily_limit: number;
lease_refresh_daily_limit: number;
relogin_high_value_daily_limit: number;
relogin_ordinary_daily_limit: number;
manual_daily_limit: number;
@@ -1786,6 +1810,7 @@ export interface AutomationLoginQuota {
failure_pause_ratio: number;
enabled: boolean;
updated_at?: string | null;
usage?: AutomationLoginQuotaUsageSummary;
}
export interface AutomationLoginQuotaRecommendation {
@@ -1798,6 +1823,8 @@ export interface AutomationLoginQuotaRecommendation {
invalid_backlog: number;
invalid_high_value: number;
invalid_ordinary: number;
protected_valid_accounts: number;
protected_invalid_backlog: number;
imported_backlog: number;
recent_sample: number;
recent_success_rate: number;
+106 -8
View File
@@ -55,9 +55,11 @@ const BUDGET_LABELS: Record<string, string> = {
daily_attempt_limit: "全局每日尝试",
hourly_attempt_limit: "全局每小时尝试",
per_account_daily_limit: "单账号每日尝试",
onboarding_daily_limit: "首次登录",
relogin_high_value_daily_limit: "高价值账号重登",
relogin_ordinary_daily_limit: "普通账号重登",
relogin_protected_daily_limit: "P0 履约保护失效重登",
lease_refresh_daily_limit: "P1 履约快过期续期",
relogin_high_value_daily_limit: "P2 高价值账号重登",
relogin_ordinary_daily_limit: "P3 普通账号重登",
onboarding_daily_limit: "P4 首次登录",
manual_daily_limit: "人工登录保留",
login_concurrency: "登录并发",
failure_pause_ratio: "失败率熔断",
@@ -67,9 +69,11 @@ type BudgetFieldName =
| "daily_attempt_limit"
| "hourly_attempt_limit"
| "per_account_daily_limit"
| "onboarding_daily_limit"
| "relogin_protected_daily_limit"
| "lease_refresh_daily_limit"
| "relogin_high_value_daily_limit"
| "relogin_ordinary_daily_limit"
| "onboarding_daily_limit"
| "manual_daily_limit"
| "login_concurrency"
| "failure_pause_ratio";
@@ -84,9 +88,31 @@ const BUDGET_FIELDS: Array<{
{ name: "daily_attempt_limit", label: "全局每日尝试", min: 1, max: 1_000_000 },
{ name: "hourly_attempt_limit", label: "全局每小时尝试", min: 1, max: 100_000 },
{ name: "per_account_daily_limit", label: "单账号每日尝试", min: 1, max: 100 },
{ name: "onboarding_daily_limit", label: "首次登录预算", min: 0, max: 100_000 },
{ name: "relogin_high_value_daily_limit", label: "高价值重登预算", min: 0, max: 100_000 },
{ name: "relogin_ordinary_daily_limit", label: "普通重登预算", min: 0, max: 100_000 },
{
name: "relogin_protected_daily_limit",
label: "P0 履约保护失效重登预算",
min: 0,
max: 100_000,
},
{
name: "lease_refresh_daily_limit",
label: "P1 履约快过期续期预算",
min: 0,
max: 100_000,
},
{
name: "relogin_high_value_daily_limit",
label: "P2 高价值重登预算",
min: 0,
max: 100_000,
},
{
name: "relogin_ordinary_daily_limit",
label: "P3 普通重登预算",
min: 0,
max: 100_000,
},
{ name: "onboarding_daily_limit", label: "P4 首次登录预算", min: 0, max: 100_000 },
{ name: "manual_daily_limit", label: "人工登录保留", min: 0, max: 100_000 },
{ name: "login_concurrency", label: "登录并发", min: 1, max: 10 },
{ name: "failure_pause_ratio", label: "失败率熔断阈值", min: 0, max: 100, suffix: "%" },
@@ -119,7 +145,7 @@ const JOB_UI: Record<string, JobUiSpec> = {
showConcurrency: false,
},
lease_ck_refresh: {
description: "对仍有效、但预测 24 小时内到期的生效租约账号提前登录续 CK;只处理 platform_fulfillment / douyu_collab 租约。",
description: "对仍有效、但预测 24 小时内到期的履约保护账号提前登录续 CK;覆盖预售、协作单和生效租约。",
core: true,
showRecheck: false,
showConcurrency: true,
@@ -654,6 +680,78 @@ export default function AutomationPage() {
const budgetTab = (
<Space orientation="vertical" size={16} style={{ width: "100%" }}>
{loginQuota?.usage ? (
<Card
title="今日优先级配额消耗与积压"
extra={
<Space size={16}>
<Text type="secondary">
今日全局 {loginQuota.usage.daily_used} / {loginQuota.usage.daily_limit}
</Text>
<Text type="secondary">
本小时 {loginQuota.usage.hourly_used} / {loginQuota.usage.hourly_limit}
</Text>
</Space>
}
>
<Alert
type="info"
showIcon
style={{ marginBottom: 12 }}
message="严格按 P0 > P1 > P2 > P3 > P4 顺序预留与调度"
description="当剩余小时/日配额紧张时,低优先级类别会自动为高优先级类别让路;其中 P0/P1 涵盖预售、协作单和生效租约全部履约保护目标。"
/>
<Table
rowKey="category"
size="small"
pagination={false}
dataSource={loginQuota.usage.categories}
columns={[
{
title: "优先级",
dataIndex: "priority",
width: 85,
render: (value: string) => (
<Tag
color={
value === "P0"
? "red"
: value === "P1"
? "orange"
: value === "P2"
? "gold"
: value === "人工"
? "green"
: "default"
}
>
{value}
</Tag>
),
},
{ title: "类别", dataIndex: "label" },
{
title: "待处理积压",
dataIndex: "pending",
width: 110,
render: (value: number, row) =>
row.category === "manual_login" ? "-" : value,
},
{ title: "今日已用", dataIndex: "used", width: 100 },
{ title: "每日上限", dataIndex: "limit", width: 100 },
{
title: "今日剩余",
dataIndex: "remaining",
width: 100,
render: (value: number) => (
<Text type={value > 0 ? "success" : "danger"}>{value}</Text>
),
},
]}
/>
</Card>
) : null}
<Card
title="登录预算与并发"
extra={
+2 -1
View File
@@ -52,9 +52,10 @@ const LOGIN_CATEGORY_LABELS: Record<string, string> = {
onboarding: '首次登录',
relogin_high_value: '高价值重登',
relogin_ordinary: '普通重登',
relogin_protected: '履约保护重登',
manual: '人工登录',
account_check: '账号检测',
lease_refresh: '租约CK续期',
lease_refresh: '履约快过期续期',
};
function loginSourceLabel(task: LoginTaskItem) {