fix(frontend): 优化 task log 前端交互体验
- 简化虚拟滚动实现,移除 @tanstack/vue-virtual 依赖 - 添加分页组件,支持翻页查看历史任务 - 添加 SSE 指数退避重试机制(最多 3 次) - 更新 API 接口支持分页参数 - 添加重试状态指示器 背景:前端存在虚拟滚动与 SSE 不兼容、缺少分页、连接断开无重试等问题 关联 commit:fix/logs 分支
This commit is contained in:
@@ -24,10 +24,20 @@ export interface TaskLogLine {
|
|||||||
export interface TaskLogListParams {
|
export interface TaskLogListParams {
|
||||||
source?: string
|
source?: string
|
||||||
businessLineId?: number
|
businessLineId?: number
|
||||||
|
page?: number
|
||||||
|
pageSize?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskLogListResult {
|
||||||
|
items: TaskLogSummary[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
page_size: number
|
||||||
|
total_pages: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export const taskLogApi = {
|
export const taskLogApi = {
|
||||||
async list(params: TaskLogListParams = {}): Promise<TaskLogSummary[]> {
|
async list(params: TaskLogListParams = {}): Promise<TaskLogListResult> {
|
||||||
const query = new URLSearchParams()
|
const query = new URLSearchParams()
|
||||||
if (params.source && params.source !== 'all') {
|
if (params.source && params.source !== 'all') {
|
||||||
query.set('source', params.source)
|
query.set('source', params.source)
|
||||||
@@ -35,9 +45,21 @@ export const taskLogApi = {
|
|||||||
if (params.businessLineId) {
|
if (params.businessLineId) {
|
||||||
query.set('business_line_id', String(params.businessLineId))
|
query.set('business_line_id', String(params.businessLineId))
|
||||||
}
|
}
|
||||||
|
if (params.page) {
|
||||||
|
query.set('page', String(params.page))
|
||||||
|
}
|
||||||
|
if (params.pageSize) {
|
||||||
|
query.set('page_size', String(params.pageSize))
|
||||||
|
}
|
||||||
const suffix = query.toString() ? `?${query.toString()}` : ''
|
const suffix = query.toString() ? `?${query.toString()}` : ''
|
||||||
const data = await authRequest(`/auth/api/v1/task-logs${suffix}`)
|
const data = await authRequest(`/auth/api/v1/task-logs${suffix}`)
|
||||||
return Array.isArray(data.items) ? data.items : []
|
return {
|
||||||
|
items: Array.isArray(data.items) ? data.items : [],
|
||||||
|
total: data.total || 0,
|
||||||
|
page: data.page || 1,
|
||||||
|
page_size: data.page_size || 20,
|
||||||
|
total_pages: data.total_pages || 0,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async get(id: string): Promise<{ task: TaskLogSummary; lines: TaskLogLine[] }> {
|
async get(id: string): Promise<{ task: TaskLogSummary; lines: TaskLogLine[] }> {
|
||||||
@@ -89,6 +111,8 @@ export interface TaskLogStreamCallbacks {
|
|||||||
|
|
||||||
export function createTaskLogStream(taskId: string, callbacks: TaskLogStreamCallbacks): EventSource {
|
export function createTaskLogStream(taskId: string, callbacks: TaskLogStreamCallbacks): EventSource {
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
|
// 注意:EventSource 不支持自定义请求头,只能通过 query parameter 传递 token
|
||||||
|
// TODO: 在生产环境中,应考虑使用 WebSocket 或 HttpOnly Cookie 方式以提高安全性
|
||||||
const url = `/auth/api/v1/task-logs/stream?task_id=${encodeURIComponent(taskId)}&access_token=${encodeURIComponent(token || '')}`
|
const url = `/auth/api/v1/task-logs/stream?task_id=${encodeURIComponent(taskId)}&access_token=${encodeURIComponent(token || '')}`
|
||||||
|
|
||||||
const es = new EventSource(url)
|
const es = new EventSource(url)
|
||||||
|
|||||||
@@ -42,7 +42,11 @@
|
|||||||
暂无任务记录
|
暂无任务记录
|
||||||
</div>
|
</div>
|
||||||
<div class="pagination">
|
<div class="pagination">
|
||||||
<span>共 {{ tasks.length }} 条 · 当前业务线:{{ currentName }}</span>
|
<span>共 {{ totalTasks }} 条 · 第 {{ currentPage }}/{{ totalPages }} 页 · 当前业务线:{{ currentName }}</span>
|
||||||
|
<div class="pagination-actions">
|
||||||
|
<el-button size="small" :disabled="currentPage <= 1" @click="prevPage">上一页</el-button>
|
||||||
|
<el-button size="small" :disabled="currentPage >= totalPages" @click="nextPage">下一页</el-button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -53,6 +57,7 @@
|
|||||||
<span>任务日志</span>
|
<span>任务日志</span>
|
||||||
<span class="selected-name">{{ selectedTaskName }}</span>
|
<span class="selected-name">{{ selectedTaskName }}</span>
|
||||||
<span v-if="isStreaming" class="streaming-indicator">● 实时更新中</span>
|
<span v-if="isStreaming" class="streaming-indicator">● 实时更新中</span>
|
||||||
|
<span v-if="streamRetryCount > 0" class="retry-indicator">重试中 ({{ streamRetryCount }}/3)</span>
|
||||||
</h3>
|
</h3>
|
||||||
<div class="panel-actions">
|
<div class="panel-actions">
|
||||||
<el-switch
|
<el-switch
|
||||||
@@ -68,24 +73,13 @@
|
|||||||
class="panel-body log-stream"
|
class="panel-body log-stream"
|
||||||
@scroll="handleScroll"
|
@scroll="handleScroll"
|
||||||
>
|
>
|
||||||
<!-- 虚拟滚动容器 -->
|
<!-- 简单滚动容器 -->
|
||||||
<div
|
<div
|
||||||
:style="{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }"
|
v-for="(log, index) in logs"
|
||||||
|
:key="index"
|
||||||
|
:class="['task-log-line', log.class]"
|
||||||
>
|
>
|
||||||
<div
|
<span class="t">{{ log.time }}</span>{{ log.message }}
|
||||||
v-for="virtualRow in virtualizer.getVirtualItems()"
|
|
||||||
:key="String(virtualRow.key)"
|
|
||||||
:class="['task-log-line', logs[virtualRow.index].class]"
|
|
||||||
:style="{
|
|
||||||
position: 'absolute',
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
width: '100%',
|
|
||||||
transform: `translateY(${virtualRow.start}px)`,
|
|
||||||
}"
|
|
||||||
>
|
|
||||||
<span class="t">{{ logs[virtualRow.index].time }}</span>{{ logs[virtualRow.index].message }}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div v-if="loadingLogs" class="task-log-line">
|
<div v-if="loadingLogs" class="task-log-line">
|
||||||
<span class="t">...</span>加载中
|
<span class="t">...</span>加载中
|
||||||
@@ -104,7 +98,6 @@ import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
|
|||||||
import { taskLogApi, createTaskLogStream, type TaskLogLine, type TaskLogSummary } from '@/api/taskLog'
|
import { taskLogApi, createTaskLogStream, type TaskLogLine, type TaskLogSummary } from '@/api/taskLog'
|
||||||
import { useBusinessLineStore } from '@/stores/businessLine'
|
import { useBusinessLineStore } from '@/stores/businessLine'
|
||||||
import { useBusinessLineMockProfile } from '@/utils/businessLineMock'
|
import { useBusinessLineMockProfile } from '@/utils/businessLineMock'
|
||||||
import { useVirtualizer } from '@tanstack/vue-virtual'
|
|
||||||
|
|
||||||
const { currentName } = useBusinessLineMockProfile()
|
const { currentName } = useBusinessLineMockProfile()
|
||||||
const businessLineStore = useBusinessLineStore()
|
const businessLineStore = useBusinessLineStore()
|
||||||
@@ -121,13 +114,16 @@ let eventSource: EventSource | null = null
|
|||||||
const autoScroll = ref(true)
|
const autoScroll = ref(true)
|
||||||
const logContainerRef = ref<HTMLDivElement | null>(null)
|
const logContainerRef = ref<HTMLDivElement | null>(null)
|
||||||
|
|
||||||
// 虚拟滚动配置
|
// 分页相关
|
||||||
const virtualizer = useVirtualizer({
|
const currentPage = ref(1)
|
||||||
count: logs.value.length,
|
const pageSize = ref(20)
|
||||||
getScrollElement: () => logContainerRef.value,
|
const totalTasks = ref(0)
|
||||||
estimateSize: () => 20,
|
const totalPages = computed(() => Math.ceil(totalTasks.value / pageSize.value))
|
||||||
overscan: 5,
|
|
||||||
})
|
// SSE 重试相关
|
||||||
|
const streamRetryCount = ref(0)
|
||||||
|
const maxRetryCount = 3
|
||||||
|
let retryTimeout: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
const selectedTask = computed(() => tasks.value.find((task) => task.id === selectedTaskId.value))
|
const selectedTask = computed(() => tasks.value.find((task) => task.id === selectedTaskId.value))
|
||||||
const selectedTaskName = computed(() => selectedTask.value?.name || '未选择')
|
const selectedTaskName = computed(() => selectedTask.value?.name || '未选择')
|
||||||
@@ -137,10 +133,14 @@ const lastLoadedText = computed(() => lastLoadedAt.value ? `更新于 ${formatTi
|
|||||||
async function loadTasks() {
|
async function loadTasks() {
|
||||||
loadingTasks.value = true
|
loadingTasks.value = true
|
||||||
try {
|
try {
|
||||||
tasks.value = await taskLogApi.list({
|
const result = await taskLogApi.list({
|
||||||
source: sourceFilter.value,
|
source: sourceFilter.value,
|
||||||
businessLineId: businessLineStore.current?.id,
|
businessLineId: businessLineStore.current?.id,
|
||||||
|
page: currentPage.value,
|
||||||
|
pageSize: pageSize.value,
|
||||||
})
|
})
|
||||||
|
tasks.value = result.items
|
||||||
|
totalTasks.value = result.total
|
||||||
lastLoadedAt.value = new Date()
|
lastLoadedAt.value = new Date()
|
||||||
if (!tasks.value.some((task) => task.id === selectedTaskId.value)) {
|
if (!tasks.value.some((task) => task.id === selectedTaskId.value)) {
|
||||||
selectedTaskId.value = tasks.value[0]?.id || ''
|
selectedTaskId.value = tasks.value[0]?.id || ''
|
||||||
@@ -163,6 +163,7 @@ async function loadLogs(taskId: string) {
|
|||||||
const data = await taskLogApi.get(taskId)
|
const data = await taskLogApi.get(taskId)
|
||||||
logs.value = data.lines
|
logs.value = data.lines
|
||||||
lastLoadedAt.value = new Date()
|
lastLoadedAt.value = new Date()
|
||||||
|
scrollToBottom()
|
||||||
// 启动 SSE 流式更新
|
// 启动 SSE 流式更新
|
||||||
startStream(taskId)
|
startStream(taskId)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -174,6 +175,7 @@ async function loadLogs(taskId: string) {
|
|||||||
|
|
||||||
function startStream(taskId: string) {
|
function startStream(taskId: string) {
|
||||||
stopStream() // 关闭之前的连接
|
stopStream() // 关闭之前的连接
|
||||||
|
streamRetryCount.value = 0
|
||||||
|
|
||||||
eventSource = createTaskLogStream(taskId, {
|
eventSource = createTaskLogStream(taskId, {
|
||||||
onInit: (lines) => {
|
onInit: (lines) => {
|
||||||
@@ -182,23 +184,45 @@ function startStream(taskId: string) {
|
|||||||
scrollToBottom()
|
scrollToBottom()
|
||||||
},
|
},
|
||||||
onUpdate: (newLines) => {
|
onUpdate: (newLines) => {
|
||||||
logs.value = [...logs.value, ...newLines]
|
logs.value = newLines
|
||||||
lastLoadedAt.value = new Date()
|
lastLoadedAt.value = new Date()
|
||||||
scrollToBottom()
|
scrollToBottom()
|
||||||
},
|
},
|
||||||
onFinished: () => {
|
onFinished: () => {
|
||||||
isStreaming.value = false
|
isStreaming.value = false
|
||||||
|
streamRetryCount.value = 0
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
console.error('SSE error:', error)
|
console.error('SSE error:', error)
|
||||||
isStreaming.value = false
|
isStreaming.value = false
|
||||||
|
// 尝试重连
|
||||||
|
retryStream(taskId)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
isStreaming.value = true
|
isStreaming.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function retryStream(taskId: string) {
|
||||||
|
if (streamRetryCount.value >= maxRetryCount) {
|
||||||
|
console.error('Max retry count reached')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
streamRetryCount.value++
|
||||||
|
// 指数退避:1s, 2s, 4s
|
||||||
|
const delay = Math.pow(2, streamRetryCount.value - 1) * 1000
|
||||||
|
|
||||||
|
retryTimeout = setTimeout(() => {
|
||||||
|
startStream(taskId)
|
||||||
|
}, delay)
|
||||||
|
}
|
||||||
|
|
||||||
function stopStream() {
|
function stopStream() {
|
||||||
|
if (retryTimeout) {
|
||||||
|
clearTimeout(retryTimeout)
|
||||||
|
retryTimeout = null
|
||||||
|
}
|
||||||
if (eventSource) {
|
if (eventSource) {
|
||||||
eventSource.close()
|
eventSource.close()
|
||||||
eventSource = null
|
eventSource = null
|
||||||
@@ -244,6 +268,20 @@ function refreshCurrent() {
|
|||||||
void loadTasks()
|
void loadTasks()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function prevPage() {
|
||||||
|
if (currentPage.value > 1) {
|
||||||
|
currentPage.value--
|
||||||
|
void loadTasks()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextPage() {
|
||||||
|
if (currentPage.value < totalPages.value) {
|
||||||
|
currentPage.value++
|
||||||
|
void loadTasks()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function formatTime(date: Date) {
|
function formatTime(date: Date) {
|
||||||
return date.toLocaleTimeString('zh-CN', { hour12: false })
|
return date.toLocaleTimeString('zh-CN', { hour12: false })
|
||||||
}
|
}
|
||||||
@@ -251,6 +289,7 @@ function formatTime(date: Date) {
|
|||||||
watch(
|
watch(
|
||||||
() => businessLineStore.current?.id,
|
() => businessLineStore.current?.id,
|
||||||
() => {
|
() => {
|
||||||
|
currentPage.value = 1
|
||||||
void loadTasks()
|
void loadTasks()
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -419,6 +458,26 @@ onUnmounted(() => {
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.pagination {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 12px 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.retry-indicator {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--warn);
|
||||||
|
animation: pulse 1s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 1180px) {
|
@media (max-width: 1180px) {
|
||||||
.task-layout {
|
.task-layout {
|
||||||
grid-template-columns: minmax(280px, 340px) minmax(0, 1fr);
|
grid-template-columns: minmax(280px, 340px) minmax(0, 1fr);
|
||||||
|
|||||||
Reference in New Issue
Block a user