From 51f2fb30a1f89c17fc81ce8f240baa8aac53fc14 Mon Sep 17 00:00:00 2001 From: chenpei Date: Wed, 29 Jul 2026 13:46:16 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=90=88=E5=B9=B6=E6=97=A7=E5=88=86?= =?UTF-8?q?=E6=94=AF=E4=B8=AD=E7=9A=84=E4=B8=8A=E4=BC=A0=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E7=A8=B3=E5=AE=9A=E6=80=A7=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/external/download/route.ts | 210 ++++++++++-------- .../materials/[id]/retry-transcode/route.ts | 24 +- .../[id]/skus/batch-download/route.ts | 65 ++++-- app/api/performance/quick/route.ts | 68 ++---- lib/__tests__/retry-transcode-route.test.ts | 84 +++++++ lib/__tests__/s3-key-from-url.test.ts | 34 +++ lib/s3.ts | 40 ++-- lib/upload-sessions-redis.ts | 84 +++++-- lib/upload-sessions.ts | 53 +++++ lib/video-processor.ts | 38 ++-- 10 files changed, 491 insertions(+), 209 deletions(-) create mode 100644 lib/__tests__/retry-transcode-route.test.ts create mode 100644 lib/__tests__/s3-key-from-url.test.ts diff --git a/app/api/external/download/route.ts b/app/api/external/download/route.ts index a395b85b..9dba40ed 100644 --- a/app/api/external/download/route.ts +++ b/app/api/external/download/route.ts @@ -400,21 +400,32 @@ async function downloadSingleFile(asset: any) { if (isHttpUrl(normalizedFileUrl)) { try { const response = await fetch(normalizedFileUrl); - if (!response.ok) { + if (!response.ok || !response.body) { return NextResponse.json( { success: false, error: { code: 'FILE_NOT_FOUND', message: '文件不存在' } }, { status: 404 } ); } - const arrayBuffer = await response.arrayBuffer(); const contentType = response.headers.get('content-type') || getContentType(fileName); + const contentLength = response.headers.get('content-length'); + const nodeStream = Readable.fromWeb(response.body as any); + const stream = new ReadableStream({ + start(controller) { + nodeStream.on('data', (chunk) => controller.enqueue(chunk)); + nodeStream.on('end', () => controller.close()); + nodeStream.on('error', (error) => controller.error(error)); + }, + cancel() { + nodeStream.destroy(); + }, + }); - return new NextResponse(arrayBuffer, { + return new NextResponse(stream as any, { headers: { 'Content-Type': contentType, 'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}"`, - 'Content-Length': arrayBuffer.byteLength.toString(), + ...(contentLength ? { 'Content-Length': contentLength } : {}), }, }); } catch (error) { @@ -502,75 +513,86 @@ async function downloadAsZip(assets: any[], taskNo: string, downloadType: string console.log(`[downloadAsZip] 资产 ${index + 1}: type=${asset.assetType}, url=${asset.fileUrl}, fileName=${asset.fileName}`); }); - return new Promise((resolve, reject) => { - const archive = archiver('zip', { zlib: { level: 5 } }); - const chunks: Buffer[] = []; - let successCount = 0; - let failCount = 0; + const archive = archiver('zip', { zlib: { level: 5 } }); + let successCount = 0; + let failCount = 0; - archive.on('data', (chunk) => chunks.push(chunk)); - archive.on('end', () => { - const buffer = Buffer.concat(chunks); - const fileName = `${taskNo}-${downloadType}.zip`; - - console.log(`[downloadAsZip] 打包完成: 成功 ${successCount} 个, 失败 ${failCount} 个`); - console.log(`[downloadAsZip] ZIP 文件大小: ${(buffer.length / 1024 / 1024).toFixed(2)} MB`); - console.log(`[downloadAsZip] ====================================`); + for (const asset of assets) { + const fileUrl = normalizeAssetFileUrl(asset.fileUrl); + const fileName = asset.fileName || path.basename(fileUrl); + const entryName = `${asset.assetType}/${fileName}`; - resolve(new NextResponse(buffer, { - headers: { - 'Content-Type': 'application/zip', - 'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}"`, - 'Content-Length': buffer.length.toString(), - }, - })); - }); - archive.on('error', (err) => { - console.error('[downloadAsZip] archive error:', err); - reject(err); - }); - - // 添加文件到压缩包 - (async () => { - for (const asset of assets) { - const fileUrl = asset.fileUrl; - const fileName = asset.fileName || path.basename(fileUrl); - const folder = asset.assetType; // main/sku/detail - - try { - if (fileUrl.startsWith('/uploads/') || fileUrl.startsWith('uploads/')) { - // 本地文件 - const localPath = path.join(process.cwd(), fileUrl.replace(/^\//, '')); - if (fs.existsSync(localPath)) { - archive.file(localPath, { name: `${folder}/${fileName}` }); - successCount++; - console.log(`[downloadAsZip] ✅ 添加本地文件成功: ${folder}/${fileName}`); - } else { - failCount++; - console.error(`[downloadAsZip] ❌ 本地文件不存在: ${localPath}`); - } - } else { - // 远程文件(S3) - console.log(`[downloadAsZip] 正在获取远程文件: ${fileUrl}`); - const response = await fetch(fileUrl); - if (response.ok) { - const arrayBuffer = await response.arrayBuffer(); - archive.append(Buffer.from(arrayBuffer), { name: `${folder}/${fileName}` }); - successCount++; - console.log(`[downloadAsZip] ✅ 添加远程文件成功: ${folder}/${fileName} (${(arrayBuffer.byteLength / 1024).toFixed(2)} KB)`); - } else { - failCount++; - console.error(`[downloadAsZip] ❌ 远程文件获取失败: ${fileUrl}, status=${response.status}`); - } - } - } catch (error) { - failCount++; - console.error(`[downloadAsZip] ❌ 添加文件失败: ${fileName}`, error); - } + try { + const localPath = resolveAssetLocalPath(fileUrl); + if (localPath && fs.existsSync(localPath)) { + archive.file(localPath, { name: entryName }); + successCount++; + continue; + } + if (localPath) { + console.error(`[downloadAsZip] ❌ 本地文件不存在: ${localPath}`); + failCount++; + continue; } - archive.finalize(); - })(); + if (isHttpUrl(fileUrl)) { + const response = await fetch(fileUrl); + if (response.ok && response.body) { + archive.append(Readable.fromWeb(response.body as any), { name: entryName }); + successCount++; + continue; + } + console.error(`[downloadAsZip] ❌ 远程文件获取失败: ${fileUrl}, status=${response.status}`); + } else { + console.error(`[downloadAsZip] ❌ 文件地址无效: ${fileUrl}`); + } + failCount++; + } catch (error) { + failCount++; + console.error(`[downloadAsZip] ❌ 添加文件失败: ${fileName}`, error); + } + } + + if (successCount === 0) { + archive.destroy(); + return NextResponse.json( + { success: false, error: { code: 'NO_FILES', message: '没有可下载的文件' } }, + { status: 404 } + ); + } + + const stream = new ReadableStream({ + start(controller) { + let settled = false; + const close = () => { + if (!settled) { + settled = true; + console.log(`[downloadAsZip] 打包完成: 成功 ${successCount} 个, 失败 ${failCount} 个`); + controller.close(); + } + }; + const fail = (error: Error) => { + if (!settled) { + settled = true; + controller.error(error); + } + }; + + archive.on('data', (chunk) => controller.enqueue(chunk)); + archive.on('end', close); + archive.on('error', fail); + void archive.finalize().catch(fail); + }, + cancel() { + archive.abort(); + }, + }); + + return new NextResponse(stream as any, { + headers: { + 'Content-Type': 'application/zip', + 'Content-Disposition': `attachment; filename="${encodeURIComponent(`${taskNo}-${downloadType}.zip`)}"`, + }, }); } @@ -1041,29 +1063,21 @@ async function buildDynamicZipFromDisplayImages(material: any) { ); } - const zip = new JSZip(); + const archive = archiver('zip', { zlib: { level: 6 } }); let addedCount = 0; for (let i = 0; i < displayImages.length; i++) { const imageUrl = displayImages[i]; try { const response = await fetch(imageUrl); - if (!response.ok) { + if (!response.ok || !response.body) { console.warn(`[external/download] Failed to fetch display image index=${i} url=${imageUrl}, status=${response.status}`); continue; } - const arrayBuffer = await response.arrayBuffer(); - const buffer = Buffer.from(arrayBuffer); - - if (!buffer || buffer.length === 0) { - console.warn(`[external/download] Empty buffer for display image index=${i} url=${imageUrl}, skipping`); - continue; - } - const urlObj = new URL(imageUrl); const filename = (path.basename(urlObj.pathname) || `image-${i + 1}.webp`).replace(/[^\w\-.]+/g, '_'); - zip.file(filename, buffer); + archive.append(Readable.fromWeb(response.body as any), { name: filename }); addedCount++; } catch (error) { console.error(`[external/download] Error while adding display image index=${i} url=${imageUrl} to zip:`, error); @@ -1071,18 +1085,13 @@ async function buildDynamicZipFromDisplayImages(material: any) { } if (addedCount === 0) { + archive.destroy(); return NextResponse.json( { success: false, error: { code: 'NO_DOWNLOADABLE_FILES', message: '该素材可能只包含图片' } }, { status: 404 } ); } - const zipBuffer = await zip.generateAsync({ - type: 'nodebuffer', - compression: 'DEFLATE', - compressionOptions: { level: 6 }, - }); - const filenameParts = [ material.productModel || 'unknown', material.categoryName || '', @@ -1093,10 +1102,35 @@ async function buildDynamicZipFromDisplayImages(material: any) { const filename = `${filenameParts.join('_')}.zip`; - return new NextResponse(zipBuffer as any, { + const stream = new ReadableStream({ + start(controller) { + let settled = false; + const close = () => { + if (!settled) { + settled = true; + controller.close(); + } + }; + const fail = (error: Error) => { + if (!settled) { + settled = true; + controller.error(error); + } + }; + + archive.on('data', (chunk) => controller.enqueue(chunk)); + archive.on('end', close); + archive.on('error', fail); + void archive.finalize().catch(fail); + }, + cancel() { + archive.abort(); + }, + }); + + return new NextResponse(stream as any, { headers: { 'Content-Type': 'application/zip', - 'Content-Length': zipBuffer.length.toString(), 'Content-Disposition': `attachment; filename="${encodeURIComponent(filename)}"`, }, }); diff --git a/app/api/materials/[id]/retry-transcode/route.ts b/app/api/materials/[id]/retry-transcode/route.ts index 158c7039..974ce883 100644 --- a/app/api/materials/[id]/retry-transcode/route.ts +++ b/app/api/materials/[id]/retry-transcode/route.ts @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' +import { enqueueVideoTranscodeTask } from '@/lib/video-transcode-task' // 重试转码API export async function POST( @@ -23,7 +24,8 @@ export async function POST( id: true, userId: true, videoProcessingStatus: true, - videoSourceUrl: true + videoSourceUrl: true, + videoCoverUrl: true, } }) @@ -57,9 +59,23 @@ export async function POST( } }) - // TODO: 这里应该触发实际的转码任务 - // 由于转码服务是后台运行的,这里只是更新状态 - // 实际的转码任务会由后台服务自动检测并处理 + try { + await enqueueVideoTranscodeTask( + materialId, + material.videoSourceUrl, + !material.videoCoverUrl + ) + } catch (enqueueError) { + const message = enqueueError instanceof Error ? enqueueError.message : String(enqueueError) + await prisma.material.update({ + where: { id: materialId }, + data: { + videoProcessingStatus: 'failed', + transcodeLastError: message.slice(0, 500), + }, + }) + return NextResponse.json({ error: `转码入队失败: ${message}` }, { status: 500 }) + } return NextResponse.json({ success: true, diff --git a/app/api/materials/[id]/skus/batch-download/route.ts b/app/api/materials/[id]/skus/batch-download/route.ts index b2a1e4f8..1cbfd8bd 100644 --- a/app/api/materials/[id]/skus/batch-download/route.ts +++ b/app/api/materials/[id]/skus/batch-download/route.ts @@ -1,6 +1,6 @@ import { promises as fs } from 'fs' import path from 'path' -import JSZip from 'jszip' +import archiver from 'archiver' import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' @@ -131,8 +131,7 @@ export async function POST( return NextResponse.json({ error: '没有找到可下载的 SKU' }, { status: 404 }) } - const zip = new JSZip() - let addedCount = 0 + const archiveEntries: Array<{ filePath: string; name: string }> = [] if (downloadType === 'white-background') { const whiteBackgroundAssets = await prisma.materialAsset.findMany({ @@ -169,8 +168,11 @@ export async function POST( if (!filePath) { throw new Error('白底图文件路径无效') } - const fileBuffer = await fs.readFile(filePath) - zip.file(`${sku.skuName}/${entry.fileName}`, fileBuffer) + await fs.access(filePath) + archiveEntries.push({ + filePath, + name: `${sku.skuName}/${entry.fileName}`, + }) } for (const entry of otherEntries) { @@ -178,11 +180,12 @@ export async function POST( if (!filePath) { throw new Error('白底图文件路径无效') } - const fileBuffer = await fs.readFile(filePath) - zip.file(`${sku.skuName}/other/${entry.fileName}`, fileBuffer) + await fs.access(filePath) + archiveEntries.push({ + filePath, + name: `${sku.skuName}/other/${entry.fileName}`, + }) } - - addedCount++ } catch (error) { console.error(`[SKU Batch Download] 添加白底图失败: ${sku.id}`, error) } @@ -204,38 +207,60 @@ export async function POST( sku.filePath || null, ) - const fileBuffer = await fs.readFile(filePath) - zip.file(fileName, fileBuffer) - addedCount++ + await fs.access(filePath) + archiveEntries.push({ filePath, name: fileName }) } catch (error) { console.error(`[SKU Batch Download] 添加模型失败: ${sku.id}`, error) } } } - if (addedCount === 0) { + if (archiveEntries.length === 0) { return NextResponse.json( { error: downloadType === 'white-background' ? '没有可下载的白底图文件' : '没有可下载的模型文件' }, { status: 404 } ) } - const zipBuffer = await zip.generateAsync({ - type: 'nodebuffer', - compression: 'DEFLATE', - compressionOptions: { level: 6 }, + const filename = `${material.productModel}_${downloadType === 'white-background' ? 'SKU白底图' : 'SKU模型'}_${Date.now()}.zip` + const archive = archiver('zip', { zlib: { level: 6 } }) + archiveEntries.forEach((entry) => { + archive.file(entry.filePath, { name: entry.name }) }) - const filename = `${material.productModel}_${downloadType === 'white-background' ? 'SKU白底图' : 'SKU模型'}_${Date.now()}.zip` + const stream = new ReadableStream({ + start(controller) { + let settled = false + const close = () => { + if (!settled) { + settled = true + controller.close() + } + } + const fail = (error: Error) => { + if (!settled) { + settled = true + controller.error(error) + } + } + + archive.on('data', (chunk: Buffer) => controller.enqueue(chunk)) + archive.on('end', close) + archive.on('error', fail) + void archive.finalize().catch(fail) + }, + cancel() { + archive.abort() + }, + }) recordBatchDownloadLog(materialId, userId).catch((error) => { console.error('[SKU Batch Download] 记录下载日志失败:', error) }) - return new NextResponse(zipBuffer as any, { + return new NextResponse(stream, { headers: { 'Content-Type': 'application/zip', - 'Content-Length': zipBuffer.length.toString(), 'Content-Disposition': `attachment; filename="${encodeURIComponent(filename)}"`, }, }) diff --git a/app/api/performance/quick/route.ts b/app/api/performance/quick/route.ts index 640499ef..83127268 100644 --- a/app/api/performance/quick/route.ts +++ b/app/api/performance/quick/route.ts @@ -1,8 +1,6 @@ import { NextRequest, NextResponse } from 'next/server' import { getServerSession } from 'next-auth' import os from 'os' -import { exec } from 'child_process' -import { promisify } from 'util' import { getAllSessions } from '@/lib/upload-sessions-redis' import { transcodeQueue } from '@/lib/video-transcode-queue' import { prisma } from '@/lib/prisma' @@ -10,7 +8,6 @@ import { getNetworkSpeed } from '@/lib/network-bandwidth-monitor' import { authOptions } from '@/lib/auth' import { hasSystemAdminPermission } from '@/lib/department-permission' -const execAsync = promisify(exec) const RATE_LIMIT_WINDOW_MS = 60 * 1000 const RATE_LIMIT_MAX_REQUESTS = 40 const MAX_VISIBLE_UPLOAD_SESSIONS = 100 @@ -38,59 +35,34 @@ export const revalidate = 0 // 获取CPU使用率(正确的方法:需要两次采样) async function getCpuUsage(): Promise { try { - // 方法1:使用 /proc/stat 两次采样计算CPU使用率(最准确) - const getCpuStats = async () => { - const { stdout } = await execAsync("cat /proc/stat | grep '^cpu '") - const parts = stdout.trim().split(/\s+/) - return { - user: parseInt(parts[1]) || 0, - nice: parseInt(parts[2]) || 0, - system: parseInt(parts[3]) || 0, - idle: parseInt(parts[4]) || 0, - iowait: parseInt(parts[5]) || 0, - irq: parseInt(parts[6]) || 0, - softirq: parseInt(parts[7]) || 0, + const snapshot = () => os.cpus().map((cpu) => cpu.times) + const before = snapshot() + await new Promise((resolve) => setTimeout(resolve, 200)) + const after = snapshot() + let totalDiff = 0 + let idleDiff = 0 + + for (let index = 0; index < Math.min(before.length, after.length); index += 1) { + const previous = before[index] + const current = after[index] + if (!previous || !current) { + continue } + const previousTotal = + previous.user + previous.nice + previous.sys + previous.idle + previous.irq + const currentTotal = + current.user + current.nice + current.sys + current.idle + current.irq + totalDiff += Math.max(0, currentTotal - previousTotal) + idleDiff += Math.max(0, current.idle - previous.idle) } - const stats1 = await getCpuStats() - await new Promise(resolve => setTimeout(resolve, 1000)) // 等待1秒 - const stats2 = await getCpuStats() - - const total1 = stats1.user + stats1.nice + stats1.system + stats1.idle + stats1.iowait + stats1.irq + stats1.softirq - const total2 = stats2.user + stats2.nice + stats2.system + stats2.idle + stats2.iowait + stats2.irq + stats2.softirq - const totalDiff = total2 - total1 - if (totalDiff > 0) { - const idleDiff = stats2.idle - stats1.idle - const usedDiff = totalDiff - idleDiff + const usedDiff = Math.max(0, totalDiff - idleDiff) const cpuUsage = (usedDiff / totalDiff) * 100 return Math.min(Math.max(Math.round(cpuUsage), 0), 100) } } catch (error) { - console.warn('[PerformanceQuick] Failed to get CPU usage from /proc/stat:', error) - } - - try { - // 方法2:尝试使用 top 命令(批处理模式,更准确) - const { stdout } = await execAsync("top -bn2 -d1 | grep 'Cpu(s)' | tail -1 | awk '{print $2}' | sed 's/%us,//'", { timeout: 3000 }) - const cpuUsage = parseFloat(stdout.trim()) - if (!isNaN(cpuUsage) && cpuUsage >= 0 && cpuUsage <= 100) { - return Math.round(cpuUsage) - } - } catch (error) { - console.warn('[PerformanceQuick] Failed to get CPU usage from top:', error) - } - - try { - // 方法3:使用 vmstat(如果可用) - const { stdout } = await execAsync("vmstat 1 2 | tail -1 | awk '{print 100-$15}'", { timeout: 3000 }) - const cpuUsage = parseFloat(stdout.trim()) - if (!isNaN(cpuUsage) && cpuUsage >= 0 && cpuUsage <= 100) { - return Math.round(cpuUsage) - } - } catch (error) { - console.warn('[PerformanceQuick] Failed to get CPU usage from vmstat:', error) + console.warn('[PerformanceQuick] Failed to sample CPU usage:', error) } // 降级方案:使用负载平均值估算(不准确,但总比没有好) diff --git a/lib/__tests__/retry-transcode-route.test.ts b/lib/__tests__/retry-transcode-route.test.ts new file mode 100644 index 00000000..75668a8c --- /dev/null +++ b/lib/__tests__/retry-transcode-route.test.ts @@ -0,0 +1,84 @@ +/** @jest-environment node */ + +import { NextRequest } from 'next/server' +import { getServerSession } from 'next-auth' +import { POST } from '@/app/api/materials/[id]/retry-transcode/route' +import { prisma } from '@/lib/prisma' +import { enqueueVideoTranscodeTask } from '@/lib/video-transcode-task' + +jest.mock('next-auth', () => ({ + getServerSession: jest.fn(), +})) + +jest.mock('@/lib/auth', () => ({ + authOptions: {}, +})) + +jest.mock('@/lib/prisma', () => ({ + prisma: { + material: { + findUnique: jest.fn(), + update: jest.fn(), + }, + user: { + findUnique: jest.fn(), + }, + }, +})) + +jest.mock('@/lib/video-transcode-task', () => ({ + enqueueVideoTranscodeTask: jest.fn(), +})) + +describe('retry transcode route', () => { + beforeEach(() => { + jest.clearAllMocks() + ;(getServerSession as jest.Mock).mockResolvedValue({ + user: { id: 'owner-1', role: 'USER' }, + }) + ;(prisma.material.findUnique as jest.Mock).mockResolvedValue({ + id: 'material-1', + userId: 'owner-1', + videoProcessingStatus: 'failed', + videoSourceUrl: 'uploads/materials/source.mp4', + videoCoverUrl: null, + }) + ;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ role: 'USER' }) + ;(prisma.material.update as jest.Mock).mockResolvedValue({}) + ;(enqueueVideoTranscodeTask as jest.Mock).mockResolvedValue(undefined) + }) + + function createRequest() { + return new NextRequest('http://localhost/api/materials/material-1/retry-transcode', { + method: 'POST', + }) + } + + it('重试时会真正将视频任务加入转码队列', async () => { + const response = await POST(createRequest(), { params: { id: 'material-1' } }) + + expect(response.status).toBe(200) + expect(enqueueVideoTranscodeTask).toHaveBeenCalledWith( + 'material-1', + 'uploads/materials/source.mp4', + true + ) + }) + + it('入队失败时回写失败状态而不是永久停留在 processing', async () => { + ;(enqueueVideoTranscodeTask as jest.Mock).mockRejectedValue(new Error('queue unavailable')) + + const response = await POST(createRequest(), { params: { id: 'material-1' } }) + const body = await response.json() + + expect(response.status).toBe(500) + expect(body.error).toContain('queue unavailable') + expect(prisma.material.update).toHaveBeenLastCalledWith({ + where: { id: 'material-1' }, + data: { + videoProcessingStatus: 'failed', + transcodeLastError: 'queue unavailable', + }, + }) + }) +}) diff --git a/lib/__tests__/s3-key-from-url.test.ts b/lib/__tests__/s3-key-from-url.test.ts new file mode 100644 index 00000000..2d598f3a --- /dev/null +++ b/lib/__tests__/s3-key-from-url.test.ts @@ -0,0 +1,34 @@ +import { getS3KeyFromUrl } from '@/lib/s3' + +describe('getS3KeyFromUrl', () => { + const originalBucket = process.env.S3_BUCKET + + afterEach(() => { + if (originalBucket === undefined) { + delete process.env.S3_BUCKET + } else { + process.env.S3_BUCKET = originalBucket + } + }) + + it('剥离公网 URL 中的 bucket 前缀并解码中文路径', () => { + process.env.S3_BUCKET = 'gongxiangpan' + const url = 'https://s3.yydd.ai/gongxiangpan/%E7%94%B1%E5%A3%B9%E7%82%B9AI/video-thumb-1.jpg' + + expect(getS3KeyFromUrl(url)).toBe('由壹点AI/video-thumb-1.jpg') + }) + + it('剥离内网 MinIO path-style URL 中的 bucket 前缀', () => { + process.env.S3_BUCKET = 'gongxiangpan' + + expect( + getS3KeyFromUrl('http://192.168.58.20:9000/gongxiangpan/abc/def.png') + ).toBe('abc/def.png') + }) + + it('路径不含 bucket 时保留完整对象 Key', () => { + process.env.S3_BUCKET = 'gongxiangpan' + + expect(getS3KeyFromUrl('https://cdn.example.com/由壹点AI/x.webp')).toBe('由壹点AI/x.webp') + }) +}) diff --git a/lib/s3.ts b/lib/s3.ts index 5fa8175f..436490b1 100644 --- a/lib/s3.ts +++ b/lib/s3.ts @@ -3,6 +3,21 @@ import { createReadStream } from 'fs' import { stat } from 'fs/promises' import { Readable } from 'stream' +/** + * 从 S3 公网 URL 或 MinIO path-style URL 中提取对象 Key。 + */ +export function getS3KeyFromUrl(fileUrl: string): string { + const url = new URL(fileUrl) + let key = decodeURIComponent(url.pathname.slice(1)) + const bucket = process.env.S3_BUCKET || '' + + if (bucket && key.startsWith(`${bucket}/`)) { + key = key.slice(bucket.length + 1) + } + + return key +} + /** * 判断 URL 是否为 HTTP/HTTPS URL */ @@ -148,19 +163,8 @@ export async function uploadFileToS3( export async function downloadFromS3(fileUrl: string): Promise { try { - // Extract key from URL - const url = new URL(fileUrl) - let key = url.pathname.slice(1) // Remove leading slash - - // URL decode the key to handle Chinese characters and special characters - key = decodeURIComponent(key) - - // Remove bucket name from key if present (for MinIO path-style URLs) - // URL format: http://endpoint/bucket/key + const key = getS3KeyFromUrl(fileUrl) const bucket = process.env.S3_BUCKET! - if (key.startsWith(bucket + '/')) { - key = key.substring(bucket.length + 1) - } console.log(`[S3] Downloading file: bucket=${bucket}, key=${key}`) @@ -191,18 +195,10 @@ export async function downloadFromS3(fileUrl: string): Promise { export async function deleteFromS3(fileUrl: string): Promise { try { - // Extract key from URL - const url = new URL(fileUrl) - let key = url.pathname.slice(1) // Remove leading slash - key = decodeURIComponent(key) - - const bucket = process.env.S3_BUCKET! - if (key.startsWith(bucket + '/')) { - key = key.substring(bucket.length + 1) - } + const key = getS3KeyFromUrl(fileUrl) const command = new DeleteObjectCommand({ - Bucket: bucket, + Bucket: process.env.S3_BUCKET!, Key: key, }) diff --git a/lib/upload-sessions-redis.ts b/lib/upload-sessions-redis.ts index 9afaa592..efff9627 100644 --- a/lib/upload-sessions-redis.ts +++ b/lib/upload-sessions-redis.ts @@ -39,6 +39,46 @@ const redis = new Redis(redisUrl, { const KEY_PREFIX = 'upload:session:' const EXPIRE_TIME = 4 * 60 * 60 // 4小时(秒),支持大文件上传(17.5分钟×13≈220GB) +function parsePositiveIntEnv(name: string, fallback: number): number { + const value = Number.parseInt(process.env[name] || '', 10) + return Number.isFinite(value) && value > 0 ? value : fallback +} + +async function scanSessionKeys(options?: { + maxKeys?: number + timeBudgetMs?: number +}): Promise { + const maxKeys = options?.maxKeys ?? Number.POSITIVE_INFINITY + const timeBudgetMs = options?.timeBudgetMs ?? Number.POSITIVE_INFINITY + const scanCount = parsePositiveIntEnv('UPLOAD_SESSION_SCAN_COUNT', 200) + const keys = new Set() + const startedAt = Date.now() + let cursor = '0' + + do { + const [nextCursor, batchKeys] = await redis.scan( + cursor, + 'MATCH', + `${KEY_PREFIX}*`, + 'COUNT', + scanCount + ) + cursor = nextCursor + for (const key of batchKeys) { + keys.add(key) + if (keys.size >= maxKeys) { + break + } + } + } while ( + cursor !== '0' && + keys.size < maxKeys && + Date.now() - startedAt <= timeBudgetMs + ) + + return Array.from(keys) +} + /** * 保存上传会话 */ @@ -163,7 +203,7 @@ export async function getSessionTTL(uploadId: string): Promise { */ export async function getActiveSessionsCount(): Promise { try { - const keys = await redis.keys(`${KEY_PREFIX}*`) + const keys = await scanSessionKeys() return keys.length } catch (error) { console.error('[Redis] 获取活跃会话数量失败', error) @@ -226,24 +266,42 @@ export async function setCompletedSessionTTL(uploadId: string): Promise { */ export async function getAllSessions(): Promise> { try { - const keys = await redis.keys(`${KEY_PREFIX}*`) + const keys = await scanSessionKeys({ + maxKeys: parsePositiveIntEnv('UPLOAD_SESSION_SCAN_MAX_KEYS', 2000), + timeBudgetMs: parsePositiveIntEnv('UPLOAD_SESSION_SCAN_TIME_BUDGET_MS', 150), + }) const sessions = new Map() - for (const key of keys) { - try { - const data = await redis.get(key) - if (data) { - const uploadId = key.replace(KEY_PREFIX, '') - const session = JSON.parse(data) - sessions.set(uploadId, { - ...session, - chunks: new Map(session.chunks || []), - }) + if (keys.length === 0) { + return sessions + } + + const pipeline = redis.pipeline() + keys.forEach((key) => pipeline.get(key)) + const results = await pipeline.exec() + + results?.forEach((result, index) => { + const key = keys[index] + const error = result?.[0] + const data = result?.[1] as string | null + if (!key || error || !data) { + if (error && key) { + console.error(`[Redis] 获取会话失败: ${key}`, error) } + return + } + + try { + const uploadId = key.replace(KEY_PREFIX, '') + const session = JSON.parse(data) + sessions.set(uploadId, { + ...session, + chunks: new Map(session.chunks || []), + }) } catch (error) { console.error(`[Redis] 解析会话失败: ${key}`, error) } - } + }) return sessions } catch (error) { diff --git a/lib/upload-sessions.ts b/lib/upload-sessions.ts index 84373e06..91bc7dfc 100644 --- a/lib/upload-sessions.ts +++ b/lib/upload-sessions.ts @@ -53,6 +53,11 @@ export interface UploadSession { userId: string } +function parsePositiveIntEnv(name: string, fallback: number): number { + const value = Number.parseInt(process.env[name] || '', 10) + return Number.isFinite(value) && value > 0 ? value : fallback +} + // 检查是否使用Redis const USE_REDIS = process.env.USE_REDIS === 'true' @@ -76,9 +81,54 @@ if (USE_REDIS) { const memorySessions = new Map() const MAX_UPLOAD_SESSION_AGE_MS = 8 * 60 * 60 * 1000 const SAFE_UPLOAD_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/ +const MEMORY_CACHE_LIMIT = parsePositiveIntEnv('UPLOAD_SESSION_MEMORY_CACHE_LIMIT', 500) +const MEMORY_CACHE_MAX_AGE_MS = parsePositiveIntEnv( + 'UPLOAD_SESSION_MEMORY_CACHE_MAX_AGE_MS', + 2 * 60 * 60 * 1000 +) +const MEMORY_CACHE_PRUNE_INTERVAL_MS = parsePositiveIntEnv( + 'UPLOAD_SESSION_MEMORY_CACHE_PRUNE_INTERVAL_MS', + 5 * 60 * 1000 +) +let lastCachePruneAt = 0 + +function pruneMemorySessions(now: number) { + if (!(USE_REDIS && redisModule)) { + return + } + + if ( + now - lastCachePruneAt < MEMORY_CACHE_PRUNE_INTERVAL_MS && + memorySessions.size <= MEMORY_CACHE_LIMIT + ) { + return + } + lastCachePruneAt = now + + const expiredKeys: string[] = [] + memorySessions.forEach((session, uploadId) => { + const activityAt = session.lastActivityAt || session.createdAt + if (now - activityAt > MEMORY_CACHE_MAX_AGE_MS) { + expiredKeys.push(uploadId) + } + }) + expiredKeys.forEach((uploadId) => memorySessions.delete(uploadId)) + + while (memorySessions.size > MEMORY_CACHE_LIMIT) { + const oldestUploadId = memorySessions.keys().next().value as string | undefined + if (!oldestUploadId) { + break + } + memorySessions.delete(oldestUploadId) + } +} function setMemorySession(uploadId: string, session: UploadSession) { + if (memorySessions.has(uploadId)) { + memorySessions.delete(uploadId) + } memorySessions.set(uploadId, session) + pruneMemorySessions(Date.now()) } function deleteMemorySession(uploadId: string) { @@ -96,6 +146,9 @@ function getMemorySession(uploadId: string): UploadSession | null { return null } + if (USE_REDIS && redisModule) { + setMemorySession(uploadId, session) + } return session } diff --git a/lib/video-processor.ts b/lib/video-processor.ts index 1fdecd3f..8b9eebda 100644 --- a/lib/video-processor.ts +++ b/lib/video-processor.ts @@ -13,13 +13,14 @@ import { exec } from 'child_process' import { promisify } from 'util' -import { readFile, unlink, writeFile, stat } from 'fs/promises' +import { readFile, unlink, stat } from 'fs/promises' import { createWriteStream } from 'fs' import { tmpdir } from 'os' import path from 'path' const { join, resolve, isAbsolute } = path -import { uploadToS3, getS3ObjectStream, isHttpUrl, isS3PublicUrl } from './s3' +import { uploadToS3, getS3KeyFromUrl, getS3ObjectStream, isHttpUrl, isS3PublicUrl } from './s3' import { Readable } from 'stream' +import { pipeline } from 'stream/promises' const execAsync = promisify(exec) @@ -98,7 +99,7 @@ async function downloadRemoteToTemp(remoteUrl: string, tempPath: string): Promis let stream try { console.log(`[VideoProcessor] Fetching S3 object: ${remoteUrl}`) - stream = await getS3ObjectStream(remoteUrl) + stream = await getS3ObjectStream(getS3KeyFromUrl(remoteUrl)) if (!stream.body) { throw new Error('Failed to get video stream from S3: stream body is null') } @@ -116,19 +117,28 @@ async function downloadRemoteToTemp(remoteUrl: string, tempPath: string): Promis } try { - const chunks: Buffer[] = [] - const readable = stream.body as Readable - console.log(`[VideoProcessor] Reading stream chunks...`) - for await (const chunk of readable) { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)) + if (stream.contentLength && stream.contentLength > TRANSCODE_CONFIG.maxTempFileSize) { + throw new Error( + `Remote video too large: ${stream.contentLength} bytes (max ${TRANSCODE_CONFIG.maxTempFileSize})` + ) } - const totalSize = Buffer.concat(chunks).length - console.log(`[VideoProcessor] Stream read complete, total size: ${totalSize} bytes`) - await writeFile(tempPath, Buffer.concat(chunks)) - console.log(`[VideoProcessor] File written to: ${tempPath}`) - const { stat } = await import('fs/promises') + + const readable = stream.body as Readable + try { + await pipeline(readable, createWriteStream(tempPath)) + } catch (error) { + await unlink(tempPath).catch(() => {}) + throw error + } + const fileStat = await stat(tempPath) - console.log(`[VideoProcessor] File verified, size: ${fileStat.size} bytes`) + if (fileStat.size > TRANSCODE_CONFIG.maxTempFileSize) { + await unlink(tempPath).catch(() => {}) + throw new Error( + `Temp video file too large: ${fileStat.size} bytes (max ${TRANSCODE_CONFIG.maxTempFileSize})` + ) + } + console.log(`[VideoProcessor] S3 file written to: ${tempPath}, size=${fileStat.size} bytes`) } catch (error: any) { const errorMsg = error?.message || String(error) console.error(`[VideoProcessor] File write error: ${errorMsg}`)