From 03c7c74eab37c071eee3ded6a938fd1e3ca20f75 Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 24 Nov 2026 18:04:09 +0800 Subject: [PATCH] =?UTF-8?q?feat(automation):=20=E5=A2=9E=E5=8A=A0=E7=A7=9F?= =?UTF-8?q?=E7=BA=A6=20CK=20=E5=88=B0=E6=9C=9F=E5=89=8D=E5=88=B7=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 保护组新增 lease_bound,覆盖全部生效履约/协作租约 - 新增 lease_ck_refresh 作业,提前 24h 为有效 CK 续期 - 已失效重登仍由 ck_relogin 处理 - 失败按类型设置退避,避免每轮重复撞 - 补充保护组、选行、作业执行测试 --- docs/设计-账号全生命周期.md | 40 +++++ tests/test_account_protection_service.py | 53 ++++++ tests/test_lease_ck_refresh.py | 131 ++++++++++++++ .../services/account_protection_service.py | 23 +++ web/backend/services/automation/__init__.py | 18 ++ .../automation/jobs/lease_ck_refresh.py | 170 ++++++++++++++++++ web/frontend/src/api/types.ts | 2 +- web/frontend/src/pages/AutomationPage.tsx | 6 + 8 files changed, 442 insertions(+), 1 deletion(-) create mode 100644 tests/test_lease_ck_refresh.py create mode 100644 web/backend/services/automation/jobs/lease_ck_refresh.py diff --git a/docs/设计-账号全生命周期.md b/docs/设计-账号全生命周期.md index 83bf4cd..78f52db 100644 --- a/docs/设计-账号全生命周期.md +++ b/docs/设计-账号全生命周期.md @@ -268,3 +268,43 @@ CK 本体和健康结果都在账号上: - 不用官方时间替换本地 7 天规则; - 不把 `change_role_wait_time`(相对秒数)当分配依据; - 不为了“能选中”绕过本地锁。 + +## P1:租约 CK 到期前刷新(2026-11-24) + +生产基线:3,973 个生效租约,其中约 293 个有效 CK 预测 24 小时内到期 +(`platform_fulfillment` 202,`douyu_collab` 91)。 + +### 保护组 + +`ck_health.config["protection_groups"]` 新增 `lease_bound`: + +- 成员:`account_leases.status=active` 且 purpose 为 + `platform_fulfillment` / `douyu_collab`; +- 默认开启; +- 巡检间隔 30 分钟(比普通账号更短); +- 自动重登开启。 + +这样所有生效租约账号都会进入 CK 巡检和失效重登保护,不再只覆盖预售/协作单。 + +### 到期前刷新作业 + +新增 `lease_ck_refresh`: + +- 只处理仍为 `ck_check_status=valid` 的生效租约账号; +- 预测到期时间在 24h 内; +- 有 Cookie、可自动管理、没有在途登录; +- 人工失败分型和退避中的账号跳过; +- 每轮 batch=10,10 分钟一轮,默认开启; +- 走 `run_login_batch_with_fallback`,与首次登录/重登共用登录配额和审计。 + +与 `ck_relogin` 的分工: + +| 作业 | 对象 | +| --- | --- | +| `lease_ck_refresh` | 仍有效、但 24h 内到期的租约账号,提前续 CK | +| `ck_relogin` | 已经 invalid 的账号,失效后重登 | + +### 为什么不是等失效再登 + +租约账号在履约期间 CK 失效会出现不可用窗口;提前登录可以把窗口前移到空闲时段。 +作业不直接改绑定或订单,只刷新 Cookie。 diff --git a/tests/test_account_protection_service.py b/tests/test_account_protection_service.py index 014a3c2..a0f5a3b 100644 --- a/tests/test_account_protection_service.py +++ b/tests/test_account_protection_service.py @@ -6,6 +6,7 @@ from datetime import UTC, datetime, timedelta from web.backend.models import ( Account, + AccountLease, AutomationJob, DouyuExternalOrder, PlatformFulfillmentTask, @@ -123,6 +124,58 @@ def test_protection_membership_uses_active_fulfillment_relationships(db): ) +def test_lease_bound_includes_all_active_lease_purposes(db): + user = User( + username="lease-protection-user", + password_hash="h", + role="super_admin", + is_active=True, + ) + leased = _account("protection-leased") + collab_leased = _account("protection-collab-leased") + released = _account("protection-released") + other_purpose = _account("protection-other-purpose") + db.add_all([user, leased, collab_leased, released, other_purpose]) + db.flush() + db.add_all( + [ + AccountLease( + account_id=leased.id, + holder_user_id=user.id, + purpose="platform_fulfillment", + status="active", + ), + AccountLease( + account_id=collab_leased.id, + holder_user_id=user.id, + purpose="douyu_collab", + status="active", + ), + AccountLease( + account_id=released.id, + holder_user_id=user.id, + purpose="platform_fulfillment", + status="released", + ), + AccountLease( + account_id=other_purpose.id, + holder_user_id=user.id, + purpose="other", + status="active", + ), + ] + ) + db.commit() + + snapshot = load_protection_snapshot(db, job_config=None) + + assert snapshot.group_account_ids["lease_bound"] == frozenset( + {leased.id, collab_leased.id} + ) + assert snapshot.groups["lease_bound"]["probe_interval_minutes"] == 30 + assert leased.id in snapshot.relogin_ids + + def test_protection_target_reports_ck_health_and_shortage(db): valid = _account("protection-valid") invalid = _account("protection-invalid", ck_status="invalid") diff --git a/tests/test_lease_ck_refresh.py b/tests/test_lease_ck_refresh.py new file mode 100644 index 0000000..c6005dd --- /dev/null +++ b/tests/test_lease_ck_refresh.py @@ -0,0 +1,131 @@ +"""租约 CK 到期前刷新的选行和作业测试。""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +from web.backend.models import Account, AccountLease, AutomationJob, User +from web.backend.services.automation.jobs import lease_ck_refresh + + +def _account(name: str, *, cookie_updated_at: datetime, ck_status: str = "valid", **overrides) -> Account: + values = { + "username": name, + "password": "p", + "email": f"{name}@example.com", + "email_password": "ep", + "cookie": "acf_uid=1", + "cookie_updated_at": cookie_updated_at, + "ck_check_status": ck_status, + "ck_checked_at": cookie_updated_at, + "status": "active", + "auto_managed": True, + } + values.update(overrides) + return Account(**values) + + +def _user(db) -> User: + user = User( + username="lease-refresh-admin", + password_hash="h", + role="super_admin", + is_active=True, + ) + db.add(user) + db.commit() + return user + + +def _lease(db, user: User, account: Account, *, purpose: str = "platform_fulfillment", status: str = "active") -> AccountLease: + lease = AccountLease( + account_id=account.id, + holder_user_id=user.id, + purpose=purpose, + status=status, + ) + db.add(lease) + return lease + + +def test_select_due_lease_accounts_only_returns_valid_expiring_leases(db): + now = datetime.now(UTC).replace(microsecond=0) + user = _user(db) + due = _account("lease-due", cookie_updated_at=now - timedelta(days=6, hours=20)) + due_collab = _account("lease-due-collab", cookie_updated_at=now - timedelta(days=6, hours=21)) + fresh = _account("lease-fresh", cookie_updated_at=now - timedelta(days=1)) + invalid = _account("lease-invalid", cookie_updated_at=now - timedelta(days=6, hours=20), ck_status="invalid") + no_lease = _account("lease-none", cookie_updated_at=now - timedelta(days=6, hours=20)) + manual = _account("lease-manual", cookie_updated_at=now - timedelta(days=6, hours=20), auto_managed=False) + db.add_all([due, due_collab, fresh, invalid, no_lease, manual]) + db.flush() + _lease(db, user, due) + _lease(db, user, due_collab, purpose="douyu_collab") + _lease(db, user, fresh) + _lease(db, user, invalid) + _lease(db, user, manual) + db.commit() + + rows = lease_ck_refresh.select_due_lease_accounts(db, now=now, limit=10) + + assert {row.id for row in rows} == {due.id, due_collab.id} + + +def test_select_due_lease_accounts_skips_released_lease(db): + now = datetime.now(UTC).replace(microsecond=0) + user = _user(db) + released = _account("lease-released", cookie_updated_at=now - timedelta(days=6, hours=20)) + db.add(released) + db.flush() + _lease(db, user, released, status="released") + db.commit() + + assert lease_ck_refresh.select_due_lease_accounts(db, now=now, limit=10) == [] + + +def test_run_lease_ck_refresh_calls_login_for_selected_accounts(db, monkeypatch): + from web.backend.services.automation.jobs import lease_ck_refresh as job_module + + now = datetime.now(UTC).replace(microsecond=0) + user = _user(db) + due = _account("lease-run-due", cookie_updated_at=now - timedelta(days=6, hours=20)) + db.add(due) + db.flush() + _lease(db, user, due) + db.commit() + + job = AutomationJob( + key=job_module.JOB_KEY, + title=job_module.TITLE, + enabled=True, + batch_size=10, + concurrency=3, + config={}, + ) + db.add(job) + db.commit() + + calls: dict[str, object] = {} + + def fake_run(db_session, **kwargs): + calls["db"] = db_session + calls["kwargs"] = kwargs + return SimpleNamespace( + success_ids=[due.id], + failed_ids=[], + skipped_ids=[], + fallback_used=False, + batch_ids=["lease-batch"], + fallback_batch_ids=[], + ) + + monkeypatch.setattr(job_module, "run_login_batch_with_fallback", fake_run) + + result = job_module.run_lease_ck_refresh(db, job) + + assert calls["kwargs"]["account_ids"] == [due.id] + assert calls["kwargs"]["mode"] == "login" + assert result["scanned"] == 1 + assert result["success"] == 1 + assert result["batchIds"] == ["lease-batch"] diff --git a/web/backend/services/account_protection_service.py b/web/backend/services/account_protection_service.py index fad0c6d..b3f478b 100644 --- a/web/backend/services/account_protection_service.py +++ b/web/backend/services/account_protection_service.py @@ -22,6 +22,7 @@ from sqlalchemy.orm import Session from ..models import ( Account, + AccountLease, AutomationJob, DouyuExternalOrder, PlatformFulfillmentTask, @@ -55,6 +56,14 @@ GROUP_DEFINITIONS: dict[str, dict[str, Any]] = { "probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES, "auto_relogin": True, }, + "lease_bound": { + "label": "生效租约账号", + "description": "当前所有生效的直播履约/协作租约账号,优先 CK 巡检和到期前刷新", + "enabled": True, + "target_count": 0, + "probe_interval_minutes": 30, + "auto_relogin": True, + }, } @@ -136,6 +145,19 @@ def _collab_account_ids(db: Session) -> set[int]: return {int(row[0]) for row in rows if row[0] is not None} +def _lease_account_ids(db: Session) -> set[int]: + rows = ( + db.query(AccountLease.account_id) + .filter( + AccountLease.status == "active", + AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")), + ) + .distinct() + .all() + ) + return {int(row[0]) for row in rows if row[0] is not None} + + @dataclass(frozen=True) class ProtectionSnapshot: groups: dict[str, dict[str, Any]] @@ -189,6 +211,7 @@ def load_protection_snapshot( group_account_ids={ "presale_bound": frozenset(_presale_account_ids(db)), "collab_bound": frozenset(_collab_account_ids(db)), + "lease_bound": frozenset(_lease_account_ids(db)), }, ) diff --git a/web/backend/services/automation/__init__.py b/web/backend/services/automation/__init__.py index e06b612..73cafaa 100644 --- a/web/backend/services/automation/__init__.py +++ b/web/backend/services/automation/__init__.py @@ -52,6 +52,8 @@ from .jobs.douyu_tasks_retention import ( from .jobs.douyu_tasks_retention import ( run_douyu_tasks_retention, ) +from .jobs.lease_ck_refresh import JOB_KEY as LEASE_CK_REFRESH_KEY +from .jobs.lease_ck_refresh import run_lease_ck_refresh from .jobs.platform_fulfillment_lease_reaper import ( JOB_KEY as PLATFORM_FULFILLMENT_LEASE_REAPER_KEY, ) @@ -84,6 +86,7 @@ __all__ = [ "CK_HEALTH_KEY", "CK_RELOGIN_KEY", "DOUYU_TASKS_RETENTION_KEY", + "LEASE_CK_REFRESH_KEY", "PLATFORM_FULFILLMENT_LEASE_REAPER_KEY", "POINTS_EXPIRE_KEY", "JobSpec", @@ -104,6 +107,7 @@ __all__ = [ "run_douyu_tasks_retention", "run_due_jobs", "run_job_now", + "run_lease_ck_refresh", "run_platform_fulfillment_lease_reaper", "run_points_expire_check", "scheduler_status", @@ -226,6 +230,20 @@ def register_default_jobs() -> None: run=run_ck_relogin, ) ) + register_job( + JobSpec( + key=LEASE_CK_REFRESH_KEY, + title="租约 CK 到期前刷新", + # 只处理仍有效、但预测 24h 内到期的生效租约账号;提前续 CK, + # 不参与普通失效重登的批次。 + interval_seconds=600, + run_interval_seconds=600, + batch_size=10, + concurrency=3, + run=run_lease_ck_refresh, + default_enabled=True, + ) + ) register_job( JobSpec( key=CK_HEALTH_KEY, diff --git a/web/backend/services/automation/jobs/lease_ck_refresh.py b/web/backend/services/automation/jobs/lease_ck_refresh.py new file mode 100644 index 0000000..56a7e88 --- /dev/null +++ b/web/backend/services/automation/jobs/lease_ck_refresh.py @@ -0,0 +1,170 @@ +"""租约账号 CK 到期前刷新(P1)。 + +`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`); +- 失败分型为人工的账号、仍在退避窗口内的账号不碰。 + +作业只负责“提前续 CK”,不替代 `ck_relogin` 的失效重登;两者共用登录配额和 +登录任务审计。 +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import Any + +from sqlalchemy import func, or_ +from sqlalchemy.orm import Session + +from ....models import Account, AccountLease, AutomationJob, User +from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS +from ...account_query_filters import automation_account_filter +from ...login_automation import run_login_batch_with_fallback + +JOB_KEY = "lease_ck_refresh" +TITLE = "租约 CK 到期前刷新" +REFRESH_BEFORE = timedelta(hours=24) + + +def _system_user_id(db: Session) -> int | None: + 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 due_lease_account_query( + db: Session, + now: datetime | None = None, +): + """到期前 24h 的租约账号查询(执行和测试共用)。""" + moment = now or datetime.now(UTC) + cutoff = moment + REFRESH_BEFORE + return ( + db.query(Account) + .join(AccountLease, AccountLease.account_id == Account.id) + .filter( + AccountLease.status == "active", + AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")), + 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 <= moment, + ), + ) + .order_by(Account.cookie_updated_at.asc(), Account.id.asc()) + ) + + +def select_due_lease_accounts( + db: Session, + *, + now: datetime | None = None, + limit: int = 10, +) -> list[Account]: + return due_lease_account_query(db, now=now).limit(max(1, int(limit))).all() + + +def run_lease_ck_refresh(db: Session, job: AutomationJob) -> dict[str, Any]: + now = datetime.now(UTC) + system_user_id = _system_user_id(db) + if system_user_id is None: + return { + "scanned": 0, + "success": 0, + "failed": 0, + "message": "库里没有可用用户,无法以系统身份发起租约 CK 刷新", + } + + batch_size = max(1, int(job.batch_size or 10)) + accounts = select_due_lease_accounts(db, now=now, limit=batch_size) + if not accounts: + return { + "scanned": 0, + "success": 0, + "failed": 0, + "message": "没有 24h 内到期的租约账号需要刷新", + } + + account_ids = [int(account.id) for account in accounts] + outcome = run_login_batch_with_fallback( + db, + account_ids=account_ids, + mode="login", + created_by=system_user_id, + concurrency=max(1, min(int(job.concurrency or 3), 8)), + max_total_time=240, + ) + _settle_outcome(accounts, outcome, now=now) + db.commit() + retry = len(outcome.failed_ids) - _manual_count(outcome) + return { + "scanned": len(account_ids), + "success": len(outcome.success_ids), + "failed": len(outcome.failed_ids), + "retry": max(0, retry), + "manual": _manual_count(outcome), + "skipped": len(outcome.skipped_ids), + "fallbackUsed": outcome.fallback_used, + "batchIds": list(outcome.batch_ids) + list(outcome.fallback_batch_ids), + "message": ( + f"租约 CK 到期前刷新 {len(account_ids)} 条," + f"成功 {len(outcome.success_ids)},失败 {len(outcome.failed_ids)}" + ), + } + + +def _manual_count(outcome) -> int: + return sum( + 1 + for account_id in outcome.failed_ids + if outcome.failure_kinds.get(account_id) in MANUAL_KINDS + ) + + +def _settle_outcome(accounts: list[Account], outcome, *, now: datetime) -> None: + """成功清退避,失败按类型设置下次重试,避免每 10 分钟撞一次。""" + by_id = {int(account.id): account for account in accounts} + for account_id in outcome.success_ids: + account = by_id.get(int(account_id)) + if account is None: + continue + account.relogin_failure_kind = "" + account.relogin_last_error = "" + account.relogin_attempts = 0 + account.relogin_next_at = None + for account_id in outcome.failed_ids: + account = by_id.get(int(account_id)) + if account is None: + continue + kind = str(outcome.failure_kinds.get(account_id) or "unknown") + account.relogin_failure_kind = kind + account.relogin_attempts = int(account.relogin_attempts or 0) + 1 + if kind in MANUAL_KINDS: + account.relogin_next_at = None + elif kind == "email_quota": + account.relogin_next_at = now + timedelta(hours=12) + else: + account.relogin_next_at = now + timedelta(hours=1) diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index ecafdf0..2d1bb5b 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -802,7 +802,7 @@ export interface DouyuSupplyTargetUpdate { } export interface DouyuAccountProtectionTarget { - group_key: 'presale_bound' | 'collab_bound'; + group_key: 'presale_bound' | 'collab_bound' | 'lease_bound'; label: string; description: string; enabled: boolean; diff --git a/web/frontend/src/pages/AutomationPage.tsx b/web/frontend/src/pages/AutomationPage.tsx index 6f78ce7..ca96ffc 100644 --- a/web/frontend/src/pages/AutomationPage.tsx +++ b/web/frontend/src/pages/AutomationPage.tsx @@ -118,6 +118,12 @@ const JOB_UI: Record = { showRecheck: false, showConcurrency: false, }, + lease_ck_refresh: { + description: "对仍有效、但预测 24 小时内到期的生效租约账号提前登录续 CK;只处理 platform_fulfillment / douyu_collab 租约。", + core: true, + showRecheck: false, + showConcurrency: true, + }, account_onboarding: { description: "对没有 CK 的未登录账号执行首次真实登录;成功后写入 CK 并联动商品能力同步。默认关闭,建议先小批量。", core: true,