From 9bdd2f4e1a558427611fca0f3ed3cf7985aeb7bc Mon Sep 17 00:00:00 2001 From: yml Date: Wed, 25 Nov 2026 22:13:21 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96(=E8=B4=A6=E5=8F=B7=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8C=96):=20=E5=B1=A5=E7=BA=A6=E4=BF=9D=E6=8A=A4?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E9=85=8D=E9=A2=9D=E4=B8=8E=E9=87=8D=E7=99=BB?= =?UTF-8?q?=E4=BC=98=E5=85=88=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 17 +- core/douyu/login.py | 62 +-- docs/斗鱼/账号CK全自动化计划.md | 4 +- tests/test_account_protection_service.py | 317 +++++++++++++ tests/test_automation_ck_relogin.py | 69 ++- tests/test_douyu_login_retry_policy.py | 40 +- tests/test_lease_ck_refresh.py | 39 +- tests/test_login_batch_slot_budget.py | 62 +++ tests/test_login_budget_recommendation.py | 52 ++- tests/test_migrations.py | 2 +- .../migrations/migration_manifest.json | 4 + ...61125_0135_protected_login_quota_limits.py | 56 +++ web/backend/models.py | 6 + web/backend/routers/automation.py | 26 +- web/backend/services/automation/__init__.py | 6 +- .../services/automation/jobs/ck_relogin.py | 132 ++++-- .../automation/jobs/lease_ck_refresh.py | 36 +- web/backend/services/execution_worker.py | 18 +- web/backend/services/login_automation.py | 16 +- .../services/login_budget_recommendation.py | 143 ++++-- web/backend/services/login_quota_service.py | 418 ++++++++++++++++-- web/backend/services/login_service.py | 34 +- web/frontend/src/api/types.ts | 27 ++ web/frontend/src/pages/AutomationPage.tsx | 114 ++++- web/frontend/src/pages/LoginTasksPage.tsx | 3 +- 25 files changed, 1510 insertions(+), 193 deletions(-) create mode 100644 web/backend/migrations/versions/20261125_0135_protected_login_quota_limits.py diff --git a/.env.example b/.env.example index 152d09a..f6d835c 100644 --- a/.env.example +++ b/.env.example @@ -50,18 +50,15 @@ LOG_RETENTION_DAYS=14 # 日志目录由启动脚本固定:./dev.sh 使用项目 logs/,Docker 使用挂载的 /app/logs。 # CK 重登保护:单账号最多尝试次数与总耗时秒数,超时/失败均保留旧 Cookie。 -# 单账号总时长要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟), -# 且不小于 DOUYU_EMAIL_CODE_WAIT_SECONDS + DOUYU_EMAIL_CODE_RESCUE_SECONDS。 +# 单账号总时长覆盖极验 + 一轮邮箱验证码等待(最多 180 秒)。 COOKIE_RELOGIN_MAX_RETRIES=5 -COOKIE_RELOGIN_MAX_TOTAL_TIME=1800 +COOKIE_RELOGIN_MAX_TOTAL_TIME=300 -# 斗鱼登录邮箱验证码:等邮件的最长秒数(60-1800,默认 900)。 -# 斗鱼的验证码邮件是攒批投递的:早高峰延迟 6~20 秒,高峰会劣化到 8~13 分钟, -# 同一批请求的邮件会在同一分钟内成批到达。窗口太小会把「邮件还在路上」误判 -# 成「根本没发出来」。 -DOUYU_EMAIL_CODE_WAIT_SECONDS=900 -# 首轮等待超时后,不重新发信、只补等迟到邮件的秒数(0-1800,默认 600,0 关闭)。 -DOUYU_EMAIL_CODE_RESCUE_SECONDS=600 +# 斗鱼登录邮箱验证码:一轮等待(首轮 + 补等合计)最多 180 秒(3 分钟)。 +# 首轮等邮件秒数(15-180,默认 120)。 +DOUYU_EMAIL_CODE_WAIT_SECONDS=120 +# 首轮等待超时后,不重新发信、只补等迟到邮件的秒数(0-180,默认 60,0 关闭;总计不超过 180)。 +DOUYU_EMAIL_CODE_RESCUE_SECONDS=60 # 发信/提交验证码接口本身报错时,自动切到另一条通道(iframe <-> wgapi);off 可关闭。 # 注意:取码超时不触发切换 —— 切换会重新发信,把斗鱼邮件队列压得更长、flush 更晚。 DOUYU_LOGIN_EMAIL_FALLBACK_API=iframe diff --git a/core/douyu/login.py b/core/douyu/login.py index 76ed124..8092764 100644 --- a/core/douyu/login.py +++ b/core/douyu/login.py @@ -121,6 +121,8 @@ class DouyuLogin: MAX_STATIC_RETRY = 3 # 静态代理失败上限(无法切换代理时的最大重试次数) # 邮箱验证码最多等几轮(首轮 + 补等)。补等不重新发信,只是继续等迟到邮件。 EMAIL_CODE_MAX_ATTEMPTS = 2 + # 一轮邮箱验证码(首轮 + 补等合计)最多等待 3 分钟,避免单个账号卡死并发槽。 + MAX_EMAIL_CODE_WAIT_SECONDS = 180 # 首轮等待超时后,不重新发信、只补等迟到邮件的秒数上限。 EMAIL_RESCUE_ENV = "DOUYU_EMAIL_CODE_RESCUE_SECONDS" # 邮箱验证码发信/校验的两条通道:wgapi(新版)与 iframe(旧版)。 @@ -1020,29 +1022,23 @@ class DouyuLogin: @staticmethod def _email_code_wait_seconds() -> int: - """等验证码邮件的最长秒数;本地联调可用环境变量调小。 - - 默认 900 秒:斗鱼的验证码邮件是**攒批投递**的 —— 请求到达后,邮件要等 - 它自己的批处理 flush 才落地。生产实测延迟从早高峰的 6~20 秒一路劣化 - 到高峰的 8~13 分钟,同一批请求的邮件会在同一分钟内成批到达。窗口只给 - 60 秒,会把「邮件还在路上」误判成「根本没发出来」。 - """ + """等验证码邮件的最长秒数;一轮验证码(含补等)最多 3 分钟。""" raw = str(os.getenv("DOUYU_EMAIL_CODE_WAIT_SECONDS") or "").strip() try: - value = int(raw) if raw else 900 + value = int(raw) if raw else 120 except ValueError: - value = 900 - return max(60, min(value, 1800)) + value = 120 + return max(15, min(value, DouyuLogin.MAX_EMAIL_CODE_WAIT_SECONDS)) @classmethod def _email_code_rescue_seconds(cls) -> int: """首轮等待超时后的补等秒数:只等迟到邮件,不重新发信。""" raw = str(os.getenv(cls.EMAIL_RESCUE_ENV) or "").strip() try: - value = int(raw) if raw else 600 + value = int(raw) if raw else 60 except ValueError: - value = 600 - return max(0, min(value, 1800)) + value = 60 + return max(0, min(value, cls.MAX_EMAIL_CODE_WAIT_SECONDS)) def _wait_for_email_code( self, @@ -1052,22 +1048,31 @@ class DouyuLogin: email_sent_at: float, deadline: float = 0, ) -> str: - """等待验证码邮件;首轮超时后**不重新发信**地补等一轮。 + """等待验证码邮件;首轮超时后**不重新发信**地补等一轮,总计不超过 3 分钟。 - 为什么不能超时后重新发信:斗鱼侧验证码是攒批投递的,队列越长 flush - 越晚。生产实测一旦开始超时重发,每账号发信量从 1.5 封涨到 3.3 封, - 邮件延迟随即从 10 秒级恶化到 8~13 分钟 —— 重发只会把队列压得更死。 - - 补等用的是同一个 verifier 和同一个发信前 UID 快照,所以迟到的邮件 - (UID 更大)照样能被认出来,且不会多消耗一次发信。 + 为什么不能超时后重新发信:斗鱼侧验证码是攒批投递的,重发只会把队列压得更死; + 同时单轮总等待必须封顶 180 秒(3 分钟),避免少数收不到邮件的账号把整批拖死。 """ rounds = max(1, self.EMAIL_CODE_MAX_ATTEMPTS) rescue_seconds = self._email_code_rescue_seconds() wait_seconds = self._email_code_wait_seconds() + total_cap = min( + wait_seconds + rescue_seconds, + self.MAX_EMAIL_CODE_WAIT_SECONDS, + ) + round_caps = [min(wait_seconds, total_cap)] + if rounds > 1 and rescue_seconds > 0: + round_caps.append(min(rescue_seconds, max(0, total_cap - round_caps[0]))) + email_deadline = time.monotonic() + total_cap last_error = "" - for round_index in range(rounds): - budget = wait_seconds if round_index == 0 else rescue_seconds + for round_index, planned_budget in enumerate(round_caps): + if planned_budget <= 0: + break + remaining_email = email_deadline - time.monotonic() + if remaining_email <= 0: + break + budget = min(float(planned_budget), remaining_email) if deadline: # 单账号总时长是硬约束:等待不能超出预算,否则会占住批次并发位。 remaining = deadline - time.monotonic() @@ -1079,18 +1084,23 @@ class DouyuLogin: break try: return verifier.get_verification_code( - max_wait=int(budget), + max_wait=max(1, int(budget)), after_timestamp=email_sent_at, min_uid=baseline_uid, stop_event=self.stop_event, ) except TimeoutError as exc: last_error = str(exc) - if round_index + 1 >= rounds or rescue_seconds <= 0: + next_budget = ( + round_caps[round_index + 1] + if round_index + 1 < len(round_caps) + else 0 + ) + if next_budget <= 0 or email_deadline - time.monotonic() <= 0: break logger.warning( - f"等待验证码超时(首轮已等 {wait_seconds}s)," - f"不重新发信,再等 {rescue_seconds}s 等迟到邮件" + f"等待验证码超时(首轮已等 {int(budget)}s)," + f"不重新发信,最多补等 {min(next_budget, int(max(0.0, email_deadline - time.monotonic())))}s 等迟到邮件" ) raise EmailCodeTimeoutError(last_error or "等待验证码超时") diff --git a/docs/斗鱼/账号CK全自动化计划.md b/docs/斗鱼/账号CK全自动化计划.md index 6848dce..1070fe8 100644 --- a/docs/斗鱼/账号CK全自动化计划.md +++ b/docs/斗鱼/账号CK全自动化计划.md @@ -81,9 +81,7 @@ 100%;一旦开始超时重发,12:00 后每账号发信涨到 **3.2~3.7 封**,队列更长、 flush 更晚,取码成功率掉到 20% 左右。 -因此:窗口只给 60 秒会把「邮件还在路上」误判成「没发出来」,而超时后重发 -会把队列压得更死。修复方向是**放大等待窗口 + 超时补等而不重发**,而不是找 -「第三个发信接口」—— 两个通道写的是同一个队列,发两次只会更慢。 +因此:一轮邮箱验证码等待(首轮 + 补等合计)上限控制在 **3 分钟(180 秒)**内(默认首轮 120s + 补等 60s),超时后**不重发**,交给后续轮次和退避机制;同时确保履约保护目标(预售/协作单/生效租约)在重登队列优先级与日/时配额预留上绝对优先于普通库存。 ### 3.3 极验 diff --git a/tests/test_account_protection_service.py b/tests/test_account_protection_service.py index 2c8a300..e347a46 100644 --- a/tests/test_account_protection_service.py +++ b/tests/test_account_protection_service.py @@ -390,3 +390,320 @@ def test_protection_target_update_route_returns_current_status(db): 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] diff --git a/tests/test_automation_ck_relogin.py b/tests/test_automation_ck_relogin.py index f19de09..3827ce0 100644 --- a/tests/test_automation_ck_relogin.py +++ b/tests/test_automation_ck_relogin.py @@ -235,6 +235,34 @@ class TestFailureCircuit(_Base): assert paused is False + def test_skipped_attempts_do_not_dilute_failure_rate(self): + paused, hard, ratio = ck_relogin.evaluate_failure_circuit( + { + "scanned": 20, + "skipped": 10, + "invalid": 2, + "email_quota": 0, + }, + {"failure_pause_ratio": 10}, + ) + + assert paused is True + assert hard == 2 + assert ratio == 0.2 + + def test_minimum_sample_counts_only_actually_attempted_accounts(self): + paused, _, _ = ck_relogin.evaluate_failure_circuit( + { + "scanned": 20, + "skipped": 11, + "invalid": 9, + "email_quota": 0, + }, + {"failure_pause_min_scanned": 10}, + ) + + assert paused is False + class TestAdaptiveBatch(_Base): def _attempts( @@ -649,6 +677,44 @@ class TestSettlement(_Base): assert account.relogin_failure_kind == "captcha" assert account.status == "manual" + def test_skipped_attempt_does_not_burn_attempts_or_turn_manual(self): + """预算/时长跳过不是失败:不加 relogin_attempts、不转人工、也不按 email_quota 推迟到次日。""" + now = datetime.now(UTC).replace(microsecond=0) + account = self.make_account( + "skipped-prot", + relogin_attempts=1, + relogin_next_at=now - timedelta(minutes=1), + ) + work = enqueue_account_work( + self.session, + account_id=account.id, + work_type=ck_relogin.WORK_LOGIN_RELOGIN, + priority=10, + due_at=now, + max_attempts=20, + ) + work.status = "running" + task = self.make_attempt( + account, + attempt_status="skipped", + attempt_message="未执行:批次已达 1800s 时长预算,本轮未执行(该账号留待下一轮)", + ) + self.session.commit() + + counters, settled_at = self._settle([(account, task)], max_attempts=2) + self.session.refresh(account) + self.session.refresh(work) + + assert counters["invalid"] == 0 + assert counters["manual"] == 0 + assert counters["skipped"] == 1 + assert account.relogin_attempts == 1 + assert account.relogin_failure_kind == "" + assert account.status == "invalid" + assert work.status == "pending" + assert work.due_at >= settled_at + timedelta(minutes=4) + assert work.due_at < settled_at + timedelta(hours=1) + class TestManualQueueApi(_Base): """待人工处理队列:只列自动重登救不了的,按原因分组。""" @@ -883,7 +949,8 @@ class TestSettlementVisibility(_Base): settled_work = checker.get(AccountWorkItem, work.id) settled_account = checker.get(Account, account.id) assert counters["scanned"] == 1 - assert counters["retry"] == 1 + assert counters["skipped"] == 1 + assert counters["retry"] == 0 assert settled_work.status == "pending" assert settled_work.due_at >= now + timedelta(minutes=59) assert settled_account.relogin_next_at >= now + timedelta(minutes=59) diff --git a/tests/test_douyu_login_retry_policy.py b/tests/test_douyu_login_retry_policy.py index fbb07f4..0d8cd59 100644 --- a/tests/test_douyu_login_retry_policy.py +++ b/tests/test_douyu_login_retry_policy.py @@ -161,17 +161,43 @@ def test_missing_email_fails_fast_before_waiting(monkeypatch): def test_email_wait_seconds_is_configurable(monkeypatch): monkeypatch.delenv("DOUYU_EMAIL_CODE_WAIT_SECONDS", raising=False) - # 默认 900 秒:斗鱼验证码是攒批投递的,高峰延迟实测 8~13 分钟 - assert DouyuLogin._email_code_wait_seconds() == 900 + # 默认 120 秒(配合 60 秒补等,一轮邮箱验证码合计最多 3 分钟) + assert DouyuLogin._email_code_wait_seconds() == 120 monkeypatch.setenv("DOUYU_EMAIL_CODE_WAIT_SECONDS", "1800") - assert DouyuLogin._email_code_wait_seconds() == 1800 - # 下限 60:给再小也会把「邮件在路上」误判成没收到 - monkeypatch.setenv("DOUYU_EMAIL_CODE_WAIT_SECONDS", "15") - assert DouyuLogin._email_code_wait_seconds() == 60 + assert DouyuLogin._email_code_wait_seconds() == 180 + # 下限 15 秒 + monkeypatch.setenv("DOUYU_EMAIL_CODE_WAIT_SECONDS", "5") + assert DouyuLogin._email_code_wait_seconds() == 15 def test_email_rescue_seconds_is_configurable(monkeypatch): monkeypatch.delenv("DOUYU_EMAIL_CODE_RESCUE_SECONDS", raising=False) - assert DouyuLogin._email_code_rescue_seconds() == 600 + assert DouyuLogin._email_code_rescue_seconds() == 60 monkeypatch.setenv("DOUYU_EMAIL_CODE_RESCUE_SECONDS", "0") assert DouyuLogin._email_code_rescue_seconds() == 0 + + +def test_email_code_round_total_wait_capped_at_three_minutes(monkeypatch): + """即使环境变量同时调大主等待和补等,一轮验证码总等待也绝不超过 3 分钟(180s)。""" + monkeypatch.setenv("DOUYU_EMAIL_CODE_WAIT_SECONDS", "180") + monkeypatch.setenv("DOUYU_EMAIL_CODE_RESCUE_SECONDS", "180") + client = _login() + waits: list[int] = [] + + class _AlwaysTimeoutVerifier: + def get_verification_code(self, max_wait: int, **kwargs): + waits.append(max_wait) + raise TimeoutError("等待验证码超时") + + try: + client._wait_for_email_code( + _AlwaysTimeoutVerifier(), # type: ignore[arg-type] + baseline_uid=1, + email_sent_at=0.0, + ) + except EmailCodeTimeoutError: + pass + else: # pragma: no cover + raise AssertionError("应当在超时后抛出 EmailCodeTimeoutError") + + assert sum(waits) <= 180 diff --git a/tests/test_lease_ck_refresh.py b/tests/test_lease_ck_refresh.py index 35e188d..16fc986 100644 --- a/tests/test_lease_ck_refresh.py +++ b/tests/test_lease_ck_refresh.py @@ -128,8 +128,43 @@ def test_run_lease_ck_refresh_calls_login_for_selected_accounts(db, monkeypatch) assert calls["kwargs"]["mode"] == "login" # 租约账号**有 CK**,不能被判成"首次登录",否则页面标签和日预算都错位 assert calls["kwargs"]["category"] == "lease_refresh" - # 单账号总时长要能覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟) - assert calls["kwargs"]["max_total_time"] >= 1800 + # 单账号总时长覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待 + assert calls["kwargs"]["max_total_time"] >= 300 assert result["scanned"] == 1 assert result["success"] == 1 assert result["batchIds"] == ["lease-batch"] + + +def test_select_due_lease_accounts_also_covers_presale_and_collab_protection(db): + """P1 到期前刷新不仅看生效租约,也覆盖预售与协作单绑定的履约保护账号。""" + from web.backend.models import DouyuExternalOrder, PlatformFulfillmentTask + + now = datetime.now(UTC).replace(microsecond=0) + presale_due = _account("presale-expiring", cookie_updated_at=now - timedelta(days=6, hours=20)) + collab_due = _account("collab-expiring", cookie_updated_at=now - timedelta(days=6, hours=21)) + ordinary_due = _account("ordinary-expiring", cookie_updated_at=now - timedelta(days=6, hours=20)) + db.add_all([presale_due, collab_due, ordinary_due]) + db.flush() + db.add( + PlatformFulfillmentTask( + source_order_id="p1-order", + source_order_item_id="p1-item", + sale_mode="presale", + account_id=presale_due.id, + binding_status="bound", + execution_status="bound", + ) + ) + db.add( + DouyuExternalOrder( + order_no="p1-collab", + account_id=collab_due.id, + account_username=collab_due.username, + status="incomplete", + ) + ) + db.commit() + + rows = lease_ck_refresh.select_due_lease_accounts(db, now=now, limit=10) + + assert {row.id for row in rows} == {presale_due.id, collab_due.id} diff --git a/tests/test_login_batch_slot_budget.py b/tests/test_login_batch_slot_budget.py index e99a986..4a99240 100644 --- a/tests/test_login_batch_slot_budget.py +++ b/tests/test_login_batch_slot_budget.py @@ -117,3 +117,65 @@ def test_batch_max_seconds_default_and_env(monkeypatch): # 0 = 不限 monkeypatch.setenv("LOGIN_BATCH_MAX_SECONDS", "0") assert login_service._batch_max_seconds() == 0.0 + + +def test_batch_budget_skipped_account_releases_quota_and_avoids_email_quota(monkeypatch): + """超时跳过走完整 run() 结算后,不消耗日配额、不记失败、也不触发 email_quota 误判。""" + from web.backend.models import LoginAttempt, LoginQuotaSetting, LoginQuotaUsage + from web.backend.services.login_failure import classify_failure + + engine, session, user, account = _setup() + try: + session.add( + LoginQuotaSetting( + id=1, + daily_attempt_limit=10, + hourly_attempt_limit=10, + per_account_daily_limit=1, + onboarding_daily_limit=10, + enabled=True, + ) + ) + session.commit() + + monkeypatch.setattr(login_service, "DouyuLogin", _FakeLogin) + monkeypatch.setattr(login_service, "_batch_max_seconds", lambda: 0.001) + _FakeLogin.calls = 0 + + original_submit = login_service.submit + + def delayed_submit(lane, fn, /, *args, **kwargs): + time.sleep(0.02) + return original_submit(lane, fn, *args, **kwargs) + + monkeypatch.setattr(login_service, "submit", delayed_submit) + + runner_db = sessionmaker(bind=engine)() + runner = login_service.LoginBatchRunner( + db=runner_db, + account_ids=[account.id], + created_by=user.id, + creator_permissions=["login:view_all"], + proxy_config=None, + concurrency=1, + mode="login", + ) + runner.run() + + check = sessionmaker(bind=engine)() + try: + task = check.query(LoginTask).filter_by(account_id=account.id).one() + attempt = check.query(LoginAttempt).filter_by(account_id=account.id).one() + usage_rows = check.query(LoginQuotaUsage).all() + + assert task.attempt_status == "skipped" + assert classify_failure(task.attempt_message) != "email_quota" + assert attempt.status == "skipped" + assert attempt.failure_kind == "" + assert all(int(row.attempt_count or 0) == 0 for row in usage_rows) + assert all(int(row.failure_count or 0) == 0 for row in usage_rows) + assert _FakeLogin.calls == 0 + finally: + check.close() + finally: + session.close() diff --git a/tests/test_login_budget_recommendation.py b/tests/test_login_budget_recommendation.py index 9e23dd7..103c0e4 100644 --- a/tests/test_login_budget_recommendation.py +++ b/tests/test_login_budget_recommendation.py @@ -4,7 +4,14 @@ from __future__ import annotations from datetime import UTC, datetime -from web.backend.models import Account, LoginAttempt, LoginQuotaSetting +from web.backend.models import ( + Account, + AutomationJob, + LoginAttempt, + LoginQuotaSetting, + PlatformFulfillmentTask, +) +from web.backend.services.automation.jobs import ck_health from web.backend.services.login_budget_recommendation import recommend_login_budget @@ -121,3 +128,46 @@ def test_email_quota_failures_do_not_lower_success_rate(db): assert recommendation["basis"]["recent_sample"] == 10 assert recommendation["basis"]["recent_success_rate"] == 100.0 + + +def test_protected_inventory_is_allocated_once_within_daily_budget(db): + now = datetime.now(UTC) + protected = _account("budget-protected-valid") + db.add(protected) + db.flush() + db.add_all( + [ + PlatformFulfillmentTask( + source_order_id="budget-protected-order", + source_order_item_id="budget-protected-item", + sale_mode="presale", + account_id=protected.id, + binding_status="bound", + execution_status="bound", + ), + AutomationJob( + key=ck_health.JOB_KEY, + interval_seconds=6 * 3600, + batch_size=200, + concurrency=3, + ), + ] + ) + db.commit() + + recommendation = recommend_login_budget(db, now=now) + recommended = recommendation["recommended"] + allocated = ( + recommended["relogin_protected_daily_limit"] + + recommended["lease_refresh_daily_limit"] + + recommended["relogin_high_value_daily_limit"] + + recommended["relogin_ordinary_daily_limit"] + + recommended["onboarding_daily_limit"] + + recommended["manual_daily_limit"] + ) + + assert recommendation["basis"]["protected_valid_accounts"] == 1 + assert recommendation["basis"]["protected_invalid_backlog"] == 0 + assert recommended["relogin_protected_daily_limit"] >= 50 + assert recommended["lease_refresh_daily_limit"] >= 50 + assert allocated <= recommended["daily_attempt_limit"] diff --git a/tests/test_migrations.py b/tests/test_migrations.py index c015a06..0b17432 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261125_0134" +HEAD_REVISION = "20261125_0135" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index f901ce7..c67f79c 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -537,6 +537,10 @@ "20261125_0134_login_task_logs.py": { "revision": "20261125_0134", "sha256": "c21a4833874676b08a9156e20cfb89c2786aece628d998e8a1bf87a8d0b3cd4b" + }, + "20261125_0135_protected_login_quota_limits.py": { + "revision": "20261125_0135", + "sha256": "8bc4b6a5e9952087e6a18f038f1cb4a054bf25feed311677c94ffcbd1b5711f2" } } } diff --git a/web/backend/migrations/versions/20261125_0135_protected_login_quota_limits.py b/web/backend/migrations/versions/20261125_0135_protected_login_quota_limits.py new file mode 100644 index 0000000..1880f4a --- /dev/null +++ b/web/backend/migrations/versions/20261125_0135_protected_login_quota_limits.py @@ -0,0 +1,56 @@ +"""为履约保护失效重登与快过期续期新增独立的每日登录预算列。""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261125_0135" +down_revision: str | None = "20261125_0134" +branch_labels: str | None = None +depends_on: str | None = None + +TABLE = "login_quota_settings" + + +def _column_exists(name: str) -> bool: + conn = op.get_bind() + count = conn.execute( + sa.text( + "SELECT COUNT(*) FROM information_schema.columns " + "WHERE table_schema = DATABASE() AND table_name = :table " + "AND column_name = :name" + ), + {"table": TABLE, "name": name}, + ).scalar() + return bool(count) + + +def upgrade() -> None: + if not _column_exists("relogin_protected_daily_limit"): + op.add_column( + TABLE, + sa.Column( + "relogin_protected_daily_limit", + sa.Integer(), + nullable=False, + server_default="500", + ), + ) + if not _column_exists("lease_refresh_daily_limit"): + op.add_column( + TABLE, + sa.Column( + "lease_refresh_daily_limit", + sa.Integer(), + nullable=False, + server_default="300", + ), + ) + + +def downgrade() -> None: + if _column_exists("lease_refresh_daily_limit"): + op.drop_column(TABLE, "lease_refresh_daily_limit") + if _column_exists("relogin_protected_daily_limit"): + op.drop_column(TABLE, "relogin_protected_daily_limit") diff --git a/web/backend/models.py b/web/backend/models.py index f97512c..aae551a 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -3049,6 +3049,12 @@ class LoginQuotaSetting(Base): relogin_ordinary_daily_limit: Mapped[int] = mapped_column( Integer, nullable=False, default=500, server_default="500" ) + relogin_protected_daily_limit: Mapped[int] = mapped_column( + Integer, nullable=False, default=500, server_default="500" + ) + lease_refresh_daily_limit: Mapped[int] = mapped_column( + Integer, nullable=False, default=300, server_default="300" + ) manual_daily_limit: Mapped[int] = mapped_column( Integer, nullable=False, default=300, server_default="300" ) diff --git a/web/backend/routers/automation.py b/web/backend/routers/automation.py index 5091d3f..9604cda 100644 --- a/web/backend/routers/automation.py +++ b/web/backend/routers/automation.py @@ -69,6 +69,8 @@ class LoginQuotaUpdate(BaseModel): hourly_attempt_limit: int = Field(..., ge=1, le=100_000) per_account_daily_limit: int = Field(..., ge=1, le=100) onboarding_daily_limit: int = Field(..., ge=0, le=100_000) + relogin_protected_daily_limit: int = Field(default=500, ge=0, le=100_000) + lease_refresh_daily_limit: int = Field(default=300, ge=0, le=100_000) relogin_high_value_daily_limit: int = Field(..., ge=0, le=100_000) relogin_ordinary_daily_limit: int = Field(..., ge=0, le=100_000) manual_daily_limit: int = Field(..., ge=0, le=100_000) @@ -77,12 +79,21 @@ class LoginQuotaUpdate(BaseModel): enabled: bool = True -def _login_quota_out(row: LoginQuotaSetting) -> dict[str, Any]: - return { +def _login_quota_out( + row: LoginQuotaSetting, + db: Session | None = None, +) -> dict[str, Any]: + payload: dict[str, Any] = { "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_protected_daily_limit": int( + getattr(row, "relogin_protected_daily_limit", 500) + ), + "lease_refresh_daily_limit": int( + getattr(row, "lease_refresh_daily_limit", 300) + ), "relogin_high_value_daily_limit": int( row.relogin_high_value_daily_limit ), @@ -95,6 +106,11 @@ def _login_quota_out(row: LoginQuotaSetting) -> dict[str, Any]: "enabled": bool(row.enabled), "updated_at": row.updated_at.isoformat() if row.updated_at else None, } + if db is not None: + from ..services.login_quota_service import get_login_quota_usage_summary + + payload["usage"] = get_login_quota_usage_summary(db) + return payload def _job_out(job: AutomationJob) -> dict[str, Any]: @@ -228,7 +244,7 @@ def get_login_quota( row = LoginQuotaSetting(id=1) db.add(row) db.commit() - return _login_quota_out(row) + return _login_quota_out(row, db=db) @router.get("/login-quota/recommendation") @@ -257,6 +273,8 @@ def update_login_quota( "hourly_attempt_limit", "per_account_daily_limit", "onboarding_daily_limit", + "relogin_protected_daily_limit", + "lease_refresh_daily_limit", "relogin_high_value_daily_limit", "relogin_ordinary_daily_limit", "manual_daily_limit", @@ -275,7 +293,7 @@ def update_login_quota( detail={"before": before, "after": _login_quota_out(row)}, ) db.commit() - return _login_quota_out(row) + return _login_quota_out(row, db=db) @router.patch("/jobs/{key}") diff --git a/web/backend/services/automation/__init__.py b/web/backend/services/automation/__init__.py index 73cafaa..c995ebb 100644 --- a/web/backend/services/automation/__init__.py +++ b/web/backend/services/automation/__init__.py @@ -233,9 +233,9 @@ def register_default_jobs() -> None: register_job( JobSpec( key=LEASE_CK_REFRESH_KEY, - title="租约 CK 到期前刷新", - # 只处理仍有效、但预测 24h 内到期的生效租约账号;提前续 CK, - # 不参与普通失效重登的批次。 + title="履约 CK 到期前刷新", + # 处理仍有效、但预测 24h 内到期的全部履约保护账号(预售 / 协作单 / 生效租约), + # 提前续 CK,不参与普通失效重登的批次。 interval_seconds=600, run_interval_seconds=600, batch_size=10, diff --git a/web/backend/services/automation/jobs/ck_relogin.py b/web/backend/services/automation/jobs/ck_relogin.py index 963c9c7..ae084c0 100644 --- a/web/backend/services/automation/jobs/ck_relogin.py +++ b/web/backend/services/automation/jobs/ck_relogin.py @@ -45,7 +45,7 @@ from ...account_protection_service import ( load_protection_snapshot, ) from ...account_query_filters import automation_account_filter -from ...account_value import value_tier_expr +from ...account_value import is_high_value_expr, value_tier_expr from ...account_work_queue import ( WORK_AGING_SECONDS, active_account_work_exists, @@ -74,9 +74,8 @@ RETRYABLE_KINDS = frozenset({"email_code", "interrupted", "network"}) # 退避阶梯(分钟):1h → 3h → 12h → 24h,超出取最后一级。 BACKOFF_MINUTES = (60, 180, 720, 1440) -# 自动重登时给 runner 的总时长上限。必须能覆盖斗鱼验证码邮件的最坏投递延迟 -# (实测 8~13 分钟),否则等待会被掐断成失败;一轮跑不完的账号反正有退避。 -AUTO_MAX_TOTAL_TIME = 1800 +# 自动重登时给 runner 的总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。 +AUTO_MAX_TOTAL_TIME = 300 # 邮箱配额打满后退避到次日零点,再叠加随机抖动,避免整点齐发。 QUOTA_JITTER_MINUTES = 30 @@ -226,18 +225,22 @@ def _enqueue_due_relogin_work( max_attempts: int, protection: ProtectionSnapshot, limit: int, + account_ids_filter: frozenset[int] | None = None, ) -> int: """把已判定失效但尚未进入队列的账号补成持久工作项。""" - accounts = build_select_query( + query = build_select_query( db, job, now, max_attempts=max_attempts, protection=protection, apply_limit=False, - ).filter( - ~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN) - ).limit(max(1, limit)).all() + ).filter(~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN)) + if account_ids_filter is not None: + if not account_ids_filter: + return 0 + query = query.filter(Account.id.in_(account_ids_filter)) + accounts = query.limit(max(1, limit)).all() for account in accounts: priority = 10 if int(account.id) in protection.relogin_ids else 30 enqueue_account_work( @@ -314,6 +317,28 @@ def _claim_relogin_work( limit: int, ) -> list[AccountWorkItem]: """从持久队列领取重登任务,而不是每轮重新从账号表直接选执行对象。""" + relogin_ids = protection.relogin_ids + if relogin_ids: + # 先把已在队列但优先级仍为普通档的保护账号同步到 10, + # 防止先失效、后进保护组的账号一直排在后面。 + db.query(AccountWorkItem).filter( + AccountWorkItem.work_type == WORK_LOGIN_RELOGIN, + AccountWorkItem.status == "pending", + AccountWorkItem.account_id.in_(relogin_ids), + AccountWorkItem.priority > 10, + ).update({AccountWorkItem.priority: 10}, synchronize_session=False) + # 履约关系结束后必须收回上一轮提升过的优先级,否则历史保护账号会 + # 一直以 P0 档排在普通库存前面。 + demote_query = db.query(AccountWorkItem).filter( + AccountWorkItem.work_type == WORK_LOGIN_RELOGIN, + AccountWorkItem.status == "pending", + AccountWorkItem.priority == 10, + ) + if relogin_ids: + demote_query = demote_query.filter( + ~AccountWorkItem.account_id.in_(relogin_ids) + ) + demote_query.update({AccountWorkItem.priority: 30}, synchronize_session=False) eligible_ids = build_select_query( db, job, @@ -322,42 +347,58 @@ def _claim_relogin_work( protection=protection, apply_limit=False, ).with_entities(Account.id) + ordering: list[Any] = [] + if relogin_ids: + # P0 履约保护目标绝对优先:即使普通账号已积压超 30 分钟, + # 也绝不允许通过 aging 插队到保护账号前面。 + ordering.append( + case((AccountWorkItem.account_id.in_(relogin_ids), 0), else_=1) + ) + # P2 高价值(第 1、2 档)优先于 P3 普通账号,aging 仅在同档内部防饿死。 + ordering.extend( + [ + case((is_high_value_expr(now=now), 0), else_=1), + case( + ( + AccountWorkItem.due_at + <= now - timedelta(seconds=WORK_AGING_SECONDS), + 0, + ), + else_=1, + ), + AccountWorkItem.priority.asc(), + AccountWorkItem.due_at.asc(), + AccountWorkItem.id.asc(), + ] + ) account_ids = [ int(account_id) for (account_id,) in ( db.query(AccountWorkItem.account_id) + .join(Account, Account.id == AccountWorkItem.account_id) .filter( AccountWorkItem.work_type == WORK_LOGIN_RELOGIN, AccountWorkItem.status == "pending", AccountWorkItem.due_at <= now, AccountWorkItem.account_id.in_(eligible_ids), ) - .order_by( - case( - ( - AccountWorkItem.due_at - <= now - timedelta(seconds=WORK_AGING_SECONDS), - 0, - ), - else_=1, - ), - AccountWorkItem.priority.asc(), - AccountWorkItem.due_at.asc(), - AccountWorkItem.id.asc(), - ) + .order_by(*ordering) .limit(max(1, limit)) .all() ) ] if not account_ids: return [] - return claim_account_work( + claimed = claim_account_work( db, work_types=(WORK_LOGIN_RELOGIN,), account_ids=tuple(account_ids), limit=limit, now=now, ) + order_index = {account_id: index for index, account_id in enumerate(account_ids)} + claimed.sort(key=lambda item: order_index.get(int(item.account_id), len(order_index))) + return claimed def _load_batch_state( @@ -486,8 +527,10 @@ def evaluate_failure_circuit( counters: dict[str, int], config: dict[str, Any], ) -> tuple[bool, int, float]: - """评估硬失败率;邮箱配额满属于预期供给限制,不计入熔断。""" + """评估硬失败率;预算跳过和邮箱配额满都不属于真实失败样本。""" scanned = max(0, int(counters.get("scanned", 0) or 0)) + skipped = max(0, int(counters.get("skipped", 0) or 0)) + attempted = max(0, scanned - skipped) invalid = max(0, int(counters.get("invalid", 0) or 0)) email_quota = max(0, int(counters.get("email_quota", 0) or 0)) hard_failures = max(0, invalid - email_quota) @@ -505,8 +548,8 @@ def evaluate_failure_circuit( ) threshold = raw_ratio / 100 if raw_ratio > 1 else raw_ratio threshold = max(0.0, min(threshold, 1.0)) - ratio = hard_failures / scanned if scanned else 0.0 - return scanned >= minimum and ratio > threshold, hard_failures, ratio + ratio = hard_failures / attempted if attempted else 0.0 + return attempted >= minimum and ratio > threshold, hard_failures, ratio def resolve_failure_circuit_config( @@ -544,7 +587,7 @@ def _recent_relogin_success( .filter( LoginAttempt.quota_day >= start_day, LoginAttempt.category.in_( - ("relogin_high_value", "relogin_ordinary") + ("relogin_high_value", "relogin_ordinary", "relogin_protected") ), ) .group_by(LoginAttempt.status, LoginAttempt.failure_kind) @@ -701,6 +744,17 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]: now=now, pending=pending, ) + if protection.relogin_ids: + # 先把尚未入队的到期履约保护账号补进队列,避免被既有普通积压挡住。 + _enqueue_due_relogin_work( + db, + job, + now, + max_attempts=max_attempts, + protection=protection, + limit=adaptive.batch_size, + account_ids_filter=protection.relogin_ids, + ) work_items = _claim_relogin_work( db, job, @@ -773,6 +827,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]: concurrency=max(min(int(job.concurrency or 3), 8), 1), mode="relogin", trigger_source="automation", + batch_max_seconds=0.0, ) batch_id = runner.batch_id try: @@ -839,6 +894,8 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]: parts.append(f"硬失败 {hard_failures}({hard_failure_ratio:.0%})") if paused: parts.append("失败率过高,已自动暂停作业") + if counters.get("skipped"): + parts.append(f"预算/预检跳过 {counters['skipped']}") if adaptive.action != "hold": parts.append( f"批量策略 {adaptive.previous_batch_size}->{adaptive.batch_size}" @@ -850,7 +907,7 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]: "invalid": counters["invalid"], "relogin_started": counters["scanned"], "relogin_success": counters["valid"], - "skipped": 0, + "skipped": counters.get("skipped", 0), "message": ",".join(parts), "detail": { "batch_id": batch_id, @@ -902,6 +959,7 @@ def settle_results( "manual": 0, "retry": 0, "email_quota": 0, + "skipped": 0, } for account_id in account_ids: entry = fresh.get(account_id) @@ -917,7 +975,7 @@ def settle_results( due_at=retry_at, reason="自动重登未产生账号任务,重新排队", ) - counters["retry"] += 1 + counters["skipped"] += 1 continue account, task = entry if task.attempt_status == "success": @@ -925,6 +983,24 @@ def settle_results( # 重登成功:清退避痕迹 + 重算状态(与人工登录成功同一套语义) on_login_success(db, account, occurred_at=now) continue + if task.attempt_status == "skipped": + counters["skipped"] += 1 + # 被预算/槽位跳过不是失败:绝不加 relogin_attempts、不转人工, + # 只保留在队列中等待下一轮重试。 + skip_message = task.attempt_message or "本轮未执行,留待下一轮" + delay = ( + timedelta(hours=1) + if "今日登录尝试上限" in skip_message + else timedelta(minutes=5) + ) + reschedule_account_work_type( + db, + account_id=int(account.id), + work_type=WORK_LOGIN_RELOGIN, + due_at=now + delay, + reason=skip_message, + ) + continue counters["invalid"] += 1 kind = classify_failure(task.attempt_message) diff --git a/web/backend/services/automation/jobs/lease_ck_refresh.py b/web/backend/services/automation/jobs/lease_ck_refresh.py index 1439b06..06f805a 100644 --- a/web/backend/services/automation/jobs/lease_ck_refresh.py +++ b/web/backend/services/automation/jobs/lease_ck_refresh.py @@ -1,11 +1,12 @@ -"""租约账号 CK 到期前刷新(P1)。 +"""履约保护账号 CK 到期前刷新(P1)。 -`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但租约账号如果等到 -失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前 -24 小时**,对仍持有有效 CK 的生效租约账号做一次主动登录,延长 CK 生命周期。 +`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`); @@ -23,18 +24,18 @@ from typing import Any from sqlalchemy import func, or_ from sqlalchemy.orm import Session -from ....models import Account, AccountLease, AutomationJob, User +from ....models import Account, AutomationJob, User from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS +from ...account_protection_service import load_protection_snapshot from ...account_query_filters import automation_account_filter from ...login_automation import run_login_batch_with_fallback from ...login_quota_service import CATEGORY_LEASE_REFRESH JOB_KEY = "lease_ck_refresh" -# 单账号总时长上限:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟), -# 否则等待会被掐断成"等待验证码超时",租约账号一批批地失败。 -LEASE_MAX_TOTAL_TIME = 1800 -TITLE = "租约 CK 到期前刷新" +# 单账号总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。 +LEASE_MAX_TOTAL_TIME = 300 +TITLE = "履约 CK 到期前刷新" REFRESH_BEFORE = timedelta(hours=24) @@ -55,15 +56,17 @@ def due_lease_account_query( db: Session, now: datetime | None = None, ): - """到期前 24h 的租约账号查询(执行和测试共用)。""" + """到期前 24h 的履约保护账号查询(预售 / 协作单 / 生效租约共用)。""" moment = now or datetime.now(UTC) cutoff = moment + REFRESH_BEFORE + protection = load_protection_snapshot(db) + relogin_ids = protection.relogin_ids + if not relogin_ids: + return db.query(Account).filter(Account.id == -1) return ( db.query(Account) - .join(AccountLease, AccountLease.account_id == Account.id) .filter( - AccountLease.status == "active", - AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")), + Account.id.in_(relogin_ids), Account.ck_check_status == "valid", Account.cookie_updated_at.isnot(None), automation_account_filter(cookie_operable=True), @@ -79,7 +82,12 @@ def due_lease_account_query( Account.relogin_next_at <= moment, ), ) - .order_by(Account.cookie_updated_at.asc(), Account.id.asc()) + .order_by( + Account.ck_expected_expires_at.is_(None).asc(), + Account.ck_expected_expires_at.asc(), + Account.cookie_updated_at.asc(), + Account.id.asc(), + ) ) diff --git a/web/backend/services/execution_worker.py b/web/backend/services/execution_worker.py index ec369a6..63d9df5 100644 --- a/web/backend/services/execution_worker.py +++ b/web/backend/services/execution_worker.py @@ -4,7 +4,7 @@ from __future__ import annotations import os import threading -from concurrent.futures import Future, ThreadPoolExecutor, wait +from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait from datetime import UTC, datetime from typing import Any @@ -163,7 +163,7 @@ class ExecutionJobWorker: self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1) try: future.result() - except Exception: # noqa: BLE001 - 结果已落库,这里只消费异常 + except Exception: # noqa: BLE001, S110 - 结果已落库,这里只消费异常 pass executors = self._executors if not executors: @@ -190,13 +190,21 @@ class ExecutionJobWorker: jobs = [] executor = executors.get(lane) for job in jobs: - if executor is None: + if executor is None or self._stop.is_set(): + break + try: + future = executor.submit(self._run_job, job.id) + except RuntimeError: break self._inflight[lane] = self._inflight.get(lane, 0) + 1 - futures[executor.submit(self._run_job, job.id)] = lane + futures[future] = lane slots -= len(jobs) if futures: - wait(list(futures), timeout=poll_seconds) + wait( + list(futures), + timeout=poll_seconds, + return_when=FIRST_COMPLETED, + ) else: self._stop.wait(poll_seconds) diff --git a/web/backend/services/login_automation.py b/web/backend/services/login_automation.py index e558127..af0e702 100644 --- a/web/backend/services/login_automation.py +++ b/web/backend/services/login_automation.py @@ -21,9 +21,8 @@ FALLBACK_LOGIN_API = "iframe" #: 1.5 封涨到 3.3 封,邮件延迟随即从 10 秒级恶化到 8~13 分钟,取码成功率反而 #: 从 100% 掉到 20% 左右。取码失败现在靠「补等迟到邮件 + 批次级退避重试」处理。 EMAIL_FALLBACK_KINDS: frozenset[str] = frozenset() -# 单账号总时长上限:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟), -# 否则等待会被预算掐断,账号白白失败。 -DEFAULT_MAX_TOTAL_TIME = 1800 +# 单账号总时长上限:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待。 +DEFAULT_MAX_TOTAL_TIME = 300 DEFAULT_MAX_RETRIES = 5 @@ -233,7 +232,12 @@ def run_login_batch_with_fallback( attempted = dict(primary) attempted.update(fallback) - outcome.attempted_ids = sorted(attempted) + actually_attempted = [ + account_id + for account_id, (status, _) in attempted.items() + if status != "skipped" + ] + outcome.attempted_ids = sorted(actually_attempted) outcome.success_ids = sorted(success_ids) outcome.failed_ids = [ account_id @@ -241,7 +245,9 @@ def run_login_batch_with_fallback( if account_id not in success_ids ] outcome.skipped_ids = [ - account_id for account_id in ordered_ids if account_id not in attempted + account_id + for account_id in ordered_ids + if account_id not in attempted or attempted[account_id][0] == "skipped" ] for account_id in outcome.failed_ids: status, kind = attempted.get(account_id, ("", "")) diff --git a/web/backend/services/login_budget_recommendation.py b/web/backend/services/login_budget_recommendation.py index 17726b4..b47bb75 100644 --- a/web/backend/services/login_budget_recommendation.py +++ b/web/backend/services/login_budget_recommendation.py @@ -11,6 +11,7 @@ from sqlalchemy.orm import Session from ..models import Account, LoginAttempt, LoginQuotaSetting from .account_lifecycle import MANUAL_KINDS, MANUAL_STATES +from .account_protection_service import load_protection_snapshot from .account_value import is_high_value_expr CK_AVERAGE_LIFETIME_DAYS = 7.38 @@ -25,6 +26,19 @@ MAX_DAILY_ATTEMPTS = 5000 ASSUMED_ACTIVE_HOURS = 12 +def _fit_priority_budgets(limits: list[int], available: int) -> list[int]: + """把 P0-P3 预算压进全局可用名额,按优先级从低到高削减。""" + fitted = list(limits) + excess = max(0, sum(fitted) - max(0, int(available))) + for index in range(len(fitted) - 1, -1, -1): + if excess <= 0: + break + cut = min(fitted[index], excess) + fitted[index] -= cut + excess -= cut + return fitted + + def _automatable_accounts(db: Session): return db.query(Account).filter( Account.auto_managed.is_(True), @@ -55,6 +69,7 @@ def _recent_login_outcomes( "onboarding", "relogin_high_value", "relogin_ordinary", + "relogin_protected", "lease_refresh", ) ), @@ -83,6 +98,8 @@ def _current_quota(db: Session) -> dict[str, int]: "hourly_attempt_limit": 100, "per_account_daily_limit": 2, "onboarding_daily_limit": 150, + "relogin_protected_daily_limit": 500, + "lease_refresh_daily_limit": 300, "relogin_high_value_daily_limit": 300, "relogin_ordinary_daily_limit": 500, "manual_daily_limit": 300, @@ -95,6 +112,12 @@ def _current_quota(db: Session) -> dict[str, int]: "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_protected_daily_limit": int( + getattr(row, "relogin_protected_daily_limit", 500) + ), + "lease_refresh_daily_limit": int( + getattr(row, "lease_refresh_daily_limit", 300) + ), "relogin_high_value_daily_limit": int( row.relogin_high_value_daily_limit ), @@ -134,6 +157,36 @@ def recommend_login_budget( invalid_total = int(invalid_query.count() or 0) invalid_high = _count_high_value(db, invalid_query) invalid_ordinary = max(0, invalid_total - invalid_high) + protection = load_protection_snapshot(db) + protected_ids = protection.relogin_ids + if protected_ids: + protected_valid = int( + valid_query.filter(Account.id.in_(protected_ids)).count() or 0 + ) + protected_invalid = int( + invalid_query.filter(Account.id.in_(protected_ids)).count() or 0 + ) + nonprotected_valid_high = int( + _count_high_value( + db, + valid_query.filter(~Account.id.in_(protected_ids)), + ) + or 0 + ) + nonprotected_invalid_high = int( + _count_high_value( + db, + invalid_query.filter(~Account.id.in_(protected_ids)), + ) + or 0 + ) + else: + protected_valid = 0 + protected_invalid = 0 + nonprotected_valid_high = valid_high + nonprotected_invalid_high = invalid_high + nonprotected_valid = max(0, valid_total - protected_valid) + nonprotected_invalid = max(0, invalid_total - protected_invalid) imported_total = int( _automatable_accounts(db).filter(Account.status == "imported").count() or 0 ) @@ -154,40 +207,76 @@ def recommend_login_budget( ) 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, + nonprotected_relogin_pressure_high = ( + nonprotected_valid_high / CK_AVERAGE_LIFETIME_DAYS + + nonprotected_invalid_high / RELOGIN_RECOVERY_DAYS ) - 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 + nonprotected_relogin_pressure_total = ( + nonprotected_valid / CK_AVERAGE_LIFETIME_DAYS + + nonprotected_invalid / RELOGIN_RECOVERY_DAYS ) high_share = ( - relogin_pressure_high / relogin_pressure_total - if relogin_pressure_total > 0 + nonprotected_relogin_pressure_high + / nonprotected_relogin_pressure_total + if nonprotected_relogin_pressure_total > 0 else 0.5 ) + nonprotected_relogin_attempts = math.ceil( + nonprotected_relogin_pressure_total / effective_rate + ) relogin_high_limit = max( 0, - math.ceil(relogin_success * high_share), + math.ceil(nonprotected_relogin_attempts * high_share), ) - relogin_ordinary_limit = max(0, relogin_success - relogin_high_limit) + relogin_ordinary_limit = max( + 0, + nonprotected_relogin_attempts - relogin_high_limit, + ) + relogin_protected_limit = max( + 50, + math.ceil( + (protected_invalid / RELOGIN_RECOVERY_DAYS) / effective_rate + ), + ) + lease_refresh_limit = max( + 50, + math.ceil( + (protected_valid / CK_AVERAGE_LIFETIME_DAYS) / effective_rate + ), + ) + + raw_relogin_limits = [ + relogin_protected_limit, + lease_refresh_limit, + relogin_high_limit, + relogin_ordinary_limit, + ] + planned_attempts = ( + sum(raw_relogin_limits) + onboarding_attempts + manual_reserve + ) + daily_attempts = min( + MAX_DAILY_ATTEMPTS, + max( + MIN_DAILY_ATTEMPTS, + core_attempts + manual_reserve, + planned_attempts, + ), + ) + available_relogin_attempts = max( + 0, + daily_attempts - onboarding_attempts - manual_reserve, + ) + ( + relogin_protected_limit, + lease_refresh_limit, + relogin_high_limit, + relogin_ordinary_limit, + ) = _fit_priority_budgets( + raw_relogin_limits, + available_relogin_attempts, + ) + hourly_attempts = max(1, math.ceil(daily_attempts / ASSUMED_ACTIVE_HOURS)) if sample < MIN_RECENT_SAMPLE or recent_success_rate < 70: concurrency = 3 @@ -201,6 +290,8 @@ def recommend_login_budget( "hourly_attempt_limit": hourly_attempts, "per_account_daily_limit": 2, "onboarding_daily_limit": onboarding_attempts, + "relogin_protected_daily_limit": relogin_protected_limit, + "lease_refresh_daily_limit": lease_refresh_limit, "relogin_high_value_daily_limit": relogin_high_limit, "relogin_ordinary_daily_limit": relogin_ordinary_limit, "manual_daily_limit": manual_reserve, @@ -217,6 +308,8 @@ def recommend_login_budget( "invalid_backlog": invalid_total, "invalid_high_value": invalid_high, "invalid_ordinary": invalid_ordinary, + "protected_valid_accounts": protected_valid, + "protected_invalid_backlog": protected_invalid, "imported_backlog": imported_total, "recent_sample": sample, "recent_success_rate": recent_success_rate, diff --git a/web/backend/services/login_quota_service.py b/web/backend/services/login_quota_service.py index cfef603..3151d5d 100644 --- a/web/backend/services/login_quota_service.py +++ b/web/backend/services/login_quota_service.py @@ -3,9 +3,10 @@ from __future__ import annotations from dataclasses import dataclass -from datetime import UTC, date, datetime +from datetime import UTC, date, datetime, timedelta from zoneinfo import ZoneInfo +from sqlalchemy import and_, func, or_, select from sqlalchemy.orm import Session from ..models import ( @@ -15,7 +16,10 @@ from ..models import ( LoginQuotaUsage, LoginTask, ) -from .account_value import is_high_value_account +from .account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS +from .account_protection_service import ProtectionSnapshot, load_protection_snapshot +from .account_query_filters import automation_account_filter +from .account_value import is_high_value_account, is_high_value_expr from .douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES CATEGORY_ALL = "all" @@ -23,12 +27,33 @@ CATEGORY_MANUAL = "manual_login" CATEGORY_ONBOARDING = "onboarding" CATEGORY_RELOGIN_HIGH = "relogin_high_value" CATEGORY_RELOGIN_ORDINARY = "relogin_ordinary" +#: 履约保护目标(预售/协作单/生效租约绑定账号)的失效重登:独立分类与配额保护, +#: 不被全库普通重登吃干当天登录次数。 +CATEGORY_RELOGIN_PROTECTED = "relogin_protected" CATEGORY_ACCOUNT_CHECK = "account_check" #: 租约 CK 续期:账号**已经有 CK**,只是租约到期前提前登录续一次。 #: 必须和「首次登录」分开 —— 两者触发方式都是 automation,但预算归属不同, #: 页面标签也不同(曾经被显示成"自动化·首次登录",排查时非常误导)。 CATEGORY_LEASE_REFRESH = "lease_refresh" +_MANUAL_BYPASS_CATEGORIES = frozenset( + { + CATEGORY_MANUAL, + CATEGORY_ACCOUNT_CHECK, + } +) +_REFRESH_LOOKAHEAD = timedelta(hours=24) + +# 自动化登录优先级(数值越小优先级越高): +# P0 履约保护失效重登 > P1 履约快过期续期 > P2 高价值重登 > P3 普通重登 > P4 首次登录 +_TIER_BY_CATEGORY: dict[str, int] = { + CATEGORY_RELOGIN_PROTECTED: 0, + CATEGORY_LEASE_REFRESH: 1, + CATEGORY_RELOGIN_HIGH: 2, + CATEGORY_RELOGIN_ORDINARY: 3, + CATEGORY_ONBOARDING: 4, +} + BUSINESS_TZ = ZoneInfo("Asia/Shanghai") @@ -53,6 +78,7 @@ def classify_login_category( trigger_source: str = "manual", now: datetime | None = None, category: str = "", + protected: bool = False, ) -> str: # 调用方显式指定分类时优先用它(例如租约 CK 续期)。 if category: @@ -60,6 +86,8 @@ def classify_login_category( if mode == "check": return CATEGORY_ACCOUNT_CHECK if mode == "relogin": + if protected: + return CATEGORY_RELOGIN_PROTECTED return ( CATEGORY_RELOGIN_HIGH if is_high_value_account(account, now=now) @@ -166,13 +194,305 @@ def _category_limit(setting: LoginQuotaSetting, category: str) -> int: CATEGORY_ONBOARDING: int(setting.onboarding_daily_limit), CATEGORY_RELOGIN_HIGH: int(setting.relogin_high_value_daily_limit), CATEGORY_RELOGIN_ORDINARY: int(setting.relogin_ordinary_daily_limit), + CATEGORY_RELOGIN_PROTECTED: int( + getattr(setting, "relogin_protected_daily_limit", setting.daily_attempt_limit) + ), + CATEGORY_LEASE_REFRESH: int( + getattr(setting, "lease_refresh_daily_limit", setting.daily_attempt_limit) + ), CATEGORY_MANUAL: int(setting.manual_daily_limit), CATEGORY_ACCOUNT_CHECK: int(setting.manual_daily_limit), - # 租约续期本质是「提前重登」,借用普通重登的日预算。 - CATEGORY_LEASE_REFRESH: int(setting.relogin_ordinary_daily_limit), }.get(category, int(setting.daily_attempt_limit)) +def _available_today_filter( + *, + per_account_limit: int, + quota_day: date, +): + in_flight = ( + select(LoginAttempt.id) + .where( + LoginAttempt.account_id == Account.id, + LoginAttempt.status.in_(("pending", "running")), + ) + .correlate(Account) + .exists() + ) + used_today = ( + select(func.count(LoginAttempt.id)) + .where( + LoginAttempt.account_id == Account.id, + LoginAttempt.quota_day == quota_day, + LoginAttempt.status != "skipped", + ) + .correlate(Account) + .scalar_subquery() + ) + return and_(~in_flight, used_today < per_account_limit) + + +def _count_available_today( + query, + *, + per_account_limit: int, + quota_day: date, +) -> int: + if per_account_limit <= 0: + return 0 + return int( + query.filter( + _available_today_filter( + per_account_limit=per_account_limit, + quota_day=quota_day, + ) + ).count() + or 0 + ) + + +def _pending_protected_invalid_query( + db: Session, + *, + protection: ProtectionSnapshot, + now: datetime, +): + relogin_ids = protection.relogin_ids + if not relogin_ids: + return db.query(Account.id).filter(Account.id == -1) + return db.query(Account.id).filter( + Account.id.in_(relogin_ids), + Account.ck_check_status == "invalid", + automation_account_filter(cookie_operable=True), + func.coalesce(Account.relogin_failure_kind, "").notin_( + tuple(sorted(MANUAL_KINDS)) + ), + or_( + Account.relogin_next_at.is_(None), + Account.relogin_next_at <= now, + ), + ) + + +def _pending_protected_expiring_query( + db: Session, + *, + protection: ProtectionSnapshot, + now: datetime, +): + relogin_ids = protection.relogin_ids + if not relogin_ids: + return db.query(Account.id).filter(Account.id == -1) + cutoff = now + _REFRESH_LOOKAHEAD + return db.query(Account.id).filter( + Account.id.in_(relogin_ids), + 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 <= now, + ), + ) + + +def _pending_inventory_relogin_query( + db: Session, + *, + protection: ProtectionSnapshot, + now: datetime, +): + excluded_ids = protection.monitored_ids + query = db.query(Account.id).filter( + Account.ck_check_status == "invalid", + automation_account_filter(cookie_operable=True), + func.coalesce(Account.relogin_failure_kind, "").notin_( + tuple(sorted(MANUAL_KINDS)) + ), + or_( + Account.relogin_next_at.is_(None), + Account.relogin_next_at <= now, + ), + ) + if excluded_ids: + query = query.filter(~Account.id.in_(excluded_ids)) + return query + + +def _pending_inventory_relogin_counts( + db: Session, + *, + protection: ProtectionSnapshot, + setting: LoginQuotaSetting, + quota_day: date, + now: datetime, +) -> tuple[int, int]: + per_account_limit = int(setting.per_account_daily_limit) + query = _pending_inventory_relogin_query( + db, + protection=protection, + now=now, + ) + high = _count_available_today( + query.filter(is_high_value_expr(now=now)), + per_account_limit=per_account_limit, + quota_day=quota_day, + ) + ordinary = _count_available_today( + query.filter(~is_high_value_expr(now=now)), + per_account_limit=per_account_limit, + quota_day=quota_day, + ) + return high, ordinary + + +def _tier_reserve_needed( + db: Session, + *, + tier: int, + protection: ProtectionSnapshot, + setting: LoginQuotaSetting, + quota_day: date, + now: datetime, +) -> tuple[int, str]: + """计算比当前请求优先级更高的类别还需要预留多少全局名额。""" + if tier <= 0: + return 0, "" + per_account_limit = int(setting.per_account_daily_limit) + if per_account_limit <= 0: + return 0, "" + + def _remaining_cat(category: str) -> int: + return max( + 0, + _category_limit(setting, category) + - _category_daily_total(db, quota_day, category), + ) + + p0_pending = _count_available_today( + _pending_protected_invalid_query(db, protection=protection, now=now), + per_account_limit=per_account_limit, + quota_day=quota_day, + ) + reserved = min(p0_pending, _remaining_cat(CATEGORY_RELOGIN_PROTECTED)) + if tier == 1: + return reserved, "履约保护失效账号" + + p1_pending = _count_available_today( + _pending_protected_expiring_query(db, protection=protection, now=now), + per_account_limit=per_account_limit, + quota_day=quota_day, + ) + reserved += min(p1_pending, _remaining_cat(CATEGORY_LEASE_REFRESH)) + if tier == 2: + return reserved, "履约保护与快过期账号" + + p2_pending, p3_pending = _pending_inventory_relogin_counts( + db, + protection=protection, + setting=setting, + quota_day=quota_day, + now=now, + ) + reserved += min(p2_pending, _remaining_cat(CATEGORY_RELOGIN_HIGH)) + if tier == 3: + return reserved, "履约保护与高价值账号" + + reserved += min(p3_pending, _remaining_cat(CATEGORY_RELOGIN_ORDINARY)) + return reserved, "高优先级重登账号" + + +def get_login_quota_usage_summary( + db: Session, + *, + now: datetime | None = None, +) -> dict[str, object]: + """返回今日/本小时全局及各优先级分类的登录配额使用与积压情况。""" + moment = now or datetime.now(UTC) + quota_day, quota_hour = _bucket(moment) + setting = db.query(LoginQuotaSetting).filter(LoginQuotaSetting.id == 1).first() + if setting is None: + setting = LoginQuotaSetting(id=1) + protection = load_protection_snapshot(db) + per_account_limit = int(setting.per_account_daily_limit) + + p0_pending = _count_available_today( + _pending_protected_invalid_query(db, protection=protection, now=moment), + per_account_limit=per_account_limit, + quota_day=quota_day, + ) + p1_pending = _count_available_today( + _pending_protected_expiring_query(db, protection=protection, now=moment), + per_account_limit=per_account_limit, + quota_day=quota_day, + ) + p2_pending, p3_pending = _pending_inventory_relogin_counts( + db, + protection=protection, + setting=setting, + quota_day=quota_day, + now=moment, + ) + p4_pending = int( + db.query(func.count(Account.id)) + .filter( + Account.auto_managed.is_(True), + Account.status == "imported", + Account.username != "", + Account.password != "", + or_(Account.cookie.is_(None), Account.cookie == ""), + ) + .scalar() + or 0 + ) + + specs = [ + ("P0", CATEGORY_RELOGIN_PROTECTED, "履约保护失效重登", p0_pending), + ("P1", CATEGORY_LEASE_REFRESH, "履约快过期续期", p1_pending), + ("P2", CATEGORY_RELOGIN_HIGH, "高价值重登", p2_pending), + ("P3", CATEGORY_RELOGIN_ORDINARY, "普通重登", p3_pending), + ("P4", CATEGORY_ONBOARDING, "首次登录", p4_pending), + ("人工", CATEGORY_MANUAL, "人工登录", 0), + ] + categories = [] + for priority, category, label, pending in specs: + limit = _category_limit(setting, category) + used = _category_daily_total(db, quota_day, category) + categories.append( + { + "priority": priority, + "category": category, + "label": label, + "limit": limit, + "used": used, + "remaining": max(0, limit - used), + "pending": pending, + } + ) + daily_limit = int(setting.daily_attempt_limit) + daily_used = _daily_total(db, quota_day) + hourly_limit = int(setting.hourly_attempt_limit) + hourly_used = _hourly_total(db, quota_day, quota_hour) + return { + "quota_day": quota_day.isoformat(), + "quota_hour": quota_hour, + "daily_limit": daily_limit, + "daily_used": daily_used, + "daily_remaining": max(0, daily_limit - daily_used), + "hourly_limit": hourly_limit, + "hourly_used": hourly_used, + "hourly_remaining": max(0, hourly_limit - hourly_used), + "categories": categories, + } + + def reserve_login_attempt( db: Session, *, @@ -187,18 +507,24 @@ def reserve_login_attempt( moment = now or datetime.now(UTC) quota_day, quota_hour = _bucket(moment) setting = _setting(db) + protection = None + is_protected = False + if mode == "relogin" and not category: + protection = load_protection_snapshot(db) + is_protected = int(account.id) in protection.relogin_ids + resolved_category = classify_login_category( + account, + mode=mode, + trigger_source=trigger_source, + now=moment, + category=category, + protected=is_protected, + ) if not setting.enabled: - category = classify_login_category( - account, - mode=mode, - trigger_source=trigger_source, - now=moment, - category=category, - ) attempt = LoginAttempt( account_id=int(account.id), batch_id=batch_id[:64], - category=category, + category=resolved_category, trigger_source=trigger_source[:16], created_by=created_by, started_at=moment, @@ -209,6 +535,9 @@ def reserve_login_attempt( db.flush() return QuotaDecision(True, attempt=attempt) + if resolved_category not in _MANUAL_BYPASS_CATEGORIES and protection is None: + protection = load_protection_snapshot(db) + in_flight = ( db.query(LoginTask.id) .filter( @@ -233,35 +562,59 @@ def reserve_login_attempt( .filter( LoginAttempt.account_id == account.id, LoginAttempt.quota_day == quota_day, + LoginAttempt.status != "skipped", ) .count() ) if account_day_count >= int(setting.per_account_daily_limit): return QuotaDecision(False, reason="该账号已达到今日登录尝试上限") - if _daily_total(db, quota_day) >= int(setting.daily_attempt_limit): + daily_used = _daily_total(db, quota_day) + daily_limit = int(setting.daily_attempt_limit) + if daily_used >= daily_limit: return QuotaDecision(False, reason="全局每日登录尝试预算已用完") - if _hourly_total(db, quota_day, quota_hour) >= int( - setting.hourly_attempt_limit - ): + + hourly_used = _hourly_total(db, quota_day, quota_hour) + hourly_limit = int(setting.hourly_attempt_limit) + if hourly_used >= hourly_limit: return QuotaDecision(False, reason="全局每小时登录尝试预算已用完") - category = classify_login_category( - account, - mode=mode, - trigger_source=trigger_source, - now=moment, - category=category, - ) - if _category_daily_total(db, quota_day, category) >= _category_limit( - setting, category + if resolved_category not in _MANUAL_BYPASS_CATEGORIES: + assert protection is not None + tier = ( + 0 + if is_protected and resolved_category != CATEGORY_LEASE_REFRESH + else _TIER_BY_CATEGORY.get(resolved_category, 4) + ) + reserved_needed, target_label = _tier_reserve_needed( + db, + tier=tier, + protection=protection, + setting=setting, + quota_day=quota_day, + now=moment, + ) + if reserved_needed > 0: + if (daily_limit - daily_used) <= reserved_needed: + return QuotaDecision( + False, + reason=f"全局每日登录尝试预算已预留给{target_label}", + ) + if (hourly_limit - hourly_used) <= reserved_needed: + return QuotaDecision( + False, + reason=f"全局每小时登录尝试预算已预留给{target_label}", + ) + + if _category_daily_total(db, quota_day, resolved_category) >= _category_limit( + setting, resolved_category ): - return QuotaDecision(False, reason=f"{category} 今日登录预算已用完") + return QuotaDecision(False, reason=f"{resolved_category} 今日登录预算已用完") attempt = LoginAttempt( account_id=int(account.id), batch_id=batch_id[:64], - category=category, + category=resolved_category, trigger_source=trigger_source[:16], created_by=created_by, started_at=moment, @@ -269,7 +622,7 @@ def reserve_login_attempt( quota_day=quota_day, ) db.add(attempt) - for usage_category in (CATEGORY_ALL, category): + for usage_category in (CATEGORY_ALL, resolved_category): usage = _usage_row( db, quota_day=quota_day, @@ -289,7 +642,7 @@ def finish_login_attempt( failure_kind: str = "", now: datetime | None = None, ) -> None: - if attempt.status in {"success", "failed", "error", "stopped"}: + if attempt.status in {"success", "failed", "error", "stopped", "skipped"}: return moment = now or datetime.now(UTC) attempt.status = status[:16] @@ -307,7 +660,10 @@ def finish_login_attempt( quota_hour=quota_hour, category=usage_category, ) - if status == "success": + if status == "skipped": + # 本轮未真正发出登录请求:退还预扣的 attempt_count,也不记入失败。 + usage.attempt_count = max(0, int(usage.attempt_count or 0) - 1) + elif status == "success": usage.success_count = int(usage.success_count or 0) + 1 elif status in {"failed", "error"}: usage.failure_count = int(usage.failure_count or 0) + 1 @@ -346,10 +702,12 @@ __all__ = [ "CATEGORY_ONBOARDING", "CATEGORY_RELOGIN_HIGH", "CATEGORY_RELOGIN_ORDINARY", + "CATEGORY_RELOGIN_PROTECTED", "QuotaDecision", "classify_login_category", "cleanup_orphan_login_attempts", "finish_login_attempt", + "get_login_quota_usage_summary", "login_concurrency_limit", "reserve_login_attempt", ] diff --git a/web/backend/services/login_service.py b/web/backend/services/login_service.py index 6c78628..38bee33 100644 --- a/web/backend/services/login_service.py +++ b/web/backend/services/login_service.py @@ -245,8 +245,8 @@ def get_relogin_limits() -> tuple[int, int]: """读取客服 CK 重登的重试与总时长限制。""" return ( _positive_env_int("COOKIE_RELOGIN_MAX_RETRIES", 5), - # 单账号总时长:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟) - _positive_env_int("COOKIE_RELOGIN_MAX_TOTAL_TIME", 1800), + # 单账号总时长:覆盖极验 + 一轮邮箱验证码最多 3 分钟(180s)等待 + _positive_env_int("COOKIE_RELOGIN_MAX_TOTAL_TIME", 300), ) @@ -533,6 +533,7 @@ class LoginBatchRunner: category: str = "", batch_id: str | None = None, log_sink: Callable[[dict[str, Any]], None] | None = None, + batch_max_seconds: float | None = None, ): self.db = db self.account_ids = account_ids @@ -569,6 +570,7 @@ class LoginBatchRunner: self._completed = 0 # 批次起点(单调时钟):每个账号开始执行前据此判断批次是否已超时。 self._batch_started_at = 0.0 + self._batch_max_seconds_override = batch_max_seconds # 逐账号日志走模块级 loguru sink(见文件头 _LOG_CONTEXT), # 这里保证 sink 与刷新线程都已就绪。 _install_task_log_sink() @@ -674,17 +676,7 @@ class LoginBatchRunner: task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first() if task is None: return - now = datetime.now(UTC) - message = f"未执行:{reason}" - task.attempt_status = "skipped" - task.attempt_message = message - task.attempt_batch_id = self.batch_id - task.attempt_at = now - task.finished_at = now - if not task.account.cookie: - task.status = "skipped" - task.message = message - task.logs = [_task_log_entry("warning", f"本次登录未执行:{reason}")] + self._record_skipped_attempt(task, task.account, reason) worker_db.commit() finally: worker_db.close() @@ -739,16 +731,17 @@ class LoginBatchRunner: self._mark_relogin_stopped(task_id, "任务已停止,旧 Cookie 已保留") return - # 批次在执行任务队列里占着一个槽。斗鱼邮箱验证码是攒批投递的,等一封 - # 验证码最长 25 分钟/账号,批次不设上限的话 10 个账号能占着槽位跑近 - # 一小时,把同队列的斗鱼履约批次饿死(新建任务直接报「斗鱼任务繁忙」)。 - # 所以每个账号**开始执行前**都看一次批次时长,超时就不再接新账号。 - budget = _batch_max_seconds() + # 每个账号**开始执行前**检查批次时长,超时就不再接新账号,避免单批无限占槽。 + budget = ( + _batch_max_seconds() + if self._batch_max_seconds_override is None + else max(0.0, float(self._batch_max_seconds_override)) + ) if budget > 0 and self._batch_started_at > 0: elapsed = time.monotonic() - self._batch_started_at if elapsed > budget: reason = ( - f"批次已达 {int(budget)}s 时长上限,本轮未执行" + f"批次已达 {int(budget)}s 时长预算,本轮未执行" "(该账号留待下一轮)" ) self._push_log("warning", reason) @@ -1252,6 +1245,9 @@ def _settle_login_attempts(batch_id: str) -> None: if task_status == "success" or task_status == "account_verified": status = "success" failure_kind = "" + elif task_status == "skipped": + status = "skipped" + failure_kind = "" elif task_status in CHECK_STATUS_MESSAGES: status = "failed" failure_kind = ( diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 8be8164..720ea83 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -1774,11 +1774,35 @@ export interface AutomationJobUpdate { concurrency?: number; } +export interface AutomationLoginQuotaCategoryUsage { + priority: string; + category: string; + label: string; + limit: number; + used: number; + remaining: number; + pending: number; +} + +export interface AutomationLoginQuotaUsageSummary { + quota_day: string; + quota_hour: number; + daily_limit: number; + daily_used: number; + daily_remaining: number; + hourly_limit: number; + hourly_used: number; + hourly_remaining: number; + categories: AutomationLoginQuotaCategoryUsage[]; +} + export interface AutomationLoginQuota { daily_attempt_limit: number; hourly_attempt_limit: number; per_account_daily_limit: number; onboarding_daily_limit: number; + relogin_protected_daily_limit: number; + lease_refresh_daily_limit: number; relogin_high_value_daily_limit: number; relogin_ordinary_daily_limit: number; manual_daily_limit: number; @@ -1786,6 +1810,7 @@ export interface AutomationLoginQuota { failure_pause_ratio: number; enabled: boolean; updated_at?: string | null; + usage?: AutomationLoginQuotaUsageSummary; } export interface AutomationLoginQuotaRecommendation { @@ -1798,6 +1823,8 @@ export interface AutomationLoginQuotaRecommendation { invalid_backlog: number; invalid_high_value: number; invalid_ordinary: number; + protected_valid_accounts: number; + protected_invalid_backlog: number; imported_backlog: number; recent_sample: number; recent_success_rate: number; diff --git a/web/frontend/src/pages/AutomationPage.tsx b/web/frontend/src/pages/AutomationPage.tsx index ca96ffc..8494275 100644 --- a/web/frontend/src/pages/AutomationPage.tsx +++ b/web/frontend/src/pages/AutomationPage.tsx @@ -55,9 +55,11 @@ const BUDGET_LABELS: Record = { daily_attempt_limit: "全局每日尝试", hourly_attempt_limit: "全局每小时尝试", per_account_daily_limit: "单账号每日尝试", - onboarding_daily_limit: "首次登录", - relogin_high_value_daily_limit: "高价值账号重登", - relogin_ordinary_daily_limit: "普通账号重登", + relogin_protected_daily_limit: "P0 履约保护失效重登", + lease_refresh_daily_limit: "P1 履约快过期续期", + relogin_high_value_daily_limit: "P2 高价值账号重登", + relogin_ordinary_daily_limit: "P3 普通账号重登", + onboarding_daily_limit: "P4 首次登录", manual_daily_limit: "人工登录保留", login_concurrency: "登录并发", failure_pause_ratio: "失败率熔断", @@ -67,9 +69,11 @@ type BudgetFieldName = | "daily_attempt_limit" | "hourly_attempt_limit" | "per_account_daily_limit" - | "onboarding_daily_limit" + | "relogin_protected_daily_limit" + | "lease_refresh_daily_limit" | "relogin_high_value_daily_limit" | "relogin_ordinary_daily_limit" + | "onboarding_daily_limit" | "manual_daily_limit" | "login_concurrency" | "failure_pause_ratio"; @@ -84,9 +88,31 @@ const BUDGET_FIELDS: Array<{ { name: "daily_attempt_limit", label: "全局每日尝试", min: 1, max: 1_000_000 }, { name: "hourly_attempt_limit", label: "全局每小时尝试", min: 1, max: 100_000 }, { name: "per_account_daily_limit", label: "单账号每日尝试", min: 1, max: 100 }, - { name: "onboarding_daily_limit", label: "首次登录预算", min: 0, max: 100_000 }, - { name: "relogin_high_value_daily_limit", label: "高价值重登预算", min: 0, max: 100_000 }, - { name: "relogin_ordinary_daily_limit", label: "普通重登预算", min: 0, max: 100_000 }, + { + name: "relogin_protected_daily_limit", + label: "P0 履约保护失效重登预算", + min: 0, + max: 100_000, + }, + { + name: "lease_refresh_daily_limit", + label: "P1 履约快过期续期预算", + min: 0, + max: 100_000, + }, + { + name: "relogin_high_value_daily_limit", + label: "P2 高价值重登预算", + min: 0, + max: 100_000, + }, + { + name: "relogin_ordinary_daily_limit", + label: "P3 普通重登预算", + min: 0, + max: 100_000, + }, + { name: "onboarding_daily_limit", label: "P4 首次登录预算", min: 0, max: 100_000 }, { name: "manual_daily_limit", label: "人工登录保留", min: 0, max: 100_000 }, { name: "login_concurrency", label: "登录并发", min: 1, max: 10 }, { name: "failure_pause_ratio", label: "失败率熔断阈值", min: 0, max: 100, suffix: "%" }, @@ -119,7 +145,7 @@ const JOB_UI: Record = { showConcurrency: false, }, lease_ck_refresh: { - description: "对仍有效、但预测 24 小时内到期的生效租约账号提前登录续 CK;只处理 platform_fulfillment / douyu_collab 租约。", + description: "对仍有效、但预测 24 小时内到期的履约保护账号提前登录续 CK;覆盖预售、协作单和生效租约。", core: true, showRecheck: false, showConcurrency: true, @@ -654,6 +680,78 @@ export default function AutomationPage() { const budgetTab = ( + {loginQuota?.usage ? ( + + + 今日全局 {loginQuota.usage.daily_used} / {loginQuota.usage.daily_limit} + + + 本小时 {loginQuota.usage.hourly_used} / {loginQuota.usage.hourly_limit} + + + } + > + + ( + + {value} + + ), + }, + { title: "类别", dataIndex: "label" }, + { + title: "待处理积压", + dataIndex: "pending", + width: 110, + render: (value: number, row) => + row.category === "manual_login" ? "-" : value, + }, + { title: "今日已用", dataIndex: "used", width: 100 }, + { title: "每日上限", dataIndex: "limit", width: 100 }, + { + title: "今日剩余", + dataIndex: "remaining", + width: 100, + render: (value: number) => ( + 0 ? "success" : "danger"}>{value} + ), + }, + ]} + /> + + ) : null} + = { onboarding: '首次登录', relogin_high_value: '高价值重登', relogin_ordinary: '普通重登', + relogin_protected: '履约保护重登', manual: '人工登录', account_check: '账号检测', - lease_refresh: '租约CK续期', + lease_refresh: '履约快过期续期', }; function loginSourceLabel(task: LoginTaskItem) {