feat(semi-auto): 新增履约历史与全链路报文留痕
运营端历史抽屉展示状态流转与全链路报文:客户/运营接口入站 + 虎牙 WUP/livelink、外部 Connector 出站;轮询按状态变化采样,Cookie/Token/短信验证码不落库,报文保留 180 天。同步收敛登录/绑定事件,避免轮询重复写时间线。
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
-- 半自动履约:全链路报文留痕(原本系统入站请求 + 外部平台/Connector 出站调用)
|
||||
-- Cookie / Token / 密钥一律不落库;报文按 180 天保留,由服务侧定期清理。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS semi_auto_trace_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
task_id BIGINT NOT NULL REFERENCES semi_auto_tasks(id) ON DELETE CASCADE,
|
||||
order_no TEXT NOT NULL DEFAULT '',
|
||||
request_id TEXT NOT NULL DEFAULT '',
|
||||
direction TEXT NOT NULL CHECK (direction IN ('inbound', 'outbound')),
|
||||
channel TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'ok' CHECK (status IN ('ok', 'error')),
|
||||
http_status INTEGER,
|
||||
duration_ms INTEGER,
|
||||
request_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
request_body TEXT NOT NULL DEFAULT '',
|
||||
response_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
response_body TEXT NOT NULL DEFAULT '',
|
||||
error_message TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_task
|
||||
ON semi_auto_trace_logs (task_id, id DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_request
|
||||
ON semi_auto_trace_logs (request_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_created
|
||||
ON semi_auto_trace_logs (created_at);
|
||||
|
||||
COMMENT ON TABLE semi_auto_trace_logs IS
|
||||
'半自动履约全链路报文;request_body/response_body 已脱敏(Cookie、Token、密钥不落库)';
|
||||
@@ -4,6 +4,7 @@ import { createApp } from './app.js'
|
||||
import { runtimeConfig } from './config/runtime.js'
|
||||
import { assertRuntimeConfigValid } from './config/runtime-validation.js'
|
||||
import { bootstrapCoreServices } from './startup/bootstrap.js'
|
||||
import { startSemiAutoTraceCleanup } from './services/semi-auto/semi-auto-trace.js'
|
||||
import { createShutdownController } from './startup/shutdown.js'
|
||||
import { createStartupState, formatStartupError } from './startup/state.js'
|
||||
import { logError, logInfo } from './utils/logger.js'
|
||||
@@ -30,6 +31,8 @@ const app = createApp({
|
||||
const server = app.listen(port, host, () => {
|
||||
logInfo('[startup]', `order-site-backend kuaishou-lite listening on http://${host}:${port}`)
|
||||
void bootstrapCoreServices(startupState, () => shutdownController?.isShutdownStarted() || false)
|
||||
// 半自动履约报文保留 180 天:启动先清一次,之后每 6 小时清理。
|
||||
startSemiAutoTraceCleanup()
|
||||
})
|
||||
|
||||
shutdownController = createShutdownController(server, startupState)
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import type { NextFunction, Request, Response } from 'express'
|
||||
|
||||
import { query } from '../db/client.js'
|
||||
import {
|
||||
recordSemiAutoTrace,
|
||||
runWithSemiAutoTrace,
|
||||
traceFingerprint,
|
||||
type SemiAutoTraceChannel,
|
||||
} from '../services/semi-auto/semi-auto-trace.js'
|
||||
import { logWarn } from '../utils/logger.js'
|
||||
|
||||
/**
|
||||
* 半自动履约入站报文:以 `:taskId` 路由参数为锚点。
|
||||
*
|
||||
* 用法:`router.param('taskId', createSemiAutoTaskTraceHandler({ channel: 'customer_api' }))`。
|
||||
* 命中后整条请求链路都在 AsyncLocalStorage 上下文里,外部 Connector / 虎牙 RPC 的出站报文
|
||||
* 会自动复用同一个 requestId,前端即可按 requestId 串起「一次客户操作」。
|
||||
*/
|
||||
export type SemiAutoTaskTraceOptions = {
|
||||
channel: SemiAutoTraceChannel
|
||||
/** 轮询类请求:只有失败或响应状态变化才落库。 */
|
||||
isPolling?: (req: Request) => boolean
|
||||
/** 不记录本次请求(例如返回 CK 的导出接口、历史查询自身)。 */
|
||||
skip?: (req: Request) => boolean
|
||||
}
|
||||
|
||||
const TASK_ORDER_CACHE_LIMIT = 800
|
||||
const taskOrderCache = new Map<number, string>()
|
||||
|
||||
/** 响应里代表「状态」的字段:轮询指纹只取这些,时间戳/计数变化不算状态变化。 */
|
||||
const TRACE_STATE_KEYS = [
|
||||
'status',
|
||||
'state',
|
||||
'loginStatus',
|
||||
'bindingStatus',
|
||||
'executionStatus',
|
||||
'displayStatus',
|
||||
'message',
|
||||
'msg',
|
||||
'code',
|
||||
'errorCode',
|
||||
'ok',
|
||||
'challenge',
|
||||
'ready',
|
||||
'pending',
|
||||
'type',
|
||||
'rebindUnchanged',
|
||||
'rebindRequested',
|
||||
'rebindConfirmState',
|
||||
'rebindConfirmMessage',
|
||||
'rebindCooldownDays',
|
||||
'nextRebindAt',
|
||||
'bindConfirmState',
|
||||
'bindConfirmMessage',
|
||||
'bindEffectDeadlineMs',
|
||||
'bindGameRole',
|
||||
'bindGameRoleId',
|
||||
'huyaUid',
|
||||
'lastError',
|
||||
'isBindAccount',
|
||||
'isBindRole',
|
||||
]
|
||||
|
||||
/** 客户请求体里的凭据类字段:短信验证码等一律不落库。 */
|
||||
const INBOUND_SECRET_KEYS = new Set([
|
||||
'code',
|
||||
'smscode',
|
||||
'sms_code',
|
||||
'password',
|
||||
'token',
|
||||
'cookie',
|
||||
'qrcode',
|
||||
'qrcode_token',
|
||||
'qrcodetoken',
|
||||
'ticket',
|
||||
'sig',
|
||||
])
|
||||
|
||||
function normalizeKey(key: string): string {
|
||||
return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
|
||||
}
|
||||
|
||||
function createTraceRequestId(): string {
|
||||
return `req_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`
|
||||
}
|
||||
|
||||
async function resolveTaskOrderNo(taskId: number): Promise<string> {
|
||||
const cached = taskOrderCache.get(taskId)
|
||||
if (cached !== undefined) return cached
|
||||
try {
|
||||
const result = await query<{ platform_order_id: string | null }>(
|
||||
`SELECT o.platform_order_id
|
||||
FROM semi_auto_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
WHERE task.id = $1
|
||||
LIMIT 1`,
|
||||
[taskId],
|
||||
)
|
||||
const orderNo = String(result.rows[0]?.platform_order_id || '')
|
||||
if (taskOrderCache.size >= TASK_ORDER_CACHE_LIMIT) taskOrderCache.clear()
|
||||
taskOrderCache.set(taskId, orderNo)
|
||||
return orderNo
|
||||
} catch (error) {
|
||||
logWarn('[semi-auto/trace]', '解析任务订单号失败,报文将不带订单号', {
|
||||
taskId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function maskInboundRequestBody(value: unknown, depth = 0): unknown {
|
||||
if (depth > 4) return '[max-depth]'
|
||||
if (value === null || value === undefined) return value
|
||||
if (Array.isArray(value)) {
|
||||
return value.slice(0, 50).map((item) => maskInboundRequestBody(item, depth + 1))
|
||||
}
|
||||
if (typeof value !== 'object') return value
|
||||
const source = value as Record<string, unknown>
|
||||
const masked: Record<string, unknown> = {}
|
||||
for (const [key, current] of Object.entries(source)) {
|
||||
masked[key] = INBOUND_SECRET_KEYS.has(normalizeKey(key))
|
||||
? '******'
|
||||
: maskInboundRequestBody(current, depth + 1)
|
||||
}
|
||||
return masked
|
||||
}
|
||||
|
||||
function pickTraceState(value: unknown, depth = 0): unknown {
|
||||
if (!value || typeof value !== 'object' || depth > 3) return value
|
||||
if (Array.isArray(value)) {
|
||||
return value.slice(0, 20).map((item) => pickTraceState(item, depth + 1))
|
||||
}
|
||||
const source = value as Record<string, unknown>
|
||||
const picked: Record<string, unknown> = {}
|
||||
for (const key of TRACE_STATE_KEYS) {
|
||||
if (key in source && source[key] !== undefined) picked[key] = source[key]
|
||||
}
|
||||
// 常见响应外壳:{ task, login, binding }
|
||||
for (const key of ['task', 'login', 'binding', 'result']) {
|
||||
const nested = source[key]
|
||||
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
|
||||
picked[key] = pickTraceState(nested, depth + 1)
|
||||
}
|
||||
}
|
||||
return Object.keys(picked).length > 0 ? picked : value
|
||||
}
|
||||
|
||||
function buildPollingFingerprint(payload: unknown): string {
|
||||
const body = payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {}
|
||||
return traceFingerprint({
|
||||
code: body.code,
|
||||
msg: body.msg,
|
||||
errorCode: body.errorCode,
|
||||
data: pickTraceState(body.data),
|
||||
})
|
||||
}
|
||||
|
||||
export function createSemiAutoTaskTraceHandler(options: SemiAutoTaskTraceOptions) {
|
||||
return (req: Request, res: Response, next: NextFunction, taskIdInput: string): void => {
|
||||
const taskId = Number(taskIdInput)
|
||||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
if (options.skip?.(req)) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
const pathOrderNo = String(req.params?.orderNo || '').trim()
|
||||
const startedAt = Date.now()
|
||||
const requestId = createTraceRequestId()
|
||||
const polling = options.isPolling?.(req) === true
|
||||
const actionPath = String(req.originalUrl || req.url || '').split('?')[0]
|
||||
const action = `${String(req.method || 'GET').toUpperCase()} ${actionPath}`
|
||||
const requestSummary = {
|
||||
method: req.method,
|
||||
path: actionPath,
|
||||
query: req.query || {},
|
||||
ip: req.ip || '',
|
||||
}
|
||||
const requestBody =
|
||||
req.body && typeof req.body === 'object' && Object.keys(req.body as object).length > 0
|
||||
? maskInboundRequestBody(req.body)
|
||||
: ''
|
||||
let recorded = false
|
||||
|
||||
const record = (payload: unknown) => {
|
||||
if (recorded) return
|
||||
recorded = true
|
||||
try {
|
||||
const body =
|
||||
payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {}
|
||||
const code = Number(body.code)
|
||||
const httpStatus = Number(res.statusCode || 200)
|
||||
const failed = Number.isFinite(code) ? code !== 0 : httpStatus >= 400
|
||||
const status = failed || httpStatus >= 400 ? 'error' : 'ok'
|
||||
recordSemiAutoTrace({
|
||||
taskId,
|
||||
orderNo: pathOrderNo,
|
||||
requestId,
|
||||
direction: 'inbound',
|
||||
channel: options.channel,
|
||||
action,
|
||||
status,
|
||||
httpStatus,
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary,
|
||||
requestBody,
|
||||
responseSummary: {
|
||||
code: body.code ?? null,
|
||||
msg: body.msg ?? '',
|
||||
errorCode: body.errorCode ?? '',
|
||||
},
|
||||
responseBody: payload,
|
||||
errorMessage: status === 'error' ? String(body.msg || '') : '',
|
||||
always: !polling,
|
||||
fingerprint: polling ? buildPollingFingerprint(payload) : undefined,
|
||||
})
|
||||
} catch (error) {
|
||||
logWarn('[semi-auto/trace]', '记录入站报文失败,已跳过', {
|
||||
taskId,
|
||||
action,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const originalJson = res.json.bind(res)
|
||||
res.json = ((payload: unknown) => {
|
||||
record(payload)
|
||||
return originalJson(payload as never)
|
||||
}) as Response['json']
|
||||
|
||||
const start = (orderNo: string) => {
|
||||
runWithSemiAutoTrace({ requestId, taskId, orderNo, source: options.channel }, () => next())
|
||||
}
|
||||
|
||||
if (pathOrderNo) {
|
||||
start(pathOrderNo)
|
||||
return
|
||||
}
|
||||
void resolveTaskOrderNo(taskId).then(start, () => start(''))
|
||||
}
|
||||
}
|
||||
@@ -8,15 +8,27 @@ import {
|
||||
createAdminBrowserSession,
|
||||
exportAdminSemiAutoCredential,
|
||||
getAdminSemiAutoTask,
|
||||
getAdminSemiAutoTaskHistory,
|
||||
listAdminSemiAutoTasks,
|
||||
requestAdminSemiAutoCustomerReauth,
|
||||
syncAdminSemiAutoTask,
|
||||
} from '../../services/semi-auto/semi-auto-task-service.js'
|
||||
import { createSemiAutoTaskTraceHandler } from '../../middleware/semi-auto-trace.js'
|
||||
import { bodyOf, sessionOf } from './request-helpers.js'
|
||||
import { createJsonHandler, requireAdminRoles } from './session.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
// 运营端每次操作都会记录入站报文;详情每 3 秒刷新一次,GET 只在状态变化时落库。
|
||||
router.param(
|
||||
'taskId',
|
||||
createSemiAutoTaskTraceHandler({
|
||||
channel: 'admin_api',
|
||||
isPolling: (req) => req.method === 'GET',
|
||||
skip: (req) => req.path.endsWith('/history') || req.path.endsWith('/credential/export'),
|
||||
}),
|
||||
)
|
||||
|
||||
router.use('/semi-auto', requireAdminRoles(['admin', 'operator', 'support']))
|
||||
|
||||
router.get(
|
||||
@@ -37,6 +49,18 @@ router.get(
|
||||
}),
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/semi-auto/tasks/:taskId/history',
|
||||
createJsonHandler(
|
||||
(req) => getAdminSemiAutoTaskHistory(req.params.taskId, req.query as Record<string, unknown>),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取半自动履约历史失败',
|
||||
scope: '[admin/semi-auto/tasks/:taskId/history]',
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/semi-auto/tasks/:taskId/credential/export',
|
||||
createJsonHandler(
|
||||
|
||||
@@ -19,11 +19,21 @@ import {
|
||||
submitPublicRebind,
|
||||
verifyPublicHuyaSmsChallenge,
|
||||
} from '../services/semi-auto/semi-auto-task-service.js'
|
||||
import { createSemiAutoTaskTraceHandler } from '../middleware/semi-auto-trace.js'
|
||||
import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js'
|
||||
import { createRouteHandler } from '../utils/http.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
// 客户侧每次操作都会记录入站报文;2 秒一次的 /status 轮询只在状态变化或失败时落库。
|
||||
router.param(
|
||||
'taskId',
|
||||
createSemiAutoTaskTraceHandler({
|
||||
channel: 'customer_api',
|
||||
isPolling: (req) => req.path.endsWith('/status'),
|
||||
}),
|
||||
)
|
||||
|
||||
const readLimit = createRateLimitMiddleware({
|
||||
scope: 'customer-fulfillment:read',
|
||||
windowMs: 60_000,
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
huyaNativeConnector,
|
||||
type HuyaStoredCredential,
|
||||
} from './huya-native/huya-native-connector.js'
|
||||
import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js'
|
||||
|
||||
export type ConnectorLoginSession = {
|
||||
sessionId: string
|
||||
@@ -204,9 +205,11 @@ async function callConnector<T>(
|
||||
const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000))
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
const method = String(options.method || 'GET').toUpperCase()
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const requestInit: RequestInit = {
|
||||
method: options.method || 'GET',
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
@@ -223,6 +226,20 @@ async function callConnector<T>(
|
||||
} catch {
|
||||
payload = null
|
||||
}
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'external_connector',
|
||||
action: `${method} ${path}`,
|
||||
status: response.ok ? 'ok' : 'error',
|
||||
httpStatus: response.status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||
requestBody: options.body,
|
||||
responseSummary: { bodyBytes: text.length },
|
||||
responseBody: payload ?? text,
|
||||
always: method !== 'GET',
|
||||
fingerprint: method === 'GET' ? traceFingerprint(payload) : undefined,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const detail =
|
||||
payload && typeof payload === 'object'
|
||||
@@ -235,6 +252,19 @@ async function callConnector<T>(
|
||||
}
|
||||
return payload as T
|
||||
} catch (error) {
|
||||
if (!(error && typeof error === 'object' && 'statusCode' in error)) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'external_connector',
|
||||
action: `${method} ${path}`,
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||
requestBody: options.body,
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw createHttpError('半自动履约 Connector 请求超时', {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import { recordSemiAutoTrace, traceFingerprint } from '../semi-auto-trace.js'
|
||||
import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js'
|
||||
import {
|
||||
decodeWupResponse,
|
||||
@@ -494,22 +495,67 @@ export class HuyaRpcClient {
|
||||
gid?: number
|
||||
scene?: string
|
||||
}): Promise<HuyaBindResponse | null> {
|
||||
const response = await this.callRpc(
|
||||
'webActUI',
|
||||
'checkUserBindGameAccount',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||
writer.writeInt32(1, input.gid || 0)
|
||||
writer.writeString(2, input.outerActId || '')
|
||||
writer.writeInt32(3, 0)
|
||||
writer.writeString(4, input.scene || '')
|
||||
writer.writeInt32(5, input.bindActId || 0)
|
||||
writer.writeInt32(6, input.isUseOuterActId ?? 1)
|
||||
},
|
||||
)
|
||||
return response ? readWupStruct(response, parseBindResponse) : null
|
||||
const startedAt = Date.now()
|
||||
const request = {
|
||||
servant: 'webActUI',
|
||||
func: 'checkUserBindGameAccount',
|
||||
uid: input.uid,
|
||||
gid: input.gid || 0,
|
||||
outerActId: input.outerActId || '',
|
||||
bindActId: input.bindActId || 0,
|
||||
isUseOuterActId: input.isUseOuterActId ?? 1,
|
||||
scene: input.scene || '',
|
||||
}
|
||||
try {
|
||||
const response = await this.callRpc(
|
||||
'webActUI',
|
||||
'checkUserBindGameAccount',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||
writer.writeInt32(1, input.gid || 0)
|
||||
writer.writeString(2, input.outerActId || '')
|
||||
writer.writeInt32(3, 0)
|
||||
writer.writeString(4, input.scene || '')
|
||||
writer.writeInt32(5, input.bindActId || 0)
|
||||
writer.writeInt32(6, input.isUseOuterActId ?? 1)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseBindResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.checkUserBindGameAccount',
|
||||
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||
responseBody: parsed,
|
||||
// 绑定轮询:状态没变化就不落库。
|
||||
fingerprint: traceFingerprint({
|
||||
status: parsed?.status,
|
||||
msg: parsed?.msg,
|
||||
isBindAccount: parsed?.accountData?.isBindAccount,
|
||||
isBindRole: parsed?.accountData?.isBindRole,
|
||||
role: parsed?.accountData?.gameRole?.roleName,
|
||||
roleId: parsed?.accountData?.gameRole?.roleId,
|
||||
}),
|
||||
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.checkUserBindGameAccount',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async confirmBindActAccount(input: {
|
||||
@@ -519,19 +565,55 @@ export class HuyaRpcClient {
|
||||
outerActId: string
|
||||
gid?: number
|
||||
}): Promise<HuyaConfirmResponse | null> {
|
||||
const response = await this.callRpc(
|
||||
'webActUI',
|
||||
'confirmBindActAccount',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||
writer.writeInt32(1, input.gid || 0)
|
||||
writer.writeString(2, input.outerActId || '')
|
||||
writer.writeInt32(3, input.bindActId || 0)
|
||||
},
|
||||
)
|
||||
return response ? readWupStruct(response, parseConfirmResponse) : null
|
||||
const startedAt = Date.now()
|
||||
const request = {
|
||||
servant: 'webActUI',
|
||||
func: 'confirmBindActAccount',
|
||||
uid: input.uid,
|
||||
gid: input.gid || 0,
|
||||
outerActId: input.outerActId || '',
|
||||
bindActId: input.bindActId || 0,
|
||||
}
|
||||
try {
|
||||
const response = await this.callRpc(
|
||||
'webActUI',
|
||||
'confirmBindActAccount',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||
writer.writeInt32(1, input.gid || 0)
|
||||
writer.writeString(2, input.outerActId || '')
|
||||
writer.writeInt32(3, input.bindActId || 0)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseConfirmResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.confirmBindActAccount',
|
||||
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||
responseBody: parsed,
|
||||
always: true,
|
||||
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.confirmBindActAccount',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getLiveLinkParam(input: {
|
||||
@@ -541,21 +623,57 @@ export class HuyaRpcClient {
|
||||
outerActId: number
|
||||
gameAuthScene?: string
|
||||
}): Promise<HuyaLiveLinkResponse | null> {
|
||||
const response = await this.callRpc(
|
||||
'webActUI',
|
||||
'getLiveLinkParam',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||
writer.writeInt32(1, 0)
|
||||
writer.writeInt32(2, input.outerActId || 0)
|
||||
writer.writeString(3, input.gameAuthScene || '')
|
||||
writer.writeString(4, '')
|
||||
writer.writeInt32(5, input.bindActId || 0)
|
||||
},
|
||||
)
|
||||
return response ? readWupStruct(response, parseLiveLinkResponse) : null
|
||||
const startedAt = Date.now()
|
||||
const request = {
|
||||
servant: 'webActUI',
|
||||
func: 'getLiveLinkParam',
|
||||
uid: input.uid,
|
||||
bindActId: input.bindActId || 0,
|
||||
outerActId: input.outerActId || 0,
|
||||
gameAuthScene: input.gameAuthScene || '',
|
||||
}
|
||||
try {
|
||||
const response = await this.callRpc(
|
||||
'webActUI',
|
||||
'getLiveLinkParam',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, input.uid, input.cookie)
|
||||
writer.writeInt32(1, 0)
|
||||
writer.writeInt32(2, input.outerActId || 0)
|
||||
writer.writeString(3, input.gameAuthScene || '')
|
||||
writer.writeString(4, '')
|
||||
writer.writeInt32(5, input.bindActId || 0)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseLiveLinkResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.getLiveLinkParam',
|
||||
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||
responseBody: parsed,
|
||||
always: true,
|
||||
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.getLiveLinkParam',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getUserProfileBatch(input: {
|
||||
@@ -585,17 +703,53 @@ export class HuyaRpcClient {
|
||||
}): Promise<HuyaUserProfile | null> {
|
||||
const targetUid = Math.trunc(input.targetUid)
|
||||
if (!(targetUid > 0)) return null
|
||||
const response = await this.callRpc(
|
||||
'huyauserui',
|
||||
'getUserProfile',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, 0, input.cookie)
|
||||
writer.writeInt64(1, targetUid)
|
||||
},
|
||||
)
|
||||
return response ? readWupStruct(response, parseProfileResponse) : null
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const response = await this.callRpc(
|
||||
'huyauserui',
|
||||
'getUserProfile',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, 0, input.cookie)
|
||||
writer.writeInt64(1, targetUid)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseProfileResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'huyauserui.getUserProfile',
|
||||
status: parsed ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: {
|
||||
servant: 'huyauserui',
|
||||
func: 'getUserProfile',
|
||||
uid: input.uid,
|
||||
targetUid,
|
||||
},
|
||||
responseBody: parsed,
|
||||
always: true,
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'huyauserui.getUserProfile',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: {
|
||||
servant: 'huyauserui',
|
||||
func: 'getUserProfile',
|
||||
uid: input.uid,
|
||||
targetUid,
|
||||
},
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async callRpc(
|
||||
@@ -715,6 +869,7 @@ export async function getLiveLinkMiniQrcode(
|
||||
).join('')
|
||||
const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}`
|
||||
const fetchImpl = options.fetchImpl || fetch
|
||||
const startedAt = Date.now()
|
||||
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -728,14 +883,41 @@ export async function getLiveLinkMiniQrcode(
|
||||
body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }),
|
||||
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
const traceMiniQrcode = (status: 'ok' | 'error', extra: Record<string, unknown> = {}) => {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_http',
|
||||
action: 'livelink.getMiniAppQrcode',
|
||||
status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
httpStatus: response.status,
|
||||
requestSummary: { api: 'getMiniAppQrcode', queryLength: query.length },
|
||||
responseSummary: extra,
|
||||
always: true,
|
||||
})
|
||||
}
|
||||
if (!response.ok) {
|
||||
traceMiniQrcode('error', { httpStatus: response.status })
|
||||
return null
|
||||
}
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
iRet?: number
|
||||
jData?: { qrcode?: string; qrcodeToken?: string }
|
||||
} | null
|
||||
if (!payload || payload.iRet !== 0) return null
|
||||
if (!payload || payload.iRet !== 0) {
|
||||
traceMiniQrcode('error', { iRet: payload?.iRet ?? null })
|
||||
return null
|
||||
}
|
||||
const image = livelinkQrcodeImageSrc(String(payload.jData?.qrcode || ''))
|
||||
if (!image) return null
|
||||
if (!image) {
|
||||
traceMiniQrcode('error', { iRet: payload.iRet, hasImage: false })
|
||||
return null
|
||||
}
|
||||
traceMiniQrcode('ok', {
|
||||
iRet: payload.iRet,
|
||||
hasImage: true,
|
||||
tokenLength: String(payload.jData?.qrcodeToken || '').length,
|
||||
})
|
||||
return { image, token: String(payload.jData?.qrcodeToken || '') }
|
||||
}
|
||||
|
||||
@@ -751,6 +933,7 @@ export async function getLiveLinkQrcodeStatus(
|
||||
const normalized = String(token || '').trim()
|
||||
if (!normalized) return null
|
||||
const fetchImpl = options.fetchImpl || fetch
|
||||
const startedAt = Date.now()
|
||||
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -764,7 +947,24 @@ export async function getLiveLinkQrcodeStatus(
|
||||
body: JSON.stringify({ qrcodeToken: normalized }),
|
||||
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
const traceQrcodeStatus = (status: 'ok' | 'error', extra: Record<string, unknown> = {}) => {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_http',
|
||||
action: 'livelink.poolingQrcodeStatus',
|
||||
status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
httpStatus: response.status,
|
||||
requestSummary: { api: 'poolingQrcodeStatus', tokenLength: normalized.length },
|
||||
responseSummary: extra,
|
||||
// 二维码轮询:状态没变化就不落库。
|
||||
fingerprint: traceFingerprint(extra),
|
||||
})
|
||||
}
|
||||
if (!response.ok) {
|
||||
traceQrcodeStatus('error', { httpStatus: response.status })
|
||||
return null
|
||||
}
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
iRet?: number
|
||||
jData?: {
|
||||
@@ -774,13 +974,18 @@ export async function getLiveLinkQrcodeStatus(
|
||||
isFailure?: boolean
|
||||
}
|
||||
} | null
|
||||
if (!payload || payload.iRet !== 0) return null
|
||||
return {
|
||||
if (!payload || payload.iRet !== 0) {
|
||||
traceQrcodeStatus('error', { iRet: payload?.iRet ?? null })
|
||||
return null
|
||||
}
|
||||
const result = {
|
||||
isScan: Boolean(payload.jData?.isScan),
|
||||
isExpired: Boolean(payload.jData?.isExpired),
|
||||
isCompleted: Boolean(payload.jData?.isCompleted),
|
||||
isFailure: Boolean(payload.jData?.isFailure),
|
||||
}
|
||||
traceQrcodeStatus('ok', { iRet: payload.iRet, ...result })
|
||||
return result
|
||||
}
|
||||
|
||||
export function buildBindUrls(input: {
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
markSemiAutoCredentialCheck,
|
||||
upsertSemiAutoCredentialWithClient,
|
||||
} from './semi-auto-credential-service.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
|
||||
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
|
||||
type SemiAutoPlatform = 'huya' | 'weibo'
|
||||
@@ -920,19 +921,22 @@ async function updateLoginTask(
|
||||
credentialId,
|
||||
],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_status_changed',
|
||||
actorType,
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: nextExecutionStatus,
|
||||
detail: {
|
||||
hasCredential: mapped.hasCredential,
|
||||
message: mapped.message,
|
||||
method: options.method || 'qr',
|
||||
},
|
||||
})
|
||||
// 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。
|
||||
if (mapped.status !== task.login_status || nextExecutionStatus !== task.execution_status) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_status_changed',
|
||||
actorType,
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: nextExecutionStatus,
|
||||
detail: {
|
||||
hasCredential: mapped.hasCredential,
|
||||
message: mapped.message,
|
||||
method: options.method || 'qr',
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1130,32 +1134,40 @@ async function updateBindingTask(
|
||||
mapped.bindGameRoleId,
|
||||
],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'binding_status_changed',
|
||||
actorType,
|
||||
fromBindingStatus: task.binding_status,
|
||||
toBindingStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
gameAccount: mapped.bindGameAccount,
|
||||
gameRole: mapped.bindGameRole,
|
||||
gameRoleId: mapped.bindGameRoleId,
|
||||
gameChannel: mapped.bindGameChannel,
|
||||
verdict: comparison.verdict,
|
||||
rebindRequested: mapped.rebindRequested,
|
||||
rebindUnchanged: mapped.rebindUnchanged,
|
||||
rebindConfirmState: mapped.rebindConfirmState,
|
||||
rebindConfirmMessage: mapped.rebindConfirmMessage,
|
||||
bindConfirmState: mapped.bindConfirmState,
|
||||
bindConfirmMessage: mapped.bindConfirmMessage,
|
||||
rebindCooldownDays: mapped.rebindCooldownDays,
|
||||
nextRebindAt: mapped.nextRebindAt,
|
||||
changeBindDay: mapped.platformChangeBindDay,
|
||||
changeBindTime: mapped.platformChangeBindTime,
|
||||
message: mapped.message,
|
||||
},
|
||||
})
|
||||
// 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。
|
||||
const bindingChanged =
|
||||
mapped.status !== task.binding_status ||
|
||||
executionStatus !== task.execution_status ||
|
||||
mapped.rebindUnchanged ||
|
||||
mapped.rebindConfirmState === 'rejected'
|
||||
if (bindingChanged) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'binding_status_changed',
|
||||
actorType,
|
||||
fromBindingStatus: task.binding_status,
|
||||
toBindingStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
gameAccount: mapped.bindGameAccount,
|
||||
gameRole: mapped.bindGameRole,
|
||||
gameRoleId: mapped.bindGameRoleId,
|
||||
gameChannel: mapped.bindGameChannel,
|
||||
verdict: comparison.verdict,
|
||||
rebindRequested: mapped.rebindRequested,
|
||||
rebindUnchanged: mapped.rebindUnchanged,
|
||||
rebindConfirmState: mapped.rebindConfirmState,
|
||||
rebindConfirmMessage: mapped.rebindConfirmMessage,
|
||||
bindConfirmState: mapped.bindConfirmState,
|
||||
bindConfirmMessage: mapped.bindConfirmMessage,
|
||||
rebindCooldownDays: mapped.rebindCooldownDays,
|
||||
nextRebindAt: mapped.nextRebindAt,
|
||||
changeBindDay: mapped.platformChangeBindDay,
|
||||
changeBindTime: mapped.platformChangeBindTime,
|
||||
message: mapped.message,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
return {
|
||||
status: mapped.status,
|
||||
@@ -1916,6 +1928,78 @@ export async function getAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
}
|
||||
}
|
||||
|
||||
type SemiAutoTaskEventRow = {
|
||||
id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
actor_id: string
|
||||
from_login_status: string | null
|
||||
to_login_status: string | null
|
||||
from_binding_status: string | null
|
||||
to_binding_status: string | null
|
||||
from_execution_status: string | null
|
||||
to_execution_status: string | null
|
||||
detail_json: Record<string, unknown>
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 运营端「历史」:任务状态流转事件 + 全链路报文(本系统入站 + 外部平台出站)。
|
||||
* 报文只读,不做任何写操作;Cookie / Token 已在落库前脱敏。
|
||||
*/
|
||||
export async function getAdminSemiAutoTaskHistory(
|
||||
taskIdInput: unknown,
|
||||
input: Record<string, unknown> = {},
|
||||
) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
const eventCount = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM semi_auto_task_events WHERE task_id = $1`,
|
||||
[task.id],
|
||||
)
|
||||
const events = await query<SemiAutoTaskEventRow>(
|
||||
`SELECT * FROM (
|
||||
SELECT id, event_type, actor_type, actor_id,
|
||||
from_login_status, to_login_status,
|
||||
from_binding_status, to_binding_status,
|
||||
from_execution_status, to_execution_status,
|
||||
detail_json, created_at
|
||||
FROM semi_auto_task_events
|
||||
WHERE task_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT 500
|
||||
) recent
|
||||
ORDER BY id ASC`,
|
||||
[task.id],
|
||||
)
|
||||
const traces = await querySemiAutoTraces(task.id, {
|
||||
page: Number(input.page) || 1,
|
||||
pageSize: Number(input.pageSize) || 50,
|
||||
channel: String(input.channel || '').trim(),
|
||||
status: String(input.status || '').trim(),
|
||||
requestId: String(input.requestId || '').trim(),
|
||||
keyword: String(input.keyword || '').trim(),
|
||||
})
|
||||
return {
|
||||
task: mapTask(task),
|
||||
events: events.rows.map((event) => ({
|
||||
id: Number(event.id),
|
||||
eventType: event.event_type,
|
||||
actorType: event.actor_type,
|
||||
actorId: event.actor_id,
|
||||
fromLoginStatus: event.from_login_status,
|
||||
toLoginStatus: event.to_login_status,
|
||||
fromBindingStatus: event.from_binding_status,
|
||||
toBindingStatus: event.to_binding_status,
|
||||
fromExecutionStatus: event.from_execution_status,
|
||||
toExecutionStatus: event.to_execution_status,
|
||||
detail: event.detail_json || {},
|
||||
createdAt: event.created_at,
|
||||
})),
|
||||
eventTotal: Number(eventCount.rows[0]?.total || 0),
|
||||
traces,
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
if (!task.credential_id) {
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import { query } from '../../db/client.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
|
||||
/** 报文保留天数:180 天,由 startSemiAutoTraceCleanup 定时清理。 */
|
||||
export const SEMI_AUTO_TRACE_RETENTION_DAYS = 180
|
||||
const MAX_BODY_CHARS = 32_000
|
||||
const MAX_REDACT_DEPTH = 6
|
||||
const FINGERPRINT_LIMIT = 5_000
|
||||
|
||||
export type SemiAutoTraceChannel =
|
||||
| 'customer_api'
|
||||
| 'admin_api'
|
||||
| 'huya_wup'
|
||||
| 'huya_http'
|
||||
| 'external_connector'
|
||||
|
||||
export type SemiAutoTraceContext = {
|
||||
requestId: string
|
||||
taskId?: number
|
||||
orderNo?: string
|
||||
source?: string
|
||||
}
|
||||
|
||||
export type SemiAutoTraceEntry = {
|
||||
taskId?: number
|
||||
orderNo?: string
|
||||
requestId?: string
|
||||
direction: 'inbound' | 'outbound'
|
||||
channel: SemiAutoTraceChannel | string
|
||||
action: string
|
||||
status?: 'ok' | 'error'
|
||||
httpStatus?: number
|
||||
durationMs?: number
|
||||
requestSummary?: Record<string, unknown>
|
||||
requestBody?: unknown
|
||||
responseSummary?: Record<string, unknown>
|
||||
responseBody?: unknown
|
||||
errorMessage?: string
|
||||
/** 写操作/关键读:无条件记录(轮询类不要传)。 */
|
||||
always?: boolean
|
||||
/** 轮询类请求的状态指纹:与上次相同则不记录。 */
|
||||
fingerprint?: string | undefined
|
||||
}
|
||||
|
||||
const traceStorage = new AsyncLocalStorage<SemiAutoTraceContext>()
|
||||
const lastFingerprints = new Map<string, string>()
|
||||
|
||||
/** Cookie / Token / 密钥字段:一律不落库。 */
|
||||
const SENSITIVE_KEYS = new Set([
|
||||
'cookie',
|
||||
'set-cookie',
|
||||
'authorization',
|
||||
'proxyauthorization',
|
||||
'token',
|
||||
'accesstoken',
|
||||
'access_token',
|
||||
'refreshtoken',
|
||||
'refresh_token',
|
||||
'biztoken',
|
||||
'udb_biztoken',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'apikey',
|
||||
'api_key',
|
||||
'x-semi-auto-key',
|
||||
'sig',
|
||||
'qrcodetoken',
|
||||
'qrcode_token',
|
||||
'qrcontent',
|
||||
'qr_content',
|
||||
'qrimage',
|
||||
'qr_image',
|
||||
'query_string',
|
||||
'smscode',
|
||||
'sms_code',
|
||||
'sessionid',
|
||||
'session_id',
|
||||
'baseinfo',
|
||||
'cookies',
|
||||
'cookie_header',
|
||||
'cookieheader',
|
||||
'ticket',
|
||||
'credential_payload_json',
|
||||
])
|
||||
|
||||
export function runWithSemiAutoTrace<T>(context: SemiAutoTraceContext, fn: () => T): T {
|
||||
return traceStorage.run(context, fn)
|
||||
}
|
||||
|
||||
export function currentSemiAutoTrace(): SemiAutoTraceContext | undefined {
|
||||
return traceStorage.getStore()
|
||||
}
|
||||
|
||||
function maskValue(value: unknown): unknown {
|
||||
if (value === null || value === undefined) return value
|
||||
if (typeof value !== 'string') return '******'
|
||||
return value.length > 0 ? '******' : ''
|
||||
}
|
||||
|
||||
function normalizeKey(key: string): string {
|
||||
return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
|
||||
}
|
||||
|
||||
/** 深度脱敏:Cookie / Token / 密钥字段直接替换为 ******。 */
|
||||
export function redactTraceValue(value: unknown, depth = 0): unknown {
|
||||
if (depth > MAX_REDACT_DEPTH) return '[max-depth]'
|
||||
if (value === null || value === undefined) return value
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||
return value
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.slice(0, 50).map((item) => redactTraceValue(item, depth + 1))
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
const source = value as Record<string, unknown>
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, current] of Object.entries(source)) {
|
||||
result[key] = SENSITIVE_KEYS.has(normalizeKey(key))
|
||||
? maskValue(current)
|
||||
: redactTraceValue(current, depth + 1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
export function stringifyTraceBody(value: unknown): string {
|
||||
if (value === undefined || value === null) return ''
|
||||
if (typeof value === 'string') {
|
||||
return value.length > MAX_BODY_CHARS
|
||||
? `${value.slice(0, MAX_BODY_CHARS)}\n...[truncated]`
|
||||
: value
|
||||
}
|
||||
try {
|
||||
const text = JSON.stringify(redactTraceValue(value), null, 2)
|
||||
return text.length > MAX_BODY_CHARS ? `${text.slice(0, MAX_BODY_CHARS)}\n...[truncated]` : text
|
||||
} catch {
|
||||
return String(value).slice(0, MAX_BODY_CHARS)
|
||||
}
|
||||
}
|
||||
|
||||
function fingerprintKey(entry: SemiAutoTraceEntry): string {
|
||||
return `${entry.taskId || 0}|${entry.channel}|${entry.action}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样:写操作与关键读一律记录;轮询类只在状态变化或失败时记录,避免每 2 秒一条。
|
||||
*/
|
||||
export function shouldRecordTrace(entry: SemiAutoTraceEntry): boolean {
|
||||
if (entry.always) return true
|
||||
if ((entry.status || 'ok') === 'error') return true
|
||||
const fingerprint = String(entry.fingerprint || '')
|
||||
if (!fingerprint) return true
|
||||
const key = fingerprintKey(entry)
|
||||
const previous = lastFingerprints.get(key)
|
||||
if (previous === fingerprint) return false
|
||||
lastFingerprints.set(key, fingerprint)
|
||||
if (lastFingerprints.size > FINGERPRINT_LIMIT) lastFingerprints.clear()
|
||||
return true
|
||||
}
|
||||
|
||||
/** 记录一条报文:异步落库,失败只记日志,绝不阻断主流程。 */
|
||||
export function recordSemiAutoTrace(entry: SemiAutoTraceEntry): void {
|
||||
const context = currentSemiAutoTrace()
|
||||
const taskId = Number(entry.taskId || context?.taskId || 0)
|
||||
if (!Number.isFinite(taskId) || taskId <= 0) return
|
||||
if (!shouldRecordTrace(entry)) return
|
||||
const orderNo = entry.orderNo || context?.orderNo || ''
|
||||
const requestId = entry.requestId || context?.requestId || ''
|
||||
const status = entry.status === 'error' ? 'error' : 'ok'
|
||||
const requestBody = stringifyTraceBody(entry.requestBody)
|
||||
const responseBody = stringifyTraceBody(entry.responseBody)
|
||||
void query(
|
||||
`INSERT INTO semi_auto_trace_logs (
|
||||
task_id, order_no, request_id, direction, channel, action, status,
|
||||
http_status, duration_ms, request_summary, request_body,
|
||||
response_summary, response_body, error_message, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::jsonb,$11,$12::jsonb,$13,$14,NOW())`,
|
||||
[
|
||||
taskId,
|
||||
orderNo,
|
||||
requestId,
|
||||
entry.direction,
|
||||
entry.channel,
|
||||
entry.action,
|
||||
status,
|
||||
entry.httpStatus ?? null,
|
||||
entry.durationMs ?? null,
|
||||
JSON.stringify(redactTraceValue(entry.requestSummary || {})),
|
||||
requestBody,
|
||||
JSON.stringify(redactTraceValue(entry.responseSummary || {})),
|
||||
responseBody,
|
||||
String(entry.errorMessage || ''),
|
||||
],
|
||||
).catch((error) => {
|
||||
logWarn('semi-auto/trace', '写入报文失败', {
|
||||
taskId,
|
||||
action: entry.action,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** 供调用方快速生成一个轮询指纹。 */
|
||||
export function traceFingerprint(value: unknown): string {
|
||||
if (value === null || value === undefined) return ''
|
||||
let text = ''
|
||||
if (typeof value === 'string') {
|
||||
text = value
|
||||
} else {
|
||||
try {
|
||||
text = JSON.stringify(value)
|
||||
} catch {
|
||||
text = String(value)
|
||||
}
|
||||
}
|
||||
return crypto.createHash('sha1').update(text).digest('hex')
|
||||
}
|
||||
|
||||
export type SemiAutoTraceQuery = {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
channel?: string
|
||||
status?: string
|
||||
requestId?: string
|
||||
keyword?: string
|
||||
}
|
||||
|
||||
export async function querySemiAutoTraces(taskId: number, input: SemiAutoTraceQuery = {}) {
|
||||
const page = Math.max(1, Math.floor(Number(input.page) || 1))
|
||||
const pageSize = Math.min(200, Math.max(1, Math.floor(Number(input.pageSize) || 50)))
|
||||
const conditions = ['task_id = $1']
|
||||
const params: unknown[] = [taskId]
|
||||
if (input.channel) {
|
||||
params.push(String(input.channel))
|
||||
conditions.push(`channel = $${params.length}`)
|
||||
}
|
||||
if (input.status) {
|
||||
params.push(String(input.status))
|
||||
conditions.push(`status = $${params.length}`)
|
||||
}
|
||||
if (input.requestId) {
|
||||
params.push(String(input.requestId))
|
||||
conditions.push(`request_id = $${params.length}`)
|
||||
}
|
||||
if (input.keyword) {
|
||||
params.push(`%${String(input.keyword).trim()}%`)
|
||||
conditions.push(
|
||||
`(action ILIKE $${params.length} OR request_body ILIKE $${params.length} OR response_body ILIKE $${params.length})`,
|
||||
)
|
||||
}
|
||||
const where = conditions.join(' AND ')
|
||||
const count = await query(
|
||||
`SELECT COUNT(*)::int AS total FROM semi_auto_trace_logs WHERE ${where}`,
|
||||
params,
|
||||
)
|
||||
const rows = await query(
|
||||
`SELECT id, order_no, request_id, direction, channel, action, status,
|
||||
http_status, duration_ms, request_summary, request_body,
|
||||
response_summary, response_body, error_message, created_at
|
||||
FROM semi_auto_trace_logs
|
||||
WHERE ${where}
|
||||
ORDER BY id DESC
|
||||
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
|
||||
[...params, pageSize, (page - 1) * pageSize],
|
||||
)
|
||||
const summary = await query(
|
||||
`SELECT channel, status, COUNT(*)::int AS total
|
||||
FROM semi_auto_trace_logs
|
||||
WHERE task_id = $1
|
||||
GROUP BY channel, status`,
|
||||
[taskId],
|
||||
)
|
||||
return {
|
||||
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
|
||||
summary: summary.rows,
|
||||
items: rows.rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
orderNo: row.order_no,
|
||||
requestId: row.request_id,
|
||||
direction: row.direction,
|
||||
channel: row.channel,
|
||||
action: row.action,
|
||||
status: row.status,
|
||||
httpStatus: row.http_status,
|
||||
durationMs: row.duration_ms,
|
||||
requestSummary: row.request_summary || {},
|
||||
requestBody: row.request_body || '',
|
||||
responseSummary: row.response_summary || {},
|
||||
responseBody: row.response_body || '',
|
||||
errorMessage: row.error_message || '',
|
||||
createdAt: row.created_at,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanupSemiAutoTraces(retentionDays = SEMI_AUTO_TRACE_RETENTION_DAYS) {
|
||||
const days = Math.max(1, Math.floor(Number(retentionDays) || SEMI_AUTO_TRACE_RETENTION_DAYS))
|
||||
const result = await query(
|
||||
`DELETE FROM semi_auto_trace_logs WHERE created_at < NOW() - ($1 || ' days')::interval`,
|
||||
[String(days)],
|
||||
)
|
||||
return result.rowCount || 0
|
||||
}
|
||||
|
||||
let cleanupStarted = false
|
||||
|
||||
/** 启动时清一次,之后每 6 小时清理超过保留期的报文。 */
|
||||
export function startSemiAutoTraceCleanup(): void {
|
||||
if (cleanupStarted) return
|
||||
cleanupStarted = true
|
||||
const run = () => {
|
||||
void cleanupSemiAutoTraces().catch((error) => {
|
||||
logWarn('semi-auto/trace', '清理历史报文失败', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
run()
|
||||
const timer = setInterval(run, 6 * 60 * 60 * 1000)
|
||||
timer.unref?.()
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
import { CopyOutlined, ReloadOutlined } from '@ant-design/icons'
|
||||
import {
|
||||
App,
|
||||
Button,
|
||||
Collapse,
|
||||
Drawer,
|
||||
Empty,
|
||||
Input,
|
||||
Pagination,
|
||||
Select,
|
||||
Space,
|
||||
Tabs,
|
||||
Tag,
|
||||
theme,
|
||||
Timeline,
|
||||
Typography,
|
||||
} from 'antd'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
import { fetchAdminSemiAutoTaskHistory } from '@/services/admin/semi-auto'
|
||||
import type { SemiAutoTaskHistoryEvent, SemiAutoTraceItem } from '@/types/admin/semi-auto'
|
||||
import { formatAdminDateTime } from '@/utils/admin-time'
|
||||
import { useIsMobile } from '@/utils/use-is-mobile'
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
const EVENT_LABELS: Record<string, string> = {
|
||||
task_created: '任务创建',
|
||||
customer_link_opened: '客户打开链接',
|
||||
customer_profile_saved: '客户保存角色资料',
|
||||
login_started: '开始平台登录',
|
||||
login_status_changed: '登录状态变更',
|
||||
binding_status_changed: '绑定状态变更',
|
||||
task_claimed: '客服领取',
|
||||
customer_reauth_requested: '重新发起客户授权',
|
||||
browser_session_opened: '生成浏览器注入票据',
|
||||
credential_session_restored: '凭证恢复登录',
|
||||
credential_invalidated: '凭证失效',
|
||||
task_completed: '订单完成',
|
||||
task_cancelled: '订单取消',
|
||||
}
|
||||
|
||||
const CHANNEL_LABELS: Record<string, string> = {
|
||||
customer_api: '客户接口',
|
||||
admin_api: '运营接口',
|
||||
huya_wup: '虎牙 WUP',
|
||||
huya_http: '虎牙 HTTP',
|
||||
external_connector: '外部 Connector',
|
||||
}
|
||||
|
||||
const CHANNEL_OPTIONS = Object.keys(CHANNEL_LABELS).map((value) => ({
|
||||
value,
|
||||
label: CHANNEL_LABELS[value],
|
||||
}))
|
||||
|
||||
const LOGIN_STATUS_LABELS: Record<string, string> = {
|
||||
waiting_login: '等待登录',
|
||||
qr_pending: '待扫码',
|
||||
scanned: '已扫码',
|
||||
authenticated: '已登录',
|
||||
failed: '登录失败',
|
||||
expired: '登录过期',
|
||||
}
|
||||
|
||||
const BINDING_STATUS_LABELS: Record<string, string> = {
|
||||
not_started: '未开始',
|
||||
qr_pending: '待扫码',
|
||||
scanned: '已扫码',
|
||||
role_ready: '待确认角色',
|
||||
confirmed: '已确认',
|
||||
failed: '绑定失败',
|
||||
expired: '已过期',
|
||||
}
|
||||
|
||||
const EXECUTION_STATUS_LABELS: Record<string, string> = {
|
||||
waiting_customer: '等待客户',
|
||||
waiting_operator: '等待客服',
|
||||
processing: '处理中',
|
||||
completed: '已完成',
|
||||
failed: '失败',
|
||||
cancelled: '已取消',
|
||||
}
|
||||
|
||||
type SemiAutoTaskHistoryDrawerProps = {
|
||||
open: boolean
|
||||
taskId: number | null
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function SemiAutoTaskHistoryDrawer({
|
||||
open,
|
||||
taskId,
|
||||
onClose,
|
||||
}: SemiAutoTaskHistoryDrawerProps) {
|
||||
const { message } = App.useApp()
|
||||
const isMobile = useIsMobile()
|
||||
const { token } = theme.useToken()
|
||||
const [tab, setTab] = useState('events')
|
||||
const [channel, setChannel] = useState('')
|
||||
const [status, setStatus] = useState('')
|
||||
const [keywordDraft, setKeywordDraft] = useState('')
|
||||
const [keyword, setKeyword] = useState('')
|
||||
const [requestId, setRequestId] = useState('')
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(50)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setTab('events')
|
||||
setChannel('')
|
||||
setStatus('')
|
||||
setKeywordDraft('')
|
||||
setKeyword('')
|
||||
setRequestId('')
|
||||
setPage(1)
|
||||
setPageSize(50)
|
||||
}, [open, taskId])
|
||||
|
||||
const params = useMemo(
|
||||
() => ({
|
||||
page,
|
||||
pageSize,
|
||||
channel: channel || undefined,
|
||||
status: status || undefined,
|
||||
keyword: keyword.trim() || undefined,
|
||||
requestId: requestId || undefined,
|
||||
}),
|
||||
[channel, keyword, page, pageSize, requestId, status],
|
||||
)
|
||||
|
||||
const historyQuery = useQuery({
|
||||
queryKey: ['admin-semi-auto-task-history', taskId, params],
|
||||
queryFn: () => fetchAdminSemiAutoTaskHistory(Number(taskId), params),
|
||||
enabled: open && Boolean(taskId),
|
||||
refetchInterval: open && Boolean(taskId) ? 8000 : false,
|
||||
})
|
||||
|
||||
const history = historyQuery.data?.data
|
||||
const events = history?.events || []
|
||||
const traces = history?.traces
|
||||
const traceItems = traces?.items || []
|
||||
const preStyle: CSSProperties = {
|
||||
margin: '6px 0 0',
|
||||
padding: 10,
|
||||
background: token.colorFillQuaternary,
|
||||
border: `1px solid ${token.colorBorderSecondary}`,
|
||||
borderRadius: token.borderRadius,
|
||||
color: token.colorText,
|
||||
fontSize: 12,
|
||||
lineHeight: 1.55,
|
||||
maxHeight: 320,
|
||||
overflow: 'auto',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-all',
|
||||
}
|
||||
|
||||
const copyText = (text: string, label: string) => {
|
||||
if (!text) {
|
||||
message.warning(`${label}为空`)
|
||||
return
|
||||
}
|
||||
void navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => message.success(`${label}已复制`))
|
||||
.catch(() => message.error('复制失败,请手动选择文本复制'))
|
||||
}
|
||||
|
||||
const eventsPanel = (
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
{history?.task ? (
|
||||
<Space size={6} wrap>
|
||||
<Tag color="blue">
|
||||
登录:{LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus}
|
||||
</Tag>
|
||||
<Tag color="gold">
|
||||
绑定:
|
||||
{history.task.platform === 'weibo'
|
||||
? '登录即授权'
|
||||
: BINDING_STATUS_LABELS[history.task.bindingStatus] || history.task.bindingStatus}
|
||||
</Tag>
|
||||
<Tag color="purple">
|
||||
执行:
|
||||
{EXECUTION_STATUS_LABELS[history.task.executionStatus] || history.task.executionStatus}
|
||||
</Tag>
|
||||
<Text type="secondary">创建 {formatAdminDateTime(history.task.createdAt)}</Text>
|
||||
{history.task.completedAt ? (
|
||||
<Text type="secondary">完成 {formatAdminDateTime(history.task.completedAt)}</Text>
|
||||
) : null}
|
||||
</Space>
|
||||
) : null}
|
||||
{history && history.eventTotal > events.length ? (
|
||||
<Text type="secondary">
|
||||
仅展示最近 {events.length} 条状态事件,共 {history.eventTotal} 条。
|
||||
</Text>
|
||||
) : null}
|
||||
{historyQuery.isLoading ? (
|
||||
<Text type="secondary">加载中...</Text>
|
||||
) : events.length === 0 ? (
|
||||
<Empty description="暂无状态流转记录" />
|
||||
) : (
|
||||
<Timeline
|
||||
items={events.map((event) => ({
|
||||
color: /fail|invalid|error|cancel/i.test(event.eventType) ? 'red' : 'blue',
|
||||
children: <EventItem event={event} preStyle={preStyle} />,
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
)
|
||||
|
||||
const tracesPanel = (
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部渠道"
|
||||
value={channel || undefined}
|
||||
onChange={(value) => {
|
||||
setChannel(value || '')
|
||||
setPage(1)
|
||||
}}
|
||||
options={CHANNEL_OPTIONS}
|
||||
style={isMobile ? { flex: '1 1 150px', minWidth: 120 } : { width: 160 }}
|
||||
/>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="全部结果"
|
||||
value={status || undefined}
|
||||
onChange={(value) => {
|
||||
setStatus(value || '')
|
||||
setPage(1)
|
||||
}}
|
||||
options={[
|
||||
{ value: 'ok', label: '成功' },
|
||||
{ value: 'error', label: '失败' },
|
||||
]}
|
||||
style={isMobile ? { flex: '1 1 110px', minWidth: 96 } : { width: 120 }}
|
||||
/>
|
||||
<Input.Search
|
||||
allowClear
|
||||
placeholder="动作 / 报文内容关键字"
|
||||
value={keywordDraft}
|
||||
onChange={(event) => setKeywordDraft(event.target.value)}
|
||||
onSearch={(value) => {
|
||||
setKeyword(value)
|
||||
setPage(1)
|
||||
}}
|
||||
style={isMobile ? { flex: '1 1 220px' } : { width: 240 }}
|
||||
/>
|
||||
<Button icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
|
||||
刷新
|
||||
</Button>
|
||||
{requestId ? (
|
||||
<Tag
|
||||
closable
|
||||
color="blue"
|
||||
onClose={() => {
|
||||
setRequestId('')
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
同一请求:{requestId}
|
||||
</Tag>
|
||||
) : null}
|
||||
</div>
|
||||
{traces?.summary?.length ? (
|
||||
<Space size={4} wrap>
|
||||
{traces.summary.map((item) => (
|
||||
<Tag
|
||||
key={`${item.channel}-${item.status}`}
|
||||
color={item.status === 'error' ? 'red' : 'default'}
|
||||
>
|
||||
{CHANNEL_LABELS[item.channel] || item.channel} ·{' '}
|
||||
{item.status === 'error' ? '失败' : '成功'} {item.total}
|
||||
</Tag>
|
||||
))}
|
||||
</Space>
|
||||
) : null}
|
||||
<Text type="secondary">报文保留 180 天;Cookie、Token、短信验证码和二维码内容不落库。</Text>
|
||||
{historyQuery.isLoading ? (
|
||||
<Text type="secondary">加载中...</Text>
|
||||
) : traceItems.length === 0 ? (
|
||||
<Empty description="暂无报文记录(当前只记录状态变化与失败,未变化的轮询不落库)" />
|
||||
) : (
|
||||
<Collapse
|
||||
size="small"
|
||||
items={traceItems.map((item) => ({
|
||||
key: String(item.id),
|
||||
label: <TraceLabel item={item} />,
|
||||
children: (
|
||||
<TracePayload
|
||||
item={item}
|
||||
preStyle={preStyle}
|
||||
onCopy={copyText}
|
||||
onFilterRequest={(value) => {
|
||||
setRequestId(value)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
<Pagination
|
||||
size={isMobile ? 'small' : undefined}
|
||||
current={traces?.pagination.page || page}
|
||||
pageSize={traces?.pagination.pageSize || pageSize}
|
||||
total={traces?.pagination.total || 0}
|
||||
showSizeChanger={!isMobile}
|
||||
showTotal={(total) => `共 ${total} 条`}
|
||||
onChange={(nextPage, nextPageSize) => {
|
||||
setPage(nextPage)
|
||||
setPageSize(nextPageSize)
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
)
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
width={isMobile ? '100%' : 960}
|
||||
title={history?.task ? `履约历史 · ${history.task.orderNo}` : '履约历史'}
|
||||
onClose={onClose}
|
||||
extra={
|
||||
<Button size="small" icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Tabs
|
||||
activeKey={tab}
|
||||
onChange={setTab}
|
||||
items={[
|
||||
{
|
||||
key: 'events',
|
||||
label: `状态流转(${history?.eventTotal ?? 0})`,
|
||||
children: eventsPanel,
|
||||
},
|
||||
{
|
||||
key: 'traces',
|
||||
label: `全链路报文(${traces?.pagination.total ?? 0})`,
|
||||
children: tracesPanel,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
function EventItem({
|
||||
event,
|
||||
preStyle,
|
||||
}: {
|
||||
event: SemiAutoTaskHistoryEvent
|
||||
preStyle: CSSProperties
|
||||
}) {
|
||||
const detail = event.detail || {}
|
||||
const detailKeys = Object.keys(detail)
|
||||
const transitions = [
|
||||
{
|
||||
label: '登录',
|
||||
map: LOGIN_STATUS_LABELS,
|
||||
from: event.fromLoginStatus,
|
||||
to: event.toLoginStatus,
|
||||
},
|
||||
{
|
||||
label: '绑定',
|
||||
map: BINDING_STATUS_LABELS,
|
||||
from: event.fromBindingStatus,
|
||||
to: event.toBindingStatus,
|
||||
},
|
||||
{
|
||||
label: '执行',
|
||||
map: EXECUTION_STATUS_LABELS,
|
||||
from: event.fromExecutionStatus,
|
||||
to: event.toExecutionStatus,
|
||||
},
|
||||
].filter((item) => item.from !== item.to && Boolean(item.from || item.to))
|
||||
|
||||
return (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%' }}>
|
||||
<Text strong>{EVENT_LABELS[event.eventType] || event.eventType}</Text>
|
||||
<Text type="secondary">
|
||||
{formatAdminDateTime(event.createdAt)} · {event.actorType}
|
||||
{event.actorId ? ` ${event.actorId}` : ''}
|
||||
</Text>
|
||||
{transitions.map((item) => (
|
||||
<Text key={item.label} type="secondary">
|
||||
{item.label}:{statusLabel(item.map, item.from)} → {statusLabel(item.map, item.to)}
|
||||
</Text>
|
||||
))}
|
||||
{detailKeys.length > 0 ? <pre style={preStyle}>{JSON.stringify(detail, null, 2)}</pre> : null}
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
|
||||
function TraceLabel({ item }: { item: SemiAutoTraceItem }) {
|
||||
return (
|
||||
<Space direction="vertical" size={2} style={{ width: '100%' }}>
|
||||
<Space size={6} wrap>
|
||||
<Tag color={item.direction === 'inbound' ? 'blue' : 'purple'}>
|
||||
{item.direction === 'inbound' ? '入站' : '出站'}
|
||||
</Tag>
|
||||
<Tag>{CHANNEL_LABELS[item.channel] || item.channel}</Tag>
|
||||
<Tag color={item.status === 'ok' ? 'green' : 'red'}>
|
||||
{item.status === 'ok' ? '成功' : '失败'}
|
||||
</Tag>
|
||||
{item.httpStatus ? <Text type="secondary">HTTP {item.httpStatus}</Text> : null}
|
||||
{item.durationMs !== null && item.durationMs !== undefined ? (
|
||||
<Text type="secondary">{item.durationMs}ms</Text>
|
||||
) : null}
|
||||
<Text type="secondary">{formatAdminDateTime(item.createdAt)}</Text>
|
||||
</Space>
|
||||
<Text code style={{ whiteSpace: 'break-all' }}>
|
||||
{item.action}
|
||||
</Text>
|
||||
{item.errorMessage ? <Text type="danger">{item.errorMessage}</Text> : null}
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
|
||||
function TracePayload({
|
||||
item,
|
||||
preStyle,
|
||||
onCopy,
|
||||
onFilterRequest,
|
||||
}: {
|
||||
item: SemiAutoTraceItem
|
||||
preStyle: CSSProperties
|
||||
onCopy: (text: string, label: string) => void
|
||||
onFilterRequest: (requestId: string) => void
|
||||
}) {
|
||||
return (
|
||||
<Space direction="vertical" size={10} style={{ width: '100%' }}>
|
||||
<PayloadBlock title="请求概要" value={item.requestSummary} preStyle={preStyle} />
|
||||
<PayloadBlock title="请求报文" value={item.requestBody} preStyle={preStyle} />
|
||||
<PayloadBlock title="响应概要" value={item.responseSummary} preStyle={preStyle} />
|
||||
<PayloadBlock title="响应报文" value={item.responseBody} preStyle={preStyle} />
|
||||
<Space size={6} wrap>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CopyOutlined />}
|
||||
onClick={() =>
|
||||
onCopy(
|
||||
[
|
||||
`动作:${item.action}`,
|
||||
`requestId:${item.requestId}`,
|
||||
'',
|
||||
'# 请求',
|
||||
item.requestBody,
|
||||
'',
|
||||
'# 响应',
|
||||
item.responseBody,
|
||||
].join('\n'),
|
||||
'完整报文',
|
||||
)
|
||||
}
|
||||
>
|
||||
复制完整报文
|
||||
</Button>
|
||||
{item.requestId ? (
|
||||
<Button size="small" onClick={() => onFilterRequest(item.requestId)}>
|
||||
只看同一请求
|
||||
</Button>
|
||||
) : null}
|
||||
<Text type="secondary">requestId:{item.requestId || '-'}</Text>
|
||||
</Space>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
|
||||
function PayloadBlock({
|
||||
title,
|
||||
value,
|
||||
preStyle,
|
||||
}: {
|
||||
title: string
|
||||
value: unknown
|
||||
preStyle: CSSProperties
|
||||
}) {
|
||||
const text =
|
||||
value && typeof value === 'object'
|
||||
? Object.keys(value as Record<string, unknown>).length > 0
|
||||
? JSON.stringify(value, null, 2)
|
||||
: ''
|
||||
: String(value || '').trim()
|
||||
return (
|
||||
<div>
|
||||
<Text strong>{title}</Text>
|
||||
{text ? <pre style={preStyle}>{text}</pre> : <Text type="secondary">(空)</Text>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function statusLabel(map: Record<string, string>, value: string | null) {
|
||||
if (!value) return '—'
|
||||
return map[value] || value
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
CheckCircleOutlined,
|
||||
ChromeOutlined,
|
||||
CopyOutlined,
|
||||
HistoryOutlined,
|
||||
KeyOutlined,
|
||||
ReloadOutlined,
|
||||
SendOutlined,
|
||||
@@ -30,6 +31,7 @@ import { useEffect, useMemo, useState } from 'react'
|
||||
|
||||
import ImageUpload from '@/components/files/ImageUpload'
|
||||
import PageHeader from '@/components/admin/PageHeader'
|
||||
import SemiAutoTaskHistoryDrawer from '@/components/admin/SemiAutoTaskHistoryDrawer'
|
||||
import PercentTable from '@/components/common/PercentTable'
|
||||
import {
|
||||
cancelAdminSemiAutoTask,
|
||||
@@ -94,6 +96,7 @@ export default function AdminSemiAutoTasksPage() {
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
const [detailTaskId, setDetailTaskId] = useState<number | null>(null)
|
||||
const [historyTaskId, setHistoryTaskId] = useState<number | null>(null)
|
||||
const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null)
|
||||
const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([])
|
||||
const [completeForm] = Form.useForm<CompleteFormValues>()
|
||||
@@ -416,6 +419,13 @@ export default function AdminSemiAutoTasksPage() {
|
||||
<Button size="small" onClick={() => setDetailTaskId(task.id)}>
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<HistoryOutlined />}
|
||||
onClick={() => setHistoryTaskId(task.id)}
|
||||
>
|
||||
历史
|
||||
</Button>
|
||||
{taskNeedsCustomerReauth(task) ? (
|
||||
<Button
|
||||
size="small"
|
||||
@@ -762,6 +772,12 @@ export default function AdminSemiAutoTasksPage() {
|
||||
)}
|
||||
</Drawer>
|
||||
|
||||
<SemiAutoTaskHistoryDrawer
|
||||
open={Boolean(historyTaskId)}
|
||||
taskId={historyTaskId}
|
||||
onClose={() => setHistoryTaskId(null)}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={Boolean(completeTask)}
|
||||
title="确认完成半自动履约"
|
||||
|
||||
@@ -2,6 +2,7 @@ import { apiGet, apiPost } from '@/lib/http'
|
||||
import type {
|
||||
SemiAutoCredentialExport,
|
||||
SemiAutoTaskDetail,
|
||||
SemiAutoTaskHistory,
|
||||
SemiAutoTaskListResult,
|
||||
} from '@/types/admin/semi-auto'
|
||||
|
||||
@@ -13,6 +14,13 @@ export function fetchAdminSemiAutoTask(taskId: number) {
|
||||
return apiGet<SemiAutoTaskDetail>(`/api/v1/admin/semi-auto/tasks/${taskId}`)
|
||||
}
|
||||
|
||||
export function fetchAdminSemiAutoTaskHistory(
|
||||
taskId: number,
|
||||
params: Record<string, unknown> = {},
|
||||
) {
|
||||
return apiGet<SemiAutoTaskHistory>(`/api/v1/admin/semi-auto/tasks/${taskId}/history`, params)
|
||||
}
|
||||
|
||||
export function exportAdminSemiAutoCredential(taskId: number) {
|
||||
return apiPost<SemiAutoCredentialExport>(
|
||||
`/api/v1/admin/semi-auto/tasks/${taskId}/credential/export`,
|
||||
|
||||
@@ -81,6 +81,65 @@ export type SemiAutoTaskDetail = {
|
||||
events: SemiAutoTaskEvent[]
|
||||
}
|
||||
|
||||
export type SemiAutoTaskHistoryEvent = {
|
||||
id: number
|
||||
eventType: string
|
||||
actorType: string
|
||||
actorId: string
|
||||
fromLoginStatus: string | null
|
||||
toLoginStatus: string | null
|
||||
fromBindingStatus: string | null
|
||||
toBindingStatus: string | null
|
||||
fromExecutionStatus: string | null
|
||||
toExecutionStatus: string | null
|
||||
detail: Record<string, unknown>
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export type SemiAutoTraceItem = {
|
||||
id: number
|
||||
orderNo: string
|
||||
requestId: string
|
||||
direction: 'inbound' | 'outbound' | string
|
||||
channel: string
|
||||
action: string
|
||||
status: 'ok' | 'error' | string
|
||||
httpStatus: number | null
|
||||
durationMs: number | null
|
||||
requestSummary: Record<string, unknown>
|
||||
requestBody: string
|
||||
responseSummary: Record<string, unknown>
|
||||
responseBody: string
|
||||
errorMessage: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export type SemiAutoTraceSummaryItem = {
|
||||
channel: string
|
||||
status: string
|
||||
total: number
|
||||
}
|
||||
|
||||
export type SemiAutoTraceQueryParams = {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
channel?: string
|
||||
status?: string
|
||||
requestId?: string
|
||||
keyword?: string
|
||||
}
|
||||
|
||||
export type SemiAutoTaskHistory = {
|
||||
task: SemiAutoTask
|
||||
events: SemiAutoTaskHistoryEvent[]
|
||||
eventTotal: number
|
||||
traces: {
|
||||
pagination: { page: number; pageSize: number; total: number }
|
||||
summary: SemiAutoTraceSummaryItem[]
|
||||
items: SemiAutoTraceItem[]
|
||||
}
|
||||
}
|
||||
|
||||
export type SemiAutoCredentialExport = {
|
||||
credentialId: number
|
||||
platform: SemiAutoPlatform
|
||||
|
||||
Reference in New Issue
Block a user