diff --git a/docs/斗鱼/账号CK全自动化计划.md b/docs/斗鱼/账号CK全自动化计划.md index c1945cd..e0ff0e9 100644 --- a/docs/斗鱼/账号CK全自动化计划.md +++ b/docs/斗鱼/账号CK全自动化计划.md @@ -264,3 +264,31 @@ - 不要用外部极验服务替代本地识别。 先做 P1 的 20 个账号样本,拿到成功率再决定是否放量。 + +## 10. 本轮实现(dev_11.24 分支) + +已实现,**未部署**: + +| 模块 | 内容 | +| --- | --- | +| `services/login_automation.py` | 共享登录批次执行器;`wgapi` 主通道,`email_code` 失败自动切 `iframe`;极验/凭证/配额不切 | +| `jobs/account_onboarding.py` | 首次登录作业,选中无 CK/未登录、自动托管、无在途登录的账号 | +| `automation/__init__.py` | 注册 `account_onboarding`,**默认关闭**,batch=20,间隔 5 分钟 | +| `jobs/ck_relogin.py` | 重登批次里 email_code 失败账号自动走 iframe 回退 | +| 测试 | 首次登录选择、回退通道、作业默认关闭、既有重登/注册表回归 | + +执行方式: + +1. 部署分支但作业保持关闭; +2. 在自动化中心手动跑 `account_onboarding`,建议 batch=20; +3. 看 `automation_runs.detail.batchIds / fallbackBatchIds / failureKinds`; +4. 成功率可接受后再打开作业开关; +5. 重登作业等 email 回退实测后再恢复。 + +安全边界: + +- 首次登录失败不覆盖旧 CK(runner 只在成功时写 CK); +- 同一账号在途登录会被选择条件排除; +- 预算走 `onboarding_daily_limit`; +- 回退只针对 `email_code`,不会把配额/极验/凭证失败反复重试; +- 作业默认关闭,可随时暂停。 diff --git a/tests/test_account_onboarding_job.py b/tests/test_account_onboarding_job.py new file mode 100644 index 0000000..482798f --- /dev/null +++ b/tests/test_account_onboarding_job.py @@ -0,0 +1,153 @@ +"""首次登录自动化作业与邮箱双通道回退测试。""" + +from __future__ import annotations + +from web.backend.models import Account, AutomationJob, LoginTask, User +from web.backend.services.automation.jobs import account_onboarding as job +from web.backend.services.login_automation import LoginBatchOutcome + + +def _account(name: str, **overrides) -> Account: + values = { + "username": name, + "password": "p", + "email": f"{name}@example.com", + "email_password": "ep", + "status": "imported", + "auto_managed": True, + "cookie": "", + "ck_check_status": "", + } + values.update(overrides) + return Account(**values) + + +def _job() -> AutomationJob: + return AutomationJob( + key="account_onboarding", + title="账号首次登录(CK 获取)", + enabled=True, + run_interval_seconds=300, + batch_size=20, + concurrency=3, + ) + + +def _admin(db) -> User: + user = User( + username="onboarding-admin", + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + db.commit() + return user + + +def test_selector_only_picks_unlogged_automatable_accounts(db): + admin = _admin(db) + selectable = _account("onboarding-selectable") + has_cookie = _account("onboarding-has-cookie", cookie="acf_uid=1") + opted_out = _account("onboarding-opted-out", auto_managed=False) + manual = _account("onboarding-manual", status="manual") + in_flight = _account("onboarding-in-flight") + db.add_all([selectable, has_cookie, opted_out, manual, in_flight]) + db.flush() + db.add( + LoginTask( + batch_id="inflight", + account_id=in_flight.id, + created_by=admin.id, + attempt_status="pending", + ) + ) + db.commit() + + rows = job.build_select_query(db, _job()).all() + + assert [row.id for row in rows] == [selectable.id] + assert job.count_pending_onboarding(db) == 1 + + +def test_run_account_onboarding_returns_batch_summary(db, monkeypatch): + _admin(db) + first = _account("onboarding-first") + second = _account("onboarding-second") + db.add_all([first, second]) + db.commit() + outcome = LoginBatchOutcome( + account_ids=[first.id, second.id], + attempted_ids=[first.id, second.id], + success_ids=[first.id], + failed_ids=[second.id], + failure_kinds={second.id: "email_code"}, + batch_ids=["batch-wgapi"], + fallback_batch_ids=["batch-iframe"], + fallback_used=True, + fallback_success_ids=[], + ) + monkeypatch.setattr( + job, + "run_login_batch_with_fallback", + lambda *args, **kwargs: outcome, + ) + + result = job.run_account_onboarding(db, _job()) + + assert result["scanned"] == 2 + assert result["valid"] == 1 + assert result["invalid"] == 1 + assert "邮箱回退" in result["message"] + assert result["detail"]["fallbackUsed"] is True + assert result["detail"]["fallbackBatchIds"] == ["batch-iframe"] + + +def test_email_fallback_switches_to_iframe_only_for_email_code(db, monkeypatch): + from web.backend.services import login_automation as automation + + calls: list[tuple[str, list[int]]] = [] + + def fake_run(_db, *, account_ids, api_strategy, **_kwargs): + calls.append((api_strategy, list(account_ids))) + return "batch-wgapi" if api_strategy == "wgapi" else "batch-iframe" + + def fake_collect(batch_id): + if batch_id == "batch-wgapi": + return { + 11: ("failed", "email_code"), + 12: ("failed", "credential"), + 13: ("success", ""), + } + return {11: ("success", "")} + + monkeypatch.setattr(automation, "run_login_batch", fake_run) + monkeypatch.setattr(automation, "collect_batch_results", fake_collect) + + outcome = automation.run_login_batch_with_fallback( + db, + account_ids=[11, 12, 13], + mode="login", + created_by=1, + ) + + assert calls == [("wgapi", [11, 12, 13]), ("iframe", [11])] + assert outcome.success_ids == [11, 13] + assert outcome.failed_ids == [12] + assert outcome.failure_kinds == {12: "credential"} + assert outcome.fallback_success_ids == [11] + + +def test_onboarding_job_is_registered_but_default_off(): + from web.backend.services.automation import ( + register_default_jobs, + registered_jobs, + reset_registry, + ) + + reset_registry() + register_default_jobs() + spec = registered_jobs()["account_onboarding"] + assert spec.default_enabled is False + assert "首次登录" in spec.title + assert spec.batch_size == 20 diff --git a/web/backend/services/automation/__init__.py b/web/backend/services/automation/__init__.py index fd7ef2d..6cf0dd2 100644 --- a/web/backend/services/automation/__init__.py +++ b/web/backend/services/automation/__init__.py @@ -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, diff --git a/web/backend/services/automation/jobs/account_onboarding.py b/web/backend/services/automation/jobs/account_onboarding.py new file mode 100644 index 0000000..de8a698 --- /dev/null +++ b/web/backend/services/automation/jobs/account_onboarding.py @@ -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"] diff --git a/web/backend/services/automation/jobs/ck_relogin.py b/web/backend/services/automation/jobs/ck_relogin.py index 9ea66bd..405e80d 100644 --- a/web/backend/services/automation/jobs/ck_relogin.py +++ b/web/backend/services/automation/jobs/ck_relogin.py @@ -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, diff --git a/web/backend/services/login_automation.py b/web/backend/services/login_automation.py new file mode 100644 index 0000000..342d8fe --- /dev/null +++ b/web/backend/services/login_automation.py @@ -0,0 +1,243 @@ +"""自动登录批次的共享执行器:首次登录 / 重登 / 邮箱双通道回退。""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from sqlalchemy.orm import Session + +from ..database import WorkerSessionLocal +from ..models import LoginAttempt, ProxyConfig, User +from .login_service import LoginBatchRunner, get_relogin_limits + +#: 默认登录接口;旧版 iframe 只在邮箱验证码失败时作为回退通道。 +PRIMARY_LOGIN_API = "wgapi" +FALLBACK_LOGIN_API = "iframe" +#: 触发回退的失败分型。邮箱配额满不代表通道坏了,不切换。 +EMAIL_FALLBACK_KINDS = frozenset({"email_code"}) +DEFAULT_MAX_TOTAL_TIME = 240 +DEFAULT_MAX_RETRIES = 5 + + +@dataclass +class LoginBatchOutcome: + account_ids: list[int] = field(default_factory=list) + attempted_ids: list[int] = field(default_factory=list) + success_ids: list[int] = field(default_factory=list) + failed_ids: list[int] = field(default_factory=list) + skipped_ids: list[int] = field(default_factory=list) + failure_kinds: dict[int, str] = field(default_factory=dict) + batch_ids: list[str] = field(default_factory=list) + fallback_batch_ids: list[str] = field(default_factory=list) + fallback_used: bool = False + fallback_success_ids: list[int] = field(default_factory=list) + + @property + def scanned(self) -> int: + return len(self.attempted_ids) + + @property + def success(self) -> int: + return len(self.success_ids) + + @property + def failed(self) -> int: + return len(self.failed_ids) + + @property + def skipped(self) -> int: + return len(self.skipped_ids) + + @property + def fallback_success(self) -> int: + return len(self.fallback_success_ids) + + def detail(self) -> dict[str, Any]: + return { + "batchIds": self.batch_ids, + "fallbackBatchIds": self.fallback_batch_ids, + "fallbackUsed": self.fallback_used, + "fallbackSuccess": self.fallback_success, + "attempted": self.scanned, + "skipped": self.skipped, + "failureKinds": { + str(account_id): kind + for account_id, kind in sorted(self.failure_kinds.items()) + }, + } + + +def system_user_id(db: Session) -> int | None: + """自动登录落 created_by 需要真实用户;与 ck_relogin 保持一致。""" + row = ( + db.query(User.id) + .filter(User.role == "super_admin") + .order_by(User.id.asc()) + .first() + ) + if row: + return int(row[0]) + row = db.query(User.id).order_by(User.id.asc()).first() + return int(row[0]) if row else None + + +def _max_total_time() -> int: + try: + _, configured = get_relogin_limits() + return max(30, min(int(configured or DEFAULT_MAX_TOTAL_TIME), DEFAULT_MAX_TOTAL_TIME)) + except Exception: # noqa: BLE001 - 配置异常时用安全默认值 + return DEFAULT_MAX_TOTAL_TIME + + +def run_login_batch( + db: Session, + *, + account_ids: list[int], + mode: str, + created_by: int, + api_strategy: str, + concurrency: int = 3, + max_total_time: int | None = None, + max_login_retries: int = DEFAULT_MAX_RETRIES, +) -> str: + """同步跑一个登录批次,返回 batch_id;runner 使用独立会话。""" + proxy = db.query(ProxyConfig).first() + runner_db = WorkerSessionLocal() + try: + runner = LoginBatchRunner( + db=runner_db, + account_ids=list(dict.fromkeys(int(value) for value in account_ids)), + created_by=int(created_by), + creator_permissions=["login:view_all", "cookie:operate"], + max_login_retries=max(1, int(max_login_retries)), + max_total_time=( + _max_total_time() + if max_total_time is None + else max(30, int(max_total_time)) + ), + proxy_config=proxy, + log_queue=None, + loop=None, + concurrency=max(1, min(int(concurrency or 3), 8)), + api_strategy=api_strategy, + mode=mode, + trigger_source="automation", + ) + batch_id = runner.batch_id + runner.run() + return batch_id + finally: + runner_db.close() + + +def collect_batch_results(batch_id: str) -> dict[int, tuple[str, str]]: + """在新事务里读回批次结果:account_id -> (status, failure_kind)。""" + session = WorkerSessionLocal() + try: + rows = ( + session.query( + LoginAttempt.account_id, + LoginAttempt.status, + LoginAttempt.failure_kind, + ) + .filter(LoginAttempt.batch_id == batch_id) + .order_by(LoginAttempt.id.asc()) + .all() + ) + result: dict[int, tuple[str, str]] = {} + for account_id, status, kind in rows: + result[int(account_id)] = (str(status or ""), str(kind or "")) + return result + finally: + session.close() + + +def _is_success(status: str) -> bool: + return status == "success" + + +def _is_failed(status: str) -> bool: + return status in {"failed", "error", "stopped"} + + +def run_login_batch_with_fallback( + db: Session, + *, + account_ids: list[int], + mode: str, + created_by: int, + concurrency: int = 3, + max_total_time: int | None = None, + max_login_retries: int = DEFAULT_MAX_RETRIES, +) -> LoginBatchOutcome: + """先走 wgapi;仅对 email_code 失败账号切 iframe 重试一次。 + + 首次登录和重登共用。邮箱配额满、极验、凭证、网络失败都不切通道。 + """ + ordered_ids = list(dict.fromkeys(int(value) for value in account_ids)) + outcome = LoginBatchOutcome(account_ids=ordered_ids) + + primary_batch = run_login_batch( + db, + account_ids=ordered_ids, + mode=mode, + created_by=created_by, + api_strategy=PRIMARY_LOGIN_API, + concurrency=concurrency, + max_total_time=max_total_time, + max_login_retries=max_login_retries, + ) + outcome.batch_ids.append(primary_batch) + primary = collect_batch_results(primary_batch) + + success_ids = {account_id for account_id, (status, _) in primary.items() if _is_success(status)} + email_failed_ids = [ + account_id + for account_id, (status, kind) in primary.items() + if account_id not in success_ids + and _is_failed(status) + and kind in EMAIL_FALLBACK_KINDS + ] + + fallback: dict[int, tuple[str, str]] = {} + if email_failed_ids: + outcome.fallback_used = True + fallback_batch = run_login_batch( + db, + account_ids=email_failed_ids, + mode=mode, + created_by=created_by, + api_strategy=FALLBACK_LOGIN_API, + concurrency=concurrency, + max_total_time=max_total_time, + max_login_retries=max_login_retries, + ) + outcome.fallback_batch_ids.append(fallback_batch) + fallback = collect_batch_results(fallback_batch) + for account_id, (status, _) in fallback.items(): + if _is_success(status): + success_ids.add(account_id) + + attempted = dict(primary) + attempted.update(fallback) + outcome.attempted_ids = sorted(attempted) + outcome.success_ids = sorted(success_ids) + outcome.failed_ids = [ + account_id + for account_id in outcome.attempted_ids + if account_id not in success_ids + ] + outcome.skipped_ids = [ + account_id for account_id in ordered_ids if account_id not in attempted + ] + for account_id in outcome.failed_ids: + status, kind = attempted.get(account_id, ("", "")) + if not _is_success(status): + outcome.failure_kinds[account_id] = kind + outcome.fallback_success_ids = sorted( + account_id + for account_id, (status, _) in fallback.items() + if _is_success(status) + ) + return outcome diff --git a/web/frontend/src/pages/AutomationPage.tsx b/web/frontend/src/pages/AutomationPage.tsx index ce6606b..a1377b3 100644 --- a/web/frontend/src/pages/AutomationPage.tsx +++ b/web/frontend/src/pages/AutomationPage.tsx @@ -112,6 +112,12 @@ const JOB_UI: Record = { showRecheck: true, showConcurrency: true, }, + account_onboarding: { + description: "对没有 CK 的未登录账号执行首次真实登录;成功后写入 CK 并联动商品能力同步。默认关闭,建议先小批量。", + core: true, + showRecheck: false, + showConcurrency: true, + }, account_sync_queue: { description: "独立消费账号目录、积分、鱼翅和角色同步工作,避免阻塞订单选号。", core: true,