优化(登录任务): 移除批量实时日志,增加账号独立日志
- 登录任务移除底部实时日志面板和 WebSocket 订阅 - 登录执行器按任务收集日志并在结束时持久化 - 新增登录任务日志接口和单账号日志弹窗 - 迁移 0134 增加 login_tasks.logs - 修复无 WebSocket 时开始按钮状态未复位
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
"""登录任务逐账号日志收集测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from web.backend.services.login_service import LoginBatchRunner
|
||||
|
||||
|
||||
def test_runner_collects_logs_for_current_task_only():
|
||||
runner = object.__new__(LoginBatchRunner)
|
||||
runner.batch_id = "batch-log-test"
|
||||
runner.log_queue = None
|
||||
runner.loop = None
|
||||
runner.log_sink = None
|
||||
runner._log_context = threading.local()
|
||||
|
||||
runner._log_context.task_id = 7
|
||||
runner._log_context.logs = []
|
||||
runner._push_log("info", "account log")
|
||||
runner._push_log("error", "account failed")
|
||||
|
||||
assert [item["message"] for item in runner._log_context.logs] == [
|
||||
"account log",
|
||||
"account failed",
|
||||
]
|
||||
assert runner._log_context.logs[1]["level"] == "error"
|
||||
|
||||
runner._log_context.task_id = 0
|
||||
runner._push_log("info", "batch log")
|
||||
assert [item["message"] for item in runner._log_context.logs] == [
|
||||
"account log",
|
||||
"account failed",
|
||||
]
|
||||
@@ -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_0133"
|
||||
HEAD_REVISION = "20261125_0134"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
@@ -76,6 +76,9 @@ _ACCOUNT_PLATFORM_COLUMNS = {
|
||||
}
|
||||
|
||||
_LATER_ORM_COLUMNS = {
|
||||
"login_tasks": {
|
||||
"logs": "JSON NULL",
|
||||
},
|
||||
"platform_fulfillment_tasks": {
|
||||
"sale_mode": "VARCHAR(16) NOT NULL DEFAULT 'unknown'",
|
||||
"campaign_key": "VARCHAR(128) NOT NULL DEFAULT ''",
|
||||
|
||||
@@ -533,6 +533,10 @@
|
||||
"20261125_0133_binding_failed_hold.py": {
|
||||
"revision": "20261125_0133",
|
||||
"sha256": "d282e42776fd9501b5293c2a116ad1467df0ddb1847d950b477086e3ae5440a7"
|
||||
},
|
||||
"20261125_0134_login_task_logs.py": {
|
||||
"revision": "20261125_0134",
|
||||
"sha256": "c21a4833874676b08a9156e20cfb89c2786aece628d998e8a1bf87a8d0b3cd4b"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""保存每个登录任务的逐账号日志。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261125_0134"
|
||||
down_revision: str | None = "20261125_0133"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
TABLE = "login_tasks"
|
||||
|
||||
|
||||
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("logs"):
|
||||
op.add_column(TABLE, sa.Column("logs", sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _column_exists("logs"):
|
||||
op.drop_column(TABLE, "logs")
|
||||
@@ -397,6 +397,8 @@ class LoginTask(Base):
|
||||
relogin_failure_kind: Mapped[str] = mapped_column(
|
||||
String(16), default="", server_default=""
|
||||
)
|
||||
# 本次登录尝试的逐账号日志;由 LoginBatchRunner 在任务结束时写入。
|
||||
logs: Mapped[list | None] = mapped_column(JSON, nullable=True)
|
||||
|
||||
account: Mapped[Account] = relationship("Account", back_populates="login_tasks")
|
||||
|
||||
|
||||
@@ -397,6 +397,27 @@ def list_tasks(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}/logs")
|
||||
def get_task_logs(
|
||||
task_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(get_current_user),
|
||||
):
|
||||
"""读取单个账号本次登录尝试的日志。"""
|
||||
task = (
|
||||
_visible_tasks_query(db, current, None)
|
||||
.filter(LoginTask.id == task_id)
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="登录任务不存在")
|
||||
return {
|
||||
"task_id": int(task.id),
|
||||
"account_id": int(task.account_id),
|
||||
"items": task.logs or [],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/tasks/filters")
|
||||
def task_filter_options(
|
||||
db: Session = Depends(get_db),
|
||||
|
||||
@@ -368,6 +368,8 @@ class LoginBatchRunner:
|
||||
self._stop = threading.Event()
|
||||
self._counter_lock = threading.Lock()
|
||||
self._completed = 0
|
||||
# 每个登录线程独立收集当前账号日志;批次级日志不写入账号任务。
|
||||
self._log_context = threading.local()
|
||||
|
||||
# 共享代理获取器(无池,每次取新代理)
|
||||
self._proxy_runtime = build_proxy_runtime(
|
||||
@@ -432,6 +434,20 @@ class LoginBatchRunner:
|
||||
worker_db.close()
|
||||
|
||||
def _push_log(self, level: str, message: str):
|
||||
if message:
|
||||
task_id = int(getattr(self._log_context, "task_id", 0) or 0)
|
||||
if task_id:
|
||||
logs = getattr(self._log_context, "logs", None)
|
||||
if logs is None:
|
||||
logs = []
|
||||
self._log_context.logs = logs
|
||||
logs.append(
|
||||
{
|
||||
"level": level,
|
||||
"message": message,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
)
|
||||
# 即使没有页面实时日志,也要保留批次进度到 app.log,便于排查卡点。
|
||||
if message:
|
||||
log_level = (
|
||||
@@ -475,10 +491,13 @@ class LoginBatchRunner:
|
||||
return
|
||||
|
||||
worker_db = WorkerSessionLocal()
|
||||
task = None
|
||||
try:
|
||||
task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first()
|
||||
if not task:
|
||||
return
|
||||
self._log_context.task_id = int(task.id)
|
||||
self._log_context.logs = []
|
||||
# CK、健康与重登状态都挂在账号上;登录记录只是一次尝试的历史。
|
||||
account = task.account
|
||||
|
||||
@@ -684,6 +703,16 @@ class LoginBatchRunner:
|
||||
worker_db.commit()
|
||||
|
||||
finally:
|
||||
logs = list(getattr(self._log_context, "logs", []) or [])
|
||||
if task is not None and logs:
|
||||
try:
|
||||
task.logs = logs[-300:]
|
||||
worker_db.commit()
|
||||
except Exception: # noqa: BLE001 - 日志落库失败不能掩盖登录结果
|
||||
worker_db.rollback()
|
||||
logger.exception("保存登录账号日志失败: task_id={}", task_id)
|
||||
self._log_context.task_id = 0
|
||||
self._log_context.logs = []
|
||||
worker_db.close()
|
||||
|
||||
def run(self):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import api from './client';
|
||||
import type {
|
||||
BatchLoginResult, LoginTaskFilterOptions, LoginTaskItem, MessageDeletedResponse,
|
||||
MessageResponse, TaskSummary,
|
||||
BatchLoginResult, LoginTaskFilterOptions, LoginTaskItem, LoginTaskLogItem,
|
||||
MessageDeletedResponse, MessageResponse, TaskSummary,
|
||||
} from './types';
|
||||
|
||||
interface CreateBatchParams {
|
||||
@@ -52,6 +52,12 @@ export const loginApi = {
|
||||
api.get<TaskPage, TaskPage>('/login/tasks', { params: { ...params, ...filterParams(params) } }),
|
||||
taskFilterOptions: () =>
|
||||
api.get<LoginTaskFilterOptions, LoginTaskFilterOptions>('/login/tasks/filters'),
|
||||
taskLogs: (taskId: number) =>
|
||||
api.get<{ task_id: number; account_id: number; items: LoginTaskLogItem[] }, {
|
||||
task_id: number;
|
||||
account_id: number;
|
||||
items: LoginTaskLogItem[];
|
||||
}>(`/login/tasks/${taskId}/logs`),
|
||||
tasksSummary: (params: LoginTaskFilters = {}) =>
|
||||
api.get<TaskSummary, TaskSummary>('/login/tasks/summary', { params: filterParams(params) }),
|
||||
/**
|
||||
|
||||
@@ -474,6 +474,12 @@ export interface SupportUserItem {
|
||||
|
||||
// ==================== Login Task ====================
|
||||
|
||||
export interface LoginTaskLogItem {
|
||||
level: string;
|
||||
message: string;
|
||||
at?: string | null;
|
||||
}
|
||||
|
||||
export interface LoginTaskItem {
|
||||
id: number;
|
||||
batch_id: string;
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
import { useEffect, useState, useMemo, useCallback, useRef } from 'react';
|
||||
import {
|
||||
Table, Button, Select, Tag, Space, Input, InputNumber, Tooltip, Popconfirm, theme, Modal, Form, Dropdown, Typography,
|
||||
Table, Button, Select, Tag, Space, Input, InputNumber, Tooltip, Popconfirm, theme, Modal, Form, Dropdown, Typography, Spin,
|
||||
} from 'antd';
|
||||
import { message } from '../utils/antdMessage';
|
||||
import {
|
||||
PlayCircleOutlined, StopOutlined, FilterOutlined, ReloadOutlined, DeleteOutlined,
|
||||
SettingOutlined, SafetyCertificateOutlined, DownloadOutlined, ClearOutlined,
|
||||
SettingOutlined, SafetyCertificateOutlined, DownloadOutlined, ClearOutlined, FileTextOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { accountApi, loginApi, type AccountItem, type LoginTaskItem, type TaskSummary } from '../api/modules';
|
||||
import { accountApi, loginApi, type AccountItem, type LoginTaskItem, type LoginTaskLogItem, type TaskSummary } from '../api/modules';
|
||||
import type { LoginTaskFilters } from '../api/login';
|
||||
import RealtimeLogPanel from '../components/RealtimeLogPanel';
|
||||
import { usePermissions } from '../hooks/usePermissions';
|
||||
import { useWebSocketLogs } from '../hooks/useWebSocketLogs';
|
||||
import { formatTime } from '../utils/time';
|
||||
import { getErrorMessage } from '../utils/error';
|
||||
|
||||
@@ -142,6 +140,9 @@ export default function LoginTasksPage() {
|
||||
useEffect(() => { localStorage.setItem('login_max_login_retries', String(maxLoginRetries)); }, [maxLoginRetries]);
|
||||
useEffect(() => { localStorage.setItem('login_api_strategy', apiStrategy); }, [apiStrategy]);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
||||
const [logTask, setLogTask] = useState<LoginTaskItem | null>(null);
|
||||
const [logItems, setLogItems] = useState<LoginTaskLogItem[]>([]);
|
||||
const [logsLoading, setLogsLoading] = useState(false);
|
||||
const [selectedAllMatching, setSelectedAllMatching] = useState(false);
|
||||
// 任务列表分页:库里上万条,单页装不下;total 同时用于「全选所有结果」。
|
||||
const [taskPage, setTaskPage] = useState(1);
|
||||
@@ -162,7 +163,6 @@ export default function LoginTasksPage() {
|
||||
// 用它算「成功/失败」会和「共 N 个任务」对不上(曾显示「共 8508,成功 48」)。
|
||||
const [taskSummary, setTaskSummary] = useState<TaskSummary | null>(null);
|
||||
useEffect(() => { localStorage.setItem('login_task_page_size', String(taskPageSize)); }, [taskPageSize]);
|
||||
const { logs, connected: wsConnected, connect: connectLogs } = useWebSocketLogs();
|
||||
const { can } = usePermissions();
|
||||
|
||||
const { token } = theme.useToken();
|
||||
@@ -332,19 +332,6 @@ export default function LoginTasksPage() {
|
||||
);
|
||||
const effectiveBatchId = batchId || activeBatchIdFromTasks;
|
||||
|
||||
// 活跃批次存在但未订阅时自动重连实时日志(配合后端 WS 仅在批次结束后清理注册表)。
|
||||
const wsSubscribedBatchRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!effectiveBatchId || wsConnected) return;
|
||||
if (wsSubscribedBatchRef.current === effectiveBatchId) return;
|
||||
wsSubscribedBatchRef.current = effectiveBatchId;
|
||||
connectLogs(`/api/login/ws/login/${effectiveBatchId}`, {
|
||||
onClose: () => { setBatchId(null); setStarting(false); },
|
||||
onResult: () => { setBatchId(null); setStarting(false); },
|
||||
onError: () => { setBatchId(null); setStarting(false); },
|
||||
});
|
||||
}, [effectiveBatchId, wsConnected, connectLogs]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadTags();
|
||||
void loadTaskFilterOptions();
|
||||
@@ -378,10 +365,10 @@ export default function LoginTasksPage() {
|
||||
}, [accountSearch, loadAccountsPage]);
|
||||
|
||||
useEffect(() => {
|
||||
const intervalMs = hasActiveTasks || wsConnected || starting || batchId ? 3000 : 15000;
|
||||
const intervalMs = hasActiveTasks || starting || batchId ? 3000 : 15000;
|
||||
const timer = setInterval(loadTasks, intervalMs);
|
||||
return () => clearInterval(timer);
|
||||
}, [batchId, hasActiveTasks, loadTasks, starting, wsConnected]);
|
||||
}, [batchId, hasActiveTasks, loadTasks, starting]);
|
||||
|
||||
// 共享的批量任务启动逻辑
|
||||
const startBatch = async (accountIds: number[], mode: BatchMode = 'login') => {
|
||||
@@ -407,18 +394,11 @@ export default function LoginTasksPage() {
|
||||
mode,
|
||||
});
|
||||
setBatchId(result.batch_id);
|
||||
wsSubscribedBatchRef.current = result.batch_id;
|
||||
message.success(`已创建${mode === 'check' ? '检测' : '登录'}任务,共 ${result.count} 个账号`);
|
||||
|
||||
connectLogs(`/api/login/ws/login/${result.batch_id}`, {
|
||||
onClose: () => { setBatchId(null); setStarting(false); },
|
||||
onResult: () => { setBatchId(null); setStarting(false); },
|
||||
onError: () => { setBatchId(null); setStarting(false); },
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
message.error(getErrorMessage(e));
|
||||
setStarting(false);
|
||||
} finally {
|
||||
setStarting(false);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
@@ -600,6 +580,20 @@ export default function LoginTasksPage() {
|
||||
[tagAccountIds],
|
||||
);
|
||||
|
||||
const openTaskLogs = async (task: LoginTaskItem) => {
|
||||
setLogTask(task);
|
||||
setLogItems([]);
|
||||
setLogsLoading(true);
|
||||
try {
|
||||
const data = await loginApi.taskLogs(task.id);
|
||||
setLogItems(data.items || []);
|
||||
} catch (error) {
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setLogsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{ title: '登录账号', dataIndex: 'account_username' },
|
||||
@@ -656,10 +650,18 @@ export default function LoginTasksPage() {
|
||||
{ title: '时间', dataIndex: 'created_at', width: 180, render: (val: string) => formatTime(val) },
|
||||
{
|
||||
title: '操作',
|
||||
width: 120,
|
||||
width: 190,
|
||||
render: (_: unknown, record: LoginTaskItem) => (
|
||||
<Space size={4}>
|
||||
{['failed', 'error'].includes(record.status) && !wsConnected && (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<FileTextOutlined />}
|
||||
onClick={() => void openTaskLogs(record)}
|
||||
>
|
||||
日志
|
||||
</Button>
|
||||
{['failed', 'error'].includes(record.status) && (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
@@ -981,7 +983,7 @@ export default function LoginTasksPage() {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{!wsConnected && failedCount > 0 && (
|
||||
{failedCount > 0 && (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
@@ -1048,15 +1050,6 @@ export default function LoginTasksPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 实时日志 - 底部可折叠 */}
|
||||
<RealtimeLogPanel
|
||||
logs={logs}
|
||||
connected={wsConnected}
|
||||
collapsible
|
||||
spinWhenEmpty
|
||||
style={{ marginTop: 4 }}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
title="登录设置"
|
||||
open={settingsOpen}
|
||||
@@ -1143,6 +1136,43 @@ export default function LoginTasksPage() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={logTask ? `登录日志 · ${logTask.account_username}` : '登录日志'}
|
||||
open={Boolean(logTask)}
|
||||
footer={null}
|
||||
width={760}
|
||||
onCancel={() => setLogTask(null)}
|
||||
>
|
||||
{logsLoading ? (
|
||||
<div style={{ minHeight: 120, display: 'grid', placeItems: 'center' }}>
|
||||
<Spin />
|
||||
</div>
|
||||
) : logItems.length === 0 ? (
|
||||
<Text type="secondary">暂无日志;任务完成后会写入本次登录尝试的日志。</Text>
|
||||
) : (
|
||||
<div style={{ maxHeight: '62vh', overflow: 'auto', display: 'grid', gap: 8 }}>
|
||||
{logItems.map((item, index) => (
|
||||
<div
|
||||
key={`${item.at || ''}-${index}`}
|
||||
style={{
|
||||
padding: '8px 10px',
|
||||
border: `1px solid ${token.colorBorderSecondary}`,
|
||||
borderRadius: 6,
|
||||
}}
|
||||
>
|
||||
<Space size={6} style={{ marginBottom: 4 }}>
|
||||
<Tag color={item.level === 'error' ? 'red' : item.level === 'warning' ? 'orange' : item.level === 'success' ? 'green' : 'blue'}>
|
||||
{item.level || 'info'}
|
||||
</Tag>
|
||||
{item.at ? <Text type="secondary" style={{ fontSize: 12 }}>{formatTime(item.at)}</Text> : null}
|
||||
</Space>
|
||||
<div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{item.message}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user