From b48509c34f85184679040527df55fa0fe5698515 Mon Sep 17 00:00:00 2001 From: yml Date: Tue, 17 Nov 2026 20:01:20 +0800 Subject: [PATCH] =?UTF-8?q?feat(fulfillment):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=96=97=E9=B1=BC=E5=B7=A5=E4=BD=9C=E5=8F=B0=E5=8F=8C=E5=90=91?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.server.example | 3 +- apps/backend/src/app.integration.test.ts | 46 ++++ apps/backend/src/app.ts | 2 + .../platform-fulfillment-integration.ts | 51 ++++ .../douyu-fulfillment-service.ts | 244 +++++++++++++----- .../douyu-fulfillment.test.ts | 15 +- .../douyu-fulfillment/live-hub-notifier.ts | 54 ++++ 7 files changed, 355 insertions(+), 60 deletions(-) create mode 100644 apps/backend/src/routes/platform-fulfillment-integration.ts create mode 100644 apps/backend/src/services/douyu-fulfillment/live-hub-notifier.ts diff --git a/.env.server.example b/.env.server.example index fd838293..4eb4154f 100644 --- a/.env.server.example +++ b/.env.server.example @@ -24,7 +24,8 @@ HTTP_TRUST_PROXY=1 # Claim Links CLAIM_BASE_URL=https://order.khhao.com/h5 -LIVE_HUB_PLATFORM_FULFILLMENT_URL=https://live.khhao.com +# 生产服务器间优先走私网;直播运营后台私网地址为 172.23.71.41 +LIVE_HUB_PLATFORM_FULFILLMENT_URL=http://172.23.71.41 PLATFORM_FULFILLMENT_INTEGRATION_KEY= CLAIM_TOKEN_TTL_HOURS=0 diff --git a/apps/backend/src/app.integration.test.ts b/apps/backend/src/app.integration.test.ts index 06b8be0d..e045d3fd 100644 --- a/apps/backend/src/app.integration.test.ts +++ b/apps/backend/src/app.integration.test.ts @@ -38,3 +38,49 @@ test('HTTP health route and explicit CORS preflight', async () => { await once(server, 'close') } }) + +test('履约状态集成接口要求密钥并接受空快照', async () => { + const previousKey = process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY + process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY = 'integration-test-key' + const startupState = createStartupState() + startupState.core.ready = true + const config = createDefaultRuntimeConfig('/tmp/order-site') + const server = createApp({ + startupState, + isShutdownStarted: () => false, + config, + }).listen(0, '127.0.0.1') + await once(server, 'listening') + + try { + const address = server.address() + assert.ok(address && typeof address === 'object') + const endpoint = `http://127.0.0.1:${address.port}/api/integration/platform-fulfillment/binding-state` + + const unauthorized = await fetch(endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ items: [] }), + }) + assert.equal(unauthorized.status, 401) + + const accepted = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Integration-Key': 'integration-test-key', + }, + body: JSON.stringify({ items: [] }), + }) + assert.equal(accepted.status, 200) + assert.deepEqual((await accepted.json()).data, { received: 0, updated: 0 }) + } finally { + if (previousKey === undefined) { + delete process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY + } else { + process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY = previousKey + } + server.close() + await once(server, 'close') + } +}) diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index c16b4f2a..504c7c97 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -15,6 +15,7 @@ import douyuFulfillmentRouter from './routes/douyu-fulfillment.js' import kuaishouIndustryRouter from './routes/kuaishou-industry.js' import open91Router from './routes/open-91.js' import pddExtensionRouter from './routes/pdd-extension.js' +import platformFulfillmentIntegrationRouter from './routes/platform-fulfillment-integration.js' import redeemRouter from './routes/redeem.js' import shortLinksRouter from './routes/short-links.js' import semiAutoInjectionsRouter from './routes/semi-auto-injections.js' @@ -117,6 +118,7 @@ export function createApp({ startupState, isShutdownStarted, config }: CreateApp app.use('/api/v1/open/affiliate-dash', affiliateDashRouter) app.use('/api/v1/open/91', open91Router) app.use('/api/v1/open/kuaishou-industry', kuaishouIndustryRouter) + app.use('/api/integration', platformFulfillmentIntegrationRouter) app.use('/api/v1/redeem', redeemRouter) app.use('/api/v1/claim', claimsRouter) app.use('/api/v1/customer-fulfillment', customerFulfillmentRouter) diff --git a/apps/backend/src/routes/platform-fulfillment-integration.ts b/apps/backend/src/routes/platform-fulfillment-integration.ts new file mode 100644 index 00000000..a522379c --- /dev/null +++ b/apps/backend/src/routes/platform-fulfillment-integration.ts @@ -0,0 +1,51 @@ +import { timingSafeEqual } from 'node:crypto' + +import { Router } from 'express' + +import { applyLiveBindingStateSnapshot } from '../services/douyu-fulfillment/douyu-fulfillment-service.js' +import { createRouteHandler } from '../utils/http.js' + +const router = Router() + +router.use('/platform-fulfillment', (req, res, next) => { + const expected = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim() + if (!expected) { + res.status(503).json({ + code: 1, + msg: '直播账号履约集成密钥未配置', + errorCode: 'integration_not_configured', + time: Math.floor(Date.now() / 1000), + data: null, + }) + return + } + + const provided = String(req.header('x-integration-key') || '').trim() + const expectedBuffer = Buffer.from(expected) + const providedBuffer = Buffer.from(provided) + if ( + expectedBuffer.length !== providedBuffer.length || + !timingSafeEqual(expectedBuffer, providedBuffer) + ) { + res.status(401).json({ + code: 1, + msg: '直播账号履约集成鉴权失败', + errorCode: 'integration_unauthorized', + time: Math.floor(Date.now() / 1000), + data: null, + }) + return + } + next() +}) + +router.post( + '/platform-fulfillment/binding-state', + createRouteHandler((req) => applyLiveBindingStateSnapshot(req.body), { + successMessage: '履约状态已同步', + errorMessage: '同步履约状态失败', + scope: '[integration/platform-fulfillment/binding-state]', + }), +) + +export default router diff --git a/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment-service.ts b/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment-service.ts index 84af31e2..ca002bd4 100644 --- a/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment-service.ts +++ b/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment-service.ts @@ -3,6 +3,8 @@ import type { PoolClient } from 'pg' import { query, withTransaction } from '../../db/client.js' import { nowIso } from '../../utils/time.js' import { createHttpError } from '../../utils/http.js' +import { logWarn } from '../../utils/logger.js' +import { notifyLiveHubOrderSyncAsync } from './live-hub-notifier.js' type DouyuTaskRow = { id: number @@ -65,6 +67,17 @@ type LiveBindingState = { updatedAt: string } +type LiveBindingBatchResponse = { + items: LiveBindingState[] +} + +const AUTO_DISCOVERY_INTERVAL_MS = 60_000 +const LIVE_STATE_SYNC_INTERVAL_MS = 60_000 +const TERMINAL_TASK_STATUSES = new Set(['completed', 'cancelled']) + +let lastAutomaticDiscoveryAt = 0 +let automaticDiscoveryInFlight: Promise<{ created: number; updated: number } | null> | null = null + const TASK_SELECT = ` SELECT task.*, @@ -217,9 +230,29 @@ export async function ensureDouyuFulfillmentTasks(orderNo = '') { } } }) + if (created > 0) { + notifyLiveHubOrderSyncAsync({ created, updated: candidates.rows.length - created }) + } return { created, updated: candidates.rows.length - created } } +async function ensureDouyuFulfillmentTasksAutomatically() { + if (automaticDiscoveryInFlight) return automaticDiscoveryInFlight + if (Date.now() - lastAutomaticDiscoveryAt < AUTO_DISCOVERY_INTERVAL_MS) return null + + lastAutomaticDiscoveryAt = Date.now() + const run = ensureDouyuFulfillmentTasks() + .catch((error) => { + lastAutomaticDiscoveryAt = 0 + throw error + }) + .finally(() => { + automaticDiscoveryInFlight = null + }) + automaticDiscoveryInFlight = run + return run +} + async function loadTaskByOrderNo(orderNo: string) { const normalized = String(orderNo || '').trim() if (!normalized) { @@ -309,69 +342,126 @@ function statusForLive(live: LiveBindingState): string { return 'preparing' } -async function applyLiveState(task: DouyuTaskRow, live: LiveBindingState) { +async function updateTaskFromLiveState( + client: Pick, + task: DouyuTaskRow, + live: LiveBindingState, + now: string, +) { const nextStatus = statusForLive(live) - const now = nowIso() + await client.query( + ` + UPDATE douyu_fulfillment_tasks + SET live_session_id = $2, + status = $3, + binding_phase = $4, + live_execution_status = $5, + live_binding_status = $6, + issue_code = $7, + last_error = $8, + bound_role_name = $9, + bound_area_name = $10, + bound_plat_name = $11, + binding_started_at = CASE + WHEN $12 <> '' THEN COALESCE(binding_started_at, NOW()) + ELSE binding_started_at + END, + bound_at = CASE + WHEN $13 THEN COALESCE(bound_at, NOW()) + ELSE bound_at + END, + completed_at = CASE + WHEN $14 THEN COALESCE(completed_at, NOW()) + ELSE completed_at + END, + last_synced_at = NOW(), + updated_at = $15 + WHERE id = $1 + `, + [ + task.id, + live.sessionId, + nextStatus, + live.bindPhase, + live.executionStatus, + live.bindingStatus, + live.issueCode, + live.message, + live.roleName, + live.areaName, + live.platName, + live.qrUrl, + live.bindConfirmed, + live.executionStatus === 'completed', + now, + ], + ) + if (nextStatus !== task.status) { + await appendEvent(client, task.id, 'status_changed', 'integration', { + fromStatus: task.status, + toStatus: nextStatus, + bindPhase: live.bindPhase, + }) + } +} + +async function applyLiveState(task: DouyuTaskRow, live: LiveBindingState) { await withTransaction(async (client) => { - await client.query( - ` - UPDATE douyu_fulfillment_tasks - SET live_session_id = $2, - status = $3, - binding_phase = $4, - live_execution_status = $5, - live_binding_status = $6, - issue_code = $7, - last_error = $8, - bound_role_name = $9, - bound_area_name = $10, - bound_plat_name = $11, - binding_started_at = CASE - WHEN $12 <> '' THEN COALESCE(binding_started_at, NOW()) - ELSE binding_started_at - END, - bound_at = CASE - WHEN $13 THEN COALESCE(bound_at, NOW()) - ELSE bound_at - END, - completed_at = CASE - WHEN $14 THEN COALESCE(completed_at, NOW()) - ELSE completed_at - END, - last_synced_at = NOW(), - updated_at = $15 - WHERE id = $1 - `, - [ - task.id, - live.sessionId, - nextStatus, - live.bindPhase, - live.executionStatus, - live.bindingStatus, - live.issueCode, - live.message, - live.roleName, - live.areaName, - live.platName, - live.qrUrl, - live.bindConfirmed, - live.executionStatus === 'completed', - now, - ], - ) - if (nextStatus !== task.status) { - await appendEvent(client, task.id, 'status_changed', 'integration', { - fromStatus: task.status, - toStatus: nextStatus, - bindPhase: live.bindPhase, - }) - } + await updateTaskFromLiveState(client, task, live, nowIso()) }) const updated = await loadTask(task.id) return { task: updated, live, comparison: compareCustomerRole(updated, live) } } +async function applyLiveStates(entries: Array<{ task: DouyuTaskRow; live: LiveBindingState }>) { + if (entries.length === 0) return + const now = nowIso() + await withTransaction(async (client) => { + for (const entry of entries) { + await updateTaskFromLiveState(client, entry.task, entry.live, now) + } + }) +} + +function isLiveBindingState(value: unknown): value is LiveBindingState { + if (!value || typeof value !== 'object') return false + const item = value as Partial + return ( + Number.isInteger(Number(item.sessionId)) && + Number(item.sessionId) > 0 && + typeof item.executionStatus === 'string' && + typeof item.bindingStatus === 'string' && + typeof item.exchangeStatus === 'string' && + typeof item.issueCode === 'string' && + typeof item.message === 'string' + ) +} + +export async function applyLiveBindingStateSnapshot(input: unknown) { + const rawItems = + input && typeof input === 'object' && Array.isArray((input as { items?: unknown }).items) + ? (input as { items: unknown[] }).items + : [] + const items = rawItems.filter(isLiveBindingState) + const sessionIds = Array.from( + new Set(items.map((item) => Number(item.sessionId)).filter((id) => id > 0)), + ) + if (sessionIds.length === 0) return { received: rawItems.length, updated: 0 } + + const tasks = await query( + `${TASK_SELECT} + WHERE task.live_session_id = ANY($1::bigint[])`, + [sessionIds], + ) + const taskBySessionId = new Map(tasks.rows.map((task) => [Number(task.live_session_id), task])) + const entries = items.flatMap((live) => { + const task = taskBySessionId.get(Number(live.sessionId)) + return task ? [{ task, live }] : [] + }) + await applyLiveStates(entries) + return { received: rawItems.length, updated: entries.length } +} + async function ensureLiveSession(task: DouyuTaskRow) { const live = await liveHubRequest( '/api/integration/platform-fulfillment/customer-sessions/ensure', @@ -504,6 +594,36 @@ export async function confirmDouyuCustomerBinding(orderNo: string) { return applyLiveState(task, live) } +async function syncLiveStatesForTasks(tasks: DouyuTaskRow[]) { + const now = Date.now() + const candidates = tasks.filter((task) => { + if (!task.live_session_id || TERMINAL_TASK_STATUSES.has(task.status)) return false + const lastSyncedAt = Date.parse(task.last_synced_at || '') + return !lastSyncedAt || now - lastSyncedAt >= LIVE_STATE_SYNC_INTERVAL_MS + }) + if (candidates.length === 0) return + + try { + const response = await liveHubRequest( + '/api/integration/platform-fulfillment/customer-sessions/status/batch', + { + method: 'POST', + body: { + task_ids: candidates.map((task) => Number(task.live_session_id)), + }, + }, + ) + const taskBySessionId = new Map(candidates.map((task) => [Number(task.live_session_id), task])) + const entries = response.items.flatMap((live) => { + const task = taskBySessionId.get(Number(live.sessionId)) + return task ? [{ task, live }] : [] + }) + await applyLiveStates(entries) + } catch (error) { + logWarn('[douyu-fulfillment]', '自动同步直播账号履约状态失败', { error }) + } +} + export async function listDouyuFulfillmentTasks( input: { keyword?: unknown @@ -512,7 +632,7 @@ export async function listDouyuFulfillmentTasks( pageSize?: unknown } = {}, ) { - await ensureDouyuFulfillmentTasks() + await ensureDouyuFulfillmentTasksAutomatically() const page = Math.max(1, Number(input.page || 1)) const pageSize = Math.max(1, Math.min(100, Number(input.pageSize || 20))) const keyword = String(input.keyword || '').trim() @@ -541,7 +661,15 @@ export async function listDouyuFulfillmentTasks( params, ) params.push(pageSize, (page - 1) * pageSize) - const rows = await query( + let rows = await query( + `${TASK_SELECT} + ${where} + ORDER BY task.updated_at DESC, task.id DESC + LIMIT $${params.length - 1} OFFSET $${params.length}`, + params, + ) + await syncLiveStatesForTasks(rows.rows) + rows = await query( `${TASK_SELECT} ${where} ORDER BY task.updated_at DESC, task.id DESC diff --git a/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment.test.ts b/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment.test.ts index 697721a3..77921153 100644 --- a/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment.test.ts +++ b/apps/backend/src/services/douyu-fulfillment/douyu-fulfillment.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { compareCustomerRole } from './douyu-fulfillment-service.js' +import { applyLiveBindingStateSnapshot, compareCustomerRole } from './douyu-fulfillment-service.js' const task = { customer_role_name: '狗鼻子弗尼亚bd', @@ -37,3 +37,16 @@ test('斗鱼客户资料角色名不一致时禁止确认', () => { assert.equal(result.matched, false) assert.equal(result.roleMatched, false) }) + +test('直播账号状态推送忽略空数据和无效任务', async () => { + assert.deepEqual(await applyLiveBindingStateSnapshot({ items: [] }), { + received: 0, + updated: 0, + }) + assert.deepEqual( + await applyLiveBindingStateSnapshot({ + items: [{ sessionId: 0 }, null, { sessionId: 'bad' }], + }), + { received: 3, updated: 0 }, + ) +}) diff --git a/apps/backend/src/services/douyu-fulfillment/live-hub-notifier.ts b/apps/backend/src/services/douyu-fulfillment/live-hub-notifier.ts new file mode 100644 index 00000000..458d1178 --- /dev/null +++ b/apps/backend/src/services/douyu-fulfillment/live-hub-notifier.ts @@ -0,0 +1,54 @@ +import { randomUUID } from 'node:crypto' + +import { logWarn } from '../../utils/logger.js' + +const PUBLISH_ATTEMPTS = 3 +const PUBLISH_TIMEOUT_MS = 5000 + +function liveHubBaseUrl() { + return String(process.env.LIVE_HUB_PLATFORM_FULFILLMENT_URL || '') + .trim() + .replace(/\/+$/, '') +} + +export function notifyLiveHubOrderSyncAsync(detail: Record = {}) { + const baseUrl = liveHubBaseUrl() + const integrationKey = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim() + if (!baseUrl || !integrationKey) return + + const event = { + eventId: randomUUID(), + occurredAt: new Date().toISOString(), + ...detail, + } + void publish(`${baseUrl}/api/integration/platform-fulfillment/events/order-sync`, event) +} + +async function publish(url: string, event: Record) { + const integrationKey = String(process.env.PLATFORM_FULFILLMENT_INTEGRATION_KEY || '').trim() + for (let attempt = 1; attempt <= PUBLISH_ATTEMPTS; attempt += 1) { + try { + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Integration-Key': integrationKey, + }, + body: JSON.stringify(event), + signal: AbortSignal.timeout(PUBLISH_TIMEOUT_MS), + }) + if (response.ok) return + throw new Error(`live-hub 返回 HTTP ${response.status}`) + } catch (error) { + if (attempt >= PUBLISH_ATTEMPTS) { + logWarn('[douyu-fulfillment]', '推送 live-hub 订单同步事件失败', { + eventId: event.eventId, + attempts: attempt, + error, + }) + return + } + await new Promise((resolve) => setTimeout(resolve, attempt * 500)) + } + } +}