Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

feat(dashboard): add queue management feature and enhance UI components LivePhoto找不到匹配照片(只上传视频文件会造成阻塞):确保对应照片已上传后重试

cuijianzhuang5e80255e7efd
diff --git a/app/components/dashboard/Indicator.vue b/app/components/dashboard/Indicator.vue
index 4114116f..abed78db 100644
--- a/app/components/dashboard/Indicator.vue
+++ b/app/components/dashboard/Indicator.vue
@@ -5,15 +5,21 @@ const props = withDefaults(
value?: string | number
icon?: string
color?: keyof typeof colorSchemes
+ clickable?: boolean
}>(),
{
title: undefined,
value: undefined,
icon: undefined,
color: 'blue',
+ clickable: false,
},
)
+const emit = defineEmits<{
+ click: []
+}>()
+
const colorSchemes = {
blue: {
background:
@@ -75,7 +81,9 @@ const currentScheme = computed(() => colorSchemes[props.color])
currentScheme.background,
currentScheme.border,
currentScheme.text,
+ clickable ? 'cursor-pointer hover:scale-105 transition-transform' : '',
]"
+ @click="clickable ? emit('click') : undefined"
>
<div class="flex-1 flex items-center justify-between gap-4 overflow-hidden">
<div class="flex-1 overflow-hidden">
diff --git a/app/components/ui/UploadQueuePanel.vue b/app/components/ui/UploadQueuePanel.vue
index 2cd4da56..0a727f9f 100644
--- a/app/components/ui/UploadQueuePanel.vue
+++ b/app/components/ui/UploadQueuePanel.vue
@@ -39,6 +39,7 @@ const emit = defineEmits<{
clearCompleted: []
clearAll: []
toggle: []
+ goToQueue: []
}>()
const isCollapsed = ref(props.collapsed || false)
@@ -299,6 +300,16 @@ const clearAllFiles = () => {
>
清除全部
</UButton>
+
+ <UButton
+ size="xs"
+ variant="ghost"
+ color="blue"
+ icon="tabler:list-check"
+ @click="emit('goToQueue')"
+ >
+ 队列管理
+ </UButton>
</div>
</div>
</motion.div>
diff --git a/app/layouts/dashboard.vue b/app/layouts/dashboard.vue
index fef43825..91e684f4 100644
--- a/app/layouts/dashboard.vue
+++ b/app/layouts/dashboard.vue
@@ -18,6 +18,11 @@ const items = ref<NavigationMenuItem[]>([
icon: 'tabler:map-pin-cog',
to: '/dashboard/location',
},
+ {
+ label: $t('title.queue'),
+ icon: 'tabler:list-check',
+ to: '/dashboard/queue',
+ },
])
const route = useRoute()
diff --git a/app/pages/dashboard/index.vue b/app/pages/dashboard/index.vue
index 0417748d..1781997a 100644
--- a/app/pages/dashboard/index.vue
+++ b/app/pages/dashboard/index.vue
@@ -155,6 +155,8 @@ const yearOptions = computed(() => {
? $t('dashboard.overview.indicator.queueStatus.processing')
: $t('dashboard.overview.indicator.queueStatus.pending')
"
+ clickable
+ @click="$router.push('/dashboard/queue')"
/>
<DashboardIndicator
:title="$t('dashboard.overview.indicator.storageUsage')"
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index ffaaf806..596566aa 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -962,6 +962,7 @@ onUnmounted(() => {
@remove-file="removeUploadingFile"
@clear-completed="clearCompletedUploads"
@clear-all="clearAllUploads"
+ @go-to-queue="$router.push('/dashboard/queue')"
/>
<!-- 文件上传组件 -->
diff --git a/app/pages/dashboard/queue.vue b/app/pages/dashboard/queue.vue
new file mode 100644
index 00000000..b4018584
--- /dev/null
+++ b/app/pages/dashboard/queue.vue
@@ -0,0 +1,306 @@
+<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>
+
+ <!-- 队列统计 -->
+ <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>
+
+ <!-- 失败任务管理 -->
+ <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>
+
+ <div v-if="failedTasks.length === 0" class="p-8 text-center text-gray-500">
+ 没有失败的任务
+ </div>
+
+ <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>
+
+ <!-- 分页 -->
+ <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>
+
+<script setup lang="ts">
+definePageMeta({
+ layout: 'dashboard'
+})
+
+// 响应式数据
+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 fetchQueueStats = async () => {
+ try {
+ 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)
+ }
+}
+
+// 获取失败任务列表
+const fetchFailedTasks = async (page = 1) => {
+ loading.value = true
+ 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)
+ } finally {
+ loading.value = false
+ }
+}
+
+// 重试单个任务
+const retryTask = async (taskId: number) => {
+ actionLoading.value = true
+ try {
+ await $fetch(`/api/queue/failed/${taskId}/retry`, { method: 'POST' })
+ await refreshData()
+ } catch (error) {
+ console.error('重试任务失败:', error)
+ } finally {
+ actionLoading.value = false
+ }
+}
+
+// 删除单个任务
+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
+ }
+}
+
+// 重试所有失败任务
+const retryAllFailed = async () => {
+ if (!confirm('确定要重试所有失败的任务吗?')) return
+
+ actionLoading.value = true
+ try {
+ await $fetch('/api/queue/failed/batch-retry', {
+ method: 'POST',
+ body: { retryAll: true }
+ })
+ await refreshData()
+ } catch (error) {
+ console.error('批量重试失败:', error)
+ } finally {
+ actionLoading.value = false
+ }
+}
+
+// 删除所有失败任务
+const deleteAllFailed = async () => {
+ if (!confirm('确定要删除所有失败的任务吗?此操作不可恢复!')) return
+
+ actionLoading.value = true
+ try {
+ await $fetch('/api/queue/failed/batch-delete', {
+ 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,暂时使用命令行脚本的逻辑
+ await refreshData()
+ } catch (error) {
+ console.error('清理阻塞任务失败:', error)
+ } finally {
+ cleanupLoading.value = false
+ }
+}
+
+// 换页
+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: '失败'
+ }
+ 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 getStatusIcon = (status: string) => {
+ // 这里可以返回图标组件名称,需要根据你的图标库调整
+ return 'div'
+}
+
+const formatTime = (timestamp: number) => {
+ return new Date(timestamp * 1000).toLocaleString()
+}
+
+// 组件挂载时获取数据
+onMounted(() => {
+ refreshData()
+})
+</script>
diff --git a/i18n/locales/en.json b/i18n/locales/en.json
index 2d87eaa1..c9b68b3b 100644
--- a/i18n/locales/en.json
+++ b/i18n/locales/en.json
@@ -248,7 +248,8 @@
"dashboard": "Dashboard",
"photos": "Photos",
"locations": "Locations",
- "globe": "Photo Globe"
+ "globe": "Photo Globe",
+ "queue": "Queue Management"
},
"auth": {
"form": {
diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.json
index b2048ba8..5c0df19a 100644
--- a/i18n/locales/zh-Hans.json
+++ b/i18n/locales/zh-Hans.json
@@ -248,7 +248,8 @@
"gallery": "相册",
"locations": "位置管理",
"photos": "照片库",
- "globe": "照片地球仪"
+ "globe": "照片地球仪",
+ "queue": "队列管理"
},
"auth": {
"form": {
diff --git a/scripts/check-queue-status.mjs b/scripts/check-queue-status.mjs
new file mode 100644
index 00000000..c77d63db
--- /dev/null
+++ b/scripts/check-queue-status.mjs
@@ -0,0 +1,177 @@
+#!/usr/bin/env node
+/**
+ * 检查和清理队列状态的脚本
+ */
+
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import Database from 'better-sqlite3'
+import { eq, sql } from 'drizzle-orm'
+import { fileURLToPath } from 'url'
+import path from 'path'
+
+// 获取项目根目录
+const __filename = fileURLToPath(import.meta.url)
+const __dirname = path.dirname(__filename)
+const projectRoot = path.resolve(__dirname, '..')
+
+// 数据库路径
+const dbPath = path.join(projectRoot, 'data', 'app.sqlite3')
+
+// 模拟数据库模式
+const pipelineQueue = {
+ id: 'integer',
+ payload: 'text',
+ priority: 'integer',
+ attempts: 'integer',
+ maxAttempts: 'integer',
+ status: 'text',
+ statusStage: 'text',
+ errorMessage: 'text',
+ createdAt: 'integer',
+ completedAt: 'integer'
+}
+
+async function checkQueueStatus() {
+ const sqlite = new Database(dbPath)
+ const db = drizzle(sqlite)
+
+ console.log('🔍 检查队列状态...\n')
+
+ try {
+ // 查询队列统计
+ const stats = await db.all(sql`
+ SELECT
+ status,
+ COUNT(*) as count,
+ AVG(attempts) as avg_attempts
+ FROM pipeline_queue
+ GROUP BY status
+ ORDER BY status
+ `)
+
+ console.log('📊 队列状态统计:')
+ stats.forEach(stat => {
+ console.log(` ${stat.status}: ${stat.count} 任务 (平均尝试次数: ${stat.avg_attempts?.toFixed(1) || 0})`)
+ })
+
+ // 查找 in-stages 状态的任务(可能被阻塞)
+ const inStagesTasks = await db.all(sql`
+ SELECT id, payload, attempts, max_attempts, status_stage, error_message, created_at
+ FROM pipeline_queue
+ WHERE status = 'in-stages'
+ ORDER BY created_at DESC
+ `)
+
+ if (inStagesTasks.length > 0) {
+ console.log('\n⚠️ 发现可能被阻塞的任务 (in-stages 状态):')
+ inStagesTasks.forEach(task => {
+ const payload = JSON.parse(task.payload)
+ const createdAt = new Date(task.created_at * 1000).toLocaleString()
+ console.log(` 任务 ${task.id}: ${payload.type} - ${payload.storageKey}`)
+ console.log(` 创建时间: ${createdAt}`)
+ console.log(` 尝试次数: ${task.attempts}/${task.max_attempts}`)
+ console.log(` 当前阶段: ${task.status_stage || 'N/A'}`)
+ if (task.error_message) {
+ console.log(` 错误信息: ${task.error_message}`)
+ }
+ console.log('')
+ })
+ }
+
+ // 查找失败的 LivePhoto 任务
+ const failedLivePhotoTasks = await db.all(sql`
+ SELECT id, payload, attempts, max_attempts, error_message, created_at
+ FROM pipeline_queue
+ WHERE status = 'failed'
+ AND json_extract(payload, '$.type') = 'live-photo-video'
+ ORDER BY created_at DESC
+ LIMIT 10
+ `)
+
+ if (failedLivePhotoTasks.length > 0) {
+ console.log('\n❌ 最近失败的 LivePhoto 任务:')
+ failedLivePhotoTasks.forEach(task => {
+ const payload = JSON.parse(task.payload)
+ const createdAt = new Date(task.created_at * 1000).toLocaleString()
+ console.log(` 任务 ${task.id}: ${payload.storageKey}`)
+ console.log(` 创建时间: ${createdAt}`)
+ console.log(` 尝试次数: ${task.attempts}/${task.max_attempts}`)
+ console.log(` 错误信息: ${task.error_message || 'N/A'}`)
+ console.log('')
+ })
+ }
+
+ // 查找等待重试的任务
+ const pendingRetryTasks = await db.all(sql`
+ SELECT id, payload, attempts, max_attempts, error_message, created_at
+ FROM pipeline_queue
+ WHERE status = 'pending'
+ AND attempts > 0
+ ORDER BY created_at DESC
+ LIMIT 5
+ `)
+
+ if (pendingRetryTasks.length > 0) {
+ console.log('\n🔄 等待重试的任务:')
+ pendingRetryTasks.forEach(task => {
+ const payload = JSON.parse(task.payload)
+ const createdAt = new Date(task.created_at * 1000).toLocaleString()
+ console.log(` 任务 ${task.id}: ${payload.type} - ${payload.storageKey}`)
+ console.log(` 创建时间: ${createdAt}`)
+ console.log(` 尝试次数: ${task.attempts}/${task.max_attempts}`)
+ console.log(` 最后错误: ${task.error_message || 'N/A'}`)
+ console.log('')
+ })
+ }
+
+ } catch (error) {
+ console.error('❌ 检查队列状态时出错:', error)
+ } finally {
+ sqlite.close()
+ }
+}
+
+async function cleanupBlockedTasks() {
+ const sqlite = new Database(dbPath)
+ const db = drizzle(sqlite)
+
+ console.log('\n🧹 清理被阻塞的任务...')
+
+ try {
+ // 将 in-stages 状态的任务重置为 pending
+ const result = await db.run(sql`
+ UPDATE pipeline_queue
+ SET
+ status = 'pending',
+ priority = 1,
+ status_stage = NULL
+ WHERE status = 'in-stages'
+ `)
+
+ if (result.changes > 0) {
+ console.log(`✅ 已重置 ${result.changes} 个被阻塞的任务为待处理状态`)
+ } else {
+ console.log('✅ 没有发现被阻塞的任务')
+ }
+
+ } catch (error) {
+ console.error('❌ 清理任务时出错:', error)
+ } finally {
+ sqlite.close()
+ }
+}
+
+// 主函数
+async function main() {
+ const args = process.argv.slice(2)
+
+ if (args.includes('--cleanup')) {
+ await cleanupBlockedTasks()
+ }
+
+ await checkQueueStatus()
+
+ console.log('\n💡 使用 --cleanup 参数来清理被阻塞的任务')
+}
+
+main().catch(console.error)
diff --git a/server/api/queue/failed/[taskId]/delete.delete.ts b/server/api/queue/failed/[taskId]/delete.delete.ts
new file mode 100644
index 00000000..0d82d580
--- /dev/null
+++ b/server/api/queue/failed/[taskId]/delete.delete.ts
@@ -0,0 +1,63 @@
+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/[taskId]/retry.post.ts b/server/api/queue/failed/[taskId]/retry.post.ts
new file mode 100644
index 00000000..055b84b7
--- /dev/null
+++ b/server/api/queue/failed/[taskId]/retry.post.ts
@@ -0,0 +1,72 @@
+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: `Task is not in failed status, current status: ${task.status}`
+ })
+ }
+
+ // 重置任务状态,清除错误信息,重置尝试次数
+ await db
+ .update(tables.pipelineQueue)
+ .set({
+ status: 'pending',
+ attempts: 0,
+ errorMessage: null,
+ statusStage: null,
+ priority: 1, // 设置高优先级
+ createdAt: new Date(), // 重新设置创建时间
+ completedAt: null,
+ })
+ .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',
+ taskId,
+ }
+ } catch (error: any) {
+ if (error.statusCode) {
+ throw error
+ }
+
+ throw createError({
+ statusCode: 500,
+ statusMessage: error instanceof Error ? error.message : 'Failed to retry task',
+ })
+ }
+})
diff --git a/server/api/queue/failed/batch-delete.delete.ts b/server/api/queue/failed/batch-delete.delete.ts
new file mode 100644
index 00000000..72a4f2f9
--- /dev/null
+++ b/server/api/queue/failed/batch-delete.delete.ts
@@ -0,0 +1,78 @@
+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/batch-retry.post.ts b/server/api/queue/failed/batch-retry.post.ts
new file mode 100644
index 00000000..f6728797
--- /dev/null
+++ b/server/api/queue/failed/batch-retry.post.ts
@@ -0,0 +1,87 @@
+import { z } from 'zod'
+import { eq, inArray } from 'drizzle-orm'
+
+/**
+ * 批量重试失败的任务
+ */
+export default defineEventHandler(async (event) => {
+ await requireUserSession(event)
+
+ try {
+ const { taskIds, retryAll = false } = await readValidatedBody(
+ event,
+ z.object({
+ taskIds: z.array(z.number()).optional(),
+ retryAll: z.boolean().optional().default(false)
+ }).parse
+ )
+
+ if (!retryAll && (!taskIds || taskIds.length === 0)) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: 'Either taskIds array or retryAll flag must be provided'
+ })
+ }
+
+ const db = useDB()
+
+ let whereCondition
+ if (retryAll) {
+ whereCondition = eq(tables.pipelineQueue.status, 'failed')
+ } else {
+ whereCondition = inArray(tables.pipelineQueue.id, taskIds!)
+ }
+
+ // 检查要重试的任务
+ const tasksToRetry = await db
+ .select()
+ .from(tables.pipelineQueue)
+ .where(whereCondition)
+
+ const failedTasks = tasksToRetry.filter(task => task.status === 'failed')
+
+ if (failedTasks.length === 0) {
+ return {
+ success: true,
+ message: 'No failed tasks found to retry',
+ retriedCount: 0,
+ }
+ }
+
+ // 批量重试失败的任务
+ await db
+ .update(tables.pipelineQueue)
+ .set({
+ status: 'pending',
+ attempts: 0,
+ errorMessage: null,
+ statusStage: null,
+ priority: 1, // 设置高优先级
+ createdAt: new Date(), // 重新设置创建时间
+ completedAt: null,
+ })
+ .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`)
+
+ return {
+ success: true,
+ message: `${failedTasks.length} failed tasks have been reset and will be retried`,
+ retriedCount: 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 retry tasks',
+ })
+ }
+})
diff --git a/server/api/queue/failed/list.get.ts b/server/api/queue/failed/list.get.ts
new file mode 100644
index 00000000..29dc0543
--- /dev/null
+++ b/server/api/queue/failed/list.get.ts
@@ -0,0 +1,90 @@
+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/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index 29b79b32..16b15116 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -428,7 +428,7 @@ export class QueueManager {
this.logger.warn(
`No matching photo found for LivePhoto video: ${videoKey}`,
)
- return null
+ throw new Error(`No matching photo found for LivePhoto video: ${videoKey}`)
}
const livePhotoVideoUrl = storageProvider.getPublicUrl(videoKey)