diff --git a/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql b/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql new file mode 100644 index 00000000..3bc07fea --- /dev/null +++ b/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql @@ -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、密钥不落库)'; diff --git a/apps/backend/src/index.ts b/apps/backend/src/index.ts index 15758f51..8746c200 100644 --- a/apps/backend/src/index.ts +++ b/apps/backend/src/index.ts @@ -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) diff --git a/apps/backend/src/middleware/semi-auto-trace.ts b/apps/backend/src/middleware/semi-auto-trace.ts new file mode 100644 index 00000000..13cb4c62 --- /dev/null +++ b/apps/backend/src/middleware/semi-auto-trace.ts @@ -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() + +/** 响应里代表「状态」的字段:轮询指纹只取这些,时间戳/计数变化不算状态变化。 */ +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 { + 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 + const masked: Record = {} + 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 + const picked: Record = {} + 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) : {} + 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) : {} + 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('')) + } +} diff --git a/apps/backend/src/routes/admin/semi-auto.ts b/apps/backend/src/routes/admin/semi-auto.ts index 312bfb08..7834d480 100644 --- a/apps/backend/src/routes/admin/semi-auto.ts +++ b/apps/backend/src/routes/admin/semi-auto.ts @@ -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), + { + successMessage: 'ok', + errorMessage: '读取半自动履约历史失败', + scope: '[admin/semi-auto/tasks/:taskId/history]', + }, + ), +) + router.post( '/semi-auto/tasks/:taskId/credential/export', createJsonHandler( diff --git a/apps/backend/src/routes/customer-fulfillment.ts b/apps/backend/src/routes/customer-fulfillment.ts index 2343308d..e6d80f07 100644 --- a/apps/backend/src/routes/customer-fulfillment.ts +++ b/apps/backend/src/routes/customer-fulfillment.ts @@ -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, diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.ts b/apps/backend/src/services/semi-auto/huya-connector-client.ts index bae6640b..3a57621b 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -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( 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( } 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( } 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 请求超时', { diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts index 1135af87..9f2f0fe5 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts @@ -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 { - 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 { - 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 { - 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 { 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 = {}) => { + 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 = {}) => { + 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: { diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index 97a75624..18994e1d 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -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 + created_at: string +} + +/** + * 运营端「历史」:任务状态流转事件 + 全链路报文(本系统入站 + 外部平台出站)。 + * 报文只读,不做任何写操作;Cookie / Token 已在落库前脱敏。 + */ +export async function getAdminSemiAutoTaskHistory( + taskIdInput: unknown, + input: Record = {}, +) { + 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( + `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) { diff --git a/apps/backend/src/services/semi-auto/semi-auto-trace.ts b/apps/backend/src/services/semi-auto/semi-auto-trace.ts new file mode 100644 index 00000000..0788d1a7 --- /dev/null +++ b/apps/backend/src/services/semi-auto/semi-auto-trace.ts @@ -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 + requestBody?: unknown + responseSummary?: Record + responseBody?: unknown + errorMessage?: string + /** 写操作/关键读:无条件记录(轮询类不要传)。 */ + always?: boolean + /** 轮询类请求的状态指纹:与上次相同则不记录。 */ + fingerprint?: string | undefined +} + +const traceStorage = new AsyncLocalStorage() +const lastFingerprints = new Map() + +/** 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(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 + const result: Record = {} + 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?.() +} diff --git a/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx new file mode 100644 index 00000000..10837271 --- /dev/null +++ b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx @@ -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 = { + 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 = { + 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 = { + waiting_login: '等待登录', + qr_pending: '待扫码', + scanned: '已扫码', + authenticated: '已登录', + failed: '登录失败', + expired: '登录过期', +} + +const BINDING_STATUS_LABELS: Record = { + not_started: '未开始', + qr_pending: '待扫码', + scanned: '已扫码', + role_ready: '待确认角色', + confirmed: '已确认', + failed: '绑定失败', + expired: '已过期', +} + +const EXECUTION_STATUS_LABELS: Record = { + 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 = ( + + {history?.task ? ( + + + 登录:{LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus} + + + 绑定: + {history.task.platform === 'weibo' + ? '登录即授权' + : BINDING_STATUS_LABELS[history.task.bindingStatus] || history.task.bindingStatus} + + + 执行: + {EXECUTION_STATUS_LABELS[history.task.executionStatus] || history.task.executionStatus} + + 创建 {formatAdminDateTime(history.task.createdAt)} + {history.task.completedAt ? ( + 完成 {formatAdminDateTime(history.task.completedAt)} + ) : null} + + ) : null} + {history && history.eventTotal > events.length ? ( + + 仅展示最近 {events.length} 条状态事件,共 {history.eventTotal} 条。 + + ) : null} + {historyQuery.isLoading ? ( + 加载中... + ) : events.length === 0 ? ( + + ) : ( + ({ + color: /fail|invalid|error|cancel/i.test(event.eventType) ? 'red' : 'blue', + children: , + }))} + /> + )} + + ) + + const tracesPanel = ( + +
+ { + setStatus(value || '') + setPage(1) + }} + options={[ + { value: 'ok', label: '成功' }, + { value: 'error', label: '失败' }, + ]} + style={isMobile ? { flex: '1 1 110px', minWidth: 96 } : { width: 120 }} + /> + setKeywordDraft(event.target.value)} + onSearch={(value) => { + setKeyword(value) + setPage(1) + }} + style={isMobile ? { flex: '1 1 220px' } : { width: 240 }} + /> + + {requestId ? ( + { + setRequestId('') + setPage(1) + }} + > + 同一请求:{requestId} + + ) : null} +
+ {traces?.summary?.length ? ( + + {traces.summary.map((item) => ( + + {CHANNEL_LABELS[item.channel] || item.channel} ·{' '} + {item.status === 'error' ? '失败' : '成功'} {item.total} + + ))} + + ) : null} + 报文保留 180 天;Cookie、Token、短信验证码和二维码内容不落库。 + {historyQuery.isLoading ? ( + 加载中... + ) : traceItems.length === 0 ? ( + + ) : ( + ({ + key: String(item.id), + label: , + children: ( + { + setRequestId(value) + setPage(1) + }} + /> + ), + }))} + /> + )} + `共 ${total} 条`} + onChange={(nextPage, nextPageSize) => { + setPage(nextPage) + setPageSize(nextPageSize) + }} + /> +
+ ) + + return ( + } onClick={() => void historyQuery.refetch()}> + 刷新 + + } + > + + + ) +} + +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 ( + + {EVENT_LABELS[event.eventType] || event.eventType} + + {formatAdminDateTime(event.createdAt)} · {event.actorType} + {event.actorId ? ` ${event.actorId}` : ''} + + {transitions.map((item) => ( + + {item.label}:{statusLabel(item.map, item.from)} → {statusLabel(item.map, item.to)} + + ))} + {detailKeys.length > 0 ?
{JSON.stringify(detail, null, 2)}
: null} +
+ ) +} + +function TraceLabel({ item }: { item: SemiAutoTraceItem }) { + return ( + + + + {item.direction === 'inbound' ? '入站' : '出站'} + + {CHANNEL_LABELS[item.channel] || item.channel} + + {item.status === 'ok' ? '成功' : '失败'} + + {item.httpStatus ? HTTP {item.httpStatus} : null} + {item.durationMs !== null && item.durationMs !== undefined ? ( + {item.durationMs}ms + ) : null} + {formatAdminDateTime(item.createdAt)} + + + {item.action} + + {item.errorMessage ? {item.errorMessage} : null} + + ) +} + +function TracePayload({ + item, + preStyle, + onCopy, + onFilterRequest, +}: { + item: SemiAutoTraceItem + preStyle: CSSProperties + onCopy: (text: string, label: string) => void + onFilterRequest: (requestId: string) => void +}) { + return ( + + + + + + + + {item.requestId ? ( + + ) : null} + requestId:{item.requestId || '-'} + + + ) +} + +function PayloadBlock({ + title, + value, + preStyle, +}: { + title: string + value: unknown + preStyle: CSSProperties +}) { + const text = + value && typeof value === 'object' + ? Object.keys(value as Record).length > 0 + ? JSON.stringify(value, null, 2) + : '' + : String(value || '').trim() + return ( +
+ {title} + {text ?
{text}
: (空)} +
+ ) +} + +function statusLabel(map: Record, value: string | null) { + if (!value) return '—' + return map[value] || value +} diff --git a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx index fea9e891..91365073 100644 --- a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx +++ b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx @@ -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(null) + const [historyTaskId, setHistoryTaskId] = useState(null) const [completeTask, setCompleteTask] = useState(null) const [completeFiles, setCompleteFiles] = useState([]) const [completeForm] = Form.useForm() @@ -416,6 +419,13 @@ export default function AdminSemiAutoTasksPage() { + {taskNeedsCustomerReauth(task) ? (