1211 lines
41 KiB
TypeScript
1211 lines
41 KiB
TypeScript
import { EXTERNAL_MATERIAL_SCOPE_WHERE } from '@/lib/material-access-scope'
|
|
import { randomUUID } from 'crypto'
|
|
import type { Prisma } from '@prisma/client'
|
|
import {
|
|
AutoListingCallbackError,
|
|
normalizeAutoListingCallbackUrl,
|
|
postAutoListingCallback,
|
|
summarizeAutoListingCallbackError,
|
|
validateAutoListingCallbackUrl,
|
|
validateCallbackAuth,
|
|
} from '@/lib/external-auto-listing-callback'
|
|
import { decryptCallbackSecret, encryptCallbackSecret } from '@/lib/external-auto-listing-crypto'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { getPublicAppOrigin } from '@/lib/public-app-url'
|
|
import { XIAOYI_DELIVERY_MATERIAL_TYPES, type XiaoyiDeliveryKind } from '@/lib/xiaoyi-delivery-material'
|
|
|
|
export const AUTO_LISTING_EVENT_TYPE = 'task-detail.full-set.ready'
|
|
export const TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE = 'task-detail.barcode-images.updated'
|
|
export const XIAOYI_AUTO_LISTING_EVENT_TYPE = 'xiaoyi.auto-listing.material.ready'
|
|
|
|
export const AUTO_LISTING_AUTH_TYPE = {
|
|
NONE: 'none',
|
|
BEARER: 'bearer',
|
|
HEADER: 'header',
|
|
} as const
|
|
|
|
export const AUTO_LISTING_DELIVERY_STATUS = {
|
|
PENDING: 'pending',
|
|
PROCESSING: 'processing',
|
|
RETRYING: 'retrying',
|
|
SUCCEEDED: 'succeeded',
|
|
EXHAUSTED: 'exhausted',
|
|
} as const
|
|
|
|
export interface ExternalNotificationTarget {
|
|
id: string
|
|
name: string
|
|
callbackUrl: string
|
|
isActive: boolean
|
|
authType: string
|
|
authConfig: Record<string, string>
|
|
eventTypes: string[]
|
|
createdAt: string
|
|
updatedAt: string
|
|
}
|
|
|
|
export interface ExternalNotificationTargetAdminView
|
|
extends Omit<ExternalNotificationTarget, 'authConfig'> {
|
|
authConfig: Record<string, string>
|
|
authConfigured: boolean
|
|
authMasked: string
|
|
}
|
|
|
|
export interface ExternalNotificationDelivery {
|
|
id: string
|
|
targetId: string
|
|
targetName: string
|
|
eventType: string
|
|
materialId: string
|
|
materialType: string
|
|
taskNo: string | null
|
|
status: string
|
|
attemptCount: number
|
|
maxAttempts: number
|
|
nextRetryAt: string | null
|
|
lastStatusCode: number | null
|
|
lastResponseBody: string | null
|
|
lastError: string | null
|
|
payload: Record<string, unknown> | null
|
|
createdAt: string
|
|
updatedAt: string
|
|
completedAt: string | null
|
|
}
|
|
|
|
export type ExternalNotificationDeliverySummary =
|
|
Omit<ExternalNotificationDelivery, 'lastResponseBody' | 'payload'> & { projectId: string | null; eventId: string | null }
|
|
|
|
export interface ExternalNotificationTargetInput {
|
|
name: string
|
|
callbackUrl: string
|
|
isActive?: boolean
|
|
authType?: string
|
|
authConfig?: Record<string, string>
|
|
eventTypes?: string[]
|
|
}
|
|
|
|
const TARGET_TABLE = 'external_notification_targets'
|
|
const DELIVERY_TABLE = 'external_notification_deliveries'
|
|
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 = 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 = [
|
|
AUTO_LISTING_EVENT_TYPE,
|
|
TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE,
|
|
XIAOYI_AUTO_LISTING_EVENT_TYPE,
|
|
] as const
|
|
|
|
let isTableInitialized = false
|
|
let isWorkerStarted = false
|
|
let recoveryRunning = false
|
|
let recoveryRequested = false
|
|
const inFlightTargets = new Set<string>()
|
|
|
|
function asJson(value: unknown, fallback: string) {
|
|
try {
|
|
return JSON.stringify(value ?? JSON.parse(fallback))
|
|
} catch {
|
|
return fallback
|
|
}
|
|
}
|
|
|
|
function toIsoString(value: unknown): string | null {
|
|
if (!value) {
|
|
return null
|
|
}
|
|
|
|
if (value instanceof Date) {
|
|
return value.toISOString()
|
|
}
|
|
|
|
const date = new Date(String(value))
|
|
return Number.isNaN(date.getTime()) ? null : date.toISOString()
|
|
}
|
|
|
|
function normalizeAuthType(value: string | null | undefined) {
|
|
if (value === AUTO_LISTING_AUTH_TYPE.BEARER || value === AUTO_LISTING_AUTH_TYPE.HEADER) {
|
|
return value
|
|
}
|
|
|
|
return AUTO_LISTING_AUTH_TYPE.NONE
|
|
}
|
|
|
|
function normalizeAuthConfig(input: unknown): Record<string, string> {
|
|
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
return {}
|
|
}
|
|
|
|
return Object.entries(input as Record<string, unknown>).reduce<Record<string, string>>((acc, [key, value]) => {
|
|
const normalizedKey = String(key || '').trim()
|
|
const normalizedValue = typeof value === 'string' ? value.trim() : ''
|
|
if (normalizedKey && normalizedValue) {
|
|
acc[normalizedKey] = normalizedValue
|
|
}
|
|
return acc
|
|
}, {})
|
|
}
|
|
|
|
function normalizeEventTypes(eventTypes?: string[] | null): string[] {
|
|
const normalized = Array.isArray(eventTypes)
|
|
? eventTypes
|
|
.map((item) => String(item || '').trim())
|
|
.filter((item): item is (typeof SUPPORTED_AUTO_LISTING_EVENT_TYPES)[number] =>
|
|
Boolean(item) && (SUPPORTED_AUTO_LISTING_EVENT_TYPES as readonly string[]).includes(item),
|
|
)
|
|
: []
|
|
|
|
return normalized.length > 0 ? Array.from(new Set(normalized)) : [AUTO_LISTING_EVENT_TYPE]
|
|
}
|
|
|
|
function buildBarcodeLookupUrl(barcode: string) {
|
|
return `${getPublicAppOrigin()}/api/external/product-barcode-images?barcode=${encodeURIComponent(barcode)}`
|
|
}
|
|
|
|
function compareBarcodeTimeline(
|
|
left: { createdAt: Date; sortOrder: number },
|
|
right: { createdAt: Date; sortOrder: number },
|
|
) {
|
|
const createdAtDiff = right.createdAt.getTime() - left.createdAt.getTime()
|
|
if (createdAtDiff !== 0) {
|
|
return createdAtDiff
|
|
}
|
|
|
|
return left.sortOrder - right.sortOrder
|
|
}
|
|
|
|
async function listActiveTargetsByEventType(eventType: string) {
|
|
return queryRaw<any>(
|
|
`
|
|
SELECT
|
|
id,
|
|
name,
|
|
callback_url AS "callbackUrl",
|
|
is_active AS "isActive",
|
|
auth_type AS "authType",
|
|
auth_config AS "authConfig",
|
|
event_types AS "eventTypes",
|
|
created_at AS "createdAt",
|
|
updated_at AS "updatedAt"
|
|
FROM "${TARGET_TABLE}"
|
|
WHERE is_active = TRUE
|
|
AND event_types ? $1
|
|
ORDER BY created_at ASC
|
|
`,
|
|
eventType,
|
|
)
|
|
}
|
|
|
|
async function enqueueNotificationDeliveries(options: {
|
|
eventType: string
|
|
materialId: string
|
|
materialType: string
|
|
taskNo?: string | null
|
|
dedupeKey: string
|
|
payload: Record<string, unknown>
|
|
}) {
|
|
const targets = await listActiveTargetsByEventType(options.eventType)
|
|
const createdIds: string[] = []
|
|
|
|
for (const row of targets) {
|
|
const deliveryId = randomUUID()
|
|
const insertedRows = await queryRaw<{ id: string }>(
|
|
`
|
|
INSERT INTO "${DELIVERY_TABLE}" (
|
|
id,
|
|
target_id,
|
|
event_type,
|
|
material_id,
|
|
material_type,
|
|
task_no,
|
|
dedupe_key,
|
|
status,
|
|
payload,
|
|
attempt_count,
|
|
max_attempts,
|
|
next_retry_at,
|
|
created_at,
|
|
updated_at
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::jsonb, 0, $10, NOW(), NOW(), NOW())
|
|
ON CONFLICT ("target_id", "event_type", "dedupe_key") DO NOTHING
|
|
RETURNING id
|
|
`,
|
|
deliveryId,
|
|
String(row.id),
|
|
options.eventType,
|
|
options.materialId,
|
|
options.materialType,
|
|
options.taskNo || null,
|
|
options.dedupeKey,
|
|
AUTO_LISTING_DELIVERY_STATUS.PENDING,
|
|
asJson(options.payload, '{}'),
|
|
DELIVERY_MAX_ATTEMPTS,
|
|
)
|
|
|
|
const inserted = insertedRows[0]
|
|
if (inserted?.id) {
|
|
createdIds.push(String(inserted.id))
|
|
}
|
|
}
|
|
|
|
if (createdIds.length) setTimeout(wakeDeliveryWorker, 0).unref?.()
|
|
return createdIds
|
|
}
|
|
|
|
function normalizeTargetRow(row: any): ExternalNotificationTarget {
|
|
return {
|
|
id: String(row.id),
|
|
name: String(row.name || ''),
|
|
callbackUrl: String(row.callbackUrl || ''),
|
|
isActive: Boolean(row.isActive),
|
|
authType: normalizeAuthType(row.authType),
|
|
authConfig: normalizeAuthConfig(row.authConfig),
|
|
eventTypes: normalizeEventTypes(Array.isArray(row.eventTypes) ? row.eventTypes : []),
|
|
createdAt: toIsoString(row.createdAt) || new Date().toISOString(),
|
|
updatedAt: toIsoString(row.updatedAt) || new Date().toISOString(),
|
|
}
|
|
}
|
|
|
|
export function buildExternalNotificationTargetAdminView(
|
|
target: ExternalNotificationTarget,
|
|
): ExternalNotificationTargetAdminView {
|
|
const { authConfig, ...summary } = target
|
|
// Older rows can contain URL credentials or query parameters. Keep them out of responses.
|
|
const url = URL.canParse(target.callbackUrl) ? new URL(target.callbackUrl) : null
|
|
const callbackUrl = url && (url.protocol === 'http:' || url.protocol === 'https:')
|
|
? url.origin + url.pathname
|
|
: ''
|
|
const hasEncryptedSecret = Boolean(authConfig.secretCiphertext)
|
|
const isBearer = target.authType === AUTO_LISTING_AUTH_TYPE.BEARER
|
|
const isHeader = target.authType === AUTO_LISTING_AUTH_TYPE.HEADER
|
|
const authConfigured = isBearer
|
|
? hasEncryptedSecret || Boolean(authConfig.token)
|
|
: isHeader && Boolean(authConfig.headerName && (hasEncryptedSecret || authConfig.headerValue))
|
|
|
|
return {
|
|
...summary,
|
|
callbackUrl,
|
|
authConfig: isHeader && authConfig.headerName ? { headerName: authConfig.headerName } : {},
|
|
authConfigured,
|
|
authMasked: isBearer || isHeader
|
|
? `${isBearer ? 'Bearer' : '自定义请求头'} · ${authConfigured ? '已配置' : '未配置'}`
|
|
: '无鉴权',
|
|
}
|
|
}
|
|
|
|
export function summarizeExternalNotificationDelivery(
|
|
{ lastResponseBody: _lastResponseBody, payload, ...delivery }: ExternalNotificationDelivery,
|
|
): ExternalNotificationDeliverySummary {
|
|
return {
|
|
...delivery,
|
|
projectId: typeof payload?.projectId === 'string' ? payload.projectId : null,
|
|
eventId: typeof payload?.eventId === 'string' ? payload.eventId : null,
|
|
lastError: summarizeAutoListingCallbackError(delivery.lastError, delivery.lastStatusCode),
|
|
}
|
|
}
|
|
|
|
function normalizeDeliveryRow(row: any): ExternalNotificationDelivery {
|
|
return {
|
|
id: String(row.id),
|
|
targetId: String(row.targetId || ''),
|
|
targetName: String(row.targetName || ''),
|
|
eventType: String(row.eventType || ''),
|
|
materialId: String(row.materialId || ''),
|
|
materialType: String(row.materialType || ''),
|
|
taskNo: row.taskNo ? String(row.taskNo) : null,
|
|
status: String(row.status || AUTO_LISTING_DELIVERY_STATUS.PENDING),
|
|
attemptCount: Number(row.attemptCount || 0),
|
|
maxAttempts: Number(row.maxAttempts || DELIVERY_MAX_ATTEMPTS),
|
|
nextRetryAt: toIsoString(row.nextRetryAt),
|
|
lastStatusCode:
|
|
typeof row.lastStatusCode === 'number'
|
|
? row.lastStatusCode
|
|
: row.lastStatusCode != null
|
|
? Number(row.lastStatusCode)
|
|
: null,
|
|
lastResponseBody: row.lastResponseBody ? String(row.lastResponseBody) : null,
|
|
lastError: row.lastError ? String(row.lastError) : null,
|
|
payload:
|
|
row.payload && typeof row.payload === 'object' && !Array.isArray(row.payload)
|
|
? (row.payload as Record<string, unknown>)
|
|
: null,
|
|
createdAt: toIsoString(row.createdAt) || new Date().toISOString(),
|
|
updatedAt: toIsoString(row.updatedAt) || new Date().toISOString(),
|
|
completedAt: toIsoString(row.completedAt),
|
|
}
|
|
}
|
|
|
|
async function normalizeTargetInput(
|
|
input: Partial<ExternalNotificationTargetInput>,
|
|
existing?: ExternalNotificationTarget,
|
|
) {
|
|
const name = (input.name ?? existing?.name ?? '').trim()
|
|
if (!name) throw new AutoListingCallbackError('目标系统名称不能为空')
|
|
|
|
const inputUrl = normalizeAutoListingCallbackUrl(input.callbackUrl ?? existing?.callbackUrl ?? '').href
|
|
const callbackUrl = inputUrl === existing?.callbackUrl
|
|
? inputUrl
|
|
: await validateAutoListingCallbackUrl(inputUrl)
|
|
const authType = normalizeAuthType(input.authType ?? existing?.authType)
|
|
const config = normalizeAuthConfig(input.authConfig)
|
|
const headerName = authType === AUTO_LISTING_AUTH_TYPE.BEARER
|
|
? 'Authorization'
|
|
: config.headerName || existing?.authConfig.headerName || ''
|
|
const canKeepSecret = existing && authType === existing.authType
|
|
&& callbackUrl === existing.callbackUrl
|
|
&& (authType !== AUTO_LISTING_AUTH_TYPE.HEADER || headerName === existing.authConfig.headerName)
|
|
|
|
let authConfig: Record<string, string> = {}
|
|
if (authType !== AUTO_LISTING_AUTH_TYPE.NONE) {
|
|
const secret = authType === AUTO_LISTING_AUTH_TYPE.BEARER ? config.token : config.headerValue
|
|
if (!secret && canKeepSecret && existing.authConfig.secretCiphertext) {
|
|
authConfig = existing.authConfig
|
|
} else {
|
|
const savedSecret = canKeepSecret
|
|
? (authType === AUTO_LISTING_AUTH_TYPE.BEARER ? existing.authConfig.token : existing.authConfig.headerValue)
|
|
: undefined
|
|
const nextSecret = secret || savedSecret
|
|
if (!nextSecret || !headerName) {
|
|
throw new AutoListingCallbackError('请填写回调鉴权凭据,更改地址或鉴权方式后需重新填写')
|
|
}
|
|
validateCallbackAuth(headerName, authType === AUTO_LISTING_AUTH_TYPE.BEARER ? `Bearer ${nextSecret}` : nextSecret)
|
|
authConfig = encryptCallbackSecret(nextSecret)
|
|
if (authType === AUTO_LISTING_AUTH_TYPE.HEADER) authConfig.headerName = headerName
|
|
}
|
|
}
|
|
|
|
return {
|
|
name,
|
|
callbackUrl,
|
|
isActive: input.isActive ?? existing?.isActive ?? true,
|
|
authType,
|
|
authConfig,
|
|
eventTypes: normalizeEventTypes(input.eventTypes ?? existing?.eventTypes),
|
|
}
|
|
}
|
|
|
|
export async function getExternalNotificationTargetById(targetId: string) {
|
|
const rows = await queryRaw<any>(
|
|
`
|
|
SELECT
|
|
id,
|
|
name,
|
|
callback_url AS "callbackUrl",
|
|
is_active AS "isActive",
|
|
auth_type AS "authType",
|
|
auth_config AS "authConfig",
|
|
event_types AS "eventTypes",
|
|
created_at AS "createdAt",
|
|
updated_at AS "updatedAt"
|
|
FROM "${TARGET_TABLE}"
|
|
WHERE id = $1
|
|
LIMIT 1
|
|
`,
|
|
targetId,
|
|
)
|
|
|
|
return rows[0] ? normalizeTargetRow(rows[0]) : null
|
|
}
|
|
|
|
export async function createExternalNotificationTarget(input: ExternalNotificationTargetInput) {
|
|
const normalized = await normalizeTargetInput(input)
|
|
await ensureExternalNotificationTables()
|
|
ensureExternalNotificationWorkerStarted()
|
|
const targetId = randomUUID()
|
|
|
|
await executeRaw(
|
|
`
|
|
INSERT INTO "${TARGET_TABLE}" (
|
|
id,
|
|
name,
|
|
callback_url,
|
|
is_active,
|
|
auth_type,
|
|
auth_config,
|
|
event_types,
|
|
created_at,
|
|
updated_at
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7::jsonb, NOW(), NOW())
|
|
`,
|
|
targetId,
|
|
normalized.name,
|
|
normalized.callbackUrl,
|
|
normalized.isActive,
|
|
normalized.authType,
|
|
asJson(normalized.authConfig, '{}'),
|
|
asJson(normalized.eventTypes, '[]'),
|
|
)
|
|
|
|
const created = await getExternalNotificationTargetById(targetId)
|
|
if (!created) {
|
|
throw new Error('创建通知目标失败')
|
|
}
|
|
|
|
return created
|
|
}
|
|
|
|
export async function listExternalNotificationTargets() {
|
|
await ensureExternalNotificationTables()
|
|
|
|
const rows = await queryRaw<any>(
|
|
`
|
|
SELECT
|
|
id,
|
|
name,
|
|
callback_url AS "callbackUrl",
|
|
is_active AS "isActive",
|
|
auth_type AS "authType",
|
|
auth_config AS "authConfig",
|
|
event_types AS "eventTypes",
|
|
created_at AS "createdAt",
|
|
updated_at AS "updatedAt"
|
|
FROM "${TARGET_TABLE}"
|
|
ORDER BY created_at ASC, name ASC
|
|
`,
|
|
)
|
|
|
|
return rows.map((row) => normalizeTargetRow(row))
|
|
}
|
|
|
|
export async function updateExternalNotificationTarget(
|
|
targetId: string,
|
|
input: Partial<ExternalNotificationTargetInput>,
|
|
) {
|
|
await ensureExternalNotificationTables()
|
|
ensureExternalNotificationWorkerStarted()
|
|
|
|
const existing = await getExternalNotificationTargetById(targetId)
|
|
if (!existing) return null
|
|
|
|
const normalized = await normalizeTargetInput(input, existing)
|
|
|
|
await executeRaw(
|
|
`
|
|
UPDATE "${TARGET_TABLE}"
|
|
SET
|
|
name = $2,
|
|
callback_url = $3,
|
|
is_active = COALESCE($4, is_active),
|
|
auth_type = $5,
|
|
auth_config = $6::jsonb,
|
|
event_types = $7::jsonb,
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
`,
|
|
targetId,
|
|
normalized.name,
|
|
normalized.callbackUrl,
|
|
input.isActive ?? null,
|
|
normalized.authType,
|
|
asJson(normalized.authConfig, '{}'),
|
|
asJson(normalized.eventTypes, '[]'),
|
|
)
|
|
|
|
return getExternalNotificationTargetById(targetId)
|
|
}
|
|
|
|
export async function setExternalNotificationTargetActive(targetId: string, isActive: boolean) {
|
|
await ensureExternalNotificationTables()
|
|
const updated = await executeRaw(
|
|
`UPDATE "${TARGET_TABLE}" SET is_active = $2, updated_at = NOW() WHERE id = $1`,
|
|
targetId,
|
|
isActive,
|
|
)
|
|
if (!updated) return null
|
|
ensureExternalNotificationWorkerStarted()
|
|
return getExternalNotificationTargetById(targetId)
|
|
}
|
|
|
|
export async function testExternalNotificationTarget(targetId: string) {
|
|
await ensureExternalNotificationTables()
|
|
const target = await getExternalNotificationTargetById(targetId)
|
|
if (!target) return null
|
|
|
|
const statusCode = await postAutoListingCallback(target.callbackUrl, buildNotificationHeaders(target), {
|
|
eventId: randomUUID(),
|
|
eventType: 'auto-listing.callback.test',
|
|
test: true,
|
|
occurredAt: new Date().toISOString(),
|
|
})
|
|
|
|
return {
|
|
statusCode,
|
|
error: summarizeAutoListingCallbackError(null, statusCode),
|
|
}
|
|
}
|
|
|
|
export async function listExternalNotificationDeliveries(options?: {
|
|
canAccessOperationsG?: boolean
|
|
status?: string
|
|
targetId?: string
|
|
materialId?: string
|
|
query?: string
|
|
limit?: number
|
|
}) {
|
|
await ensureExternalNotificationTables()
|
|
|
|
const conditions = ['1 = 1']
|
|
const params: any[] = []
|
|
if (!options?.canAccessOperationsG) {
|
|
conditions.push(`NOT EXISTS (SELECT 1 FROM materials m WHERE m.id = d.material_id AND m.access_scope = 'operations_g')`)
|
|
conditions.push(`NOT EXISTS (SELECT 1 FROM material_purge_jobs p WHERE p.material_id = d.material_id AND p.material_snapshot->>'accessScope' = 'operations_g')`)
|
|
}
|
|
|
|
if (options?.status) {
|
|
params.push(String(options.status).trim())
|
|
conditions.push(`d.status = $${params.length}`)
|
|
}
|
|
|
|
if (options?.targetId) {
|
|
params.push(String(options.targetId).trim())
|
|
conditions.push(`d.target_id = $${params.length}`)
|
|
}
|
|
|
|
if (options?.materialId) {
|
|
params.push(String(options.materialId).trim())
|
|
conditions.push(`d.material_id = $${params.length}`)
|
|
}
|
|
|
|
const query = options?.query?.trim()
|
|
if (query) {
|
|
params.push(query)
|
|
const key = '$' + params.length
|
|
conditions.push(`(d.material_id = ${key} OR d.task_no = UPPER(${key})
|
|
OR d.payload->>'projectId' = ${key} OR d.payload->>'eventId' = ${key})`)
|
|
}
|
|
|
|
const limit = Number.isFinite(options?.limit) && Number(options?.limit) > 0
|
|
? Math.min(Number(options?.limit), 200)
|
|
: 100
|
|
params.push(limit)
|
|
|
|
const rows = await queryRaw<any>(
|
|
`
|
|
SELECT
|
|
d.id,
|
|
d.target_id AS "targetId",
|
|
t.name AS "targetName",
|
|
d.event_type AS "eventType",
|
|
d.material_id AS "materialId",
|
|
d.material_type AS "materialType",
|
|
d.task_no AS "taskNo",
|
|
d.status,
|
|
d.attempt_count AS "attemptCount",
|
|
d.max_attempts AS "maxAttempts",
|
|
d.next_retry_at AS "nextRetryAt",
|
|
d.last_status_code AS "lastStatusCode",
|
|
d.last_response_body AS "lastResponseBody",
|
|
d.last_error AS "lastError",
|
|
d.payload,
|
|
d.created_at AS "createdAt",
|
|
d.updated_at AS "updatedAt",
|
|
d.completed_at AS "completedAt"
|
|
FROM "${DELIVERY_TABLE}" d
|
|
LEFT JOIN "${TARGET_TABLE}" t ON t.id = d.target_id
|
|
WHERE ${conditions.join(' AND ')}
|
|
ORDER BY d.created_at DESC
|
|
LIMIT $${params.length}
|
|
`,
|
|
...params,
|
|
)
|
|
|
|
return rows.map((row) => normalizeDeliveryRow(row))
|
|
}
|
|
|
|
async function executeRaw(sql: string, ...params: any[]) {
|
|
return prisma.$executeRawUnsafe(sql, ...params)
|
|
}
|
|
|
|
async function queryRaw<T>(sql: string, ...params: any[]) {
|
|
return prisma.$queryRawUnsafe(sql, ...params) as Promise<T[]>
|
|
}
|
|
|
|
export type XiaoyiOutcomeKind = XiaoyiDeliveryKind
|
|
|
|
export interface XiaoyiAutoListingEvent {
|
|
materialId: string
|
|
materialType: string
|
|
outcomeKind: XiaoyiOutcomeKind
|
|
projectId: string
|
|
revisionId: string
|
|
}
|
|
|
|
export async function queueXiaoyiAutoListingNotification(
|
|
tx: Pick<Prisma.TransactionClient, 'xiaoyiAutoListingOutbox'>,
|
|
event: XiaoyiAutoListingEvent,
|
|
) {
|
|
if (!event.materialId || !event.projectId || XIAOYI_DELIVERY_MATERIAL_TYPES[event.outcomeKind] !== event.materialType) {
|
|
throw new Error('小壹交付通知参数无效')
|
|
}
|
|
await tx.xiaoyiAutoListingOutbox.create({ data: event })
|
|
}
|
|
|
|
export function wakeXiaoyiAutoListingNotifications() {
|
|
ensureExternalNotificationWorkerStarted()
|
|
wakeDeliveryWorker()
|
|
}
|
|
|
|
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 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 (COALESCE(d.dedupe_key,d.material_id)=e.material_id AND d.created_at>=e.created_at))
|
|
)
|
|
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
|
|
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() {
|
|
await ensureExternalNotificationTables()
|
|
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 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, 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
|
|
}
|
|
|
|
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() {
|
|
ensureExternalNotificationWorkerStarted()
|
|
}
|
|
|
|
function ensureExternalNotificationWorkerStarted() {
|
|
if (isWorkerStarted) return
|
|
isWorkerStarted = true
|
|
setTimeout(wakeDeliveryWorker, 1000).unref?.()
|
|
setInterval(wakeDeliveryWorker, RECOVERY_INTERVAL_MS).unref?.()
|
|
}
|
|
|
|
function buildNotificationHeaders(target: ExternalNotificationTarget) {
|
|
const headers = { 'Content-Type': 'application/json' }
|
|
if (target.authType === AUTO_LISTING_AUTH_TYPE.NONE) return headers
|
|
|
|
const isBearer = target.authType === AUTO_LISTING_AUTH_TYPE.BEARER
|
|
const { authConfig } = target
|
|
const headerName = isBearer ? 'Authorization' : authConfig.headerName
|
|
const secret = authConfig.secretCiphertext
|
|
? decryptCallbackSecret(authConfig)
|
|
: (isBearer ? authConfig.token : authConfig.headerValue)
|
|
if (!secret || !headerName) throw new AutoListingCallbackError('回调鉴权凭据不可用,请重新填写', 503)
|
|
|
|
const headerValue = isBearer ? `Bearer ${secret}` : secret
|
|
validateCallbackAuth(headerName, headerValue)
|
|
return { ...headers, [headerName]: headerValue }
|
|
}
|
|
|
|
async function buildTaskDetailNotificationPayload(materialId: string) {
|
|
const material = await prisma.material.findFirst({
|
|
where: {
|
|
id: materialId,
|
|
deletedAt: null,
|
|
materialType: '任务-详情',
|
|
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
|
isFullSet: true,
|
|
},
|
|
select: {
|
|
id: true,
|
|
taskNo: true,
|
|
productModel: true,
|
|
categoryName: true,
|
|
sceneName: true,
|
|
materialType: true,
|
|
previewUrl: true,
|
|
isFullSet: true,
|
|
createdAt: true,
|
|
assets: {
|
|
where: {
|
|
assetType: {
|
|
in: ['main-preview', 'sku-preview', 'detail-preview'],
|
|
},
|
|
},
|
|
orderBy: { sortOrder: 'asc' },
|
|
select: {
|
|
id: true,
|
|
assetType: true,
|
|
fileUrl: true,
|
|
fileName: true,
|
|
sortOrder: true,
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
if (!material) {
|
|
return null
|
|
}
|
|
|
|
const mapPreviewAssets = (assetType: 'main-preview' | 'sku-preview' | 'detail-preview') =>
|
|
material.assets
|
|
.filter((asset: any) => asset.assetType === assetType)
|
|
.sort((left: any, right: any) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0))
|
|
.map((asset: any) => ({
|
|
id: String(asset.id),
|
|
url: String(asset.fileUrl || ''),
|
|
fileName: String(asset.fileName || ''),
|
|
sortOrder: Number(asset.sortOrder || 0),
|
|
}))
|
|
|
|
return {
|
|
eventId: randomUUID(),
|
|
eventType: AUTO_LISTING_EVENT_TYPE,
|
|
materialId: material.id,
|
|
materialType: material.materialType,
|
|
taskNo: material.taskNo,
|
|
productModel: material.productModel,
|
|
categoryName: material.categoryName,
|
|
shopName: material.categoryName,
|
|
sceneName: material.sceneName,
|
|
isFullSet: Boolean(material.isFullSet),
|
|
occurredAt: material.createdAt.toISOString(),
|
|
pullUrl: `${getPublicAppOrigin()}/api/external/product-assets?materialId=${material.id}`,
|
|
coverPreviewUrl: material.previewUrl || null,
|
|
previewAssets: {
|
|
main: mapPreviewAssets('main-preview'),
|
|
sku: mapPreviewAssets('sku-preview'),
|
|
detail: mapPreviewAssets('detail-preview'),
|
|
},
|
|
}
|
|
}
|
|
|
|
async function buildTaskDetailBarcodeNotificationPayload(materialId: string, assetIds: string[]) {
|
|
const normalizedAssetIds = Array.from(new Set(assetIds.map((assetId) => String(assetId || '').trim()).filter(Boolean)))
|
|
if (normalizedAssetIds.length === 0) {
|
|
return null
|
|
}
|
|
|
|
const material = await prisma.material.findFirst({
|
|
where: {
|
|
id: materialId,
|
|
deletedAt: null,
|
|
materialType: '任务-详情',
|
|
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
|
},
|
|
select: {
|
|
id: true,
|
|
taskNo: true,
|
|
productModel: true,
|
|
categoryName: true,
|
|
sceneName: true,
|
|
materialType: true,
|
|
authorName: true,
|
|
createdAt: true,
|
|
user: {
|
|
select: {
|
|
realName: true,
|
|
username: true,
|
|
},
|
|
},
|
|
assets: {
|
|
where: {
|
|
id: { in: normalizedAssetIds },
|
|
assetType: 'sku-preview',
|
|
},
|
|
orderBy: [
|
|
{ createdAt: 'desc' },
|
|
{ sortOrder: 'asc' },
|
|
],
|
|
select: {
|
|
id: true,
|
|
fileUrl: true,
|
|
fileName: true,
|
|
sortOrder: true,
|
|
skuCode: true,
|
|
createdAt: true,
|
|
updatedAt: true,
|
|
barcodes: {
|
|
select: {
|
|
barcode: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
if (!material || material.assets.length === 0) {
|
|
return null
|
|
}
|
|
|
|
const barcodes = Array.from(
|
|
new Set(
|
|
material.assets.flatMap((asset: any) =>
|
|
(asset.barcodes || []).map((item: any) => String(item.barcode || '').trim()).filter(Boolean),
|
|
),
|
|
),
|
|
)
|
|
|
|
const latestBarcodeRecords = await prisma.materialAssetBarcode.findMany({
|
|
where: {
|
|
barcode: { in: barcodes },
|
|
asset: {
|
|
assetType: 'sku-preview',
|
|
material: {
|
|
deletedAt: null,
|
|
materialType: '任务-详情',
|
|
...EXTERNAL_MATERIAL_SCOPE_WHERE,
|
|
},
|
|
},
|
|
},
|
|
select: {
|
|
barcode: true,
|
|
assetId: true,
|
|
asset: {
|
|
select: {
|
|
createdAt: true,
|
|
sortOrder: true,
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
const latestAssetByBarcode = new Map<string, string>()
|
|
const latestMetaByBarcode = new Map<string, { createdAt: Date; sortOrder: number }>()
|
|
|
|
for (const record of latestBarcodeRecords) {
|
|
const barcode = String(record.barcode || '').trim()
|
|
if (!barcode || !record.asset) {
|
|
continue
|
|
}
|
|
|
|
const nextMeta = {
|
|
createdAt: record.asset.createdAt,
|
|
sortOrder: Number(record.asset.sortOrder || 0),
|
|
}
|
|
const currentMeta = latestMetaByBarcode.get(barcode)
|
|
if (!currentMeta || compareBarcodeTimeline(nextMeta, currentMeta) < 0) {
|
|
latestMetaByBarcode.set(barcode, nextMeta)
|
|
latestAssetByBarcode.set(barcode, String(record.assetId))
|
|
}
|
|
}
|
|
|
|
const uploaderName =
|
|
material.user?.realName || material.user?.username || material.authorName || ''
|
|
|
|
const items = material.assets.flatMap((asset: any) => {
|
|
const assetBarcodes: string[] = Array.from(
|
|
new Set((asset.barcodes || []).map((item: any) => String(item.barcode || '').trim()).filter(Boolean)),
|
|
)
|
|
|
|
return assetBarcodes.map((barcode) => ({
|
|
materialId: material.id,
|
|
assetId: String(asset.id),
|
|
skuCode: asset.skuCode || null,
|
|
barcode,
|
|
previewUrl: String(asset.fileUrl || ''),
|
|
fileName: String(asset.fileName || ''),
|
|
sortOrder: Number(asset.sortOrder || 0),
|
|
uploadedAt: asset.createdAt.toISOString(),
|
|
updatedAt: asset.updatedAt.toISOString(),
|
|
uploaderName,
|
|
isLatest: latestAssetByBarcode.get(barcode) === String(asset.id),
|
|
lookupUrl: buildBarcodeLookupUrl(barcode),
|
|
}))
|
|
})
|
|
|
|
return {
|
|
eventId: randomUUID(),
|
|
eventType: TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE,
|
|
materialId: material.id,
|
|
materialType: material.materialType,
|
|
taskNo: material.taskNo,
|
|
productModel: material.productModel,
|
|
categoryName: material.categoryName,
|
|
shopName: material.categoryName,
|
|
sceneName: material.sceneName,
|
|
occurredAt: new Date().toISOString(),
|
|
items,
|
|
}
|
|
}
|
|
|
|
export async function queueTaskDetailFullSetNotification(materialId: string) {
|
|
await ensureExternalNotificationTables()
|
|
ensureExternalNotificationWorkerStarted()
|
|
|
|
const payload = await buildTaskDetailNotificationPayload(materialId)
|
|
if (!payload) {
|
|
return []
|
|
}
|
|
|
|
return enqueueNotificationDeliveries({
|
|
eventType: AUTO_LISTING_EVENT_TYPE,
|
|
materialId: payload.materialId,
|
|
materialType: payload.materialType,
|
|
taskNo: payload.taskNo,
|
|
dedupeKey: payload.materialId,
|
|
payload,
|
|
})
|
|
}
|
|
|
|
export async function queueTaskDetailBarcodeImagesUpdatedNotification(
|
|
materialId: string,
|
|
assetIds: string[],
|
|
) {
|
|
await ensureExternalNotificationTables()
|
|
ensureExternalNotificationWorkerStarted()
|
|
|
|
const normalizedAssetIds = Array.from(new Set(assetIds.map((assetId) => String(assetId || '').trim()).filter(Boolean)))
|
|
const payload = await buildTaskDetailBarcodeNotificationPayload(materialId, normalizedAssetIds)
|
|
if (!payload || payload.items.length === 0) {
|
|
return []
|
|
}
|
|
|
|
return enqueueNotificationDeliveries({
|
|
eventType: TASK_DETAIL_BARCODE_IMAGES_UPDATED_EVENT_TYPE,
|
|
materialId: payload.materialId,
|
|
materialType: payload.materialType,
|
|
taskNo: payload.taskNo,
|
|
dedupeKey: payload.eventId,
|
|
payload,
|
|
})
|
|
}
|
|
|
|
export async function retryExternalNotificationDelivery(deliveryId: string, actorId: string) {
|
|
await ensureExternalNotificationTables()
|
|
const result = await prisma.$transaction(async tx => {
|
|
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
|
|
`
|
|
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<>'succeeded'
|
|
AND (status<>'processing' OR COALESCE(lease_expires_at,updated_at + INTERVAL '10 minutes') <= NOW())
|
|
`
|
|
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()
|
|
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
|
|
}
|