From 8b978f50ec906d465b952f56ea86ee38523ac0b2 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 3 Aug 2026 02:01:02 +0800 Subject: [PATCH] =?UTF-8?q?fix(inbox):=20=E4=BF=AE=E5=A4=8D=E8=BE=B9?= =?UTF-8?q?=E7=95=8C=E7=BC=BA=E5=8F=A3=20=E2=80=94=20=E6=9E=9A=E4=B8=BE?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E3=80=81parent=5Fid=E5=AD=98=E5=9C=A8?= =?UTF-8?q?=E6=80=A7=E3=80=81=E8=BD=AF=E5=88=A0=E9=99=A4=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E3=80=81thread=E9=98=B2=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/service/inbox/index.js | 17 +++- app/service/inbox/receiver.js | 159 ++++++++++++++++++++-------------- 2 files changed, 106 insertions(+), 70 deletions(-) diff --git a/app/service/inbox/index.js b/app/service/inbox/index.js index 6a68f32..3d2d9e2 100644 --- a/app/service/inbox/index.js +++ b/app/service/inbox/index.js @@ -35,6 +35,7 @@ class InboxService extends Service { const where = { warehouse_id: warehouseId, + deleted_at: null, }; if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) { @@ -105,7 +106,7 @@ class InboxService extends Service { } const record = await InboxMessage.findOne({ - where: { id, warehouse_id: warehouseId }, + where: { id, warehouse_id: warehouseId, deleted_at: null }, }); if (!record) { @@ -146,18 +147,26 @@ class InboxService extends Service { } // 收集对话链:从根到叶 + const MAX_THREAD_DEPTH = 50; const thread = [ root ]; + const visited = new Set([ root.id ]); // 查找所有回信(以 root.id 为 parent_id) const replies = await InboxMessage.findAll({ where: { warehouse_id: warehouseId, parent_id: root.id, + deleted_at: null, }, order: [[ 'created_at', 'ASC' ]], }); - thread.push(...replies); + for (const reply of replies) { + if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(reply.id); + thread.push(reply); + } + } // 如果当前消息不是根(有 parent_id),也向上查找原消息 if (root.parent_id) { @@ -165,10 +174,12 @@ class InboxService extends Service { where: { id: root.parent_id, warehouse_id: warehouseId, + deleted_at: null, }, }); - if (parent) { + if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) { + visited.add(parent.id); thread.unshift(parent); } } diff --git a/app/service/inbox/receiver.js b/app/service/inbox/receiver.js index fd9433a..81bab94 100644 --- a/app/service/inbox/receiver.js +++ b/app/service/inbox/receiver.js @@ -5,16 +5,16 @@ const Service = require('egg').Service; const { URL } = require('url'); const { networkInterfaces } = require('os'); -/** 推送 body 大小上限:64KB */ +/** 推�?body 大小上限�?4KB */ const MAX_PUSH_BODY_SIZE = 64 * 1024; -/** 最大重试次数 */ +/** 最大重试次�?*/ const MAX_RETRY_COUNT = 3; /** 僵尸恢复阈值:5分钟 */ const ZOMBIE_RECOVERY_MINUTES = 5; /** - * 收集本机所有内网 IPv4 地址。 - * @return {string[]} 内网IP地址列表。 + * 收集本机所有内�?IPv4 地址�? + * @return {string[]} 内网IP地址列表�? */ function getLocalInternalIps() { const ips = new Set(); @@ -38,9 +38,9 @@ const INTERNAL_IP_PREFIXES = [ ]; /** - * 判断给定 IP 是否属于本机内网IP。 - * @param {string} ip IP地址。 - * @return {boolean} 是否为内网IP。 + * 判断给定 IP 是否属于本机内网IP�? + * @param {string} ip IP地址�? + * @return {boolean} 是否为内网IP�? */ function isInternalIp(ip) { if (!ip || ip === 'localhost') return true; @@ -50,7 +50,7 @@ function isInternalIp(ip) { if (ip.startsWith(prefix)) return true; } - // 检查 172.16.0.0 ~ 172.31.255.255 + // 检�?172.16.0.0 ~ 172.31.255.255 const parts = ip.split('.').map(Number); if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) { return true; @@ -64,9 +64,9 @@ function isInternalIp(ip) { } /** - * 校验 target_url 安全性:仅允许 https://,禁止内网IP。 - * @param {string} urlStr 目标URL。 - * @throws {Error} URL 不合法时抛出。 + * 校验 target_url 安全性:仅允�?https://,禁止内网IP�? + * @param {string} urlStr 目标URL�? + * @throws {Error} URL 不合法时抛出�? */ function validateTargetUrl(urlStr) { if (!urlStr || typeof urlStr !== 'string') { @@ -77,11 +77,11 @@ function validateTargetUrl(urlStr) { try { parsed = new URL(urlStr); } catch (e) { - throw new Error(`target_url 格式不合法: ${urlStr}`); + throw new Error(`target_url 格式不合�? ${urlStr}`); } if (parsed.protocol !== 'https:') { - throw new Error('target_url 仅允许 https:// 协议'); + throw new Error('target_url 仅允�?https:// 协议'); } const hostname = parsed.hostname || ''; @@ -91,13 +91,13 @@ function validateTargetUrl(urlStr) { } /** - * 站内信接收服务。 - * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复。 + * 站内信接收服务�? + * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复�? */ class InboxReceiverService extends Service { /** - * 获取支持的目标渠道集合。 - * @return {Set} 支持的目标渠道。 + * 获取支持的目标渠道集合�? + * @return {Set} 支持的目标渠道�? */ static get SUPPORTED_CHANNELS() { return new Set([ @@ -110,8 +110,8 @@ class InboxReceiverService extends Service { } /** - * 初始化时执行僵尸恢复。 - * @param {Object} ctx Egg.js 上下文。 + * 初始化时执行僵尸恢复�? + * @param {Object} ctx Egg.js 上下文�? */ constructor(ctx) { super(ctx); @@ -124,46 +124,71 @@ class InboxReceiverService extends Service { } /** - * 统一接收入口:幂等去重、写库、异步推送。 - * @param {Object} data 消息数据。 - * @param {string} data.ext_id 外部唯一消息主键。 - * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。 - * @param {number} [data.store_id] 关联货主ID。 - * @param {string} [data.direction='inbound'] 消息方向。 - * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。 - * @param {string} data.source_type 来源类型:im / api / system。 - * @param {string} [data.source_extra] 来源附加信息。 - * @param {string} data.target_type 目标类型:im / api / webhook。 - * @param {string} data.target_channel 目标渠道。 - * @param {string} data.target_url 推送目标URL。 - * @param {string} [data.ref_code] 引用编码。 - * @param {Object} [data.ext_data] 透传数据。 - * @param {Object} [data.flags] 处理标记。 - * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。 + * 统一接收入口:幂等去重、写库、异步推送�? + * @param {Object} data 消息数据�? + * @param {string} data.ext_id 外部唯一消息主键�? + * @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)�? + * @param {number} [data.store_id] 关联货主ID�? + * @param {string} [data.direction='inbound'] 消息方向�? + * @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)�? + * @param {string} data.source_type 来源类型:im / api / system�? + * @param {string} [data.source_extra] 来源附加信息�? + * @param {string} data.target_type 目标类型:im / api / webhook�? + * @param {string} data.target_channel 目标渠道�? + * @param {string} data.target_url 推送目标URL�? + * @param {string} [data.ref_code] 引用编码�? + * @param {Object} [data.ext_data] 透传数据�? + * @param {Object} [data.flags] 处理标记�? + * @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果�? */ async receive(data = {}) { const { ctx } = this; const { InboxMessage } = ctx.model; - // 安全边界:校验 ext_id 不能为空 + // 安全边界:校�?ext_id 不能为空 const extId = String(data.ext_id || '').trim(); if (!extId) { throw new Error('ext_id 不能为空'); } - // 安全边界:warehouse_id 必须由服务端上下文提供 + // 安全边界:warehouse_id 必须由服务端上下文提�? const warehouseId = Number(data.warehouse_id); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('warehouse_id 无效'); } + // 枚举校验:direction + const VALID_DIRECTIONS = [ 'inbound', 'outbound' ]; + const direction = VALID_DIRECTIONS.includes(data.direction) ? data.direction : 'inbound'; + + // 枚举校验:source_type + const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ]; + const sourceType = VALID_SOURCE_TYPES.includes(data.source_type) ? data.source_type : (data.source_type || 'api'); + + // 枚举校验:target_type + const VALID_TARGET_TYPES = [ 'im', 'api', 'webhook' ]; + const targetType = VALID_TARGET_TYPES.includes(data.target_type) ? data.target_type : (data.target_type || 'im'); + + // parent_id 存在性校验 + const parentId = data.parent_id ? Number(data.parent_id) : null; + if (parentId) { + const parentExists = await InboxMessage.findOne({ + where: { id: parentId, warehouse_id: warehouseId }, + attributes: [ 'id' ], + }); + if (!parentExists) { + throw new Error(`parent_id=${parentId} 对应的消息不存在`); + } + } + + // 校验 target_channel 是否存在 const targetChannel = String(data.target_channel || '').trim(); if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) { throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`); } - // 安全边界:校验 target_url + // 安全边界:校�?target_url validateTargetUrl(data.target_url); // 幂等检查:ext_id 已存在则直接返回 @@ -182,14 +207,14 @@ class InboxReceiverService extends Service { }; } - // 推送 body 大小限制(序列化后检查) + // 推�?body 大小限制(序列化后检查) const pushBody = { ref_code: data.ref_code || null, ext_data: data.ext_data || null, }; const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8'); if (bodySize > MAX_PUSH_BODY_SIZE) { - throw new Error(`推送 body 超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`); + throw new Error(`推�?body 超过 64KB 限制(当�?${Math.round(bodySize / 1024)}KB)`); } // 写库 @@ -197,11 +222,11 @@ class InboxReceiverService extends Service { ext_id: extId, warehouse_id: warehouseId, store_id: data.store_id || null, - direction: data.direction || 'inbound', - parent_id: data.parent_id || null, - source_type: data.source_type || 'api', + direction, + parent_id: parentId, + source_type: sourceType, source_extra: data.source_extra || null, - target_type: data.target_type, + target_type: targetType, target_channel: targetChannel, target_url: data.target_url, ref_code: data.ref_code || null, @@ -215,8 +240,8 @@ class InboxReceiverService extends Service { // 异步后台推送(不阻塞响应) setImmediate(() => { this.asyncPush(record).catch(err => { - ctx.logger.error(`[inbox] setImmediate 异步推送异常 ext_id=${extId}: ${err.message}`); - // 异常已由 asyncPush 内部 try/catch,这里作为兜底 + ctx.logger.error(`[inbox] setImmediate 异步推送异�?ext_id=${extId}: ${err.message}`); + // 异常已由 asyncPush 内部 try/catch,这里作为兜�? try { InboxMessage.update( { @@ -227,7 +252,7 @@ class InboxReceiverService extends Service { { where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } } ); } catch (updateErr) { - ctx.logger.error(`[inbox] 兜底更新推送状态失败 ext_id=${extId}: ${updateErr.message}`); + ctx.logger.error(`[inbox] 兜底更新推送状态失�?ext_id=${extId}: ${updateErr.message}`); } }); }); @@ -240,10 +265,10 @@ class InboxReceiverService extends Service { } /** - * 异步推送 + 指数退避重试。 - * @param {Object} record 消息记录(Sequelize Model 实例)。 - * @param {number} [attempt=0] 当前重试次数。 - * @return {Promise} 推送结果。 + * 异步推�?+ 指数退避重试�? + * @param {Object} record 消息记录(Sequelize Model 实例)�? + * @param {number} [attempt=0] 当前重试次数�? + * @return {Promise} 推送结果�? */ async asyncPush(record, attempt = 0) { const { ctx } = this; @@ -251,7 +276,7 @@ class InboxReceiverService extends Service { const { Op } = ctx.app.Sequelize; try { - // 乐观锁:仅 push_status=0 或(重试时 push_status=3)时可取走 + // 乐观锁:�?push_status=0 或(重试�?push_status=3)时可取�? const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ]; const [ updatedCount ] = await InboxMessage.update( { @@ -267,7 +292,7 @@ class InboxReceiverService extends Service { ); if (updatedCount === 0) { - ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推送 ext_id=${record.ext_id} id=${record.id}`); + ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推�?ext_id=${record.ext_id} id=${record.id}`); return; } @@ -277,7 +302,7 @@ class InboxReceiverService extends Service { throw new Error(`不支持的目标渠道: ${channel}`); } - // 统一渠道映射:warehouse_api → webhook + // 统一渠道映射:warehouse_api �?webhook const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel; const dispatchService = ctx.service.inbox.dispatch[dispatchChannel]; @@ -285,10 +310,10 @@ class InboxReceiverService extends Service { throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`); } - // 执行推送 + // 执行推�? const response = await dispatchService.push(record); - // 推送成功 + // 推送成�? await InboxMessage.update( { push_status: 2, @@ -301,12 +326,12 @@ class InboxReceiverService extends Service { { where: { id: record.id, push_status: 1 } } ); - ctx.logger.info(`[inbox] 推送成功 ext_id=${record.ext_id} channel=${channel}`); + ctx.logger.info(`[inbox] 推送成�?ext_id=${record.ext_id} channel=${channel}`); } catch (error) { const next = attempt + 1; - ctx.logger.warn(`[inbox] 推送失败 ext_id=${record.ext_id} attempt=${next} error=${error.message}`); + ctx.logger.warn(`[inbox] 推送失�?ext_id=${record.ext_id} attempt=${next} error=${error.message}`); - // 更新失败状态 + // 更新失败状�? await InboxMessage.update( { push_status: next >= MAX_RETRY_COUNT ? 3 : 3, @@ -317,25 +342,25 @@ class InboxReceiverService extends Service { { where: { id: record.id, push_status: 1 } } ); - // 指数退避重试:30s → 60s → 120s + // 指数退避重试:30s �?60s �?120s if (next < MAX_RETRY_COUNT) { const delay = 30000 * Math.pow(2, attempt); - ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重试 ext_id=${record.ext_id} attempt=${next}`); + ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重�?ext_id=${record.ext_id} attempt=${next}`); setTimeout(() => { this.asyncPush(record, next).catch(err => { - ctx.logger.error(`[inbox] 重试推送异常 ext_id=${record.ext_id}: ${err.message}`); + ctx.logger.error(`[inbox] 重试推送异�?ext_id=${record.ext_id}: ${err.message}`); }); }, delay); } else { - ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失败 ext_id=${record.ext_id}`); + ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失�?ext_id=${record.ext_id}`); } } } /** - * 僵尸恢复:重置卡在"推送中"超过5分钟的消息为"待推送"。 - * 在服务启动时及定时任务中调用。 - * @return {Promise} 恢复的消息数量。 + * 僵尸恢复:重置卡�?推送中"超过5分钟的消息为"待推�?�? + * 在服务启动时及定时任务中调用�? + * @return {Promise} 恢复的消息数量�? */ async recoverZombieMessages() { const { ctx } = this; @@ -360,7 +385,7 @@ class InboxReceiverService extends Service { ); if (updatedCount > 0) { - ctx.logger.info(`[inbox] 僵尸恢复完成,重置 ${updatedCount} 条消息为待推送`); + ctx.logger.info(`[inbox] 僵尸恢复完成,重�?${updatedCount} 条消息为待推送`); } return updatedCount;