"""履约保护账号的动态成员、目标和巡检/重登优先级测试。""" from __future__ import annotations from datetime import UTC, datetime, timedelta from web.backend.models import ( Account, AccountLease, AutomationJob, DouyuExternalOrder, PlatformFulfillmentTask, User, ) from web.backend.routers.douyu import update_account_protection_target from web.backend.schemas import DouyuAccountProtectionTargetUpdate from web.backend.services.account_observability import account_platform_status from web.backend.services.account_protection_service import ( PROTECTION_CONFIG_KEY, evaluate_protection_targets, load_protection_snapshot, update_protection_group, ) from web.backend.services.automation.jobs import ck_health, ck_relogin NOW = datetime.now(UTC).replace(microsecond=0) def _account( name: str, *, ck_status: str = "valid", checked_at: datetime | None = None, points: int = 0, ) -> Account: return Account( username=name, password="p", email=f"{name}@example.com", email_password="ep", cookie="acf_uid=100", cookie_updated_at=NOW, ck_check_status=ck_status, ck_checked_at=checked_at or NOW, status="active", auto_managed=True, points=points, ) def _presale_task(account: Account, *, execution_status: str = "bound") -> PlatformFulfillmentTask: return PlatformFulfillmentTask( source_order_id=f"order-{account.id or account.username}", source_order_item_id=f"item-{account.id or account.username}", sale_mode="presale", account_id=account.id, binding_status=( "bound" if execution_status not in {"completed", "cancelled"} else "not_started" ), execution_status=execution_status, ) def _collab_order( account: Account, *, order_no: str | None = None, status: str = "incomplete", archived_at: datetime | None = None, ) -> DouyuExternalOrder: return DouyuExternalOrder( order_no=order_no or f"collab-{account.username}", account_id=account.id, account_username=account.username, status=status, archived_at=archived_at, ) def _health_job(config: dict | None = None) -> AutomationJob: return AutomationJob( key=ck_health.JOB_KEY, interval_seconds=6 * 3600, batch_size=200, concurrency=3, config=config, ) def test_protection_membership_uses_active_fulfillment_relationships(db): shared = _account("protection-shared") presale_only = _account("protection-presale") collab_only = _account("protection-collab") finished = _account("protection-finished") db.add_all([shared, presale_only, collab_only, finished]) db.flush() db.add_all( [ _presale_task(shared), _presale_task(presale_only), _presale_task(finished, execution_status="completed"), _collab_order(shared), _collab_order(collab_only), _collab_order(finished, status="done"), _collab_order( finished, order_no="collab-finished-archived", archived_at=NOW, ), ] ) db.commit() snapshot = load_protection_snapshot(db, job_config=None) assert snapshot.group_account_ids["presale_bound"] == frozenset( {shared.id, presale_only.id} ) assert snapshot.group_account_ids["collab_bound"] == frozenset( {shared.id, collab_only.id} ) assert snapshot.monitored_ids == frozenset( {shared.id, presale_only.id, collab_only.id} ) 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"] == 240 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") db.add_all([valid, invalid]) db.flush() db.add_all([_presale_task(valid), _presale_task(invalid)]) job = _health_job( { PROTECTION_CONFIG_KEY: { "presale_bound": { "enabled": True, "target_count": 3, "probe_interval_minutes": 30, "auto_relogin": True, } } } ) db.add(job) db.commit() rows = evaluate_protection_targets(db, job_config=job.config, now=NOW) presale = next(row for row in rows if row["group_key"] == "presale_bound") status = account_platform_status(db, now=NOW) assert presale["bound_count"] == 2 assert presale["ck_valid"] == 1 assert presale["ck_invalid"] == 1 assert presale["target_shortage"] == 2 assert presale["needs_attention"] is True assert { alert["code"] for alert in status["alerts"] } >= { "account_protection_ck_affected", "account_protection_target_shortage", } def test_protection_target_counts_missing_cookie_without_full_account_load(db): account = _account("protection-no-cookie") account.cookie = "" db.add(account) db.flush() db.add(_presale_task(account)) db.add(_health_job()) db.commit() rows = evaluate_protection_targets(db, now=NOW) presale = next(row for row in rows if row["group_key"] == "presale_bound") assert presale["bound_count"] == 1 assert presale["without_cookie"] == 1 def test_ck_health_probes_protected_account_at_its_shorter_interval_first(db): protected = _account( "protection-due", checked_at=NOW - timedelta(minutes=90), ) regular_due = _account( "protection-regular-due", checked_at=NOW - timedelta(days=2), ) regular_due.points = None regular_due.gold_balance = 0 regular_due.elite_opened = False regular_due.overview_queried_at = NOW regular_fresh = _account( "protection-regular-fresh", checked_at=NOW - timedelta(minutes=30), ) db.add_all([protected, regular_due, regular_fresh]) db.flush() db.add(_presale_task(protected)) job = _health_job( { PROTECTION_CONFIG_KEY: { "presale_bound": { "enabled": True, "target_count": 1, "probe_interval_minutes": 60, "auto_relogin": True, } } } ) db.add(job) db.commit() selected = ck_health._select_accounts(db, job, NOW) assert [account.id for account in selected] == [protected.id, regular_due.id] def test_ck_relogin_prioritizes_protected_invalid_account(db): protected = _account( "protection-relogin-first", ck_status="invalid", ) high_value = _account( "protection-high-value", ck_status="invalid", points=1000, ) db.add_all([protected, high_value]) db.flush() db.add(_presale_task(protected)) db.add(_health_job()) relogin_job = AutomationJob( key=ck_relogin.JOB_KEY, interval_seconds=6 * 3600, batch_size=2, concurrency=1, ) db.commit() selected = ck_relogin.build_select_query( db, relogin_job, NOW, batch_limit=2, ).all() assert [account.id for account in selected] == [protected.id, high_value.id] def test_ck_relogin_can_be_disabled_for_a_protection_group(db): protected = _account("protection-no-auto-relogin", ck_status="invalid") ordinary = _account("protection-ordinary-auto-relogin", ck_status="invalid") db.add_all([protected, ordinary]) db.flush() db.add(_presale_task(protected)) db.add( _health_job( { PROTECTION_CONFIG_KEY: { "presale_bound": { "enabled": True, "target_count": 1, "probe_interval_minutes": 60, "auto_relogin": False, } } } ) ) relogin_job = AutomationJob( key=ck_relogin.JOB_KEY, interval_seconds=6 * 3600, batch_size=10, concurrency=1, ) db.commit() selected = ck_relogin.build_select_query( db, relogin_job, NOW, batch_limit=10, ).all() assert [account.id for account in selected] == [ordinary.id] def test_update_protection_group_preserves_other_job_config(db): job = _health_job({"unrelated": {"keep": True}}) db.add(job) db.commit() updated, groups = update_protection_group( db, group_key="collab_bound", enabled=False, target_count=25, probe_interval_minutes=90, auto_relogin=False, ) db.commit() assert updated.config["unrelated"] == {"keep": True} assert groups["collab_bound"]["target_count"] == 25 assert updated.config[PROTECTION_CONFIG_KEY]["collab_bound"]["enabled"] is False def test_protection_target_update_route_returns_current_status(db): user = User( username="protection-admin", password_hash="h", role="super_admin", is_active=True, ) account = _account("protection-route") db.add_all([user, account]) db.flush() db.add_all([_presale_task(account), _health_job()]) db.commit() result = update_account_protection_target( "presale_bound", DouyuAccountProtectionTargetUpdate( enabled=True, target_count=5, probe_interval_minutes=45, auto_relogin=True, ), db=db, current=user, ) assert result["group_key"] == "presale_bound" assert result["bound_count"] == 1 assert result["target_count"] == 5 assert result["target_shortage"] == 4 assert result["probe_interval_minutes"] == 45 def test_aged_ordinary_work_cannot_preempt_protected_account(db): """积压超过 30 分钟的普通失效号不能反超履约保护目标。""" from web.backend.models import AccountWorkItem from web.backend.services.account_lifecycle import WORK_LOGIN_RELOGIN from web.backend.services.account_work_queue import ( WORK_AGING_SECONDS, enqueue_account_work, ) ordinary = _account("aged-ordinary", ck_status="invalid") protected = _account("fresh-protected", ck_status="invalid") db.add_all([ordinary, protected]) db.flush() db.add(_presale_task(protected)) db.add(_health_job()) enqueue_account_work( db, account_id=ordinary.id, work_type=WORK_LOGIN_RELOGIN, priority=30, due_at=NOW - timedelta(seconds=WORK_AGING_SECONDS + 3600), ) # 模拟账号先失效后才绑定进保护组:队列里原本还是 priority=30 enqueue_account_work( db, account_id=protected.id, work_type=WORK_LOGIN_RELOGIN, priority=30, due_at=NOW, ) db.commit() relogin_job = AutomationJob( key=ck_relogin.JOB_KEY, interval_seconds=6 * 3600, batch_size=1, concurrency=1, ) claimed = ck_relogin._claim_relogin_work( db, relogin_job, NOW, max_attempts=2, protection=load_protection_snapshot(db), limit=1, ) assert [item.account_id for item in claimed] == [protected.id] refreshed = db.query(AccountWorkItem).filter_by(account_id=protected.id).one() assert refreshed.priority == 10 def test_relogin_priority_is_demoted_after_leaving_protection_group(db): from web.backend.models import AccountWorkItem from web.backend.services.account_lifecycle import WORK_LOGIN_RELOGIN from web.backend.services.account_work_queue import enqueue_account_work account = _account("former-protected", ck_status="invalid") db.add(account) db.flush() presale = _presale_task(account) db.add_all([presale, _health_job()]) enqueue_account_work( db, account_id=account.id, work_type=WORK_LOGIN_RELOGIN, priority=10, due_at=NOW, ) db.commit() db.delete(presale) db.commit() relogin_job = AutomationJob( key=ck_relogin.JOB_KEY, interval_seconds=6 * 3600, batch_size=1, concurrency=1, ) ck_relogin._claim_relogin_work( db, relogin_job, NOW, max_attempts=2, protection=load_protection_snapshot(db), limit=1, ) work = db.query(AccountWorkItem).filter_by(account_id=account.id).one() assert work.priority == 30 def test_protected_account_reserves_quota_against_ordinary_backlog(db): """普通重登耗尽普通分类或接近小时/日上限时,履约保护账号仍保有配额。""" from web.backend.models import LoginQuotaSetting from web.backend.services.login_quota_service import ( CATEGORY_RELOGIN_PROTECTED, reserve_login_attempt, ) ordinary = _account("quota-ordinary", ck_status="invalid") ordinary.points = 0 protected = _account("quota-protected", ck_status="invalid") protected.points = 0 db.add_all([ordinary, protected]) db.flush() db.add(_presale_task(protected)) db.add(_health_job()) db.add( LoginQuotaSetting( id=1, daily_attempt_limit=2, hourly_attempt_limit=1, per_account_daily_limit=2, relogin_high_value_daily_limit=0, relogin_ordinary_daily_limit=0, manual_daily_limit=10, enabled=True, ) ) db.commit() # 普通账号不得抢占唯一剩给待重登保护账号的 1 个小时名额 ordinary_decision = reserve_login_attempt( db, account=ordinary, mode="relogin", trigger_source="automation", batch_id="b-ord", created_by=None, now=NOW, ) assert not ordinary_decision.allowed assert "履约保护" in ordinary_decision.reason # 保护账号走独立分类 relogin_protected,不受 relogin_ordinary_daily_limit=0 限制 protected_decision = reserve_login_attempt( db, account=protected, mode="relogin", trigger_source="automation", batch_id="b-prot", created_by=None, now=NOW, ) assert protected_decision.allowed assert protected_decision.attempt is not None assert protected_decision.attempt.category == CATEGORY_RELOGIN_PROTECTED def test_cascading_priority_quota_reservation_p0_p1_p2_p3(db): """配额紧张时严格按 P0(保护失效) > P1(快过期) > P2(高价值) > P3(普通) 预留名额。""" from web.backend.models import LoginQuotaSetting from web.backend.services.login_quota_service import ( CATEGORY_LEASE_REFRESH, CATEGORY_RELOGIN_HIGH, CATEGORY_RELOGIN_ORDINARY, CATEGORY_RELOGIN_PROTECTED, get_login_quota_usage_summary, reserve_login_attempt, ) p0 = _account("tier-p0", ck_status="invalid") p1 = _account( "tier-p1", ck_status="valid", checked_at=NOW, ) p1.cookie_updated_at = NOW - timedelta(days=6, hours=20) p2 = _account("tier-p2", ck_status="invalid", points=500) p3 = _account("tier-p3", ck_status="invalid", points=0) db.add_all([p0, p1, p2, p3]) db.flush() db.add(_presale_task(p0)) db.add(_collab_order(p1)) db.add(_health_job()) db.add( LoginQuotaSetting( id=1, daily_attempt_limit=10, hourly_attempt_limit=3, per_account_daily_limit=2, relogin_protected_daily_limit=10, lease_refresh_daily_limit=10, relogin_high_value_daily_limit=10, relogin_ordinary_daily_limit=10, manual_daily_limit=10, enabled=True, ) ) db.commit() # 小时上限 3,当前 P0=1、P1=1、P2=1:P3 必须让路给 P0+P1+P2(3<=3) d_p3 = reserve_login_attempt( db, account=p3, mode="relogin", trigger_source="automation", batch_id="b-p3", created_by=None, now=NOW, ) assert not d_p3.allowed # 同理 P2 可以拿到名额,但先验证 P2 只有 3 > P0+P1(2) 所以允许; # 若先把 P1 占掉 1 槽(剩 2 槽),P2(需要 P0+P1 留 2 槽 -> 2<=2) 应先让路给 P0/P1 d_p1_wait = reserve_login_attempt( db, account=p1, mode="login", trigger_source="automation", batch_id="b-p1", created_by=None, now=NOW, category=CATEGORY_LEASE_REFRESH, ) assert d_p1_wait.allowed assert d_p1_wait.attempt is not None assert d_p1_wait.attempt.category == CATEGORY_LEASE_REFRESH # 现剩 2 小时槽位,P0 还要 1 槽:P2 应能拿到(2 > 1)? 此时 P1 已 in-flight,P0=1 -> P2 可拿 # 先测试 P0 拿走 1 槽 d_p0 = reserve_login_attempt( db, account=p0, mode="relogin", trigger_source="automation", batch_id="b-p0", created_by=None, now=NOW, ) assert d_p0.allowed assert d_p0.attempt is not None assert d_p0.attempt.category == CATEGORY_RELOGIN_PROTECTED # 现剩 1 小时槽位,P0/P1 均已满足 -> P2 拿到最后 1 槽 d_p2 = reserve_login_attempt( db, account=p2, mode="relogin", trigger_source="automation", batch_id="b-p2", created_by=None, now=NOW, ) assert d_p2.allowed assert d_p2.attempt is not None assert d_p2.attempt.category == CATEGORY_RELOGIN_HIGH summary = get_login_quota_usage_summary(db, now=NOW) assert summary["daily_used"] == 3 by_cat = {row["category"]: row for row in summary["categories"]} assert by_cat[CATEGORY_RELOGIN_PROTECTED]["priority"] == "P0" assert by_cat[CATEGORY_RELOGIN_PROTECTED]["used"] == 1 assert by_cat[CATEGORY_LEASE_REFRESH]["used"] == 1 assert by_cat[CATEGORY_RELOGIN_HIGH]["used"] == 1 assert by_cat[CATEGORY_RELOGIN_ORDINARY]["pending"] == 1 def test_p2_high_value_claims_before_aged_p3_ordinary_while_p0_wins_all(db): """P0(履约保护) > P2(高价值) > P3(普通),积压超 30 分钟的普通号不能反超 P2。""" from web.backend.services.account_lifecycle import WORK_LOGIN_RELOGIN from web.backend.services.account_work_queue import ( WORK_AGING_SECONDS, enqueue_account_work, ) p3 = _account("claim-p3-aged", ck_status="invalid", points=0) p2 = _account("claim-p2-high", ck_status="invalid", points=500) p0 = _account("claim-p0-prot", ck_status="invalid", points=0) db.add_all([p3, p2, p0]) db.flush() db.add(_presale_task(p0)) db.add(_health_job()) enqueue_account_work( db, account_id=p3.id, work_type=WORK_LOGIN_RELOGIN, priority=30, due_at=NOW - timedelta(seconds=WORK_AGING_SECONDS + 3600), ) enqueue_account_work( db, account_id=p2.id, work_type=WORK_LOGIN_RELOGIN, priority=30, due_at=NOW, ) enqueue_account_work( db, account_id=p0.id, work_type=WORK_LOGIN_RELOGIN, priority=10, due_at=NOW, ) db.commit() relogin_job = AutomationJob( key=ck_relogin.JOB_KEY, interval_seconds=6 * 3600, batch_size=3, concurrency=1, ) claimed = ck_relogin._claim_relogin_work( db, relogin_job, NOW, max_attempts=2, protection=load_protection_snapshot(db), limit=3, ) assert [item.account_id for item in claimed] == [p0.id, p2.id, p3.id]