feat(automation): 实现首次登录与邮箱双通道回退

- 新增 account_onboarding 首次登录作业,默认关闭,batch=20
- 新增 login_automation 共享执行器:wgapi 主通道,email_code 失败自动切 iframe
- 重登作业对 email_code 失败账号增加 iframe 回退
- 自动化中心展示首次登录作业
- 补充首次登录/回退/注册表回归测试
- 文档补充执行顺序与本轮实现
This commit is contained in:
yml
2026-11-24 15:48:09 +08:00
parent f24a5f0579
commit 8449b726a3
7 changed files with 602 additions and 0 deletions
@@ -12,6 +12,12 @@ from .jobs.account_capability_refresh import (
from .jobs.account_capability_refresh import (
run_account_capability_refresh,
)
from .jobs.account_onboarding import (
JOB_KEY as ACCOUNT_ONBOARDING_KEY,
)
from .jobs.account_onboarding import (
run_account_onboarding,
)
from .jobs.account_supply_replenishment import (
JOB_KEY as ACCOUNT_SUPPLY_REPLENISHMENT_KEY,
)
@@ -64,6 +70,7 @@ from .scheduler import (
__all__ = [
"ACCOUNT_CAPABILITY_REFRESH_KEY",
"ACCOUNT_ONBOARDING_KEY",
"ACCOUNT_SUPPLY_REPLENISHMENT_KEY",
"ACCOUNT_SYNC_QUEUE_KEY",
"ACCOUNT_VALUE_PROJECTION_KEY",
@@ -80,6 +87,7 @@ __all__ = [
"registered_jobs",
"reset_registry",
"run_account_capability_refresh",
"run_account_onboarding",
"run_account_supply_replenishment",
"run_account_sync_queue_job",
"run_account_value_projection",
@@ -149,6 +157,19 @@ def register_default_jobs() -> None:
run=run_account_capability_refresh,
)
)
register_job(
JobSpec(
key=ACCOUNT_ONBOARDING_KEY,
title="账号首次登录(CK 获取)",
# 默认关闭:先在自动化中心手动跑 20 个样本,确认成功率后再打开。
interval_seconds=300,
run_interval_seconds=300,
batch_size=20,
concurrency=3,
run=run_account_onboarding,
default_enabled=False,
)
)
register_job(
JobSpec(
key=POINTS_EXPIRE_KEY,
@@ -0,0 +1,121 @@
"""账号首次登录:把未登录账号自动变成持有有效 CK 的可用账号。"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session
from ....models import Account, AutomationJob, LoginTask
from ...account_lifecycle import MANUAL_STATES, STATUS_MANUAL
from ...login_automation import run_login_batch_with_fallback, system_user_id
JOB_KEY = "account_onboarding"
def _in_flight_login_exists():
return (
select(LoginTask.id)
.where(
LoginTask.account_id == Account.id,
func.coalesce(LoginTask.attempt_status, "").in_(("pending", "running")),
)
.exists()
)
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)),
or_(Account.cookie.is_(None), Account.cookie == ""),
~_in_flight_login_exists(),
)
.order_by(Account.id.asc())
)
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:
return int(
db.query(func.count(Account.id))
.filter(
Account.auto_managed.is_(True),
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
or_(Account.cookie.is_(None), Account.cookie == ""),
~_in_flight_login_exists(),
)
.scalar()
or 0
)
def run_account_onboarding(db: Session, job: AutomationJob) -> dict[str, Any]:
now = datetime.now(UTC)
user_id = system_user_id(db)
if user_id is None:
return {
"scanned": 0,
"valid": 0,
"invalid": 0,
"skipped": 0,
"message": "库里没有可用用户,无法以系统身份发起首次登录",
}
accounts = build_select_query(db, job).all()
pending = count_pending_onboarding(db)
if not accounts:
return {
"scanned": 0,
"valid": 0,
"invalid": 0,
"skipped": 0,
"message": f"没有待首次登录账号(当前积压 {pending})",
}
account_ids = [int(account.id) for account in accounts]
outcome = run_login_batch_with_fallback(
db,
account_ids=account_ids,
mode="login",
created_by=user_id,
concurrency=max(1, int(job.concurrency or 3)),
)
parts = [
f"本轮首次登录 {outcome.scanned} 个",
f"成功 {outcome.success}",
f"失败 {outcome.failed}",
]
if outcome.skipped:
parts.append(f"预算/预检跳过 {outcome.skipped}")
if outcome.fallback_used:
parts.append(
f"邮箱回退 wgapi→iframe {outcome.fallback_success} 个成功"
)
if pending:
parts.append(f"待首次登录积压 {pending}")
return {
"scanned": outcome.scanned,
"valid": outcome.success,
"invalid": outcome.failed,
"skipped": outcome.skipped,
"message": ",".join(parts),
"detail": {
**outcome.detail(),
"pending": pending,
"selected": len(account_ids),
"startedAt": now.isoformat(),
},
}
__all__ = ["JOB_KEY", "build_select_query", "count_pending_onboarding", "run_account_onboarding"]
@@ -54,6 +54,7 @@ from ...account_work_queue import (
fail_account_work_type,
reschedule_account_work_type,
)
from ...login_automation import collect_batch_results, run_login_batch
from ...login_failure import classify_failure
from ...login_service import LoginBatchRunner, get_relogin_limits
@@ -782,6 +783,31 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
max_attempts=max_attempts,
expected_account_ids=account_ids,
)
# 邮箱取码失败先切 iframe 再试一次;只对 email_code 失败,不碰极验/凭证/配额。
fallback_success = 0
fallback_batch_id = ""
email_failed_ids = [
account_id
for account_id, (status, kind) in collect_batch_results(batch_id).items()
if status in {"failed", "error"} and kind == "email_code"
]
if email_failed_ids:
fallback_batch_id = run_login_batch(
db,
account_ids=email_failed_ids,
mode="relogin",
created_by=system_user_id,
api_strategy="iframe",
concurrency=max(1, min(int(job.concurrency or 3), 8)),
max_total_time=min(int(max_total_time), AUTO_MAX_TOTAL_TIME),
)
fallback_success = sum(
1
for status, _ in collect_batch_results(fallback_batch_id).values()
if status == "success"
)
counters["valid"] += fallback_success
counters["invalid"] = max(0, counters["invalid"] - fallback_success)
paused, hard_failures, hard_failure_ratio = evaluate_failure_circuit(
counters,
config,
@@ -799,6 +825,8 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
parts.append(f"待重试 {counters['retry']}")
if counters["email_quota"]:
parts.append(f"其中配额满 {counters['email_quota']}(退避到次日)")
if fallback_success:
parts.append(f"邮箱回退 wgapi→iframe {fallback_success} 个成功")
if counters["manual"]:
parts.append(f"转人工 {counters['manual']}")
if hard_failures:
@@ -823,6 +851,8 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
"manual": counters["manual"],
"retry": counters["retry"],
"email_quota": counters["email_quota"],
"fallback_batch_id": fallback_batch_id,
"fallback_success": fallback_success,
"hard_failures": hard_failures,
"hard_failure_ratio": round(hard_failure_ratio, 4),
"paused": paused,