fix(qimen): 出站请求日志使用独立 log_id 并幂等消费日志队列

- qimen_client.sendRequest 出站日志改为 generateLogId() 生成 QL-<时间戳>-<随机>,
  不再复用入站 ctx.qimenLogId,避免与入站文件队列落库撞 wms_qimen_log.log_id 唯一索引
- qimen.saveQimenLog 去掉 ctx.qimenLogId 兜底;saveQimenLogResult / saveQimenLogBody
  改为按 log_id 定位更新(原先按 id 字段更新与调用语义不符)
- schedule/consume_qimen_logs 插入遇 ER_DUP_ENTRY 视为幂等命中跳过并推进消费进度,
  避免重复日志卡死文件队列
- test: qimen_query.test.js 断言改为校验新 log_id 格式
This commit is contained in:
liufumingren 2026-09-13 15:29:43 +08:00
parent d725e7e457
commit cf3b9092c6
4 changed files with 72 additions and 15 deletions

View File

@ -1,7 +1,8 @@
'use strict';
const https = require('https');
const crypto = require('crypto');
const http = require('http');
const https = require('https');
class QimenClient {
constructor(app) {
@ -15,7 +16,6 @@ class QimenClient {
return {
ctx,
qimenLogId: runtime.qimenLogId ?? ctx.qimenLogId ?? null,
toXml: runtime.toXml || (signService && typeof signService.toXml === 'function'
? signService.toXml.bind(signService)
: qimenService && typeof qimenService.formatResponse === 'function'
@ -46,6 +46,15 @@ class QimenClient {
return { request: data };
}
/**
* 生成出站奇门请求的唯一日志 ID。
* 不复用入站请求的 ctx.qimenLogId,避免与入站文件队列落库产生唯一索引冲突。
* @return {string} 唯一日志 ID。
*/
generateLogId() {
return `QL-${Date.now()}-${crypto.randomBytes(3).toString('hex')}`;
}
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi');
const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi');
@ -182,18 +191,30 @@ class QimenClient {
return { queryId: result.queryId, xmlArray };
}
/**
* 发送出站奇门 HTTP 请求,并把出站请求日志直接落库。
* 出站日志使用独立生成的 log_id,不复用入站请求的 ctx.qimenLogId,
* 避免与入站日志的文件队列落库路径产生 log_id 唯一索引冲突。
* @param {string} url 请求地址。
* @param {Object|string} requestData 请求数据(对象或 XML 字符串)。
* @param {Object} [logData={}] 日志附加字段。
* @param {Object} [runtime={}] 运行时依赖。
* @return {Promise<{queryId: number|undefined, res: string}>} 查询 ID 与响应内容。
*/
async sendRequest(url, requestData, logData = {}, runtime = {}) {
const helpers = this.resolveRuntime(runtime);
const startTime = Date.now();
// 出站请求不复用入站 ctx.qimenLogId:入站日志统一由文件队列异步落库,
// log_id 唯一索引下共用同一 ID 会触发 Duplicate entry 冲突。
const requestLogData = Object.assign({
body: requestData,
result: '',
log_id: helpers.qimenLogId,
log_id: this.generateLogId(),
}, logData);
requestLogData.body = requestLogData.body || requestData;
requestLogData.result = requestLogData.result || '';
requestLogData.log_id = requestLogData.log_id || helpers.qimenLogId || null;
requestLogData.log_id = requestLogData.log_id || this.generateLogId();
const httpquery = url.indexOf('https://') > -1 ? https : http;
let requestXml;

View File

@ -3,10 +3,11 @@
const path = require('path');
/**
* 定时消费奇门日志文件队列,逐条插入数据库。
* 定时消费奇门日志文件队列,逐条幂等插入数据库。
* 间隔 30 秒执行,type: worker(仅一个 worker 执行)。
* 使用 fileWriter.consumeFiles 内置的逐条进度追踪,
* 任一记录插入失败即停止,下次从失败位置重试。
* 同一 log_id 已落库时视为幂等命中直接跳过,避免唯一索引冲突卡死队列。
*/
module.exports = {
schedule: {
@ -16,6 +17,11 @@ module.exports = {
disable: false,
},
/**
* 消费奇门日志队列任务入口。
* @param {Egg.Context} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
// 防止重入
if (ctx.app._consumeQimenLogsRunning) return;
@ -32,7 +38,7 @@ module.exports = {
maxConsumeRecordsPerWindow: 500,
parseJson: true,
onRecord: async record => {
await mysql.insert('wms_qimen_log', {
const row = {
log_id: record.log_id || null,
from_key: record.from_key || '',
to_key: record.to_key || '',
@ -45,7 +51,17 @@ module.exports = {
body: record.body || '',
result: record.result || '',
use_time: record.use_time || 0,
});
};
try {
await mysql.insert('wms_qimen_log', row);
} catch (err) {
const isDuplicate = !!err && (err.code === 'ER_DUP_ENTRY' || err.errno === 1062);
if (!isDuplicate) {
throw err;
}
// 同一 log_id 已落库时视为幂等命中,跳过并继续推进消费进度
ctx.logger.warn(`[consume-qimen-logs] 跳过重复日志 log_id=${row.log_id}`);
}
},
});

View File

@ -230,10 +230,12 @@ class QimenService extends Service {
});
}
/**
* 保存奇门请求日志。
* @param {Object} logData 日志数据。
* 保存出站奇门请求日志(直接落库)。
* 仅用于出站请求(qimenClient.sendRequest)的日志落库;
* 入站请求日志统一走文件队列异步消费落库,避免同一 log_id 双写入冲突。
* @param {Object} logData 日志数据,需包含 log_id 等字段。
* @param {number} startTime 请求开始时间戳。
* @return {Promise<number|undefined>} 新增日志ID。
* @return {Promise<number|undefined>} 新增日志主键 ID,失败时返回 undefined。
*/
async saveQimenLog(logData, startTime) {
const {
@ -252,9 +254,10 @@ class QimenService extends Service {
logData.use_time = Date.now() - startTime;
// 使用 egg-mysql 保存日志到数据库
// 不再回退使用 ctx.qimenLogId:入站 log_id 已由文件队列消费落库,
// 出站复用会触发唯一索引冲突,出站日志必须使用自身生成的 log_id。
const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', {
log_id: logData.log_id || ctx.qimenLogId || null,
log_id: logData.log_id || null,
from_key: logData.from_key || '',
to_key: logData.to_key || '',
method: logData.method || '',
@ -274,11 +277,27 @@ class QimenService extends Service {
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
}
}
/**
* 按 log_id 更新奇门请求日志的响应内容。
* @param {string} result 响应内容。
* @return {Promise<Object>} 数据库更新结果。
*/
async saveQimenLogResult(result) {
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { result, id: this.ctx.qimenLogId });
const { ctx } = this;
await ctx.app.mysql.get('wms').update('wms_qimen_log', { result }, {
where: { log_id: ctx.qimenLogId },
});
}
/**
* 按 log_id 更新奇门请求日志的请求体内容。
* @param {string} body 请求体内容。
* @return {Promise<Object>} 数据库更新结果。
*/
async saveQimenLogBody(body) {
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { body, id: this.ctx.qimenLogId });
const { ctx } = this;
await ctx.app.mysql.get('wms').update('wms_qimen_log', { body }, {
where: { log_id: ctx.qimenLogId },
});
}
}

View File

@ -52,7 +52,8 @@ describe('test/app/service/systems/qimen_query.test.js', () => {
}
assert.ok(savedLog);
assert.equal(savedLog.log_id, 'QL-20260414-abc123');
// 出站日志不复用入站 ctx.qimenLogId,使用独立生成的 log_id,避免唯一索引冲突
assert.match(savedLog.log_id, /^QL-\d{13}-[0-9a-f]{6}$/);
assert.equal(savedLog.body, '<request/>');
assert.match(savedLog.result, /network down/);
});