'use strict'; const Service = require('egg').Service; const { URL } = require('url'); const { networkInterfaces } = require('os'); /** 推送 body 大小上限:64KB */ const MAX_PUSH_BODY_SIZE = 64 * 1024; /** 最大重试次数 */ const MAX_RETRY_COUNT = 3; /** 僵尸恢复阈值:5分钟 */ const ZOMBIE_RECOVERY_MINUTES = 5; /** * 收集本机所有内网 IPv4 地址。 * @return {string[]} 内网IP地址列表。 */ function getLocalInternalIps() { const ips = new Set(); const nets = networkInterfaces(); for (const interfaces of Object.values(nets)) { for (const iface of interfaces) { if (iface.family === 'IPv4' && !iface.internal) { ips.add(iface.address); } } } return Array.from(ips); } /** 内网 IP 前缀集合 */ const INTERNAL_IP_PREFIXES = [ '127.', '10.', '192.168.', '0.', ]; /** * 判断给定 IP 是否属于本机内网IP。 * @param {string} ip IP地址。 * @return {boolean} 是否为内网IP。 */ function isInternalIp(ip) { if (!ip || ip === 'localhost') return true; // 检查已知内网前缀 for (const prefix of INTERNAL_IP_PREFIXES) { if (ip.startsWith(prefix)) return true; } // 检查 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; } // 检查本机实际内网IP const localIps = getLocalInternalIps(); if (localIps.includes(ip)) return true; return false; } /** * 校验 target_url 安全性:仅允许 https://,禁止内网IP。 * @param {string} urlStr 目标URL。 * @throws {Error} URL 不合法时抛出。 */ function validateTargetUrl(urlStr) { if (!urlStr || typeof urlStr !== 'string') { throw new Error('target_url 不能为空'); } let parsed; try { parsed = new URL(urlStr); } catch (e) { throw new Error(`target_url 格式不合法: ${urlStr}`); } if (parsed.protocol !== 'https:') { throw new Error('target_url 仅允许 https:// 协议'); } const hostname = parsed.hostname || ''; if (isInternalIp(hostname)) { throw new Error('target_url 不允许指向内网地址'); } } /** * 站内信接收服务。 * 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复。 */ class InboxReceiverService extends Service { /** * 获取支持的目标渠道集合。 * @return {Set} 支持的目标渠道。 */ static get SUPPORTED_CHANNELS() { return new Set([ 'webhook', 'wecom', 'dingtalk', 'feishu', 'warehouse_api', ]); } /** * 初始化时执行僵尸恢复。 * @param {Object} ctx Egg.js 上下文。 */ constructor(ctx) { super(ctx); // 异步执行僵尸恢复,不阻塞服务启动 setImmediate(() => { this.recoverZombieMessages().catch(err => { ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`); }); }); } /** * 统一接收入口:幂等去重、写库、异步推送。 * @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 不能为空 const extId = String(data.ext_id || '').trim(); if (!extId) { throw new Error('ext_id 不能为空'); } // 安全边界:warehouse_id 必须由服务端上下文提供 const warehouseId = Number(data.warehouse_id); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('warehouse_id 无效'); } // 校验 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 validateTargetUrl(data.target_url); // 幂等检查:ext_id 已存在则直接返回 const exist = await InboxMessage.findOne({ where: { ext_id: extId }, attributes: [ 'id', 'ext_id', 'push_status' ], paranoid: false, }); if (exist) { ctx.logger.info(`[inbox] 消息已存在,跳过入库 ext_id=${extId} id=${exist.id}`); return { ok: true, id: exist.id, ext_id: extId, }; } // 推送 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)`); } // 写库 const record = await InboxMessage.create({ 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', source_extra: data.source_extra || null, target_type: data.target_type, target_channel: targetChannel, target_url: data.target_url, ref_code: data.ref_code || null, ext_data: data.ext_data || null, flags: data.flags || {}, push_status: 0, }); ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`); // 异步后台推送(不阻塞响应) setImmediate(() => { this.asyncPush(record).catch(err => { ctx.logger.error(`[inbox] setImmediate 异步推送异常 ext_id=${extId}: ${err.message}`); // 异常已由 asyncPush 内部 try/catch,这里作为兜底 try { InboxMessage.update( { push_status: 3, push_response: { error: `setImmediate 异常: ${err.message}` }, pushed_at: new Date(), }, { 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}`); } }); }); return { ok: true, id: record.id, ext_id: extId, }; } /** * 异步推送 + 指数退避重试。 * @param {Object} record 消息记录(Sequelize Model 实例)。 * @param {number} [attempt=0] 当前重试次数。 * @return {Promise} 推送结果。 */ async asyncPush(record, attempt = 0) { const { ctx } = this; const { InboxMessage } = ctx.model; const { Op } = ctx.app.Sequelize; try { // 乐观锁:仅 push_status=0 或(重试时 push_status=3)时可取走 const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ]; const [ updatedCount ] = await InboxMessage.update( { push_status: 1, push_started_at: new Date(), }, { where: { id: record.id, push_status: { [Op.in]: allowedStatuses }, }, } ); if (updatedCount === 0) { ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推送 ext_id=${record.ext_id} id=${record.id}`); return; } // 获取 dispatch 服务 const channel = record.target_channel; if (!InboxReceiverService.SUPPORTED_CHANNELS.has(channel)) { throw new Error(`不支持的目标渠道: ${channel}`); } // 统一渠道映射:warehouse_api → webhook const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel; const dispatchService = ctx.service.inbox.dispatch[dispatchChannel]; if (!dispatchService || typeof dispatchService.push !== 'function') { throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`); } // 执行推送 const response = await dispatchService.push(record); // 推送成功 await InboxMessage.update( { push_status: 2, push_response: { http_status: response.status, body: response.data, }, pushed_at: new Date(), }, { where: { id: record.id, push_status: 1 } } ); 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}`); // 更新失败状态 await InboxMessage.update( { push_status: next >= MAX_RETRY_COUNT ? 3 : 3, retry_count: next, push_response: { error: error.message }, ...(next >= MAX_RETRY_COUNT ? { pushed_at: new Date() } : {}), }, { where: { id: record.id, push_status: 1 } } ); // 指数退避重试: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}`); setTimeout(() => { this.asyncPush(record, next).catch(err => { ctx.logger.error(`[inbox] 重试推送异常 ext_id=${record.ext_id}: ${err.message}`); }); }, delay); } else { ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失败 ext_id=${record.ext_id}`); } } } /** * 僵尸恢复:重置卡在"推送中"超过5分钟的消息为"待推送"。 * 在服务启动时及定时任务中调用。 * @return {Promise} 恢复的消息数量。 */ async recoverZombieMessages() { const { ctx } = this; const { InboxMessage } = ctx.model; const { Op } = ctx.app.Sequelize; const threshold = new Date(Date.now() - ZOMBIE_RECOVERY_MINUTES * 60 * 1000); const [ updatedCount ] = await InboxMessage.update( { push_status: 0, push_started_at: null, }, { where: { push_status: 1, push_started_at: { [Op.lt]: threshold, }, }, } ); if (updatedCount > 0) { ctx.logger.info(`[inbox] 僵尸恢复完成,重置 ${updatedCount} 条消息为待推送`); } return updatedCount; } } module.exports = InboxReceiverService;