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:
@@ -11972,6 +11972,35 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/system/admin/runtime/queues/{queue}/archived": {
|
||||
"delete": {
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"System Admin"
|
||||
],
|
||||
"summary": "Purge all archived tasks in a queue",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Queue name",
|
||||
"name": "queue",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/system/admin/runtime/queues/{queue}/tasks": {
|
||||
"get": {
|
||||
"produces": [
|
||||
@@ -14939,6 +14968,7 @@ const docTemplate = `{
|
||||
"system.queue_task_deleted",
|
||||
"system.queue_task_run_now",
|
||||
"system.queue_task_cancelled",
|
||||
"system.queue_archived_purged",
|
||||
"kb.created",
|
||||
"kb.updated",
|
||||
"kb.deleted",
|
||||
@@ -15001,6 +15031,7 @@ const docTemplate = `{
|
||||
"AuditActionSystemQueueTaskDeleted",
|
||||
"AuditActionSystemQueueTaskRunNow",
|
||||
"AuditActionSystemQueueTaskCancelled",
|
||||
"AuditActionSystemQueueArchivedPurged",
|
||||
"AuditActionKBCreated",
|
||||
"AuditActionKBUpdated",
|
||||
"AuditActionKBDeleted",
|
||||
|
||||
@@ -11965,6 +11965,35 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/system/admin/runtime/queues/{queue}/archived": {
|
||||
"delete": {
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"System Admin"
|
||||
],
|
||||
"summary": "Purge all archived tasks in a queue",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Queue name",
|
||||
"name": "queue",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/system/admin/runtime/queues/{queue}/tasks": {
|
||||
"get": {
|
||||
"produces": [
|
||||
@@ -14932,6 +14961,7 @@
|
||||
"system.queue_task_deleted",
|
||||
"system.queue_task_run_now",
|
||||
"system.queue_task_cancelled",
|
||||
"system.queue_archived_purged",
|
||||
"kb.created",
|
||||
"kb.updated",
|
||||
"kb.deleted",
|
||||
@@ -14994,6 +15024,7 @@
|
||||
"AuditActionSystemQueueTaskDeleted",
|
||||
"AuditActionSystemQueueTaskRunNow",
|
||||
"AuditActionSystemQueueTaskCancelled",
|
||||
"AuditActionSystemQueueArchivedPurged",
|
||||
"AuditActionKBCreated",
|
||||
"AuditActionKBUpdated",
|
||||
"AuditActionKBDeleted",
|
||||
|
||||
@@ -300,6 +300,7 @@ definitions:
|
||||
- system.queue_task_deleted
|
||||
- system.queue_task_run_now
|
||||
- system.queue_task_cancelled
|
||||
- system.queue_archived_purged
|
||||
- kb.created
|
||||
- kb.updated
|
||||
- kb.deleted
|
||||
@@ -362,6 +363,7 @@ definitions:
|
||||
- AuditActionSystemQueueTaskDeleted
|
||||
- AuditActionSystemQueueTaskRunNow
|
||||
- AuditActionSystemQueueTaskCancelled
|
||||
- AuditActionSystemQueueArchivedPurged
|
||||
- AuditActionKBCreated
|
||||
- AuditActionKBUpdated
|
||||
- AuditActionKBDeleted
|
||||
@@ -13370,6 +13372,25 @@ paths:
|
||||
summary: 获取解析任务队列运行时状态
|
||||
tags:
|
||||
- 系统管理
|
||||
/system/admin/runtime/queues/{queue}/archived:
|
||||
delete:
|
||||
parameters:
|
||||
- description: Queue name
|
||||
in: path
|
||||
name: queue
|
||||
required: true
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
summary: Purge all archived tasks in a queue
|
||||
tags:
|
||||
- System Admin
|
||||
/system/admin/runtime/queues/{queue}/tasks:
|
||||
get:
|
||||
parameters:
|
||||
|
||||
@@ -651,3 +651,18 @@ export async function mutateRuntimeTask(
|
||||
`/api/v1/system/admin/runtime/queues/${encodeURIComponent(queue)}/tasks/${encodeURIComponent(taskID)}/actions/${encodeURIComponent(action)}`,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear every archived (finally-failed) task in one queue in a single call.
|
||||
* Only touches the archived dead-letter set — live tasks are never affected.
|
||||
* Backend: DELETE /api/v1/system/admin/runtime/queues/{queue}/archived.
|
||||
* Returns the object directly (no {data: ...} wrapping, see request.ts).
|
||||
*/
|
||||
export async function purgeArchivedRuntimeTasks(
|
||||
queue: string,
|
||||
): Promise<{ success: boolean; deleted: number }> {
|
||||
const response = await del(
|
||||
`/api/v1/system/admin/runtime/queues/${encodeURIComponent(queue)}/archived`,
|
||||
)
|
||||
return response as unknown as { success: boolean; deleted: number }
|
||||
}
|
||||
|
||||
@@ -3770,6 +3770,10 @@ export default {
|
||||
runNowConfirm: "This task will move to pending immediately without resetting its retry count. Continue?",
|
||||
deleteRecord: "Clear record",
|
||||
deleteConfirm: "This only removes the record from this queue. It will not run or complete the original task, and historical logs remain. Clear it?",
|
||||
purgeArchived: "Clear all failed tasks",
|
||||
purgeArchivedConfirm: "Remove all {count} failed records from this queue at once. This only clears failed tasks in the queue — it does not affect running or pending tasks, nor does it roll back the business status of documents that already failed. Clear them?",
|
||||
purgeArchivedSuccess: "Cleared {count} failed tasks",
|
||||
purgeArchivedError: "Failed to clear failed tasks",
|
||||
stateFilter: "Filter by task state",
|
||||
states: {
|
||||
active: "Active",
|
||||
@@ -3839,6 +3843,7 @@ export default {
|
||||
},
|
||||
queueNames: {
|
||||
default: "Document parsing",
|
||||
chat_attachment: "Chat attachments",
|
||||
postprocess: "Post-process",
|
||||
summary: "Summaries",
|
||||
sync: "Source sync",
|
||||
@@ -3850,6 +3855,7 @@ export default {
|
||||
},
|
||||
queueDescriptions: {
|
||||
default: "Document parse, manual reparse",
|
||||
chat_attachment: "Session-scoped chat upload parsing",
|
||||
postprocess: "Parse finalization, enrichment fan-out",
|
||||
summary: "Document & table summaries",
|
||||
sync: "Manual & scheduled sync",
|
||||
@@ -4060,6 +4066,7 @@ export default {
|
||||
'system.queue_task_deleted': 'Failed task record cleared',
|
||||
'system.queue_task_run_now': 'Queue task run now',
|
||||
'system.queue_task_cancelled': 'Queue task cancelled',
|
||||
'system.queue_archived_purged': 'All failed tasks cleared',
|
||||
},
|
||||
outcome: {
|
||||
success: 'Success',
|
||||
|
||||
@@ -2751,6 +2751,10 @@ export default {
|
||||
deleteConfirm: "현재 큐에서만 기록을 제거합니다. 원래 작업은 실행되거나 완료되지 않으며 기록 로그는 유지됩니다. 지울까요?",
|
||||
deleteSuccess: "실패 기록을 지웠습니다",
|
||||
deleteError: "실패 기록을 지우지 못했습니다",
|
||||
purgeArchived: "실패 작업 모두 지우기",
|
||||
purgeArchivedConfirm: "현재 큐의 실패 기록 {count}건을 한 번에 제거합니다. 큐의 실패 작업만 정리하며 실행 중이거나 대기 중인 작업에는 영향이 없고, 이미 실패한 문서의 비즈니스 상태도 되돌리지 않습니다. 지울까요?",
|
||||
purgeArchivedSuccess: "실패 작업 {count}건을 지웠습니다",
|
||||
purgeArchivedError: "실패 작업을 지우지 못했습니다",
|
||||
taskTypes: {
|
||||
documentProcess: "문서 파싱",
|
||||
manualProcess: "수동 재처리",
|
||||
@@ -2801,6 +2805,7 @@ export default {
|
||||
},
|
||||
queueNames: {
|
||||
default: "문서 파싱",
|
||||
chat_attachment: "대화 첨부파일 파싱",
|
||||
postprocess: "후처리 오케스트레이션",
|
||||
summary: "요약 생성",
|
||||
sync: "데이터 소스 동기화",
|
||||
@@ -2812,6 +2817,7 @@ export default {
|
||||
},
|
||||
queueDescriptions: {
|
||||
default: "문서 파싱, 수동 재파싱",
|
||||
chat_attachment: "세션 내 업로드 첨부파일 파싱",
|
||||
postprocess: "파싱 마무리, 보강 분배",
|
||||
summary: "문서 요약, 테이블 요약",
|
||||
sync: "수동 및 예약 동기화",
|
||||
@@ -3022,6 +3028,7 @@ export default {
|
||||
"system.queue_task_deleted": "실패 작업 기록 삭제",
|
||||
"system.queue_task_run_now": "큐 작업 즉시 실행",
|
||||
"system.queue_task_cancelled": "큐 작업 취소",
|
||||
"system.queue_archived_purged": "실패 작업 모두 지우기",
|
||||
},
|
||||
outcome: {
|
||||
success: "성공",
|
||||
|
||||
@@ -2439,6 +2439,10 @@ export default {
|
||||
deleteConfirm: "Запись будет удалена только из этой очереди; исходная задача не будет выполнена, а исторические журналы сохранятся. Очистить?",
|
||||
deleteSuccess: "Запись о сбое удалена",
|
||||
deleteError: "Не удалось удалить запись",
|
||||
purgeArchived: "Очистить все сбойные задачи",
|
||||
purgeArchivedConfirm: "Удалить сразу все {count} сбойных записей из этой очереди. Очищаются только сбойные задачи в очереди — это не затронет выполняемые или ожидающие задачи и не откатит бизнес-статус уже сбойных документов. Очистить?",
|
||||
purgeArchivedSuccess: "Очищено сбойных задач: {count}",
|
||||
purgeArchivedError: "Не удалось очистить сбойные задачи",
|
||||
taskTypes: {
|
||||
documentProcess: "Разбор документа",
|
||||
manualProcess: "Ручная повторная обработка",
|
||||
@@ -2489,6 +2493,7 @@ export default {
|
||||
},
|
||||
queueNames: {
|
||||
default: "Разбор документов",
|
||||
chat_attachment: "Разбор вложений чата",
|
||||
postprocess: "Постобработка",
|
||||
summary: "Сводки",
|
||||
sync: "Синхронизация источников",
|
||||
@@ -2500,6 +2505,7 @@ export default {
|
||||
},
|
||||
queueDescriptions: {
|
||||
default: "Разбор документов, ручной повторный разбор",
|
||||
chat_attachment: "Разбор вложений, загруженных в сессии",
|
||||
postprocess: "Завершение разбора, запуск обогащения",
|
||||
summary: "Сводки документов и таблиц",
|
||||
sync: "Ручная и плановая синхронизация",
|
||||
@@ -2710,6 +2716,7 @@ export default {
|
||||
'system.queue_task_deleted': 'Удалена запись о сбойной задаче',
|
||||
'system.queue_task_run_now': 'Задача очереди запущена сейчас',
|
||||
'system.queue_task_cancelled': 'Задача очереди отменена',
|
||||
'system.queue_archived_purged': 'Очищены все сбойные задачи',
|
||||
},
|
||||
outcome: {
|
||||
success: 'Успешно',
|
||||
|
||||
@@ -2725,6 +2725,10 @@ export default {
|
||||
runNowConfirm: "该任务将立即进入待执行队列,重试次数不会重置。确认继续?",
|
||||
deleteRecord: "清除记录",
|
||||
deleteConfirm: "仅从当前队列移除这条失败记录,不会执行或完成原任务,历史日志仍会保留。确认清除?",
|
||||
purgeArchived: "清除全部失败任务",
|
||||
purgeArchivedConfirm: "将从当前队列一次性移除全部 {count} 条失败记录,仅清理队列里的失败任务,不影响运行中或排队中的任务,也不会回滚已失败文档的业务状态。确认清除?",
|
||||
purgeArchivedSuccess: "已清除 {count} 条失败任务",
|
||||
purgeArchivedError: "清除失败任务失败",
|
||||
stateFilter: "按任务状态筛选",
|
||||
states: {
|
||||
active: "运行中",
|
||||
@@ -2802,6 +2806,7 @@ export default {
|
||||
},
|
||||
queueNames: {
|
||||
default: "文档解析",
|
||||
chat_attachment: "对话附件解析",
|
||||
postprocess: "后处理编排",
|
||||
summary: "摘要生成",
|
||||
sync: "数据源同步",
|
||||
@@ -2813,6 +2818,7 @@ export default {
|
||||
},
|
||||
queueDescriptions: {
|
||||
default: "文档解析、手工重解析",
|
||||
chat_attachment: "会话内上传附件解析",
|
||||
postprocess: "解析收尾、富化扇出",
|
||||
summary: "文档摘要、表格摘要",
|
||||
sync: "手动与定时同步",
|
||||
@@ -3034,6 +3040,7 @@ export default {
|
||||
"system.queue_task_deleted": "清除失败任务记录",
|
||||
"system.queue_task_run_now": "立即执行队列任务",
|
||||
"system.queue_task_cancelled": "终止队列任务",
|
||||
"system.queue_archived_purged": "清除全部失败任务",
|
||||
},
|
||||
outcome: {
|
||||
success: "成功",
|
||||
|
||||
@@ -339,15 +339,34 @@
|
||||
<h4 class="setting-drawer__section-title">
|
||||
{{ t('system.globalSettings.runtime.tasks.listTitle', { state: taskStateLabel(taskState) }) }}
|
||||
</h4>
|
||||
<t-button
|
||||
variant="text"
|
||||
size="small"
|
||||
:loading="tasksLoading && !tasksLoadingMore"
|
||||
@click="reloadRuntimeTasks"
|
||||
>
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
{{ t('system.globalSettings.runtime.refresh') }}
|
||||
</t-button>
|
||||
<div class="rq-failed-section-actions">
|
||||
<t-popconfirm
|
||||
v-if="taskState === 'archived' && tasks.length > 0"
|
||||
theme="danger"
|
||||
:content="t('system.globalSettings.runtime.tasks.purgeArchivedConfirm', { count: taskStateCount(taskQueue, 'archived') })"
|
||||
@confirm="purgeArchivedTasks"
|
||||
>
|
||||
<t-button
|
||||
variant="text"
|
||||
size="small"
|
||||
theme="danger"
|
||||
:loading="purging"
|
||||
:disabled="Boolean(taskActionID)"
|
||||
>
|
||||
<template #icon><t-icon name="clear" /></template>
|
||||
{{ t('system.globalSettings.runtime.tasks.purgeArchived') }}
|
||||
</t-button>
|
||||
</t-popconfirm>
|
||||
<t-button
|
||||
variant="text"
|
||||
size="small"
|
||||
:loading="tasksLoading && !tasksLoadingMore"
|
||||
@click="reloadRuntimeTasks"
|
||||
>
|
||||
<template #icon><t-icon name="refresh" /></template>
|
||||
{{ t('system.globalSettings.runtime.refresh') }}
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="tasksLoading && tasks.length === 0" class="rq-failed-loading">
|
||||
@@ -497,6 +516,7 @@ import {
|
||||
getRuntimeTasks,
|
||||
getRuntimeQueues,
|
||||
mutateRuntimeTask,
|
||||
purgeArchivedRuntimeTasks,
|
||||
type ModelRuntimeStat,
|
||||
type QueueStat,
|
||||
type RuntimeTask,
|
||||
@@ -531,6 +551,7 @@ const tasksHasMore = ref(false)
|
||||
const tasksSentinelRef = ref<HTMLElement | null>(null)
|
||||
const taskActionID = ref('')
|
||||
const taskAction = ref<RuntimeTaskAction | ''>('')
|
||||
const purging = ref(false)
|
||||
|
||||
const TASK_PAGE_SIZE = 20
|
||||
const taskStates: RuntimeTaskState[] = ['active', 'pending', 'scheduled', 'retry', 'archived', 'completed']
|
||||
@@ -860,6 +881,22 @@ async function runTaskAction(task: RuntimeTask, action: RuntimeTaskAction) {
|
||||
}
|
||||
}
|
||||
|
||||
async function purgeArchivedTasks() {
|
||||
const queue = taskQueue.value?.name
|
||||
if (!queue || purging.value) return
|
||||
purging.value = true
|
||||
try {
|
||||
const { deleted } = await purgeArchivedRuntimeTasks(queue)
|
||||
MessagePlugin.success(t('system.globalSettings.runtime.tasks.purgeArchivedSuccess', { count: deleted }))
|
||||
await Promise.all([reloadRuntimeTasks(), load(false)])
|
||||
taskQueue.value = queues.value.find((item) => item.name === queue) ?? taskQueue.value
|
||||
} catch (err: any) {
|
||||
MessagePlugin.error(err?.message || t('system.globalSettings.runtime.tasks.purgeArchivedError'))
|
||||
} finally {
|
||||
purging.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function load(showSpinner: boolean) {
|
||||
if (showSpinner) loading.value = true
|
||||
try {
|
||||
@@ -1477,6 +1514,13 @@ onUnmounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
.rq-failed-section-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.rq-failed-loading {
|
||||
display: flex;
|
||||
min-height: 180px;
|
||||
|
||||
@@ -258,6 +258,7 @@ function auditActionTheme(
|
||||
case 'system.user_password_reset':
|
||||
case 'system.queue_task_deleted':
|
||||
case 'system.queue_task_cancelled':
|
||||
case 'system.queue_archived_purged':
|
||||
return 'danger'
|
||||
case 'rbac.access_denied':
|
||||
return 'danger'
|
||||
@@ -331,6 +332,10 @@ function auditTargetKey(row: AuditLog): string {
|
||||
const taskID = details && typeof details.task_id === 'string' ? details.task_id : row.target_id
|
||||
return queue && taskID ? `${queue}:${taskID}` : taskID || queue
|
||||
}
|
||||
if (row.action === 'system.queue_archived_purged') {
|
||||
const queue = details && typeof details.queue === 'string' ? details.queue : ''
|
||||
return queue || row.target_id || ''
|
||||
}
|
||||
if (row.target_user_id) return row.target_user_id.slice(0, 8)
|
||||
if (row.target_id) {
|
||||
return row.target_type ? `${row.target_type}:${row.target_id}` : row.target_id
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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{}}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user