feat(system): expand runtime queue task inspection and safe actions
Replace failed-only task views with state-aware runtime task listing, operator-safe cancel/run-now/delete actions, orphan detection, and multimodal queue cleanup for deleted knowledge rows.
This commit is contained in:
@@ -3,12 +3,14 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
filesvc "github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
@@ -138,16 +140,18 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
||||
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
|
||||
}
|
||||
|
||||
// Short-circuit when the parent knowledge has been cancelled by the user
|
||||
// or marked for deletion. Skip the VLM call entirely so we don't burn
|
||||
// model quota on already-aborted work.
|
||||
if k, kerr := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID); kerr == nil && k != nil {
|
||||
switch k.ParseStatus {
|
||||
case types.ParseStatusCancelled, types.ParseStatusDeleting:
|
||||
logger.Infof(ctx, "[ImageMultimodal] Knowledge %s aborted (%s), skipping image %s",
|
||||
payload.KnowledgeID, k.ParseStatus, payload.ImageURL)
|
||||
return nil
|
||||
}
|
||||
// Drop orphaned or user-aborted work before touching VLM. Missing
|
||||
// knowledge/KB rows are permanent failures — retrying only burns queue
|
||||
// capacity (asynq default MaxRetry=25 on legacy tasks).
|
||||
drop, dropErr := s.shouldDropOrphanedMultimodal(ctx, &payload)
|
||||
if dropErr != nil {
|
||||
return dropErr
|
||||
}
|
||||
if drop {
|
||||
logger.Infof(ctx,
|
||||
"[ImageMultimodal] Dropping task chunk=%s knowledge=%s kb=%s image=%s",
|
||||
payload.ChunkID, payload.KnowledgeID, payload.KnowledgeBaseID, payload.ImageURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Open a per-image subspan under the parent attempt's multimodal
|
||||
@@ -350,6 +354,41 @@ func (s *ImageMultimodalService) Handle(ctx context.Context, task *asynq.Task) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// shouldDropOrphanedMultimodal reports whether the task should exit without
|
||||
// retrying. True for user-cancelled/deleting knowledge, or when the parent
|
||||
// knowledge / knowledge-base row no longer exists (deleted while queue entries
|
||||
// survived).
|
||||
func (s *ImageMultimodalService) shouldDropOrphanedMultimodal(
|
||||
ctx context.Context, payload *types.ImageMultimodalPayload,
|
||||
) (bool, error) {
|
||||
if payload.KnowledgeID != "" && s.knowledgeRepo != nil {
|
||||
k, err := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID)
|
||||
if errors.Is(err, repository.ErrKnowledgeNotFound) {
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
switch k.ParseStatus {
|
||||
case types.ParseStatusCancelled, types.ParseStatusDeleting:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
if payload.KnowledgeBaseID != "" && s.kbService != nil {
|
||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
|
||||
if errors.Is(err, repository.ErrKnowledgeBaseNotFound) {
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if kb == nil {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// isFinalAsynqAttempt reports whether the current task context belongs to the
|
||||
// last retry attempt before asynq archives the task as a dead-letter. We use
|
||||
// this to flip multimodal finalize semantics: during normal retries we skip
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
type orphanKnowledgeRepo struct {
|
||||
interfaces.KnowledgeRepository
|
||||
knowledge *types.Knowledge
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *orphanKnowledgeRepo) GetKnowledgeByIDOnly(_ context.Context, _ string) (*types.Knowledge, error) {
|
||||
if r.err != nil {
|
||||
return nil, r.err
|
||||
}
|
||||
return r.knowledge, nil
|
||||
}
|
||||
|
||||
type orphanKBService struct {
|
||||
interfaces.KnowledgeBaseService
|
||||
kb *types.KnowledgeBase
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *orphanKBService) GetKnowledgeBaseByIDOnly(_ context.Context, _ string) (*types.KnowledgeBase, error) {
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
return s.kb, nil
|
||||
}
|
||||
|
||||
func TestShouldDropOrphanedMultimodal(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc := &ImageMultimodalService{}
|
||||
|
||||
drop, err := svc.shouldDropOrphanedMultimodal(context.Background(), &types.ImageMultimodalPayload{
|
||||
KnowledgeID: "missing",
|
||||
})
|
||||
if err != nil || drop {
|
||||
t.Fatalf("nil repo should not drop: drop=%v err=%v", drop, err)
|
||||
}
|
||||
|
||||
svc.knowledgeRepo = &orphanKnowledgeRepo{err: repository.ErrKnowledgeNotFound}
|
||||
drop, err = svc.shouldDropOrphanedMultimodal(context.Background(), &types.ImageMultimodalPayload{
|
||||
KnowledgeID: "missing",
|
||||
})
|
||||
if err != nil || !drop {
|
||||
t.Fatalf("missing knowledge should drop: drop=%v err=%v", drop, err)
|
||||
}
|
||||
|
||||
svc.knowledgeRepo = &orphanKnowledgeRepo{knowledge: &types.Knowledge{ParseStatus: types.ParseStatusCancelled}}
|
||||
drop, err = svc.shouldDropOrphanedMultimodal(context.Background(), &types.ImageMultimodalPayload{
|
||||
KnowledgeID: "cancelled",
|
||||
})
|
||||
if err != nil || !drop {
|
||||
t.Fatalf("cancelled knowledge should drop: drop=%v err=%v", drop, err)
|
||||
}
|
||||
|
||||
svc.knowledgeRepo = &orphanKnowledgeRepo{knowledge: &types.Knowledge{ParseStatus: types.ParseStatusProcessing}}
|
||||
svc.kbService = &orphanKBService{err: repository.ErrKnowledgeBaseNotFound}
|
||||
drop, err = svc.shouldDropOrphanedMultimodal(context.Background(), &types.ImageMultimodalPayload{
|
||||
KnowledgeID: "live",
|
||||
KnowledgeBaseID: "missing-kb",
|
||||
})
|
||||
if err != nil || !drop {
|
||||
t.Fatalf("missing kb should drop: drop=%v err=%v", drop, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageMultimodalHandleDropsMissingKnowledge(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc := &ImageMultimodalService{
|
||||
knowledgeRepo: &orphanKnowledgeRepo{err: repository.ErrKnowledgeNotFound},
|
||||
kbService: &orphanKBService{kb: &types.KnowledgeBase{ID: "kb-1"}},
|
||||
}
|
||||
payload, err := json.Marshal(types.ImageMultimodalPayload{
|
||||
TenantID: 1,
|
||||
KnowledgeID: "missing",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
ImageURL: "minio://bucket/img.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.Handle(context.Background(), asynq.NewTask(types.TypeImageMultimodal, payload)); err != nil {
|
||||
t.Fatalf("orphan task should succeed without retry: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageMultimodalHandlePropagatesTransientKnowledgeError(t *testing.T) {
|
||||
t.Parallel()
|
||||
dbErr := errors.New("db unavailable")
|
||||
svc := &ImageMultimodalService{
|
||||
knowledgeRepo: &orphanKnowledgeRepo{err: dbErr},
|
||||
kbService: &orphanKBService{kb: &types.KnowledgeBase{ID: "kb-1"}},
|
||||
}
|
||||
payload, err := json.Marshal(types.ImageMultimodalPayload{
|
||||
TenantID: 1,
|
||||
KnowledgeID: "k-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.Handle(context.Background(), asynq.NewTask(types.TypeImageMultimodal, payload)); !errors.Is(err, dbErr) {
|
||||
t.Fatalf("transient error should propagate: %v", err)
|
||||
}
|
||||
}
|
||||
+174
-62
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/database"
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
modellimiter "github.com/Tencent/WeKnora/internal/models/limiter"
|
||||
@@ -32,6 +33,10 @@ import (
|
||||
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
|
||||
)
|
||||
|
||||
type runtimeKnowledgeCanceller interface {
|
||||
CancelKnowledgeParse(ctx context.Context, knowledgeID string) (*types.Knowledge, error)
|
||||
}
|
||||
|
||||
// SystemHandler handles system-related requests
|
||||
type SystemHandler struct {
|
||||
cfg *config.Config
|
||||
@@ -49,6 +54,10 @@ type SystemHandler struct {
|
||||
// Lite mode), so GetRuntimeQueues can distinguish "no queues in this
|
||||
// deployment" from "queues are empty".
|
||||
taskInspector interfaces.TaskInspector
|
||||
// knowledgeSvc supplies the domain-level cancellation path used by the
|
||||
// runtime task console. It updates business state and tracing before queue
|
||||
// records are removed, unlike a raw Redis deletion.
|
||||
knowledgeSvc runtimeKnowledgeCanceller
|
||||
}
|
||||
|
||||
// NewSystemHandler creates a new system handler
|
||||
@@ -60,6 +69,7 @@ func NewSystemHandler(cfg *config.Config,
|
||||
systemSettingSvc interfaces.SystemSettingService,
|
||||
auditSvc interfaces.AuditLogService,
|
||||
taskInspector interfaces.TaskInspector,
|
||||
knowledgeSvc interfaces.KnowledgeService,
|
||||
) *SystemHandler {
|
||||
return &SystemHandler{
|
||||
cfg: cfg,
|
||||
@@ -70,6 +80,7 @@ func NewSystemHandler(cfg *config.Config,
|
||||
systemSettingSvc: systemSettingSvc,
|
||||
auditSvc: auditSvc,
|
||||
taskInspector: taskInspector,
|
||||
knowledgeSvc: knowledgeSvc,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1593,15 +1604,12 @@ func (h *SystemHandler) GetRuntimeQueues(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// RuntimeFailedTasksResponse is a page of tasks that exhausted automatic
|
||||
// retries. Available=false is used by Lite mode, where there is no durable
|
||||
// queue backend to inspect or mutate.
|
||||
type RuntimeFailedTasksResponse struct {
|
||||
Available bool `json:"available"`
|
||||
Tasks []types.FailedTaskInfo `json:"tasks"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
HasMore bool `json:"has_more"`
|
||||
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"`
|
||||
}
|
||||
|
||||
func isKnownRuntimeQueue(name string) bool {
|
||||
@@ -1613,7 +1621,7 @@ func isKnownRuntimeQueue(name string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func runtimeFailedTaskPage(c *gin.Context) (int, int) {
|
||||
func runtimeTaskPage(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
if page < 1 {
|
||||
@@ -1628,40 +1636,37 @@ func runtimeFailedTaskPage(c *gin.Context) (int, int) {
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
// ListRuntimeFailedTasks godoc
|
||||
// @Summary List tasks that stopped after exhausting automatic retries
|
||||
// @Tags System Admin
|
||||
// @Produce json
|
||||
// @Param queue path string true "Queue name"
|
||||
// @Success 200 {object} RuntimeFailedTasksResponse
|
||||
// @Router /system/admin/runtime/queues/{queue}/failed-tasks [get]
|
||||
func (h *SystemHandler) ListRuntimeFailedTasks(c *gin.Context) {
|
||||
func (h *SystemHandler) listRuntimeTasks(c *gin.Context, state types.RuntimeTaskState) {
|
||||
queue := c.Param("queue")
|
||||
if !isKnownRuntimeQueue(queue) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown task queue"})
|
||||
return
|
||||
}
|
||||
page, pageSize := runtimeFailedTaskPage(c)
|
||||
inspector, ok := h.taskInspector.(interfaces.FailedTaskInspector)
|
||||
if !state.Valid() {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown task state"})
|
||||
return
|
||||
}
|
||||
page, pageSize := runtimeTaskPage(c)
|
||||
inspector, ok := h.taskInspector.(interfaces.RuntimeTaskInspector)
|
||||
if !ok {
|
||||
c.JSON(http.StatusOK, RuntimeFailedTasksResponse{
|
||||
c.JSON(http.StatusOK, RuntimeTasksResponse{
|
||||
Available: false,
|
||||
Tasks: []types.FailedTaskInfo{},
|
||||
Tasks: []types.RuntimeTaskInfo{},
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
})
|
||||
return
|
||||
}
|
||||
tasks, supported, err := inspector.ListFailedTasks(c.Request.Context(), queue, page, pageSize)
|
||||
tasks, supported, err := inspector.ListRuntimeTasks(c.Request.Context(), queue, state, page, pageSize)
|
||||
if err != nil {
|
||||
logger.Errorf(c.Request.Context(), "list failed queue tasks queue=%s: %v", queue, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list stopped tasks"})
|
||||
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.FailedTaskInfo{}
|
||||
tasks = []types.RuntimeTaskInfo{}
|
||||
}
|
||||
c.JSON(http.StatusOK, RuntimeFailedTasksResponse{
|
||||
c.JSON(http.StatusOK, RuntimeTasksResponse{
|
||||
Available: supported,
|
||||
Tasks: tasks,
|
||||
Page: page,
|
||||
@@ -1670,29 +1675,55 @@ func (h *SystemHandler) ListRuntimeFailedTasks(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListRuntimeTasks returns one live task-state page for the unified operator
|
||||
// drawer. Raw task payloads are never included.
|
||||
// @Summary List runtime queue tasks by state
|
||||
// @Tags System Admin
|
||||
// @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 page_size query int false "Page size" default(20)
|
||||
// @Success 200 {object} RuntimeTasksResponse
|
||||
// @Router /system/admin/runtime/queues/{queue}/tasks [get]
|
||||
func (h *SystemHandler) ListRuntimeTasks(c *gin.Context) {
|
||||
h.listRuntimeTasks(c, types.RuntimeTaskState(c.Query("state")))
|
||||
}
|
||||
|
||||
func (h *SystemHandler) emitQueueTaskAudit(
|
||||
ctx context.Context,
|
||||
action types.AuditAction,
|
||||
queue, taskID string,
|
||||
extra map[string]string,
|
||||
) {
|
||||
if h.auditSvc == nil {
|
||||
return
|
||||
}
|
||||
actorID, _ := types.UserIDFromContext(ctx)
|
||||
details, _ := json.Marshal(map[string]string{"queue": queue, "task_id": taskID})
|
||||
detailMap := map[string]string{"queue": queue, "task_id": taskID}
|
||||
for key, value := range extra {
|
||||
detailMap[key] = value
|
||||
}
|
||||
details, _ := json.Marshal(detailMap)
|
||||
targetType := "queue_task"
|
||||
targetID := taskID
|
||||
if targetID == "" {
|
||||
targetType = "task_queue"
|
||||
targetID = queue
|
||||
}
|
||||
_ = h.auditSvc.Log(ctx, &types.AuditLog{
|
||||
TenantID: 0,
|
||||
ActorUserID: actorID,
|
||||
ActorRole: "system_admin",
|
||||
Action: action,
|
||||
TargetType: "queue_task",
|
||||
TargetID: taskID,
|
||||
TargetType: targetType,
|
||||
TargetID: targetID,
|
||||
Outcome: types.AuditOutcomeSuccess,
|
||||
Details: types.JSON(details),
|
||||
})
|
||||
}
|
||||
|
||||
func runtimeFailedTaskParams(c *gin.Context) (string, string, bool) {
|
||||
func runtimeTaskParams(c *gin.Context) (string, string, bool) {
|
||||
queue := c.Param("queue")
|
||||
taskID := c.Param("task_id")
|
||||
if !isKnownRuntimeQueue(queue) || taskID == "" {
|
||||
@@ -1702,56 +1733,137 @@ func runtimeFailedTaskParams(c *gin.Context) (string, string, bool) {
|
||||
return queue, taskID, true
|
||||
}
|
||||
|
||||
// RetryRuntimeFailedTask schedules one stopped task for one immediate manual
|
||||
// run. It does not reset the automatic retry counter.
|
||||
func (h *SystemHandler) RetryRuntimeFailedTask(c *gin.Context) {
|
||||
queue, taskID, ok := runtimeFailedTaskParams(c)
|
||||
func (h *SystemHandler) mutateRuntimeTask(c *gin.Context, action types.RuntimeTaskAction) {
|
||||
queue, taskID, ok := runtimeTaskParams(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
inspector, supported := h.taskInspector.(interfaces.FailedTaskInspector)
|
||||
inspector, supported := h.taskInspector.(interfaces.RuntimeTaskInspector)
|
||||
if !supported {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
|
||||
return
|
||||
}
|
||||
available, err := inspector.RetryFailedTask(c.Request.Context(), queue, taskID)
|
||||
task, available, err := inspector.GetRuntimeTask(c.Request.Context(), queue, taskID)
|
||||
if !available {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf(c.Request.Context(), "retry failed queue task queue=%s task=%s: %v", queue, taskID, err)
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Task is no longer available for retry"})
|
||||
if err != nil || task == nil {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Task is no longer available"})
|
||||
return
|
||||
}
|
||||
h.emitQueueTaskAudit(c.Request.Context(), types.AuditActionSystemQueueTaskRetried, queue, taskID)
|
||||
if !task.Allows(action) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Action is not allowed for the current task state"})
|
||||
return
|
||||
}
|
||||
|
||||
var auditAction types.AuditAction
|
||||
auditDetails := map[string]string{
|
||||
"task_type": task.Type,
|
||||
"from_state": string(task.State),
|
||||
"action": string(action),
|
||||
}
|
||||
switch action {
|
||||
case types.RuntimeTaskActionCancel:
|
||||
if h.knowledgeSvc == nil || task.TenantID == 0 || task.KnowledgeID == "" {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Business cancellation is unavailable"})
|
||||
return
|
||||
}
|
||||
cancelCtx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, task.TenantID)
|
||||
if _, err = h.knowledgeSvc.CancelKnowledgeParse(cancelCtx, task.KnowledgeID); err != nil {
|
||||
if isKnowledgeGone(err) {
|
||||
if h.purgeOrphanRuntimeTask(c.Request.Context(), inspector, queue, taskID, task.KnowledgeID) {
|
||||
logger.Warnf(c.Request.Context(),
|
||||
"cancel runtime queue task queue=%s task=%s: knowledge gone, purged queue record",
|
||||
queue, taskID)
|
||||
auditDetails["orphan_purge"] = "true"
|
||||
auditAction = types.AuditActionSystemQueueTaskCancelled
|
||||
break
|
||||
}
|
||||
}
|
||||
logger.Errorf(c.Request.Context(), "cancel runtime queue task queue=%s task=%s: %v", queue, taskID, err)
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Task can no longer be cancelled"})
|
||||
return
|
||||
}
|
||||
auditAction = types.AuditActionSystemQueueTaskCancelled
|
||||
case types.RuntimeTaskActionRunNow:
|
||||
available, err = inspector.RunRuntimeTask(c.Request.Context(), queue, taskID)
|
||||
if !available {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf(c.Request.Context(), "run queue task now queue=%s task=%s: %v", queue, taskID, err)
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Task is no longer available to run"})
|
||||
return
|
||||
}
|
||||
auditAction = types.AuditActionSystemQueueTaskRunNow
|
||||
case types.RuntimeTaskActionDelete:
|
||||
available, err = inspector.DeleteRuntimeTask(c.Request.Context(), queue, taskID)
|
||||
if !available {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf(c.Request.Context(), "delete queue task queue=%s task=%s: %v", queue, taskID, err)
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Task is no longer available for deletion"})
|
||||
return
|
||||
}
|
||||
auditAction = types.AuditActionSystemQueueTaskDeleted
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown task action"})
|
||||
return
|
||||
}
|
||||
h.emitQueueTaskAudit(c.Request.Context(), auditAction, queue, taskID, auditDetails)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// DeleteRuntimeFailedTask removes one stopped task from the queue archive. It
|
||||
// does not rerun the task or change its related business object.
|
||||
func (h *SystemHandler) DeleteRuntimeFailedTask(c *gin.Context) {
|
||||
queue, taskID, ok := runtimeFailedTaskParams(c)
|
||||
if !ok {
|
||||
return
|
||||
func isKnowledgeGone(err error) bool {
|
||||
if errors.Is(err, repository.ErrKnowledgeNotFound) {
|
||||
return true
|
||||
}
|
||||
inspector, supported := h.taskInspector.(interfaces.FailedTaskInspector)
|
||||
if !supported {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
|
||||
return
|
||||
var appErr *apperrors.AppError
|
||||
return errors.As(err, &appErr) && appErr.Code == apperrors.ErrNotFound
|
||||
}
|
||||
|
||||
// purgeOrphanRuntimeTask removes queue records for a task whose knowledge row
|
||||
// is already gone. Best-effort: CancelTasksForKnowledge sweeps every queue
|
||||
// state; ForceDeleteRuntimeTask is the fallback for the specific task ID.
|
||||
func (h *SystemHandler) purgeOrphanRuntimeTask(
|
||||
ctx context.Context,
|
||||
inspector interfaces.RuntimeTaskInspector,
|
||||
queue, taskID, knowledgeID string,
|
||||
) bool {
|
||||
if h.taskInspector != nil && knowledgeID != "" {
|
||||
deleted, _, err := h.taskInspector.CancelTasksForKnowledge(ctx, knowledgeID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "purge orphan tasks for knowledge %s: %v", knowledgeID, err)
|
||||
} else if deleted > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
available, err := inspector.DeleteFailedTask(c.Request.Context(), queue, taskID)
|
||||
if !available {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
|
||||
return
|
||||
supported, err := inspector.ForceDeleteRuntimeTask(ctx, queue, taskID)
|
||||
if !supported || err != nil {
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "force delete orphan task queue=%s task=%s: %v", queue, taskID, err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf(c.Request.Context(), "delete failed queue task queue=%s task=%s: %v", queue, taskID, err)
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Task is no longer available for deletion"})
|
||||
return
|
||||
}
|
||||
h.emitQueueTaskAudit(c.Request.Context(), types.AuditActionSystemQueueTaskDeleted, queue, taskID)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
return true
|
||||
}
|
||||
|
||||
// MutateRuntimeTask executes a backend-advertised action after re-reading the
|
||||
// current task state to close click/race windows.
|
||||
// @Summary Run a safe runtime task action
|
||||
// @Tags System Admin
|
||||
// @Produce json
|
||||
// @Param queue path string true "Queue name"
|
||||
// @Param task_id path string true "Task ID"
|
||||
// @Param action path string true "Action" Enums(cancel,run_now,delete)
|
||||
// @Success 200 {object} map[string]bool
|
||||
// @Router /system/admin/runtime/queues/{queue}/tasks/{task_id}/actions/{action} [post]
|
||||
func (h *SystemHandler) MutateRuntimeTask(c *gin.Context) {
|
||||
h.mutateRuntimeTask(c, types.RuntimeTaskAction(c.Param("action")))
|
||||
}
|
||||
|
||||
func (h *SystemHandler) ListSystemSettings(c *gin.Context) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -75,21 +76,79 @@ func (runtimeTestInspector) WorkerServerStats(context.Context) ([]types.WorkerSe
|
||||
}, true, nil
|
||||
}
|
||||
|
||||
type runtimeFailedTestInspector struct {
|
||||
type runtimeTaskTestInspector struct {
|
||||
runtimeTestInspector
|
||||
tasks []types.FailedTaskInfo
|
||||
retriedTask string
|
||||
deletedTask string
|
||||
mutatedQueue string
|
||||
tasks []types.RuntimeTaskInfo
|
||||
retriedTask string
|
||||
deletedTask string
|
||||
forceDeleted string
|
||||
cancelKnowledge string
|
||||
cancelDeleted int
|
||||
mutatedQueue string
|
||||
}
|
||||
|
||||
func (r *runtimeFailedTestInspector) ListFailedTasks(
|
||||
context.Context, string, int, int,
|
||||
) ([]types.FailedTaskInfo, bool, error) {
|
||||
func (r *runtimeTaskTestInspector) CancelTasksForKnowledge(
|
||||
_ context.Context, knowledgeID string,
|
||||
) (int, int, error) {
|
||||
r.cancelKnowledge = knowledgeID
|
||||
if r.cancelDeleted > 0 {
|
||||
return r.cancelDeleted, 0, nil
|
||||
}
|
||||
return 0, 0, nil
|
||||
}
|
||||
|
||||
type runtimeKnowledgeCancelTest struct {
|
||||
tenantID uint64
|
||||
knowledgeID string
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *runtimeKnowledgeCancelTest) CancelKnowledgeParse(
|
||||
ctx context.Context, knowledgeID string,
|
||||
) (*types.Knowledge, error) {
|
||||
r.tenantID, _ = ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
r.knowledgeID = knowledgeID
|
||||
if r.err != nil {
|
||||
return nil, r.err
|
||||
}
|
||||
return &types.Knowledge{ID: knowledgeID, TenantID: r.tenantID}, nil
|
||||
}
|
||||
|
||||
func (r *runtimeTaskTestInspector) ListRuntimeTasks(
|
||||
_ context.Context, _ string, state types.RuntimeTaskState, _, _ int,
|
||||
) ([]types.RuntimeTaskInfo, bool, error) {
|
||||
for i := range r.tasks {
|
||||
if r.tasks[i].State == "" {
|
||||
r.tasks[i].State = state
|
||||
}
|
||||
if r.tasks[i].AllowedActions == nil && state == types.RuntimeTaskArchived {
|
||||
r.tasks[i].AllowedActions = []types.RuntimeTaskAction{
|
||||
types.RuntimeTaskActionRunNow,
|
||||
types.RuntimeTaskActionDelete,
|
||||
}
|
||||
}
|
||||
}
|
||||
return r.tasks, true, nil
|
||||
}
|
||||
|
||||
func (r *runtimeFailedTestInspector) RetryFailedTask(
|
||||
func (r *runtimeTaskTestInspector) GetRuntimeTask(
|
||||
_ context.Context, queue, taskID string,
|
||||
) (*types.RuntimeTaskInfo, bool, error) {
|
||||
for i := range r.tasks {
|
||||
if r.tasks[i].ID == taskID {
|
||||
return &r.tasks[i], true, nil
|
||||
}
|
||||
}
|
||||
return &types.RuntimeTaskInfo{
|
||||
ID: taskID, Queue: queue, State: types.RuntimeTaskArchived,
|
||||
AllowedActions: []types.RuntimeTaskAction{
|
||||
types.RuntimeTaskActionRunNow,
|
||||
types.RuntimeTaskActionDelete,
|
||||
},
|
||||
}, true, nil
|
||||
}
|
||||
|
||||
func (r *runtimeTaskTestInspector) RunRuntimeTask(
|
||||
_ context.Context, queue, taskID string,
|
||||
) (bool, error) {
|
||||
r.mutatedQueue = queue
|
||||
@@ -97,7 +156,7 @@ func (r *runtimeFailedTestInspector) RetryFailedTask(
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *runtimeFailedTestInspector) DeleteFailedTask(
|
||||
func (r *runtimeTaskTestInspector) DeleteRuntimeTask(
|
||||
_ context.Context, queue, taskID string,
|
||||
) (bool, error) {
|
||||
r.mutatedQueue = queue
|
||||
@@ -105,6 +164,14 @@ func (r *runtimeFailedTestInspector) DeleteFailedTask(
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (r *runtimeTaskTestInspector) ForceDeleteRuntimeTask(
|
||||
_ context.Context, queue, taskID string,
|
||||
) (bool, error) {
|
||||
r.mutatedQueue = queue
|
||||
r.forceDeleted = taskID
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func TestGetRuntimeQueuesReportsIsolatedPoolCapacity(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := &SystemHandler{
|
||||
@@ -186,9 +253,9 @@ func TestGetRuntimeQueuesFallsBackFromInvalidHistoricalConcurrency(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRuntimeFailedTasksReturnsSafeTaskDetails(t *testing.T) {
|
||||
func TestListRuntimeTasksReturnsSafeTaskDetails(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
inspector := &runtimeFailedTestInspector{tasks: []types.FailedTaskInfo{{
|
||||
inspector := &runtimeTaskTestInspector{tasks: []types.RuntimeTaskInfo{{
|
||||
ID: "task-1",
|
||||
Queue: types.QueueDefault,
|
||||
Type: types.TypeDocumentProcess,
|
||||
@@ -202,13 +269,13 @@ func TestListRuntimeFailedTasksReturnsSafeTaskDetails(t *testing.T) {
|
||||
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/failed-tasks", nil)
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/system/admin/runtime/queues/default/tasks?state=archived", nil)
|
||||
|
||||
handler.ListRuntimeFailedTasks(ctx)
|
||||
handler.ListRuntimeTasks(ctx)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
var response RuntimeFailedTasksResponse
|
||||
var response RuntimeTasksResponse
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
@@ -220,9 +287,9 @@ func TestListRuntimeFailedTasksReturnsSafeTaskDetails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeFailedTaskMutationsDelegateToInspector(t *testing.T) {
|
||||
func TestRuntimeTaskMutationsDelegateToInspector(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
inspector := &runtimeFailedTestInspector{}
|
||||
inspector := &runtimeTaskTestInspector{}
|
||||
handler := &SystemHandler{taskInspector: inspector}
|
||||
|
||||
retryRecorder := httptest.NewRecorder()
|
||||
@@ -230,9 +297,10 @@ func TestRuntimeFailedTaskMutationsDelegateToInspector(t *testing.T) {
|
||||
retryCtx.Params = gin.Params{
|
||||
{Key: "queue", Value: types.QueueDefault},
|
||||
{Key: "task_id", Value: "task-1"},
|
||||
{Key: "action", Value: string(types.RuntimeTaskActionRunNow)},
|
||||
}
|
||||
retryCtx.Request = httptest.NewRequest(http.MethodPost, "/retry", nil)
|
||||
handler.RetryRuntimeFailedTask(retryCtx)
|
||||
handler.MutateRuntimeTask(retryCtx)
|
||||
if retryRecorder.Code != http.StatusOK || inspector.retriedTask != "task-1" {
|
||||
t.Fatalf("retry failed: status=%d inspector=%+v", retryRecorder.Code, inspector)
|
||||
}
|
||||
@@ -242,24 +310,94 @@ func TestRuntimeFailedTaskMutationsDelegateToInspector(t *testing.T) {
|
||||
deleteCtx.Params = gin.Params{
|
||||
{Key: "queue", Value: types.QueueDefault},
|
||||
{Key: "task_id", Value: "task-2"},
|
||||
{Key: "action", Value: string(types.RuntimeTaskActionDelete)},
|
||||
}
|
||||
deleteCtx.Request = httptest.NewRequest(http.MethodDelete, "/task-2", nil)
|
||||
handler.DeleteRuntimeFailedTask(deleteCtx)
|
||||
handler.MutateRuntimeTask(deleteCtx)
|
||||
if deleteRecorder.Code != http.StatusOK || inspector.deletedTask != "task-2" {
|
||||
t.Fatalf("delete failed: status=%d inspector=%+v", deleteRecorder.Code, inspector)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRuntimeFailedTasksRejectsUnknownQueue(t *testing.T) {
|
||||
func TestListRuntimeTasksRejectsUnknownQueue(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := &SystemHandler{taskInspector: &runtimeFailedTestInspector{}}
|
||||
handler := &SystemHandler{taskInspector: &runtimeTaskTestInspector{}}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Params = gin.Params{{Key: "queue", Value: "unknown"}}
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/failed-tasks", nil)
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/tasks?state=archived", nil)
|
||||
|
||||
handler.ListRuntimeFailedTasks(ctx)
|
||||
handler.ListRuntimeTasks(ctx)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRuntimeTasksRejectsUnknownState(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := &SystemHandler{taskInspector: &runtimeTaskTestInspector{}}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Params = gin.Params{{Key: "queue", Value: types.QueueDefault}}
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/tasks?state=unknown", nil)
|
||||
|
||||
handler.ListRuntimeTasks(ctx)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeTaskCancelUsesDomainCancellationWithTaskTenant(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
inspector := &runtimeTaskTestInspector{tasks: []types.RuntimeTaskInfo{{
|
||||
ID: "task-cancel", Queue: types.QueueDefault, Type: types.TypeDocumentProcess,
|
||||
State: types.RuntimeTaskActive, TenantID: 42, KnowledgeID: "knowledge-42",
|
||||
AllowedActions: []types.RuntimeTaskAction{types.RuntimeTaskActionCancel},
|
||||
}}}
|
||||
canceller := &runtimeKnowledgeCancelTest{}
|
||||
handler := &SystemHandler{taskInspector: inspector, knowledgeSvc: canceller}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Params = gin.Params{
|
||||
{Key: "queue", Value: types.QueueDefault},
|
||||
{Key: "task_id", Value: "task-cancel"},
|
||||
{Key: "action", Value: string(types.RuntimeTaskActionCancel)},
|
||||
}
|
||||
ctx.Request = httptest.NewRequest(http.MethodPost, "/cancel", nil)
|
||||
|
||||
handler.MutateRuntimeTask(ctx)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if canceller.tenantID != 42 || canceller.knowledgeID != "knowledge-42" {
|
||||
t.Fatalf("domain cancellation context mismatch: %+v", canceller)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeTaskCancelPurgesOrphanWhenKnowledgeGone(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
inspector := &runtimeTaskTestInspector{tasks: []types.RuntimeTaskInfo{{
|
||||
ID: "task-orphan", Queue: types.QueueMultimodal, Type: types.TypeImageMultimodal,
|
||||
State: types.RuntimeTaskRetry, TenantID: 42, KnowledgeID: "knowledge-gone",
|
||||
AllowedActions: []types.RuntimeTaskAction{types.RuntimeTaskActionCancel},
|
||||
}}}
|
||||
canceller := &runtimeKnowledgeCancelTest{err: repository.ErrKnowledgeNotFound}
|
||||
handler := &SystemHandler{taskInspector: inspector, knowledgeSvc: canceller}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Params = gin.Params{
|
||||
{Key: "queue", Value: types.QueueMultimodal},
|
||||
{Key: "task_id", Value: "task-orphan"},
|
||||
{Key: "action", Value: string(types.RuntimeTaskActionCancel)},
|
||||
}
|
||||
ctx.Request = httptest.NewRequest(http.MethodPost, "/cancel", nil)
|
||||
|
||||
handler.MutateRuntimeTask(ctx)
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if inspector.forceDeleted != "task-orphan" {
|
||||
t.Fatalf("expected force delete, got deleted=%q force=%q cancel=%q",
|
||||
inspector.deletedTask, inspector.forceDeleted, inspector.cancelKnowledge)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -899,14 +899,12 @@ func RegisterSystemAdminRoutes(
|
||||
adminRoutes.PUT("/settings/:key", handler.UpdateSystemSetting)
|
||||
adminRoutes.DELETE("/settings/:key", handler.ResetSystemSetting)
|
||||
|
||||
// Runtime observability: live asynq queue depths + worker pool
|
||||
// concurrency for the parse/wiki pools. Read-only snapshot for the
|
||||
// SystemAdmin runtime dashboard. Returns available=false in Lite
|
||||
// mode (no Redis) so the UI degrades gracefully.
|
||||
// Runtime operations: live asynq queue depths, safe task projections,
|
||||
// and state-checked task actions for the SystemAdmin dashboard. Lite
|
||||
// mode returns available=false.
|
||||
adminRoutes.GET("/runtime/queues", handler.GetRuntimeQueues)
|
||||
adminRoutes.GET("/runtime/queues/:queue/failed-tasks", handler.ListRuntimeFailedTasks)
|
||||
adminRoutes.POST("/runtime/queues/:queue/failed-tasks/:task_id/retry", handler.RetryRuntimeFailedTask)
|
||||
adminRoutes.DELETE("/runtime/queues/:queue/failed-tasks/:task_id", handler.DeleteRuntimeFailedTask)
|
||||
adminRoutes.GET("/runtime/queues/:queue/tasks", handler.ListRuntimeTasks)
|
||||
adminRoutes.POST("/runtime/queues/:queue/tasks/:task_id/actions/:action", handler.MutateRuntimeTask)
|
||||
|
||||
// Bulk action — write the current default-quota setting onto
|
||||
// every existing tenant. Lives under /tenants instead of
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -46,12 +47,21 @@ type knowledgeIDProbe struct {
|
||||
KnowledgeID string `json:"knowledge_id,omitempty"`
|
||||
}
|
||||
|
||||
type failedTaskPayloadProbe struct {
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
|
||||
KBID string `json:"kb_id,omitempty"`
|
||||
KnowledgeID string `json:"knowledge_id,omitempty"`
|
||||
TaskID string `json:"task_id,omitempty"`
|
||||
type runtimeTaskPayloadProbe struct {
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
|
||||
KBID string `json:"kb_id,omitempty"`
|
||||
KnowledgeID string `json:"knowledge_id,omitempty"`
|
||||
TaskID string `json:"task_id,omitempty"`
|
||||
SourceID string `json:"source_id,omitempty"`
|
||||
TargetID string `json:"target_id,omitempty"`
|
||||
SourceKBID string `json:"source_kb_id,omitempty"`
|
||||
TargetKBID string `json:"target_kb_id,omitempty"`
|
||||
DataSourceID string `json:"data_source_id,omitempty"`
|
||||
SyncLogID string `json:"sync_log_id,omitempty"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
EnqueuedAt int64 `json:"enqueued_at,omitempty"`
|
||||
CreatedAt int64 `json:"created_at,omitempty"`
|
||||
}
|
||||
|
||||
// queuesScanned is the fixed set of queue names this codebase enqueues
|
||||
@@ -192,17 +202,165 @@ func (a *asynqTaskInspector) QueueStats(
|
||||
return stats, true, nil
|
||||
}
|
||||
|
||||
// ListFailedTasks returns archived tasks newest-first. Only routing metadata is
|
||||
// projected from the payload so the SystemAdmin dashboard never exposes raw
|
||||
// document content or connector secrets.
|
||||
func (a *asynqTaskInspector) ListFailedTasks(
|
||||
type runtimeWorkerMetadata struct {
|
||||
started time.Time
|
||||
worker string
|
||||
}
|
||||
|
||||
func runtimeTaskState(state asynq.TaskState) (types.RuntimeTaskState, error) {
|
||||
switch state {
|
||||
case asynq.TaskStatePending:
|
||||
return types.RuntimeTaskPending, nil
|
||||
case asynq.TaskStateActive:
|
||||
return types.RuntimeTaskActive, nil
|
||||
case asynq.TaskStateScheduled:
|
||||
return types.RuntimeTaskScheduled, nil
|
||||
case asynq.TaskStateRetry:
|
||||
return types.RuntimeTaskRetry, nil
|
||||
case asynq.TaskStateArchived:
|
||||
return types.RuntimeTaskArchived, nil
|
||||
case asynq.TaskStateCompleted:
|
||||
return types.RuntimeTaskCompleted, nil
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported runtime task state %v", state)
|
||||
}
|
||||
}
|
||||
|
||||
func runtimeTaskTime(value time.Time) *time.Time {
|
||||
if value.IsZero() {
|
||||
return nil
|
||||
}
|
||||
copy := value
|
||||
return ©
|
||||
}
|
||||
|
||||
func runtimePayloadTime(value int64) *time.Time {
|
||||
if value <= 0 {
|
||||
return nil
|
||||
}
|
||||
// Payload timestamps in this repository are seconds today. Accept the
|
||||
// common higher-precision Unix forms as well for connector-originated jobs.
|
||||
var parsed time.Time
|
||||
if value > 100_000_000_000_000_000 {
|
||||
parsed = time.Unix(0, value)
|
||||
} else if value > 100_000_000_000_000 {
|
||||
parsed = time.UnixMicro(value)
|
||||
} else if value > 10_000_000_000 {
|
||||
parsed = time.UnixMilli(value)
|
||||
} else {
|
||||
parsed = time.Unix(value, 0)
|
||||
}
|
||||
return &parsed
|
||||
}
|
||||
|
||||
func runtimeTaskActions(info types.RuntimeTaskInfo) []types.RuntimeTaskAction {
|
||||
actions := make([]types.RuntimeTaskAction, 0, 3)
|
||||
if _, cancellable := taskTypesForKnowledgeCancel[info.Type]; cancellable &&
|
||||
info.TenantID > 0 && info.KnowledgeID != "" {
|
||||
switch info.State {
|
||||
case types.RuntimeTaskPending, types.RuntimeTaskActive,
|
||||
types.RuntimeTaskScheduled, types.RuntimeTaskRetry:
|
||||
actions = append(actions, types.RuntimeTaskActionCancel)
|
||||
}
|
||||
}
|
||||
switch info.State {
|
||||
case types.RuntimeTaskScheduled, types.RuntimeTaskRetry:
|
||||
actions = append(actions, types.RuntimeTaskActionRunNow)
|
||||
case types.RuntimeTaskArchived:
|
||||
actions = append(actions, types.RuntimeTaskActionRunNow, types.RuntimeTaskActionDelete)
|
||||
}
|
||||
return actions
|
||||
}
|
||||
|
||||
func projectRuntimeTask(task *asynq.TaskInfo, worker runtimeWorkerMetadata) (types.RuntimeTaskInfo, error) {
|
||||
state, err := runtimeTaskState(task.State)
|
||||
if err != nil {
|
||||
return types.RuntimeTaskInfo{}, err
|
||||
}
|
||||
probe := runtimeTaskPayloadProbe{}
|
||||
_ = json.Unmarshal(task.Payload, &probe)
|
||||
kbID := probe.KnowledgeBaseID
|
||||
if kbID == "" {
|
||||
kbID = probe.KBID
|
||||
}
|
||||
enqueuedAt := probe.EnqueuedAt
|
||||
if enqueuedAt == 0 {
|
||||
enqueuedAt = probe.CreatedAt
|
||||
}
|
||||
info := types.RuntimeTaskInfo{
|
||||
ID: task.ID,
|
||||
Queue: task.Queue,
|
||||
Type: task.Type,
|
||||
State: state,
|
||||
LastError: task.LastErr,
|
||||
LastFailedAt: runtimeTaskTime(task.LastFailedAt),
|
||||
NextProcessAt: runtimeTaskTime(task.NextProcessAt),
|
||||
StartedAt: runtimeTaskTime(worker.started),
|
||||
CompletedAt: runtimeTaskTime(task.CompletedAt),
|
||||
Deadline: runtimeTaskTime(task.Deadline),
|
||||
EnqueuedAt: runtimePayloadTime(enqueuedAt),
|
||||
Retried: task.Retried,
|
||||
MaxRetry: task.MaxRetry,
|
||||
IsOrphaned: task.IsOrphaned,
|
||||
Worker: worker.worker,
|
||||
TenantID: probe.TenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
KnowledgeID: probe.KnowledgeID,
|
||||
TaskID: probe.TaskID,
|
||||
SourceID: probe.SourceID,
|
||||
TargetID: probe.TargetID,
|
||||
SourceKBID: probe.SourceKBID,
|
||||
TargetKBID: probe.TargetKBID,
|
||||
DataSourceID: probe.DataSourceID,
|
||||
SyncLogID: probe.SyncLogID,
|
||||
KnowledgeCount: len(probe.KnowledgeIDs),
|
||||
}
|
||||
info.AllowedActions = runtimeTaskActions(info)
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (a *asynqTaskInspector) activeWorkerMetadata() map[string]runtimeWorkerMetadata {
|
||||
result := make(map[string]runtimeWorkerMetadata)
|
||||
servers, err := a.inspector.Servers()
|
||||
if err != nil {
|
||||
return result
|
||||
}
|
||||
for _, server := range servers {
|
||||
if server == nil {
|
||||
continue
|
||||
}
|
||||
workerName := server.Host
|
||||
if server.PID > 0 {
|
||||
workerName = fmt.Sprintf("%s:%d", server.Host, server.PID)
|
||||
}
|
||||
for _, worker := range server.ActiveWorkers {
|
||||
if worker == nil {
|
||||
continue
|
||||
}
|
||||
result[worker.Queue+"\x00"+worker.TaskID] = runtimeWorkerMetadata{
|
||||
started: worker.Started,
|
||||
worker: workerName,
|
||||
}
|
||||
}
|
||||
}
|
||||
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.
|
||||
func (a *asynqTaskInspector) ListRuntimeTasks(
|
||||
ctx context.Context,
|
||||
queue string,
|
||||
state types.RuntimeTaskState,
|
||||
page, pageSize int,
|
||||
) ([]types.FailedTaskInfo, bool, error) {
|
||||
) ([]types.RuntimeTaskInfo, bool, error) {
|
||||
if a == nil || a.inspector == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
if !state.Valid() {
|
||||
return nil, true, fmt.Errorf("unsupported runtime task state %q", state)
|
||||
}
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
@@ -212,79 +370,104 @@ func (a *asynqTaskInspector) ListFailedTasks(
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
tasks, err := a.inspector.ListArchivedTasks(queue, asynq.Page(page), asynq.PageSize(pageSize))
|
||||
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.FailedTaskInfo{}, true, nil
|
||||
return []types.RuntimeTaskInfo{}, true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
result := make([]types.FailedTaskInfo, 0, len(tasks))
|
||||
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
|
||||
}
|
||||
probe := failedTaskPayloadProbe{}
|
||||
_ = json.Unmarshal(task.Payload, &probe)
|
||||
kbID := probe.KnowledgeBaseID
|
||||
if kbID == "" {
|
||||
kbID = probe.KBID
|
||||
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
|
||||
}
|
||||
result = append(result, types.FailedTaskInfo{
|
||||
ID: task.ID,
|
||||
Queue: task.Queue,
|
||||
Type: task.Type,
|
||||
LastError: task.LastErr,
|
||||
LastFailedAt: task.LastFailedAt,
|
||||
Retried: task.Retried,
|
||||
MaxRetry: task.MaxRetry,
|
||||
TenantID: probe.TenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
KnowledgeID: probe.KnowledgeID,
|
||||
TaskID: probe.TaskID,
|
||||
})
|
||||
result = append(result, info)
|
||||
}
|
||||
return result, true, nil
|
||||
}
|
||||
|
||||
// RetryFailedTask schedules one archived task for one immediate manual run.
|
||||
// Asynq deliberately preserves the retry counter, so a repeated failure is
|
||||
// archived again instead of silently starting a fresh automatic retry cycle.
|
||||
func (a *asynqTaskInspector) RetryFailedTask(
|
||||
ctx context.Context,
|
||||
queue, taskID string,
|
||||
) (bool, error) {
|
||||
func (a *asynqTaskInspector) GetRuntimeTask(
|
||||
ctx context.Context, queue, taskID string,
|
||||
) (*types.RuntimeTaskInfo, bool, error) {
|
||||
if a == nil || a.inspector == nil {
|
||||
return nil, false, nil
|
||||
}
|
||||
task, err := a.inspector.GetTaskInfo(queue, taskID)
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
workers := map[string]runtimeWorkerMetadata{}
|
||||
if task.State == asynq.TaskStateActive {
|
||||
workers = a.activeWorkerMetadata()
|
||||
}
|
||||
info, err := projectRuntimeTask(task, workers[task.Queue+"\x00"+task.ID])
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
return &info, true, nil
|
||||
}
|
||||
|
||||
// RunRuntimeTask moves a scheduled, retry, or archived task to pending. Asynq
|
||||
// deliberately preserves the retry counter.
|
||||
func (a *asynqTaskInspector) RunRuntimeTask(ctx context.Context, queue, taskID string) (bool, error) {
|
||||
if a == nil || a.inspector == nil {
|
||||
return false, nil
|
||||
}
|
||||
if err := a.ensureTaskArchived(queue, taskID); err != nil {
|
||||
task, _, err := a.GetRuntimeTask(ctx, queue, taskID)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
if task == nil || !task.Allows(types.RuntimeTaskActionRunNow) {
|
||||
return true, fmt.Errorf("task %s in queue %s cannot run now", taskID, queue)
|
||||
}
|
||||
return true, a.inspector.RunTask(queue, taskID)
|
||||
}
|
||||
|
||||
func (a *asynqTaskInspector) DeleteFailedTask(
|
||||
ctx context.Context,
|
||||
queue, taskID string,
|
||||
) (bool, error) {
|
||||
func (a *asynqTaskInspector) DeleteRuntimeTask(ctx context.Context, queue, taskID string) (bool, error) {
|
||||
if a == nil || a.inspector == nil {
|
||||
return false, nil
|
||||
}
|
||||
if err := a.ensureTaskArchived(queue, taskID); err != nil {
|
||||
task, _, err := a.GetRuntimeTask(ctx, queue, taskID)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
if task == nil || !task.Allows(types.RuntimeTaskActionDelete) {
|
||||
return true, fmt.Errorf("task %s in queue %s cannot be deleted", taskID, queue)
|
||||
}
|
||||
return true, a.inspector.DeleteTask(queue, taskID)
|
||||
}
|
||||
|
||||
func (a *asynqTaskInspector) ensureTaskArchived(queue, taskID string) error {
|
||||
task, err := a.inspector.GetTaskInfo(queue, taskID)
|
||||
if err != nil {
|
||||
return err
|
||||
func (a *asynqTaskInspector) ForceDeleteRuntimeTask(ctx context.Context, queue, taskID string) (bool, error) {
|
||||
if a == nil || a.inspector == nil {
|
||||
return false, nil
|
||||
}
|
||||
if task.State != asynq.TaskStateArchived {
|
||||
return fmt.Errorf("task %s in queue %s is no longer archived", taskID, queue)
|
||||
}
|
||||
return nil
|
||||
return true, a.inspector.DeleteTask(queue, taskID)
|
||||
}
|
||||
|
||||
func (a *asynqTaskInspector) WorkerServerStats(
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
func TestProjectRuntimeTaskRedactsPayloadAndBuildsSafeActions(t *testing.T) {
|
||||
payload, err := json.Marshal(map[string]any{
|
||||
"tenant_id": 42,
|
||||
"knowledge_base_id": "kb-1",
|
||||
"knowledge_id": "knowledge-1",
|
||||
"file_url": "secret://signed-document-url",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started := time.Unix(1_700_000_000, 0)
|
||||
info, err := projectRuntimeTask(&asynq.TaskInfo{
|
||||
ID: "task-1", Queue: types.QueueDefault, Type: types.TypeDocumentProcess,
|
||||
Payload: payload, State: asynq.TaskStateActive, MaxRetry: 3, Retried: 1,
|
||||
}, runtimeWorkerMetadata{started: started, worker: "worker-a:123"})
|
||||
if err != nil {
|
||||
t.Fatalf("project task: %v", err)
|
||||
}
|
||||
if info.State != types.RuntimeTaskActive || info.TenantID != 42 ||
|
||||
info.KnowledgeBaseID != "kb-1" || info.KnowledgeID != "knowledge-1" {
|
||||
t.Fatalf("safe routing metadata missing: %+v", info)
|
||||
}
|
||||
if info.StartedAt == nil || !info.StartedAt.Equal(started) || info.Worker != "worker-a:123" {
|
||||
t.Fatalf("worker metadata missing: %+v", info)
|
||||
}
|
||||
if len(info.AllowedActions) != 1 || info.AllowedActions[0] != types.RuntimeTaskActionCancel {
|
||||
t.Fatalf("active document actions = %v", info.AllowedActions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectRuntimeTaskActionsFollowCurrentState(t *testing.T) {
|
||||
payload := []byte(`{"tenant_id":7,"knowledge_id":"knowledge-7"}`)
|
||||
cases := []struct {
|
||||
state asynq.TaskState
|
||||
want []types.RuntimeTaskAction
|
||||
}{
|
||||
{asynq.TaskStateScheduled, []types.RuntimeTaskAction{types.RuntimeTaskActionCancel, types.RuntimeTaskActionRunNow}},
|
||||
{asynq.TaskStateRetry, []types.RuntimeTaskAction{types.RuntimeTaskActionCancel, types.RuntimeTaskActionRunNow}},
|
||||
{asynq.TaskStateArchived, []types.RuntimeTaskAction{types.RuntimeTaskActionRunNow, types.RuntimeTaskActionDelete}},
|
||||
{asynq.TaskStateCompleted, []types.RuntimeTaskAction{}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
info, err := projectRuntimeTask(&asynq.TaskInfo{
|
||||
ID: "task", Queue: types.QueueDefault, Type: types.TypeDocumentProcess,
|
||||
Payload: payload, State: tc.state,
|
||||
}, runtimeWorkerMetadata{})
|
||||
if err != nil {
|
||||
t.Fatalf("state %v: %v", tc.state, err)
|
||||
}
|
||||
if len(info.AllowedActions) != len(tc.want) {
|
||||
t.Fatalf("state %v actions = %v, want %v", tc.state, info.AllowedActions, tc.want)
|
||||
}
|
||||
for i := range tc.want {
|
||||
if info.AllowedActions[i] != tc.want[i] {
|
||||
t.Fatalf("state %v actions = %v, want %v", tc.state, info.AllowedActions, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectRuntimeTaskUsesAllowListedBatchMetadata(t *testing.T) {
|
||||
payload := []byte(`{
|
||||
"tenant_id":9,
|
||||
"task_id":"move-1",
|
||||
"source_kb_id":"source-kb",
|
||||
"target_kb_id":"target-kb",
|
||||
"knowledge_ids":["a","b"],
|
||||
"created_at":1700000000,
|
||||
"content":"must-not-be-projected"
|
||||
}`)
|
||||
info, err := projectRuntimeTask(&asynq.TaskInfo{
|
||||
ID: "task-move", Queue: types.QueueMaintenance, Type: types.TypeKnowledgeMove,
|
||||
Payload: payload, State: asynq.TaskStatePending,
|
||||
}, runtimeWorkerMetadata{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.TaskID != "move-1" || info.SourceKBID != "source-kb" ||
|
||||
info.TargetKBID != "target-kb" || info.KnowledgeCount != 2 || info.EnqueuedAt == nil {
|
||||
t.Fatalf("batch projection mismatch: %+v", info)
|
||||
}
|
||||
if len(info.AllowedActions) != 0 {
|
||||
t.Fatalf("generic maintenance task must not expose raw deletion: %v", info.AllowedActions)
|
||||
}
|
||||
}
|
||||
@@ -125,8 +125,10 @@ const (
|
||||
// Runtime queue mutations are privileged SystemAdmin actions. Retrying an
|
||||
// archived task can repeat its original side effects; deleting one removes
|
||||
// the Redis failure record. Both must leave a platform audit trail.
|
||||
AuditActionSystemQueueTaskRetried AuditAction = "system.queue_task_retried"
|
||||
AuditActionSystemQueueTaskDeleted AuditAction = "system.queue_task_deleted"
|
||||
AuditActionSystemQueueTaskRetried AuditAction = "system.queue_task_retried"
|
||||
AuditActionSystemQueueTaskDeleted AuditAction = "system.queue_task_deleted"
|
||||
AuditActionSystemQueueTaskRunNow AuditAction = "system.queue_task_run_now"
|
||||
AuditActionSystemQueueTaskCancelled AuditAction = "system.queue_task_cancelled"
|
||||
)
|
||||
|
||||
// AuditOutcome distinguishes successful mutations from middleware-level
|
||||
|
||||
@@ -40,6 +40,8 @@ func TestAuditAction_DotNamespaceConvention(t *testing.T) {
|
||||
AuditActionSystemUserPasswordReset,
|
||||
AuditActionSystemQueueTaskRetried,
|
||||
AuditActionSystemQueueTaskDeleted,
|
||||
AuditActionSystemQueueTaskRunNow,
|
||||
AuditActionSystemQueueTaskCancelled,
|
||||
}
|
||||
for _, a := range all {
|
||||
s := string(a)
|
||||
@@ -124,6 +126,8 @@ func TestAuditAction_NoCollisionsAcrossNamespaces(t *testing.T) {
|
||||
register("AuditActionSystemUserPasswordReset", AuditActionSystemUserPasswordReset)
|
||||
register("AuditActionSystemQueueTaskRetried", AuditActionSystemQueueTaskRetried)
|
||||
register("AuditActionSystemQueueTaskDeleted", AuditActionSystemQueueTaskDeleted)
|
||||
register("AuditActionSystemQueueTaskRunNow", AuditActionSystemQueueTaskRunNow)
|
||||
register("AuditActionSystemQueueTaskCancelled", AuditActionSystemQueueTaskCancelled)
|
||||
}
|
||||
|
||||
// TestAuditAction_SystemNamespacePrefix pins the system.* actions
|
||||
@@ -140,6 +144,8 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {
|
||||
AuditActionSystemUserPasswordReset,
|
||||
AuditActionSystemQueueTaskRetried,
|
||||
AuditActionSystemQueueTaskDeleted,
|
||||
AuditActionSystemQueueTaskRunNow,
|
||||
AuditActionSystemQueueTaskCancelled,
|
||||
}
|
||||
for _, a := range cases {
|
||||
assert.True(t,
|
||||
@@ -164,6 +170,8 @@ func TestAuditAction_SystemWireValues(t *testing.T) {
|
||||
{AuditActionSystemUserPasswordReset, "system.user_password_reset"},
|
||||
{AuditActionSystemQueueTaskRetried, "system.queue_task_retried"},
|
||||
{AuditActionSystemQueueTaskDeleted, "system.queue_task_deleted"},
|
||||
{AuditActionSystemQueueTaskRunNow, "system.queue_task_run_now"},
|
||||
{AuditActionSystemQueueTaskCancelled, "system.queue_task_cancelled"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
assert.Equal(t, c.wire, string(c.constant))
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package types
|
||||
|
||||
import "time"
|
||||
|
||||
// FailedTaskInfo is the operator-facing projection of an asynq task that
|
||||
// exhausted its automatic retry budget. Payloads are intentionally not
|
||||
// exposed by the SystemAdmin API: they may contain document content or
|
||||
// connector credentials. Only stable routing identifiers are copied out.
|
||||
type FailedTaskInfo struct {
|
||||
ID string `json:"id"`
|
||||
Queue string `json:"queue"`
|
||||
Type string `json:"type"`
|
||||
LastError string `json:"last_error"`
|
||||
LastFailedAt time.Time `json:"last_failed_at"`
|
||||
Retried int `json:"retried"`
|
||||
MaxRetry int `json:"max_retry"`
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
|
||||
KnowledgeID string `json:"knowledge_id,omitempty"`
|
||||
TaskID string `json:"task_id,omitempty"`
|
||||
}
|
||||
@@ -64,16 +64,22 @@ type TaskInspector interface {
|
||||
WorkerServerStats(ctx context.Context) (stats []types.WorkerServerStat, supported bool, err error)
|
||||
}
|
||||
|
||||
// FailedTaskInspector is the optional operator surface implemented by queue
|
||||
// backends that retain tasks after their automatic retry budget is exhausted.
|
||||
// It is separate from TaskInspector so Lite-mode and test implementations that
|
||||
// only support cancellation/metrics do not need to pretend failed tasks exist.
|
||||
type FailedTaskInspector interface {
|
||||
ListFailedTasks(
|
||||
// RuntimeTaskInspector is the optional operator surface implemented by queue
|
||||
// backends that retain inspectable task state. It is separate from
|
||||
// TaskInspector so Lite mode and light-weight tests do not need to implement
|
||||
// queue mutations.
|
||||
type RuntimeTaskInspector interface {
|
||||
ListRuntimeTasks(
|
||||
ctx context.Context,
|
||||
queue string,
|
||||
state types.RuntimeTaskState,
|
||||
page, pageSize int,
|
||||
) (tasks []types.FailedTaskInfo, supported bool, err error)
|
||||
RetryFailedTask(ctx context.Context, queue, taskID string) (supported bool, err error)
|
||||
DeleteFailedTask(ctx context.Context, queue, taskID string) (supported bool, err error)
|
||||
) (tasks []types.RuntimeTaskInfo, 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)
|
||||
// ForceDeleteRuntimeTask removes a queue record without checking the
|
||||
// operator-facing AllowedActions. Used when the business row is already
|
||||
// gone but a retry/pending task survived (orphan cleanup).
|
||||
ForceDeleteRuntimeTask(ctx context.Context, queue, taskID string) (supported bool, err error)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package types
|
||||
|
||||
import "time"
|
||||
|
||||
// RuntimeTaskState is the stable operator-facing task lifecycle. It mirrors
|
||||
// the durable states exposed by asynq while keeping the HTTP API independent
|
||||
// from the queue library's Go enum.
|
||||
type RuntimeTaskState string
|
||||
|
||||
const (
|
||||
RuntimeTaskPending RuntimeTaskState = "pending"
|
||||
RuntimeTaskActive RuntimeTaskState = "active"
|
||||
RuntimeTaskScheduled RuntimeTaskState = "scheduled"
|
||||
RuntimeTaskRetry RuntimeTaskState = "retry"
|
||||
RuntimeTaskArchived RuntimeTaskState = "archived"
|
||||
RuntimeTaskCompleted RuntimeTaskState = "completed"
|
||||
)
|
||||
|
||||
func (s RuntimeTaskState) Valid() bool {
|
||||
switch s {
|
||||
case RuntimeTaskPending, RuntimeTaskActive, RuntimeTaskScheduled,
|
||||
RuntimeTaskRetry, RuntimeTaskArchived, RuntimeTaskCompleted:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// RuntimeTaskAction is returned by the backend for every task. The frontend
|
||||
// renders only these actions instead of inferring safety from the state.
|
||||
type RuntimeTaskAction string
|
||||
|
||||
const (
|
||||
RuntimeTaskActionCancel RuntimeTaskAction = "cancel"
|
||||
RuntimeTaskActionRunNow RuntimeTaskAction = "run_now"
|
||||
RuntimeTaskActionDelete RuntimeTaskAction = "delete"
|
||||
)
|
||||
|
||||
// RuntimeTaskInfo is the safe SystemAdmin projection of one queue task.
|
||||
// Raw payloads and results are deliberately excluded because they may contain
|
||||
// document content, signed object URLs, or connector credentials.
|
||||
type RuntimeTaskInfo struct {
|
||||
ID string `json:"id"`
|
||||
Queue string `json:"queue"`
|
||||
Type string `json:"type"`
|
||||
State RuntimeTaskState `json:"state"`
|
||||
AllowedActions []RuntimeTaskAction `json:"allowed_actions"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
LastFailedAt *time.Time `json:"last_failed_at,omitempty"`
|
||||
NextProcessAt *time.Time `json:"next_process_at,omitempty"`
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
Deadline *time.Time `json:"deadline,omitempty"`
|
||||
EnqueuedAt *time.Time `json:"enqueued_at,omitempty"`
|
||||
Retried int `json:"retried"`
|
||||
MaxRetry int `json:"max_retry"`
|
||||
IsOrphaned bool `json:"is_orphaned,omitempty"`
|
||||
Worker string `json:"worker,omitempty"`
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
|
||||
KnowledgeID string `json:"knowledge_id,omitempty"`
|
||||
TaskID string `json:"task_id,omitempty"`
|
||||
SourceID string `json:"source_id,omitempty"`
|
||||
TargetID string `json:"target_id,omitempty"`
|
||||
SourceKBID string `json:"source_kb_id,omitempty"`
|
||||
TargetKBID string `json:"target_kb_id,omitempty"`
|
||||
DataSourceID string `json:"data_source_id,omitempty"`
|
||||
SyncLogID string `json:"sync_log_id,omitempty"`
|
||||
KnowledgeCount int `json:"knowledge_count,omitempty"`
|
||||
}
|
||||
|
||||
func (t RuntimeTaskInfo) Allows(action RuntimeTaskAction) bool {
|
||||
for _, allowed := range t.AllowedActions {
|
||||
if allowed == action {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user