Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(queue): add queue management page and i18n support
HoshinoSuzumi86186ea4d0e4
diff --git a/app/components/dashboard/Indicator.vue b/app/components/dashboard/Indicator.vueindex abed78db..0092f6d2 100644--- a/app/components/dashboard/Indicator.vue+++ b/app/components/dashboard/Indicator.vue@@ -1,4 +1,6 @@<script lang="ts" setup>+import { isNil } from 'es-toolkit';+const props = withDefaults(defineProps<{title?: string@@ -94,7 +96,7 @@ const currentScheme = computed(() => colorSchemes[props.color]){{ title }}</p><p- v-if="value"+ v-if="!isNil(value)"class="text-lg font-bold max-w-full sm:max-w-1/2 truncate">{{ value }}diff --git a/app/components/ui/UploadQueuePanel.vue b/app/components/ui/UploadQueuePanel.vueindex 0a727f9f..f2df4917 100644--- a/app/components/ui/UploadQueuePanel.vue+++ b/app/components/ui/UploadQueuePanel.vue@@ -281,7 +281,7 @@ const clearAllFiles = () => {{{ stats.completed }} 完成, {{ stats.error }} 失败</div>- <div class="flex items-center gap-2">+ <div class="flex items-center gap-0.5"><UButtonv-if="stats.completed > 0"size="xs"@@ -296,6 +296,7 @@ const clearAllFiles = () => {size="xs"variant="ghost"color="error"+ icon="tabler:trash"@click="clearAllFiles">清除全部@@ -304,7 +305,7 @@ const clearAllFiles = () => {<UButtonsize="xs"variant="ghost"- color="blue"+ color="info"icon="tabler:list-check"@click="emit('goToQueue')">diff --git a/app/pages/dashboard/queue.vue b/app/pages/dashboard/queue.vueindex b4018584..43205abe 100644--- a/app/pages/dashboard/queue.vue+++ b/app/pages/dashboard/queue.vue@@ -1,306 +1,493 @@-<template>- <div class="container mx-auto p-6 space-y-6">- <div class="flex items-center justify-between">- <h1 class="text-3xl font-bold">队列管理</h1>- <div class="flex gap-2">- <button- @click="refreshData"- :disabled="loading"- class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50"- >- {{ loading ? '刷新中...' : '刷新' }}- </button>- <button- @click="cleanupBlockedTasks"- :disabled="cleanupLoading"- class="px-4 py-2 bg-yellow-500 text-white rounded hover:bg-yellow-600 disabled:opacity-50"- >- {{ cleanupLoading ? '清理中...' : '清理阻塞任务' }}- </button>- </div>- </div>+<script setup lang="ts">+import type { TableColumn } from '@nuxt/ui'- <!-- 队列统计 -->- <div class="grid grid-cols-1 md:grid-cols-4 gap-4">- <div v-for="stat in queueStats" :key="stat.status" class="bg-white p-4 rounded-lg shadow">- <div class="flex items-center justify-between">- <div>- <p class="text-sm text-gray-600">{{ getStatusLabel(stat.status) }}</p>- <p class="text-2xl font-bold">{{ stat.count }}</p>- </div>- <div :class="getStatusColor(stat.status)" class="w-12 h-12 rounded-full flex items-center justify-center">- <component :is="getStatusIcon(stat.status)" class="w-6 h-6 text-white" />- </div>- </div>- </div>- </div>+definePageMeta({+ layout: 'dashboard',+})- <!-- 失败任务管理 -->- <div class="bg-white rounded-lg shadow">- <div class="p-4 border-b border-gray-200">- <div class="flex items-center justify-between">- <h2 class="text-xl font-semibold">失败任务</h2>- <div class="flex gap-2">- <button- @click="retryAllFailed"- :disabled="actionLoading"- class="px-3 py-1 bg-green-500 text-white text-sm rounded hover:bg-green-600 disabled:opacity-50"- >- 重试所有- </button>- <button- @click="deleteAllFailed"- :disabled="actionLoading"- class="px-3 py-1 bg-red-500 text-white text-sm rounded hover:bg-red-600 disabled:opacity-50"- >- 删除所有- </button>- </div>- </div>- </div>+useHead({+ title: $t('dashboard.queue.title'),+})- <div v-if="failedTasks.length === 0" class="p-8 text-center text-gray-500">- 没有失败的任务- </div>+const toast = useToast()- <div v-else class="divide-y divide-gray-200">- <div v-for="task in failedTasks" :key="task.id" class="p-4 hover:bg-gray-50">- <div class="flex items-center justify-between">- <div class="flex-1">- <div class="flex items-center gap-2 mb-2">- <span class="px-2 py-1 bg-gray-100 text-xs rounded">{{ task.type }}</span>- <span class="text-sm text-gray-600">任务 #{{ task.id }}</span>- </div>- <p class="font-medium text-sm">{{ task.storageKey }}</p>- <p class="text-red-600 text-sm mt-1">{{ task.errorMessage }}</p>- <div class="flex items-center gap-4 mt-2 text-xs text-gray-500">- <span>尝试次数: {{ task.attempts }}/{{ task.maxAttempts }}</span>- <span>创建时间: {{ formatTime(task.createdAt) }}</span>- </div>- </div>- <div class="flex gap-2">- <button- @click="retryTask(task.id)"- :disabled="actionLoading"- class="px-3 py-1 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 disabled:opacity-50"- >- 重试- </button>- <button- @click="deleteTask(task.id)"- :disabled="actionLoading"- class="px-3 py-1 bg-red-500 text-white text-sm rounded hover:bg-red-600 disabled:opacity-50"- >- 删除- </button>- </div>- </div>- </div>- </div>+// 状态管理+const isLoading = ref(false)+const selectedTasks = ref<number[]>([])+const statusFilter = ref<string>('all')+const typeFilter = ref<string>('all')- <!-- 分页 -->- <div v-if="pagination.totalPages > 1" class="p-4 border-t border-gray-200">- <div class="flex items-center justify-between">- <div class="text-sm text-gray-600">- 显示 {{ (pagination.page - 1) * pagination.limit + 1 }} -- {{ Math.min(pagination.page * pagination.limit, pagination.total) }}- / {{ pagination.total }} 个任务- </div>- <div class="flex gap-2">- <button- @click="changePage(pagination.page - 1)"- :disabled="!pagination.hasPrev || loading"- class="px-3 py-1 border rounded disabled:opacity-50"- >- 上一页- </button>- <span class="px-3 py-1">{{ pagination.page }} / {{ pagination.totalPages }}</span>- <button- @click="changePage(pagination.page + 1)"- :disabled="!pagination.hasNext || loading"- class="px-3 py-1 border rounded disabled:opacity-50"- >- 下一页- </button>- </div>- </div>- </div>- </div>- </div>-</template>+// 数据获取+const { data: queueData, refresh: refreshQueue } = await useFetch(+ '/api/queue/task/list',+ {+ query: computed(() => ({+ ...(statusFilter.value !== 'all' && { status: statusFilter.value }),+ ...(typeFilter.value !== 'all' && { type: typeFilter.value }),+ })),+ },+)-<script setup lang="ts">-definePageMeta({- layout: 'dashboard'-})+// 队列统计数据+const queueStats = computed(() => {+ if (!queueData.value?.data)+ return { pending: 0, processing: 0, completed: 0, failed: 0 }-// 响应式数据-const loading = ref(false)-const actionLoading = ref(false)-const cleanupLoading = ref(false)--const queueStats = ref<Array<{ status: string; count: number }>>([])-const failedTasks = ref<Array<any>>([])-const pagination = ref({- page: 1,- limit: 20,- total: 0,- totalPages: 0,- hasNext: false,- hasPrev: false,+ const stats = { pending: 0, processing: 0, completed: 0, failed: 0 }+ queueData.value.data.forEach((task) => {+ if (task.status === 'pending') stats.pending+++ else if (task.status === 'in-stages') stats.processing+++ else if (task.status === 'completed') stats.completed+++ else if (task.status === 'failed') stats.failed+++ })+ return stats})-// 获取队列统计-const fetchQueueStats = async () => {+// 刷新数据+const refreshData = async () => {+ isLoading.value = truetry {- const { data } = await $fetch('/api/queue/stats')- queueStats.value = Object.entries(data.queue).map(([status, count]) => ({- status,- count: count as number- }))- } catch (error) {- console.error('获取队列统计失败:', error)+ await refreshQueue()+ selectedTasks.value = []+ } finally {+ isLoading.value = false}}-// 获取失败任务列表-const fetchFailedTasks = async (page = 1) => {- loading.value = true+// 清理非活跃任务+const clearNonActiveTasks = async () => {try {- const { data } = await $fetch(`/api/queue/failed/list?page=${page}&limit=${pagination.value.limit}`)- failedTasks.value = data.tasks- pagination.value = data.pagination- } catch (error) {- console.error('获取失败任务失败:', error)+ isLoading.value = true+ const result = await $fetch('/api/queue/task/clear', {+ method: 'DELETE',+ query: {+ includeCompleted: 'true',+ includeFailed: 'true',+ },+ })++ toast.add({+ title: $t('dashboard.queue.messages.clearSuccess'),+ description: `清除了 ${result.deletedCount} 个任务`,+ color: 'success',+ })++ await refreshData()+ } catch (error: any) {+ console.error('Clear tasks failed:', error)+ toast.add({+ title: $t('dashboard.queue.messages.operationFailed'),+ description: error?.message || '清理任务失败',+ color: 'error',+ })} finally {- loading.value = false+ isLoading.value = false}}// 重试单个任务const retryTask = async (taskId: number) => {- actionLoading.value = truetry {- await $fetch(`/api/queue/failed/${taskId}/retry`, { method: 'POST' })- await refreshData()- } catch (error) {- console.error('重试任务失败:', error)- } finally {- actionLoading.value = false- }-}+ await $fetch('/api/queue/task/retry', {+ method: 'POST',+ body: { taskId },+ })++ toast.add({+ title: $t('dashboard.queue.messages.retrySuccess'),+ color: 'success',+ })-// 删除单个任务-const deleteTask = async (taskId: number) => {- if (!confirm('确定要删除这个失败的任务吗?')) return-- actionLoading.value = true- try {- await $fetch(`/api/queue/failed/${taskId}/delete`, { method: 'DELETE' })await refreshData()- } catch (error) {- console.error('删除任务失败:', error)- } finally {- actionLoading.value = false+ } catch (error: any) {+ console.error('Retry task failed:', error)+ toast.add({+ title: $t('dashboard.queue.messages.operationFailed'),+ description: error?.message || '重试任务失败',+ color: 'error',+ })}}-// 重试所有失败任务-const retryAllFailed = async () => {- if (!confirm('确定要重试所有失败的任务吗?')) return-- actionLoading.value = true+// 批量重试失败任务+const retryAllFailedTasks = async () => {try {- await $fetch('/api/queue/failed/batch-retry', {+ isLoading.value = true+ const result = await $fetch('/api/queue/task/retry-batch', {method: 'POST',- body: { retryAll: true }+ body: { retryAll: true },})++ toast.add({+ title: $t('dashboard.queue.messages.batchRetrySuccess'),+ description: `重试了 ${result.retriedCount} 个任务`,+ color: 'success',+ })+await refreshData()- } catch (error) {- console.error('批量重试失败:', error)+ } catch (error: any) {+ console.error('Batch retry failed:', error)+ toast.add({+ title: $t('dashboard.queue.messages.operationFailed'),+ description: error?.message || '批量重试失败',+ color: 'error',+ })} finally {- actionLoading.value = false+ isLoading.value = false}}-// 删除所有失败任务-const deleteAllFailed = async () => {- if (!confirm('确定要删除所有失败的任务吗?此操作不可恢复!')) return-- actionLoading.value = true+// 删除单个任务(仅适用于失败任务)+const deleteTask = async (taskId: number) => {try {- await $fetch('/api/queue/failed/batch-delete', {+ await $fetch(`/api/queue/failed/${taskId}`, {method: 'DELETE',- body: { deleteAll: true }})- await refreshData()- } catch (error) {- console.error('批量删除失败:', error)- } finally {- actionLoading.value = false- }-}-// 清理阻塞任务-const cleanupBlockedTasks = async () => {- if (!confirm('确定要清理阻塞的任务吗?这将重置所有in-stages状态的任务。')) return-- cleanupLoading.value = true- try {- // 这里可以调用一个专门的清理API,暂时使用命令行脚本的逻辑+ toast.add({+ title: $t('dashboard.queue.messages.deleteSuccess'),+ color: 'success',+ })+await refreshData()- } catch (error) {- console.error('清理阻塞任务失败:', error)- } finally {- cleanupLoading.value = false+ } catch (error: any) {+ console.error('Delete task failed:', error)+ toast.add({+ title: $t('dashboard.queue.messages.operationFailed'),+ description: error?.message || '删除任务失败',+ color: 'error',+ })}}-// 换页-const changePage = (page: number) => {- fetchFailedTasks(page)-}--// 刷新数据-const refreshData = async () => {- await Promise.all([- fetchQueueStats(),- fetchFailedTasks(pagination.value.page)- ])-}--// 工具函数-const getStatusLabel = (status: string) => {- const labels: Record<string, string> = {- pending: '等待中',- 'in-stages': '处理中',- completed: '已完成',- failed: '失败'+// 获取状态颜色+const getStatusColor = (+ status: 'pending' | 'in-stages' | 'completed' | 'failed',+) => {+ switch (status) {+ case 'pending':+ return 'warning'+ case 'in-stages':+ return 'info'+ case 'completed':+ return 'success'+ case 'failed':+ return 'error'+ default:+ return 'neutral'}- return labels[status] || status}-const getStatusColor = (status: string) => {- const colors: Record<string, string> = {- pending: 'bg-yellow-500',- 'in-stages': 'bg-blue-500',- completed: 'bg-green-500',- failed: 'bg-red-500'- }- return colors[status] || 'bg-gray-500'-}+// 状态选项+const statusOptions = [+ { label: $t('dashboard.queue.filters.all'), value: 'all' },+ { label: $t('dashboard.queue.status.pending'), value: 'pending' },+ { label: $t('dashboard.queue.status.in-stages'), value: 'in-stages' },+ { label: $t('dashboard.queue.status.completed'), value: 'completed' },+ { label: $t('dashboard.queue.status.failed'), value: 'failed' },+]-const getStatusIcon = (status: string) => {- // 这里可以返回图标组件名称,需要根据你的图标库调整- return 'div'-}+// 类型选项+const typeOptions = [+ { label: $t('dashboard.queue.filters.all'), value: 'all' },+ { label: $t('dashboard.queue.types.photo'), value: 'photo' },+ {+ label: $t('dashboard.queue.types.live-photo-video'),+ value: 'live-photo-video',+ },+]-const formatTime = (timestamp: number) => {- return new Date(timestamp * 1000).toLocaleString()-}+// 表格列定义+const columns: TableColumn<any>[] = [+ {+ accessorKey: 'id',+ header: $t('dashboard.queue.table.id'),+ },+ {+ id: 'type',+ accessorFn: (row) => row.payload.type,+ header: $t('dashboard.queue.table.type'),+ },+ {+ accessorKey: 'status',+ header: $t('dashboard.queue.table.status'),+ },+ {+ accessorKey: 'attempts',+ header: $t('dashboard.queue.table.attempts'),+ },+ {+ accessorKey: 'priority',+ header: $t('dashboard.queue.table.priority'),+ },+ {+ accessorKey: 'statusStage',+ header: $t('dashboard.queue.table.stage'),+ },+ {+ accessorKey: 'createdAt',+ header: $t('dashboard.queue.table.createdAt'),+ },+ {+ id: 'actions',+ header: $t('dashboard.queue.table.actions'),+ },+]-// 组件挂载时获取数据-onMounted(() => {- refreshData()+// 自动刷新+const refreshInterval = setInterval(refreshData, 10000) // 每10秒刷新一次+onBeforeUnmount(() => {+ clearInterval(refreshInterval)})</script>++<template>+ <div class="flex flex-col gap-6 h-full p-4">+ <!-- 页面标题和操作 -->+ <div class="flex items-center justify-between">+ <h1 class="text-2xl font-bold">+ {{ $t('dashboard.queue.title') }}+ </h1>+ <div class="flex items-center gap-2">+ <UButton+ icon="tabler:refresh"+ variant="soft"+ :loading="isLoading"+ @click="refreshData"+ >+ {{ $t('dashboard.queue.actions.refresh') }}+ </UButton>+ <UButton+ icon="tabler:refresh"+ color="warning"+ variant="soft"+ :loading="isLoading"+ @click="retryAllFailedTasks"+ >+ {{ $t('dashboard.queue.actions.retryAll') }}+ </UButton>+ <UButton+ icon="tabler:trash"+ color="error"+ variant="soft"+ :loading="isLoading"+ @click="clearNonActiveTasks"+ >+ {{ $t('dashboard.queue.actions.clearNonActive') }}+ </UButton>+ </div>+ </div>++ <!-- 状态指示器 -->+ <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">+ <DashboardIndicator+ :title="$t('dashboard.queue.indicator.pending')"+ icon="tabler:clock"+ color="orange"+ :value="queueStats.pending"+ />+ <DashboardIndicator+ :title="$t('dashboard.queue.indicator.processing')"+ icon="tabler:loader"+ color="blue"+ :value="queueStats.processing"+ />+ <DashboardIndicator+ :title="$t('dashboard.queue.indicator.completed')"+ icon="tabler:check"+ color="green"+ :value="queueStats.completed"+ />+ <DashboardIndicator+ :title="$t('dashboard.queue.indicator.failed')"+ icon="tabler:alert-triangle"+ color="red"+ :value="queueStats.failed"+ />+ </div>++ <!-- 筛选器和表格 -->+ <UCard>+ <template #header>+ <div class="flex items-center justify-between pb-2">+ <h2 class="text-lg font-semibold">队列任务列表</h2>+ <div class="flex items-center gap-2">+ <USelectMenu+ v-model="statusFilter"+ :items="statusOptions"+ value-key="value"+ size="sm"+ variant="soft"+ class="w-32"+ :search-input="false"+ />+ <USelectMenu+ v-model="typeFilter"+ :items="typeOptions"+ value-key="value"+ size="sm"+ variant="soft"+ class="w-32"+ :search-input="false"+ />+ </div>+ </div>+ </template>++ <div class="space-y-4">+ <!-- 任务表格 -->+ <UTable+ :data="queueData?.data || []"+ :columns="columns"+ :loading="isLoading"+ :empty-state="{+ icon: 'tabler:inbox',+ label: $t('dashboard.queue.messages.noTasks'),+ }"+ class="w-full"+ >+ <!-- 任务类型 -->+ <template #type-cell="{ row }">+ <UBadge+ :label="$t(`dashboard.queue.types.${row.original.payload.type}`)"+ variant="soft"+ :color="+ row.original.payload.type === 'photo' ? 'info' : 'secondary'+ "+ size="sm"+ />+ </template>++ <!-- 状态 -->+ <template #status-cell="{ row }">+ <UBadge+ :label="$t(`dashboard.queue.status.${row.original.status}`)"+ variant="soft"+ :color="getStatusColor(row.original.status)"+ size="sm"+ />+ </template>++ <!-- 尝试次数 -->+ <template #attempts-cell="{ row }">+ <span class="text-sm">+ {{ row.original.attempts }}/{{ row.original.maxAttempts }}+ </span>+ </template>++ <!-- 处理阶段 -->+ <template #statusStage-cell="{ row }">+ <span+ v-if="row.original.statusStage"+ class="text-xs text-gray-500"+ >+ {{ $t(`dashboard.queue.stages.${row.original.statusStage}`) }}+ </span>+ <span+ v-else+ class="text-xs text-gray-400"+ >-</span+ >+ </template>++ <!-- 创建时间 -->+ <template #createdAt-cell="{ row }">+ <span class="text-sm">{{+ $dayjs(row.original.createdAt).format('MM-DD HH:mm:ss')+ }}</span>+ </template>++ <!-- 操作按钮 -->+ <template #actions-cell="{ row }">+ <div class="flex items-center gap-1">+ <UButton+ v-if="row.original.status === 'failed'"+ icon="tabler:refresh"+ size="xs"+ variant="soft"+ color="warning"+ @click="retryTask(row.original.id)"+ >+ {{ $t('dashboard.queue.buttons.retry') }}+ </UButton>+ <UButton+ v-if="row.original.status !== 'in-stage'"+ icon="tabler:trash"+ size="xs"+ variant="soft"+ color="error"+ @click="deleteTask(row.original.id)"+ >+ {{ $t('dashboard.queue.buttons.delete') }}+ </UButton>+ <span+ v-if="+ row.original.status === 'pending' ||+ row.original.status === 'in-stages'+ "+ class="text-xs text-gray-400"+ >+ -+ </span>+ </div>+ </template>+ </UTable>+ </div>+ </UCard>++ <!-- 错误信息显示 -->+ <UCard+ v-if="+ queueData?.data?.some(+ (task) => task.status === 'failed' && task.errorMessage,+ )+ "+ >+ <template #header>+ <h3 class="font-semibold text-red-600">最近的错误信息</h3>+ </template>++ <div class="space-y-2 max-h-64 overflow-y-auto">+ <div+ v-for="task in queueData.data+ .filter((t) => t.status === 'failed' && t.errorMessage)+ .slice(0, 5)"+ :key="task.id"+ class="p-3 bg-red-50 dark:bg-red-950/20 rounded-lg border border-red-100 dark:border-red-900/30"+ >+ <div class="flex items-start justify-between gap-2 text-sm">+ <div class="flex-1">+ <p class="font-medium text-red-800 dark:text-red-200">+ 任务 #{{ task.id }} ({{+ $t(`dashboard.queue.types.${task.payload.type}`)+ }})+ </p>+ <p class="text-red-600 dark:text-red-300 mt-1 text-xs break-all">+ {{ task.errorMessage }}+ </p>+ <p class="text-red-500 dark:text-red-400 mt-1 text-xs">+ {{ $dayjs(task.createdAt).format('MM-DD HH:mm:ss') }}+ </p>+ </div>+ <UButton+ icon="tabler:refresh"+ size="xs"+ variant="soft"+ color="warning"+ @click="retryTask(task.id)"+ >+ 重试+ </UButton>+ </div>+ </div>+ </div>+ </UCard>+ </div>+</template>++<style scoped>+/* 确保表格在小屏幕上正常显示 */+:deep(.table-wrapper) {+ overflow-x: auto;+}+</style>diff --git a/docs/queue-task-api.md b/docs/queue-task-api.mdnew file mode 100644index 00000000..2377da64--- /dev/null+++ b/docs/queue-task-api.md@@ -0,0 +1,145 @@+# 队列任务管理 API 文档++本文档描述了ChronoFrame应用中新增的队列任务管理API端点。++## API 端点++### 1. GET `/api/queue/task/list` - 列出所有队列任务记录++获取队列中所有任务的列表++**响应示例:**+```json+[+ {+ "id": 123,+ "type": "photo",+ "storageKey": "uploads/2024/photo.jpg",+ "priority": 0,+ "attempts": 2,+ "maxAttempts": 3,+ "status": "failed",+ "statusStage": "exif",+ "errorMessage": "EXIF extraction failed",+ "createdAt": "2024-10-02T10:00:00Z",+ "completedAt": null+ }+]+```++### 2. POST `/api/queue/task/retry` - 重试失败任务++重试一个指定的失败状态任务。只有状态为 `failed` 的任务才能被重试。++**请求体:**+```json+{+ "taskId": 123+}+```++**响应示例:**+```json+{+ "success": true,+ "message": "Task 123 has been reset and will be retried",+ "taskId": 123,+ "payload": {+ "type": "photo",+ "storageKey": "uploads/2024/photo.jpg"+ }+}+```++**错误情况:**+- 404: 任务不存在+- 400: 任务不是失败状态++### 3. POST `/api/queue/task/retry-batch` - 批量重试任务++批量重试多个失败的任务,或重试所有失败的任务。++**请求体:**+```json+{+ "taskIds": [123, 124, 125], // 可选,指定任务ID列表+ "retryAll": false // 可选,是否重试所有失败任务+}+```++**注意:** `taskIds` 和 `retryAll` 必须提供其中一个。++**响应示例:**+```json+{+ "success": true,+ "message": "Successfully reset 2 failed tasks for retry",+ "retriedCount": 2,+ "skippedCount": 1,+ "retriedTasks": [+ {+ "id": 123,+ "type": "photo",+ "storageKey": "uploads/2024/photo1.jpg"+ },+ {+ "id": 124,+ "type": "live-photo-video",+ "storageKey": "uploads/2024/video.mov"+ }+ ],+ "skippedTasks": [+ {+ "id": 125,+ "status": "completed",+ "reason": "Task is not in failed status (current: completed)"+ }+ ]+}+```++### 4. DELETE `/api/queue/task/clear` - 清理非进行中任务++清理已完成和/或失败的任务,可选择性地按时间范围过滤。++**查询参数:**+- `includeCompleted` (可选): 是否包含已完成的任务,默认为 "true"+- `includeFailed` (可选): 是否包含失败的任务,默认为 "true"+- `olderThanDays` (可选): 只清理指定天数之前的任务++**响应示例:**+```json+{+ "success": true,+ "message": "Successfully cleared 45 non-active tasks",+ "deletedCount": 45,+ "breakdown": {+ "completed": 30,+ "failed": 15+ },+ "filter": {+ "olderThanDays": 7,+ "thresholdDate": "2024-09-25T10:00:00.000Z"+ }+}+```++## 安全性++所有API端点都需要用户会话验证(`requireUserSession`),确保只有已认证的用户才能访问。++## 错误处理++所有API都遵循统一的错误处理模式:+- 参数验证错误返回 400 状态码+- 资源不存在返回 404 状态码+- 服务器内部错误返回 500 状态码+- 错误响应包含 `statusMessage` 字段描述具体错误++## 使用场景++1. **任务监控**: 使用 `/task/list` 查看队列状态和任务进度+2. **故障恢复**: 使用 `/task/retry` 或 `/task/retry-batch` 重试失败的任务+3. **维护清理**: 使用 `/task/clear` 定期清理已完成的旧任务,保持队列整洁++这些API与现有的队列管理系统完全集成,遵循项目的架构设计原则和代码规范。\ No newline at end of filediff --git a/i18n/locales/en.json b/i18n/locales/en.jsonindex c9b68b3b..0a45674c 100644--- a/i18n/locales/en.json+++ b/i18n/locales/en.json@@ -341,6 +341,71 @@"avgSuccessRate": "Success rate"}}+ },+ "queue": {+ "title": "Queue Management",+ "indicator": {+ "pending": "Pending",+ "processing": "Processing",+ "completed": "Completed",+ "failed": "Failed"+ },+ "actions": {+ "refresh": "Refresh Data",+ "clearCompleted": "Clear Completed",+ "clearFailed": "Clear Failed",+ "clearAll": "Clear All",+ "retrySelected": "Retry Selected",+ "retryAll": "Retry All Failed",+ "clearNonActive": "Clear Non-Active"+ },+ "table": {+ "id": "Task ID",+ "type": "Type",+ "status": "Status",+ "attempts": "Attempts",+ "priority": "Priority",+ "stage": "Stage",+ "error": "Error",+ "createdAt": "Created At",+ "completedAt": "Completed At",+ "actions": "Actions"+ },+ "status": {+ "pending": "Pending",+ "in-stages": "Processing",+ "completed": "Completed",+ "failed": "Failed"+ },+ "types": {+ "photo": "Photo Processing",+ "live-photo-video": "LivePhoto Video"+ },+ "stages": {+ "preprocessing": "Preprocessing",+ "metadata": "Metadata",+ "thumbnail": "Thumbnail",+ "exif": "EXIF Processing",+ "reverse-geocoding": "Geocoding",+ "live-photo": "LivePhoto Processing"+ },+ "buttons": {+ "retry": "Retry",+ "delete": "Delete"+ },+ "messages": {+ "noTasks": "No tasks found",+ "retrySuccess": "Task retry successful",+ "deleteSuccess": "Task deleted successfully",+ "batchRetrySuccess": "Batch retry successful",+ "clearSuccess": "Clear completed",+ "operationFailed": "Operation failed"+ },+ "filters": {+ "all": "All",+ "status": "Filter by Status",+ "type": "Filter by Type"+ }}}}\ No newline at end of filediff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.jsonindex 5c0df19a..3be944f9 100644--- a/i18n/locales/zh-Hans.json+++ b/i18n/locales/zh-Hans.json@@ -341,6 +341,71 @@"avgSuccessRate": "成功率"}}+ },+ "queue": {+ "title": "队列管理",+ "indicator": {+ "pending": "等待处理",+ "processing": "正在处理",+ "completed": "已完成",+ "failed": "失败任务"+ },+ "actions": {+ "refresh": "刷新数据",+ "clearCompleted": "清理已完成",+ "clearFailed": "清理失败任务",+ "clearAll": "清理全部",+ "retrySelected": "重试选中",+ "retryAll": "重试全部失败",+ "clearNonActive": "清理非活跃任务"+ },+ "table": {+ "id": "任务ID",+ "type": "类型",+ "status": "状态",+ "attempts": "尝试次数",+ "priority": "优先级",+ "stage": "处理阶段",+ "error": "错误信息",+ "createdAt": "创建时间",+ "completedAt": "完成时间",+ "actions": "操作"+ },+ "status": {+ "pending": "等待中",+ "in-stages": "处理中",+ "completed": "已完成",+ "failed": "失败"+ },+ "types": {+ "photo": "照片处理",+ "live-photo-video": "LivePhoto视频"+ },+ "stages": {+ "preprocessing": "预处理",+ "metadata": "元数据",+ "thumbnail": "缩略图",+ "exif": "EXIF处理",+ "reverse-geocoding": "地理解析",+ "live-photo": "LivePhoto处理"+ },+ "buttons": {+ "retry": "重试",+ "delete": "删除"+ },+ "messages": {+ "noTasks": "没有找到任务",+ "retrySuccess": "任务重试成功",+ "deleteSuccess": "任务删除成功",+ "batchRetrySuccess": "批量重试成功",+ "clearSuccess": "清理完成",+ "operationFailed": "操作失败"+ },+ "filters": {+ "all": "全部",+ "status": "按状态筛选",+ "type": "按类型筛选"+ }}}}diff --git a/server/api/queue/failed/[taskId]/delete.delete.ts b/server/api/queue/failed/[taskId]/delete.delete.tsdeleted file mode 100644index 0d82d580..00000000--- a/server/api/queue/failed/[taskId]/delete.delete.ts+++ /dev/null@@ -1,63 +0,0 @@-import { z } from 'zod'-import { eq } from 'drizzle-orm'--/**- * 删除失败的任务- */-export default defineEventHandler(async (event) => {- await requireUserSession(event)-- try {- const { taskId } = await getValidatedRouterParams(- event,- z.object({- taskId: z.string().transform(val => parseInt(val))- }).parse- )-- const db = useDB()-- // 检查任务是否存在- const task = await db- .select()- .from(tables.pipelineQueue)- .where(eq(tables.pipelineQueue.id, taskId))- .get()-- if (!task) {- throw createError({- statusCode: 404,- statusMessage: 'Task not found'- })- }-- if (task.status !== 'failed') {- throw createError({- statusCode: 400,- statusMessage: `Cannot delete task that is not failed, current status: ${task.status}`- })- }-- // 删除任务- await db- .delete(tables.pipelineQueue)- .where(eq(tables.pipelineQueue.id, taskId))-- logger.chrono.info(`Failed task ${taskId} has been deleted by user`)-- return {- success: true,- message: 'Failed task has been deleted',- taskId,- }- } catch (error: any) {- if (error.statusCode) {- throw error- }-- throw createError({- statusCode: 500,- statusMessage: error instanceof Error ? error.message : 'Failed to delete task',- })- }-})diff --git a/server/api/queue/failed/batch-delete.delete.ts b/server/api/queue/failed/batch-delete.delete.tsdeleted file mode 100644index 72a4f2f9..00000000--- a/server/api/queue/failed/batch-delete.delete.ts+++ /dev/null@@ -1,78 +0,0 @@-import { z } from 'zod'-import { eq, inArray } from 'drizzle-orm'--/**- * 批量删除失败的任务- */-export default defineEventHandler(async (event) => {- await requireUserSession(event)-- try {- const { taskIds, deleteAll = false } = await readValidatedBody(- event,- z.object({- taskIds: z.array(z.number()).optional(),- deleteAll: z.boolean().optional().default(false)- }).parse- )-- if (!deleteAll && (!taskIds || taskIds.length === 0)) {- throw createError({- statusCode: 400,- statusMessage: 'Either taskIds array or deleteAll flag must be provided'- })- }-- const db = useDB()-- let whereCondition- if (deleteAll) {- whereCondition = eq(tables.pipelineQueue.status, 'failed')- } else {- whereCondition = inArray(tables.pipelineQueue.id, taskIds!)- }-- // 检查要删除的任务- const tasksToDelete = await db- .select()- .from(tables.pipelineQueue)- .where(whereCondition)-- const failedTasks = tasksToDelete.filter(task => task.status === 'failed')-- if (failedTasks.length === 0) {- return {- success: true,- message: 'No failed tasks found to delete',- deletedCount: 0,- }- }-- // 批量删除失败的任务- await db- .delete(tables.pipelineQueue)- .where(- deleteAll- ? eq(tables.pipelineQueue.status, 'failed')- : inArray(tables.pipelineQueue.id, failedTasks.map(t => t.id))- )-- logger.chrono.info(`${failedTasks.length} failed tasks have been deleted by user`)-- return {- success: true,- message: `${failedTasks.length} failed tasks have been deleted`,- deletedCount: failedTasks.length,- taskIds: failedTasks.map(t => t.id),- }- } catch (error: any) {- if (error.statusCode) {- throw error- }-- throw createError({- statusCode: 500,- statusMessage: error instanceof Error ? error.message : 'Failed to delete tasks',- })- }-})diff --git a/server/api/queue/failed/list.get.ts b/server/api/queue/failed/list.get.tsdeleted file mode 100644index 29dc0543..00000000--- a/server/api/queue/failed/list.get.ts+++ /dev/null@@ -1,90 +0,0 @@-import { z } from 'zod'-import { eq, desc, sql } from 'drizzle-orm'--/**- * 获取失败任务列表- */-export default defineEventHandler(async (event) => {- await requireUserSession(event)-- try {- const query = getQuery(event)- const {- page = '1',- limit = '20',- type- } = await z.object({- page: z.string().optional().default('1'),- limit: z.string().optional().default('20'),- type: z.enum(['photo', 'live-photo-video']).optional()- }).parseAsync(query)-- const pageNum = parseInt(page)- const limitNum = parseInt(limit)- const offset = (pageNum - 1) * limitNum-- const db = useDB()-- // 构建查询条件- let whereCondition = eq(tables.pipelineQueue.status, 'failed')-- // 构建查询- const queryBuilder = db- .select({- id: tables.pipelineQueue.id,- payload: tables.pipelineQueue.payload,- attempts: tables.pipelineQueue.attempts,- maxAttempts: tables.pipelineQueue.maxAttempts,- errorMessage: tables.pipelineQueue.errorMessage,- createdAt: tables.pipelineQueue.createdAt,- completedAt: tables.pipelineQueue.completedAt,- })- .from(tables.pipelineQueue)- .where(whereCondition)- .orderBy(desc(tables.pipelineQueue.createdAt))- .limit(limitNum)- .offset(offset)-- const failedTasks = await queryBuilder-- // 统计总数- const totalResult = await db- .select({ count: sql<number>`COUNT(*)` })- .from(tables.pipelineQueue)- .where(whereCondition)-- const total = totalResult[0].count-- // 格式化结果- const formattedTasks = failedTasks.map(task => ({- id: task.id,- type: task.payload.type,- storageKey: task.payload.storageKey,- attempts: task.attempts,- maxAttempts: task.maxAttempts,- errorMessage: task.errorMessage,- createdAt: task.createdAt,- completedAt: task.completedAt,- }))-- return {- success: true,- data: {- tasks: formattedTasks,- pagination: {- page: pageNum,- limit: limitNum,- total,- totalPages: Math.ceil(total / limitNum),- hasNext: pageNum * limitNum < total,- hasPrev: pageNum > 1,- },- },- }- } catch (error: any) {- throw createError({- statusCode: 500,- statusMessage: error instanceof Error ? error.message : 'Failed to get failed tasks',- })- }-})diff --git a/server/api/queue/task/clear.delete.ts b/server/api/queue/task/clear.delete.tsnew file mode 100644index 00000000..2c7ae124--- /dev/null+++ b/server/api/queue/task/clear.delete.ts@@ -0,0 +1,121 @@+import { z } from 'zod'+import { or, eq, sql } from 'drizzle-orm'++/**+ * 清理非进行中的任务(已完成和失败的任务)+ */+export default defineEventHandler(async (event) => {+ await requireUserSession(event)++ try {+ const query = getQuery(event)+ const {+ includeCompleted = 'true',+ includeFailed = 'true',+ olderThanDays+ } = await z.object({+ includeCompleted: z.string().optional().default('true'),+ includeFailed: z.string().optional().default('true'),+ olderThanDays: z.string().optional()+ }).parseAsync(query)++ const shouldIncludeCompleted = includeCompleted === 'true'+ const shouldIncludeFailed = includeFailed === 'true'++ if (!shouldIncludeCompleted && !shouldIncludeFailed) {+ throw createError({+ statusCode: 400,+ statusMessage: 'At least one of includeCompleted or includeFailed must be true'+ })+ }++ const db = useDB()++ // 构建状态条件+ const statusConditions = []+ if (shouldIncludeCompleted) {+ statusConditions.push(eq(tables.pipelineQueue.status, 'completed'))+ }+ if (shouldIncludeFailed) {+ statusConditions.push(eq(tables.pipelineQueue.status, 'failed'))+ }++ let whereCondition = or(...statusConditions)++ // 如果指定了时间范围,添加时间条件+ if (olderThanDays) {+ const daysThreshold = parseInt(olderThanDays)+ if (isNaN(daysThreshold) || daysThreshold < 0) {+ throw createError({+ statusCode: 400,+ statusMessage: 'olderThanDays must be a non-negative integer'+ })+ }++ const thresholdTimestamp = Math.floor((Date.now() - daysThreshold * 24 * 60 * 60 * 1000) / 1000)+ const timeCondition = sql`${tables.pipelineQueue.createdAt} < ${thresholdTimestamp}`++ whereCondition = sql`(${whereCondition}) AND ${timeCondition}`+ }++ // 首先查询要删除的任务以便返回统计信息+ const tasksToDelete = await db+ .select({+ id: tables.pipelineQueue.id,+ status: tables.pipelineQueue.status,+ payload: tables.pipelineQueue.payload,+ createdAt: tables.pipelineQueue.createdAt+ })+ .from(tables.pipelineQueue)+ .where(whereCondition)++ if (tasksToDelete.length === 0) {+ return {+ success: true,+ message: 'No tasks found to clear',+ deletedCount: 0,+ breakdown: {+ completed: 0,+ failed: 0+ }+ }+ }++ // 执行删除操作+ await db+ .delete(tables.pipelineQueue)+ .where(whereCondition)++ // 统计删除的任务+ const breakdown = tasksToDelete.reduce((acc, task) => {+ acc[task.status] = (acc[task.status] || 0) + 1+ return acc+ }, {} as Record<string, number>)++ return {+ success: true,+ message: `Successfully cleared ${tasksToDelete.length} non-active tasks`,+ deletedCount: tasksToDelete.length,+ breakdown: {+ completed: breakdown.completed || 0,+ failed: breakdown.failed || 0+ },+ ...(olderThanDays && {+ filter: {+ olderThanDays: parseInt(olderThanDays),+ thresholdDate: new Date(Date.now() - parseInt(olderThanDays) * 24 * 60 * 60 * 1000).toISOString()+ }+ })+ }+ } catch (error) {+ if (error && typeof error === 'object' && 'statusCode' in error) {+ throw error+ }++ console.error('Failed to clear tasks:', error)+ throw createError({+ statusCode: 500,+ statusMessage: 'Failed to clear tasks'+ })+ }+})\ No newline at end of filediff --git a/server/api/queue/task/list.get.ts b/server/api/queue/task/list.get.tsnew file mode 100644index 00000000..9ba41346--- /dev/null+++ b/server/api/queue/task/list.get.ts@@ -0,0 +1,69 @@+import { z } from 'zod'+import { desc, sql, eq, and } from 'drizzle-orm'++/**+ * 获取所有队列任务记录列表+ */+export default defineEventHandler(async (event) => {+ await requireUserSession(event)++ try {+ const query = getQuery(event)+ const {+ status,+ type+ } = await z.object({+ status: z.enum(['pending', 'in-stages', 'completed', 'failed']).optional(),+ type: z.enum(['photo', 'live-photo-video']).optional()+ }).parseAsync(query)++ const db = useDB()++ // 构建查询条件+ const conditions = []++ if (status) {+ conditions.push(eq(tables.pipelineQueue.status, status))+ }++ if (type) {+ conditions.push(eq(sql`json_extract(${tables.pipelineQueue.payload}, '$.type')`, type))+ }++ const whereCondition = conditions.length > 0 ? and(...conditions) : undefined++ // 构建查询+ const queryBuilder = db+ .select({+ id: tables.pipelineQueue.id,+ payload: tables.pipelineQueue.payload,+ priority: tables.pipelineQueue.priority,+ attempts: tables.pipelineQueue.attempts,+ maxAttempts: tables.pipelineQueue.maxAttempts,+ status: tables.pipelineQueue.status,+ statusStage: tables.pipelineQueue.statusStage,+ errorMessage: tables.pipelineQueue.errorMessage,+ createdAt: tables.pipelineQueue.createdAt,+ completedAt: tables.pipelineQueue.completedAt,+ })+ .from(tables.pipelineQueue)+ .orderBy(desc(tables.pipelineQueue.createdAt))++ if (whereCondition) {+ queryBuilder.where(whereCondition)+ }++ const tasks = await queryBuilder++ return {+ success: true,+ data: tasks,+ }+ } catch (error) {+ console.error('Failed to fetch task list:', error)+ throw createError({+ statusCode: 500,+ statusMessage: 'Failed to fetch task list',+ })+ }+})\ No newline at end of filediff --git a/server/api/queue/failed/batch-retry.post.ts b/server/api/queue/task/retry-batch.post.tssimilarity index 56%rename from server/api/queue/failed/batch-retry.post.tsrename to server/api/queue/task/retry-batch.post.tsindex f6728797..d771d904 100644--- a/server/api/queue/failed/batch-retry.post.ts+++ b/server/api/queue/task/retry-batch.post.ts@@ -11,7 +11,7 @@ export default defineEventHandler(async (event) => {const { taskIds, retryAll = false } = await readValidatedBody(event,z.object({- taskIds: z.array(z.number()).optional(),+ taskIds: z.array(z.number().int().positive()).optional(),retryAll: z.boolean().optional().default(false)}).parse)@@ -45,43 +45,51 @@ export default defineEventHandler(async (event) => {success: true,message: 'No failed tasks found to retry',retriedCount: 0,+ skippedCount: retryAll ? 0 : (taskIds?.length || 0)}}- // 批量重试失败的任务+ const nonFailedTasks = tasksToRetry.filter(task => task.status !== 'failed')++ // 批量重置失败任务的状态+ const failedTaskIds = failedTasks.map(task => task.id)+await db.update(tables.pipelineQueue).set({status: 'pending',- attempts: 0,- errorMessage: null,statusStage: null,- priority: 1, // 设置高优先级- createdAt: new Date(), // 重新设置创建时间- completedAt: null,+ errorMessage: null,+ attempts: 0, // 重置尝试次数+ createdAt: new Date() // 更新创建时间以便重新调度})- .where(- retryAll- ? eq(tables.pipelineQueue.status, 'failed')- : inArray(tables.pipelineQueue.id, failedTasks.map(t => t.id))- )-- logger.chrono.info(`${failedTasks.length} failed tasks have been reset for retry by user`)+ .where(inArray(tables.pipelineQueue.id, failedTaskIds))return {success: true,- message: `${failedTasks.length} failed tasks have been reset and will be retried`,+ message: `Successfully reset ${failedTasks.length} failed tasks for retry`,retriedCount: failedTasks.length,- taskIds: failedTasks.map(t => t.id),+ skippedCount: nonFailedTasks.length,+ retriedTasks: failedTasks.map(task => ({+ id: task.id,+ type: task.payload.type,+ storageKey: task.payload.storageKey+ })),+ skippedTasks: nonFailedTasks.map(task => ({+ id: task.id,+ status: task.status,+ reason: `Task is not in failed status (current: ${task.status})`+ }))}- } catch (error: any) {- if (error.statusCode) {+ } catch (error) {+ if (error && typeof error === 'object' && 'statusCode' in error) {throw error}-++ console.error('Failed to batch retry tasks:', error)throw createError({statusCode: 500,- statusMessage: error instanceof Error ? error.message : 'Failed to retry tasks',+ statusMessage: 'Failed to batch retry tasks'})}-})+})\ No newline at end of filediff --git a/server/api/queue/failed/[taskId]/retry.post.ts b/server/api/queue/task/retry.post.tssimilarity index 61%rename from server/api/queue/failed/[taskId]/retry.post.tsrename to server/api/queue/task/retry.post.tsindex 055b84b7..2816284f 100644--- a/server/api/queue/failed/[taskId]/retry.post.ts+++ b/server/api/queue/task/retry.post.ts@@ -2,16 +2,16 @@ import { z } from 'zod'import { eq } from 'drizzle-orm'/**- * 重试失败的任务+ * 重试指定的失败任务*/export default defineEventHandler(async (event) => {await requireUserSession(event)try {- const { taskId } = await getValidatedRouterParams(+ const { taskId } = await readValidatedBody(event,z.object({- taskId: z.string().transform(val => parseInt(val))+ taskId: z.number().int().positive()}).parse)@@ -38,35 +38,36 @@ export default defineEventHandler(async (event) => {})}- // 重置任务状态,清除错误信息,重置尝试次数+ // 重置任务状态为 pending,清除错误信息和状态阶段await db.update(tables.pipelineQueue).set({status: 'pending',- attempts: 0,- errorMessage: null,statusStage: null,- priority: 1, // 设置高优先级- createdAt: new Date(), // 重新设置创建时间- completedAt: null,+ errorMessage: null,+ attempts: 0, // 重置尝试次数+ createdAt: new Date() // 更新创建时间以便重新调度}).where(eq(tables.pipelineQueue.id, taskId))- logger.chrono.info(`Task ${taskId} has been reset for retry by user`)-return {success: true,- message: 'Task has been reset and will be retried',+ message: `Task ${taskId} has been reset and will be retried`,taskId,+ payload: {+ type: task.payload.type,+ storageKey: task.payload.storageKey+ }}- } catch (error: any) {- if (error.statusCode) {+ } catch (error) {+ if (error && typeof error === 'object' && 'statusCode' in error) {throw error}-++ console.error('Failed to retry task:', error)throw createError({statusCode: 500,- statusMessage: error instanceof Error ? error.message : 'Failed to retry task',+ statusMessage: 'Failed to retry task'})}-})+})\ No newline at end of file