410 lines
13 KiB
JavaScript
410 lines
13 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
const { URL } = require('url');
|
||
const { networkInterfaces } = require('os');
|
||
|
||
/** 推<>?body 大小上限<E4B88A>?4KB */
|
||
const MAX_PUSH_BODY_SIZE = 64 * 1024;
|
||
/** 最大重试次<E8AF95>?*/
|
||
const MAX_RETRY_COUNT = 3;
|
||
/** 僵尸恢复阈值:5分钟 */
|
||
const ZOMBIE_RECOVERY_MINUTES = 5;
|
||
|
||
/**
|
||
* 收集本机所有内<E69C89>?IPv4 地址<E59CB0>?
|
||
* @return {string[]} 内网IP地址列表<E58897>?
|
||
*/
|
||
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<49>?
|
||
* @param {string} ip IP地址<E59CB0>?
|
||
* @return {boolean} 是否为内网IP<49>?
|
||
*/
|
||
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 安全性:仅允<E4BB85>?https://,禁止内网IP<49>?
|
||
* @param {string} urlStr 目标URL<52>?
|
||
* @throws {Error} URL 不合法时抛出<E68A9B>?
|
||
*/
|
||
// eslint-disable-next-line no-unused-vars
|
||
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 格式不合<E4B88D>? ${urlStr}`);
|
||
}
|
||
|
||
if (parsed.protocol !== 'https:') {
|
||
throw new Error('target_url 仅允<E4BB85>?https:// 协议');
|
||
}
|
||
|
||
const hostname = parsed.hostname || '';
|
||
if (isInternalIp(hostname)) {
|
||
throw new Error('target_url 不允许指向内网地址');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 站内信接收服务<E69C8D>?
|
||
* 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复<E681A2>?
|
||
*/
|
||
class InboxReceiverService extends Service {
|
||
/**
|
||
* 获取支持的目标渠道集合<E99B86>?
|
||
* @return {Set<string>} 支持的目标渠道<E6B8A0>?
|
||
*/
|
||
static get SUPPORTED_CHANNELS() {
|
||
return new Set([
|
||
'webhook',
|
||
'wecom',
|
||
'dingtalk',
|
||
'feishu',
|
||
'warehouse_api',
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* 初始化时执行僵尸恢复<E681A2>?
|
||
* @param {Object} ctx Egg.js 上下文<E4B88B>?
|
||
*/
|
||
constructor(ctx) {
|
||
super(ctx);
|
||
// 异步执行僵尸恢复,不阻塞服务启动
|
||
setImmediate(() => {
|
||
this.recoverZombieMessages().catch(err => {
|
||
ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`);
|
||
});
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 统一接收入口:幂等去重、写库、异步推送<E68EA8>?
|
||
* @param {Object} data 消息数据<E695B0>?
|
||
* @param {string} data.ext_id 外部唯一消息主键<E4B8BB>?
|
||
* @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)<E585A5>?
|
||
* @param {number} [data.store_id] 关联货主ID<49>?
|
||
* @param {string} [data.direction='inbound'] 消息方向<E696B9>?
|
||
* @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)<E681AF>?
|
||
* @param {string} data.source_type 来源类型:im / api / system<65>?
|
||
* @param {string} [data.source_extra] 来源附加信息<E4BFA1>?
|
||
* @param {string} data.target_type 目标类型:im / api / webhook<6F>?
|
||
* @param {string} data.target_channel 目标渠道<E6B8A0>?
|
||
* @param {string} data.target_url 推送目标URL<52>?
|
||
* @param {string} [data.ref_code] 引用编码<E7BC96>?
|
||
* @param {Object} [data.ext_data] 透传数据<E695B0>?
|
||
* @param {Object} [data.flags] 处理标记<E6A087>?
|
||
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果<E7BB93>?
|
||
*/
|
||
async receive(data = {}) {
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
|
||
// 安全边界:校<EFBC9A>?ext_id 不能为空
|
||
const extId = String(data.ext_id || '').trim();
|
||
if (!extId) {
|
||
throw new Error('ext_id 不能为空');
|
||
}
|
||
|
||
// 安全边界:warehouse_id 必须由服务端上下文提<E69687>?
|
||
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(', ')}`);
|
||
}
|
||
|
||
// 安全边界:校<EFBC9A>?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 = {
|
||
ext_data: data.ext_data || null,
|
||
};
|
||
const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8');
|
||
if (bodySize > MAX_PUSH_BODY_SIZE) {
|
||
throw new Error(`推<EFBFBD>?body 超过 64KB 限制(当<EFBC88>?${Math.round(bodySize / 1024)}KB)`);
|
||
}
|
||
|
||
// 写库
|
||
|
||
// store_id 签约校验,若传入 store_id,必须存在有效合约关系
|
||
const storeId = data.store_id ? Number(data.store_id) : null;
|
||
if (storeId && Number.isFinite(storeId) && storeId > 0) {
|
||
const contract = await ctx.model.StoreWarehouse.findOne({
|
||
where: {
|
||
store_id: storeId,
|
||
warehouse_id: warehouseId,
|
||
auth_status: 2,
|
||
warehouse_use_status: 1,
|
||
},
|
||
attributes: [ 'id' ],
|
||
});
|
||
if (!contract) {
|
||
throw new Error(`store_id=${storeId} 与仓库 ${warehouseId} 无有效签约关系`);
|
||
}
|
||
}
|
||
const record = await InboxMessage.create({
|
||
ext_id: extId,
|
||
warehouse_id: warehouseId,
|
||
store_id: data.store_id || null,
|
||
direction,
|
||
parent_id: parentId,
|
||
source_type: sourceType,
|
||
source_extra: data.source_extra || null,
|
||
target_type: targetType,
|
||
target_channel: targetChannel,
|
||
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 异步推送异<E98081>?ext_id=${extId}: ${err.message}`);
|
||
// 异常已由 asyncPush 内部 try/catch,这里作为兜<E4B8BA>?
|
||
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] 兜底更新推送状态失<E68081>?ext_id=${extId}: ${updateErr.message}`);
|
||
}
|
||
});
|
||
});
|
||
|
||
return {
|
||
ok: true,
|
||
id: record.id,
|
||
ext_id: extId,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 异步推<E6ADA5>?+ 指数退避重试<E9878D>?
|
||
* @param {Object} record 消息记录(Sequelize Model 实例)<E4BE8B>?
|
||
* @param {number} [attempt=0] 当前重试次数<E6ACA1>?
|
||
* @return {Promise<void>} 推送结果<E7BB93>?
|
||
*/
|
||
async asyncPush(record, attempt = 0) {
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
const { Op } = ctx.app.Sequelize;
|
||
|
||
try {
|
||
// 乐观锁:<E99481>?push_status=0 或(重试<E9878D>?push_status=3)时可取<E58FAF>?
|
||
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] 消息已被其他进程取走,跳过推<E8BF87>?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 <20>?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} 未实现`);
|
||
}
|
||
|
||
// 执行推<E8A18C>?
|
||
const response = await dispatchService.push(record);
|
||
|
||
// 推送成<E98081>?
|
||
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] 推送成<E98081>?ext_id=${record.ext_id} channel=${channel}`);
|
||
} catch (error) {
|
||
const next = attempt + 1;
|
||
ctx.logger.warn(`[inbox] 推送失<E98081>?ext_id=${record.ext_id} attempt=${next} error=${error.message}`);
|
||
|
||
// 更新失败状<E8B4A5>?
|
||
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 <20>?60s <20>?120s
|
||
if (next < MAX_RETRY_COUNT) {
|
||
const delay = 30000 * Math.pow(2, attempt);
|
||
ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重<E5908E>?ext_id=${record.ext_id} attempt=${next}`);
|
||
setTimeout(() => {
|
||
this.asyncPush(record, next).catch(err => {
|
||
ctx.logger.error(`[inbox] 重试推送异<E98081>?ext_id=${record.ext_id}: ${err.message}`);
|
||
});
|
||
}, delay);
|
||
} else {
|
||
ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失<E68081>?ext_id=${record.ext_id}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 僵尸恢复:重置卡<E7BDAE>?推送中"超过5分钟的消息为"待推<E5BE85>?<3F>?
|
||
* 在服务启动时及定时任务中调用<E8B083>?
|
||
* @return {Promise<number>} 恢复的消息数量<E695B0>?
|
||
*/
|
||
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] 僵尸恢复完成,重<EFBC8C>?${updatedCount} 条消息为待推送`);
|
||
}
|
||
|
||
return updatedCount;
|
||
}
|
||
}
|
||
|
||
module.exports = InboxReceiverService;
|