From 3c0c7634c581895c9555da01d09ccb90707996c8 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 10 Nov 2026 02:42:16 +0800 Subject: [PATCH] =?UTF-8?q?fix(inbox):=20notify.reply=20=E6=8C=89=E7=BE=A4?= =?UTF-8?q?/=E6=B6=88=E6=81=AF=E6=9D=A5=E6=BA=90=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E5=9B=9E=E6=89=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 同一仓库存在多个仓库级 API 应用且都勾选 notify.reply 时,回执按 id 升序逐个尝试, 可能被首个返回 200 的其它适配器接走,导致错投且被记为已送达。 - receiver: 群已存在时补写空白的 source_type/source_extra,来源不一致仅告警不覆盖 - processor: 回执来源优先级改为 群(wms_inbox_group) → 入站消息 → ext_id 解析, 来源应用承接时只发给它;来源缺失或未承接时保持原候选顺序并告警 - warehouseNotify: push 支持 preferredAppKey,系统通知按群来源应用发送 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- app/service/inbox/processor.js | 104 ++++++++++++++++++++++++- app/service/inbox/receiver.js | 28 ++++++- app/service/systems/warehouseNotify.js | 67 +++++++++++++++- 3 files changed, 191 insertions(+), 8 deletions(-) diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index 594001a..19e13ff 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -527,8 +527,16 @@ class InboxProcessorService extends Service { } const ackExtId = `sys:ack:${extId}`; - // 多候选路由:按 method 查询全部承接应用(id 升序),逐个尝试直到成功 - const callbackConfigs = await this.listApiAppCallbackConfigs(warehouseId, 'notify.reply'); + // 多候选路由:按 method 查询全部承接应用(id 升序),逐个尝试直到成功。 + // 同一仓库可能存在多个仓库级 API 应用,必须先按「群/消息来源应用」收敛候选 + // (群以 wms_inbox_group 为准):否则回执可能被首个返回 200 的其它适配器接走, + // 错投且被记为已送达。 + const sourceAppKey = await this.resolveReplySourceAppKey({ parentId, groupId, warehouseId, extId }); + const callbackConfigs = this.orderCallbackConfigsBySource( + await this.listApiAppCallbackConfigs(warehouseId, 'notify.reply'), + sourceAppKey, + { warehouseId, extId } + ); // 重推(reuse_message_id>0):直接复用原记录,避免按 sys:ack: 前缀另建一条记录—— // 那样会让原记录(如 sys:notice:* 系统通知)状态永远停留在失败/待推送,且每次重推都新建记录 // 声明在 try 之外:异常兜底回写失败状态时仍需定位到该记录 @@ -903,6 +911,98 @@ class InboxProcessorService extends Service { } } + /** + * 从来源记录中提取仓库级 API 应用的 AppKey。 + * 仅 source_type='api' 时 source_extra 才是 appKey(IM 来源存的是平台标识)。 + * @param {Object|null} row 入站消息或群记录。 + * @return {string|null} 来源应用 AppKey。 + */ + pickApiSourceAppKey(row) { + if (!row || String(row.source_type || '') !== 'api') return null; + const appKey = String(row.source_extra || '').trim(); + return appKey || null; + } + + /** + * 解析回执应发往的来源应用 AppKey。 + * 优先级:群创建来源(wms_inbox_group 为准)→ 入站消息来源 → ext_id(api:{appKey}:{requestId})兜底。 + * 群是站内信的会话归属中心,内部通知与回执都从群配置出发,优先按群来源收敛候选。 + * @param {Object} options 解析参数。 + * @param {number} [options.parentId] 入站消息记录 ID。 + * @param {string} [options.groupId] 外部群 ID。 + * @param {number} [options.warehouseId] 仓库 ID。 + * @param {string} [options.extId] 入站消息 ext_id。 + * @return {Promise} 来源应用 AppKey。 + */ + async resolveReplySourceAppKey({ parentId, groupId, warehouseId, extId } = {}) { + const { ctx } = this; + + const groupIdStr = String(groupId || '').trim(); + if (groupIdStr && Number(warehouseId) > 0) { + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'source_type', 'source_extra' ], + where: { group_id: groupIdStr, warehouse_id: Number(warehouseId) }, + raw: true, + }); + const appKey = this.pickApiSourceAppKey(group); + if (appKey) return appKey; + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询群来源失败: ${error.message}`); + } + } + + const inboundId = Number(parentId) || 0; + if (inboundId > 0) { + try { + const row = await ctx.model.InboxMessage.findOne({ + attributes: [ 'source_type', 'source_extra' ], + where: { id: inboundId, warehouse_id: Number(warehouseId) || 0 }, + raw: true, + }); + const appKey = this.pickApiSourceAppKey(row); + if (appKey) return appKey; + } catch (error) { + ctx.logger.warn(`[inbox processor] 查询入站消息来源失败: ${error.message}`); + } + } + + // ext_id 约定:api:{appKey}:{requestId} + const matched = /^api:([^:]+):/.exec(String(extId || '')); + return matched ? matched[1] : null; + } + + /** + * 按来源应用收敛回执候选:来源应用承接时只发给它,避免多应用错投; + * 来源缺失或未承接时保持原有候选顺序(兼容旧行为)并记录告警。 + * @param {Array} candidates 候选应用列表(含 appKey)。 + * @param {string|null} sourceAppKey 来源应用 AppKey。 + * @param {Object} [context] 日志上下文。 + * @param {number} [context.warehouseId] 仓库 ID。 + * @param {string} [context.extId] 消息 ext_id。 + * @return {Array} 收敛后的候选列表。 + */ + orderCallbackConfigsBySource(candidates, sourceAppKey, { warehouseId, extId } = {}) { + const list = Array.isArray(candidates) ? candidates : []; + if (list.length <= 1) return list; + + const sourceKey = String(sourceAppKey || '').trim(); + if (!sourceKey) { + this.ctx.logger.warn( + `[inbox processor] 无法确定回执来源应用,按候选顺序尝试 warehouse=${warehouseId} ext_id=${extId} candidates=${list.length}` + ); + return list; + } + + const matched = list.filter(item => String(item.appKey || '').trim() === sourceKey); + if (matched.length > 0) return matched; + + this.ctx.logger.warn( + `[inbox processor] 来源应用未承接 notify.reply,按候选顺序兜底 warehouse=${warehouseId} source_app=${sourceKey} ext_id=${extId} candidates=${list.length}` + ); + return list; + } + /** * 单次回执推送尝试(回执专用协议:MD5(appSecret+timestamp+bodyJson) + POST)。 * 每次尝试均写 wms_warehouse_log,失败不改动接口配置。 diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index 38fee5b..799ba54 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -156,14 +156,34 @@ class InboxReceiverService extends Service { }); if (group) { - // 群已存在:名称变化时更新名称,不新建 - if (group.group_name !== groupName) { - const oldName = group.group_name; - await group.update({ group_name: groupName }); + // 群已存在:名称变化时更新名称,不新建。 + // 来源字段为空时补写(用于出站 notify.reply 按来源应用路由); + // 已有来源且与本次不一致时不覆盖,避免多应用共用群时归属被反复改写。 + const patch = {}; + const oldName = group.group_name; + if (oldName !== groupName) { + patch.group_name = groupName; + } + if (!group.source_type && sourceType) { + patch.source_type = sourceType; + } + if (!group.source_extra && data.source_extra) { + patch.source_extra = data.source_extra; + } + if (Object.keys(patch).length > 0) { + await group.update(patch); + } + if (patch.group_name) { ctx.logger.info( `[inbox] 群名称已更新 group_id=${extGroupId}: ${oldName} → ${groupName}` ); } + if (group.source_extra && data.source_extra + && String(group.source_extra) !== String(data.source_extra)) { + ctx.logger.warn( + `[inbox] 群来源不一致 group_id=${extGroupId} existing=${group.source_extra} incoming=${data.source_extra}` + ); + } } else { // 群ID不存在:按群ID直接新建(群以ID为准,不按名称匹配既有群) await ctx.model.InboxGroup.create({ diff --git a/app/service/systems/warehouseNotify.js b/app/service/systems/warehouseNotify.js index 526b310..026ac7d 100644 --- a/app/service/systems/warehouseNotify.js +++ b/app/service/systems/warehouseNotify.js @@ -120,6 +120,60 @@ class WarehouseNotifyService extends Service { } } + /** + * 按来源应用收敛候选:来源应用承接时只发给它,避免多应用错投; + * 来源缺失或未承接时保持原有候选顺序(兼容旧行为)并记录告警。 + * @param {Array} candidates 候选应用列表(含 appKey)。 + * @param {string|null} preferredAppKey 期望的目标应用 AppKey。 + * @param {number} warehouseId 仓库 ID。 + * @return {Array} 收敛后的候选列表。 + */ + orderCandidatesBySource(candidates, preferredAppKey, warehouseId) { + const list = Array.isArray(candidates) ? candidates : []; + if (list.length <= 1) return list; + + const appKey = String(preferredAppKey || '').trim(); + if (!appKey) { + this.ctx.logger.warn( + `[warehouseNotify] 无法确定来源应用,按候选顺序尝试 warehouse=${warehouseId} candidates=${list.length}` + ); + return list; + } + + const matched = list.filter(item => String(item.appKey || '').trim() === appKey); + if (matched.length > 0) return matched; + + this.ctx.logger.warn( + `[warehouseNotify] 来源应用未承接回调,按候选顺序兜底 warehouse=${warehouseId} source_app=${appKey} candidates=${list.length}` + ); + return list; + } + + /** + * 读取群的创建来源应用 AppKey(仅 source_type='api' 时有效)。 + * @param {string} groupId 外部群 ID。 + * @param {number} warehouseId 仓库 ID。 + * @return {Promise} 来源应用 AppKey。 + */ + async resolveGroupSourceAppKey(groupId, warehouseId) { + const { ctx } = this; + const groupIdStr = String(groupId || '').trim(); + if (!groupIdStr || !Number(warehouseId)) return null; + + try { + const group = await ctx.model.InboxGroup.findOne({ + attributes: [ 'source_type', 'source_extra' ], + where: { group_id: groupIdStr, warehouse_id: Number(warehouseId) }, + raw: true, + }); + if (!group || String(group.source_type || '') !== 'api') return null; + return String(group.source_extra || '').trim() || null; + } catch (error) { + ctx.logger.warn(`[warehouseNotify] 查询群来源失败: ${error.message}`); + return null; + } + } + /** * 计算 MD5 签名:MD5(appSecret + timestamp + bodyJson)。 * @param {Object} options 签名参数。 @@ -268,17 +322,23 @@ class WarehouseNotifyService extends Service { * 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。 * 路由规则:查承接该 method 的全部候选应用(按 id 升序)逐个尝试, * 第一个成功即返回;全部失败返回失败且不改动任何接口配置。 + * 传入 preferredAppKey 时优先只发给该应用(来源亲和),避免多应用场景错投。 * @param {Object} options 推送参数。 * @param {number} options.warehouseId 仓库 ID。 * @param {string} [options.method='notify.reply'] 出站 method。 * @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。 + * @param {string} [options.preferredAppKey=null] 期望的目标应用 AppKey。 * @return {Promise} 推送结果(含 attempts 明细)。 */ - async push({ warehouseId, method = 'notify.reply', data = {} } = {}) { + async push({ warehouseId, method = 'notify.reply', data = {}, preferredAppKey = null } = {}) { const { ctx } = this; const methodStr = String(method || '').trim() || 'notify.reply'; - const candidates = await this.listCallbackConfigs(warehouseId, methodStr); + const candidates = this.orderCandidatesBySource( + await this.listCallbackConfigs(warehouseId, methodStr), + preferredAppKey, + warehouseId + ); if (candidates.length === 0) { ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 无应用承接回调 method=${methodStr},跳过推送`); return { @@ -469,10 +529,13 @@ class WarehouseNotifyService extends Service { pushData.user_id = normalizedUserIds; } + // 群来源应用优先:同一仓库多应用承接 notify.reply 时避免系统通知错投渠道 + const preferredAppKey = await this.resolveGroupSourceAppKey(groupId, warehouseId); const result = await this.push({ warehouseId, method: 'notify.reply', data: pushData, + preferredAppKey, }); // 回写推送状态(失败仅记日志,不影响业务)