feat(automation): 增加登录预算动态建议
This commit is contained in:
@@ -32,6 +32,7 @@ from ..services.automation import (
|
||||
run_job_now,
|
||||
scheduler_status,
|
||||
)
|
||||
from ..services.login_budget_recommendation import recommend_login_budget
|
||||
|
||||
router = APIRouter(prefix="/api/automation", tags=["自动化"])
|
||||
|
||||
@@ -179,6 +180,15 @@ def get_login_quota(
|
||||
return _login_quota_out(row)
|
||||
|
||||
|
||||
@router.get("/login-quota/recommendation")
|
||||
def get_login_quota_recommendation(
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("automation:view")),
|
||||
):
|
||||
"""Advisory budget sizing; applying it remains an explicit operator action."""
|
||||
return recommend_login_budget(db)
|
||||
|
||||
|
||||
@router.put("/login-quota")
|
||||
def update_login_quota(
|
||||
payload: LoginQuotaUpdate,
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Advisory login-budget sizing from current inventory and recent outcomes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Account, LoginAttempt, LoginQuotaSetting
|
||||
from .account_lifecycle import MANUAL_KINDS, MANUAL_STATES
|
||||
from .account_value import is_high_value_expr
|
||||
|
||||
CK_AVERAGE_LIFETIME_DAYS = 7.38
|
||||
RELOGIN_RECOVERY_DAYS = 3
|
||||
ONBOARDING_RAMP_DAYS = 7
|
||||
RECENT_WINDOW_DAYS = 7
|
||||
MIN_RECENT_SAMPLE = 20
|
||||
DEFAULT_SUCCESS_RATE = 70.0
|
||||
MIN_EFFECTIVE_SUCCESS_RATE = 35.0
|
||||
MIN_DAILY_ATTEMPTS = 50
|
||||
MAX_DAILY_ATTEMPTS = 5000
|
||||
ASSUMED_ACTIVE_HOURS = 12
|
||||
|
||||
|
||||
def _automatable_accounts(db: Session):
|
||||
return db.query(Account).filter(
|
||||
Account.auto_managed.is_(True),
|
||||
Account.status.notin_(MANUAL_STATES),
|
||||
)
|
||||
|
||||
|
||||
def _count_high_value(db: Session, query) -> int:
|
||||
return int(query.filter(is_high_value_expr()).count() or 0)
|
||||
|
||||
|
||||
def _recent_login_outcomes(
|
||||
db: Session,
|
||||
*,
|
||||
now: datetime,
|
||||
) -> tuple[int, float]:
|
||||
start_day = now.date() - timedelta(days=RECENT_WINDOW_DAYS - 1)
|
||||
rows = (
|
||||
db.query(
|
||||
LoginAttempt.status,
|
||||
LoginAttempt.failure_kind,
|
||||
func.count(LoginAttempt.id),
|
||||
)
|
||||
.filter(
|
||||
LoginAttempt.quota_day >= start_day,
|
||||
LoginAttempt.category.in_(
|
||||
("onboarding", "relogin_high_value", "relogin_ordinary")
|
||||
),
|
||||
)
|
||||
.group_by(LoginAttempt.status, LoginAttempt.failure_kind)
|
||||
.all()
|
||||
)
|
||||
success = 0
|
||||
failed = 0
|
||||
for status, failure_kind, count in rows:
|
||||
count_value = int(count or 0)
|
||||
if status == "success":
|
||||
success += count_value
|
||||
elif status in {"failed", "error", "stopped"} and failure_kind != "email_quota":
|
||||
failed += count_value
|
||||
sample = success + failed
|
||||
rate = success * 100 / sample if sample else DEFAULT_SUCCESS_RATE
|
||||
return sample, round(rate, 1)
|
||||
|
||||
|
||||
def _current_quota(db: Session) -> dict[str, int]:
|
||||
row = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first()
|
||||
if row is None:
|
||||
return {
|
||||
"daily_attempt_limit": 1500,
|
||||
"hourly_attempt_limit": 100,
|
||||
"per_account_daily_limit": 2,
|
||||
"onboarding_daily_limit": 150,
|
||||
"relogin_high_value_daily_limit": 300,
|
||||
"relogin_ordinary_daily_limit": 500,
|
||||
"manual_daily_limit": 300,
|
||||
"login_concurrency": 3,
|
||||
"failure_pause_ratio": 40,
|
||||
"enabled": True,
|
||||
}
|
||||
return {
|
||||
"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_high_value_daily_limit": int(
|
||||
row.relogin_high_value_daily_limit
|
||||
),
|
||||
"relogin_ordinary_daily_limit": int(row.relogin_ordinary_daily_limit),
|
||||
"manual_daily_limit": int(row.manual_daily_limit),
|
||||
"login_concurrency": int(row.login_concurrency),
|
||||
"failure_pause_ratio": int(row.failure_pause_ratio),
|
||||
"enabled": bool(row.enabled),
|
||||
}
|
||||
|
||||
|
||||
def recommend_login_budget(
|
||||
db: Session,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Return a conservative quota recommendation; never mutate current settings."""
|
||||
moment = now or datetime.now(UTC)
|
||||
manual_kinds = tuple(sorted(MANUAL_KINDS))
|
||||
|
||||
valid_query = _automatable_accounts(db).filter(
|
||||
Account.cookie.isnot(None),
|
||||
Account.cookie != "",
|
||||
Account.ck_check_status == "valid",
|
||||
)
|
||||
valid_total = int(valid_query.count() or 0)
|
||||
valid_high = _count_high_value(db, valid_query)
|
||||
valid_ordinary = max(0, valid_total - valid_high)
|
||||
|
||||
invalid_query = _automatable_accounts(db).filter(
|
||||
Account.cookie.isnot(None),
|
||||
Account.cookie != "",
|
||||
Account.ck_check_status == "invalid",
|
||||
Account.relogin_attempts < 2,
|
||||
func.coalesce(Account.relogin_failure_kind, "").notin_(manual_kinds),
|
||||
)
|
||||
invalid_total = int(invalid_query.count() or 0)
|
||||
invalid_high = _count_high_value(db, invalid_query)
|
||||
invalid_ordinary = max(0, invalid_total - invalid_high)
|
||||
imported_total = int(
|
||||
_automatable_accounts(db).filter(Account.status == "imported").count() or 0
|
||||
)
|
||||
|
||||
sample, recent_success_rate = _recent_login_outcomes(db, now=moment)
|
||||
effective_rate = (
|
||||
recent_success_rate
|
||||
if sample >= MIN_RECENT_SAMPLE
|
||||
else DEFAULT_SUCCESS_RATE
|
||||
)
|
||||
effective_rate = max(effective_rate, MIN_EFFECTIVE_SUCCESS_RATE) / 100
|
||||
|
||||
expected_daily_invalid = valid_total / CK_AVERAGE_LIFETIME_DAYS
|
||||
recovery_pressure = invalid_total / RELOGIN_RECOVERY_DAYS
|
||||
onboarding_pressure = imported_total / ONBOARDING_RAMP_DAYS
|
||||
required_success = math.ceil(
|
||||
expected_daily_invalid + recovery_pressure + onboarding_pressure
|
||||
)
|
||||
core_attempts = math.ceil(required_success / effective_rate)
|
||||
manual_reserve = max(30, math.ceil(core_attempts * 0.1))
|
||||
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,
|
||||
)
|
||||
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
|
||||
)
|
||||
high_share = (
|
||||
relogin_pressure_high / relogin_pressure_total
|
||||
if relogin_pressure_total > 0
|
||||
else 0.5
|
||||
)
|
||||
relogin_high_limit = max(
|
||||
0,
|
||||
math.ceil(relogin_success * high_share),
|
||||
)
|
||||
relogin_ordinary_limit = max(0, relogin_success - relogin_high_limit)
|
||||
|
||||
if sample < MIN_RECENT_SAMPLE or recent_success_rate < 70:
|
||||
concurrency = 3
|
||||
elif recent_success_rate >= 90 and invalid_total >= 50:
|
||||
concurrency = 6
|
||||
else:
|
||||
concurrency = 4
|
||||
|
||||
recommended = {
|
||||
"daily_attempt_limit": daily_attempts,
|
||||
"hourly_attempt_limit": hourly_attempts,
|
||||
"per_account_daily_limit": 2,
|
||||
"onboarding_daily_limit": onboarding_attempts,
|
||||
"relogin_high_value_daily_limit": relogin_high_limit,
|
||||
"relogin_ordinary_daily_limit": relogin_ordinary_limit,
|
||||
"manual_daily_limit": manual_reserve,
|
||||
"login_concurrency": concurrency,
|
||||
}
|
||||
current = _current_quota(db)
|
||||
return {
|
||||
"generated_at": moment,
|
||||
"window_days": RECENT_WINDOW_DAYS,
|
||||
"basis": {
|
||||
"valid_accounts": valid_total,
|
||||
"valid_high_value": valid_high,
|
||||
"valid_ordinary": valid_ordinary,
|
||||
"invalid_backlog": invalid_total,
|
||||
"invalid_high_value": invalid_high,
|
||||
"invalid_ordinary": invalid_ordinary,
|
||||
"imported_backlog": imported_total,
|
||||
"recent_sample": sample,
|
||||
"recent_success_rate": recent_success_rate,
|
||||
"effective_success_rate": round(effective_rate * 100, 1),
|
||||
"expected_daily_invalid": round(expected_daily_invalid, 2),
|
||||
"required_daily_success": required_success,
|
||||
"manual_reserve": manual_reserve,
|
||||
},
|
||||
"current": current,
|
||||
"recommended": recommended,
|
||||
"delta": {
|
||||
key: recommended[key] - current[key]
|
||||
for key in recommended
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["recommend_login_budget"]
|
||||
Reference in New Issue
Block a user