优化(直播履约): 改为订单快照事件驱动
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
import type { PoolClient } from 'pg'
|
||||
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { publishRealtimeEvent } from '../realtime/realtime-event-service.js'
|
||||
import {
|
||||
publishCustomerOrderRealtimeChange,
|
||||
publishRealtimeEvent,
|
||||
} from '../realtime/realtime-event-service.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
@@ -36,6 +39,7 @@ type DouyuTaskRow = {
|
||||
bound_at: string | null
|
||||
completed_at: string | null
|
||||
last_synced_at: string | null
|
||||
live_state_version: number | string
|
||||
qr_url: string
|
||||
qr_generated_at: string | null
|
||||
qr_expires_at: string | null
|
||||
@@ -74,6 +78,7 @@ type LiveBindingState = {
|
||||
bindConfirmed: boolean
|
||||
customerProfileReset?: boolean
|
||||
resetReason?: string
|
||||
stateVersion?: number | string
|
||||
completedAt: string | null
|
||||
updatedAt: string
|
||||
}
|
||||
@@ -272,6 +277,7 @@ export async function ensureDouyuFulfillmentTasks(orderNo = '') {
|
||||
if (candidates.rows.length === 0) return { created: 0, updated: 0 }
|
||||
|
||||
let created = 0
|
||||
const createdOrderNos = new Set<string>()
|
||||
await withTransaction(async (client) => {
|
||||
for (const row of candidates.rows) {
|
||||
const inserted = await client.query<{ id: number; inserted: boolean }>(
|
||||
@@ -298,12 +304,16 @@ export async function ensureDouyuFulfillmentTasks(orderNo = '') {
|
||||
if (!taskId) continue
|
||||
if (inserted.rows[0]?.inserted) {
|
||||
created += 1
|
||||
createdOrderNos.add(row.platform_order_id)
|
||||
await appendEvent(client, taskId, 'task_created', 'system', {
|
||||
platformOrderId: row.platform_order_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
for (const platformOrderId of createdOrderNos) {
|
||||
publishCustomerOrderRealtimeChange(platformOrderId, 'douyu_fulfillment_task_created')
|
||||
}
|
||||
return { created, updated: candidates.rows.length - created }
|
||||
}
|
||||
|
||||
@@ -424,6 +434,12 @@ export function statusForLive(live: LiveBindingState): string {
|
||||
return 'preparing'
|
||||
}
|
||||
|
||||
export function isStaleLiveStateVersion(current: unknown, incoming: unknown) {
|
||||
const currentVersion = Math.max(0, Math.trunc(Number(current || 0)))
|
||||
const incomingVersion = Math.max(0, Math.trunc(Number(incoming || 0)))
|
||||
return incomingVersion > 0 && incomingVersion < currentVersion
|
||||
}
|
||||
|
||||
async function updateTaskFromLiveState(
|
||||
client: Pick<PoolClient, 'query'>,
|
||||
task: DouyuTaskRow,
|
||||
@@ -432,6 +448,27 @@ async function updateTaskFromLiveState(
|
||||
) {
|
||||
const resetCustomerProfile = live.customerProfileReset === true
|
||||
const nextStatus = statusForLive(live)
|
||||
const incomingVersion = Math.max(0, Math.trunc(Number(live.stateVersion || 0)))
|
||||
const currentVersion = Math.max(0, Math.trunc(Number(task.live_state_version || 0)))
|
||||
if (isStaleLiveStateVersion(currentVersion, incomingVersion)) {
|
||||
return false
|
||||
}
|
||||
const changed =
|
||||
incomingVersion > currentVersion ||
|
||||
Number(task.live_session_id || 0) !== Number(live.sessionId || 0) ||
|
||||
task.status !== nextStatus ||
|
||||
task.binding_phase !== live.bindPhase ||
|
||||
task.live_execution_status !== live.executionStatus ||
|
||||
task.live_binding_status !== live.bindingStatus ||
|
||||
task.issue_code !== live.issueCode ||
|
||||
task.last_error !== live.message ||
|
||||
task.bound_role_name !== live.roleName ||
|
||||
task.bound_area_name !== live.areaName ||
|
||||
task.bound_plat_name !== live.platName ||
|
||||
task.qr_url !== live.qrUrl ||
|
||||
normalizeLiveTimestamp(task.qr_generated_at) !== normalizeLiveTimestamp(live.qrGeneratedAt) ||
|
||||
normalizeLiveTimestamp(task.qr_expires_at) !== normalizeLiveTimestamp(live.qrExpiresAt) ||
|
||||
resetCustomerProfile
|
||||
await client.query(
|
||||
`
|
||||
UPDATE douyu_fulfillment_tasks
|
||||
@@ -466,6 +503,7 @@ async function updateTaskFromLiveState(
|
||||
qr_url = $15,
|
||||
qr_generated_at = NULLIF($16, '')::timestamptz,
|
||||
qr_expires_at = NULLIF($17, '')::timestamptz,
|
||||
live_state_version = GREATEST(live_state_version, $20),
|
||||
last_synced_at = NOW(),
|
||||
updated_at = $18
|
||||
WHERE id = $1
|
||||
@@ -490,6 +528,7 @@ async function updateTaskFromLiveState(
|
||||
live.qrExpiresAt,
|
||||
now,
|
||||
resetCustomerProfile,
|
||||
incomingVersion,
|
||||
],
|
||||
)
|
||||
if (nextStatus !== task.status) {
|
||||
@@ -504,24 +543,35 @@ async function updateTaskFromLiveState(
|
||||
reason: String(live.resetReason || ''),
|
||||
})
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
async function applyLiveState(task: DouyuTaskRow, live: LiveBindingState) {
|
||||
let changed = false
|
||||
await withTransaction(async (client) => {
|
||||
await updateTaskFromLiveState(client, task, live, nowIso())
|
||||
changed = await updateTaskFromLiveState(client, task, live, nowIso())
|
||||
})
|
||||
const updated = await loadTask(task.id)
|
||||
if (changed) {
|
||||
publishCustomerOrderRealtimeChange(updated.platform_order_id, 'douyu_binding_state_changed')
|
||||
}
|
||||
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()
|
||||
const changedOrderNos = new Set<string>()
|
||||
await withTransaction(async (client) => {
|
||||
for (const entry of entries) {
|
||||
await updateTaskFromLiveState(client, entry.task, entry.live, now)
|
||||
if (await updateTaskFromLiveState(client, entry.task, entry.live, now)) {
|
||||
changedOrderNos.add(entry.task.platform_order_id)
|
||||
}
|
||||
}
|
||||
})
|
||||
for (const platformOrderId of changedOrderNos) {
|
||||
publishCustomerOrderRealtimeChange(platformOrderId, 'douyu_binding_state_changed')
|
||||
}
|
||||
}
|
||||
|
||||
function isLiveBindingState(value: unknown): value is LiveBindingState {
|
||||
@@ -563,10 +613,21 @@ function liveBindingStateFromTask(task: DouyuTaskRow): LiveBindingState {
|
||||
bindReadyForConfirm: task.status === 'role_ready',
|
||||
bindConfirmed: ['bound', 'waiting_operator', 'processing', 'completed'].includes(task.status),
|
||||
completedAt: task.completed_at,
|
||||
stateVersion: Number(task.live_state_version || 0),
|
||||
updatedAt: task.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
function localCustomerFulfillment(task: DouyuTaskRow) {
|
||||
const live = liveBindingStateFromTask(task)
|
||||
return {
|
||||
task,
|
||||
live,
|
||||
comparison: compareCustomerRole(task, live),
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyLiveBindingStateSnapshot(
|
||||
input: unknown,
|
||||
options: { eventId?: string; eventType?: string } = {},
|
||||
@@ -612,7 +673,11 @@ export async function applyLiveBindingStateSnapshot(
|
||||
[eventId, String(options.eventType || '')],
|
||||
)
|
||||
if (claimed.rowCount === 0) {
|
||||
return { received: rawItems.length, updated: 0 }
|
||||
return {
|
||||
received: rawItems.length,
|
||||
updated: 0,
|
||||
changedOrderNos: new Set<string>(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -636,13 +701,21 @@ export async function applyLiveBindingStateSnapshot(
|
||||
taskByOrderItemId.get(String(live.sourceOrderItemId || ''))
|
||||
return task ? [{ task, live }] : []
|
||||
})
|
||||
let changedCount = 0
|
||||
const changedOrderNos = new Set<string>()
|
||||
for (const entry of entries) {
|
||||
await updateTaskFromLiveState(client, entry.task, entry.live, now)
|
||||
if (await updateTaskFromLiveState(client, entry.task, entry.live, now)) {
|
||||
changedCount += 1
|
||||
changedOrderNos.add(entry.task.platform_order_id)
|
||||
}
|
||||
}
|
||||
return { received: rawItems.length, updated: entries.length }
|
||||
return { received: rawItems.length, updated: changedCount, changedOrderNos }
|
||||
})
|
||||
|
||||
if (result.updated > 0) {
|
||||
for (const platformOrderId of result.changedOrderNos) {
|
||||
publishCustomerOrderRealtimeChange(platformOrderId, 'douyu_binding_state_changed')
|
||||
}
|
||||
publishRealtimeEvent({
|
||||
type: 'order.changed',
|
||||
entityId: 0,
|
||||
@@ -652,7 +725,14 @@ export async function applyLiveBindingStateSnapshot(
|
||||
admin: true,
|
||||
})
|
||||
}
|
||||
return result
|
||||
return { received: result.received, updated: result.updated }
|
||||
}
|
||||
|
||||
function normalizeLiveTimestamp(value: unknown) {
|
||||
const text = String(value || '').trim()
|
||||
if (!text) return ''
|
||||
const parsed = Date.parse(text)
|
||||
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : text
|
||||
}
|
||||
|
||||
async function ensureLiveSession(task: DouyuTaskRow) {
|
||||
@@ -682,13 +762,7 @@ export async function getCustomerDouyuFulfillment(orderNo: string) {
|
||||
await appendEvent(client, task.id, 'customer_link_opened', 'customer')
|
||||
})
|
||||
}
|
||||
const session = await ensureLiveSession(task)
|
||||
return {
|
||||
task: session.task,
|
||||
live: session.live,
|
||||
comparison: session.comparison,
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
}
|
||||
return localCustomerFulfillment(task)
|
||||
}
|
||||
|
||||
export async function saveDouyuCustomerProfile(
|
||||
@@ -766,18 +840,7 @@ export async function refreshDouyuCustomerBinding(orderNo: string) {
|
||||
}
|
||||
|
||||
export async function getDouyuCustomerFulfillmentCached(orderNo: string) {
|
||||
let task = await loadTaskByOrderNo(orderNo)
|
||||
if (!task.live_session_id) {
|
||||
return ensureLiveSession(task)
|
||||
}
|
||||
task = await loadTask(task.id)
|
||||
const live = liveBindingStateFromTask(task)
|
||||
return {
|
||||
task,
|
||||
live,
|
||||
comparison: compareCustomerRole(task, live),
|
||||
linkPath: `/coll/d/${encodeURIComponent(task.platform_order_id)}`,
|
||||
}
|
||||
return localCustomerFulfillment(await loadTaskByOrderNo(orderNo))
|
||||
}
|
||||
|
||||
export async function confirmDouyuCustomerBinding(orderNo: string) {
|
||||
@@ -918,7 +981,7 @@ export async function listDouyuFulfillmentTasks(
|
||||
export async function getDouyuFulfillmentDetail(orderNo: string) {
|
||||
const task = await loadTaskByOrderNo(orderNo)
|
||||
const [session, events] = await Promise.all([
|
||||
ensureLiveSession(task),
|
||||
Promise.resolve(localCustomerFulfillment(task)),
|
||||
query<{
|
||||
id: number
|
||||
event_type: string
|
||||
|
||||
@@ -4,6 +4,7 @@ import test from 'node:test'
|
||||
import {
|
||||
applyLiveBindingStateSnapshot,
|
||||
compareCustomerRole,
|
||||
isStaleLiveStateVersion,
|
||||
statusForLive,
|
||||
} from './douyu-fulfillment-service.js'
|
||||
|
||||
@@ -81,6 +82,13 @@ test('已分配账号保持 allocated,不折叠成准备账号', () => {
|
||||
assert.equal(status, 'allocated')
|
||||
})
|
||||
|
||||
test('直播账号状态版本只允许向前推进', () => {
|
||||
assert.equal(isStaleLiveStateVersion(8, 7), true)
|
||||
assert.equal(isStaleLiveStateVersion(8, 8), false)
|
||||
assert.equal(isStaleLiveStateVersion(8, 9), false)
|
||||
assert.equal(isStaleLiveStateVersion(8, 0), false)
|
||||
})
|
||||
|
||||
test('直播账号状态推送忽略空数据和无效任务', async () => {
|
||||
assert.deepEqual(await applyLiveBindingStateSnapshot({ items: [] }), {
|
||||
received: 0,
|
||||
|
||||
Reference in New Issue
Block a user