优化(登录任务): 日志实时写库并支持弹窗自动刷新
- 进行中任务的日志每 3 秒增量写库,不再等结束才有内容 - 弹窗打开期间每 3 秒自动刷新,显示任务进行中提示 - 缺少邮箱/邮箱密码时直接失败,不再白等两轮验证码 - 邮箱验证码等待时长支持 DOUYU_EMAIL_CODE_WAIT_SECONDS 配置 - 补充对应测试
This commit is contained in:
@@ -49,6 +49,12 @@ from .task_runtime import TaskLane, submit
|
||||
_LOG_CONTEXT = threading.local()
|
||||
_TASK_LOG_SINK_ID: int | None = None
|
||||
_TASK_LOG_SINK_LOCK = threading.Lock()
|
||||
# 进行中的任务日志放在模块字典里(而不是线程局部):页面要看「正在登录」的
|
||||
# 实时进度,必须由独立的刷新线程能读到登录线程写的内容。
|
||||
_TASK_LOGS: dict[int, list[dict[str, Any]]] = {}
|
||||
_TASK_LOGS_LOCK = threading.Lock()
|
||||
_TASK_LOG_FLUSHER: threading.Thread | None = None
|
||||
_TASK_LOG_FLUSH_SECONDS = 3.0
|
||||
# 单任务最多保留条数;超出后优先丢 DEBUG,避免把关键步骤挤掉。
|
||||
TASK_LOG_LIMIT = 300
|
||||
TASK_LOG_MESSAGE_LIMIT = 1200
|
||||
@@ -67,25 +73,64 @@ def _append_task_log(level: str, message: str, module: str = "") -> None:
|
||||
end = text.find("] ")
|
||||
if end > 0:
|
||||
text = text[end + 2 :].strip()
|
||||
logs = getattr(_LOG_CONTEXT, "logs", None)
|
||||
if logs is None:
|
||||
logs = []
|
||||
_LOG_CONTEXT.logs = logs
|
||||
logs.append(
|
||||
{
|
||||
"level": level,
|
||||
"message": text[:TASK_LOG_MESSAGE_LIMIT],
|
||||
"module": module,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
)
|
||||
if len(logs) > TASK_LOG_LIMIT:
|
||||
for index, item in enumerate(logs):
|
||||
if item.get("level") == "debug":
|
||||
del logs[index]
|
||||
break
|
||||
else:
|
||||
del logs[0]
|
||||
entry = {
|
||||
"level": level,
|
||||
"message": text[:TASK_LOG_MESSAGE_LIMIT],
|
||||
"module": module,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
with _TASK_LOGS_LOCK:
|
||||
logs = _TASK_LOGS.setdefault(task_id, [])
|
||||
logs.append(entry)
|
||||
if len(logs) > TASK_LOG_LIMIT:
|
||||
for index, item in enumerate(logs):
|
||||
if item.get("level") == "debug":
|
||||
del logs[index]
|
||||
break
|
||||
else:
|
||||
del logs[0]
|
||||
|
||||
|
||||
def _snapshot_task_logs(task_id: int) -> list[dict[str, Any]]:
|
||||
with _TASK_LOGS_LOCK:
|
||||
return list(_TASK_LOGS.get(task_id, ()))
|
||||
|
||||
|
||||
def _drop_task_logs(task_id: int) -> list[dict[str, Any]]:
|
||||
with _TASK_LOGS_LOCK:
|
||||
return _TASK_LOGS.pop(task_id, [])
|
||||
|
||||
|
||||
def _flush_active_task_logs() -> None:
|
||||
"""把进行中的任务日志增量写库,页面就能看到实时进度。"""
|
||||
with _TASK_LOGS_LOCK:
|
||||
task_ids = list(_TASK_LOGS)
|
||||
for task_id in task_ids:
|
||||
logs = _snapshot_task_logs(task_id)
|
||||
if logs:
|
||||
_persist_task_logs(task_id, logs)
|
||||
|
||||
|
||||
def _start_task_log_flusher() -> None:
|
||||
global _TASK_LOG_FLUSHER
|
||||
if _TASK_LOG_FLUSHER is not None and _TASK_LOG_FLUSHER.is_alive():
|
||||
return
|
||||
with _TASK_LOG_SINK_LOCK:
|
||||
if _TASK_LOG_FLUSHER is not None and _TASK_LOG_FLUSHER.is_alive():
|
||||
return
|
||||
|
||||
def loop() -> None:
|
||||
while True:
|
||||
time.sleep(_TASK_LOG_FLUSH_SECONDS)
|
||||
try:
|
||||
_flush_active_task_logs()
|
||||
except Exception: # noqa: BLE001 - 刷新线程必须存活
|
||||
logger.exception("刷新登录任务日志失败")
|
||||
|
||||
_TASK_LOG_FLUSHER = threading.Thread(
|
||||
target=loop, name="login-task-log-flusher", daemon=True
|
||||
)
|
||||
_TASK_LOG_FLUSHER.start()
|
||||
|
||||
|
||||
def _task_log_sink(message: Any) -> None:
|
||||
@@ -462,8 +507,9 @@ class LoginBatchRunner:
|
||||
self._counter_lock = threading.Lock()
|
||||
self._completed = 0
|
||||
# 逐账号日志走模块级 loguru sink(见文件头 _LOG_CONTEXT),
|
||||
# 这里只保证 sink 已挂上。
|
||||
# 这里保证 sink 与刷新线程都已就绪。
|
||||
_install_task_log_sink()
|
||||
_start_task_log_flusher()
|
||||
|
||||
# 共享代理获取器(无池,每次取新代理)
|
||||
self._proxy_runtime = build_proxy_runtime(
|
||||
@@ -578,7 +624,7 @@ class LoginBatchRunner:
|
||||
if not task:
|
||||
return
|
||||
_LOG_CONTEXT.task_id = int(task.id)
|
||||
_LOG_CONTEXT.logs = []
|
||||
_drop_task_logs(int(task.id))
|
||||
# CK、健康与重登状态都挂在账号上;登录记录只是一次尝试的历史。
|
||||
account = task.account
|
||||
|
||||
@@ -784,9 +830,8 @@ class LoginBatchRunner:
|
||||
worker_db.commit()
|
||||
|
||||
finally:
|
||||
logs = list(getattr(_LOG_CONTEXT, "logs", []) or [])
|
||||
_LOG_CONTEXT.task_id = 0
|
||||
_LOG_CONTEXT.logs = []
|
||||
logs = _drop_task_logs(task_id)
|
||||
# 先关会话释放行锁,再用独立短事务写日志;反过来会在异常路径上
|
||||
# 自己堵自己(同一行 UPDATE 等锁 50 秒)。
|
||||
worker_db.close()
|
||||
|
||||
@@ -580,20 +580,36 @@ export default function LoginTasksPage() {
|
||||
[tagAccountIds],
|
||||
);
|
||||
|
||||
const openTaskLogs = async (task: LoginTaskItem) => {
|
||||
const openTaskLogs = (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);
|
||||
}
|
||||
};
|
||||
|
||||
// 弹窗打开期间拉日志;任务还在跑就每 3 秒刷新,能看到实时进度。
|
||||
useEffect(() => {
|
||||
if (!logTask) return;
|
||||
let alive = true;
|
||||
const taskId = logTask.id;
|
||||
const running = ['pending', 'running'].includes(logTask.status);
|
||||
const load = async (silent: boolean) => {
|
||||
if (!silent) setLogsLoading(true);
|
||||
try {
|
||||
const data = await loginApi.taskLogs(taskId);
|
||||
if (alive) setLogItems(data.items || []);
|
||||
} catch (error) {
|
||||
if (alive && !silent) message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
if (alive && !silent) setLogsLoading(false);
|
||||
}
|
||||
};
|
||||
void load(false);
|
||||
const timer = running ? window.setInterval(() => void load(true), 3000) : undefined;
|
||||
return () => {
|
||||
alive = false;
|
||||
if (timer) window.clearInterval(timer);
|
||||
};
|
||||
}, [logTask]);
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 78 },
|
||||
{
|
||||
@@ -1193,13 +1209,20 @@ export default function LoginTasksPage() {
|
||||
</div>
|
||||
) : logItems.length === 0 ? (
|
||||
<Text type="secondary">
|
||||
暂无日志。逐账号日志在本次登录尝试结束后写入;旧的登录任务不会再补。
|
||||
{logTask && ['pending', 'running'].includes(logTask.status)
|
||||
? '该账号还没产生日志(可能仍在排队或刚开始),页面会每 3 秒自动刷新。'
|
||||
: '暂无日志。逐账号日志在登录过程中实时写入;部署前的旧任务不会补。'}
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
共 {logItems.length} 条,包含代理预检、极验、登录步骤和邮箱取码等完整过程。
|
||||
</Text>
|
||||
<Space size={8} wrap>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
共 {logItems.length} 条,包含代理预检、极验、登录步骤和邮箱取码等完整过程。
|
||||
</Text>
|
||||
{logTask && ['pending', 'running'].includes(logTask.status) ? (
|
||||
<Tag color="processing">任务进行中,每 3 秒自动刷新</Tag>
|
||||
) : null}
|
||||
</Space>
|
||||
<div style={{ maxHeight: '58vh', overflow: 'auto', display: 'grid', gap: 6, marginTop: 8 }}>
|
||||
{logItems.map((item, index) => (
|
||||
<div
|
||||
|
||||
Reference in New Issue
Block a user