fix(douyu): 替换 CK 是最后一步,只有登录成功才写回记录
上一版把可见性改成「记录里还有 CK」,账号不会再消失,但根因还在:批次启动 时就把复用的成功记录改成 pending(旧 CK 仍在),停止或失败后没人恢复状态, 记录一直显示成一次没完成的登录。 按「替换 CK 是最后一步」把两者拆开: - login_tasks 新增 attempt_status / attempt_message / attempt_batch_id / attempt_at,批次只写 attempt_*,status/cookie/message 只在登录成功时更新; - _begin_attempt 只登记尝试,_mark_attempt_failed 只记录失败(已有 CK 的记录 原样不动),_write_login_success 是唯一替换旧 CK 的入口; - 停止批次、代理不可用、登录异常、进程重启清理全部改为收敛 attempt_*, 因此停止一个批次不可能再让账号失去 CK; - 复用的记录改用「持有 CK 的记录」,不再创建第二条记录,失败记录在无 CK 时 才复用; - 登录任务列表/统计按 attempt_* 展示「这次登录怎么样了」,批次筛选同时匹配 attempt_batch_id;CK 操作页的重登状态也从 attempt_* 映射; - 迁移 20261001_0035 归一存量数据:持有 CK 的记录 status 统一为 success、 历史状态搬进 attempt_*,无 CK 且卡在 pending/running 的收敛为 failed。 新增测试:批次失败/停止不碰旧 CK、成功后替换 CK、列表展示尝试状态、 迁移存量数据归一。
This commit is contained in:
@@ -207,8 +207,8 @@ class TestCookieOperation:
|
||||
)
|
||||
|
||||
def test_relogin_failed_record_stays_visible_and_can_be_checked(self):
|
||||
self.owned_task.status = "relogin_failed"
|
||||
self.owned_task.message = "重新登录失败: 密码错误(旧 Cookie 已保留)"
|
||||
self.owned_task.attempt_status = "failed"
|
||||
self.owned_task.attempt_message = "重新登录失败: 密码错误(旧 Cookie 已保留)"
|
||||
self.session.commit()
|
||||
|
||||
result = list_cookie_operations(
|
||||
@@ -223,9 +223,13 @@ class TestCookieOperation:
|
||||
assert result["total"] == 1
|
||||
assert result["items"][0]["relogin_status"] == "relogin_failed"
|
||||
assert "旧 Cookie 已保留" in result["items"][0]["relogin_message"]
|
||||
# 失败的重登尝试不影响记录持有的 CK
|
||||
assert self.owned_task.cookie == "owned-secret"
|
||||
assert self.owned_task.status == "success"
|
||||
|
||||
def test_service_restart_cleans_orphan_relogin_tasks(self):
|
||||
self.owned_task.status = "relogin_running"
|
||||
self.owned_task.attempt_status = "running"
|
||||
self.owned_task.attempt_message = "正在重新登录,旧 Cookie 保留中"
|
||||
self.session.commit()
|
||||
|
||||
cleaned = cleanup_orphan_relogin_tasks(self.session)
|
||||
@@ -233,13 +237,17 @@ class TestCookieOperation:
|
||||
assert cleaned == 1
|
||||
self.session.refresh(self.owned_task)
|
||||
self.session.refresh(self.other_task)
|
||||
assert self.owned_task.status == "relogin_failed"
|
||||
assert "服务重启" in self.owned_task.message
|
||||
# 只收敛尝试状态,已有 CK 与成功状态原封不动
|
||||
assert self.owned_task.attempt_status == "failed"
|
||||
assert "服务重启" in self.owned_task.attempt_message
|
||||
assert self.owned_task.status == "success"
|
||||
assert self.owned_task.cookie == "owned-secret"
|
||||
assert self.other_task.attempt_status == ""
|
||||
assert self.other_task.status == "success"
|
||||
|
||||
def test_service_restart_cleans_orphan_login_tasks(self):
|
||||
"""普通登录批次遗留的 pending/running 必须收敛,且保留旧 CK。"""
|
||||
self.owned_task.status = "pending"
|
||||
"""普通登录批次遗留的在途尝试必须收敛,且保留旧 CK。"""
|
||||
self.owned_task.attempt_status = "pending"
|
||||
self.owned_task.cookie = "acf_uid=owned"
|
||||
self.session.commit()
|
||||
|
||||
@@ -248,11 +256,25 @@ class TestCookieOperation:
|
||||
assert cleaned == 1
|
||||
self.session.refresh(self.owned_task)
|
||||
self.session.refresh(self.other_task)
|
||||
assert self.owned_task.status == "failed"
|
||||
assert self.owned_task.attempt_status == "failed"
|
||||
assert self.owned_task.cookie == "acf_uid=owned"
|
||||
assert "服务重启" in self.owned_task.message
|
||||
assert self.owned_task.status == "success"
|
||||
assert "服务重启" in self.owned_task.attempt_message
|
||||
assert self.other_task.status == "success"
|
||||
|
||||
def test_service_restart_cleans_legacy_in_flight_status(self):
|
||||
"""升级前直接把状态写在 status 上的在途记录也要能收敛。"""
|
||||
self.owned_task.status = "relogin_running"
|
||||
self.owned_task.attempt_status = ""
|
||||
self.session.commit()
|
||||
|
||||
cleaned = cleanup_orphan_login_tasks(self.session)
|
||||
|
||||
assert cleaned == 1
|
||||
self.session.refresh(self.owned_task)
|
||||
assert self.owned_task.attempt_status == "failed"
|
||||
assert self.owned_task.cookie == "owned-secret"
|
||||
|
||||
def test_runner_copies_proxy_config_before_background_execution(self):
|
||||
proxy = ProxyConfig(
|
||||
enabled=True,
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""回归:替换 CK 必须是最后一步,只有登录成功才会写回记录。
|
||||
|
||||
事故背景:批次启动时会把复用的成功记录直接改成 pending(旧 CK 仍保留),
|
||||
批次被停止或失败后没有任何地方把它改回成功,账号于是从工作台消失。
|
||||
现在尝试状态独立存放在 attempt_*,status/cookie/message 只在登录成功时
|
||||
更新,所以停止、失败、进程重启都不可能破坏账号已有的 CK。
|
||||
"""
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
import web.backend.database as database_module
|
||||
from web.backend.database import Base
|
||||
from web.backend.models import Account, LoginTask, User
|
||||
from web.backend.routers.login import list_tasks
|
||||
from web.backend.services import login_service
|
||||
|
||||
|
||||
class _FakeLogin:
|
||||
"""替身登录器:不发网络请求,结果由类属性控制。"""
|
||||
|
||||
success = True
|
||||
cookie = "new-cookie"
|
||||
message = "登录成功"
|
||||
code = None
|
||||
calls = 0
|
||||
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def login(self):
|
||||
type(self).calls += 1
|
||||
return SimpleNamespace(
|
||||
success=type(self).success,
|
||||
cookie=type(self).cookie if type(self).success else "",
|
||||
message=type(self).message,
|
||||
code=type(self).code,
|
||||
)
|
||||
|
||||
def check_account(self):
|
||||
return self.login()
|
||||
|
||||
|
||||
class TestLoginAttemptIsolation:
|
||||
def setup_method(self):
|
||||
self.tmpdir = tempfile.TemporaryDirectory()
|
||||
url = f"sqlite:///{Path(self.tmpdir.name) / 'attempt.db'}"
|
||||
self.engine = create_engine(url, connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(self.engine)
|
||||
# 批次执行器在后台线程里用 SessionLocal,测试期间指向同一个文件库。
|
||||
database_module.SessionLocal.configure(bind=self.engine)
|
||||
self.session = sessionmaker(bind=self.engine)()
|
||||
|
||||
self.user = User(username="admin", password_hash="hash", role="super_admin")
|
||||
self.session.add(self.user)
|
||||
self.session.flush()
|
||||
self.account = Account(
|
||||
username="远行者103",
|
||||
password="password",
|
||||
email="yuanxingzhe@example.com",
|
||||
email_password="mail-password",
|
||||
)
|
||||
self.session.add(self.account)
|
||||
self.session.flush()
|
||||
self.task = LoginTask(
|
||||
batch_id="old-batch",
|
||||
account_id=self.account.id,
|
||||
created_by=self.user.id,
|
||||
status="success",
|
||||
cookie="old-cookie",
|
||||
message="登录成功",
|
||||
)
|
||||
self.session.add(self.task)
|
||||
self.session.commit()
|
||||
self.task_id = self.task.id
|
||||
|
||||
_FakeLogin.success = True
|
||||
_FakeLogin.cookie = "new-cookie"
|
||||
_FakeLogin.message = "登录成功"
|
||||
_FakeLogin.calls = 0
|
||||
|
||||
def teardown_method(self):
|
||||
database_module.SessionLocal.configure(bind=database_module.engine)
|
||||
self.session.close()
|
||||
Base.metadata.drop_all(self.engine)
|
||||
self.engine.dispose()
|
||||
self.tmpdir.cleanup()
|
||||
|
||||
def _run_batch(self, monkeypatch, *, mode="login", account_ids=None, stop=False):
|
||||
monkeypatch.setattr(login_service, "DouyuLogin", _FakeLogin)
|
||||
# 批次结束时 runner 会关掉自己的会话,因此单独给它一个。
|
||||
runner_db = sessionmaker(bind=self.engine)()
|
||||
runner = login_service.LoginBatchRunner(
|
||||
db=runner_db,
|
||||
account_ids=account_ids if account_ids is not None else [self.account.id],
|
||||
created_by=self.user.id,
|
||||
creator_permissions=["login:view_all"],
|
||||
proxy_config=None,
|
||||
concurrency=1,
|
||||
mode=mode,
|
||||
)
|
||||
if stop:
|
||||
runner.stop()
|
||||
runner.run()
|
||||
return runner
|
||||
|
||||
def _fresh(self, task_id: int) -> LoginTask:
|
||||
session = sessionmaker(bind=self.engine)()
|
||||
try:
|
||||
return session.query(LoginTask).filter(LoginTask.id == task_id).one()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
def _fresh_user(self, session) -> User:
|
||||
return session.query(User).filter(User.id == self.user.id).one()
|
||||
|
||||
def test_failed_attempt_keeps_existing_cookie(self, monkeypatch):
|
||||
_FakeLogin.success = False
|
||||
_FakeLogin.message = "账号密码错误"
|
||||
|
||||
self._run_batch(monkeypatch)
|
||||
|
||||
task = self._fresh(self.task_id)
|
||||
# 记录持有 CK 的字段完全没被碰过
|
||||
assert task.status == "success"
|
||||
assert task.cookie == "old-cookie"
|
||||
assert task.message == "登录成功"
|
||||
assert task.batch_id == "old-batch"
|
||||
# 失败只体现在尝试字段上
|
||||
assert task.attempt_status == "failed"
|
||||
assert task.attempt_message == "账号密码错误"
|
||||
assert task.attempt_at is not None
|
||||
|
||||
def test_failed_attempt_reuses_the_cookie_row(self, monkeypatch):
|
||||
_FakeLogin.success = False
|
||||
_FakeLogin.message = "账号密码错误"
|
||||
|
||||
self._run_batch(monkeypatch)
|
||||
|
||||
session = sessionmaker(bind=self.engine)()
|
||||
try:
|
||||
rows = (
|
||||
session.query(LoginTask)
|
||||
.filter(LoginTask.account_id == self.account.id)
|
||||
.all()
|
||||
)
|
||||
finally:
|
||||
session.close()
|
||||
assert [row.id for row in rows] == [self.task_id]
|
||||
|
||||
def test_successful_attempt_replaces_cookie(self, monkeypatch):
|
||||
self._run_batch(monkeypatch)
|
||||
|
||||
task = self._fresh(self.task_id)
|
||||
assert task.status == "success"
|
||||
assert task.cookie == "new-cookie"
|
||||
assert task.message == "登录成功"
|
||||
assert task.attempt_status == "success"
|
||||
assert task.attempt_at is not None
|
||||
assert task.batch_id != "old-batch"
|
||||
|
||||
def test_stopped_batch_keeps_existing_cookie(self, monkeypatch):
|
||||
self._run_batch(monkeypatch, stop=True)
|
||||
|
||||
task = self._fresh(self.task_id)
|
||||
assert _FakeLogin.calls == 0
|
||||
assert task.cookie == "old-cookie"
|
||||
assert task.status == "success"
|
||||
assert task.attempt_status == "failed"
|
||||
assert "旧 Cookie 已保留" in task.attempt_message
|
||||
|
||||
def test_list_tasks_reports_attempt_state_without_losing_ck_row(self, monkeypatch):
|
||||
_FakeLogin.success = False
|
||||
_FakeLogin.message = "账号密码错误"
|
||||
|
||||
runner = self._run_batch(monkeypatch)
|
||||
|
||||
read_db = sessionmaker(bind=self.engine)()
|
||||
try:
|
||||
rows = list_tasks(
|
||||
batch_id=runner.batch_id, db=read_db, current=self._fresh_user(read_db)
|
||||
)
|
||||
finally:
|
||||
read_db.close()
|
||||
assert len(rows) == 1
|
||||
row = rows[0]
|
||||
# 页面看到的是「这次尝试怎么样了」,而记录仍然持有 CK
|
||||
assert row.status == "failed"
|
||||
assert row.message == "账号密码错误"
|
||||
assert row.batch_id == runner.batch_id
|
||||
assert self._fresh(self.task_id).cookie == "old-cookie"
|
||||
|
||||
def test_account_without_cookie_still_reports_failure(self, monkeypatch):
|
||||
"""首次登录失败的账号没有 CK 需要保护,保持原来的失败语义。"""
|
||||
fresh_account = Account(
|
||||
username="no-cookie",
|
||||
password="password",
|
||||
email="nocookie@example.com",
|
||||
email_password="mail-password",
|
||||
)
|
||||
self.session.add(fresh_account)
|
||||
self.session.commit()
|
||||
_FakeLogin.success = False
|
||||
_FakeLogin.message = "账号密码错误"
|
||||
|
||||
self._run_batch(monkeypatch, account_ids=[fresh_account.id])
|
||||
|
||||
session = sessionmaker(bind=self.engine)()
|
||||
try:
|
||||
task = (
|
||||
session.query(LoginTask)
|
||||
.filter(LoginTask.account_id == fresh_account.id)
|
||||
.one()
|
||||
)
|
||||
assert task.status == "failed"
|
||||
assert task.message == "账号密码错误"
|
||||
assert task.attempt_status == "failed"
|
||||
assert task.cookie == ""
|
||||
finally:
|
||||
session.close()
|
||||
@@ -0,0 +1,152 @@
|
||||
"""迁移 20261001_0035 的存量数据归一验证。
|
||||
|
||||
线上升级时要保证:
|
||||
- 持有 CK 的记录 status 归一到 success,历史批次状态搬进 attempt_*;
|
||||
- 没有 CK 且卡在 pending/running 的记录收敛为 failed;
|
||||
- 任何情况下都不丢 CK。
|
||||
"""
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _migration_config(url: str) -> Config:
|
||||
config = Config(str(PROJECT_ROOT / "alembic.ini"))
|
||||
config.set_main_option(
|
||||
"script_location", str(PROJECT_ROOT / "web" / "backend" / "migrations")
|
||||
)
|
||||
config.set_main_option("sqlalchemy.url", url)
|
||||
return config
|
||||
|
||||
|
||||
def _insert_task(conn, *, status: str, cookie: str, message: str = "") -> None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO login_tasks
|
||||
(batch_id, account_id, status, cookie, message, created_by,
|
||||
created_at, finished_at)
|
||||
VALUES
|
||||
('batch-1', 1, :status, :cookie, :message, 1,
|
||||
'2026-09-30 00:00:00', '2026-09-30 01:00:00')
|
||||
"""
|
||||
),
|
||||
{"status": status, "cookie": cookie, "message": message},
|
||||
)
|
||||
|
||||
|
||||
class TestLoginAttemptMigration:
|
||||
def setup_method(self):
|
||||
import web.backend.database as database_module
|
||||
|
||||
self.database_module = database_module
|
||||
self.original_url = database_module.DATABASE_URL
|
||||
self.tmpdir = tempfile.TemporaryDirectory()
|
||||
self.url = f"sqlite:///{Path(self.tmpdir.name) / 'upgrade.db'}"
|
||||
# env.py 用模块级 DATABASE_URL 覆盖配置里的连接串。
|
||||
database_module.DATABASE_URL = self.url
|
||||
self.config = _migration_config(self.url)
|
||||
command.upgrade(self.config, "20260901_0034")
|
||||
|
||||
self.engine = create_engine(self.url)
|
||||
with self.engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO accounts
|
||||
(id, username, password, email, email_password,
|
||||
email_imap_server, email_imap_port, email_imap_ssl,
|
||||
tag, remark, uid, nickname, created_at, updated_at)
|
||||
VALUES
|
||||
(1, '远行者103', 'p', 'e@example.com', 'm',
|
||||
'', 993, 1, '', '', '', '', '2026-09-30 00:00:00',
|
||||
'2026-09-30 00:00:00')
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO users (id, username, password_hash, role, is_active)
|
||||
VALUES (1, 'admin', 'hash', 'super_admin', 1)
|
||||
"""
|
||||
)
|
||||
)
|
||||
_insert_task(conn, status="success", cookie="ck-success")
|
||||
_insert_task(
|
||||
conn,
|
||||
status="relogin_failed",
|
||||
cookie="ck-relogin",
|
||||
message="重新登录失败: 密码错误(旧 Cookie 已保留)",
|
||||
)
|
||||
_insert_task(conn, status="pending", cookie="ck-pending")
|
||||
_insert_task(conn, status="pending", cookie="")
|
||||
_insert_task(conn, status="running", cookie="")
|
||||
_insert_task(conn, status="failed", cookie="ck-failed", message="登录失败")
|
||||
|
||||
def teardown_method(self):
|
||||
self.database_module.DATABASE_URL = self.original_url
|
||||
self.engine.dispose()
|
||||
self.tmpdir.cleanup()
|
||||
|
||||
def _rows(self) -> list[dict]:
|
||||
with self.engine.connect() as conn:
|
||||
rows = conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT status, cookie, message, attempt_status,
|
||||
attempt_message, attempt_batch_id, attempt_at
|
||||
FROM login_tasks
|
||||
ORDER BY id
|
||||
"""
|
||||
)
|
||||
).mappings()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def test_upgrade_normalizes_existing_rows(self):
|
||||
command.upgrade(self.config, "head")
|
||||
|
||||
rows = self._rows()
|
||||
(
|
||||
success,
|
||||
relogin_failed,
|
||||
pending_with_ck,
|
||||
pending_without_ck,
|
||||
running_without_ck,
|
||||
failed_with_ck,
|
||||
) = rows
|
||||
|
||||
# 已经成功的记录:status 不变,也没有历史尝试需要搬迁
|
||||
assert success["status"] == "success"
|
||||
assert success["cookie"] == "ck-success"
|
||||
assert success["attempt_status"] in (None, "")
|
||||
|
||||
# 重登失败:CK 保留,status 归一为 success,失败信息进 attempt_*
|
||||
assert relogin_failed["cookie"] == "ck-relogin"
|
||||
assert relogin_failed["status"] == "success"
|
||||
assert relogin_failed["attempt_status"] == "failed"
|
||||
assert "旧 Cookie 已保留" in relogin_failed["attempt_message"]
|
||||
assert relogin_failed["attempt_batch_id"] == "batch-1"
|
||||
|
||||
# 卡在 pending 但持有 CK:同样归一为 success + 中断说明
|
||||
assert pending_with_ck["cookie"] == "ck-pending"
|
||||
assert pending_with_ck["status"] == "success"
|
||||
assert pending_with_ck["attempt_status"] == "failed"
|
||||
assert "旧 Cookie 已保留" in pending_with_ck["attempt_message"]
|
||||
|
||||
# 没有 CK 的在途记录:收敛为失败,不再永久排队
|
||||
for row in (pending_without_ck, running_without_ck):
|
||||
assert row["status"] == "failed"
|
||||
assert row["attempt_status"] == "failed"
|
||||
assert "服务重启" in row["message"]
|
||||
|
||||
# 复用记录上的旧 CK 不能被清掉
|
||||
assert failed_with_ck["status"] == "success"
|
||||
assert failed_with_ck["cookie"] == "ck-failed"
|
||||
assert failed_with_ck["attempt_status"] == "failed"
|
||||
@@ -22,7 +22,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20260901_0034"
|
||||
HEAD_REVISION = "20261001_0035"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
|
||||
Reference in New Issue
Block a user