放宽外发投递重放与上架回执限制

This commit is contained in:
WuYongJie 2026-12-05 11:54:51 +08:00
parent c1d216eb8f
commit fcf1bfbd45
5 changed files with 101 additions and 14 deletions

View File

@ -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) {

View File

@ -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)
})
})

View File

@ -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)
})

View File

@ -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<Array<{ enabled: boolean }>>`
SELECT (t.is_active AND t.event_types ? d.event_type) AS enabled
const [target] = await tx.$queryRaw<Array<{ id: string; enabled: boolean }>>`
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()

View File

@ -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
}