diff --git a/docs/docs.go b/docs/docs.go index 44cac9ff..c9c7ce22 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -11349,10 +11349,9 @@ const docTemplate = `{ "required": true }, { - "type": "integer", - "default": 1, - "description": "Page", - "name": "page", + "type": "string", + "description": "Opaque continuation cursor", + "name": "cursor", "in": "query" }, { @@ -20385,8 +20384,8 @@ const docTemplate = `{ "has_more": { "type": "boolean" }, - "page": { - "type": "integer" + "next_cursor": { + "type": "string" }, "page_size": { "type": "integer" diff --git a/docs/swagger.json b/docs/swagger.json index 14c6cd58..484f857d 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -11342,10 +11342,9 @@ "required": true }, { - "type": "integer", - "default": 1, - "description": "Page", - "name": "page", + "type": "string", + "description": "Opaque continuation cursor", + "name": "cursor", "in": "query" }, { @@ -20378,8 +20377,8 @@ "has_more": { "type": "boolean" }, - "page": { - "type": "integer" + "next_cursor": { + "type": "string" }, "page_size": { "type": "integer" diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 0ddbc861..f09a6eff 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -4932,8 +4932,8 @@ definitions: type: boolean has_more: type: boolean - page: - type: integer + next_cursor: + type: string page_size: type: integer tasks: @@ -12743,11 +12743,10 @@ paths: name: state required: true type: string - - default: 1 - description: Page + - description: Opaque continuation cursor in: query - name: page - type: integer + name: cursor + type: string - default: 20 description: Page size in: query diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 62e2697d..01b105ca 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -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 { export async function getRuntimeTasks( queue: string, state: RuntimeTaskState, - page = 1, + cursor = '', pageSize = 20, ): Promise { return get(`/api/v1/system/admin/runtime/queues/${encodeURIComponent(queue)}/tasks`, { - params: { state, page, page_size: pageSize }, + params: { state, ...(cursor ? { cursor } : {}), page_size: pageSize }, }) } diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index b1d3e79a..2c08731f 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -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", diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index d68e83b0..a279df7e 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -2588,7 +2588,7 @@ export default { }, tasks: { title: "작업 상세 · {queue}", - description: "모든 작업 상태를 확인하고 백엔드가 현재 상태에 안전하다고 표시한 작업만 실행합니다.", + description: "모든 작업 상태를 확인합니다. 예약 및 재시도 작업은 다음 실행 순서로, 나머지는 최신 작업부터 표시됩니다.", guideTitle: "원인을 해결한 뒤 다시 실행하세요", guideDescription: "‘한 번 다시 실행’은 재시도 횟수를 초기화하지 않고 즉시 한 번 실행합니다. ‘기록 지우기’는 현재 큐에서만 제거하며 원래 작업을 완료하지 않고 기록 로그는 유지됩니다.", listTitle: "{state} 작업", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index de75aaf6..c4d2840b 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -2285,7 +2285,7 @@ export default { }, tasks: { title: "Сведения о задачах · {queue}", - description: "Просмотр всех состояний; доступны только действия, которые сервер считает безопасными для текущей задачи.", + description: "Запланированные и повторные задачи показаны по ближайшему запуску, остальные — от новых к старым.", guideTitle: "Сначала устраните причину", guideDescription: "«Запустить один раз» выполняет одну попытку без сброса счётчика повторов. «Очистить запись» удаляет её только из этой очереди, не завершает исходную задачу и сохраняет исторические журналы.", listTitle: "Задачи: {state}", diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 7985ee65..8d6c384d 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2591,7 +2591,7 @@ export default { }, tasks: { title: "任务明细 · {queue}", - description: "查看各状态任务及其安全管理动作。可用动作由后端根据任务当前状态和业务语义返回。", + description: "查看各状态任务及其安全管理动作。定时、重试任务按最近执行时间优先,其余状态按时间倒序。", listTitle: "{state}任务", openAria: "查看{queue}中 {count} 个{state}任务", unavailable: "当前部署不支持查看任务明细", diff --git a/frontend/src/views/system/RuntimeQueues.vue b/frontend/src/views/system/RuntimeQueues.vue index 64dc4180..8f22734a 100644 --- a/frontend/src/views/system/RuntimeQueues.vue +++ b/frontend/src/views/system/RuntimeQueues.vue @@ -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([]) 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(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 diff --git a/frontend/src/views/system/runtimeTaskPagination.test.ts b/frontend/src/views/system/runtimeTaskPagination.test.ts new file mode 100644 index 00000000..0c253141 --- /dev/null +++ b/frontend/src/views/system/runtimeTaskPagination.test.ts @@ -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'], + ) +}) diff --git a/frontend/src/views/system/runtimeTaskPagination.ts b/frontend/src/views/system/runtimeTaskPagination.ts new file mode 100644 index 00000000..7965c5aa --- /dev/null +++ b/frontend/src/views/system/runtimeTaskPagination.ts @@ -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 +} diff --git a/internal/handler/system.go b/internal/handler/system.go index ace04500..5e8b4c7c 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -1605,11 +1605,11 @@ func (h *SystemHandler) GetRuntimeQueues(c *gin.Context) { } type RuntimeTasksResponse struct { - Available bool `json:"available"` - Tasks []types.RuntimeTaskInfo `json:"tasks"` - Page int `json:"page"` - PageSize int `json:"page_size"` - HasMore bool `json:"has_more"` + Available bool `json:"available"` + Tasks []types.RuntimeTaskInfo `json:"tasks"` + PageSize int `json:"page_size"` + HasMore bool `json:"has_more"` + NextCursor string `json:"next_cursor,omitempty"` } func isKnownRuntimeQueue(name string) bool { @@ -1621,19 +1621,15 @@ func isKnownRuntimeQueue(name string) bool { return false } -func runtimeTaskPage(c *gin.Context) (int, int) { - page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) +func runtimeTaskPageSize(c *gin.Context) int { pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) - if page < 1 { - page = 1 - } if pageSize < 1 { pageSize = 20 } if pageSize > 100 { pageSize = 100 } - return page, pageSize + return pageSize } func (h *SystemHandler) listRuntimeTasks(c *gin.Context, state types.RuntimeTaskState) { @@ -1646,32 +1642,46 @@ func (h *SystemHandler) listRuntimeTasks(c *gin.Context, state types.RuntimeTask c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown task state"}) return } - page, pageSize := runtimeTaskPage(c) + pageSize := runtimeTaskPageSize(c) + cursor := c.Query("cursor") inspector, ok := h.taskInspector.(interfaces.RuntimeTaskInspector) if !ok { c.JSON(http.StatusOK, RuntimeTasksResponse{ Available: false, Tasks: []types.RuntimeTaskInfo{}, - Page: page, PageSize: pageSize, }) return } - tasks, supported, err := inspector.ListRuntimeTasks(c.Request.Context(), queue, state, page, pageSize) + page, supported, err := inspector.ListRuntimeTasks(c.Request.Context(), queue, state, cursor, pageSize) if err != nil { + if errors.Is(err, types.ErrInvalidRuntimeTaskCursor) { + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Invalid task list cursor", + "code": "runtime_task_cursor_invalid", + }) + return + } + if errors.Is(err, types.ErrExpiredRuntimeTaskCursor) { + c.JSON(http.StatusConflict, gin.H{ + "error": "Task list changed; refresh from the beginning", + "code": "runtime_task_cursor_expired", + }) + return + } logger.Errorf(c.Request.Context(), "list runtime queue tasks queue=%s state=%s: %v", queue, state, err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list queue tasks"}) return } - if tasks == nil { - tasks = []types.RuntimeTaskInfo{} + if page.Tasks == nil { + page.Tasks = []types.RuntimeTaskInfo{} } c.JSON(http.StatusOK, RuntimeTasksResponse{ - Available: supported, - Tasks: tasks, - Page: page, - PageSize: pageSize, - HasMore: len(tasks) == pageSize, + Available: supported, + Tasks: page.Tasks, + PageSize: pageSize, + HasMore: page.HasMore, + NextCursor: page.NextCursor, }) } @@ -1682,7 +1692,7 @@ func (h *SystemHandler) listRuntimeTasks(c *gin.Context, state types.RuntimeTask // @Produce json // @Param queue path string true "Queue name" // @Param state query string true "Task state" Enums(pending,active,scheduled,retry,archived,completed) -// @Param page query int false "Page" default(1) +// @Param cursor query string false "Opaque continuation cursor" // @Param page_size query int false "Page size" default(20) // @Success 200 {object} RuntimeTasksResponse // @Router /system/admin/runtime/queues/{queue}/tasks [get] diff --git a/internal/handler/system_runtime_test.go b/internal/handler/system_runtime_test.go index 664466d7..14966587 100644 --- a/internal/handler/system_runtime_test.go +++ b/internal/handler/system_runtime_test.go @@ -79,13 +79,18 @@ func (runtimeTestInspector) WorkerServerStats(context.Context) ([]types.WorkerSe type runtimeTaskTestInspector struct { runtimeTestInspector - tasks []types.RuntimeTaskInfo - retriedTask string - deletedTask string - forceDeleted string - cancelKnowledge string - cancelDeleted int - mutatedQueue string + tasks []types.RuntimeTaskInfo + retriedTask string + deletedTask string + forceDeleted string + cancelKnowledge string + cancelDeleted int + mutatedQueue string + nextCursor string + hasMore bool + inputCursor string + inputPageSize int + listErr error forceDeleteErr error getRuntimeErr error getRuntimeErrFrom int @@ -120,8 +125,13 @@ func (r *runtimeKnowledgeCancelTest) CancelKnowledgeParse( } func (r *runtimeTaskTestInspector) ListRuntimeTasks( - _ context.Context, _ string, state types.RuntimeTaskState, _, _ int, -) ([]types.RuntimeTaskInfo, bool, error) { + _ context.Context, _ string, state types.RuntimeTaskState, cursor string, pageSize int, +) (types.RuntimeTaskPage, bool, error) { + r.inputCursor = cursor + r.inputPageSize = pageSize + if r.listErr != nil { + return types.RuntimeTaskPage{}, true, r.listErr + } for i := range r.tasks { if r.tasks[i].State == "" { r.tasks[i].State = state @@ -133,7 +143,9 @@ func (r *runtimeTaskTestInspector) ListRuntimeTasks( } } } - return r.tasks, true, nil + return types.RuntimeTaskPage{ + Tasks: r.tasks, NextCursor: r.nextCursor, HasMore: r.hasMore, + }, true, nil } func (r *runtimeTaskTestInspector) GetRuntimeTask( @@ -296,6 +308,65 @@ func TestListRuntimeTasksReturnsSafeTaskDetails(t *testing.T) { } } +func TestListRuntimeTasksReturnsAndForwardsCursor(t *testing.T) { + gin.SetMode(gin.TestMode) + inspector := &runtimeTaskTestInspector{ + tasks: []types.RuntimeTaskInfo{{ID: "task-1"}}, + nextCursor: "next-page", hasMore: true, + } + handler := &SystemHandler{taskInspector: inspector} + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "queue", Value: types.QueueDefault}} + ctx.Request = httptest.NewRequest( + http.MethodGet, + "/api/v1/system/admin/runtime/queues/default/tasks?state=archived&cursor=previous-page&page_size=25", + nil, + ) + + handler.ListRuntimeTasks(ctx) + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String()) + } + var response RuntimeTasksResponse + if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil { + t.Fatalf("decode response: %v", err) + } + if inspector.inputCursor != "previous-page" || inspector.inputPageSize != 25 { + t.Fatalf("cursor request not forwarded: cursor=%q size=%d", inspector.inputCursor, inspector.inputPageSize) + } + if !response.HasMore || response.NextCursor != "next-page" { + t.Fatalf("cursor response missing: %+v", response) + } +} + +func TestListRuntimeTasksReportsExpiredCursorForFrontendRefresh(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := &SystemHandler{taskInspector: &runtimeTaskTestInspector{ + listErr: types.ErrExpiredRuntimeTaskCursor, + }} + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "queue", Value: types.QueueDefault}} + ctx.Request = httptest.NewRequest( + http.MethodGet, + "/api/v1/system/admin/runtime/queues/default/tasks?state=pending&cursor=expired", + nil, + ) + + handler.ListRuntimeTasks(ctx) + if recorder.Code != http.StatusConflict { + t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String()) + } + var response map[string]any + if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil { + t.Fatalf("decode response: %v", err) + } + if response["code"] != "runtime_task_cursor_expired" { + t.Fatalf("unexpected error response: %+v", response) + } +} + func TestRuntimeTaskMutationsDelegateToInspector(t *testing.T) { gin.SetMode(gin.TestMode) inspector := &runtimeTaskTestInspector{} diff --git a/internal/router/task_inspector.go b/internal/router/task_inspector.go index d29c4fc8..d230d6d6 100644 --- a/internal/router/task_inspector.go +++ b/internal/router/task_inspector.go @@ -2,6 +2,7 @@ package router import ( "context" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -11,12 +12,13 @@ import ( "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/hibiken/asynq" + "github.com/redis/go-redis/v9" ) // NewAsynqInspector constructs an *asynq.Inspector pointed at the same // Redis used by the asynq client. Only registered in asynq mode. -func NewAsynqInspector() *asynq.Inspector { - return asynq.NewInspector(getAsynqRedisClientOpt()) +func NewAsynqInspector(redisClient *redis.Client) *asynq.Inspector { + return asynq.NewInspectorFromRedisClient(redisClient) } // asynqTaskInspector implements interfaces.TaskInspector backed by an @@ -27,16 +29,17 @@ func NewAsynqInspector() *asynq.Inspector { // flaky. type asynqTaskInspector struct { inspector *asynq.Inspector + redis redis.UniversalClient } // NewAsynqTaskInspector returns a TaskInspector wrapping the given // *asynq.Inspector. nil-safe: a nil inspector degrades to a no-op so // the cancel path remains usable when the inspector failed to init. -func NewAsynqTaskInspector(inspector *asynq.Inspector) interfaces.TaskInspector { - if inspector == nil { +func NewAsynqTaskInspector(inspector *asynq.Inspector, redisClient *redis.Client) interfaces.TaskInspector { + if inspector == nil || redisClient == nil { return noopTaskInspector{} } - return &asynqTaskInspector{inspector: inspector} + return &asynqTaskInspector{inspector: inspector, redis: redisClient} } // knowledgeIDProbe is the minimal payload shape we need to filter @@ -346,23 +349,176 @@ func (a *asynqTaskInspector) activeWorkerMetadata() map[string]runtimeWorkerMeta return result } -// ListRuntimeTasks returns one task state page. Only allow-listed routing -// metadata is projected from the payload so the dashboard never exposes raw -// document content, signed URLs, or connector secrets. +const ( + runtimeTaskCursorVersion = 1 + runtimeTaskCursorMaxAnchors = 32 + runtimeTaskCursorMaxBytes = 16 * 1024 +) + +type runtimeTaskCursor struct { + Version int `json:"v"` + Queue string `json:"q"` + State types.RuntimeTaskState `json:"s"` + Anchors []string `json:"a"` +} + +type runtimeTaskStorageOrder int + +const ( + runtimeTaskListNewestFirst runtimeTaskStorageOrder = iota + runtimeTaskZSetEarliestFirst + runtimeTaskZSetNewestFirst +) + +func runtimeTaskStorage(state types.RuntimeTaskState) (suffix string, order runtimeTaskStorageOrder) { + switch state { + case types.RuntimeTaskPending, types.RuntimeTaskActive: + // Asynq LPUSHes newly enqueued/started tasks, so index zero is the + // newest task in these live-state lists. + return string(state), runtimeTaskListNewestFirst + case types.RuntimeTaskScheduled, types.RuntimeTaskRetry: + // Sorted-set scores are NextProcessAt. Earliest-first keeps the next + // operational action visible instead of hiding it below later work. + return string(state), runtimeTaskZSetEarliestFirst + case types.RuntimeTaskArchived, types.RuntimeTaskCompleted: + // Archived scores are LastFailedAt; completed scores are expiry time. + // Reverse score order presents the newest failures and the newest + // retained completion records first. + return string(state), runtimeTaskZSetNewestFirst + default: + return "", runtimeTaskListNewestFirst + } +} + +func runtimeTaskStateKey(queue string, state types.RuntimeTaskState) (string, runtimeTaskStorageOrder) { + suffix, order := runtimeTaskStorage(state) + // Asynq's public Inspector only supports offset pages and does not expose + // sort direction or continuation cursors. Keep the v0.26 queue-key schema + // isolated here and covered by cursor-order integration tests. + return "asynq:{" + queue + "}:" + suffix, order +} + +func decodeRuntimeTaskCursor(raw, queue string, state types.RuntimeTaskState) ([]string, error) { + if raw == "" { + return nil, nil + } + if len(raw) > runtimeTaskCursorMaxBytes { + return nil, types.ErrInvalidRuntimeTaskCursor + } + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, types.ErrInvalidRuntimeTaskCursor + } + var cursor runtimeTaskCursor + if err = json.Unmarshal(data, &cursor); err != nil || + cursor.Version != runtimeTaskCursorVersion || cursor.Queue != queue || cursor.State != state || + len(cursor.Anchors) == 0 || len(cursor.Anchors) > runtimeTaskCursorMaxAnchors { + return nil, types.ErrInvalidRuntimeTaskCursor + } + for _, anchor := range cursor.Anchors { + if anchor == "" { + return nil, types.ErrInvalidRuntimeTaskCursor + } + } + return cursor.Anchors, nil +} + +func encodeRuntimeTaskCursor(queue string, state types.RuntimeTaskState, anchors []string) (string, error) { + if len(anchors) > runtimeTaskCursorMaxAnchors { + anchors = anchors[len(anchors)-runtimeTaskCursorMaxAnchors:] + } + data, err := json.Marshal(runtimeTaskCursor{ + Version: runtimeTaskCursorVersion, + Queue: queue, + State: state, + Anchors: anchors, + }) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +// runtimeTaskAnchorOffset finds the newest surviving anchor. Retaining a +// small window of anchors lets pagination continue when the last item from a +// previous live-state page finishes, retries, or is deleted between requests. +func (a *asynqTaskInspector) runtimeTaskAnchorOffset( + ctx context.Context, + key string, + order runtimeTaskStorageOrder, + anchors []string, +) (int64, error) { + if len(anchors) == 0 { + return 0, nil + } + pipe := a.redis.Pipeline() + ranks := make([]*redis.IntCmd, 0, len(anchors)) + for i := len(anchors) - 1; i >= 0; i-- { + switch order { + case runtimeTaskListNewestFirst: + ranks = append(ranks, pipe.LPos(ctx, key, anchors[i], redis.LPosArgs{})) + case runtimeTaskZSetEarliestFirst: + ranks = append(ranks, pipe.ZRank(ctx, key, anchors[i])) + case runtimeTaskZSetNewestFirst: + ranks = append(ranks, pipe.ZRevRank(ctx, key, anchors[i])) + } + } + _, err := pipe.Exec(ctx) + if err != nil && !errors.Is(err, redis.Nil) { + return 0, err + } + for _, rank := range ranks { + if rank.Err() == nil { + return rank.Val() + 1, nil + } + if !errors.Is(rank.Err(), redis.Nil) { + return 0, rank.Err() + } + } + return 0, types.ErrExpiredRuntimeTaskCursor +} + +func (a *asynqTaskInspector) listRuntimeTaskIDs( + ctx context.Context, + queue string, + state types.RuntimeTaskState, + anchors []string, + limit int, +) ([]string, error) { + key, order := runtimeTaskStateKey(queue, state) + start, err := a.runtimeTaskAnchorOffset(ctx, key, order, anchors) + if err != nil { + return nil, err + } + stop := start + int64(limit) - 1 + switch order { + case runtimeTaskListNewestFirst: + return a.redis.LRange(ctx, key, start, stop).Result() + case runtimeTaskZSetEarliestFirst: + return a.redis.ZRange(ctx, key, start, stop).Result() + case runtimeTaskZSetNewestFirst: + return a.redis.ZRevRange(ctx, key, start, stop).Result() + default: + return nil, fmt.Errorf("unsupported runtime task storage order %d", order) + } +} + +// ListRuntimeTasks returns one cursor page in state-appropriate time order: +// newest first for pending/active/archived/completed, and next-to-run first +// for scheduled/retry. Only allow-listed routing metadata is projected from +// payloads so the dashboard never exposes document content or secrets. func (a *asynqTaskInspector) ListRuntimeTasks( ctx context.Context, queue string, state types.RuntimeTaskState, - page, pageSize int, -) ([]types.RuntimeTaskInfo, bool, error) { - if a == nil || a.inspector == nil { - return nil, false, nil + cursor string, + pageSize int, +) (types.RuntimeTaskPage, bool, error) { + if a == nil || a.inspector == nil || a.redis == nil { + return types.RuntimeTaskPage{}, false, nil } if !state.Valid() { - return nil, true, fmt.Errorf("unsupported runtime task state %q", state) - } - if page < 1 { - page = 1 + return types.RuntimeTaskPage{}, true, fmt.Errorf("unsupported runtime task state %q", state) } if pageSize < 1 { pageSize = 20 @@ -370,46 +526,76 @@ func (a *asynqTaskInspector) ListRuntimeTasks( if pageSize > 100 { pageSize = 100 } - opts := []asynq.ListOption{asynq.Page(page), asynq.PageSize(pageSize)} - var tasks []*asynq.TaskInfo - var err error - switch state { - case types.RuntimeTaskPending: - tasks, err = a.inspector.ListPendingTasks(queue, opts...) - case types.RuntimeTaskActive: - tasks, err = a.inspector.ListActiveTasks(queue, opts...) - case types.RuntimeTaskScheduled: - tasks, err = a.inspector.ListScheduledTasks(queue, opts...) - case types.RuntimeTaskRetry: - tasks, err = a.inspector.ListRetryTasks(queue, opts...) - case types.RuntimeTaskArchived: - tasks, err = a.inspector.ListArchivedTasks(queue, opts...) - case types.RuntimeTaskCompleted: - tasks, err = a.inspector.ListCompletedTasks(queue, opts...) - } - if errors.Is(err, asynq.ErrQueueNotFound) { - return []types.RuntimeTaskInfo{}, true, nil - } + anchors, err := decodeRuntimeTaskCursor(cursor, queue, state) if err != nil { - return nil, true, err + return types.RuntimeTaskPage{}, true, err } workers := map[string]runtimeWorkerMetadata{} if state == types.RuntimeTaskActive { workers = a.activeWorkerMetadata() } - result := make([]types.RuntimeTaskInfo, 0, len(tasks)) - for _, task := range tasks { - if task == nil { - continue + result := make([]types.RuntimeTaskInfo, 0, pageSize) + hasMore := false + + for len(result) < pageSize { + // The extra ID proves there is another raw item without consuming it + // into this page's continuation cursor. + batchLimit := pageSize - len(result) + 1 + ids, listErr := a.listRuntimeTaskIDs(ctx, queue, state, anchors, batchLimit) + if listErr != nil { + if errors.Is(listErr, types.ErrExpiredRuntimeTaskCursor) && cursor == "" { + return types.RuntimeTaskPage{Tasks: result}, true, nil + } + return types.RuntimeTaskPage{}, true, listErr } - info, projectErr := projectRuntimeTask(task, workers[task.Queue+"\x00"+task.ID]) - if projectErr != nil { - logger.Warnf(ctx, "[TaskInspector] project runtime task queue=%s id=%s: %v", queue, task.ID, projectErr) - continue + if len(ids) == 0 { + break + } + for i, id := range ids { + if len(result) == pageSize { + hasMore = true + break + } + anchors = append(anchors, id) + if len(anchors) > runtimeTaskCursorMaxAnchors { + anchors = anchors[len(anchors)-runtimeTaskCursorMaxAnchors:] + } + task, getErr := a.inspector.GetTaskInfo(queue, id) + if errors.Is(getErr, asynq.ErrTaskNotFound) || errors.Is(getErr, asynq.ErrQueueNotFound) { + continue + } + if getErr != nil { + return types.RuntimeTaskPage{}, true, getErr + } + info, projectErr := projectRuntimeTask(task, workers[task.Queue+"\x00"+task.ID]) + if projectErr != nil { + logger.Warnf(ctx, "[TaskInspector] project runtime task queue=%s id=%s: %v", queue, task.ID, projectErr) + continue + } + if info.State != state { + continue + } + result = append(result, info) + if len(result) == pageSize { + // A full raw batch may have contained stale IDs that were + // skipped above. In that case the last returned item can also be + // the last fetched ID even though older Redis entries still exist. + hasMore = i < len(ids)-1 || len(ids) == batchLimit + } + } + if hasMore || len(ids) < batchLimit { + break } - result = append(result, info) } - return result, true, nil + + page := types.RuntimeTaskPage{Tasks: result, HasMore: hasMore} + if hasMore { + page.NextCursor, err = encodeRuntimeTaskCursor(queue, state, anchors) + if err != nil { + return types.RuntimeTaskPage{}, true, err + } + } + return page, true, nil } func (a *asynqTaskInspector) GetRuntimeTask( diff --git a/internal/router/task_inspector_runtime_test.go b/internal/router/task_inspector_runtime_test.go index e5be85bd..755a409c 100644 --- a/internal/router/task_inspector_runtime_test.go +++ b/internal/router/task_inspector_runtime_test.go @@ -1,12 +1,15 @@ package router import ( + "context" "encoding/json" "testing" "time" "github.com/Tencent/WeKnora/internal/types" + "github.com/alicebob/miniredis/v2" "github.com/hibiken/asynq" + "github.com/redis/go-redis/v9" ) func TestProjectRuntimeTaskRedactsPayloadAndBuildsSafeActions(t *testing.T) { @@ -94,3 +97,163 @@ func TestProjectRuntimeTaskUsesAllowListedBatchMetadata(t *testing.T) { t.Fatalf("generic maintenance task must not expose raw deletion: %v", info.AllowedActions) } } + +func TestRuntimeTaskCursorUsesStateTimeOrderAndSurvivingAnchors(t *testing.T) { + server := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + inspector := &asynqTaskInspector{redis: client} + ctx := context.Background() + + pendingKey, _ := runtimeTaskStateKey(types.QueueDefault, types.RuntimeTaskPending) + if err := client.LPush(ctx, pendingKey, "old", "middle", "new").Err(); err != nil { + t.Fatal(err) + } + ids, err := inspector.listRuntimeTaskIDs(ctx, types.QueueDefault, types.RuntimeTaskPending, nil, 2) + if err != nil { + t.Fatal(err) + } + if got, want := ids, []string{"new", "middle"}; !equalStrings(got, want) { + t.Fatalf("pending order = %v, want %v", got, want) + } + if err = client.LRem(ctx, pendingKey, 0, "middle").Err(); err != nil { + t.Fatal(err) + } + ids, err = inspector.listRuntimeTaskIDs( + ctx, types.QueueDefault, types.RuntimeTaskPending, []string{"new", "middle"}, 2, + ) + if err != nil { + t.Fatal(err) + } + if got, want := ids, []string{"old"}; !equalStrings(got, want) { + t.Fatalf("anchor fallback order = %v, want %v", got, want) + } + + scheduledKey, _ := runtimeTaskStateKey(types.QueueDefault, types.RuntimeTaskScheduled) + if err = client.ZAdd(ctx, scheduledKey, + redis.Z{Score: 30, Member: "later"}, + redis.Z{Score: 10, Member: "next"}, + redis.Z{Score: 20, Member: "after-next"}, + ).Err(); err != nil { + t.Fatal(err) + } + ids, err = inspector.listRuntimeTaskIDs(ctx, types.QueueDefault, types.RuntimeTaskScheduled, nil, 3) + if err != nil { + t.Fatal(err) + } + if got, want := ids, []string{"next", "after-next", "later"}; !equalStrings(got, want) { + t.Fatalf("scheduled order = %v, want %v", got, want) + } + + archivedKey, _ := runtimeTaskStateKey(types.QueueDefault, types.RuntimeTaskArchived) + if err = client.ZAdd(ctx, archivedKey, + redis.Z{Score: 10, Member: "old-failure"}, + redis.Z{Score: 30, Member: "new-failure"}, + redis.Z{Score: 20, Member: "middle-failure"}, + ).Err(); err != nil { + t.Fatal(err) + } + ids, err = inspector.listRuntimeTaskIDs(ctx, types.QueueDefault, types.RuntimeTaskArchived, nil, 3) + if err != nil { + t.Fatal(err) + } + if got, want := ids, []string{"new-failure", "middle-failure", "old-failure"}; !equalStrings(got, want) { + t.Fatalf("archived order = %v, want %v", got, want) + } +} + +func TestRuntimeTaskCursorIsBoundToQueueAndState(t *testing.T) { + raw, err := encodeRuntimeTaskCursor( + types.QueueDefault, + types.RuntimeTaskArchived, + []string{"task-1", "task-2"}, + ) + if err != nil { + t.Fatal(err) + } + anchors, err := decodeRuntimeTaskCursor(raw, types.QueueDefault, types.RuntimeTaskArchived) + if err != nil { + t.Fatal(err) + } + if !equalStrings(anchors, []string{"task-1", "task-2"}) { + t.Fatalf("anchors = %v", anchors) + } + if _, err = decodeRuntimeTaskCursor(raw, types.QueueDefault, types.RuntimeTaskRetry); err == nil { + t.Fatal("cursor from another state should be rejected") + } + if _, err = decodeRuntimeTaskCursor("not-base64", types.QueueDefault, types.RuntimeTaskArchived); err == nil { + t.Fatal("malformed cursor should be rejected") + } +} + +func TestListRuntimeTasksPaginatesNewestPendingTasksWithoutOverlap(t *testing.T) { + server := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + asynqClient := asynq.NewClientFromRedisClient(client) + inspector := &asynqTaskInspector{ + inspector: asynq.NewInspectorFromRedisClient(client), + redis: client, + } + + for _, id := range []string{"old", "middle", "new"} { + _, err := asynqClient.Enqueue( + asynq.NewTask(types.TypeDocumentProcess, []byte(`{"tenant_id":1,"knowledge_id":"knowledge-1"}`)), + asynq.Queue(types.QueueDefault), + asynq.TaskID(id), + ) + if err != nil { + t.Fatalf("enqueue %s: %v", id, err) + } + } + pendingKey, _ := runtimeTaskStateKey(types.QueueDefault, types.RuntimeTaskPending) + if err := client.LInsert(context.Background(), pendingKey, "AFTER", "new", "already-gone").Err(); err != nil { + t.Fatalf("insert stale task id: %v", err) + } + + first, supported, err := inspector.ListRuntimeTasks( + context.Background(), types.QueueDefault, types.RuntimeTaskPending, "", 2, + ) + if err != nil || !supported { + t.Fatalf("first page: supported=%v err=%v", supported, err) + } + if got, want := runtimeTaskIDs(first.Tasks), []string{"new", "middle"}; !equalStrings(got, want) { + t.Fatalf("first page = %v, want %v", got, want) + } + if !first.HasMore || first.NextCursor == "" { + t.Fatalf("first page cursor missing: %+v", first) + } + + second, supported, err := inspector.ListRuntimeTasks( + context.Background(), types.QueueDefault, types.RuntimeTaskPending, first.NextCursor, 2, + ) + if err != nil || !supported { + t.Fatalf("second page: supported=%v err=%v", supported, err) + } + if got, want := runtimeTaskIDs(second.Tasks), []string{"old"}; !equalStrings(got, want) { + t.Fatalf("second page = %v, want %v", got, want) + } + if second.HasMore || second.NextCursor != "" { + t.Fatalf("unexpected continuation after final page: %+v", second) + } +} + +func runtimeTaskIDs(tasks []types.RuntimeTaskInfo) []string { + ids := make([]string, 0, len(tasks)) + for _, task := range tasks { + ids = append(ids, task.ID) + } + return ids +} + +func equalStrings(left, right []string) bool { + if len(left) != len(right) { + return false + } + for i := range left { + if left[i] != right[i] { + return false + } + } + return true +} diff --git a/internal/types/interfaces/task_inspector.go b/internal/types/interfaces/task_inspector.go index 79d62b1f..222100d4 100644 --- a/internal/types/interfaces/task_inspector.go +++ b/internal/types/interfaces/task_inspector.go @@ -73,8 +73,9 @@ type RuntimeTaskInspector interface { ctx context.Context, queue string, state types.RuntimeTaskState, - page, pageSize int, - ) (tasks []types.RuntimeTaskInfo, supported bool, err error) + cursor string, + pageSize int, + ) (page types.RuntimeTaskPage, supported bool, err error) GetRuntimeTask(ctx context.Context, queue, taskID string) (task *types.RuntimeTaskInfo, supported bool, err error) RunRuntimeTask(ctx context.Context, queue, taskID string) (supported bool, err error) DeleteRuntimeTask(ctx context.Context, queue, taskID string) (supported bool, err error) diff --git a/internal/types/runtime_task.go b/internal/types/runtime_task.go index a79e068b..4eee48c0 100644 --- a/internal/types/runtime_task.go +++ b/internal/types/runtime_task.go @@ -1,6 +1,19 @@ package types -import "time" +import ( + "errors" + "time" +) + +var ( + // ErrInvalidRuntimeTaskCursor means the client supplied a cursor that was + // malformed or belonged to another queue/state view. + ErrInvalidRuntimeTaskCursor = errors.New("invalid runtime task cursor") + // ErrExpiredRuntimeTaskCursor means every task anchor retained in the + // cursor has left the selected live state. The caller should refresh from + // the first page rather than falling back to offset pagination. + ErrExpiredRuntimeTaskCursor = errors.New("expired runtime task cursor") +) // RuntimeTaskState is the stable operator-facing task lifecycle. It mirrors // the durable states exposed by asynq while keeping the HTTP API independent @@ -69,6 +82,14 @@ type RuntimeTaskInfo struct { KnowledgeCount int `json:"knowledge_count,omitempty"` } +// RuntimeTaskPage is one stable slice of the operator task list. NextCursor +// is opaque to HTTP clients and remains tied to the selected queue/state. +type RuntimeTaskPage struct { + Tasks []RuntimeTaskInfo + NextCursor string + HasMore bool +} + func (t RuntimeTaskInfo) Allows(action RuntimeTaskAction) bool { for _, allowed := range t.AllowedActions { if allowed == action {