feat(system): add cursor pagination for runtime queue tasks

Replace offset-based page numbers with opaque Redis-backed cursors so
scheduled/retry tasks sort by next run time and live lists stay stable
when queue state changes between requests.
This commit is contained in:
wizardchen
2026-07-14 16:48:01 +08:00
committed by lyingbug
parent f583d77fa0
commit 01f1011511
17 changed files with 620 additions and 114 deletions
+3 -3
View File
@@ -591,9 +591,9 @@ export interface RuntimeTask {
export interface RuntimeTasksResponse {
available: boolean
tasks: RuntimeTask[]
page: number
page_size: number
has_more: boolean
next_cursor?: string
}
/**
@@ -610,11 +610,11 @@ export async function getRuntimeQueues(): Promise<RuntimeQueuesResponse> {
export async function getRuntimeTasks(
queue: string,
state: RuntimeTaskState,
page = 1,
cursor = '',
pageSize = 20,
): Promise<RuntimeTasksResponse> {
return get(`/api/v1/system/admin/runtime/queues/${encodeURIComponent(queue)}/tasks`, {
params: { state, page, page_size: pageSize },
params: { state, ...(cursor ? { cursor } : {}), page_size: pageSize },
})
}
+1 -1
View File
@@ -3603,7 +3603,7 @@ export default {
},
tasks: {
title: "Task details · {queue}",
description: "Inspect every task state and use only the actions the backend marks safe for the current task.",
description: "Inspect every task state. Scheduled and retry tasks show the next run first; other states show the newest tasks first.",
listTitle: "{state} tasks",
openAria: "View {count} {state} tasks in {queue}",
unavailable: "Task details are unavailable in this deployment",
+1 -1
View File
@@ -2588,7 +2588,7 @@ export default {
},
tasks: {
title: "작업 상세 · {queue}",
description: "모든 작업 상태를 확인하고 백엔드가 현재 상태에 안전하다고 표시한 작업만 실행합니다.",
description: "모든 작업 상태를 확인합니다. 예약 및 재시도 작업은 다음 실행 순서로, 나머지는 최신 작업부터 표시됩니다.",
guideTitle: "원인을 해결한 뒤 다시 실행하세요",
guideDescription: "‘한 번 다시 실행’은 재시도 횟수를 초기화하지 않고 즉시 한 번 실행합니다. ‘기록 지우기’는 현재 큐에서만 제거하며 원래 작업을 완료하지 않고 기록 로그는 유지됩니다.",
listTitle: "{state} 작업",
+1 -1
View File
@@ -2285,7 +2285,7 @@ export default {
},
tasks: {
title: "Сведения о задачах · {queue}",
description: "Просмотр всех состояний; доступны только действия, которые сервер считает безопасными для текущей задачи.",
description: "Запланированные и повторные задачи показаны по ближайшему запуску, остальные — от новых к старым.",
guideTitle: "Сначала устраните причину",
guideDescription: "«Запустить один раз» выполняет одну попытку без сброса счётчика повторов. «Очистить запись» удаляет её только из этой очереди, не завершает исходную задачу и сохраняет исторические журналы.",
listTitle: "Задачи: {state}",
+1 -1
View File
@@ -2591,7 +2591,7 @@ export default {
},
tasks: {
title: "任务明细 · {queue}",
description: "查看各状态任务及其安全管理动作。可用动作由后端根据任务当前状态和业务语义返回。",
description: "查看各状态任务及其安全管理动作。定时、重试任务按最近执行时间优先,其余状态按时间倒序。",
listTitle: "{state}任务",
openAria: "查看{queue}中 {count} 个{state}任务",
unavailable: "当前部署不支持查看任务明细",
+14 -7
View File
@@ -489,6 +489,7 @@ import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import { mergeRuntimeTaskPage } from './runtimeTaskPagination'
import {
getRuntimeTasks,
getRuntimeQueues,
@@ -522,7 +523,7 @@ const tasks = ref<RuntimeTask[]>([])
const tasksLoading = ref(false)
const tasksLoadingMore = ref(false)
const tasksError = ref('')
const tasksPage = ref(1)
const tasksCursor = ref('')
const tasksHasMore = ref(false)
const tasksSentinelRef = ref<HTMLElement | null>(null)
const taskActionID = ref('')
@@ -753,9 +754,10 @@ async function fetchRuntimeTasks(reset: boolean) {
const requestedState = taskState.value
const requestID = ++tasksRequestID
const page = reset ? 1 : tasksPage.value + 1
const cursor = reset ? '' : tasksCursor.value
if (reset) {
tasksPage.value = 1
tasksCursor.value = ''
tasksHasMore.value = false
tasks.value = []
tasksLoading.value = true
} else {
@@ -763,17 +765,22 @@ async function fetchRuntimeTasks(reset: boolean) {
}
tasksError.value = ''
try {
const response = await getRuntimeTasks(queue, requestedState, page, TASK_PAGE_SIZE)
const response = await getRuntimeTasks(queue, requestedState, cursor, TASK_PAGE_SIZE)
if (requestID !== tasksRequestID || taskQueue.value?.name !== queue || taskState.value !== requestedState) return
if (!response.available) {
tasksError.value = t('system.globalSettings.runtime.tasks.unavailable')
return
}
tasks.value = reset ? response.tasks : [...tasks.value, ...response.tasks]
tasksPage.value = page
tasksHasMore.value = response.has_more
tasks.value = reset ? response.tasks : mergeRuntimeTaskPage(tasks.value, response.tasks)
tasksCursor.value = response.next_cursor || ''
tasksHasMore.value = response.has_more && Boolean(response.next_cursor)
} catch (err: any) {
if (requestID !== tasksRequestID) return
if (!reset && err?.code === 'runtime_task_cursor_expired') {
tasksLoadingMore.value = false
await fetchRuntimeTasks(true)
return
}
tasksError.value = err?.message || t('system.globalSettings.runtime.tasks.loadError')
} finally {
if (requestID !== tasksRequestID) return
@@ -0,0 +1,31 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import type { RuntimeTask } from '@/api/system'
import { mergeRuntimeTaskPage } from './runtimeTaskPagination.ts'
function task(id: string): RuntimeTask {
return {
id,
queue: 'default',
type: 'document:process',
state: 'archived',
allowed_actions: [],
retried: 0,
max_retry: 0,
}
}
test('appends a cursor page without changing backend order', () => {
assert.deepEqual(
mergeRuntimeTaskPage([task('newest'), task('newer')], [task('older'), task('oldest')]).map((item) => item.id),
['newest', 'newer', 'older', 'oldest'],
)
})
test('deduplicates overlap from a surviving cursor anchor', () => {
assert.deepEqual(
mergeRuntimeTaskPage([task('a'), task('b'), task('c')], [task('c'), task('d')]).map((item) => item.id),
['a', 'b', 'c', 'd'],
)
})
@@ -0,0 +1,19 @@
import type { RuntimeTask } from '@/api/system'
// Cursor anchors can fall back to an earlier still-live task when queue state
// changes between requests. That deliberately favors continuing the list over
// failing, and may return a small overlap. Keep the first occurrence so Vue
// row keys remain unique and the scroll position stays stable.
export function mergeRuntimeTaskPage(
current: RuntimeTask[],
incoming: RuntimeTask[],
): RuntimeTask[] {
const seen = new Set(current.map((task) => task.id))
const merged = [...current]
for (const task of incoming) {
if (seen.has(task.id)) continue
seen.add(task.id)
merged.push(task)
}
return merged
}