From fcf1bfbd453a6fa4eaf78642a6ef00be356ff7c1 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Sat, 5 Dec 2026 11:54:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=BE=E5=AE=BD=E5=A4=96=E5=8F=91=E6=8A=95?= =?UTF-8?q?=E9=80=92=E9=87=8D=E6=94=BE=E4=B8=8E=E4=B8=8A=E6=9E=B6=E5=9B=9E?= =?UTF-8?q?=E6=89=A7=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../[id]/retry/route.ts | 2 +- lib/__tests__/external-auto-listing.test.ts | 23 +++++-- lib/__tests__/xiaoyi-listing-status.test.ts | 67 +++++++++++++++++++ lib/external-auto-listing.ts | 19 ++++-- lib/xiaoyi-listing-status.ts | 4 +- 5 files changed, 101 insertions(+), 14 deletions(-) create mode 100644 lib/__tests__/xiaoyi-listing-status.test.ts diff --git a/app/api/admin/external-notification-deliveries/[id]/retry/route.ts b/app/api/admin/external-notification-deliveries/[id]/retry/route.ts index 05523380..7b05ff68 100644 --- a/app/api/admin/external-notification-deliveries/[id]/retry/route.ts +++ b/app/api/admin/external-notification-deliveries/[id]/retry/route.ts @@ -22,7 +22,7 @@ export async function POST(request: NextRequest, { params }: { params: { id: str return NextResponse.json({ success: false, error: '请先启用目标及对应事件订阅' }, { status: 409 }) } if (result === 'conflict') { - return NextResponse.json({ success: false, error: '仅可重放已用完重试次数的投递' }, { status: 409 }) + return NextResponse.json({ success: false, error: '投递正在执行或已成功,无法补发' }, { status: 409 }) } return NextResponse.json({ success: true, message: '补发任务已重新入队' }) } catch (error) { diff --git a/lib/__tests__/external-auto-listing.test.ts b/lib/__tests__/external-auto-listing.test.ts index c6cbbc39..77253934 100644 --- a/lib/__tests__/external-auto-listing.test.ts +++ b/lib/__tests__/external-auto-listing.test.ts @@ -257,6 +257,10 @@ describe('external auto listing', () => { 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]) + const [sql, resetError, circuitError] = write.mock.calls[1] + expect(sql.join('')).toContain('IS NULL THEN 0') + expect(sql.join('')).toContain("INTERVAL '1 millisecond') ELSE NULL END") + expect([resetError, circuitError]).toEqual([null, null]) }) test('过期持有者无法更新目标熔断计数或覆盖投递结果', async () => { @@ -356,16 +360,22 @@ describe('external auto listing', () => { }) }) - test('手工重放只有耗尽任务能重置预算并记录操作人', async () => { - const query = jest.fn().mockResolvedValue([{ enabled: true }]) - const write = jest.fn().mockResolvedValueOnce(1).mockResolvedValueOnce(0) + test('手工重放重置投递预算和目标熔断,保留成功记录及生效中的租约', async () => { + const query = jest.fn().mockResolvedValue([{ id: 'target-1', enabled: true }]) + const write = jest.fn().mockResolvedValueOnce(1).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("status<>'succeeded'") + expect(sql.join('')).toContain("status<>'processing' OR COALESCE(lease_expires_at,updated_at + INTERVAL '10 minutes') <= NOW()") expect(sql.join('')).toContain('attempt_count=0') + expect(sql.join('')).toContain('next_retry_at=NOW()') expect([actor, id]).toEqual(['admin', 'delivery-2']) + const [resetSql, targetId] = write.mock.calls[1] + expect(resetSql.join('')).toContain('consecutive_failures=0, circuit_open_until=NULL') + expect(targetId).toBe('target-1') + expect(write).toHaveBeenCalledTimes(3) }) test('精确匹配素材、任务、项目和事件编号,在截取最近记录前执行筛选', async () => { @@ -496,6 +506,9 @@ describe('external auto listing', () => { 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') + const [circuitSql, , , limit, cooldown] = write.mock.calls[1] + expect(circuitSql.join('')).toContain('consecutive_failures+1 >=') + expect(limit).toBe(10) + expect(cooldown).toBe(120_000) }) }) diff --git a/lib/__tests__/xiaoyi-listing-status.test.ts b/lib/__tests__/xiaoyi-listing-status.test.ts new file mode 100644 index 00000000..53608789 --- /dev/null +++ b/lib/__tests__/xiaoyi-listing-status.test.ts @@ -0,0 +1,67 @@ +/** @jest-environment node */ +import { prisma } from '@/lib/prisma' +import { applyListingReceipt, recordListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status' + +jest.mock('@/lib/prisma', () => ({ prisma: { $transaction: jest.fn() } })) + +const listed: ListingStatus = { + eventId: 'event-1', sequence: 2, state: 'listed', listingId: 'listing-1', message: null, + updatedAt: '2026-12-04T10:00:00.000Z', +} +const now = '2026-12-05T10:00:00.000Z' + +test('同一成功回执重复提交保持幂等,新序号也可回传成功', () => { + const { updatedAt, ...update } = listed + expect(applyListingReceipt(listed, update, now)).toEqual({ + status: 200, applied: false, listingStatus: listed, + }) + expect(applyListingReceipt(listed, { ...update, sequence: 3 }, now)).toEqual({ + status: 200, applied: true, listingStatus: { ...update, sequence: 3, updatedAt: now }, + }) +}) + +test.each(['listing', 'failed'] as const)('同一事件上架成功后拒绝用更大序号改为 %s', state => { + expect(applyListingReceipt(listed, { ...listed, sequence: 3, state }, now)).toMatchObject({ + status: 409, code: 'ALREADY_LISTED', + }) +}) + +test('修订后的事件可以从上架中转为成功,期间保留已上架状态', async () => { + const identity = { materialId: 'material-1', channel: 'auto-listing', store: '' } + const receipts = { [listed.eventId]: listed } + const tx = { + $queryRaw: jest.fn().mockResolvedValue([{ + eventId: 'event-2', legacyEventId: null, deletedAt: null, listingStatus: listed, + }]), + channelListing: { + findUnique: jest.fn().mockResolvedValue({ state: 'listed', listingId: listed.listingId, receipts }), + upsert: jest.fn(), + }, + $executeRaw: jest.fn(), + } + jest.mocked(prisma.$transaction).mockImplementation(async action => action(tx as any)) + const update = { eventId: 'event-2', sequence: 1, state: 'listing', listingId: null, message: null } as const + + await expect(recordListingStatus(identity.materialId, update)).resolves.toMatchObject({ + status: 200, applied: true, listingStatus: update, + }) + expect(tx.channelListing.upsert).toHaveBeenLastCalledWith(expect.objectContaining({ + update: { state: 'listed', listingId: listed.listingId, receipts: { + 'event-1': listed, + 'event-2': { ...update, updatedAt: expect.any(String) }, + } }, + })) + expect(tx.$executeRaw).not.toHaveBeenCalled() + + const success = { ...update, sequence: 2, state: 'listed', listingId: 'listing-2' } as const + await expect(recordListingStatus(identity.materialId, success)).resolves.toMatchObject({ + status: 200, applied: true, listingStatus: success, + }) + expect(tx.channelListing.upsert).toHaveBeenLastCalledWith(expect.objectContaining({ + update: { state: 'listed', listingId: success.listingId, receipts: { + 'event-1': listed, + 'event-2': { ...success, updatedAt: expect.any(String) }, + } }, + })) + expect(tx.$executeRaw).toHaveBeenCalledTimes(1) +}) diff --git a/lib/external-auto-listing.ts b/lib/external-auto-listing.ts index 515911fb..cbfecff0 100644 --- a/lib/external-auto-listing.ts +++ b/lib/external-auto-listing.ts @@ -90,8 +90,8 @@ const XIAOYI_EVENT_TABLE = 'xiaoyi_auto_listing_events' 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 CIRCUIT_FAILURE_LIMIT = 10 +const CIRCUIT_COOLDOWN_MS = 2 * 60_000 const RECOVERY_INTERVAL_MS = 60_000 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 = [ @@ -1086,8 +1086,8 @@ export async function queueTaskDetailBarcodeImagesUpdatedNotification( export async function retryExternalNotificationDelivery(deliveryId: string, actorId: string) { await ensureExternalNotificationTables() const result = await prisma.$transaction(async tx => { - const [target] = await tx.$queryRaw>` - SELECT (t.is_active AND t.event_types ? d.event_type) AS enabled + const [target] = await tx.$queryRaw>` + SELECT t.id, (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 ` @@ -1098,9 +1098,16 @@ export async function retryExternalNotificationDelivery(deliveryId: string, acto 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' + WHERE id=${deliveryId} AND status<>'succeeded' + AND (status<>'processing' OR COALESCE(lease_expires_at,updated_at + INTERVAL '10 minutes') <= NOW()) ` - return updated ? 'queued' : 'conflict' + if (!updated) return 'conflict' + await tx.$executeRaw` + UPDATE external_notification_targets + SET consecutive_failures=0, circuit_open_until=NULL + WHERE id=${target.id} + ` + return 'queued' }) if (result === 'queued') { ensureExternalNotificationWorkerStarted() diff --git a/lib/xiaoyi-listing-status.ts b/lib/xiaoyi-listing-status.ts index cb4e91d1..52d9d106 100644 --- a/lib/xiaoyi-listing-status.ts +++ b/lib/xiaoyi-listing-status.ts @@ -34,8 +34,8 @@ export function applyListingReceipt(current: ListingStatus | undefined, update: } return { status: 200, applied: false, listingStatus: current } as const } - if (current?.state === 'listed') { - return { status: 409, code: 'ALREADY_LISTED', message: '上架成功后不能再更新此交付的状态' } as const + if (current?.state === 'listed' && update.state !== 'listed') { + return { status: 409, code: 'ALREADY_LISTED', message: '上架成功后不能改回上架中或失败' } as const } return { status: 200, applied: true, listingStatus: { ...update, updatedAt: now } } as const }