feat(runtime): add bulk purge for archived queue tasks and chat_attachment i18n

Operators can clear all finally-failed tasks in one queue from the runtime
drawer, with audit logging and scoped API access. Also localize the
chat_attachment queue label in the runtime queue details table.
This commit is contained in:
wizardchen
2026-07-23 16:51:09 +08:00
committed by lyingbug
parent de7507cc96
commit 6c794f64cf
18 changed files with 307 additions and 9 deletions
+37
View File
@@ -2066,6 +2066,43 @@ func (h *SystemHandler) MutateRuntimeTask(c *gin.Context) {
h.mutateRuntimeTask(c, types.RuntimeTaskAction(c.Param("action")))
}
// PurgeArchivedRuntimeTasks clears every archived (finally-failed) task in one
// queue. It only touches the archived dead-letter set — live pending/active/
// scheduled/retry tasks are untouched — and mirrors single-record delete
// semantics by leaving business state as-is (archived tasks already had their
// document status flipped to "failed" on their last retry).
// @Summary Purge all archived tasks in a queue
// @Tags System Admin
// @Produce json
// @Param queue path string true "Queue name"
// @Success 200 {object} map[string]interface{}
// @Router /system/admin/runtime/queues/{queue}/archived [delete]
func (h *SystemHandler) PurgeArchivedRuntimeTasks(c *gin.Context) {
queue := c.Param("queue")
if !isKnownRuntimeQueue(queue) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid queue"})
return
}
inspector, supported := h.taskInspector.(interfaces.RuntimeTaskInspector)
if !supported {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
return
}
deleted, available, err := inspector.PurgeArchivedRuntimeTasks(c.Request.Context(), queue)
if !available {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Task queue is unavailable"})
return
}
if err != nil {
logger.Errorf(c.Request.Context(), "purge archived queue tasks queue=%s: %v", queue, err)
c.JSON(http.StatusConflict, gin.H{"error": "Archived tasks could not be purged"})
return
}
h.emitQueueTaskAudit(c.Request.Context(), types.AuditActionSystemQueueArchivedPurged, queue, "",
map[string]string{"deleted": strconv.Itoa(deleted)})
c.JSON(http.StatusOK, gin.H{"success": true, "deleted": deleted})
}
func (h *SystemHandler) ListSystemSettings(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
rows, err := h.systemSettingSvc.List(ctx)
+53
View File
@@ -83,6 +83,9 @@ type runtimeTaskTestInspector struct {
retriedTask string
deletedTask string
forceDeleted string
purgedQueue string
purgedCount int
purgeErr error
cancelKnowledge string
cancelDeleted int
mutatedQueue string
@@ -193,6 +196,16 @@ func (r *runtimeTaskTestInspector) ForceDeleteRuntimeTask(
return true, r.forceDeleteErr
}
func (r *runtimeTaskTestInspector) PurgeArchivedRuntimeTasks(
_ context.Context, queue string,
) (int, bool, error) {
r.purgedQueue = queue
if r.purgeErr != nil {
return 0, true, r.purgeErr
}
return r.purgedCount, true, nil
}
func TestGetRuntimeQueuesReportsIsolatedPoolCapacity(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := &SystemHandler{
@@ -399,6 +412,46 @@ func TestRuntimeTaskMutationsDelegateToInspector(t *testing.T) {
}
}
func TestPurgeArchivedRuntimeTasksDelegatesToInspector(t *testing.T) {
gin.SetMode(gin.TestMode)
inspector := &runtimeTaskTestInspector{purgedCount: 7}
handler := &SystemHandler{taskInspector: inspector}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "queue", Value: types.QueueChatAttachment}}
ctx.Request = httptest.NewRequest(http.MethodDelete, "/archived", nil)
handler.PurgeArchivedRuntimeTasks(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
}
if inspector.purgedQueue != types.QueueChatAttachment {
t.Fatalf("purged queue = %q, want %q", inspector.purgedQueue, types.QueueChatAttachment)
}
var response map[string]any
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatalf("decode response: %v", err)
}
if response["deleted"] != float64(7) {
t.Fatalf("deleted = %v, want 7", response["deleted"])
}
}
func TestPurgeArchivedRuntimeTasksRejectsUnknownQueue(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: "unknown"}}
ctx.Request = httptest.NewRequest(http.MethodDelete, "/archived", nil)
handler.PurgeArchivedRuntimeTasks(ctx)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusBadRequest)
}
}
func TestListRuntimeTasksRejectsUnknownQueue(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := &SystemHandler{taskInspector: &runtimeTaskTestInspector{}}
+2
View File
@@ -998,6 +998,8 @@ func RegisterSystemAdminRoutes(
handler.ListRuntimeTasks)
g.apiKeyRoute(adminRoutes, http.MethodPost, "/runtime/queues/:queue/tasks/:task_id/actions/:action",
apiKeyPlatform(types.APIKeyCapabilitySystemRuntimeManage), handler.MutateRuntimeTask)
g.apiKeyRoute(adminRoutes, http.MethodDelete, "/runtime/queues/:queue/archived",
apiKeyPlatform(types.APIKeyCapabilitySystemRuntimeManage), handler.PurgeArchivedRuntimeTasks)
// Bulk action — write the current default-quota setting onto
// every existing tenant. Lives under /tenants instead of
@@ -62,6 +62,7 @@ func TestPlatformControlPlaneRoutesDeclarePlatformCapabilities(t *testing.T) {
{http.MethodPut, "/api/v1/system/admin/settings/:key", types.APIKeyCapabilitySystemSettingsManage},
{http.MethodGet, "/api/v1/system/admin/runtime/queues", types.APIKeyCapabilitySystemRuntimeRead},
{http.MethodPost, "/api/v1/system/admin/runtime/queues/:queue/tasks/:task_id/actions/:action", types.APIKeyCapabilitySystemRuntimeManage},
{http.MethodDelete, "/api/v1/system/admin/runtime/queues/:queue/archived", types.APIKeyCapabilitySystemRuntimeManage},
}
for _, tc := range cases {
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
+14
View File
@@ -682,6 +682,20 @@ func (a *asynqTaskInspector) ForceDeleteRuntimeTask(ctx context.Context, queue,
return true, a.inspector.DeleteTask(queue, taskID)
}
// PurgeArchivedRuntimeTasks clears the whole archived (dead-letter) set for one
// queue. asynq's DeleteAllArchivedTasks scopes strictly to the archived list,
// so pending/active/scheduled/retry work is never at risk.
func (a *asynqTaskInspector) PurgeArchivedRuntimeTasks(ctx context.Context, queue string) (int, bool, error) {
if a == nil || a.inspector == nil {
return 0, false, nil
}
deleted, err := a.inspector.DeleteAllArchivedTasks(queue)
if err != nil {
return 0, true, err
}
return deleted, true, nil
}
func (a *asynqTaskInspector) WorkerServerStats(
ctx context.Context,
) ([]types.WorkerServerStat, bool, error) {
+4
View File
@@ -131,6 +131,10 @@ const (
AuditActionSystemQueueTaskDeleted AuditAction = "system.queue_task_deleted"
AuditActionSystemQueueTaskRunNow AuditAction = "system.queue_task_run_now"
AuditActionSystemQueueTaskCancelled AuditAction = "system.queue_task_cancelled"
// AuditActionSystemQueueArchivedPurged fires when an operator clears every
// archived (finally-failed) task in one queue in a single action. The
// detail payload records the queue and how many records were removed.
AuditActionSystemQueueArchivedPurged AuditAction = "system.queue_archived_purged"
// Knowledge-base activity actions. These rows use scope_type=knowledge_base
// and scope_id=<kb id>; TargetType/TargetID identify the concrete child
+4
View File
@@ -42,6 +42,7 @@ func TestAuditAction_DotNamespaceConvention(t *testing.T) {
AuditActionSystemQueueTaskDeleted,
AuditActionSystemQueueTaskRunNow,
AuditActionSystemQueueTaskCancelled,
AuditActionSystemQueueArchivedPurged,
}
for _, a := range all {
s := string(a)
@@ -128,6 +129,7 @@ func TestAuditAction_NoCollisionsAcrossNamespaces(t *testing.T) {
register("AuditActionSystemQueueTaskDeleted", AuditActionSystemQueueTaskDeleted)
register("AuditActionSystemQueueTaskRunNow", AuditActionSystemQueueTaskRunNow)
register("AuditActionSystemQueueTaskCancelled", AuditActionSystemQueueTaskCancelled)
register("AuditActionSystemQueueArchivedPurged", AuditActionSystemQueueArchivedPurged)
}
// TestAuditAction_SystemNamespacePrefix pins the system.* actions
@@ -146,6 +148,7 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {
AuditActionSystemQueueTaskDeleted,
AuditActionSystemQueueTaskRunNow,
AuditActionSystemQueueTaskCancelled,
AuditActionSystemQueueArchivedPurged,
}
for _, a := range cases {
assert.True(t,
@@ -172,6 +175,7 @@ func TestAuditAction_SystemWireValues(t *testing.T) {
{AuditActionSystemQueueTaskDeleted, "system.queue_task_deleted"},
{AuditActionSystemQueueTaskRunNow, "system.queue_task_run_now"},
{AuditActionSystemQueueTaskCancelled, "system.queue_task_cancelled"},
{AuditActionSystemQueueArchivedPurged, "system.queue_archived_purged"},
}
for _, c := range cases {
assert.Equal(t, c.wire, string(c.constant))
@@ -101,4 +101,12 @@ type RuntimeTaskInspector interface {
// 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)
// PurgeArchivedRuntimeTasks removes every archived (finally-failed) task
// from one queue in a single call and returns how many records were
// deleted. It only ever touches the archived (dead-letter) set, so live
// pending/active/scheduled/retry tasks are never affected. Business state
// is intentionally left untouched: archived tasks have already had their
// document status flipped to "failed" on their last retry, mirroring the
// semantics of deleting archived records one by one.
PurgeArchivedRuntimeTasks(ctx context.Context, queue string) (deleted int, supported bool, err error)
}