fix(inbox): 修复边界缺口 — 枚举校验、parent_id存在性、软删除过滤、thread防环

This commit is contained in:
liufumingren 2026-08-03 02:01:02 +08:00
parent 4374ad01e3
commit 8b978f50ec
2 changed files with 106 additions and 70 deletions

View File

@ -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);
}
}

View File

@ -5,16 +5,16 @@ const Service = require('egg').Service;
const { URL } = require('url');
const { networkInterfaces } = require('os');
/** 推送 body 大小上限:64KB */
/** 推<EFBFBD>?body 大小上限<E4B88A>?4KB */
const MAX_PUSH_BODY_SIZE = 64 * 1024;
/** 最大重试次数 */
/** 最大重试次<EFBFBD>?*/
const MAX_RETRY_COUNT = 3;
/** 僵尸恢复阈值:5分钟 */
const ZOMBIE_RECOVERY_MINUTES = 5;
/**
* 收集本机所有内网 IPv4 地址。
* @return {string[]} 内网IP地址列表。
* 收集本机所有内<EFBFBD>?IPv4 地址<EFBFBD>?
* @return {string[]} 内网IP地址列表<EFBFBD>?
*/
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<EFBFBD>?
* @param {string} ip IP地址<EFBFBD>?
* @return {boolean} 是否为内网IP<EFBFBD>?
*/
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
// 检<EFBFBD>?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 安全性:仅允<EFBFBD>?https://,禁止内网IP<49>?
* @param {string} urlStr 目标URL<EFBFBD>?
* @throws {Error} URL 不合法时抛出<EFBFBD>?
*/
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 格式不合<EFBFBD>? ${urlStr}`);
}
if (parsed.protocol !== 'https:') {
throw new Error('target_url 仅允许 https:// 协议');
throw new Error('target_url 仅允<EFBFBD>?https:// 协议');
}
const hostname = parsed.hostname || '';
@ -91,13 +91,13 @@ function validateTargetUrl(urlStr) {
}
/**
* 站内信接收服务。
* 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复。
* 站内信接收服务<EFBFBD>?
* 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复<EFBFBD>?
*/
class InboxReceiverService extends Service {
/**
* 获取支持的目标渠道集合。
* @return {Set<string>} 支持的目标渠道。
* 获取支持的目标渠道集合<EFBFBD>?
* @return {Set<string>} 支持的目标渠道<EFBFBD>?
*/
static get SUPPORTED_CHANNELS() {
return new Set([
@ -110,8 +110,8 @@ class InboxReceiverService extends Service {
}
/**
* 初始化时执行僵尸恢复。
* @param {Object} ctx Egg.js 上下文。
* 初始化时执行僵尸恢复<EFBFBD>?
* @param {Object} ctx Egg.js 上下文<EFBFBD>?
*/
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}>} 接收结果。
* 统一接收入口:幂等去重、写库、异步推送<EFBFBD>?
* @param {Object} data 消息数据<EFBFBD>?
* @param {string} data.ext_id 外部唯一消息主键<EFBFBD>?
* @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)<EFBFBD>?
* @param {number} [data.store_id] 关联货主ID<EFBFBD>?
* @param {string} [data.direction='inbound'] 消息方向<EFBFBD>?
* @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)<EFBFBD>?
* @param {string} data.source_type 来源类型:im / api / system<EFBFBD>?
* @param {string} [data.source_extra] 来源附加信息<EFBFBD>?
* @param {string} data.target_type 目标类型:im / api / webhook<EFBFBD>?
* @param {string} data.target_channel 目标渠道<EFBFBD>?
* @param {string} data.target_url 推送目标URL<EFBFBD>?
* @param {string} [data.ref_code] 引用编码<EFBFBD>?
* @param {Object} [data.ext_data] 透传数据<EFBFBD>?
* @param {Object} [data.flags] 处理标记<EFBFBD>?
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果<EFBFBD>?
*/
async receive(data = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
// 安全边界:校验 ext_id 不能为空
// 安全边界:校<EFBFBD>?ext_id 不能为空
const extId = String(data.ext_id || '').trim();
if (!extId) {
throw new Error('ext_id 不能为空');
}
// 安全边界:warehouse_id 必须由服务端上下文提供
// 安全边界:warehouse_id 必须由服务端上下文提<EFBFBD>?
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
// 安全边界:校<EFBFBD>?target_url
validateTargetUrl(data.target_url);
// 幂等检查:ext_id 已存在则直接返回
@ -182,14 +207,14 @@ class InboxReceiverService extends Service {
};
}
// 推送 body 大小限制(序列化后检查)
// 推<EFBFBD>?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(`推<EFBFBD>?body 超过 64KB 限制(当<EFBC88>?${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 异步推送异<EFBFBD>?ext_id=${extId}: ${err.message}`);
// 异常已由 asyncPush 内部 try/catch,这里作为兜<EFBFBD>?
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] 兜底更新推送状态失<EFBFBD>?ext_id=${extId}: ${updateErr.message}`);
}
});
});
@ -240,10 +265,10 @@ class InboxReceiverService extends Service {
}
/**
* 异步推送 + 指数退避重试。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @param {number} [attempt=0] 当前重试次数。
* @return {Promise<void>} 推送结果。
* 异步推<EFBFBD>?+ 指数退避重试<EFBFBD>?
* @param {Object} record 消息记录(Sequelize Model 实例)<EFBFBD>?
* @param {number} [attempt=0] 当前重试次数<EFBFBD>?
* @return {Promise<void>} 推送结果<EFBFBD>?
*/
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)时可取走
// 乐观锁:<EFBFBD>?push_status=0 或(重试<E9878D>?push_status=3)时可取<E58FAF>?
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] 消息已被其他进程取走,跳过推<EFBFBD>?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 <EFBFBD>?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} 未实现`);
}
// 执行推送
// 执行推<EFBFBD>?
const response = await dispatchService.push(record);
// 推送成功
// 推送成<EFBFBD>?
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] 推送成<EFBFBD>?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] 推送失<EFBFBD>?ext_id=${record.ext_id} attempt=${next} error=${error.message}`);
// 更新失败状态
// 更新失败状<EFBFBD>?
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 <EFBFBD>?60s <20>?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 后重<EFBFBD>?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] 重试推送异<EFBFBD>?ext_id=${record.ext_id}: ${err.message}`);
});
}, delay);
} else {
ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失败 ext_id=${record.ext_id}`);
ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失<EFBFBD>?ext_id=${record.ext_id}`);
}
}
}
/**
* 僵尸恢复:重置卡在"推送中"超过5分钟的消息为"待推送"。
* 在服务启动时及定时任务中调用。
* @return {Promise<number>} 恢复的消息数量。
* 僵尸恢复:重置卡<EFBFBD>?推送中"超过5分钟的消息为"待推<EFBFBD>?<EFBFBD>?
* 在服务启动时及定时任务中调用<EFBFBD>?
* @return {Promise<number>} 恢复的消息数量<EFBFBD>?
*/
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] 僵尸恢复完成,重<EFBFBD>?${updatedCount} 条消息为待推送`);
}
return updatedCount;