From 00c30cc24e123e0e31af574c34a762586889fd62 Mon Sep 17 00:00:00 2001 From: yml Date: Fri, 20 Nov 2026 20:46:55 +0800 Subject: [PATCH] =?UTF-8?q?fix(douyu):=20=E7=99=BB=E5=BD=95=E5=90=8E?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=A4=8D=E6=A3=80=20CK=20=E5=B9=B6=E6=94=B6?= =?UTF-8?q?=E7=B4=A7=E5=88=86=E9=85=8D=E6=B1=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/设计-账号全生命周期.md | 10 +- tests/test_account_actions.py | 6 +- tests/test_account_assign_filter.py | 50 ++++++-- tests/test_login_attempt_isolation.py | 83 ++++++++++--- web/backend/routers/accounts.py | 58 ++++----- web/backend/schemas.py | 2 +- web/backend/services/login_service.py | 137 ++++++++++++--------- web/frontend/src/api/types.ts | 2 +- web/frontend/src/pages/AssignmentsPage.tsx | 5 +- 9 files changed, 239 insertions(+), 114 deletions(-) diff --git a/docs/设计-账号全生命周期.md b/docs/设计-账号全生命周期.md index 863b1ec..36f6d32 100644 --- a/docs/设计-账号全生命周期.md +++ b/docs/设计-账号全生命周期.md @@ -61,7 +61,15 @@ CK 本体和健康结果都在账号上: 2. 只在“由好变坏”时写一条 `ck_invalid` 事件; 3. 重新推导账号生命周期状态。 -登录成功统一调用 `on_login_success()`:清空重登退避痕迹并重新推导状态。 +普通登录与重登成功后,都会用本次新 Cookie 立即执行一次 CK 探针: + +1. 网络探针期间不持有数据库事务; +2. 在同一事务里写回账号 Cookie、`cookie_updated_at`、`valid / invalid / error` + 和晚于 Cookie 更新时间的 `ck_checked_at`; +3. 清空重登退避痕迹并重新推导状态。 + +分配池只接受 `ck_check_status=valid` 且 `ck_checked_at >= cookie_updated_at` +的账号。旧 Cookie 的检测结论不能用于新 Cookie。 清空 CK 统一调用 `on_ck_cleared()`:同时清空健康字段、记录 `ck_cleared` 事件并回到未登录。 ## 账号事件流 diff --git a/tests/test_account_actions.py b/tests/test_account_actions.py index 392fb74..3ead7bf 100644 --- a/tests/test_account_actions.py +++ b/tests/test_account_actions.py @@ -11,7 +11,7 @@ S4 之前的状态(都是「定义了却从没发过」): 本文件守住修复后的行为。 """ -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta import pytest @@ -46,6 +46,10 @@ class _Base: email_password="ep", cookie=kwargs.pop("cookie", "acf_uid=1"), ck_check_status=kwargs.pop("ck_check_status", "valid"), + cookie_updated_at=kwargs.pop( + "cookie_updated_at", NOW - timedelta(seconds=1) + ), + ck_checked_at=kwargs.pop("ck_checked_at", NOW), **kwargs, ) self.session.add(account) diff --git a/tests/test_account_assign_filter.py b/tests/test_account_assign_filter.py index bb44ce4..6277491 100644 --- a/tests/test_account_assign_filter.py +++ b/tests/test_account_assign_filter.py @@ -12,14 +12,20 @@ 「筛出未分配 → 一键分给某人」不必先勾选。显式 `account_ids` 的旧路径不变。 """ +from datetime import UTC, datetime, timedelta + +import pytest +from fastapi import HTTPException + from tests.support.db import get_test_engine, make_test_session from web.backend.models import Account, User from web.backend.routers.accounts import ( + assign_account, assignments_summary, batch_assign_accounts, list_accounts, ) -from web.backend.schemas import BatchAssign +from web.backend.schemas import AccountAssign, BatchAssign class _Base: @@ -31,11 +37,13 @@ class _Base: self.other = User(username="af-kf2", password_hash="h", role="support") self.session.add_all([self.admin, self.support, self.other]) self.session.commit() + self.now = datetime.now(UTC) def teardown_method(self): self.session.close() def make_account(self, name: str, **kwargs) -> Account: + ck_check_status = kwargs.pop("ck_check_status", "valid") account = Account( username=name, password="p", @@ -43,6 +51,11 @@ class _Base: email_password="ep", # 默认持有 CK —— 分配接口只接受「还拿着 CK」的账号 cookie=kwargs.pop("cookie", "acf_uid=1"), + ck_check_status=ck_check_status, + cookie_updated_at=kwargs.pop( + "cookie_updated_at", self.now - timedelta(seconds=1) + ), + ck_checked_at=kwargs.pop("ck_checked_at", self.now), **kwargs, ) self.session.add(account) @@ -102,19 +115,23 @@ class TestAssignFilter(_Base): class TestAssignablePool(_Base): - """分配池口径:CK 失效的号必须先修复,不能混进「未分配」让人误分配。""" + """分配池口径:只收当前 Cookie 的新鲜有效检测结果。""" - def test_assignable_only_excludes_invalid_ck(self): + def test_assignable_only_requires_fresh_valid_ck(self): self.make_account("ap-valid", ck_check_status="valid") - self.make_account("ap-unchecked") # 还没检测过:按可用处理 - self.make_account("ap-error", ck_check_status="error") # 查不到 ≠ 失效 + self.make_account("ap-unchecked", ck_check_status="", ck_checked_at=None) + self.make_account("ap-error", ck_check_status="error") self.make_account("ap-invalid", ck_check_status="invalid") + self.make_account( + "ap-stale-valid", + ck_check_status="valid", + cookie_updated_at=self.now, + ck_checked_at=self.now - timedelta(seconds=1), + ) self.make_account("ap-disabled", ck_check_status="valid", status="disabled") assert self.names(assign_status="unassigned", assignable_only=True) == [ "ap-valid", - "ap-unchecked", - "ap-error", ] def test_summary_counts_only_assignable(self): @@ -160,6 +177,25 @@ class TestAssignablePool(_Base): assert valid.assigned_to == self.support.id assert invalid.assigned_to is None + def test_single_assign_rejects_stale_valid_verdict(self): + stale = self.make_account( + "single-stale", + ck_check_status="valid", + cookie_updated_at=self.now, + ck_checked_at=self.now - timedelta(seconds=1), + ) + + with pytest.raises(HTTPException) as exc_info: + assign_account( + stale.id, + AccountAssign(assigned_to=self.support.id), + db=self.session, + current=self.admin, + ) + + assert exc_info.value.status_code == 400 + assert "有效 CK 检测" in exc_info.value.detail + class TestAllMatchingAssign(_Base): def test_assigns_every_matching_unassigned(self): diff --git a/tests/test_login_attempt_isolation.py b/tests/test_login_attempt_isolation.py index b156302..aa6fb2b 100644 --- a/tests/test_login_attempt_isolation.py +++ b/tests/test_login_attempt_isolation.py @@ -86,8 +86,31 @@ class TestLoginAttemptIsolation: def teardown_method(self): self.session.close() - def _run_batch(self, monkeypatch, *, mode="login", account_ids=None, stop=False): + def _run_batch( + self, + monkeypatch, + *, + mode="login", + account_ids=None, + stop=False, + cookie_check=None, + ): monkeypatch.setattr(login_service, "DouyuLogin", _FakeLogin) + monkeypatch.setattr( + login_service, + "check_douyu_cookie", + cookie_check + or ( + lambda _cookie: { + "valid": True, + "message": "ok", + "fish_ball": 1, + "nickname": "n", + "level": 1, + "checked_at": datetime.now(UTC), + } + ), + ) # 批次结束时 runner 会关掉自己的会话,因此单独给它一个。 runner_db = sessionmaker(bind=self.engine)() runner = login_service.LoginBatchRunner( @@ -163,7 +186,7 @@ class TestLoginAttemptIsolation: task = self._fresh(self.task_id) account = self._fresh_account() assert task.status == "success" - assert task.message == "登录成功" + assert task.message == "登录成功,Cookie 有效" assert task.attempt_status == "success" assert task.attempt_at is not None assert task.batch_id != "old-batch" @@ -171,6 +194,9 @@ class TestLoginAttemptIsolation: assert account.cookie == "new-cookie" assert account.cookie_updated_at is not None assert account.cookie_source == "web" + assert account.ck_check_status == "valid" + assert account.ck_checked_at >= account.cookie_updated_at + assert account.status == "active" def test_relogin_success_writes_ck_verdict_on_the_account(self, monkeypatch): """重登成功后的复检必须写到账号上,不能写到登录器的临时对象上。 @@ -181,19 +207,6 @@ class TestLoginAttemptIsolation: """ self.account.ck_check_status = "invalid" self.session.commit() - monkeypatch.setattr( - login_service, - "check_douyu_cookie", - lambda _cookie: { - "valid": True, - "message": "ok", - "fish_ball": 1, - "nickname": "n", - "level": 1, - "checked_at": datetime.now(UTC), - }, - ) - self._run_batch(monkeypatch, mode="relogin") task = self._fresh(self.task_id) @@ -203,6 +216,46 @@ class TestLoginAttemptIsolation: assert account.cookie == "new-cookie" assert account.ck_check_status == "valid" + def test_normal_login_replaces_stale_invalid_verdict_after_probe(self, monkeypatch): + self.account.ck_check_status = "invalid" + self.account.status = "invalid" + self.session.commit() + + self._run_batch(monkeypatch) + + task = self._fresh(self.task_id) + account = self._fresh_account() + assert task.attempt_status == "success" + assert task.message == "登录成功,Cookie 有效" + assert account.cookie == "new-cookie" + assert account.ck_check_status == "valid" + assert account.ck_checked_at >= account.cookie_updated_at + assert account.status == "active" + + def test_login_success_with_failed_probe_keeps_account_out_of_pool( + self, monkeypatch + ): + self.account.ck_check_status = "invalid" + self.account.status = "invalid" + self.session.commit() + + self._run_batch( + monkeypatch, + cookie_check=lambda _cookie: { + "valid": False, + "message": "Cookie 已失效", + "checked_at": datetime.now(UTC), + }, + ) + + task = self._fresh(self.task_id) + account = self._fresh_account() + assert task.attempt_status == "success" + assert "Cookie 有效性检测失败" in task.message + assert account.cookie == "new-cookie" + assert account.ck_check_status == "invalid" + assert account.status == "invalid" + def test_stopped_batch_keeps_existing_cookie(self, monkeypatch): self._run_batch(monkeypatch, stop=True) diff --git a/web/backend/routers/accounts.py b/web/backend/routers/accounts.py index a5242f4..ba96e0d 100644 --- a/web/backend/routers/accounts.py +++ b/web/backend/routers/accounts.py @@ -87,15 +87,13 @@ def _visible_accounts_query(db: Session, current: User): def _assignable_account_filter(): - """分配池口径:有 CK 且 CK **还没被判失效**,并且没被人工停用/归档。 - - - `ck_check_status` 为空 = 还没检测过(`derive_status` 同样按可用处理); - - `error` = 本轮查不到,不代表失效,照常留在池子里; - - `invalid` = 巡检已判失效,必须先重登/修复,分配给它也跑不了任何任务。 - """ + """分配池口径:当前 Cookie 必须有一次不早于它的有效 CK 检测。""" return and_( cookie_holding_filter(), - or_(Account.ck_check_status.is_(None), Account.ck_check_status != "invalid"), + Account.ck_check_status == "valid", + Account.ck_checked_at.isnot(None), + Account.cookie_updated_at.isnot(None), + Account.ck_checked_at >= Account.cookie_updated_at, or_( Account.status.is_(None), Account.status.notin_([STATUS_DISABLED, STATUS_ARCHIVED]), @@ -442,7 +440,7 @@ def list_accounts( assigned_user_id: int | None = Query(None, description="只看某个客服名下的账号"), assignable_only: bool = Query( False, - description="只看可分配账号:持 CK 且 CK 未失效(排除已停用/归档)", + description="只看可分配账号:当前 Cookie 已通过新鲜 CK 检测(排除已停用/归档)", ), tag: str = Query(None), account_names: str = Query( @@ -1025,17 +1023,20 @@ def assign_account( if target.role != "support": raise HTTPException(status_code=400, detail="只能分配给客服角色") - # 只能分配当前仍持有 CK 的账号(CK 现在挂在账号上) + # 只能分配当前 Cookie 已通过新鲜 CK 检测的账号。 has_success = ( db.query(Account) .filter( Account.id == account_id, - cookie_holding_filter(), + _assignable_account_filter(), ) .first() ) if not has_success: - raise HTTPException(status_code=400, detail="该账号尚未成功登录,无法分配") + raise HTTPException( + status_code=400, + detail="该账号尚未通过有效 CK 检测,无法分配", + ) if acc.assigned_to != req.assigned_to: acc.assigned_to = req.assigned_to @@ -1081,27 +1082,28 @@ def batch_assign_accounts( if target.role != "support": raise HTTPException(status_code=400, detail="只能分配给客服角色") - # 只能分配当前仍持有 CK 的账号(CK 现在挂在账号上) - cookie_ids_query = select(Account.id).where(cookie_holding_filter()) - invalid_ids = ( - db.query(Account.id) - .filter( - Account.id.in_(ids), - Account.id.notin_(cookie_ids_query), - ) - .all() - ) - if invalid_ids: - names = ( - db.query(Account.username) - .filter(Account.id.in_([i[0] for i in invalid_ids])) + # 只能分配当前 Cookie 已通过新鲜 CK 检测的账号。 + assignable_ids = { + int(account_id) + for (account_id,) in ( + db.query(Account.id) + .filter( + Account.id.in_(ids), + _assignable_account_filter(), + ) .all() ) + } + invalid_ids = [ + account_id for account_id in ids if account_id not in assignable_ids + ] + if invalid_ids: + names = db.query(Account.username).filter(Account.id.in_(invalid_ids)).all() name_list = ", ".join([n[0] for n in names[:5]]) suffix = "..." if len(invalid_ids) > 5 else "" raise HTTPException( status_code=400, - detail=f"以下账号尚未成功登录,无法分配:{name_list}{suffix}", + detail=f"以下账号尚未通过有效 CK 检测,无法分配:{name_list}{suffix}", ) # 先取出账号对象(批量时间线要逐个写事件,光有 count 不够)。 @@ -1176,9 +1178,9 @@ def assignments_summary( db: Session = Depends(get_db), current: User = Depends(require_permission("account:assign")), ): - """分配概览:每个客服分到了多少**可分配账号**(持 CK 且 CK 未失效)。 + """分配概览:每个客服分到了多少**可分配账号**(当前 Cookie 已通过新鲜 CK 检测)。 - 失效 CK 的账号必须先重登/修复,放进分配池只会让客服以为能跑任务, + 未检测、检测失败或旧结论的账号必须先重登/复检,放进分配池只会让客服以为能跑任务, 所以列表、全量分配与这里的统计统一用 `_assignable_account_filter()`。 """ results = ( diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 959cf96..7429b20 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -212,7 +212,7 @@ class AccountBulkSelection(BaseModel): assign_status: str = "" #: 只看某个客服名下的账号(与 assign_status 可叠加) assigned_user_id: int | None = None - #: 分配池口径:持 CK 且 CK 未失效(排除停用/归档) + #: 分配池口径:当前 Cookie 已有不早于它的 valid CK 检测(排除停用/归档) assignable_only: bool = False has_cookie: bool = False status: str = "" diff --git a/web/backend/services/login_service.py b/web/backend/services/login_service.py index 89d19b2..930401e 100644 --- a/web/backend/services/login_service.py +++ b/web/backend/services/login_service.py @@ -239,6 +239,62 @@ def _write_login_success( ) +def _persist_login_cookie_verification( + db: Session, + task: LoginTask, + account: AccountModel, + check_result: dict, + *, + batch_id: str, + mode: str, +) -> str: + """把新 Cookie 的检测结论落到账号。 + + 普通登录与重登共享这一入口。登录成功只证明登录流程拿到了 Cookie,不能 + 直接复用账号上一次的 CK 结论;必须让本次新 Cookie 形成 ``valid/invalid/error`` + 的新鲜判定,分配池才能据此放行。 + """ + detail = ( + check_result.get("detail") + if isinstance(check_result.get("detail"), dict) + else {} + ) + persist_probe_result( + db, + account, + { + "probe_id": f"login-verify:{batch_id}:{task.id}", + "identity": { + "uid": account.uid, + "username": account.username, + "nickname": detail.get("nickname") or "", + "nickname_source": "session", + }, + "session": check_result, + "elite": {}, + "eligibility": {}, + "roles": {}, + "gold": {}, + "goods": {}, + "errors": {}, + }, + source="login.verify", + record_event=False, + commit=False, + ) + prefix = "重新登录成功" if mode == "relogin" else "登录成功" + if check_result.get("status") == "valid": + message = f"{prefix},Cookie 有效" + else: + message = ( + f"{prefix},但 Cookie 有效性检测失败: " + f"{check_result.get('message') or '状态未知'}" + ) + task.message = message[:512] + task.attempt_message = task.message + return task.message + + class LoginBatchRunner: """批量登录执行器,在线程中运行,通过 ThreadPoolExecutor 并发登录多个账号。""" @@ -495,46 +551,10 @@ class LoginBatchRunner: ) elif result.success: message = result.message or "登录成功" - if self.mode == "relogin" and account is not None: - check_result = probe_session( - result.cookie, - checker=check_douyu_cookie, - ) - detail = ( - check_result.get("detail") - if isinstance(check_result.get("detail"), dict) - else {} - ) - persist_probe_result( - worker_db, - account, - { - "probe_id": f"relogin:{self.batch_id}:{task.id}", - "identity": { - "uid": account.uid, - "username": account.username, - "nickname": detail.get("nickname") or "", - "nickname_source": "session", - }, - "session": check_result, - "elite": {}, - "eligibility": {}, - "roles": {}, - "gold": {}, - "goods": {}, - "errors": {}, - }, - source="login.relogin_verify", - record_event=False, - commit=False, - ) - if check_result["status"] == "valid": - message = "重新登录成功,Cookie 有效" - else: - message = ( - "重新登录成功,但 Cookie 有效性检测失败: " - f"{check_result['message']}" - ) + check_result = probe_session( + result.cookie, + checker=check_douyu_cookie, + ) # 唯一替换旧 CK 的入口:登录成功后写回账号。 # # ⚠️ 必须传 **worker_db**(本线程的会话),不能传 self.db: @@ -557,27 +577,30 @@ class LoginBatchRunner: else EVENT_LOGIN_OK ), ) - if self.mode == "relogin": - if account is not None and account.ck_check_status == "valid": - self._push_log( - "success", - f"[{current}] {acc_info['username']} 重新登录成功,Cookie 已替换并验证有效", - ) - else: - detail = ( - account.ck_check_result.get("message") - if account is not None and account.ck_check_result - else "" - ) - self._push_log( - "warning", - f"[{current}] {acc_info['username']} 重新登录成功,但 Cookie 有效性检测失败: {detail}", - ) - else: + if account is not None: + _persist_login_cookie_verification( + worker_db, + task, + account, + check_result, + batch_id=self.batch_id, + mode=self.mode, + ) + if account is not None and account.ck_check_status == "valid": self._push_log( "success", f"[{current}] {acc_info['username']} {task.message}", ) + else: + detail = ( + account.ck_check_result.get("message") + if account is not None and account.ck_check_result + else "" + ) + self._push_log( + "warning", + f"[{current}] {acc_info['username']} {task.message or detail}", + ) else: if self.mode == "relogin": # 重登失败不动旧 CK 与成功状态,只记录这次尝试失败 diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index 99312ac..cb9fd6d 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -36,7 +36,7 @@ export interface AccountBulkSelection { assign_status?: string; /** 只看某个客服名下的账号 */ assigned_user_id?: number; - /** 分配池口径:持 CK 且 CK 未失效(排除停用/归档) */ + /** 分配池口径:当前 Cookie 已通过新鲜 CK 检测(排除停用/归档) */ assignable_only?: boolean; has_cookie?: boolean; status?: string; diff --git a/web/frontend/src/pages/AssignmentsPage.tsx b/web/frontend/src/pages/AssignmentsPage.tsx index 91f2d15..bf59fc1 100644 --- a/web/frontend/src/pages/AssignmentsPage.tsx +++ b/web/frontend/src/pages/AssignmentsPage.tsx @@ -80,8 +80,7 @@ export default function AssignmentsPage() { const params: Parameters[0] = { page: currentPage, page_size: pageSize, - // 分配池只收「有 CK 且 CK 未失效」的账号:失效号的下一步是重登/修复, - // 不是分配给客服(分过去也跑不了任务)。 + // 分配池只收当前 Cookie 已通过新鲜 CK 检测的账号。 assignable_only: true, include_sensitive: false, search: searchText.trim() || undefined, @@ -316,7 +315,7 @@ export default function AssignmentsPage() { - +