Version Xiaoyi deliveries and fence outbound notifications
This commit is contained in:
parent
ee9b7eb461
commit
c1d216eb8f
@ -1,46 +1,32 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { isAllowedCorsOrigin } from '@/lib/cors-origin'
|
||||
import { isSuperAdmin } from '@/lib/department-permission'
|
||||
import { retryExternalNotificationDelivery } from '@/lib/external-auto-listing'
|
||||
|
||||
async function assertAdminPermission() {
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session?.user || !(session.user as any).id) {
|
||||
return NextResponse.json({ success: false, error: '未登录' }, { status: 401 })
|
||||
}
|
||||
|
||||
const userId = (session.user as any).id
|
||||
if (!(await isSuperAdmin(userId))) {
|
||||
return NextResponse.json({ success: false, error: '仅超级管理员可操作' }, { status: 403 })
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } },
|
||||
) {
|
||||
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
|
||||
try {
|
||||
const authError = await assertAdminPermission()
|
||||
if (authError) {
|
||||
return authError
|
||||
const session = await getServerSession(authOptions)
|
||||
const userId = (session?.user as { id?: string } | undefined)?.id
|
||||
if (!userId) return NextResponse.json({ success: false, error: '未登录' }, { status: 401 })
|
||||
const origin = request.headers.get('origin')
|
||||
if (!(await isSuperAdmin(userId)) || !origin || request.headers.get('sec-fetch-site') === 'cross-site'
|
||||
|| !isAllowedCorsOrigin(request, origin)) {
|
||||
return NextResponse.json({ success: false, error: '仅超级管理员可从素材外发页操作' }, { status: 403 })
|
||||
}
|
||||
|
||||
const deliveryId = String(params?.id || '').trim()
|
||||
if (!deliveryId) {
|
||||
return NextResponse.json({ success: false, error: '投递记录不存在' }, { status: 404 })
|
||||
const deliveryId = params.id.trim()
|
||||
const result = deliveryId ? await retryExternalNotificationDelivery(deliveryId, userId) : 'missing'
|
||||
if (result === 'missing') return NextResponse.json({ success: false, error: '投递记录不存在' }, { status: 404 })
|
||||
if (result === 'unavailable') {
|
||||
return NextResponse.json({ success: false, error: '请先启用目标及对应事件订阅' }, { status: 409 })
|
||||
}
|
||||
|
||||
await retryExternalNotificationDelivery(deliveryId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: '补发任务已重新入队',
|
||||
})
|
||||
if (result === 'conflict') {
|
||||
return NextResponse.json({ success: false, error: '仅可重放已用完重试次数的投递' }, { status: 409 })
|
||||
}
|
||||
return NextResponse.json({ success: true, message: '补发任务已重新入队' })
|
||||
} catch (error) {
|
||||
console.error('[admin/external-notification-deliveries/[id]/retry] POST error:', error)
|
||||
console.error('[admin/external-notification-deliveries/retry] POST error:', error)
|
||||
return NextResponse.json({ success: false, error: '服务器错误' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
25
app/api/admin/xiaoyi-delivery-gc/route.ts
Normal file
25
app/api/admin/xiaoyi-delivery-gc/route.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { isAllowedCorsOrigin } from '@/lib/cors-origin'
|
||||
import { isSuperAdmin } from '@/lib/department-permission'
|
||||
import { collectXiaoyiDeliveryGarbage } from '@/lib/xiaoyi-delivery-gc'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const session = await getServerSession(authOptions)
|
||||
const userId = (session?.user as { id?: string } | undefined)?.id
|
||||
if (!userId) return NextResponse.json({ success: false, error: '未登录' }, { status: 401 })
|
||||
const origin = request.headers.get('origin')
|
||||
if (!await isSuperAdmin(userId) || !origin || request.headers.get('sec-fetch-site') === 'cross-site'
|
||||
|| !isAllowedCorsOrigin(request, origin)) {
|
||||
return NextResponse.json({ success: false, error: '仅超级管理员可从素材库操作' }, { status: 403 })
|
||||
}
|
||||
const body = await request.json().catch(() => null)
|
||||
if (!body || (body.kind !== 'deliveries' && body.kind !== 'uploads')
|
||||
|| (body.dryRun !== undefined && typeof body.dryRun !== 'boolean')
|
||||
|| (body.after !== undefined && (typeof body.after !== 'string' || !/^[A-Za-z0-9_/-]{1,265}$/.test(body.after)))) {
|
||||
return NextResponse.json({ success: false, error: '清理参数无效' }, { status: 400 })
|
||||
}
|
||||
const result = await collectXiaoyiDeliveryGarbage(body)
|
||||
return NextResponse.json({ success: true, ...result }, { headers: { 'Cache-Control': 'no-store' } })
|
||||
}
|
||||
312
app/api/external/download/route.ts
vendored
312
app/api/external/download/route.ts
vendored
@ -1,3 +1,5 @@
|
||||
import { getDeliveryRevision, getHistoricalDeliveryAsset, getLegacyDeliveryRevisionId } from '@/lib/delivery-revisions'
|
||||
import { ExternalZipBusyError, ExternalZipSourceError, ExternalZipTooLargeError, streamExternalZip } from '@/lib/external-zip-stream'
|
||||
import { EXTERNAL_MATERIAL_SCOPE_WHERE, isRestrictedMaterial } from '@/lib/material-access-scope'
|
||||
import { resolveStoredUploadPath } from '@/lib/upload-paths'
|
||||
import { isXiaoyiDeliveryMaterial, xiaoyiSkuDimensions } from '@/lib/xiaoyi-delivery-material'
|
||||
@ -12,7 +14,6 @@ import { verifyDownloadToken, isTokenExpired } from '@/lib/download-token';
|
||||
import { errorResponse, API_ERROR } from '@/lib/external-api';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { ASSET_TYPE } from '@/lib/product-package';
|
||||
import archiver from 'archiver';
|
||||
import { Readable } from 'stream';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
@ -25,7 +26,6 @@ import { resolveExternalImageDownloadSource } from '@/lib/external-image-assets'
|
||||
import { resolveTaskDetailDownload } from '@/lib/external-task-details';
|
||||
import { resolveCertificateReportSource } from '@/lib/external-certificate-reports';
|
||||
import { nodeReadableToWebStream } from '@/lib/node-readable-stream';
|
||||
import { createArchiveDownloadStream } from '@/lib/archive-download-stream';
|
||||
import {
|
||||
getVideoDownloadAvailability,
|
||||
getVideoDownloadUnavailableMessage,
|
||||
@ -42,7 +42,6 @@ import {
|
||||
* GET - 下载文件
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
// Token 绑定素材身份而非某次文件路径;再次访问必须解析当前版本。
|
||||
const response = await handleDownload(request);
|
||||
response.headers.set('Cache-Control', 'private, no-store');
|
||||
return response;
|
||||
@ -97,7 +96,7 @@ async function handleDownload(request: NextRequest) {
|
||||
const material: any = await prisma.material.findUnique({
|
||||
where: { ...EXTERNAL_MATERIAL_SCOPE_WHERE, id: materialId, deletedAt: null },
|
||||
include: {
|
||||
assets: true,
|
||||
assets: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }] },
|
||||
},
|
||||
});
|
||||
|
||||
@ -158,37 +157,29 @@ async function handleDownload(request: NextRequest) {
|
||||
assetId,
|
||||
skuId,
|
||||
rangeHeader,
|
||||
request.signal,
|
||||
);
|
||||
}
|
||||
|
||||
if (isXiaoyiDeliveryMaterial(material.materialType)) {
|
||||
const revisionId = payload.revisionId ?? (downloadType === 'all' && material.currentRevisionId
|
||||
? (await getLegacyDeliveryRevisionId(material.id))?.id ?? material.currentRevisionId
|
||||
: null)
|
||||
const revision = revisionId ? await getDeliveryRevision(material.id, revisionId) : null
|
||||
if (revisionId && !revision) return errorResponse(API_ERROR.MATERIAL_NOT_FOUND)
|
||||
const assets = revision?.assets ?? material.assets
|
||||
if (downloadType === 'all') {
|
||||
const assets = material.assets.filter((item: any) => ['main','sku','detail','video','buyer_show'].includes(item.assetType))
|
||||
if (!assets.length) {
|
||||
const files = assets.filter((item: any) => ['main','sku','detail','video','buyer_show'].includes(item.assetType))
|
||||
if (!files.length) {
|
||||
return NextResponse.json({success:false,error:{code:'FILE_NOT_FOUND',message:'交付文件暂不可用'}},{status:503})
|
||||
}
|
||||
const prefetchedStreams = new Map<string, { body: Readable; contentLength?: number }>()
|
||||
for (const item of assets) {
|
||||
const normalizedUrl = normalizeAssetFileUrl(item.fileUrl)
|
||||
const local = resolveAssetLocalPath(normalizedUrl)
|
||||
if (local && fs.existsSync(local)) continue
|
||||
if (isHttpUrl(normalizedUrl)) continue
|
||||
const remote = await openRemoteFallbackStream(normalizedUrl)
|
||||
if (remote) {
|
||||
prefetchedStreams.set(item.id, remote)
|
||||
continue
|
||||
}
|
||||
for (const stream of Array.from(prefetchedStreams.values())) {
|
||||
stream.body.destroy()
|
||||
}
|
||||
return NextResponse.json({success:false,error:{code:'FILE_NOT_FOUND',message:'交付文件暂不可用'}},{status:503})
|
||||
}
|
||||
return await downloadAsZip(assets, material.id, 'all', prefetchedStreams)
|
||||
return await downloadAsZip(files, material.id, 'all', request.signal, true)
|
||||
}
|
||||
if (downloadType !== 'single' || !assetId) {
|
||||
return NextResponse.json({success:false,error:{code:'INVALID_DOWNLOAD_TYPE',message:'请指定交付文件'}},{status:400})
|
||||
}
|
||||
const asset = material.assets.find((item: any) => item.id === assetId)
|
||||
const asset = assets.find((item: any) => item.id === assetId)
|
||||
?? (!revisionId ? await getHistoricalDeliveryAsset(material.id, assetId) : null)
|
||||
if (!asset) return NextResponse.json({success:false,error:{code:'ASSET_NOT_FOUND',message:'资产不存在'}},{status:404})
|
||||
return await downloadSingleFile(asset, rangeHeader)
|
||||
}
|
||||
@ -233,7 +224,7 @@ async function handleDownload(request: NextRequest) {
|
||||
}
|
||||
|
||||
console.warn('[external/download] all.zip 缺失,使用 main/sku/detail 动态打包兜底');
|
||||
return await downloadAsZip(fallbackAssets, material.taskNo || material.id, 'all');
|
||||
return await downloadAsZip(fallbackAssets, material.taskNo || material.id, 'all', request.signal);
|
||||
}
|
||||
|
||||
// 下载分类:使用 main.zip / sku.zip / detail.zip
|
||||
@ -286,7 +277,7 @@ async function handleDownload(request: NextRequest) {
|
||||
return await downloadSingleFile(psdAssets[0], rangeHeader);
|
||||
}
|
||||
|
||||
return await downloadAsZip(psdAssets, material.taskNo || material.id, 'psd');
|
||||
return await downloadAsZip(psdAssets, material.taskNo || material.id, 'psd', request.signal);
|
||||
}
|
||||
|
||||
// 未知的下载类型
|
||||
@ -334,6 +325,8 @@ async function handleDownload(request: NextRequest) {
|
||||
// 注意:外部接口通过 token 验证,已跳过权限检查
|
||||
return await downloadNonProductPackageMaterial(material, downloadType, request);
|
||||
} catch (error) {
|
||||
const zipError = zipBusyResponse(error)
|
||||
if (zipError) return zipError
|
||||
console.error('[external/download] error:', error);
|
||||
return errorResponse(API_ERROR.SERVER_ERROR);
|
||||
}
|
||||
@ -342,9 +335,10 @@ async function handleDownload(request: NextRequest) {
|
||||
async function downloadStandardModelWhiteBackground(
|
||||
material: any,
|
||||
downloadType: 'white-background-single' | 'white-background-zip',
|
||||
assetId?: string,
|
||||
skuId?: string,
|
||||
rangeHeader: string | null = null,
|
||||
assetId: string | undefined,
|
||||
skuId: string | undefined,
|
||||
rangeHeader: string | null,
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
if (downloadType === 'white-background-single') {
|
||||
if (!assetId) {
|
||||
@ -394,7 +388,7 @@ async function downloadStandardModelWhiteBackground(
|
||||
|
||||
const whiteBackgroundGroup = groupWhiteBackgroundAssetsBySku(material.assets || []).get(sku.id);
|
||||
if (whiteBackgroundGroup && hasAnyWhiteBackgroundAssetGroup(whiteBackgroundGroup)) {
|
||||
const zipStream = await buildExternalWhiteBackgroundZipStream(whiteBackgroundGroup);
|
||||
const zipStream = await buildExternalWhiteBackgroundZipStream(whiteBackgroundGroup, signal);
|
||||
if (!zipStream) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: { code: 'FILE_NOT_FOUND', message: '白底图不存在' } },
|
||||
@ -576,56 +570,23 @@ async function downloadSingleFile(asset: any, rangeHeader: string | null = null)
|
||||
);
|
||||
}
|
||||
|
||||
async function buildExternalWhiteBackgroundZipStream(whiteBackgroundGroup: {
|
||||
function buildExternalWhiteBackgroundZipStream(whiteBackgroundGroup: {
|
||||
fixed: Record<string, any>;
|
||||
other: any[];
|
||||
}): Promise<ReadableStream<Uint8Array> | null> {
|
||||
const archive = archiver('zip', { zlib: { level: 6 } });
|
||||
const archiveDownload = createArchiveDownloadStream(archive);
|
||||
let addedCount = 0
|
||||
|
||||
try {
|
||||
for (const view of STANDARD_MODEL_WHITE_BG_VIEWS) {
|
||||
const asset = whiteBackgroundGroup.fixed[view.key];
|
||||
if (!asset?.fileUrl) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const ext = path.extname(asset.fileName || asset.fileUrl) || '.jpg';
|
||||
const fileName = asset.fileName || `${view.label}${ext}`;
|
||||
await appendExternalAssetToArchive(
|
||||
archive,
|
||||
archiveDownload.trackSource,
|
||||
asset.fileUrl,
|
||||
fileName,
|
||||
);
|
||||
addedCount += 1
|
||||
}
|
||||
|
||||
for (const asset of whiteBackgroundGroup.other || []) {
|
||||
if (!asset?.fileUrl) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await appendExternalAssetToArchive(
|
||||
archive,
|
||||
archiveDownload.trackSource,
|
||||
asset.fileUrl,
|
||||
`other/${asset.fileName || path.basename(asset.fileUrl)}`,
|
||||
);
|
||||
addedCount += 1
|
||||
}
|
||||
|
||||
if (addedCount === 0) {
|
||||
archiveDownload.abort();
|
||||
return null;
|
||||
}
|
||||
|
||||
return archiveDownload.finalize();
|
||||
} catch (error) {
|
||||
archiveDownload.abort();
|
||||
throw error;
|
||||
}
|
||||
}, signal: AbortSignal) {
|
||||
const fixed = STANDARD_MODEL_WHITE_BG_VIEWS.flatMap(view => {
|
||||
const asset = whiteBackgroundGroup.fixed[view.key]
|
||||
if (!asset?.fileUrl) return []
|
||||
const ext = path.extname(asset.fileName || asset.fileUrl) || '.jpg'
|
||||
return [{ name: asset.fileName || `${view.label}${ext}`, fileUrl: asset.fileUrl }]
|
||||
})
|
||||
const other = [...(whiteBackgroundGroup.other || [])].sort(zipAssetOrder)
|
||||
.filter(asset => asset.fileUrl)
|
||||
.map(asset => ({ name: `other/${asset.fileName || path.basename(asset.fileUrl)}`, fileUrl: asset.fileUrl }))
|
||||
const entries = [...fixed, ...other].map(({ name, fileUrl }) => ({
|
||||
name, open: (sourceSignal: AbortSignal) => openZipFile(fileUrl, sourceSignal),
|
||||
}))
|
||||
return entries.length ? streamExternalZip(entries, signal) : null
|
||||
}
|
||||
|
||||
function parseByteRange(
|
||||
@ -675,33 +636,9 @@ function parseByteRange(
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
async function appendExternalAssetToArchive(
|
||||
archive: archiver.Archiver,
|
||||
trackSource: <T extends Readable>(source: T) => T,
|
||||
fileUrl: string,
|
||||
entryName: string,
|
||||
): Promise<void> {
|
||||
if (isHttpUrl(fileUrl)) {
|
||||
const response = await fetch(fileUrl);
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`读取资源失败: ${response.status}`);
|
||||
}
|
||||
|
||||
archive.append(trackSource(Readable.fromWeb(response.body as any)), { name: entryName });
|
||||
return;
|
||||
}
|
||||
|
||||
const localPath = resolveAssetLocalPath(fileUrl);
|
||||
if (!localPath) {
|
||||
throw new Error('资源路径无效');
|
||||
}
|
||||
|
||||
await access(localPath);
|
||||
archive.file(localPath, { name: entryName });
|
||||
}
|
||||
|
||||
async function openRemoteFallbackStream(
|
||||
fileUrl?: string | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ body: Readable; contentLength?: number } | null> {
|
||||
if (!process.env.S3_BUCKET?.trim()) {
|
||||
return null;
|
||||
@ -717,11 +654,12 @@ async function openRemoteFallbackStream(
|
||||
const candidateKeys = s3Prefix ? [`${s3Prefix}/${normalized}`, normalized] : [normalized];
|
||||
for (const key of candidateKeys) {
|
||||
try {
|
||||
const result = await getS3ObjectStream(key);
|
||||
const result = await getS3ObjectStream(key, signal);
|
||||
if (result?.body) {
|
||||
return result;
|
||||
}
|
||||
} catch {
|
||||
signal?.throwIfAborted()
|
||||
// Try next candidate key.
|
||||
}
|
||||
}
|
||||
@ -731,27 +669,47 @@ async function openRemoteFallbackStream(
|
||||
/**
|
||||
* 打包下载为 ZIP
|
||||
*/
|
||||
async function downloadAsZip(
|
||||
assets: any[],
|
||||
taskNo: string,
|
||||
downloadType: string,
|
||||
prefetchedStreams?: Map<string, { body: Readable; contentLength?: number }>,
|
||||
) {
|
||||
console.log(`[downloadAsZip] ========== 开始打包下载 ==========`);
|
||||
console.log(`[downloadAsZip] taskNo: ${taskNo}, downloadType: ${downloadType}`);
|
||||
console.log(`[downloadAsZip] 待打包资产数量: ${assets.length}`);
|
||||
assets.forEach((asset, index) => {
|
||||
console.log(`[downloadAsZip] 资产 ${index + 1}: type=${asset.assetType}, url=${asset.fileUrl}, fileName=${asset.fileName}`);
|
||||
});
|
||||
async function openZipFile(fileUrl: string, signal: AbortSignal): Promise<Readable> {
|
||||
const localPath = resolveAssetLocalPath(fileUrl)
|
||||
if (localPath && fs.existsSync(localPath)) return createReadStream(localPath, { signal })
|
||||
if (localPath) {
|
||||
const remote = await openRemoteFallbackStream(fileUrl, signal)
|
||||
if (remote) return remote.body
|
||||
}
|
||||
if (isHttpUrl(fileUrl)) {
|
||||
const response = await fetch(fileUrl, { signal })
|
||||
if (response.ok && response.body) return Readable.fromWeb(response.body as any)
|
||||
await response.body?.cancel()
|
||||
}
|
||||
throw new Error('ZIP 资源不可用')
|
||||
}
|
||||
|
||||
const archive = archiver('zip', { zlib: { level: 5 } });
|
||||
const archiveDownload = createArchiveDownloadStream(archive);
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
function zipBusyResponse(error: unknown) {
|
||||
if (error instanceof ExternalZipBusyError) {
|
||||
return NextResponse.json({ success: false, error: { code: 'ZIP_BUSY', message: '下载任务繁忙,请稍后重试' } },
|
||||
{ status: 429, headers: { 'Retry-After': '5' } })
|
||||
}
|
||||
if (error instanceof ExternalZipSourceError) {
|
||||
return NextResponse.json({ success: false, error: { code: 'FILE_NOT_FOUND', message: '交付文件暂不可用' } }, { status: 503 })
|
||||
}
|
||||
if (error instanceof ExternalZipTooLargeError) {
|
||||
return NextResponse.json({ success: false, error: { code: 'ZIP_TOO_LARGE', message: '压缩包文件数量超出限制' } }, { status: 413 })
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function zipAssetOrder(left: { sortOrder?: number; id?: string }, right: typeof left) {
|
||||
const order = (left.sortOrder ?? 0) - (right.sortOrder ?? 0)
|
||||
if (order) return order
|
||||
const a = left.id ?? ''
|
||||
const b = right.id ?? ''
|
||||
return a < b ? -1 : a > b ? 1 : 0
|
||||
}
|
||||
|
||||
async function downloadAsZip(assets: any[], taskNo: string, downloadType: string, signal: AbortSignal, prime = false) {
|
||||
const skuNames = new Map<string, number>();
|
||||
const skuResolutions = new Set<string>();
|
||||
const files = assets.map(asset => {
|
||||
const files = [...assets].sort(zipAssetOrder).map(asset => {
|
||||
const fileUrl = normalizeAssetFileUrl(asset.fileUrl);
|
||||
const fileName = asset.fileName || path.basename(fileUrl);
|
||||
const { resolution } = xiaoyiSkuDimensions(asset.assetType, fileUrl);
|
||||
@ -775,77 +733,23 @@ async function downloadAsZip(
|
||||
skuGroupNameCounts.set(key, (skuGroupNameCounts.get(key) ?? 0) + 1);
|
||||
}
|
||||
const skuGroupNameOffsets = new Map<string, number>();
|
||||
for (const { asset, fileUrl, fileName, group } of groupedFiles) {
|
||||
const entries = groupedFiles.map(({ asset, fileUrl, fileName, group }) => {
|
||||
const key = `${group}\u0000${fileName.toLowerCase()}`;
|
||||
let entryName = `${group}/${fileName}`;
|
||||
let name = `${group}/${fileName}`;
|
||||
if (asset.assetType === 'sku' && (skuGroupNameCounts.get(key) ?? 0) > 1) {
|
||||
const offset = (skuGroupNameOffsets.get(key) ?? 0) + 1;
|
||||
skuGroupNameOffsets.set(key, offset);
|
||||
entryName = `${group}/${String(offset).padStart(2, '0')}/${fileName}`;
|
||||
name = `${group}/${String(offset).padStart(2, '0')}/${fileName}`;
|
||||
}
|
||||
return { name, open: (sourceSignal: AbortSignal) => openZipFile(fileUrl, sourceSignal) }
|
||||
})
|
||||
|
||||
try {
|
||||
const localPath = resolveAssetLocalPath(fileUrl);
|
||||
if (localPath && fs.existsSync(localPath)) {
|
||||
archive.file(localPath, { name: entryName });
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
const prefetched = asset?.id ? prefetchedStreams?.get(asset.id) : undefined;
|
||||
if (prefetched) {
|
||||
archive.append(archiveDownload.trackSource(prefetched.body), { name: entryName });
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
if (localPath) {
|
||||
const remote = await openRemoteFallbackStream(fileUrl);
|
||||
if (remote) {
|
||||
archive.append(archiveDownload.trackSource(remote.body), { name: entryName });
|
||||
successCount++;
|
||||
continue;
|
||||
}
|
||||
console.error(`[downloadAsZip] ❌ 本地与远程文件均不存在: ${localPath}`);
|
||||
failCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isHttpUrl(fileUrl)) {
|
||||
const response = await fetch(fileUrl);
|
||||
if (response.ok && response.body) {
|
||||
archive.append(
|
||||
archiveDownload.trackSource(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) {
|
||||
archiveDownload.abort();
|
||||
return NextResponse.json(
|
||||
{ success: false, error: { code: 'NO_FILES', message: '没有可下载的文件' } },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const stream = archiveDownload.finalize();
|
||||
|
||||
return new NextResponse(stream as any, {
|
||||
return new NextResponse(await streamExternalZip(entries, signal, prime), {
|
||||
headers: {
|
||||
'Content-Type': 'application/zip',
|
||||
'Content-Disposition': `attachment; filename="${encodeURIComponent(`${taskNo}-${downloadType}.zip`)}"`,
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1065,7 +969,7 @@ async function downloadNonProductPackageMaterial(material: any, downloadType: st
|
||||
Array.isArray(material.displayImages) &&
|
||||
material.displayImages.length > 0
|
||||
) {
|
||||
return await buildDynamicZipFromDisplayImages(material);
|
||||
return await buildDynamicZipFromDisplayImages(material, request.signal);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
@ -1195,7 +1099,7 @@ async function downloadNonProductPackageMaterial(material: any, downloadType: st
|
||||
material.displayImages.length > 0
|
||||
) {
|
||||
console.log('[external/download] Local file missing, fallback to dynamic zip from displayImages');
|
||||
return await buildDynamicZipFromDisplayImages(material);
|
||||
return await buildDynamicZipFromDisplayImages(material, request.signal);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
@ -1271,7 +1175,7 @@ async function downloadNonProductPackageMaterial(material: any, downloadType: st
|
||||
/**
|
||||
* 动态打包displayImages为ZIP
|
||||
*/
|
||||
async function buildDynamicZipFromDisplayImages(material: any) {
|
||||
async function buildDynamicZipFromDisplayImages(material: any, signal: AbortSignal) {
|
||||
const displayImages = Array.isArray(material.displayImages)
|
||||
? material.displayImages.filter((img: any) => typeof img === 'string' && img.trim().length > 0)
|
||||
: [];
|
||||
@ -1283,37 +1187,17 @@ async function buildDynamicZipFromDisplayImages(material: any) {
|
||||
);
|
||||
}
|
||||
|
||||
const archive = archiver('zip', { zlib: { level: 6 } });
|
||||
const archiveDownload = createArchiveDownloadStream(archive);
|
||||
let addedCount = 0;
|
||||
|
||||
for (let i = 0; i < displayImages.length; i++) {
|
||||
const imageUrl = displayImages[i];
|
||||
try {
|
||||
const response = await fetch(imageUrl);
|
||||
if (!response.ok || !response.body) {
|
||||
console.warn(`[external/download] Failed to fetch display image index=${i} url=${imageUrl}, status=${response.status}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const urlObj = new URL(imageUrl);
|
||||
const filename = (path.basename(urlObj.pathname) || `image-${i + 1}.webp`).replace(/[^\w\-.]+/g, '_');
|
||||
archive.append(
|
||||
archiveDownload.trackSource(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);
|
||||
}
|
||||
}
|
||||
|
||||
if (addedCount === 0) {
|
||||
archiveDownload.abort();
|
||||
const entries = displayImages.flatMap((imageUrl: string, index: number) => {
|
||||
if (!isHttpUrl(imageUrl)) return []
|
||||
const basename = path.basename(new URL(imageUrl).pathname) || `image-${index + 1}.webp`
|
||||
const name = basename.replace(/[^\w\-.]+/g, '_')
|
||||
return [{ name, open: (sourceSignal: AbortSignal) => openZipFile(imageUrl, sourceSignal) }]
|
||||
})
|
||||
if (!entries.length) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: { code: 'NO_DOWNLOADABLE_FILES', message: '该素材可能只包含图片' } },
|
||||
{ status: 404 }
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
const filenameParts = [
|
||||
@ -1326,7 +1210,7 @@ async function buildDynamicZipFromDisplayImages(material: any) {
|
||||
|
||||
const filename = `${filenameParts.join('_')}.zip`;
|
||||
|
||||
const stream = archiveDownload.finalize();
|
||||
const stream = await streamExternalZip(entries, signal);
|
||||
|
||||
return new NextResponse(stream as any, {
|
||||
headers: {
|
||||
|
||||
90
app/api/external/product-assets/route.ts
vendored
90
app/api/external/product-assets/route.ts
vendored
@ -1,4 +1,5 @@
|
||||
import { isRestrictedMaterial } from '@/lib/material-access-scope'
|
||||
import { getDeliveryRevision, getLegacyDeliveryRevisionId, type DeliveryReference } from '@/lib/delivery-revisions'
|
||||
import { EXTERNAL_MATERIAL_SCOPE_WHERE, isRestrictedMaterial } from '@/lib/material-access-scope'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import {
|
||||
isXiaoyiDeliveryMaterial, readXiaoyiDeliveryMetadata, XIAOYI_DELIVERY_LOG_ACTION,
|
||||
@ -169,23 +170,34 @@ export async function GET(request: NextRequest) {
|
||||
console.log('[external/product-assets] Material type:', material.materialType);
|
||||
|
||||
if (isXiaoyiDeliveryMaterial(material.materialType)) {
|
||||
const requestedRevision = request.nextUrl.searchParams.get('revisionId')
|
||||
const revisionId = requestedRevision ?? (material.currentRevisionId as string | null) ?? null
|
||||
const revision = revisionId ? await getDeliveryRevision(material.id, revisionId) : null
|
||||
if (revisionId && !revision) return errorResponse(API_ERROR.MATERIAL_NOT_FOUND)
|
||||
const snapshot = revision?.snapshot
|
||||
const [delivery] = await prisma.$queryRaw<Array<{
|
||||
brandName: string; productName: string; eventId: string | null; listingStatus: ListingStatus | null
|
||||
deliveryGroupId: string; authorId: string; detailBarcode: string | null; barcodes: string[] | null
|
||||
relatedMaterials: Partial<Record<XiaoyiDeliveryKind, string>> | null
|
||||
relatedMaterials: Partial<Record<XiaoyiDeliveryKind, DeliveryReference>> | null
|
||||
metadataChanges: string | null
|
||||
}>>`
|
||||
SELECT d.brand_name AS "brandName", d.product_name AS "productName",
|
||||
e.id AS "eventId", d.listing_status AS "listingStatus", d.project_id AS "deliveryGroupId", d.owner_id AS "authorId",
|
||||
COALESCE(o.id, r.snapshot->>'eventId', e.id) AS "eventId",
|
||||
CASE WHEN d.listing_status->>'state' = 'listed' THEN d.listing_status
|
||||
ELSE COALESCE(c.receipts->COALESCE(o.id, r.snapshot->>'eventId', e.id), d.listing_status)
|
||||
END AS "listingStatus", d.project_id AS "deliveryGroupId", d.owner_id AS "authorId",
|
||||
siblings."relatedMaterials", codes."detailBarcode", codes.barcodes,
|
||||
(SELECT log.changes FROM material_logs log
|
||||
WHERE log."materialId" = d.material_id AND log.action = ${XIAOYI_DELIVERY_LOG_ACTION}
|
||||
ORDER BY log.timestamp DESC LIMIT 1) AS "metadataChanges"
|
||||
FROM desktop_material_deliveries d
|
||||
JOIN materials delivered ON delivered.id = d.material_id
|
||||
LEFT JOIN delivery_revisions r ON r.id = ${revisionId ?? null} AND r.material_id = d.material_id
|
||||
LEFT JOIN xiaoyi_auto_listing_outbox o ON o.revision_id = r.id
|
||||
LEFT JOIN xiaoyi_auto_listing_events e ON e.material_id = d.material_id
|
||||
LEFT JOIN channel_listings c ON c.material_id = d.material_id AND c.channel = 'auto-listing' AND c.store = ''
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT jsonb_object_agg(related.kind, related.material_id) AS "relatedMaterials"
|
||||
SELECT jsonb_object_agg(related.kind, jsonb_build_object('materialId', related.material_id, 'revisionId', rm.current_revision_id)) AS "relatedMaterials"
|
||||
FROM desktop_material_deliveries related
|
||||
JOIN materials rm ON rm.id = related.material_id AND rm."userId" = related.owner_id
|
||||
WHERE related.project_id = d.project_id AND related.owner_id = d.owner_id
|
||||
@ -198,14 +210,35 @@ export async function GET(request: NextRequest) {
|
||||
array_agg(DISTINCT b.barcode COLLATE "C" ORDER BY b.barcode COLLATE "C") FILTER (WHERE a.asset_type = 'sku') AS barcodes
|
||||
FROM material_assets a
|
||||
JOIN material_asset_barcodes b ON b.asset_id = a.id
|
||||
WHERE a.material_id = (siblings."relatedMaterials"->>'detail')
|
||||
WHERE a.material_id = (siblings."relatedMaterials"->'detail'->>'materialId')
|
||||
) codes ON TRUE
|
||||
WHERE d.material_id = ${material.id}
|
||||
`
|
||||
if (listingOnly && !delivery?.eventId) return errorResponse(API_ERROR.MATERIAL_NOT_FOUND)
|
||||
const metadata = readXiaoyiDeliveryMetadata(delivery?.metadataChanges)
|
||||
const metadata = snapshot ? snapshot.metadata : readXiaoyiDeliveryMetadata(delivery?.metadataChanges)
|
||||
const view = snapshot ?? material
|
||||
const kind = revision?.kind as XiaoyiDeliveryKind | undefined
|
||||
const references = { ...(requestedRevision ? snapshot?.related : delivery?.relatedMaterials) }
|
||||
if (kind) references[kind] = { materialId: material.id, revisionId }
|
||||
const detailRef = references.detail
|
||||
let detailAssets: Array<{ assetType: string; barcodes: Array<{ barcode: string }> }> | undefined = detailRef?.materialId === material.id ? revision?.assets : undefined
|
||||
if (revision && detailRef && detailRef.materialId !== material.id) {
|
||||
const available = await prisma.material.findFirst({
|
||||
where: { id: detailRef.materialId, deletedAt: null, ...EXTERNAL_MATERIAL_SCOPE_WHERE },
|
||||
select: { id: true, assets: { where: { assetType: { in: ['detail', 'sku'] } }, include: { barcodes: true } } },
|
||||
})
|
||||
if (available) {
|
||||
const detailRevisionId = detailRef.revisionId ?? (await getLegacyDeliveryRevisionId(available.id))?.id
|
||||
detailAssets = detailRevisionId ? (await getDeliveryRevision(available.id, detailRevisionId))?.assets : available.assets
|
||||
}
|
||||
}
|
||||
const detailBarcodes = detailAssets?.filter(asset => asset.assetType === 'detail')
|
||||
.flatMap(asset => asset.barcodes.map(({ barcode }) => barcode)).sort()
|
||||
const skuBarcodes = detailAssets?.filter(asset => asset.assetType === 'sku')
|
||||
.flatMap(asset => asset.barcodes.map(({ barcode }) => barcode))
|
||||
const tokenParams = revisionId ? { revisionId } : {}
|
||||
const groups: Record<string, any[]> = {main: [], sku: [], detail: [], video: [], buyer_show: []}
|
||||
for (const asset of material.assets || []) {
|
||||
for (const asset of revision?.assets ?? material.assets ?? []) {
|
||||
if (!groups[asset.assetType]) continue
|
||||
const spec = metadata?.assetSpecs?.[asset.id]
|
||||
groups[asset.assetType].push({
|
||||
@ -221,7 +254,7 @@ export async function GET(request: NextRequest) {
|
||||
skuCode: asset.skuCode || null,
|
||||
barcodes: (asset.barcodes || []).map((entry: { barcode: string }) => entry.barcode),
|
||||
} : {}),
|
||||
downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'single', assetId: asset.id}),
|
||||
downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'single', assetId: asset.id, ...tokenParams}),
|
||||
})
|
||||
}
|
||||
await logApiCall({
|
||||
@ -229,37 +262,42 @@ export async function GET(request: NextRequest) {
|
||||
statusCode: 200, duration: Date.now() - startTime, ipAddress: getClientIp(request),
|
||||
userAgent: request.headers.get('user-agent') || undefined,
|
||||
})
|
||||
const relatedMaterial = (id?: string) => id ? {
|
||||
materialId: id,
|
||||
downloadUrl: generateDownloadUrl(baseUrl, {materialId: id, downloadType: 'all'}),
|
||||
const relatedMaterial = (ref?: DeliveryReference) => ref ? {
|
||||
materialId: ref.materialId,
|
||||
...(ref.revisionId && { revisionId: ref.revisionId }),
|
||||
downloadUrl: generateDownloadUrl(baseUrl, {
|
||||
materialId: ref.materialId, downloadType: 'all', ...(ref.revisionId && { revisionId: ref.revisionId }),
|
||||
}),
|
||||
} : null
|
||||
const response = successResponse({
|
||||
materialId: material.id, materialType: material.materialType, productModel: material.productModel,
|
||||
identifier: material.productModel,
|
||||
spu: delivery || groups.sku.some(asset => asset.barcodes.length) ? material.productModel : null,
|
||||
categoryName: material.categoryName, productCategoryName: material.productCategoryName,
|
||||
storeCategoryName: metadata?.storeCategoryName ?? (material.categoryName || null),
|
||||
materialId: material.id, materialType: material.materialType, productModel: view.productModel,
|
||||
identifier: view.productModel,
|
||||
spu: delivery || groups.sku.some(asset => asset.barcodes.length) ? view.productModel : null,
|
||||
categoryName: view.categoryName, productCategoryName: view.productCategoryName,
|
||||
storeCategoryName: metadata?.storeCategoryName ?? (view.categoryName || null),
|
||||
authorId: delivery?.authorId ?? material.userId,
|
||||
authorName: material.authorName,
|
||||
detailBarcode: delivery?.detailBarcode ?? null,
|
||||
barcodes: delivery?.barcodes ?? Array.from(new Set<string>(groups.sku.flatMap(asset => asset.barcodes))),
|
||||
authorName: view.authorName,
|
||||
detailBarcode: revision ? detailBarcodes?.[0] ?? null : delivery?.detailBarcode ?? null,
|
||||
barcodes: Array.from(new Set<string>(skuBarcodes ?? (revision ? undefined : delivery?.barcodes)
|
||||
?? groups.sku.flatMap(asset => asset.barcodes))).sort(),
|
||||
...(delivery?.deliveryGroupId && {
|
||||
deliveryGroupId: delivery.deliveryGroupId,
|
||||
relatedMaterials: {
|
||||
detail: relatedMaterial(delivery.relatedMaterials?.detail),
|
||||
video: relatedMaterial(delivery.relatedMaterials?.video),
|
||||
buyer_show: relatedMaterial(delivery.relatedMaterials?.buyer_show),
|
||||
detail: relatedMaterial(references.detail),
|
||||
video: relatedMaterial(references.video),
|
||||
buyer_show: relatedMaterial(references.buyer_show),
|
||||
},
|
||||
}),
|
||||
brandName: delivery?.brandName || '', productName: delivery?.productName || '', identifierType: delivery ? 'spu' : '',
|
||||
brandName: snapshot?.brandName ?? delivery?.brandName ?? '', productName: snapshot?.productName ?? delivery?.productName ?? '', identifierType: delivery ? 'spu' : '',
|
||||
isFullSet: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.detail && XIAOYI_DETAIL_ASSET_GROUPS.every(group => groups[group].length),
|
||||
...(revisionId && { revisionId }),
|
||||
...(delivery?.eventId && { eventId: delivery.eventId, listingStatus: delivery.listingStatus ?? pendingListingStatus }),
|
||||
assets: groups,
|
||||
files: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.video ? groups.video
|
||||
: material.materialType === XIAOYI_DELIVERY_MATERIAL_TYPES.buyer_show ? groups.buyer_show : [],
|
||||
downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'all'}),
|
||||
downloadUrls: {all: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'all'})},
|
||||
createdAt: material.createdAt.toISOString(), updatedAt: material.updatedAt.toISOString(),
|
||||
downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'all', ...tokenParams}),
|
||||
downloadUrls: {all: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'all', ...tokenParams})},
|
||||
createdAt: material.createdAt.toISOString(), updatedAt: (revision?.createdAt ?? material.updatedAt).toISOString(),
|
||||
})
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { getHistoricalDeliveryAsset } from '@/lib/delivery-revisions'
|
||||
import { createReadStream } from 'fs'
|
||||
import { stat } from 'fs/promises'
|
||||
import path from 'path'
|
||||
@ -34,6 +35,7 @@ export async function GET(request: NextRequest, { params }: { params: { id: stri
|
||||
if (!permitted) return new NextResponse(createDownloadPermissionError('materialType').error, { status: 403 })
|
||||
}
|
||||
const asset = await prisma.materialAsset.findFirst({ where: { id: params.assetId, materialId: material.id }, select: { fileUrl: true, fileName: true } })
|
||||
?? await getHistoricalDeliveryAsset(material.id, params.assetId)
|
||||
if (!asset?.fileUrl) return new NextResponse('文件不存在', { status: 404 })
|
||||
const filePath = resolveStoredUploadPath(asset.fileUrl)
|
||||
if (!isPathInAllowedDirs(filePath, [getUploadRootDir()])) return new NextResponse('文件不存在', { status: 404 })
|
||||
|
||||
@ -139,6 +139,36 @@ describe('SuperAdminsTab workbench navigation', () => {
|
||||
expect(screen.queryByText('事件 ID event-1')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('仅为已耗尽任务显示重放按钮,点击后刷新投递列表', async () => {
|
||||
const user = userEvent.setup()
|
||||
const fetchMock = jest.mocked(global.fetch)
|
||||
const fallback = fetchMock.getMockImplementation()!
|
||||
const toast = jest.fn()
|
||||
fetchMock.mockImplementation((input, init) => {
|
||||
const url = String(input)
|
||||
if (url === '/api/admin/external-notification-deliveries/exhausted-1/retry') {
|
||||
return Promise.resolve({ ok: true } as Response)
|
||||
}
|
||||
if (url.startsWith('/api/admin/auto-listing-targets')) {
|
||||
return Promise.resolve({ ok: true, json: async () => ({
|
||||
data: { targets: [], recentDeliveries: [
|
||||
{ id: 'pending-1', materialId: 'material-1', status: 'retrying' },
|
||||
{ id: 'exhausted-1', materialId: 'material-2', status: 'exhausted' },
|
||||
] },
|
||||
}) } as Response)
|
||||
}
|
||||
return fallback(input, init)
|
||||
})
|
||||
|
||||
render(<SuperAdminsTab showToast={toast} />)
|
||||
await user.click(await screen.findByRole('button', { name: /素材外发/ }))
|
||||
const replay = await screen.findByRole('button', { name: '重放投递' })
|
||||
expect(screen.getAllByRole('button', { name: '重放投递' })).toHaveLength(1)
|
||||
await user.click(replay)
|
||||
await waitFor(() => expect(toast).toHaveBeenCalledWith('补发任务已重新入队', 'success'))
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/admin/external-notification-deliveries/exhausted-1/retry', { method: 'POST' })
|
||||
})
|
||||
|
||||
test('可以创建只能拉取小壹素材并回传状态的专用 Key', async () => {
|
||||
const user = userEvent.setup()
|
||||
const fetchMock = global.fetch as jest.Mock
|
||||
|
||||
@ -1362,13 +1362,14 @@ export default function SuperAdminsTab({ showToast, onStateChange }: SuperAdmins
|
||||
: delivery.lastStatusCode && <p>HTTP {delivery.lastStatusCode}</p>}
|
||||
{delivery.nextRetryAt && <p>下次重试 {formatDateTime(delivery.nextRetryAt)}</p>}
|
||||
</div>
|
||||
<button
|
||||
{delivery.status === 'exhausted' && <button
|
||||
type="button"
|
||||
onClick={() => void handleRetryNotificationDelivery(delivery.id)}
|
||||
disabled={retryingNotificationDeliveryId !== null || delivery.status === 'succeeded'}
|
||||
disabled={retryingNotificationDeliveryId !== null}
|
||||
className="min-h-10 justify-self-start self-start rounded-lg border border-gray-300 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-50 focus-visible:outline-blue-600 disabled:opacity-50"
|
||||
>
|
||||
{retryingNotificationDeliveryId === delivery.id ? '补发中…' : '手工补发'}
|
||||
</button>
|
||||
{retryingNotificationDeliveryId === delivery.id ? '重放中…' : '重放投递'}
|
||||
</button>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@ -13,13 +13,15 @@ import fixture from './fixtures/xiaoyi-free-barcode.json'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({ prisma: {
|
||||
$queryRawUnsafe: jest.fn(), $queryRaw: jest.fn(), $transaction: jest.fn(), $executeRawUnsafe: jest.fn(),
|
||||
material: { create: jest.fn(), update: jest.fn() }, materialAsset: { deleteMany: jest.fn() }, materialLog: { create: jest.fn() },
|
||||
material: { create: jest.fn(), update: jest.fn(), findUniqueOrThrow: jest.fn() }, materialAsset: { deleteMany: jest.fn() }, materialLog: { create: jest.fn(), findFirst: jest.fn() },
|
||||
deliveryRevision: { create: jest.fn(), findUnique: jest.fn() },
|
||||
xiaoyiAutoListingEvent: { findUnique: jest.fn() },
|
||||
} }))
|
||||
jest.mock('@/lib/detail-generator/materials', () => ({ findDetailMaterialMatches: jest.fn() }))
|
||||
jest.mock('node:fs', () => ({ createReadStream: jest.fn(() => [Buffer.from('x')]) }))
|
||||
jest.mock('node:fs/promises', () => ({ mkdir: jest.fn(), lstat: jest.fn(), copyFile: jest.fn(), rm: jest.fn() }))
|
||||
jest.mock('@/lib/material-facets-cache', () => ({ invalidateMaterialFacetsCache: jest.fn() }))
|
||||
jest.mock('@/lib/remote-upload-sync', () => ({ syncStoredUploadFileToRemote: jest.fn() }))
|
||||
jest.mock('@/lib/remote-upload-sync', () => ({ syncStoredUploadFileToRemote: jest.fn(), isRemoteUploadSyncEnabled: jest.fn(() => false) }))
|
||||
jest.mock('@/lib/upload-sessions', () => ({ getOwnedUploadSession: jest.fn() }))
|
||||
jest.mock('@/lib/upload-paths', () => ({
|
||||
getUploadRootDir: jest.fn(),
|
||||
@ -59,6 +61,8 @@ beforeEach(() => {
|
||||
;(prisma.$queryRawUnsafe as jest.Mock).mockImplementation(async (sql: string) =>
|
||||
sql.startsWith('SELECT id FROM desktop_workspace_projects') ? [{ id: 'project-1' }] : [])
|
||||
jest.mocked(prisma.$queryRaw).mockResolvedValue([])
|
||||
jest.mocked(prisma.deliveryRevision.findUnique).mockResolvedValue(null)
|
||||
jest.mocked(prisma.deliveryRevision.create).mockResolvedValue({ id: 'revision-new' } as any)
|
||||
jest.mocked(findDetailMaterialMatches).mockResolvedValue([])
|
||||
})
|
||||
|
||||
@ -318,7 +322,14 @@ test('完结后微调图片再次点击完结支持原位修订更新,且原
|
||||
material: prisma.material,
|
||||
materialAsset: prisma.materialAsset,
|
||||
materialLog: prisma.materialLog,
|
||||
deliveryRevision: prisma.deliveryRevision,
|
||||
xiaoyiAutoListingEvent: prisma.xiaoyiAutoListingEvent,
|
||||
}))
|
||||
jest.mocked(prisma.material.findUniqueOrThrow).mockResolvedValue({
|
||||
currentRevisionId: null, authorName: '原作者', productModel: 'SPU-1', categoryName: '', productCategoryName: '',
|
||||
assets: [{ id: 'old-main', assetType: 'main', fileName: 'old.jpg', fileUrl: 'uploads/old.jpg', fileSize: BigInt(1), sortOrder: 0, barcodes: [] }],
|
||||
} as any)
|
||||
jest.mocked(prisma.deliveryRevision.create).mockResolvedValueOnce({ id: 'revision-baseline' } as any)
|
||||
jest.mocked(prisma.materialAsset.deleteMany).mockResolvedValue({ count: 3 } as any)
|
||||
jest.mocked(prisma.material.update).mockResolvedValue({ id: 'mat-existing' } as any)
|
||||
jest.mocked(prisma.materialLog.create).mockResolvedValue({} as any)
|
||||
@ -339,11 +350,21 @@ test('完结后微调图片再次点击完结支持原位修订更新,且原
|
||||
expect(prisma.material.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'mat-existing' } }))
|
||||
expect(prisma.material.create).not.toHaveBeenCalled()
|
||||
expect(queueXiaoyiAutoListingNotification).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
materialId: 'mat-existing', replaceExisting: true,
|
||||
materialId: 'mat-existing', revisionId: 'revision-new',
|
||||
}))
|
||||
|
||||
const [revisionSql] = jest.mocked(prisma.$executeRawUnsafe).mock.calls[0]
|
||||
expect(revisionSql).toMatch(/WHEN listing_status->>'state' = 'listed' OR NULLIF\(listing_status->>'listingId', ''\) IS NOT NULL\s+THEN listing_status\s+ELSE NULL/)
|
||||
expect(revisionSql).not.toContain('listing_status')
|
||||
expect(prisma.deliveryRevision.create).toHaveBeenNthCalledWith(1, expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
requestId: 'request-rev-1', assets: { createMany: { data: [expect.objectContaining({ id: 'old-main', fileUrl: 'uploads/old.jpg' })] } },
|
||||
}),
|
||||
}))
|
||||
expect(prisma.deliveryRevision.create).toHaveBeenNthCalledWith(2, expect.objectContaining({
|
||||
data: expect.objectContaining({ requestId: 'request-rev-2', parentId: 'revision-baseline' }),
|
||||
}))
|
||||
expect(jest.mocked(prisma.deliveryRevision.create).mock.invocationCallOrder[0])
|
||||
.toBeLessThan(jest.mocked(prisma.materialAsset.deleteMany).mock.invocationCallOrder[0])
|
||||
|
||||
// 交接发生在文件预写之后,也必须在事务里确认当前归属。
|
||||
jest.mocked(prisma.$queryRaw).mockResolvedValue([])
|
||||
|
||||
@ -29,6 +29,7 @@ jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
$executeRawUnsafe: jest.fn(),
|
||||
$queryRawUnsafe: jest.fn(),
|
||||
$queryRaw: jest.fn(),
|
||||
$transaction: jest.fn(),
|
||||
material: {
|
||||
findFirst: jest.fn(),
|
||||
@ -58,6 +59,7 @@ describe('external auto listing', () => {
|
||||
jest.useFakeTimers()
|
||||
;(prisma.$executeRawUnsafe as jest.Mock).mockResolvedValue(undefined)
|
||||
;(prisma.$queryRawUnsafe as jest.Mock).mockResolvedValue([])
|
||||
jest.mocked(prisma.$queryRaw).mockResolvedValue([{ ready: true }])
|
||||
;(prisma.$transaction as jest.Mock).mockImplementation(async (callback: any) =>
|
||||
callback({
|
||||
$executeRawUnsafe: jest.fn().mockResolvedValue(undefined),
|
||||
@ -231,46 +233,37 @@ describe('external auto listing', () => {
|
||||
expect(prisma.$executeRawUnsafe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('投递成功后应标记为 succeeded', async () => {
|
||||
;(prisma.$transaction as jest.Mock).mockImplementation(async (callback: any) =>
|
||||
callback({
|
||||
$executeRawUnsafe: jest.fn().mockResolvedValue(undefined),
|
||||
$queryRawUnsafe: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'delivery-1',
|
||||
status: 'pending',
|
||||
payload: { eventId: 'evt-1' },
|
||||
attemptCount: 0,
|
||||
maxAttempts: 5,
|
||||
updatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetId: 'target-1',
|
||||
name: '自动上架平台',
|
||||
callbackUrl: 'https://auto.example.com/callback',
|
||||
isActive: true,
|
||||
authType: 'bearer',
|
||||
authConfig: { token: 'secret-token' },
|
||||
eventTypes: [AUTO_LISTING_EVENT_TYPE],
|
||||
createdAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetUpdatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
},
|
||||
]),
|
||||
}),
|
||||
)
|
||||
function mockClaim(attemptCount = 1, writeCount = 1) {
|
||||
const query = jest.fn()
|
||||
.mockResolvedValueOnce([{
|
||||
id: 'target-1', name: '自动上架平台', callbackUrl: 'https://auto.example.com/callback',
|
||||
authType: 'none', authConfig: {}, eventTypes: [AUTO_LISTING_EVENT_TYPE], createdAt: new Date(),
|
||||
}])
|
||||
.mockResolvedValueOnce([{ materialId: 'material-1', attemptCount, maxAttempts: 5, payload: { eventId: 'evt-1' } }])
|
||||
.mockResolvedValue([])
|
||||
const write = jest.fn().mockResolvedValue(writeCount)
|
||||
jest.mocked(prisma.$transaction).mockImplementation(async action => action({ $queryRaw: query, $executeRaw: write } as any))
|
||||
jest.mocked(prisma.material.findFirst).mockResolvedValue({ id: 'material-1' } as any)
|
||||
return { query, write }
|
||||
}
|
||||
|
||||
test('认领时计次,完成写回绑定同一个未过期租约', async () => {
|
||||
const { query, write } = mockClaim()
|
||||
jest.mocked(postAutoListingCallback).mockResolvedValueOnce(200)
|
||||
|
||||
const result = await processExternalNotificationDelivery('delivery-1')
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
status: AUTO_LISTING_DELIVERY_STATUS.SUCCEEDED,
|
||||
await expect(processExternalNotificationDelivery('delivery-1')).resolves.toEqual({
|
||||
success: true, status: AUTO_LISTING_DELIVERY_STATUS.SUCCEEDED,
|
||||
})
|
||||
expect(prisma.$executeRawUnsafe).toHaveBeenCalledWith(
|
||||
expect.stringContaining(`UPDATE "${'external_notification_deliveries'}"`),
|
||||
'delivery-1',
|
||||
AUTO_LISTING_DELIVERY_STATUS.SUCCEEDED,
|
||||
200,
|
||||
null,
|
||||
)
|
||||
expect(query.mock.calls[0][0].join('')).toContain('SKIP LOCKED')
|
||||
expect(query.mock.calls[1][0].join('')).toContain('attempt_count=LEAST')
|
||||
expect(write.mock.calls[0][0].join('')).toContain('lease_expires_at > NOW()')
|
||||
expect(write.mock.calls[0].at(-1)).toBe(query.mock.calls[1][1])
|
||||
})
|
||||
|
||||
test('过期持有者无法更新目标熔断计数或覆盖投递结果', async () => {
|
||||
const { write } = mockClaim(1, 0)
|
||||
jest.mocked(postAutoListingCallback).mockResolvedValueOnce(500)
|
||||
await expect(processExternalNotificationDelivery('expired-job')).resolves.toBeNull()
|
||||
expect(write).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('创建通知任务时应把预览图和拉取地址写入 payload', async () => {
|
||||
@ -363,70 +356,16 @@ describe('external auto listing', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('投递失败后应进入 retrying,并支持手工补发查询', async () => {
|
||||
;(prisma.$transaction as jest.Mock).mockImplementation(async (callback: any) =>
|
||||
callback({
|
||||
$executeRawUnsafe: jest.fn().mockResolvedValue(undefined),
|
||||
$queryRawUnsafe: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'delivery-2',
|
||||
status: 'pending',
|
||||
payload: { eventId: 'evt-2' },
|
||||
attemptCount: 0,
|
||||
maxAttempts: 5,
|
||||
updatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetId: 'target-1',
|
||||
name: '自动上架平台',
|
||||
callbackUrl: 'https://auto.example.com/callback',
|
||||
isActive: true,
|
||||
authType: 'none',
|
||||
authConfig: {},
|
||||
eventTypes: [AUTO_LISTING_EVENT_TYPE],
|
||||
createdAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetUpdatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
},
|
||||
]),
|
||||
}),
|
||||
)
|
||||
;(prisma.$queryRawUnsafe as jest.Mock)
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
id: 'delivery-2',
|
||||
targetId: 'target-1',
|
||||
targetName: '自动上架平台',
|
||||
eventType: AUTO_LISTING_EVENT_TYPE,
|
||||
materialId: 'material-1',
|
||||
materialType: '任务-详情',
|
||||
taskNo: null,
|
||||
status: AUTO_LISTING_DELIVERY_STATUS.RETRYING,
|
||||
attemptCount: 1,
|
||||
maxAttempts: 5,
|
||||
nextRetryAt: new Date('2026-03-25T10:01:00.000Z'),
|
||||
lastStatusCode: 500,
|
||||
lastResponseBody: 'server error',
|
||||
lastError: 'HTTP 500',
|
||||
createdAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-03-25T10:00:01.000Z'),
|
||||
completedAt: null,
|
||||
},
|
||||
])
|
||||
jest.mocked(postAutoListingCallback).mockResolvedValueOnce(500)
|
||||
|
||||
const result = await processExternalNotificationDelivery('delivery-2')
|
||||
const deliveries = await listExternalNotificationDeliveries()
|
||||
await retryExternalNotificationDelivery('delivery-2')
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
status: AUTO_LISTING_DELIVERY_STATUS.RETRYING,
|
||||
})
|
||||
expect(deliveries).toHaveLength(1)
|
||||
expect(deliveries[0].status).toBe(AUTO_LISTING_DELIVERY_STATUS.RETRYING)
|
||||
expect(prisma.$executeRawUnsafe).toHaveBeenCalledWith(
|
||||
expect.stringContaining(`UPDATE "${'external_notification_deliveries'}"`),
|
||||
'delivery-2',
|
||||
AUTO_LISTING_DELIVERY_STATUS.PENDING,
|
||||
)
|
||||
test('手工重放只有耗尽任务能重置预算并记录操作人', async () => {
|
||||
const query = jest.fn().mockResolvedValue([{ enabled: true }])
|
||||
const write = jest.fn().mockResolvedValueOnce(1).mockResolvedValueOnce(0)
|
||||
jest.mocked(prisma.$transaction).mockImplementation(async action => action({ $queryRaw: query, $executeRaw: write } as any))
|
||||
await expect(retryExternalNotificationDelivery('delivery-2', 'admin')).resolves.toBe('queued')
|
||||
await expect(retryExternalNotificationDelivery('delivery-2', 'admin')).resolves.toBe('conflict')
|
||||
const [sql, actor, id] = write.mock.calls[0]
|
||||
expect(sql.join('')).toContain("AND status='exhausted'")
|
||||
expect(sql.join('')).toContain('attempt_count=0')
|
||||
expect([actor, id]).toEqual(['admin', 'delivery-2'])
|
||||
})
|
||||
|
||||
test('精确匹配素材、任务、项目和事件编号,在截取最近记录前执行筛选', async () => {
|
||||
@ -547,42 +486,16 @@ describe('external auto listing', () => {
|
||||
])
|
||||
})
|
||||
|
||||
test('重试退避时间应基于数据库 NOW() 计算间隔,避免 ::timestamp 时区偏差', async () => {
|
||||
;(prisma.$transaction as jest.Mock).mockImplementationOnce(async (callback) =>
|
||||
callback({
|
||||
$executeRawUnsafe: jest.fn().mockResolvedValue(1),
|
||||
$queryRawUnsafe: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'delivery-tz-1',
|
||||
status: 'retrying',
|
||||
payload: { eventId: 'evt-1' },
|
||||
attemptCount: 1,
|
||||
maxAttempts: 5,
|
||||
updatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetId: 'target-1',
|
||||
name: '自动上架平台',
|
||||
callbackUrl: 'https://auto.example.com/callback',
|
||||
isActive: true,
|
||||
authType: 'none',
|
||||
authConfig: {},
|
||||
eventTypes: [AUTO_LISTING_EVENT_TYPE],
|
||||
createdAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
targetUpdatedAt: new Date('2026-03-25T10:00:00.000Z'),
|
||||
},
|
||||
]),
|
||||
}),
|
||||
)
|
||||
test('重试退避使用数据库时间,并将回调失败计入目标熔断', async () => {
|
||||
const { write } = mockClaim(2)
|
||||
jest.mocked(postAutoListingCallback).mockResolvedValueOnce(502)
|
||||
|
||||
const result = await processExternalNotificationDelivery('delivery-tz-1')
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
status: AUTO_LISTING_DELIVERY_STATUS.RETRYING,
|
||||
await expect(processExternalNotificationDelivery('delivery-tz-1')).resolves.toEqual({
|
||||
success: false, status: AUTO_LISTING_DELIVERY_STATUS.RETRYING,
|
||||
})
|
||||
const updateCall = (prisma.$executeRawUnsafe as jest.Mock).mock.calls.at(-1)!
|
||||
expect(updateCall[0]).toContain("NOW() + ($6::bigint * INTERVAL '1 millisecond')")
|
||||
expect(updateCall[0]).not.toContain('::timestamp')
|
||||
expect(updateCall[6]).toBe(5 * 60 * 1000)
|
||||
expect(updateCall[7]).toBe(false)
|
||||
const [statement, , , , delay] = write.mock.calls[0]
|
||||
expect(statement.join('')).toContain("INTERVAL '1 millisecond'")
|
||||
expect(delay).toBeGreaterThanOrEqual(5 * 60 * 1000)
|
||||
expect(delay).toBeLessThan(6 * 60 * 1000)
|
||||
expect(write.mock.calls[1][0].join('')).toContain('consecutive_failures+1')
|
||||
})
|
||||
})
|
||||
|
||||
@ -26,6 +26,8 @@ jest.mock('@/lib/prisma', () => ({
|
||||
material: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
deliveryRevision: { findFirst: jest.fn() },
|
||||
revisionAsset: { findFirst: jest.fn() },
|
||||
},
|
||||
}))
|
||||
|
||||
@ -432,7 +434,7 @@ describe('external single-file S3 download range forwarding', () => {
|
||||
|
||||
const response = await GET(makeRequest())
|
||||
expect(response.status).toBe(200)
|
||||
expect(getS3ObjectStream).toHaveBeenCalledWith('xiaoyi/uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg')
|
||||
expect(getS3ObjectStream).toHaveBeenCalledWith('xiaoyi/uploads/xiaoyi-deliveries/owner/proj/req/0000-main.jpg', expect.anything())
|
||||
const zip = new AdmZip(Buffer.from(await response.arrayBuffer()))
|
||||
expect(zip.readAsText('main/0000-main.jpg')).toBe('remote-main-bytes')
|
||||
})
|
||||
@ -468,6 +470,37 @@ describe('external single-file S3 download range forwarding', () => {
|
||||
expect(Buffer.from(await response.arrayBuffer()).toString()).toBe('remote-single-bytes')
|
||||
})
|
||||
|
||||
test('旧单图和固定版本整包继续读取该次交付的字节', async () => {
|
||||
const oldAsset = {
|
||||
id: 'previous-main', assetType: 'main', fileName: 'old.jpg', barcodes: [],
|
||||
fileUrl: 'uploads/xiaoyi-deliveries/owner/proj/old/0000-main.jpg',
|
||||
}
|
||||
jest.mocked(prisma.material.findUnique).mockResolvedValue({
|
||||
id: 'material-1', materialType: '自动上架-详情', currentRevisionId: 'new-revision',
|
||||
createdAt: new Date('2026-12-01T00:00:00.000Z'), assets: [],
|
||||
} as any)
|
||||
jest.mocked(prisma.revisionAsset.findFirst).mockResolvedValue(oldAsset as any)
|
||||
jest.mocked(prisma.deliveryRevision.findFirst).mockResolvedValue({ assets: [oldAsset] } as any)
|
||||
jest.mocked(getS3ObjectStream).mockImplementation(async () => ({
|
||||
body: Readable.from([Buffer.from('old-version-bytes')]), contentLength: 17,
|
||||
}))
|
||||
|
||||
jest.mocked(verifyDownloadToken).mockReturnValue({ materialId: 'material-1', downloadType: 'single', assetId: oldAsset.id })
|
||||
const single = await GET(makeRequest())
|
||||
expect(single.status).toBe(200)
|
||||
expect(Buffer.from(await single.arrayBuffer()).toString()).toBe('old-version-bytes')
|
||||
expect(prisma.revisionAsset.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: oldAsset.id, revision: { materialId: 'material-1' } },
|
||||
})
|
||||
|
||||
jest.mocked(verifyDownloadToken).mockReturnValue({ materialId: 'material-1', downloadType: 'all', revisionId: 'old-revision' })
|
||||
const archive = await GET(makeRequest())
|
||||
expect(prisma.deliveryRevision.findFirst).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: { id: 'old-revision', materialId: 'material-1' },
|
||||
}))
|
||||
expect(new AdmZip(Buffer.from(await archive.arrayBuffer())).readAsText('main/old.jpg')).toBe('old-version-bytes')
|
||||
})
|
||||
|
||||
test('returns 503 when both local and S3 objects are missing for Xiaoyi ZIP', async () => {
|
||||
;(verifyDownloadToken as jest.Mock).mockReturnValue({
|
||||
materialId: 'material-1',
|
||||
|
||||
@ -257,23 +257,23 @@ describe('external notification admin routes', () => {
|
||||
})
|
||||
|
||||
test('POST /api/admin/external-notification-deliveries/[id]/retry 应触发手工补发', async () => {
|
||||
;(retryExternalNotificationDelivery as jest.Mock).mockResolvedValue(undefined)
|
||||
;(retryExternalNotificationDelivery as jest.Mock).mockResolvedValue('queued')
|
||||
|
||||
const response = await retryDeliveryRoute(new Request('http://localhost') as any, {
|
||||
const response = await retryDeliveryRoute(new Request('http://localhost', { headers: { origin: 'http://localhost', host: 'localhost' } }) as any, {
|
||||
params: { id: 'delivery-1' },
|
||||
} as any)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
expect(retryExternalNotificationDelivery).toHaveBeenCalledWith('delivery-1')
|
||||
expect(retryExternalNotificationDelivery).toHaveBeenCalledWith('delivery-1', 'admin-1')
|
||||
})
|
||||
|
||||
test('非真正超管时即使是 SYSTEM_ADMIN 也返回 403', async () => {
|
||||
;(isSuperAdmin as jest.Mock).mockResolvedValue(false)
|
||||
|
||||
const targetsResponse = await getTargetsRoute(new Request('http://localhost/api/admin/external-notification-targets') as any)
|
||||
const retryResponse = await retryDeliveryRoute(new Request('http://localhost') as any, {
|
||||
const retryResponse = await retryDeliveryRoute(new Request('http://localhost', { headers: { origin: 'http://localhost', host: 'localhost' } }) as any, {
|
||||
params: { id: 'delivery-1' },
|
||||
} as any)
|
||||
|
||||
|
||||
51
lib/__tests__/external-zip-stream.test.ts
Normal file
51
lib/__tests__/external-zip-stream.test.ts
Normal file
@ -0,0 +1,51 @@
|
||||
/** @jest-environment node */
|
||||
import { Readable } from 'node:stream'
|
||||
import AdmZip from 'adm-zip'
|
||||
import { ExternalZipBusyError, MAX_ACTIVE_EXTERNAL_ZIPS, streamExternalZip } from '@/lib/external-zip-stream'
|
||||
|
||||
test('ZIP entries open in order without buffering multiple upstream sources', async () => {
|
||||
const opened: string[] = []
|
||||
let active = 0
|
||||
let peak = 0
|
||||
const entries = Array.from({ length: 40 }, (_, index) => ({
|
||||
name: 'main/' + String(index).padStart(2, '0') + '.jpg',
|
||||
open: async () => {
|
||||
const source = Readable.from((async function* () {
|
||||
active++
|
||||
peak = Math.max(peak, active)
|
||||
try {
|
||||
yield Buffer.alloc(128 * 1024, index)
|
||||
} finally {
|
||||
active--
|
||||
}
|
||||
})(), { objectMode: false })
|
||||
opened.push(String(index))
|
||||
return source
|
||||
},
|
||||
}))
|
||||
const stream = await streamExternalZip(entries)
|
||||
const bytes = Buffer.from(await new Response(stream).arrayBuffer())
|
||||
const zip = new AdmZip(bytes)
|
||||
expect(peak).toBe(1)
|
||||
expect(opened).toEqual(entries.map((_, index) => String(index)))
|
||||
expect(zip.getEntries().map(entry => entry.entryName)).toEqual(entries.map(entry => entry.name))
|
||||
entries.forEach((entry, index) => expect(zip.readFile(entry.name)?.[0]).toBe(index))
|
||||
})
|
||||
|
||||
test('concurrent slow ZIPs are bounded and cancellation releases the slot', async () => {
|
||||
const entry = {
|
||||
name: 'main/wait.jpg',
|
||||
open: (signal: AbortSignal) => new Promise<Readable>((_, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
}),
|
||||
}
|
||||
const active = await Promise.all(Array.from({ length: MAX_ACTIVE_EXTERNAL_ZIPS }, () => streamExternalZip([entry])))
|
||||
try {
|
||||
await expect(streamExternalZip([entry])).rejects.toBeInstanceOf(ExternalZipBusyError)
|
||||
await active.shift()!.cancel()
|
||||
await new Promise<void>(resolve => setImmediate(resolve))
|
||||
await expect(streamExternalZip([]).then(stream => new Response(stream).arrayBuffer())).resolves.toBeDefined()
|
||||
} finally {
|
||||
await Promise.all(active.map(stream => stream.cancel()))
|
||||
}
|
||||
})
|
||||
@ -85,7 +85,7 @@ test('候选筛选保留特殊文件名、编码 URL 和控制字符 URL 的等
|
||||
const rows = sources.map(fileUrl => ({ fileUrl }))
|
||||
const empty = { findMany: jest.fn().mockResolvedValue([]) }
|
||||
const db: any = { material: empty, materialAsset: { findMany: jest.fn().mockResolvedValue(rows) },
|
||||
materialSku: empty, brandKnowledge: empty, systemSettings: empty, performanceSurveyWorkItem: empty,
|
||||
revisionAsset: empty, materialSku: empty, brandKnowledge: empty, systemSettings: empty, performanceSurveyWorkItem: empty,
|
||||
workReviewVersion: empty, productPackageUploadJob: empty, taskDetailChangeRequest: empty,
|
||||
$queryRaw: jest.fn().mockResolvedValue(rows.map(row => ({ sources: [row.fileUrl], derived: true }))) }
|
||||
const full = await findPurgeFileReferences(db)
|
||||
|
||||
@ -140,7 +140,7 @@ describe('external product-assets route', () => {
|
||||
const asset = (type: string) => ({ id: type, assetType: type, fileName: type + '.jpg' })
|
||||
jest.mocked(prisma.$queryRaw).mockResolvedValue([{
|
||||
productName: '椅子', brandName: '测试品牌', eventId: 'event-1', deliveryGroupId: 'project-1',
|
||||
authorId: 'account-1', relatedMaterials: ids, detailBarcode: fixture.detailBarcode, barcodes,
|
||||
authorId: 'account-1', relatedMaterials: Object.fromEntries(Object.entries(ids).map(([kind, materialId]) => [kind, { materialId, revisionId: null }])), detailBarcode: fixture.detailBarcode, barcodes,
|
||||
}])
|
||||
jest.mocked(validateApiKey).mockResolvedValue({ id: 'listing-key', scope: 'xiaoyi_auto_listing' } as any)
|
||||
const relatedMaterials = Object.fromEntries(Object.entries(ids).map(([kind, id]) => [
|
||||
@ -175,7 +175,7 @@ describe('external product-assets route', () => {
|
||||
const sql = (jest.mocked(prisma.$queryRaw).mock.calls[0][0] as TemplateStringsArray).join('$1')
|
||||
expect(sql).toContain('related.project_id = d.project_id AND related.owner_id = d.owner_id')
|
||||
expect(sql).toContain('UPPER(rm."productModel") = UPPER(delivered."productModel")')
|
||||
expect(sql).toContain("WHERE a.material_id = (siblings.\"relatedMaterials\"->>'detail')")
|
||||
expect(sql).toContain("WHERE a.material_id = (siblings.\"relatedMaterials\"->'detail'->>'materialId')")
|
||||
})
|
||||
|
||||
test('早期交付缺少详情页主条码时不把首个 SKU 条码当作主条码', async () => {
|
||||
|
||||
@ -1,94 +1,67 @@
|
||||
|
||||
/** @jest-environment node */
|
||||
import {
|
||||
XIAOYI_AUTO_LISTING_EVENT_TYPE,
|
||||
queueXiaoyiAutoListingNotification,
|
||||
queueXiaoyiDeliveries,
|
||||
} from '@/lib/external-auto-listing'
|
||||
import { queueXiaoyiAutoListingNotification, queueXiaoyiDeliveries } from '@/lib/external-auto-listing'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: { $queryRawUnsafe: jest.fn(), $executeRawUnsafe: jest.fn() },
|
||||
prisma: {
|
||||
$transaction: jest.fn(), $queryRawUnsafe: jest.fn(),
|
||||
externalNotificationDelivery: { createMany: jest.fn() },
|
||||
},
|
||||
}))
|
||||
jest.mock('@/lib/public-app-url', () => ({
|
||||
getPublicAppOrigin: () => 'https://sc.jiansun.vip',
|
||||
}))
|
||||
|
||||
const event = {
|
||||
materialId: 'material-1',
|
||||
materialType: '自动上架-详情',
|
||||
outcomeKind: 'detail' as const,
|
||||
projectId: 'project-1',
|
||||
const data = {
|
||||
materialId: 'material-1', materialType: '自动上架-详情', outcomeKind: 'detail' as const, projectId: 'project-1',
|
||||
}
|
||||
const events = ['1', '2'].map(id => ({
|
||||
...data, eventId: 'event-' + id, revisionId: 'revision-' + id, createdAt: new Date('2026-11-30T12:00:00Z'),
|
||||
}))
|
||||
|
||||
describe('小壹自动上架通知', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
jest.useFakeTimers()
|
||||
;(prisma.$queryRawUnsafe as jest.Mock).mockResolvedValue([])
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks()
|
||||
jest.mocked(prisma.$queryRawUnsafe).mockResolvedValue([])
|
||||
})
|
||||
|
||||
test('每次完结在原事务追加独立的版本事件', async () => {
|
||||
const create = jest.fn()
|
||||
const tx = { xiaoyiAutoListingOutbox: { create } } as unknown as Parameters<typeof queueXiaoyiAutoListingNotification>[0]
|
||||
for (const { revisionId } of events) await queueXiaoyiAutoListingNotification(tx, { ...data, revisionId })
|
||||
expect(create.mock.calls).toEqual(events.map(({ revisionId }) => [{ data: { ...data, revisionId } }]))
|
||||
await expect(queueXiaoyiAutoListingNotification(tx, { ...data, revisionId: 'invalid', materialType: '自动上架-视频' }))
|
||||
.rejects.toThrow('参数无效')
|
||||
})
|
||||
|
||||
test('同一素材的两个待投事件均展开,通知、拉取和重放键保持对应版本', async () => {
|
||||
const tx = {
|
||||
$queryRaw: jest.fn().mockResolvedValueOnce(events).mockResolvedValueOnce([{ id: 'target' }]),
|
||||
externalNotificationDelivery: { createMany: jest.fn() },
|
||||
xiaoyiAutoListingOutbox: { updateMany: jest.fn() },
|
||||
}
|
||||
jest.mocked(prisma.$transaction).mockImplementation(async action => action(tx as any))
|
||||
await expect(queueXiaoyiDeliveries()).resolves.toBe(2)
|
||||
expect(tx.externalNotificationDelivery.createMany).toHaveBeenCalledWith({
|
||||
skipDuplicates: true,
|
||||
data: events.map(({ eventId, revisionId }) => expect.objectContaining({
|
||||
targetId: 'target', materialId: data.materialId, dedupeKey: eventId, status: 'pending',
|
||||
payload: expect.objectContaining({
|
||||
eventId, revisionId,
|
||||
pullUrl: 'https://sc.jiansun.vip/api/external/product-assets?materialId=material-1&revisionId=' + revisionId,
|
||||
}),
|
||||
})),
|
||||
})
|
||||
afterEach(() => jest.useRealTimers())
|
||||
|
||||
test('与素材创建共用事务并按素材编号防止重复登记', async () => {
|
||||
const execute = jest.fn().mockResolvedValue(1)
|
||||
await queueXiaoyiAutoListingNotification({ $executeRawUnsafe: execute }, event)
|
||||
const [sql, id, materialId, materialType, outcomeKind, projectId] = execute.mock.calls[0]
|
||||
expect(sql).toContain('ON CONFLICT (material_id) DO NOTHING')
|
||||
expect(id).toMatch(/^[0-9a-f-]{36}$/)
|
||||
expect({ materialId, materialType, outcomeKind, projectId }).toEqual(event)
|
||||
await expect(queueXiaoyiAutoListingNotification({ $executeRawUnsafe: execute }, {
|
||||
...event, materialType: '自动上架-视频',
|
||||
})).rejects.toThrow('参数无效')
|
||||
expect(execute).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('配置接收方后按同一事件和素材编号生成可重试投递', async () => {
|
||||
;(prisma.$queryRawUnsafe as jest.Mock)
|
||||
.mockResolvedValueOnce([{
|
||||
eventId: 'event-1', targetId: 'target-1', ...event, createdAt: new Date('2026-11-30T12:00:00Z'),
|
||||
}])
|
||||
.mockResolvedValueOnce([{ id: 'delivery-1' }])
|
||||
await queueXiaoyiDeliveries()
|
||||
const [selectSql, eventType] = (prisma.$queryRawUnsafe as jest.Mock).mock.calls[0]
|
||||
expect(selectSql).toContain('t.event_types ? $1')
|
||||
expect(eventType).toBe(XIAOYI_AUTO_LISTING_EVENT_TYPE)
|
||||
const [insertSql, , targetId, insertedEventType, materialId, , status, rawPayload] =
|
||||
(prisma.$queryRawUnsafe as jest.Mock).mock.calls[1]
|
||||
expect(insertSql).toContain('ON CONFLICT ("target_id","event_type","dedupe_key") DO NOTHING')
|
||||
expect({ targetId, insertedEventType, materialId, status }).toEqual({
|
||||
targetId: 'target-1', insertedEventType: XIAOYI_AUTO_LISTING_EVENT_TYPE, materialId: 'material-1', status: 'pending',
|
||||
})
|
||||
expect(JSON.parse(rawPayload)).toEqual({
|
||||
eventId: 'event-1', eventType: XIAOYI_AUTO_LISTING_EVENT_TYPE, ...event,
|
||||
occurredAt: '2026-11-30T12:00:00.000Z',
|
||||
pullUrl: 'https://sc.jiansun.vip/api/external/product-assets?materialId=material-1',
|
||||
statusUrl: 'https://sc.jiansun.vip/api/external/product-assets?materialId=material-1',
|
||||
})
|
||||
})
|
||||
|
||||
test('没有订阅目标时不发出请求,事件仍可在以后匹配目标', async () => {
|
||||
const fetch = jest.spyOn(global, 'fetch')
|
||||
await queueXiaoyiDeliveries()
|
||||
expect(prisma.$queryRawUnsafe).toHaveBeenCalledTimes(1)
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
fetch.mockRestore()
|
||||
})
|
||||
|
||||
test('原位修订通知可更新事件并按新 eventId 去重投递,不被旧事件吞掉', async () => {
|
||||
const execute = jest.fn().mockResolvedValue(1)
|
||||
await queueXiaoyiAutoListingNotification({ $executeRawUnsafe: execute }, { ...event, replaceExisting: true })
|
||||
const [sql] = execute.mock.calls[0]
|
||||
expect(sql).toContain('ON CONFLICT (material_id) DO UPDATE')
|
||||
|
||||
;(prisma.$queryRawUnsafe as jest.Mock)
|
||||
.mockResolvedValueOnce([{
|
||||
eventId: 'event-rev-2', targetId: 'target-1', ...event, createdAt: new Date('2026-12-01T12:00:00Z'),
|
||||
}])
|
||||
.mockResolvedValueOnce([{ id: 'delivery-rev-2' }])
|
||||
await queueXiaoyiDeliveries()
|
||||
const [selectSql] = (prisma.$queryRawUnsafe as jest.Mock).mock.calls[0]
|
||||
expect(selectSql).toContain('d.dedupe_key=e.id OR (d.dedupe_key=e.material_id AND d.created_at>=e.created_at)')
|
||||
const insertCall = (prisma.$queryRawUnsafe as jest.Mock).mock.calls[1]
|
||||
expect(insertCall.at(-1)).toBe('event-rev-2')
|
||||
expect(tx.xiaoyiAutoListingOutbox.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: { in: ['event-1', 'event-2'] } }, data: { expandedAt: expect.any(Date) },
|
||||
})
|
||||
})
|
||||
|
||||
test('没有订阅目标时版本事件仍未展开', async () => {
|
||||
const tx = {
|
||||
$queryRaw: jest.fn().mockResolvedValueOnce(events).mockResolvedValueOnce([]),
|
||||
xiaoyiAutoListingOutbox: { updateMany: jest.fn() },
|
||||
}
|
||||
jest.mocked(prisma.$transaction).mockImplementation(async action => action(tx as any))
|
||||
await expect(queueXiaoyiDeliveries()).resolves.toBe(0)
|
||||
expect(tx.xiaoyiAutoListingOutbox.updateMany).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
56
lib/__tests__/xiaoyi-delivery-gc.test.ts
Normal file
56
lib/__tests__/xiaoyi-delivery-gc.test.ts
Normal file
@ -0,0 +1,56 @@
|
||||
/** @jest-environment node */
|
||||
import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { collectXiaoyiDeliveryGarbage } from '@/lib/xiaoyi-delivery-gc'
|
||||
import { findPurgeFileReferences, purgeFileIdentity } from '@/lib/material-purge-files'
|
||||
|
||||
jest.mock('@/lib/material-purge-files', () => ({
|
||||
...jest.requireActual('@/lib/material-purge-files'),
|
||||
findPurgeFileReferences: jest.fn(),
|
||||
}))
|
||||
jest.mock('@/lib/prisma', () => ({ prisma: {} }))
|
||||
jest.mock('@/lib/remote-upload-sync', () => ({ deleteStoredUploadFileFromRemote: jest.fn() }))
|
||||
|
||||
test('回收先预览并标记,复查历史引用后才删除已过宽限期的孤儿文件', async () => {
|
||||
const previousRoot = process.env.UPLOAD_DIR
|
||||
const root = await mkdtemp(path.join(tmpdir(), 'wave2-gc-'))
|
||||
process.env.UPLOAD_DIR = root
|
||||
const owner = 'a'.repeat(64)
|
||||
const folder = path.join(root, 'xiaoyi-deliveries', owner, 'project', 'old-delivery')
|
||||
const photo = path.join(folder, 'photo.jpg')
|
||||
const marker = path.join(folder, '.gc-candidate')
|
||||
const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000)
|
||||
try {
|
||||
await mkdir(folder, { recursive: true })
|
||||
await writeFile(photo, 'delivery-bytes')
|
||||
await utimes(photo, old, old)
|
||||
await utimes(folder, old, old)
|
||||
const inspect = (dryRun?: boolean) => collectXiaoyiDeliveryGarbage({ kind: 'deliveries', dryRun })
|
||||
|
||||
jest.mocked(findPurgeFileReferences).mockResolvedValue(new Set())
|
||||
expect((await inspect()).rows[0].outcome).toBe('candidate')
|
||||
await expect(readFile(marker)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect((await inspect(false)).rows[0].outcome).toBe('marked')
|
||||
expect(await readFile(photo, 'utf8')).toBe('delivery-bytes')
|
||||
|
||||
await utimes(folder, old, old)
|
||||
await utimes(marker, old, old)
|
||||
jest.mocked(findPurgeFileReferences).mockImplementationOnce(async (_, files) => new Set([purgeFileIdentity(files![0])]))
|
||||
expect((await inspect(false)).rows[0].outcome).toBe('retained')
|
||||
await expect(readFile(marker)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect(await readFile(photo, 'utf8')).toBe('delivery-bytes')
|
||||
|
||||
await utimes(folder, old, old)
|
||||
expect((await inspect(false)).rows[0].outcome).toBe('marked')
|
||||
await utimes(folder, old, old)
|
||||
await utimes(marker, old, old)
|
||||
expect((await inspect(false)).rows[0].outcome).toBe('deleted')
|
||||
await expect(readFile(photo)).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
expect((await inspect(false)).rows).toEqual([])
|
||||
} finally {
|
||||
if (previousRoot === undefined) delete process.env.UPLOAD_DIR
|
||||
else process.env.UPLOAD_DIR = previousRoot
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
65
lib/delivery-revisions.ts
Normal file
65
lib/delivery-revisions.ts
Normal file
@ -0,0 +1,65 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { acquireTaskMaterialUploadSessionLocks } from '@/lib/material-upload-cross-process-lock'
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import type { XiaoyiDeliveryKind, XiaoyiDeliveryMetadata } from '@/lib/xiaoyi-delivery-material'
|
||||
|
||||
export type DeliveryReference = { materialId: string; revisionId: string | null }
|
||||
|
||||
export type DeliverySnapshot = {
|
||||
authorName: string
|
||||
productModel: string
|
||||
categoryName: string
|
||||
productCategoryName: string
|
||||
brandName: string
|
||||
productName: string
|
||||
metadata: XiaoyiDeliveryMetadata | null
|
||||
related: Partial<Record<XiaoyiDeliveryKind, DeliveryReference>>
|
||||
legacy?: true
|
||||
eventId?: string
|
||||
}
|
||||
|
||||
type RevisionAssetInput = Prisma.RevisionAssetCreateManyRevisionInput
|
||||
|
||||
export function saveDeliveryRevision(
|
||||
tx: Prisma.TransactionClient,
|
||||
revision: { materialId: string; ownerId: string; projectId: string; kind: XiaoyiDeliveryKind; requestId: string; fingerprint: string; parentId: string | null },
|
||||
snapshot: DeliverySnapshot,
|
||||
assets: RevisionAssetInput[],
|
||||
) {
|
||||
return tx.deliveryRevision.create({
|
||||
data: { ...revision, snapshot, assets: { createMany: { data: assets } } },
|
||||
select: { id: true },
|
||||
})
|
||||
}
|
||||
|
||||
export async function getDeliveryRevision(materialId: string, revisionId: string) {
|
||||
const revision = await prisma.deliveryRevision.findFirst({
|
||||
where: { id: revisionId, materialId },
|
||||
include: { assets: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }] } },
|
||||
})
|
||||
if (!revision) return null
|
||||
return {
|
||||
...revision,
|
||||
snapshot: revision.snapshot as DeliverySnapshot,
|
||||
assets: revision.assets.map(asset => ({ ...asset, barcodes: asset.barcodes.map(barcode => ({ barcode })) })),
|
||||
}
|
||||
}
|
||||
|
||||
export function getLegacyDeliveryRevisionId(materialId: string) {
|
||||
return prisma.deliveryRevision.findFirst({
|
||||
where: { materialId, snapshot: { path: ['legacy'], equals: true } },
|
||||
select: { id: true },
|
||||
})
|
||||
}
|
||||
|
||||
export function getHistoricalDeliveryAsset(materialId: string, assetId: string) {
|
||||
return prisma.revisionAsset.findFirst({
|
||||
where: { id: assetId, revision: { materialId } },
|
||||
})
|
||||
}
|
||||
|
||||
export function acquireDeliveryAttemptLock(owner: string, project: string, attempt: string, timeoutMs?: number) {
|
||||
const key = createHash('sha256').update(`${owner}/${project}/${attempt}`).digest('hex')
|
||||
return acquireTaskMaterialUploadSessionLocks([`delivery-${key}`], { timeoutMs })
|
||||
}
|
||||
@ -6,14 +6,14 @@ import path from 'node:path'
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { invalidateMaterialFacetsCache } from '@/lib/material-facets-cache'
|
||||
import { syncStoredUploadFileToRemote } from '@/lib/remote-upload-sync'
|
||||
import { isRemoteUploadSyncEnabled, syncStoredUploadFileToRemote } from '@/lib/remote-upload-sync'
|
||||
import { getOwnedUploadSession } from '@/lib/upload-sessions'
|
||||
import { buildStoredUploadPath, getUploadRootDir, getUploadStorageExtension, inspectUploadOutput } from '@/lib/upload-paths'
|
||||
import { resolveStrictChildPath } from '@/lib/path-security'
|
||||
import { validateUploadFileName } from '@/lib/upload-file-name'
|
||||
import { detailTransactionLock } from '@/lib/detail-generator/repository'
|
||||
import { findDetailMaterialMatches } from '@/lib/detail-generator/materials'
|
||||
import { ensureExternalNotificationTables, queueXiaoyiAutoListingNotification, wakeXiaoyiAutoListingNotifications } from '@/lib/external-auto-listing'
|
||||
import { queueXiaoyiAutoListingNotification, wakeXiaoyiAutoListingNotifications } from '@/lib/external-auto-listing'
|
||||
import { desktopAssert, desktopId } from './contract.mjs'
|
||||
import { pendingListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status'
|
||||
import {
|
||||
@ -21,6 +21,9 @@ import {
|
||||
type XiaoyiAssetSpec, type XiaoyiDeliveryKind, type XiaoyiDeliveryMetadata,
|
||||
} from '@/lib/xiaoyi-delivery-material'
|
||||
import type { DesktopAccount } from './service'
|
||||
import { acquireDeliveryAttemptLock, saveDeliveryRevision, type DeliveryReference } from '@/lib/delivery-revisions'
|
||||
import { readXiaoyiDeliveryMetadata } from '@/lib/xiaoyi-delivery-material'
|
||||
import { acquireTaskMaterialUploadSessionLocks } from '@/lib/material-upload-cross-process-lock'
|
||||
|
||||
type FileInput = XiaoyiAssetSpec & {
|
||||
uploadId: string; fileName: string; fileSize: number; sha256: string
|
||||
@ -33,6 +36,36 @@ type Input = {
|
||||
}
|
||||
type DeliveryFile = Omit<FileInput, 'barcode' | 'barcodes' | 'width' | 'height'> & { group: string; barcodes: string[]; resolution?: string }
|
||||
type StoredFile = DeliveryFile & { storedPath: string }
|
||||
type PreviousDelivery = Receipt & { fingerprint: string; brandName: string; productName: string }
|
||||
|
||||
async function findDeliveryRequest(
|
||||
db: Pick<Prisma.TransactionClient, 'deliveryRevision'>,
|
||||
ownerId: string,
|
||||
request: { projectId: string; requestId: string; kind: XiaoyiDeliveryKind; fingerprint: string; legacyFingerprint: string | null },
|
||||
): Promise<Receipt | null> {
|
||||
const existing = await db.deliveryRevision.findUnique({
|
||||
where: { ownerId_requestId_kind: { ownerId, requestId: request.requestId, kind: request.kind } },
|
||||
select: { fingerprint: true, projectId: true, material: { select: { id: true, deletedAt: true } } },
|
||||
})
|
||||
if (!existing) return null
|
||||
desktopAssert(existing.projectId === request.projectId && [request.fingerprint, request.legacyFingerprint].includes(existing.fingerprint),
|
||||
'已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||||
return { requestId: request.requestId, materialId: existing.material.id,
|
||||
materialType: TYPES[request.kind], state: existing.material.deletedAt ? 'removed' : 'completed' }
|
||||
}
|
||||
|
||||
async function relatedDeliveryReferences(tx: Prisma.TransactionClient, ownerId: string, projectId: string, productModel: string) {
|
||||
const rows = await tx.$queryRaw<Array<DeliveryReference & { kind: XiaoyiDeliveryKind }>>`
|
||||
SELECT d.kind, d.material_id AS "materialId", m.current_revision_id AS "revisionId"
|
||||
FROM desktop_material_deliveries d
|
||||
JOIN materials m ON m.id = d.material_id AND m."userId" = d.owner_id
|
||||
WHERE d.owner_id = ${ownerId} AND d.project_id = ${projectId}
|
||||
AND UPPER(m."productModel") = UPPER(${productModel})
|
||||
AND m."deletedAt" IS NULL AND NOT m.is_incomplete_shell
|
||||
AND m.access_scope = 'general' AND NOT m.task_detail_private
|
||||
`
|
||||
return Object.fromEntries(rows.map(({ kind, ...ref }) => [kind, ref])) as Partial<Record<XiaoyiDeliveryKind, DeliveryReference>>
|
||||
}
|
||||
type Receipt = { requestId: string; materialId: string; materialType: string; state: 'completed' | 'removed' }
|
||||
const GROUPS = [...XIAOYI_DETAIL_ASSET_GROUPS, 'files'] as const
|
||||
const uuid = /^[a-zA-Z0-9_-]{1,80}$/
|
||||
@ -190,8 +223,10 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
const request = normalized(input)
|
||||
await reauthorize()
|
||||
await authorizeProject(ownerId, request.projectId)
|
||||
const previous = await prisma.$queryRawUnsafe<Array<Receipt & {fingerprint:string}>>(
|
||||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",
|
||||
const replay = await findDeliveryRequest(prisma, ownerId, request)
|
||||
if (replay) return replay
|
||||
const previous = await prisma.$queryRawUnsafe<PreviousDelivery[]>(
|
||||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",d.brand_name AS "brandName",d.product_name AS "productName",
|
||||
CASE WHEN m.id IS NULL OR m."deletedAt" IS NOT NULL THEN 'removed' ELSE 'completed' END AS state
|
||||
FROM desktop_material_deliveries d LEFT JOIN materials m ON m.id=d.material_id
|
||||
WHERE d.owner_id=$1 AND d.project_id=$2 AND d.kind=$3`,
|
||||
@ -243,37 +278,43 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
const projectFolder = path.join(uploadRoot, 'xiaoyi-deliveries', owner, request.projectId)
|
||||
const folder = path.join(projectFolder, attempt)
|
||||
await mkdir(projectFolder, { recursive: true })
|
||||
await mkdir(folder)
|
||||
const releaseAttempt = await acquireDeliveryAttemptLock(owner, request.projectId, attempt)
|
||||
|
||||
let result: Receipt
|
||||
let keepFolder = false
|
||||
try {
|
||||
await mkdir(folder)
|
||||
const files: StoredFile[] = []
|
||||
for (let index = 0; index < request.files.length; index++) {
|
||||
const file = request.files[index]
|
||||
const session = await getOwnedUploadSession(file.uploadId, ownerId)
|
||||
desktopAssert(session?.uploadPurpose === 'xiaoyi:' + request.projectId + ':' + request.requestId
|
||||
&& session.fileSize === file.fileSize && session.fileName === file.fileName, '交付文件不属于本次上传或已过期', 409, 'upload_mismatch')
|
||||
const tempDir = resolveStrictChildPath(uploadRoot, 'temp', file.uploadId)
|
||||
desktopAssert(tempDir, '上传会话路径无效', 409, 'upload_mismatch')
|
||||
const { existing } = await inspectUploadOutput(tempDir!, 'merged-file', 'merged-', file.fileName)
|
||||
const source = existing?.filePath
|
||||
desktopAssert(source, '上传文件不存在或尚未合并', 409, 'upload_incomplete')
|
||||
const stat = await lstat(source!)
|
||||
desktopAssert(stat.isFile() && !stat.isSymbolicLink() && stat.size === file.fileSize && await digestFile(source!) === file.sha256, '上传文件内容与交付清单不一致', 409, 'file_mismatch')
|
||||
const targetName = file.resolution ? file.fileName
|
||||
: String(index).padStart(4,'0') + '-' + file.sha256 + (getUploadStorageExtension(file.fileName) || '.bin')
|
||||
const folders = file.resolution ? ['sku', file.resolution, file.sha256] : []
|
||||
const parent = path.join(folder, ...folders)
|
||||
if (file.resolution) await mkdir(parent, { recursive: true })
|
||||
const target = path.join(parent, targetName)
|
||||
await copyFile(source!, target)
|
||||
const storedPath = buildStoredUploadPath('xiaoyi-deliveries', owner, request.projectId, attempt, ...folders, targetName)
|
||||
await syncStoredUploadFileToRemote(target, storedPath, file.fileSize)
|
||||
files.push({...file, storedPath})
|
||||
const releaseUpload = await acquireTaskMaterialUploadSessionLocks([file.uploadId])
|
||||
try {
|
||||
releaseUpload.assertHeld()
|
||||
const session = await getOwnedUploadSession(file.uploadId, ownerId)
|
||||
desktopAssert(session?.uploadPurpose === 'xiaoyi:' + request.projectId + ':' + request.requestId
|
||||
&& session.fileSize === file.fileSize && session.fileName === file.fileName, '交付文件不属于本次上传或已过期', 409, 'upload_mismatch')
|
||||
const tempDir = resolveStrictChildPath(uploadRoot, 'temp', file.uploadId)
|
||||
desktopAssert(tempDir, '上传会话路径无效', 409, 'upload_mismatch')
|
||||
const { existing } = await inspectUploadOutput(tempDir!, 'merged-file', 'merged-', file.fileName)
|
||||
const source = existing?.filePath
|
||||
desktopAssert(source, '上传文件不存在或尚未合并', 409, 'upload_incomplete')
|
||||
const stat = await lstat(source!)
|
||||
desktopAssert(stat.isFile() && !stat.isSymbolicLink() && stat.size === file.fileSize && await digestFile(source!) === file.sha256, '上传文件内容与交付清单不一致', 409, 'file_mismatch')
|
||||
const targetName = file.resolution ? file.fileName
|
||||
: String(index).padStart(4,'0') + '-' + file.sha256 + (getUploadStorageExtension(file.fileName) || '.bin')
|
||||
const folders = file.resolution ? ['sku', file.resolution, file.sha256] : []
|
||||
const parent = path.join(folder, ...folders)
|
||||
if (file.resolution) await mkdir(parent, { recursive: true })
|
||||
const target = path.join(parent, targetName)
|
||||
await copyFile(source!, target)
|
||||
const storedPath = buildStoredUploadPath('xiaoyi-deliveries', owner, request.projectId, attempt, ...folders, targetName)
|
||||
await syncStoredUploadFileToRemote(target, storedPath, file.fileSize)
|
||||
files.push({ ...file, storedPath })
|
||||
} finally {
|
||||
await releaseUpload()
|
||||
}
|
||||
}
|
||||
const author = await reauthorize()
|
||||
await ensureExternalNotificationTables()
|
||||
result = await prisma.$transaction(async tx => {
|
||||
await detailTransactionLock(tx, 'desktop-tasks:' + ownerId)
|
||||
await detailTransactionLock(tx, 'desktop:' + request.projectId)
|
||||
@ -287,8 +328,10 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
ownerId, request.projectId,
|
||||
)
|
||||
desktopAssert(!running.length, '项目仍有未完成的制作任务', 409, 'task_busy')
|
||||
const found = await tx.$queryRawUnsafe<Array<Receipt & {fingerprint:string}>>(
|
||||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",
|
||||
const replay = await findDeliveryRequest(tx, ownerId, request)
|
||||
if (replay) return replay
|
||||
const found = await tx.$queryRawUnsafe<PreviousDelivery[]>(
|
||||
`SELECT d.material_id AS "materialId",d.material_type AS "materialType",d.fingerprint,d.request_id AS "requestId",d.brand_name AS "brandName",d.product_name AS "productName",
|
||||
CASE WHEN m.id IS NULL OR m."deletedAt" IS NOT NULL THEN 'removed' ELSE 'completed' END AS state
|
||||
FROM desktop_material_deliveries d LEFT JOIN materials m ON m.id=d.material_id
|
||||
WHERE d.owner_id=$1 AND d.project_id=$2 AND d.kind=$3 FOR UPDATE OF d`,
|
||||
@ -298,6 +341,8 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
desktopAssert([request.fingerprint, request.legacyFingerprint].includes(found[0].fingerprint), '已有不同的交付记录,请保留原素材并联系管理员', 409, 'delivery_conflict')
|
||||
return {requestId:found[0].requestId,materialId:found[0].materialId,materialType:found[0].materialType,state:found[0].state}
|
||||
}
|
||||
desktopAssert(found[0]?.requestId === previous[0]?.requestId,
|
||||
'其他提交已更新交付,请重试本次提交', 409, 'delivery_conflict')
|
||||
const identifier = await projectDeliveryIdentifier(tx, ownerId, request.projectId, request.identifier)
|
||||
const materialType = TYPES[request.kind]
|
||||
const firstDetailIndex = files.findIndex(file => file.group === 'detail')
|
||||
@ -315,76 +360,106 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
...(codes.length && { barcodes: { create: codes.map(barcode => ({ barcode })) } }),
|
||||
}
|
||||
})
|
||||
if (found[0] && found[0].state !== 'removed') {
|
||||
const materialData = {
|
||||
authorName: author.name, productModel: identifier,
|
||||
categoryName: request.categoryName, productCategoryName: request.productCategoryName,
|
||||
materialType, taskStatus: 'completed', isFullSet: request.kind === 'detail', isAiGenerated: true,
|
||||
}
|
||||
const revisionIdentity = { ownerId, projectId: request.projectId, kind: request.kind,
|
||||
requestId: request.requestId, fingerprint: request.fingerprint }
|
||||
const related = await relatedDeliveryReferences(tx, ownerId, request.projectId, identifier)
|
||||
const revising = found[0] && found[0].state !== 'removed' ? found[0] : null
|
||||
let parentId: string | null = null
|
||||
let materialId: string
|
||||
if (revising) {
|
||||
materialId = revising.materialId
|
||||
const ownedMaterial = await tx.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT id FROM materials
|
||||
WHERE id = ${found[0].materialId} AND "userId" = ${ownerId} AND "deletedAt" IS NULL
|
||||
WHERE id = ${materialId} AND "userId" = ${ownerId} AND "deletedAt" IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
desktopAssert(ownedMaterial.length, '素材已交接或撤回,无法覆盖', 409, 'delivery_ownership_conflict')
|
||||
await tx.materialAsset.deleteMany({ where: { materialId: found[0].materialId } })
|
||||
await tx.material.update({
|
||||
where: { id: found[0].materialId },
|
||||
data: {
|
||||
authorName: author.name, productModel: identifier,
|
||||
categoryName: request.categoryName, productCategoryName: request.productCategoryName,
|
||||
materialType, taskStatus: 'completed', isFullSet: request.kind === 'detail', isAiGenerated: true,
|
||||
assets: { create: assets },
|
||||
},
|
||||
const current = await tx.material.findUniqueOrThrow({
|
||||
where: { id: materialId },
|
||||
select: { currentRevisionId: true, authorName: true, productModel: true, categoryName: true,
|
||||
productCategoryName: true, assets: { include: { barcodes: { select: { barcode: true } } } } },
|
||||
})
|
||||
parentId = current.currentRevisionId
|
||||
if (!parentId) {
|
||||
const lastLog = await tx.materialLog.findFirst({
|
||||
where: { materialId, action: XIAOYI_DELIVERY_LOG_ACTION },
|
||||
orderBy: [{ timestamp: 'desc' }, { id: 'desc' }], select: { changes: true },
|
||||
})
|
||||
const legacyEvent = await tx.xiaoyiAutoListingEvent.findUnique({ where: { materialId }, select: { id: true } })
|
||||
const baseline = await saveDeliveryRevision(tx, {
|
||||
...revisionIdentity, materialId, parentId: null,
|
||||
requestId: revising.requestId, fingerprint: revising.fingerprint,
|
||||
}, {
|
||||
authorName: current.authorName, productModel: current.productModel, categoryName: current.categoryName,
|
||||
productCategoryName: current.productCategoryName, brandName: revising.brandName, productName: revising.productName,
|
||||
metadata: readXiaoyiDeliveryMetadata(lastLog?.changes), related, legacy: true, ...(legacyEvent && { eventId: legacyEvent.id }),
|
||||
}, current.assets.map(({ id, assetType, fileUrl, fileName, fileSize, sortOrder, skuCode, barcodes }) => ({
|
||||
id, assetType, fileUrl, fileName, fileSize, sortOrder, skuCode, barcodes: barcodes.map(({ barcode }) => barcode),
|
||||
})))
|
||||
parentId = baseline.id
|
||||
}
|
||||
// Replace the compatibility projection. The immutable records keep the exact same asset IDs and files.
|
||||
await tx.materialAsset.deleteMany({ where: { materialId } })
|
||||
await tx.material.update({ where: { id: materialId }, data: { ...materialData, assets: { create: assets } } })
|
||||
} else {
|
||||
const material = await tx.material.create({
|
||||
data: { ...materialData, userId: ownerId, sceneName: '', previewUrl: '', assets: { create: assets } },
|
||||
select: { id: true },
|
||||
})
|
||||
materialId = material.id
|
||||
}
|
||||
const revision = await saveDeliveryRevision(tx, { ...revisionIdentity, materialId, parentId }, {
|
||||
authorName: author.name, productModel: identifier, categoryName: request.categoryName,
|
||||
productCategoryName: request.productCategoryName, brandName: request.brandName, productName: request.productName,
|
||||
metadata: deliveryMetadata, related,
|
||||
}, assets.map(({ barcodes, ...asset }, index) => ({
|
||||
...asset, sha256: files[index].sha256, barcodes: barcodes?.create.map(({ barcode }) => barcode) ?? [],
|
||||
})))
|
||||
await tx.material.update({ where: { id: materialId }, data: { currentRevisionId: revision.id } })
|
||||
if (revising) {
|
||||
await tx.$executeRawUnsafe(
|
||||
`UPDATE desktop_material_deliveries
|
||||
SET request_id=$1,fingerprint=$2,material_type=$3,brand_name=$4,product_name=$5,identifier_type=$6,
|
||||
listing_status=CASE
|
||||
WHEN listing_status->>'state' = 'listed' OR NULLIF(listing_status->>'listingId', '') IS NOT NULL
|
||||
THEN listing_status
|
||||
ELSE NULL
|
||||
END
|
||||
SET request_id=$1,fingerprint=$2,material_type=$3,brand_name=$4,product_name=$5,identifier_type=$6
|
||||
WHERE owner_id=$7 AND project_id=$8 AND kind=$9`,
|
||||
request.requestId,request.fingerprint,materialType,request.brandName,request.productName,'spu',
|
||||
ownerId,request.projectId,request.kind,
|
||||
)
|
||||
await tx.materialLog.create({ data: {
|
||||
materialId: found[0].materialId, userId: ownerId, action: XIAOYI_DELIVERY_LOG_ACTION,
|
||||
changes: JSON.stringify({ deliveryMetadata: { oldValue: null, newValue: deliveryMetadata } }),
|
||||
} })
|
||||
await queueXiaoyiAutoListingNotification(tx,{materialId:found[0].materialId,materialType,outcomeKind:request.kind,projectId:request.projectId,replaceExisting:true})
|
||||
keepFolder = true
|
||||
return {requestId:request.requestId,materialId:found[0].materialId,materialType,state:'completed' as const}
|
||||
}
|
||||
const material = await tx.material.create({data:{
|
||||
userId:ownerId, authorName:author.name, productModel:identifier,
|
||||
categoryName:request.categoryName, productCategoryName:request.productCategoryName, sceneName:'',
|
||||
materialType, previewUrl:'', taskStatus:'completed', isFullSet:request.kind === 'detail', isAiGenerated:true,
|
||||
assets: { create: assets },
|
||||
},select:{id:true}})
|
||||
if (found[0]) {
|
||||
} else if (found[0]) {
|
||||
await tx.$executeRawUnsafe(
|
||||
`UPDATE desktop_material_deliveries
|
||||
SET request_id=$1,fingerprint=$2,material_id=$3,material_type=$4,brand_name=$5,product_name=$6,identifier_type=$7,listing_status=NULL
|
||||
WHERE owner_id=$8 AND project_id=$9 AND kind=$10`,
|
||||
request.requestId,request.fingerprint,material.id,materialType,request.brandName,request.productName,'spu',
|
||||
request.requestId,request.fingerprint,materialId,materialType,request.brandName,request.productName,'spu',
|
||||
ownerId,request.projectId,request.kind,
|
||||
)
|
||||
} else {
|
||||
await tx.$executeRawUnsafe(
|
||||
'INSERT INTO desktop_material_deliveries (id,owner_id,project_id,request_id,kind,fingerprint,material_id,material_type,brand_name,product_name,identifier_type) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)',
|
||||
randomUUID(),ownerId,request.projectId,request.requestId,request.kind,request.fingerprint,material.id,materialType,request.brandName,request.productName,'spu',
|
||||
randomUUID(),ownerId,request.projectId,request.requestId,request.kind,request.fingerprint,materialId,materialType,request.brandName,request.productName,'spu',
|
||||
)
|
||||
}
|
||||
if (deliveryMetadata.storeCategoryName || Object.keys(deliveryMetadata.assetSpecs).length) {
|
||||
if (revising || deliveryMetadata.storeCategoryName || Object.keys(deliveryMetadata.assetSpecs).length) {
|
||||
await tx.materialLog.create({ data: {
|
||||
materialId: material.id, userId: ownerId, action: XIAOYI_DELIVERY_LOG_ACTION,
|
||||
materialId, userId: ownerId, action: XIAOYI_DELIVERY_LOG_ACTION,
|
||||
changes: JSON.stringify({ deliveryMetadata: { oldValue: null, newValue: deliveryMetadata } }),
|
||||
} })
|
||||
}
|
||||
await queueXiaoyiAutoListingNotification(tx,{materialId:material.id,materialType,outcomeKind:request.kind,projectId:request.projectId})
|
||||
await queueXiaoyiAutoListingNotification(tx,{materialId,materialType,outcomeKind:request.kind,projectId:request.projectId,revisionId:revision.id})
|
||||
keepFolder = true
|
||||
return {requestId:request.requestId,materialId:material.id,materialType,state:'completed' as const}
|
||||
return {requestId:request.requestId,materialId,materialType,state:'completed' as const}
|
||||
},{timeout:30000})
|
||||
} finally {
|
||||
// If the transaction reached COMMIT, the database may retain these files even when the connection fails.
|
||||
if (!keepFolder) await rm(folder, { recursive: true, force: true }).catch(() => undefined)
|
||||
try {
|
||||
if (!keepFolder && !isRemoteUploadSyncEnabled()) await rm(folder, { recursive: true, force: true })
|
||||
} finally {
|
||||
await releaseAttempt()
|
||||
}
|
||||
}
|
||||
invalidateMaterialFacetsCache()
|
||||
wakeXiaoyiAutoListingNotifications()
|
||||
|
||||
@ -28,6 +28,7 @@ export type DownloadType =
|
||||
export interface DownloadTokenPayload {
|
||||
materialId: string;
|
||||
downloadType: DownloadType;
|
||||
revisionId?: string;
|
||||
assetId?: string; // 单个资产下载时使用
|
||||
skuId?: string; // SKU 级资源下载时使用
|
||||
taskDetailFile?: TaskDetailFileReference;
|
||||
@ -78,6 +79,7 @@ export function verifyDownloadToken(token: string): DownloadTokenPayload | null
|
||||
materialId: decoded.materialId,
|
||||
downloadType: decoded.downloadType,
|
||||
assetId: decoded.assetId,
|
||||
...(decoded.revisionId && { revisionId: decoded.revisionId }),
|
||||
skuId: decoded.skuId,
|
||||
...(decoded.taskDetailFile && { taskDetailFile: decoded.taskDetailFile }),
|
||||
};
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
|
||||
import { randomUUID } from 'crypto'
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import {
|
||||
AutoListingCallbackError,
|
||||
normalizeAutoListingCallbackUrl,
|
||||
@ -86,11 +87,12 @@ export interface ExternalNotificationTargetInput {
|
||||
const TARGET_TABLE = 'external_notification_targets'
|
||||
const DELIVERY_TABLE = 'external_notification_deliveries'
|
||||
const XIAOYI_EVENT_TABLE = 'xiaoyi_auto_listing_events'
|
||||
const OLD_DELIVERY_UNIQUE_INDEX = 'external_notification_deliveries_target_event_material_key'
|
||||
const DELIVERY_DEDUPE_UNIQUE_INDEX = 'external_notification_deliveries_target_event_dedupe_key'
|
||||
const DELIVERY_MAX_ATTEMPTS = 5
|
||||
const DELIVERY_CONCURRENCY = 8
|
||||
const EXPANSION_LIMIT = 20
|
||||
const CIRCUIT_FAILURE_LIMIT = 3
|
||||
const CIRCUIT_COOLDOWN_MS = 5 * 60_000
|
||||
const RECOVERY_INTERVAL_MS = 60_000
|
||||
const STALE_PROCESSING_MS = 10 * 60 * 1000
|
||||
const RETRY_DELAYS_MS = [0, 60_000, 5 * 60_000, 15 * 60_000, 30 * 60_000, 60 * 60_000]
|
||||
export const SUPPORTED_AUTO_LISTING_EVENT_TYPES = [
|
||||
AUTO_LISTING_EVENT_TYPE,
|
||||
@ -100,9 +102,9 @@ export const SUPPORTED_AUTO_LISTING_EVENT_TYPES = [
|
||||
|
||||
let isTableInitialized = false
|
||||
let isWorkerStarted = false
|
||||
let isXiaoyiWorkerStarted = false
|
||||
let recoveryTimer: NodeJS.Timeout | null = null
|
||||
const deliveryTimers = new Map<string, NodeJS.Timeout>()
|
||||
let recoveryRunning = false
|
||||
let recoveryRequested = false
|
||||
const inFlightTargets = new Set<string>()
|
||||
|
||||
function asJson(value: unknown, fallback: string) {
|
||||
try {
|
||||
@ -248,10 +250,10 @@ async function enqueueNotificationDeliveries(options: {
|
||||
const inserted = insertedRows[0]
|
||||
if (inserted?.id) {
|
||||
createdIds.push(String(inserted.id))
|
||||
scheduleDeliveryProcessing(String(inserted.id), 0)
|
||||
}
|
||||
}
|
||||
|
||||
if (createdIds.length) setTimeout(wakeDeliveryWorker, 0).unref?.()
|
||||
return createdIds
|
||||
}
|
||||
|
||||
@ -631,237 +633,171 @@ export interface XiaoyiAutoListingEvent {
|
||||
materialType: string
|
||||
outcomeKind: XiaoyiOutcomeKind
|
||||
projectId: string
|
||||
replaceExisting?: boolean
|
||||
revisionId: string
|
||||
}
|
||||
|
||||
/** Called inside the same transaction that creates the material and its files. */
|
||||
export async function queueXiaoyiAutoListingNotification(
|
||||
tx: { $executeRawUnsafe: (sql: string, ...args: any[]) => Promise<unknown> },
|
||||
tx: Pick<Prisma.TransactionClient, 'xiaoyiAutoListingOutbox'>,
|
||||
event: XiaoyiAutoListingEvent,
|
||||
) {
|
||||
if (!event.materialId || !event.projectId || XIAOYI_DELIVERY_MATERIAL_TYPES[event.outcomeKind] !== event.materialType) {
|
||||
throw new Error('小壹交付通知参数无效')
|
||||
}
|
||||
const conflictClause = event.replaceExisting
|
||||
? `ON CONFLICT (material_id) DO UPDATE SET
|
||||
id = EXCLUDED.id,
|
||||
material_type = EXCLUDED.material_type,
|
||||
outcome_kind = EXCLUDED.outcome_kind,
|
||||
project_id = EXCLUDED.project_id,
|
||||
created_at = CURRENT_TIMESTAMP`
|
||||
: 'ON CONFLICT (material_id) DO NOTHING'
|
||||
await tx.$executeRawUnsafe(
|
||||
`INSERT INTO "${XIAOYI_EVENT_TABLE}" (id, material_id, material_type, outcome_kind, project_id)
|
||||
VALUES ($1, $2, $3, $4, $5) ${conflictClause}`,
|
||||
randomUUID(), event.materialId, event.materialType, event.outcomeKind, event.projectId,
|
||||
)
|
||||
await tx.xiaoyiAutoListingOutbox.create({ data: event })
|
||||
}
|
||||
|
||||
/** Call after commit so the worker never delivers uncommitted material. */
|
||||
export function wakeXiaoyiAutoListingNotifications() {
|
||||
ensureXiaoyiAutoListingWorkerStarted()
|
||||
void recoverDueDeliveries(20, XIAOYI_AUTO_LISTING_EVENT_TYPE)
|
||||
.catch((error) => console.error('[external-notification] 小壹通知入队失败:', error))
|
||||
ensureExternalNotificationWorkerStarted()
|
||||
wakeDeliveryWorker()
|
||||
}
|
||||
|
||||
export async function queueXiaoyiDeliveries(limit = 20) {
|
||||
const pending = await queryRaw<{
|
||||
eventId: string; materialId: string; materialType: string
|
||||
outcomeKind: XiaoyiOutcomeKind; projectId: string; createdAt: Date; targetId: string
|
||||
}>(`
|
||||
SELECT e.id AS "eventId",e.material_id AS "materialId",e.material_type AS "materialType",
|
||||
e.outcome_kind AS "outcomeKind",e.project_id AS "projectId",e.created_at AS "createdAt",
|
||||
t.id AS "targetId"
|
||||
type PendingEvent = {
|
||||
eventId: string; materialId: string; materialType: string; revisionId: string | null
|
||||
outcomeKind: XiaoyiOutcomeKind; projectId: string; createdAt: Date
|
||||
}
|
||||
|
||||
function makeXiaoyiDelivery(event: PendingEvent, targetId: string) {
|
||||
const eventType = XIAOYI_AUTO_LISTING_EVENT_TYPE
|
||||
const url = new URL('/api/external/product-assets', getPublicAppOrigin())
|
||||
url.searchParams.set('materialId', event.materialId)
|
||||
if (event.revisionId) url.searchParams.set('revisionId', event.revisionId)
|
||||
const payload = {
|
||||
eventId: event.eventId, eventType, materialId: event.materialId, materialType: event.materialType,
|
||||
outcomeKind: event.outcomeKind, projectId: event.projectId,
|
||||
...(event.revisionId && { revisionId: event.revisionId }),
|
||||
occurredAt: new Date(event.createdAt).toISOString(), pullUrl: url.href, statusUrl: url.href,
|
||||
}
|
||||
return {
|
||||
id: randomUUID(), targetId, eventType, materialId: event.materialId, materialType: event.materialType,
|
||||
dedupeKey: event.eventId, status: AUTO_LISTING_DELIVERY_STATUS.PENDING, payload,
|
||||
}
|
||||
}
|
||||
|
||||
export async function queueXiaoyiDeliveries(limit = EXPANSION_LIMIT) {
|
||||
const eventType = XIAOYI_AUTO_LISTING_EVENT_TYPE
|
||||
const expanded = await prisma.$transaction(async tx => {
|
||||
const events = await tx.$queryRaw<PendingEvent[]>`
|
||||
SELECT id AS "eventId", material_id AS "materialId", revision_id AS "revisionId", material_type AS "materialType",
|
||||
outcome_kind AS "outcomeKind", project_id AS "projectId", created_at AS "createdAt"
|
||||
FROM xiaoyi_auto_listing_outbox WHERE expanded_at IS NULL
|
||||
AND EXISTS (SELECT 1 FROM external_notification_targets WHERE is_active AND event_types ? ${eventType})
|
||||
ORDER BY created_at, id LIMIT ${limit} FOR UPDATE SKIP LOCKED
|
||||
`
|
||||
if (!events.length) return 0
|
||||
const targets = await tx.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT id FROM external_notification_targets WHERE is_active AND event_types ? ${eventType}
|
||||
`
|
||||
if (!targets.length) return 0
|
||||
const deliveries = events.flatMap(event => targets.map(({ id }) => makeXiaoyiDelivery(event, id)))
|
||||
if (deliveries.length) await tx.externalNotificationDelivery.createMany({ data: deliveries, skipDuplicates: true })
|
||||
await tx.xiaoyiAutoListingOutbox.updateMany({
|
||||
where: { id: { in: events.map(event => event.eventId) } }, data: { expandedAt: new Date() },
|
||||
})
|
||||
return events.length
|
||||
})
|
||||
|
||||
// Drain the legacy publisher's material-level rows with their original event IDs.
|
||||
const pending = await queryRaw<PendingEvent & { targetId: string }>(`
|
||||
SELECT e.id AS "eventId", e.material_id AS "materialId", r.id AS "revisionId", e.material_type AS "materialType",
|
||||
e.outcome_kind AS "outcomeKind", e.project_id AS "projectId", e.created_at AS "createdAt", t.id AS "targetId"
|
||||
FROM "${XIAOYI_EVENT_TABLE}" e
|
||||
JOIN "${TARGET_TABLE}" t ON t.is_active = TRUE AND t.event_types ? $1
|
||||
JOIN "${TARGET_TABLE}" t ON t.is_active AND t.event_types ? $1
|
||||
LEFT JOIN delivery_revisions r ON r.material_id=e.material_id AND r.snapshot->>'eventId'=e.id
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "${DELIVERY_TABLE}" d
|
||||
WHERE d.target_id=t.id AND d.event_type=$1
|
||||
AND (d.dedupe_key=e.id OR (d.dedupe_key=e.material_id AND d.created_at>=e.created_at))
|
||||
AND (d.dedupe_key=e.id OR (COALESCE(d.dedupe_key,d.material_id)=e.material_id AND d.created_at>=e.created_at))
|
||||
)
|
||||
ORDER BY e.created_at,t.created_at
|
||||
LIMIT $2
|
||||
`, XIAOYI_AUTO_LISTING_EVENT_TYPE, limit)
|
||||
for (const event of pending) {
|
||||
const materialUrl = `${getPublicAppOrigin()}/api/external/product-assets?materialId=${encodeURIComponent(event.materialId)}`
|
||||
const payload = {
|
||||
eventId: event.eventId,
|
||||
eventType: XIAOYI_AUTO_LISTING_EVENT_TYPE,
|
||||
materialId: event.materialId,
|
||||
materialType: event.materialType,
|
||||
outcomeKind: event.outcomeKind,
|
||||
projectId: event.projectId,
|
||||
occurredAt: new Date(event.createdAt).toISOString(),
|
||||
pullUrl: materialUrl,
|
||||
statusUrl: materialUrl,
|
||||
}
|
||||
const deliveryId = randomUUID()
|
||||
const inserted = await queryRaw<{ id: string }>(`
|
||||
INSERT INTO "${DELIVERY_TABLE}" (
|
||||
id,target_id,event_type,material_id,material_type,dedupe_key,status,payload,
|
||||
attempt_count,max_attempts,next_retry_at,created_at,updated_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$9,$6,$7::jsonb,0,$8,NOW(),NOW(),NOW())
|
||||
ON CONFLICT ("target_id","event_type","dedupe_key") DO NOTHING RETURNING id
|
||||
`, deliveryId, event.targetId, XIAOYI_AUTO_LISTING_EVENT_TYPE, event.materialId,
|
||||
event.materialType, AUTO_LISTING_DELIVERY_STATUS.PENDING, JSON.stringify(payload), DELIVERY_MAX_ATTEMPTS, event.eventId)
|
||||
if (inserted[0]) scheduleDeliveryProcessing(String(inserted[0].id), 0)
|
||||
}
|
||||
ORDER BY e.created_at, e.id, t.id LIMIT $2
|
||||
`, eventType, limit)
|
||||
if (pending.length) await prisma.externalNotificationDelivery.createMany({
|
||||
data: pending.map(event => makeXiaoyiDelivery(event, event.targetId)), skipDuplicates: true,
|
||||
})
|
||||
return Math.max(expanded, pending.length)
|
||||
}
|
||||
|
||||
export async function ensureExternalNotificationTables() {
|
||||
if (isTableInitialized) {
|
||||
return
|
||||
}
|
||||
|
||||
await executeRaw(`
|
||||
CREATE TABLE IF NOT EXISTS "${TARGET_TABLE}" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"name" TEXT NOT NULL,
|
||||
"callback_url" TEXT NOT NULL,
|
||||
"is_active" BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
"auth_type" TEXT NOT NULL DEFAULT 'none',
|
||||
"auth_config" JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
"event_types" JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
|
||||
await executeRaw(`
|
||||
CREATE TABLE IF NOT EXISTS "${DELIVERY_TABLE}" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"target_id" TEXT NOT NULL,
|
||||
"event_type" TEXT NOT NULL,
|
||||
"material_id" TEXT NOT NULL,
|
||||
"material_type" TEXT NOT NULL,
|
||||
"task_no" TEXT,
|
||||
"dedupe_key" TEXT,
|
||||
"status" TEXT NOT NULL,
|
||||
"payload" JSONB NOT NULL,
|
||||
"attempt_count" INT NOT NULL DEFAULT 0,
|
||||
"max_attempts" INT NOT NULL DEFAULT ${DELIVERY_MAX_ATTEMPTS},
|
||||
"next_retry_at" TIMESTAMP(3),
|
||||
"last_status_code" INT,
|
||||
"last_response_body" TEXT,
|
||||
"last_error" TEXT,
|
||||
"dispatched_at" TIMESTAMP(3),
|
||||
"completed_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
|
||||
await executeRaw(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "external_notification_targets_name_key"
|
||||
ON "${TARGET_TABLE}" ("name")
|
||||
`)
|
||||
await executeRaw(`
|
||||
ALTER TABLE "${DELIVERY_TABLE}"
|
||||
ADD COLUMN IF NOT EXISTS "dedupe_key" TEXT
|
||||
`)
|
||||
await executeRaw(`
|
||||
UPDATE "${DELIVERY_TABLE}"
|
||||
SET "dedupe_key" = COALESCE("dedupe_key", "material_id")
|
||||
WHERE "dedupe_key" IS NULL
|
||||
`)
|
||||
await executeRaw(`
|
||||
DROP INDEX IF EXISTS "${OLD_DELIVERY_UNIQUE_INDEX}"
|
||||
`)
|
||||
await executeRaw(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "${DELIVERY_DEDUPE_UNIQUE_INDEX}"
|
||||
ON "${DELIVERY_TABLE}" ("target_id", "event_type", "dedupe_key")
|
||||
`)
|
||||
await executeRaw(`
|
||||
CREATE INDEX IF NOT EXISTS "external_notification_deliveries_status_next_retry_idx"
|
||||
ON "${DELIVERY_TABLE}" ("status", "next_retry_at")
|
||||
`)
|
||||
|
||||
await executeRaw(`
|
||||
CREATE TABLE IF NOT EXISTS "${XIAOYI_EVENT_TABLE}" (
|
||||
"id" TEXT PRIMARY KEY,
|
||||
"material_id" TEXT NOT NULL UNIQUE,
|
||||
"material_type" TEXT NOT NULL,
|
||||
"outcome_kind" TEXT NOT NULL,
|
||||
"project_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`)
|
||||
|
||||
if (isTableInitialized) return
|
||||
const [row] = await prisma.$queryRaw<Array<{ ready: boolean }>>`
|
||||
SELECT to_regclass('external_notification_targets') IS NOT NULL
|
||||
AND to_regclass('xiaoyi_auto_listing_outbox') IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM pg_attribute
|
||||
WHERE attrelid = to_regclass('external_notification_deliveries')
|
||||
AND attname = 'lease_token' AND NOT attisdropped
|
||||
) AS ready
|
||||
`
|
||||
if (!row?.ready) throw new Error('外发任务表尚未完成数据库迁移')
|
||||
isTableInitialized = true
|
||||
}
|
||||
|
||||
async function recoverDueDeliveries(limit = 20, eventType?: string) {
|
||||
async function recoverDueDeliveries() {
|
||||
await ensureExternalNotificationTables()
|
||||
|
||||
await queueXiaoyiDeliveries(limit)
|
||||
|
||||
const rows = await queryRaw<{ id: string }>(
|
||||
`
|
||||
SELECT d.id
|
||||
FROM "${DELIVERY_TABLE}" d
|
||||
INNER JOIN "${TARGET_TABLE}" t ON t.id = d.target_id
|
||||
WHERE t.is_active = TRUE
|
||||
AND ($2::text IS NULL OR d.event_type = $2)
|
||||
const expanded = await queueXiaoyiDeliveries()
|
||||
const slots = DELIVERY_CONCURRENCY - inFlightTargets.size
|
||||
if (!slots) return expanded === EXPANSION_LIMIT
|
||||
const rows = await prisma.$queryRaw<Array<{ id: string; targetId: string }>>`
|
||||
SELECT due.id, t.id AS "targetId"
|
||||
FROM external_notification_targets t
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT d.id, d.created_at FROM external_notification_deliveries d
|
||||
WHERE d.target_id=t.id AND t.event_types ? d.event_type
|
||||
AND (
|
||||
(d.status IN ('pending', 'retrying') AND (d.next_retry_at IS NULL OR d.next_retry_at <= NOW()))
|
||||
OR
|
||||
(d.status = 'processing' AND d.updated_at < NOW() - INTERVAL '10 minutes')
|
||||
(d.status IN ('pending','retrying') AND COALESCE(d.next_retry_at,NOW()) <= NOW())
|
||||
OR (d.status='processing' AND COALESCE(d.lease_expires_at,d.updated_at + INTERVAL '10 minutes') <= NOW())
|
||||
)
|
||||
ORDER BY d.created_at ASC
|
||||
LIMIT $1
|
||||
`,
|
||||
limit,
|
||||
eventType ?? null,
|
||||
)
|
||||
ORDER BY d.created_at, d.id LIMIT 1
|
||||
) due
|
||||
WHERE t.is_active AND (t.circuit_open_until IS NULL OR t.circuit_open_until <= NOW())
|
||||
AND t.id <> ALL(${Array.from(inFlightTargets)}::text[])
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM external_notification_deliveries busy
|
||||
WHERE busy.target_id=t.id AND busy.status='processing'
|
||||
AND COALESCE(busy.lease_expires_at,busy.updated_at + INTERVAL '10 minutes') > NOW()
|
||||
)
|
||||
ORDER BY due.created_at, due.id LIMIT ${slots}
|
||||
`
|
||||
for (const { id, targetId } of rows) {
|
||||
inFlightTargets.add(targetId)
|
||||
void processExternalNotificationDelivery(id).then(result => {
|
||||
inFlightTargets.delete(targetId)
|
||||
if (result) wakeDeliveryWorker()
|
||||
}, error => {
|
||||
inFlightTargets.delete(targetId)
|
||||
console.error('[external-notification] 投递处理失败:', error)
|
||||
})
|
||||
}
|
||||
return expanded === EXPANSION_LIMIT
|
||||
}
|
||||
|
||||
rows.forEach((row) => scheduleDeliveryProcessing(String(row.id), 0))
|
||||
function wakeDeliveryWorker() {
|
||||
if (process.env.EXTERNAL_NOTIFICATION_WORKER_PAUSED === 'true') return
|
||||
recoveryRequested = true
|
||||
if (recoveryRunning) return
|
||||
recoveryRunning = true
|
||||
void (async () => {
|
||||
try {
|
||||
while (recoveryRequested) {
|
||||
recoveryRequested = false
|
||||
if (await recoverDueDeliveries()) recoveryRequested = true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[external-notification] 外发任务恢复失败:', error)
|
||||
} finally {
|
||||
recoveryRunning = false
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
export function ensureXiaoyiAutoListingWorkerStarted() {
|
||||
if (isXiaoyiWorkerStarted) return
|
||||
isXiaoyiWorkerStarted = true
|
||||
const recover = () => {
|
||||
void recoverDueDeliveries(20, XIAOYI_AUTO_LISTING_EVENT_TYPE)
|
||||
.catch((error) => console.error('[external-notification] 小壹通知恢复失败:', error))
|
||||
}
|
||||
const bootstrap = setTimeout(recover, 1000)
|
||||
bootstrap.unref?.()
|
||||
const interval = setInterval(recover, RECOVERY_INTERVAL_MS)
|
||||
interval.unref?.()
|
||||
ensureExternalNotificationWorkerStarted()
|
||||
}
|
||||
|
||||
function ensureExternalNotificationWorkerStarted() {
|
||||
if (isWorkerStarted) {
|
||||
return
|
||||
}
|
||||
|
||||
if (isWorkerStarted) return
|
||||
isWorkerStarted = true
|
||||
|
||||
const bootstrapTimer = setTimeout(() => {
|
||||
void recoverDueDeliveries().catch((error) => console.error('[external-notification] 恢复失败:', error))
|
||||
}, 1000)
|
||||
bootstrapTimer.unref?.()
|
||||
|
||||
recoveryTimer = setInterval(() => {
|
||||
void recoverDueDeliveries().catch((error) => console.error('[external-notification] 恢复失败:', error))
|
||||
}, RECOVERY_INTERVAL_MS)
|
||||
recoveryTimer.unref?.()
|
||||
}
|
||||
|
||||
function scheduleDeliveryProcessing(deliveryId: string, delayMs: number) {
|
||||
const existingTimer = deliveryTimers.get(deliveryId)
|
||||
if (existingTimer) {
|
||||
clearTimeout(existingTimer)
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
deliveryTimers.delete(deliveryId)
|
||||
void processExternalNotificationDelivery(deliveryId).catch((error) => {
|
||||
console.error('[external-notification] 投递结果保存失败:', error)
|
||||
})
|
||||
}, Math.max(0, delayMs))
|
||||
timer.unref?.()
|
||||
deliveryTimers.set(deliveryId, timer)
|
||||
setTimeout(wakeDeliveryWorker, 1000).unref?.()
|
||||
setInterval(wakeDeliveryWorker, RECOVERY_INTERVAL_MS).unref?.()
|
||||
}
|
||||
|
||||
function buildNotificationHeaders(target: ExternalNotificationTarget) {
|
||||
@ -1147,210 +1083,121 @@ export async function queueTaskDetailBarcodeImagesUpdatedNotification(
|
||||
})
|
||||
}
|
||||
|
||||
export async function retryExternalNotificationDelivery(deliveryId: string) {
|
||||
export async function retryExternalNotificationDelivery(deliveryId: string, actorId: string) {
|
||||
await ensureExternalNotificationTables()
|
||||
ensureExternalNotificationWorkerStarted()
|
||||
|
||||
await executeRaw(
|
||||
const result = await prisma.$transaction(async tx => {
|
||||
const [target] = await tx.$queryRaw<Array<{ enabled: boolean }>>`
|
||||
SELECT (t.is_active AND t.event_types ? d.event_type) AS enabled
|
||||
FROM external_notification_deliveries d JOIN external_notification_targets t ON t.id=d.target_id
|
||||
WHERE d.id=${deliveryId} FOR NO KEY UPDATE OF t
|
||||
`
|
||||
UPDATE "${DELIVERY_TABLE}"
|
||||
SET
|
||||
status = $2,
|
||||
next_retry_at = NOW(),
|
||||
completed_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
deliveryId,
|
||||
AUTO_LISTING_DELIVERY_STATUS.PENDING,
|
||||
)
|
||||
|
||||
scheduleDeliveryProcessing(deliveryId, 0)
|
||||
}
|
||||
|
||||
export async function processExternalNotificationDelivery(
|
||||
deliveryId: string,
|
||||
options?: { force?: boolean },
|
||||
) {
|
||||
await ensureExternalNotificationTables()
|
||||
|
||||
const claimed = await prisma.$transaction(async (tx: any) => {
|
||||
await tx.$executeRawUnsafe('SELECT pg_advisory_xact_lock(hashtext($1))', deliveryId)
|
||||
|
||||
const rows = await tx.$queryRawUnsafe(
|
||||
`
|
||||
SELECT
|
||||
d.id,
|
||||
d.status,
|
||||
d.payload,
|
||||
d.attempt_count AS "attemptCount",
|
||||
d.max_attempts AS "maxAttempts",
|
||||
d.updated_at AS "updatedAt",
|
||||
t.id AS "targetId",
|
||||
t.name,
|
||||
t.callback_url AS "callbackUrl",
|
||||
t.is_active AS "isActive",
|
||||
t.auth_type AS "authType",
|
||||
t.auth_config AS "authConfig",
|
||||
t.event_types AS "eventTypes",
|
||||
t.created_at AS "createdAt",
|
||||
t.updated_at AS "targetUpdatedAt"
|
||||
FROM "${DELIVERY_TABLE}" d
|
||||
INNER JOIN "${TARGET_TABLE}" t ON t.id = d.target_id
|
||||
WHERE d.id = $1
|
||||
LIMIT 1
|
||||
`,
|
||||
deliveryId,
|
||||
)
|
||||
|
||||
const row = rows[0]
|
||||
if (!row || !Boolean(row.isActive)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const updatedAt = new Date(String(row.updatedAt || ''))
|
||||
const isStaleProcessing =
|
||||
row.status === AUTO_LISTING_DELIVERY_STATUS.PROCESSING &&
|
||||
!Number.isNaN(updatedAt.getTime()) &&
|
||||
Date.now() - updatedAt.getTime() > STALE_PROCESSING_MS
|
||||
|
||||
if (
|
||||
!options?.force &&
|
||||
row.status === AUTO_LISTING_DELIVERY_STATUS.PROCESSING &&
|
||||
!isStaleProcessing
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (
|
||||
!options?.force &&
|
||||
row.status !== AUTO_LISTING_DELIVERY_STATUS.PENDING &&
|
||||
row.status !== AUTO_LISTING_DELIVERY_STATUS.RETRYING &&
|
||||
!isStaleProcessing
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
await tx.$executeRawUnsafe(
|
||||
`
|
||||
UPDATE "${DELIVERY_TABLE}"
|
||||
SET
|
||||
status = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
deliveryId,
|
||||
AUTO_LISTING_DELIVERY_STATUS.PROCESSING,
|
||||
)
|
||||
|
||||
return {
|
||||
attemptCount: Number(row.attemptCount || 0),
|
||||
maxAttempts: Number(row.maxAttempts || DELIVERY_MAX_ATTEMPTS),
|
||||
payload: row.payload,
|
||||
target: normalizeTargetRow({
|
||||
id: row.targetId,
|
||||
name: row.name,
|
||||
callbackUrl: row.callbackUrl,
|
||||
isActive: row.isActive,
|
||||
authType: row.authType,
|
||||
authConfig: row.authConfig,
|
||||
eventTypes: row.eventTypes,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.targetUpdatedAt,
|
||||
}),
|
||||
}
|
||||
if (!target) return 'missing'
|
||||
if (!target.enabled) return 'unavailable'
|
||||
const updated = await tx.$executeRaw`
|
||||
UPDATE external_notification_deliveries
|
||||
SET status='pending', attempt_count=0, lease_token=NULL, lease_expires_at=NULL,
|
||||
next_retry_at=NOW(), completed_at=NULL, updated_at=NOW(),
|
||||
replay_count=replay_count+1, replayed_by=${actorId}, replayed_at=NOW()
|
||||
WHERE id=${deliveryId} AND status='exhausted'
|
||||
`
|
||||
return updated ? 'queued' : 'conflict'
|
||||
})
|
||||
|
||||
if (!claimed) {
|
||||
return null
|
||||
}
|
||||
|
||||
let responseStatus: number | null = null
|
||||
let requestError: string | null = null
|
||||
|
||||
try {
|
||||
const materialId = (claimed.payload as { materialId?: string } | null)?.materialId
|
||||
if (materialId && !(await prisma.material.findFirst({
|
||||
where: { id: materialId, deletedAt: null, ...EXTERNAL_MATERIAL_SCOPE_WHERE },
|
||||
select: { id: true },
|
||||
}))) {
|
||||
await executeRaw(
|
||||
`UPDATE "${DELIVERY_TABLE}" SET status = $2, last_error = $3, next_retry_at = NULL, completed_at = NOW(), updated_at = NOW() WHERE id = $1`,
|
||||
deliveryId, AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED, '素材已不可对外提供',
|
||||
)
|
||||
return { success: false, status: AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED }
|
||||
}
|
||||
responseStatus = await postAutoListingCallback(
|
||||
claimed.target.callbackUrl,
|
||||
buildNotificationHeaders(claimed.target),
|
||||
claimed.payload,
|
||||
)
|
||||
requestError = summarizeAutoListingCallbackError(null, responseStatus)
|
||||
|
||||
if (!requestError) {
|
||||
await executeRaw(
|
||||
`
|
||||
UPDATE "${DELIVERY_TABLE}"
|
||||
SET
|
||||
status = $2,
|
||||
attempt_count = attempt_count + 1,
|
||||
last_status_code = $3,
|
||||
last_response_body = $4,
|
||||
last_error = NULL,
|
||||
next_retry_at = NULL,
|
||||
dispatched_at = COALESCE(dispatched_at, NOW()),
|
||||
completed_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
deliveryId,
|
||||
AUTO_LISTING_DELIVERY_STATUS.SUCCEEDED,
|
||||
responseStatus,
|
||||
null,
|
||||
)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: AUTO_LISTING_DELIVERY_STATUS.SUCCEEDED,
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
requestError = error instanceof AutoListingCallbackError ? error.message : '通知请求失败'
|
||||
}
|
||||
|
||||
const nextAttempt = claimed.attemptCount + 1
|
||||
const isExhausted = nextAttempt >= claimed.maxAttempts
|
||||
const retryDelayMs = RETRY_DELAYS_MS[Math.min(nextAttempt, RETRY_DELAYS_MS.length - 1)]
|
||||
|
||||
await executeRaw(
|
||||
`
|
||||
UPDATE "${DELIVERY_TABLE}"
|
||||
SET
|
||||
status = $2,
|
||||
attempt_count = attempt_count + 1,
|
||||
last_status_code = $3,
|
||||
last_response_body = $4,
|
||||
last_error = $5,
|
||||
next_retry_at = CASE WHEN $6::bigint IS NULL THEN NULL ELSE NOW() + ($6::bigint * INTERVAL '1 millisecond') END,
|
||||
completed_at = CASE WHEN $7::boolean THEN NOW() ELSE NULL END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
deliveryId,
|
||||
isExhausted ? AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED : AUTO_LISTING_DELIVERY_STATUS.RETRYING,
|
||||
responseStatus,
|
||||
null,
|
||||
requestError,
|
||||
isExhausted ? null : retryDelayMs,
|
||||
isExhausted,
|
||||
)
|
||||
|
||||
if (!isExhausted) {
|
||||
scheduleDeliveryProcessing(deliveryId, retryDelayMs)
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: isExhausted ? AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED : AUTO_LISTING_DELIVERY_STATUS.RETRYING,
|
||||
if (result === 'queued') {
|
||||
ensureExternalNotificationWorkerStarted()
|
||||
setTimeout(wakeDeliveryWorker, 0).unref?.()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export async function processExternalNotificationDelivery(deliveryId: string) {
|
||||
await ensureExternalNotificationTables()
|
||||
const leaseToken = randomUUID()
|
||||
const claimed = await prisma.$transaction(async tx => {
|
||||
const [target] = await tx.$queryRaw<Array<{
|
||||
id: string; name: string; callbackUrl: string; authType: string; authConfig: Prisma.JsonValue;
|
||||
eventTypes: Prisma.JsonValue; createdAt: Date; updatedAt: Date
|
||||
}>>`
|
||||
SELECT t.id, t.name, t.callback_url AS "callbackUrl", t.auth_type AS "authType",
|
||||
t.auth_config AS "authConfig", t.event_types AS "eventTypes",
|
||||
t.created_at AS "createdAt", t.updated_at AS "updatedAt"
|
||||
FROM external_notification_deliveries d JOIN external_notification_targets t ON t.id=d.target_id
|
||||
WHERE d.id=${deliveryId} AND t.is_active AND t.event_types ? d.event_type
|
||||
AND (t.circuit_open_until IS NULL OR t.circuit_open_until <= NOW())
|
||||
FOR NO KEY UPDATE OF t SKIP LOCKED
|
||||
`
|
||||
if (!target) return null
|
||||
|
||||
const [job] = await tx.$queryRaw<Array<{
|
||||
materialId: string; payload: Prisma.JsonValue; attemptCount: number; maxAttempts: number; expired: boolean
|
||||
}>>`
|
||||
UPDATE external_notification_deliveries d
|
||||
SET status=CASE WHEN d.attempt_count >= d.max_attempts THEN 'exhausted' ELSE 'processing' END,
|
||||
last_error=CASE WHEN d.attempt_count >= d.max_attempts THEN '投递租约到期,重试次数已用尽' ELSE d.last_error END,
|
||||
completed_at=CASE WHEN d.attempt_count >= d.max_attempts THEN NOW() ELSE NULL END,
|
||||
attempt_count=LEAST(d.attempt_count+1,d.max_attempts),
|
||||
lease_token=CASE WHEN d.attempt_count < d.max_attempts THEN ${leaseToken} ELSE NULL END,
|
||||
lease_expires_at=CASE WHEN d.attempt_count < d.max_attempts THEN NOW() + INTERVAL '10 minutes' ELSE NULL END,
|
||||
next_retry_at=NULL, updated_at=NOW()
|
||||
WHERE d.id=${deliveryId}
|
||||
AND (
|
||||
(d.status IN ('pending','retrying') AND COALESCE(d.next_retry_at,NOW()) <= NOW())
|
||||
OR (d.status='processing' AND COALESCE(d.lease_expires_at,d.updated_at + INTERVAL '10 minutes') <= NOW())
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM external_notification_deliveries busy
|
||||
WHERE busy.target_id=d.target_id AND busy.id<>d.id AND busy.status='processing'
|
||||
AND COALESCE(busy.lease_expires_at,busy.updated_at + INTERVAL '10 minutes') > NOW()
|
||||
)
|
||||
RETURNING material_id AS "materialId", payload, attempt_count AS "attemptCount",
|
||||
max_attempts AS "maxAttempts", status='exhausted' AS expired
|
||||
`
|
||||
return job ? { ...job, target: normalizeTargetRow({ ...target, isActive: true }) } : null
|
||||
})
|
||||
if (!claimed) return null
|
||||
if (claimed.expired) return { success: false, status: AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED }
|
||||
|
||||
const material = await prisma.material.findFirst({
|
||||
where: { id: claimed.materialId, deletedAt: null, ...EXTERNAL_MATERIAL_SCOPE_WHERE }, select: { id: true },
|
||||
})
|
||||
let responseStatus: number | null = null
|
||||
let requestError: string | null = material ? null : '素材已不可对外提供'
|
||||
if (material) {
|
||||
try {
|
||||
responseStatus = await postAutoListingCallback(
|
||||
claimed.target.callbackUrl, buildNotificationHeaders(claimed.target), claimed.payload,
|
||||
)
|
||||
requestError = summarizeAutoListingCallbackError(null, responseStatus)
|
||||
} catch (error) {
|
||||
requestError = error instanceof AutoListingCallbackError ? error.message : '通知请求失败'
|
||||
}
|
||||
}
|
||||
|
||||
const status = !requestError ? AUTO_LISTING_DELIVERY_STATUS.SUCCEEDED
|
||||
: !material || claimed.attemptCount >= claimed.maxAttempts ? AUTO_LISTING_DELIVERY_STATUS.EXHAUSTED
|
||||
: AUTO_LISTING_DELIVERY_STATUS.RETRYING
|
||||
const baseDelay = RETRY_DELAYS_MS[Math.min(claimed.attemptCount, RETRY_DELAYS_MS.length - 1)]
|
||||
const delayMs = status === 'retrying' ? baseDelay + Math.floor(Math.random() * baseDelay / 5) : null
|
||||
const applied = await prisma.$transaction(async tx => {
|
||||
await tx.$queryRaw`SELECT id FROM external_notification_targets WHERE id=${claimed.target.id} FOR NO KEY UPDATE`
|
||||
const changed = await tx.$executeRaw`
|
||||
UPDATE external_notification_deliveries
|
||||
SET status=${status}, lease_token=NULL, lease_expires_at=NULL, last_status_code=${responseStatus},
|
||||
last_response_body=NULL, last_error=${requestError},
|
||||
next_retry_at=NOW() + (${delayMs}::int * INTERVAL '1 millisecond'),
|
||||
dispatched_at=CASE WHEN ${status}='succeeded' THEN COALESCE(dispatched_at,NOW()) ELSE dispatched_at END,
|
||||
completed_at=CASE WHEN ${status}<>'retrying' THEN NOW() ELSE NULL END, updated_at=NOW()
|
||||
WHERE id=${deliveryId} AND status='processing' AND lease_token=${leaseToken} AND lease_expires_at > NOW()
|
||||
`
|
||||
if (changed && material) {
|
||||
await tx.$executeRaw`
|
||||
UPDATE external_notification_targets
|
||||
SET consecutive_failures=CASE WHEN ${requestError}::text IS NULL THEN 0 ELSE consecutive_failures+1 END,
|
||||
circuit_open_until=CASE WHEN ${requestError}::text IS NOT NULL AND consecutive_failures+1 >= ${CIRCUIT_FAILURE_LIMIT}
|
||||
THEN NOW() + (${CIRCUIT_COOLDOWN_MS}::int * INTERVAL '1 millisecond') ELSE NULL END
|
||||
WHERE id=${claimed.target.id}
|
||||
`
|
||||
}
|
||||
return changed > 0
|
||||
})
|
||||
return applied ? { success: status === 'succeeded', status } : null
|
||||
}
|
||||
|
||||
88
lib/external-zip-stream.ts
Normal file
88
lib/external-zip-stream.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import { nodeReadableToWebStream } from '@/lib/node-readable-stream'
|
||||
import archiver from 'archiver'
|
||||
import { Readable } from 'node:stream'
|
||||
import { createArchiveDownloadStream } from '@/lib/archive-download-stream'
|
||||
|
||||
export const MAX_ACTIVE_EXTERNAL_ZIPS = 4
|
||||
export const MAX_EXTERNAL_ZIP_ENTRIES = 1000
|
||||
let activeArchives = 0
|
||||
|
||||
export class ExternalZipBusyError extends Error {}
|
||||
export class ExternalZipTooLargeError extends Error {}
|
||||
export class ExternalZipSourceError extends Error {}
|
||||
|
||||
type ZipEntry = { name: string; open: (signal: AbortSignal) => Promise<Readable> }
|
||||
|
||||
export async function streamExternalZip(entries: ZipEntry[], requestSignal?: AbortSignal, prime = false) {
|
||||
if (entries.length > MAX_EXTERNAL_ZIP_ENTRIES) throw new ExternalZipTooLargeError()
|
||||
if (activeArchives >= MAX_ACTIVE_EXTERNAL_ZIPS) throw new ExternalZipBusyError()
|
||||
const archive = archiver('zip', { zlib: { level: 5 } })
|
||||
const download = createArchiveDownloadStream(archive)
|
||||
const controller = new AbortController()
|
||||
const signal = requestSignal ? AbortSignal.any([requestSignal, controller.signal]) : controller.signal
|
||||
activeArchives++
|
||||
let released = false
|
||||
const release = () => {
|
||||
if (released) return
|
||||
released = true
|
||||
activeArchives--
|
||||
controller.abort()
|
||||
requestSignal?.removeEventListener('abort', cancel)
|
||||
}
|
||||
const cancel = () => download.abort()
|
||||
archive.once('end', release)
|
||||
archive.once('close', release)
|
||||
requestSignal?.addEventListener('abort', cancel, { once: true })
|
||||
const stream = nodeReadableToWebStream(archive, { onCancel: cancel })
|
||||
const remaining = entries[Symbol.iterator]()
|
||||
let initial: { entry: ZipEntry; file: Readable } | undefined
|
||||
const appendNext = () => {
|
||||
if (signal.aborted || archive.destroyed) return
|
||||
const first = initial
|
||||
initial = undefined
|
||||
const next = first ? { done: false as const, value: first.entry } : remaining.next()
|
||||
if (next.done) {
|
||||
void archive.finalize().catch(error => archive.destroy(error))
|
||||
return
|
||||
}
|
||||
const entry = next.value
|
||||
const source = Readable.from((async function* () {
|
||||
signal.throwIfAborted()
|
||||
const file = first?.file ?? await entry.open(signal)
|
||||
try {
|
||||
signal.throwIfAborted()
|
||||
yield* file
|
||||
} finally {
|
||||
file.destroy()
|
||||
}
|
||||
})(), { objectMode: false, highWaterMark: 64 * 1024 })
|
||||
// Archiver starts buffering appended streams immediately. Append the next entry only after completion.
|
||||
archive.append(download.trackSource(source), { name: entry.name, date: new Date('1980-01-01T00:00:00Z') })
|
||||
}
|
||||
archive.on('entry', appendNext)
|
||||
archive.on('warning', error => archive.destroy(error))
|
||||
archive.once('error', cancel)
|
||||
try {
|
||||
signal.throwIfAborted()
|
||||
if (prime) {
|
||||
const first = remaining.next()
|
||||
if (!first.done) {
|
||||
try {
|
||||
const file = await first.value.open(signal)
|
||||
if (signal.aborted) file.destroy()
|
||||
signal.throwIfAborted()
|
||||
initial = { entry: first.value, file: download.trackSource(file) }
|
||||
} catch (error) {
|
||||
signal.throwIfAborted()
|
||||
throw new ExternalZipSourceError('ZIP 资源不可用', { cause: error })
|
||||
}
|
||||
}
|
||||
}
|
||||
appendNext()
|
||||
return stream
|
||||
} catch (error) {
|
||||
cancel()
|
||||
release()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@ -241,7 +241,7 @@ export async function hasActiveFileReferences(
|
||||
assetWhere.NOT = { id: { in: options.excludeAssetIds } };
|
||||
}
|
||||
const assetRefs = await prisma.materialAsset.count({ where: assetWhere });
|
||||
if (assetRefs > 0) {
|
||||
if (assetRefs > 0 || await prisma.revisionAsset.count({ where: { fileUrl: { in: variants } } })) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@ -153,6 +153,7 @@ export async function findPurgeFileReferences(db: Prisma.TransactionClient, file
|
||||
db.material.findMany({ select: { previewUrl: true, zipFilePath: true, displayImages: true,
|
||||
videoSourceUrl: true, videoPreview540Url: true, videoPreviewClipUrl: true, videoCoverUrl: true } }),
|
||||
db.materialAsset.findMany({ select: { fileUrl: true } }),
|
||||
db.revisionAsset.findMany({ select: { fileUrl: true } }),
|
||||
db.materialSku.findMany({ select: { filePath: true, previewUrl: true } }),
|
||||
db.brandKnowledge.findMany({ select: { filePath: true, previewImagePath: true, previewImageSlices: true } }),
|
||||
db.systemSettings.findMany({ select: { headerLogoUrl: true, loginLogoUrl: true } }),
|
||||
|
||||
@ -49,6 +49,8 @@ export async function findIndexedPurgeReferenceSources(db: Prisma.TransactionCli
|
||||
UNION ALL
|
||||
SELECT ARRAY[file_url], true FROM material_assets WHERE purge_reference_keys(ARRAY[file_url], true) && lookup.keys
|
||||
UNION ALL
|
||||
SELECT ARRAY[file_url], false FROM revision_assets WHERE purge_reference_keys(ARRAY[file_url], false) && lookup.keys
|
||||
UNION ALL
|
||||
SELECT ARRAY[file_path, preview_url], false FROM material_skus WHERE purge_reference_keys(ARRAY[file_path, preview_url], false) && lookup.keys
|
||||
UNION ALL
|
||||
SELECT ARRAY[file_path, preview_image_path] || preview_image_slices, false FROM brand_knowledge WHERE purge_reference_keys(ARRAY[file_path, preview_image_path] || preview_image_slices, false) && lookup.keys
|
||||
|
||||
@ -362,13 +362,13 @@ export async function deleteFromS3(fileUrl: string): Promise<void> {
|
||||
/**
|
||||
* 从 S3 获取对象流
|
||||
*/
|
||||
export async function getS3ObjectStream(key: string): Promise<{ body: Readable; contentLength?: number }> {
|
||||
export async function getS3ObjectStream(key: string, abortSignal?: AbortSignal): Promise<{ body: Readable; contentLength?: number }> {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: process.env.S3_BUCKET!,
|
||||
Key: key,
|
||||
})
|
||||
|
||||
const response = await s3Client.send(command)
|
||||
const response = await s3Client.send(command, { abortSignal })
|
||||
return {
|
||||
body: response.Body as Readable,
|
||||
contentLength: response.ContentLength,
|
||||
|
||||
@ -1,3 +1,6 @@
|
||||
import { isDesktopDeliveryPurpose } from './upload-auth'
|
||||
import { identifyPurgeFile, findPurgeFileReferences } from './material-purge-files'
|
||||
import { prisma } from './prisma'
|
||||
import { PERFORMANCE_CASE_UPLOAD_PURPOSE } from './performance-survey-attachment-contract'
|
||||
/**
|
||||
* Material upload 临时目录的统一安全清理协议。
|
||||
@ -24,11 +27,12 @@ import {
|
||||
import { MaterialUploadRequestError } from './material-upload-request-guard'
|
||||
import { resolveStrictChildPath } from './path-security'
|
||||
import { normalizeUploadFileName } from './upload-file-name'
|
||||
import { getUploadRootDir, inspectUploadOutput } from './upload-paths'
|
||||
import { buildStoredUploadPath, getUploadRootDir, inspectUploadOutput } from './upload-paths'
|
||||
import { uploadSessions, type UploadSession } from './upload-sessions'
|
||||
|
||||
const MAX_AGE_MS = 8 * 60 * 60 * 1000
|
||||
const ABANDONED_BRAND_KNOWLEDGE_RETENTION_MS = 24 * 60 * 60 * 1000
|
||||
export const XIAOYI_GC_GRACE_MS = 7 * 24 * 60 * 60 * 1000
|
||||
const CLEANUP_INTERVAL_MS = 60 * 60 * 1000
|
||||
const SAFE_UPLOAD_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/
|
||||
const REDIS_SESSION_KEY_PREFIX = 'upload:session:'
|
||||
@ -208,6 +212,7 @@ export async function runCleanup(): Promise<{
|
||||
}
|
||||
|
||||
const uploadPurpose = await readUploadPurposeCandidate(dirPath)
|
||||
if (uploadPurpose && isDesktopDeliveryPurpose(uploadPurpose)) continue
|
||||
const cleanup = uploadPurpose === 'brand-knowledge'
|
||||
? await cleanupAbandonedBrandKnowledgeUploadSession(uploadId)
|
||||
: await safelyCleanupMaterialUploadSession({
|
||||
@ -289,6 +294,45 @@ async function cleanupAbandonedBrandKnowledgeUploadSession(
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanExpiredXiaoyiUpload(uploadId: string, dryRun = true) {
|
||||
if (!SAFE_UPLOAD_ID_PATTERN.test(uploadId)) return 'skipped'
|
||||
const directory = resolveStrictChildPath(getTempDir(), uploadId)
|
||||
if (!directory) return 'skipped'
|
||||
const purpose = await readUploadPurposeCandidate(directory)
|
||||
if (!purpose || !isDesktopDeliveryPurpose(purpose)) return 'skipped'
|
||||
const releaseSession = await acquireTaskMaterialUploadSessionLocks([uploadId], { timeoutMs: 500 })
|
||||
try {
|
||||
const releaseStorage = await acquireMaterialUploadStorageLock('exclusive')
|
||||
try {
|
||||
const evidence = await readCleanupEvidence(uploadId)
|
||||
if (!evidence.directory.exists || !evidence.uploadPurpose || !isDesktopDeliveryPurpose(evidence.uploadPurpose)
|
||||
|| evidence.activeSession || evidence.ageMs === null || evidence.ageMs < XIAOYI_GC_GRACE_MS
|
||||
|| !evidence.directory.mtimeMs || Date.now() - evidence.directory.mtimeMs < XIAOYI_GC_GRACE_MS
|
||||
|| evidence.assembledFilePath) return 'skipped'
|
||||
const seal = await readUploadSessionSeal(uploadId)
|
||||
const terminalAt = seal?.completedAt ?? seal?.cancelledAt ?? seal?.createdAt
|
||||
if (terminalAt && Date.now() - terminalAt < XIAOYI_GC_GRACE_MS) return 'skipped'
|
||||
const files = evidence.directory.files.flatMap(file => {
|
||||
const ref = identifyPurgeFile(buildStoredUploadPath('temp', uploadId, file.name))
|
||||
return ref ? [{ ...ref, outcome: 'pending' as const }] : []
|
||||
})
|
||||
if ((await findPurgeFileReferences(prisma, files)).size) return 'retained'
|
||||
if (dryRun) return 'candidate'
|
||||
releaseSession.assertHeld()
|
||||
releaseStorage.assertHeld()
|
||||
// Completed seals already block chunks. Other sessions get a tombstone before their bytes are removed.
|
||||
if (evidence.sealState !== 'completed') await cancelUploadSessionSeal(uploadId)
|
||||
await deleteSessionStateFailClosed(uploadId)
|
||||
await rm(evidence.directory.path, { recursive: true, force: true })
|
||||
return 'deleted'
|
||||
} finally {
|
||||
await releaseStorage()
|
||||
}
|
||||
} finally {
|
||||
await releaseSession()
|
||||
}
|
||||
}
|
||||
|
||||
export function startCleanupScheduler(): void {
|
||||
if (cleanupTimer) {
|
||||
console.log('[TempCleanup] 定时任务已在运行')
|
||||
@ -707,7 +751,7 @@ async function readMetadataFailClosed(metadataPath: string): Promise<{
|
||||
|| fileSize <= 0
|
||||
|| !Number.isFinite(createdAt)
|
||||
|| createdAt <= 0
|
||||
|| (uploadPurpose && uploadPurpose !== 'brand-knowledge' && uploadPurpose !== PERFORMANCE_CASE_UPLOAD_PURPOSE)
|
||||
|| (uploadPurpose && uploadPurpose !== 'brand-knowledge' && uploadPurpose !== PERFORMANCE_CASE_UPLOAD_PURPOSE && !isDesktopDeliveryPurpose(uploadPurpose))
|
||||
) {
|
||||
throw new Error('meta.json 字段无效')
|
||||
}
|
||||
@ -769,7 +813,7 @@ function normalizeSessionEvidence(
|
||||
|| fileSize <= 0
|
||||
|| !Number.isFinite(createdAt)
|
||||
|| createdAt <= 0
|
||||
|| (uploadPurpose && uploadPurpose !== 'brand-knowledge' && uploadPurpose !== PERFORMANCE_CASE_UPLOAD_PURPOSE)
|
||||
|| (uploadPurpose && uploadPurpose !== 'brand-knowledge' && uploadPurpose !== PERFORMANCE_CASE_UPLOAD_PURPOSE && !isDesktopDeliveryPurpose(uploadPurpose))
|
||||
) {
|
||||
throw new MaterialUploadRequestError(
|
||||
'上传会话内容异常,已保留数据',
|
||||
|
||||
138
lib/xiaoyi-delivery-gc.ts
Normal file
138
lib/xiaoyi-delivery-gc.ts
Normal file
@ -0,0 +1,138 @@
|
||||
import { lstat, readdir, rm, rmdir, writeFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { acquireDeliveryAttemptLock } from '@/lib/delivery-revisions'
|
||||
import { findPurgeFileReferences, identifyPurgeFile, removePurgeFile, snapshotPurgeFile, type PurgeFile } from '@/lib/material-purge-files'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { deleteStoredUploadFileFromRemote } from '@/lib/remote-upload-sync'
|
||||
import { buildStoredUploadPath, getUploadRootDir } from '@/lib/upload-paths'
|
||||
import { cleanExpiredXiaoyiUpload, XIAOYI_GC_GRACE_MS } from '@/lib/temp-cleanup'
|
||||
|
||||
const MARKER = '.gc-candidate'
|
||||
const SAFE_PROJECT = /^[A-Za-z0-9_-]{1,80}$/
|
||||
const SAFE_ATTEMPT = /^[A-Za-z0-9_-]{1,117}$/
|
||||
const SAFE_UPLOAD = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/
|
||||
const SAFE_OWNER = /^[a-f0-9]{64}$/
|
||||
const BATCH = 50
|
||||
|
||||
type Outcome = 'candidate' | 'marked' | 'retained' | 'deleted' | 'skipped' | 'unavailable'
|
||||
|
||||
async function safeStat(file: string) {
|
||||
const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT') return null
|
||||
throw error
|
||||
})
|
||||
if (stat?.isSymbolicLink()) throw new Error('交付文件路径包含符号链接')
|
||||
return stat
|
||||
}
|
||||
|
||||
async function directories(root: string, pattern: RegExp) {
|
||||
if (!(await safeStat(root))?.isDirectory()) return []
|
||||
return (await readdir(root, { withFileTypes: true }))
|
||||
.filter(item => item.isDirectory() && pattern.test(item.name)).map(item => item.name).sort()
|
||||
}
|
||||
|
||||
async function inspectAttempt(root: string, parts: string[], dryRun: boolean): Promise<Outcome> {
|
||||
const [owner, project, attempt] = parts
|
||||
const folder = path.join(root, ...parts)
|
||||
const cutoff = Date.now() - XIAOYI_GC_GRACE_MS
|
||||
const initial = await safeStat(folder)
|
||||
if (!initial?.isDirectory() || initial.mtimeMs > cutoff) return 'skipped'
|
||||
const release = await acquireDeliveryAttemptLock(owner, project, attempt, 500)
|
||||
try {
|
||||
let location = path.dirname(root)
|
||||
for (const segment of [path.basename(root), ...parts]) {
|
||||
location = path.join(location, segment)
|
||||
if (!(await safeStat(location))?.isDirectory()) return 'skipped'
|
||||
}
|
||||
const marker = path.join(folder, MARKER)
|
||||
const markerStat = await safeStat(marker)
|
||||
if (markerStat && !markerStat.isFile()) return 'unavailable'
|
||||
const files: PurgeFile[] = []
|
||||
const nestedFolders: string[] = []
|
||||
const walk = async (relative: string[], depth: number): Promise<boolean> => {
|
||||
for (const name of await readdir(path.join(folder, ...relative))) {
|
||||
if (relative.length === 0 && name === MARKER) continue
|
||||
if (name.includes('\\') || /[\x00-\x1f]/.test(name)) return false
|
||||
const child = [...relative, name]
|
||||
const target = path.join(folder, ...child)
|
||||
const stat = await safeStat(target)
|
||||
if (!stat || stat.mtimeMs > cutoff) return false
|
||||
if (stat.isDirectory() && depth < 3) {
|
||||
if (!await walk(child, depth + 1)) return false
|
||||
nestedFolders.push(target)
|
||||
} else if (stat.isFile() && files.length < 500) {
|
||||
const file = identifyPurgeFile(buildStoredUploadPath('xiaoyi-deliveries', ...parts, ...child))
|
||||
if (!file) return false
|
||||
files.push(await snapshotPurgeFile(file))
|
||||
} else return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (!await walk([], 0)) return 'unavailable'
|
||||
const refs = await findPurgeFileReferences(prisma, files)
|
||||
release.assertHeld()
|
||||
if (refs.size) {
|
||||
if (!dryRun && markerStat) await rm(marker, { force: true })
|
||||
return 'retained'
|
||||
}
|
||||
if (!markerStat) {
|
||||
if (dryRun) return 'candidate'
|
||||
await writeFile(marker, new Date().toISOString(), { flag: 'wx' })
|
||||
return 'marked'
|
||||
}
|
||||
if (markerStat.mtimeMs > cutoff) return 'marked'
|
||||
if (dryRun) return 'candidate'
|
||||
for (const file of files) {
|
||||
release.assertHeld()
|
||||
await deleteStoredUploadFileFromRemote(file.source)
|
||||
await removePurgeFile(file)
|
||||
}
|
||||
for (const directory of nestedFolders) await rmdir(directory)
|
||||
await rm(marker, { force: true })
|
||||
await rmdir(folder)
|
||||
return 'deleted'
|
||||
} finally {
|
||||
await release()
|
||||
}
|
||||
}
|
||||
|
||||
async function* attempts(root: string) {
|
||||
for (const owner of await directories(root, SAFE_OWNER)) {
|
||||
for (const project of await directories(path.join(root, owner), SAFE_PROJECT)) {
|
||||
for (const attempt of await directories(path.join(root, owner, project), SAFE_ATTEMPT)) {
|
||||
yield [owner, project, attempt]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function collectXiaoyiDeliveryGarbage(options: {
|
||||
dryRun?: boolean; kind: 'deliveries' | 'uploads'; after?: string
|
||||
}) {
|
||||
const dryRun = options.dryRun !== false
|
||||
const uploadRoot = getUploadRootDir()
|
||||
const root = path.join(uploadRoot, options.kind === 'deliveries' ? 'xiaoyi-deliveries' : 'temp')
|
||||
const rows: Array<{ key: string; outcome: Outcome }> = []
|
||||
if (!(await safeStat(uploadRoot))?.isDirectory()) return { dryRun, rows, next: null }
|
||||
const keys = options.kind === 'deliveries' ? attempts(root)
|
||||
: (await directories(root, SAFE_UPLOAD)).map(key => [key])
|
||||
const cursor = options.after?.split('/')
|
||||
for await (const parts of keys) {
|
||||
const key = parts.join('/')
|
||||
if (cursor) {
|
||||
const difference = parts.findIndex((part, index) => part !== cursor[index])
|
||||
if (difference === -1 || parts[difference] < (cursor[difference] ?? '')) continue
|
||||
}
|
||||
if (rows.length === BATCH) return { dryRun, rows, next: rows[rows.length - 1].key }
|
||||
try {
|
||||
let outcome: Outcome
|
||||
if (options.kind === 'deliveries') outcome = await inspectAttempt(root, parts, dryRun)
|
||||
else outcome = await cleanExpiredXiaoyiUpload(parts[0], dryRun)
|
||||
rows.push({ key, outcome })
|
||||
} catch (error) {
|
||||
console.warn('[xiaoyi-gc] 保留暂无法核对的文件', { key, error })
|
||||
rows.push({ key, outcome: 'unavailable' })
|
||||
}
|
||||
}
|
||||
return { dryRun, rows, next: null }
|
||||
}
|
||||
@ -23,37 +23,72 @@ export function parseListingUpdate(body: unknown): ListingUpdate | null {
|
||||
return { eventId, sequence, state, listingId: listingId?.trim() ?? null, message: message?.trim() ?? null }
|
||||
}
|
||||
|
||||
// Existing consumers share the automatic-listing channel and have no store identifier.
|
||||
const AUTOMATIC_LISTING_CHANNEL = 'auto-listing'
|
||||
|
||||
export function applyListingReceipt(current: ListingStatus | undefined, update: ListingUpdate, now: string) {
|
||||
if (current && update.sequence <= current.sequence) {
|
||||
if (update.sequence === current.sequence && (update.state !== current.state
|
||||
|| update.listingId !== current.listingId || update.message !== current.message)) {
|
||||
return { status: 409, code: 'SEQUENCE_CONFLICT', message: '同一状态序号的内容必须一致' } as const
|
||||
}
|
||||
return { status: 200, applied: false, listingStatus: current } as const
|
||||
}
|
||||
if (current?.state === 'listed') {
|
||||
return { status: 409, code: 'ALREADY_LISTED', message: '上架成功后不能再更新此交付的状态' } as const
|
||||
}
|
||||
return { status: 200, applied: true, listingStatus: { ...update, updatedAt: now } } as const
|
||||
}
|
||||
|
||||
export async function recordListingStatus(materialId: string, update: ListingUpdate) {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const [row] = await tx.$queryRaw<Array<{ eventId: string; deletedAt: Date | null; listingStatus: ListingStatus | null }>>`
|
||||
SELECT e.id AS "eventId", m."deletedAt", d.listing_status AS "listingStatus"
|
||||
const [row] = await tx.$queryRaw<Array<{
|
||||
eventId: string | null; legacyEventId: string | null; deletedAt: Date | null; listingStatus: ListingStatus | null
|
||||
}>>`
|
||||
SELECT COALESCE(o.id, e.id) AS "eventId", e.id AS "legacyEventId", m."deletedAt", d.listing_status AS "listingStatus"
|
||||
FROM desktop_material_deliveries d
|
||||
JOIN xiaoyi_auto_listing_events e ON e.material_id = d.material_id
|
||||
JOIN materials m ON m.id = d.material_id
|
||||
WHERE d.material_id = ${materialId} AND m.access_scope = 'general' AND m.task_detail_private = false
|
||||
LEFT JOIN xiaoyi_auto_listing_outbox o ON o.revision_id = m.current_revision_id
|
||||
LEFT JOIN xiaoyi_auto_listing_events e ON e.material_id = m.id
|
||||
WHERE d.material_id = ${materialId} AND m.access_scope = 'general' AND NOT m.task_detail_private
|
||||
AND NOT m.is_incomplete_shell
|
||||
FOR UPDATE OF d, m
|
||||
`
|
||||
if (!row) return { status: 404, code: 'MATERIAL_NOT_FOUND', message: '小壹交付素材不存在' } as const
|
||||
if (row.deletedAt) return { status: 410, code: 'MATERIAL_DELETED', message: '素材已撤回' } as const
|
||||
if (row.eventId !== update.eventId) return { status: 409, code: 'EVENT_MISMATCH', message: '事件 ID 与素材不匹配' } as const
|
||||
if (row.eventId !== update.eventId && row.legacyEventId !== update.eventId &&
|
||||
!await tx.xiaoyiAutoListingOutbox.findFirst({ where: { id: update.eventId, materialId }, select: { id: true } })) {
|
||||
return { status: 409, code: 'EVENT_MISMATCH', message: '事件 ID 与素材不匹配' } as const
|
||||
}
|
||||
|
||||
const current = row.listingStatus
|
||||
if (current && update.sequence <= current.sequence) {
|
||||
if (update.sequence === current.sequence && (update.state !== current.state
|
||||
|| update.listingId !== current.listingId || update.message !== current.message)) {
|
||||
return { status: 409, code: 'SEQUENCE_CONFLICT', message: '同一状态序号的内容必须一致' } as const
|
||||
}
|
||||
return { status: 200, applied: false, listingStatus: current } as const
|
||||
const identity = { materialId, channel: AUTOMATIC_LISTING_CHANNEL, store: '' }
|
||||
const key = { materialId_channel_store: identity }
|
||||
const channel = await tx.channelListing.findUnique({ where: key })
|
||||
const receipts = (channel?.receipts ?? {}) as Record<string, ListingStatus>
|
||||
const legacy = row.listingStatus
|
||||
if (legacy && (receipts[legacy.eventId]?.sequence ?? 0) < legacy.sequence) receipts[legacy.eventId] = legacy
|
||||
const result = applyListingReceipt(receipts[update.eventId], update, new Date().toISOString())
|
||||
if (result.status !== 200 || !result.applied) return result
|
||||
|
||||
receipts[update.eventId] = result.listingStatus
|
||||
const current = row.eventId === update.eventId
|
||||
const listed = channel?.state === 'listed' || legacy?.state === 'listed'
|
||||
const state = listed || update.state === 'listed' ? 'listed' : current ? update.state : channel?.state ?? legacy?.state ?? 'pending'
|
||||
const previousListingId = channel?.listingId ?? legacy?.listingId ?? null
|
||||
const listingId = current ? update.listingId ?? previousListingId
|
||||
: previousListingId ?? (update.state === 'listed' ? update.listingId : null)
|
||||
await tx.channelListing.upsert({
|
||||
where: key,
|
||||
create: { ...identity, listingId, state, receipts },
|
||||
update: { listingId, state, receipts },
|
||||
})
|
||||
if (current && (!listed || update.state === 'listed')) {
|
||||
await tx.$executeRaw`
|
||||
UPDATE desktop_material_deliveries
|
||||
SET listing_status = ${JSON.stringify(result.listingStatus)}::jsonb
|
||||
WHERE material_id = ${materialId}
|
||||
`
|
||||
}
|
||||
if (current?.state === 'listed') {
|
||||
return { status: 409, code: 'ALREADY_LISTED', message: '上架成功后不能再更新此交付的状态' } as const
|
||||
}
|
||||
const listingStatus = { ...update, updatedAt: new Date().toISOString() }
|
||||
await tx.$executeRaw`
|
||||
UPDATE desktop_material_deliveries
|
||||
SET listing_status = ${JSON.stringify(listingStatus)}::jsonb
|
||||
WHERE material_id = ${materialId}
|
||||
`
|
||||
return { status: 200, applied: true, listingStatus } as const
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
@ -0,0 +1,118 @@
|
||||
-- Expand in place. The legacy tables and their keys are kept throughout rollout.
|
||||
SET lock_timeout = '3s';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS external_notification_targets (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
callback_url TEXT NOT NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
auth_type TEXT NOT NULL DEFAULT 'none',
|
||||
auth_config JSONB NOT NULL DEFAULT '{}',
|
||||
event_types JSONB NOT NULL DEFAULT '[]',
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS external_notification_deliveries (
|
||||
id TEXT PRIMARY KEY,
|
||||
target_id TEXT NOT NULL,
|
||||
event_type TEXT NOT NULL,
|
||||
material_id TEXT NOT NULL,
|
||||
material_type TEXT NOT NULL,
|
||||
task_no TEXT,
|
||||
status TEXT NOT NULL,
|
||||
payload JSONB NOT NULL,
|
||||
attempt_count INT NOT NULL DEFAULT 0,
|
||||
max_attempts INT NOT NULL DEFAULT 5,
|
||||
next_retry_at TIMESTAMP(3),
|
||||
last_status_code INT,
|
||||
last_response_body TEXT,
|
||||
last_error TEXT,
|
||||
dispatched_at TIMESTAMP(3),
|
||||
completed_at TIMESTAMP(3),
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS xiaoyi_auto_listing_events (
|
||||
id TEXT PRIMARY KEY,
|
||||
material_id TEXT NOT NULL UNIQUE,
|
||||
material_type TEXT NOT NULL,
|
||||
outcome_kind TEXT NOT NULL,
|
||||
project_id TEXT NOT NULL,
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
ALTER TABLE external_notification_targets
|
||||
ADD COLUMN IF NOT EXISTS consecutive_failures INT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS circuit_open_until TIMESTAMP(3);
|
||||
|
||||
ALTER TABLE external_notification_deliveries
|
||||
ADD COLUMN IF NOT EXISTS dedupe_key TEXT,
|
||||
ADD COLUMN IF NOT EXISTS lease_token TEXT,
|
||||
ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMP(3),
|
||||
ADD COLUMN IF NOT EXISTS replay_count INT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS replayed_by TEXT,
|
||||
ADD COLUMN IF NOT EXISTS replayed_at TIMESTAMP(3);
|
||||
|
||||
|
||||
CREATE TABLE delivery_revisions (
|
||||
id TEXT PRIMARY KEY,
|
||||
material_id TEXT NOT NULL REFERENCES materials(id) ON DELETE CASCADE,
|
||||
owner_id TEXT NOT NULL,
|
||||
project_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
request_id TEXT NOT NULL,
|
||||
fingerprint TEXT NOT NULL,
|
||||
parent_id TEXT,
|
||||
snapshot JSONB NOT NULL,
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (owner_id, request_id, kind)
|
||||
);
|
||||
CREATE INDEX delivery_revisions_material_id_created_at_idx ON delivery_revisions (material_id, created_at);
|
||||
|
||||
CREATE TABLE revision_assets (
|
||||
id TEXT PRIMARY KEY,
|
||||
revision_id TEXT NOT NULL REFERENCES delivery_revisions(id) ON DELETE CASCADE,
|
||||
asset_type TEXT NOT NULL,
|
||||
file_url TEXT NOT NULL,
|
||||
file_name TEXT,
|
||||
file_size BIGINT NOT NULL,
|
||||
sort_order INT NOT NULL,
|
||||
sku_code TEXT,
|
||||
sha256 TEXT,
|
||||
barcodes TEXT[] NOT NULL DEFAULT '{}'
|
||||
);
|
||||
CREATE INDEX revision_assets_revision_id_sort_order_id_idx ON revision_assets (revision_id, sort_order, id);
|
||||
CREATE INDEX revision_assets_file_url_idx ON revision_assets (file_url);
|
||||
CREATE INDEX revision_assets_purge_references_idx ON revision_assets USING gin
|
||||
(purge_reference_keys(ARRAY[file_url], false));
|
||||
|
||||
CREATE TABLE channel_listings (
|
||||
material_id TEXT NOT NULL REFERENCES materials(id) ON DELETE CASCADE,
|
||||
channel TEXT NOT NULL,
|
||||
store TEXT NOT NULL DEFAULT '',
|
||||
listing_id TEXT,
|
||||
state TEXT NOT NULL,
|
||||
receipts JSONB NOT NULL,
|
||||
updated_at TIMESTAMP(3) NOT NULL,
|
||||
PRIMARY KEY (material_id, channel, store)
|
||||
);
|
||||
|
||||
CREATE TABLE xiaoyi_auto_listing_outbox (
|
||||
id TEXT PRIMARY KEY,
|
||||
material_id TEXT NOT NULL,
|
||||
revision_id TEXT NOT NULL UNIQUE,
|
||||
material_type TEXT NOT NULL,
|
||||
outcome_kind TEXT NOT NULL,
|
||||
project_id TEXT NOT NULL,
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expanded_at TIMESTAMP(3)
|
||||
);
|
||||
CREATE INDEX xiaoyi_auto_listing_outbox_material_id_created_at_idx ON xiaoyi_auto_listing_outbox (material_id, created_at);
|
||||
CREATE INDEX xiaoyi_auto_listing_outbox_expanded_at_created_at_idx ON xiaoyi_auto_listing_outbox (expanded_at, created_at);
|
||||
|
||||
ALTER TABLE materials ADD COLUMN current_revision_id TEXT;
|
||||
ALTER TABLE materials ADD CONSTRAINT materials_current_revision_id_fkey
|
||||
FOREIGN KEY (current_revision_id) REFERENCES delivery_revisions(id) ON DELETE SET NULL ON UPDATE CASCADE NOT VALID;
|
||||
ALTER TABLE materials VALIDATE CONSTRAINT materials_current_revision_id_fkey;
|
||||
|
||||
RESET lock_timeout;
|
||||
@ -0,0 +1,2 @@
|
||||
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS external_notification_targets_name_key
|
||||
ON external_notification_targets (name);
|
||||
@ -0,0 +1,2 @@
|
||||
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS external_notification_deliveries_target_event_dedupe_key
|
||||
ON external_notification_deliveries (target_id, event_type, dedupe_key);
|
||||
@ -0,0 +1,2 @@
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS external_notification_deliveries_status_next_retry_idx
|
||||
ON external_notification_deliveries (status, next_retry_at);
|
||||
@ -0,0 +1,2 @@
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS external_notification_deliveries_target_lease_idx
|
||||
ON external_notification_deliveries (target_id, status, lease_expires_at);
|
||||
@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS external_notification_deliveries_target_event_material_key;
|
||||
@ -0,0 +1 @@
|
||||
CREATE UNIQUE INDEX CONCURRENTLY materials_current_revision_id_key ON materials (current_revision_id);
|
||||
@ -0,0 +1,24 @@
|
||||
-- Keep writes from the previous application revision visible to ChannelListing.
|
||||
CREATE FUNCTION mirror_legacy_channel_listing() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
receipt jsonb := NEW.listing_status;
|
||||
event_id text := receipt->>'eventId';
|
||||
BEGIN
|
||||
IF event_id IS NULL OR COALESCE(receipt->>'state', '') NOT IN ('listing','listed','failed') THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
INSERT INTO channel_listings (material_id, channel, store, listing_id, state, receipts, updated_at)
|
||||
SELECT NEW.material_id, 'auto-listing', '', receipt->>'listingId', receipt->>'state',
|
||||
jsonb_build_object(event_id, receipt), CURRENT_TIMESTAMP
|
||||
FROM materials WHERE id=NEW.material_id
|
||||
ON CONFLICT (material_id, channel, store) DO UPDATE SET
|
||||
listing_id=COALESCE(EXCLUDED.listing_id, channel_listings.listing_id),
|
||||
state=CASE WHEN channel_listings.state='listed' THEN 'listed' ELSE EXCLUDED.state END,
|
||||
receipts=channel_listings.receipts || EXCLUDED.receipts,
|
||||
updated_at=EXCLUDED.updated_at;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER desktop_delivery_listing_compatibility
|
||||
AFTER INSERT OR UPDATE OF listing_status ON desktop_material_deliveries
|
||||
FOR EACH ROW EXECUTE FUNCTION mirror_legacy_channel_listing();
|
||||
@ -0,0 +1,8 @@
|
||||
-- A concurrent legacy write through the compatibility trigger takes precedence over this snapshot.
|
||||
INSERT INTO channel_listings (material_id, channel, store, listing_id, state, receipts, updated_at)
|
||||
SELECT d.material_id, 'auto-listing', '', d.listing_status->>'listingId', d.listing_status->>'state',
|
||||
jsonb_build_object(d.listing_status->>'eventId', d.listing_status), CURRENT_TIMESTAMP
|
||||
FROM desktop_material_deliveries d JOIN materials m ON m.id=d.material_id
|
||||
WHERE d.listing_status->>'eventId' IS NOT NULL
|
||||
AND d.listing_status->>'state' IN ('listing','listed','failed')
|
||||
ON CONFLICT (material_id, channel, store) DO NOTHING;
|
||||
@ -376,6 +376,10 @@ model Material {
|
||||
/// 专用 init 建档时写 true,完成落库后写 false。列表/筛选只读这个标记,
|
||||
/// 不再每次去资产表现场判断是不是上传空壳。
|
||||
isIncompleteShell Boolean @default(false) @map("is_incomplete_shell")
|
||||
currentRevisionId String? @unique @map("current_revision_id")
|
||||
currentRevision DeliveryRevision? @relation("CurrentDeliveryRevision", fields: [currentRevisionId], references: [id], onDelete: SetNull)
|
||||
deliveryRevisions DeliveryRevision[] @relation("DeliveryRevisionHistory")
|
||||
channelListings ChannelListing[]
|
||||
assets MaterialAsset[]
|
||||
favorites MaterialFavorite[]
|
||||
likes MaterialLike[]
|
||||
@ -2072,3 +2076,130 @@ enum Role {
|
||||
DEPT_ADMIN
|
||||
SYSTEM_ADMIN
|
||||
}
|
||||
|
||||
model DeliveryRevision {
|
||||
id String @id @default(uuid())
|
||||
materialId String @map("material_id")
|
||||
ownerId String @map("owner_id")
|
||||
projectId String @map("project_id")
|
||||
kind String
|
||||
requestId String @map("request_id")
|
||||
fingerprint String
|
||||
parentId String? @map("parent_id")
|
||||
snapshot Json
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
material Material @relation("DeliveryRevisionHistory", fields: [materialId], references: [id], onDelete: Cascade)
|
||||
currentFor Material? @relation("CurrentDeliveryRevision")
|
||||
assets RevisionAsset[]
|
||||
|
||||
@@unique([ownerId, requestId, kind])
|
||||
@@index([materialId, createdAt])
|
||||
@@map("delivery_revisions")
|
||||
}
|
||||
|
||||
model RevisionAsset {
|
||||
id String @id
|
||||
revisionId String @map("revision_id")
|
||||
assetType String @map("asset_type")
|
||||
fileUrl String @map("file_url")
|
||||
fileName String? @map("file_name")
|
||||
fileSize BigInt @map("file_size")
|
||||
sortOrder Int @map("sort_order")
|
||||
skuCode String? @map("sku_code")
|
||||
sha256 String?
|
||||
barcodes String[] @default([])
|
||||
revision DeliveryRevision @relation(fields: [revisionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([revisionId, sortOrder, id])
|
||||
@@index([fileUrl])
|
||||
@@map("revision_assets")
|
||||
}
|
||||
|
||||
model ChannelListing {
|
||||
materialId String @map("material_id")
|
||||
channel String
|
||||
store String @default("")
|
||||
listingId String? @map("listing_id")
|
||||
state String
|
||||
receipts Json
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
material Material @relation(fields: [materialId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([materialId, channel, store])
|
||||
@@map("channel_listings")
|
||||
}
|
||||
|
||||
model ExternalNotificationTarget {
|
||||
id String @id
|
||||
name String @unique
|
||||
callbackUrl String @map("callback_url")
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
authType String @default("none") @map("auth_type")
|
||||
authConfig Json @default("{}") @map("auth_config")
|
||||
eventTypes Json @default("[]") @map("event_types")
|
||||
consecutiveFailures Int @default(0) @map("consecutive_failures")
|
||||
circuitOpenUntil DateTime? @map("circuit_open_until")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @default(now()) @map("updated_at")
|
||||
|
||||
@@map("external_notification_targets")
|
||||
}
|
||||
|
||||
model ExternalNotificationDelivery {
|
||||
id String @id
|
||||
targetId String @map("target_id")
|
||||
eventType String @map("event_type")
|
||||
materialId String @map("material_id")
|
||||
materialType String @map("material_type")
|
||||
taskNo String? @map("task_no")
|
||||
dedupeKey String? @map("dedupe_key")
|
||||
status String
|
||||
payload Json
|
||||
attemptCount Int @default(0) @map("attempt_count")
|
||||
maxAttempts Int @default(5) @map("max_attempts")
|
||||
nextRetryAt DateTime? @map("next_retry_at")
|
||||
lastStatusCode Int? @map("last_status_code")
|
||||
lastResponseBody String? @map("last_response_body")
|
||||
lastError String? @map("last_error")
|
||||
dispatchedAt DateTime? @map("dispatched_at")
|
||||
completedAt DateTime? @map("completed_at")
|
||||
leaseToken String? @map("lease_token")
|
||||
leaseExpiresAt DateTime? @map("lease_expires_at")
|
||||
replayCount Int @default(0) @map("replay_count")
|
||||
replayedBy String? @map("replayed_by")
|
||||
replayedAt DateTime? @map("replayed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @default(now()) @map("updated_at")
|
||||
|
||||
@@unique([targetId, eventType, dedupeKey], map: "external_notification_deliveries_target_event_dedupe_key")
|
||||
@@index([status, nextRetryAt], map: "external_notification_deliveries_status_next_retry_idx")
|
||||
@@index([targetId, status, leaseExpiresAt], map: "external_notification_deliveries_target_lease_idx")
|
||||
@@map("external_notification_deliveries")
|
||||
}
|
||||
|
||||
/// Legacy material-level event kept readable during the application rollout.
|
||||
model XiaoyiAutoListingEvent {
|
||||
id String @id
|
||||
materialId String @unique @map("material_id")
|
||||
materialType String @map("material_type")
|
||||
outcomeKind String @map("outcome_kind")
|
||||
projectId String @map("project_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@map("xiaoyi_auto_listing_events")
|
||||
}
|
||||
|
||||
model XiaoyiAutoListingOutbox {
|
||||
id String @id @default(uuid())
|
||||
materialId String @map("material_id")
|
||||
revisionId String @unique @map("revision_id")
|
||||
materialType String @map("material_type")
|
||||
outcomeKind String @map("outcome_kind")
|
||||
projectId String @map("project_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
expandedAt DateTime? @map("expanded_at")
|
||||
|
||||
@@index([materialId, createdAt])
|
||||
@@index([expandedAt, createdAt])
|
||||
@@map("xiaoyi_auto_listing_outbox")
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user