diff --git a/app/model/inbox_block.js b/app/model/inbox_block.js index e2fefba..3fc570c 100644 --- a/app/model/inbox_block.js +++ b/app/model/inbox_block.js @@ -9,7 +9,7 @@ * @return {Object} Sequelize Model 定义。 */ module.exports = app => { - const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + const { BIGINT, STRING, INTEGER, TINYINT, DATE } = app.Sequelize; const InboxBlock = app.model.define('inbox_block', { id: { @@ -34,6 +34,12 @@ module.exports = app => { allowNull: true, comment: '用户ID', }, + is_robot: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否机器人账号:机器人屏蔽在仓库群同样生效(仓库群默认忽略仅用户级屏蔽)', + }, created_at: { type: DATE, allowNull: false, diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js index 19e13ff..d3f8bf1 100644 --- a/app/service/inbox/processor.js +++ b/app/service/inbox/processor.js @@ -8,6 +8,15 @@ const WAREHOUSE_INTERFACE_TYPE_ID = 3; /** 历史消息过滤默认阈值:发送时间距今超过 10 分钟视为历史/补推消息,跳过 AI(可用 config.inbox.historyMessageMaxAgeMs 覆盖) */ const DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS = 10 * 60 * 1000; +/** 屏蔽集合缓存键前缀(v2:纯对象+数组结构,Redis JSON 序列化后可正常回读) */ +const BLOCK_CACHE_KEY_PREFIX = 'inbox:block:v2:'; + +/** 旧版屏蔽集合缓存键前缀(Set 结构,Redis 序列化后恒不命中,仅用于主动失效) */ +const LEGACY_BLOCK_CACHE_KEY_PREFIX = 'inbox:block:'; + +/** 屏蔽集合缓存过期秒数 */ +const BLOCK_CACHE_TTL_SECONDS = 300; + /** * 站内信内容处理器。 * 负责解析入站消息正文,按 source_type 分流处理, @@ -717,10 +726,68 @@ class InboxProcessorService extends Service { } } + /** + * 加载仓库维度屏蔽集合(带缓存)。 + * 缓存值使用「纯对象 + 数组」(Redis 以 JSON 存储,Set 会被序列化成 {} 导致缓存恒不命中), + * 读取后转成 Set 便于 O(1) 判定。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise<{pairs: Set, groupAll: Set, users: Set, + * robotPairs: Set, robotGroupAll: Set, robotUsers: Set}>} 屏蔽集合。 + */ + async loadBlockSets(warehouseId) { + const { ctx } = this; + const app = ctx.app; + const cacheKey = `${BLOCK_CACHE_KEY_PREFIX}${warehouseId}`; + + const toSets = raw => ({ + pairs: new Set(raw.pairs || []), + groupAll: new Set(raw.groupAll || []), + users: new Set(raw.users || []), + robotPairs: new Set(raw.robotPairs || []), + robotGroupAll: new Set(raw.robotGroupAll || []), + robotUsers: new Set(raw.robotUsers || []), + }); + + const cached = typeof app.getCacheAsync === 'function' ? await app.getCacheAsync(cacheKey) : null; + if (cached && Array.isArray(cached.pairs)) return toSets(cached); + + const { InboxBlock } = ctx.model; + const rows = await InboxBlock.findAll({ + attributes: [ 'group_id', 'user_id', 'is_robot' ], + where: { warehouse_id: warehouseId }, + raw: true, + }); + + const raw = { + pairs: [], groupAll: [], users: [], + robotPairs: [], robotGroupAll: [], robotUsers: [], + }; + for (const row of rows) { + const g = String(row.group_id || '').trim(); + const u = String(row.user_id || '').trim(); + if (Number(row.is_robot) === 1) { + if (g && u) raw.robotPairs.push(`${g}:${u}`); + else if (g) raw.robotGroupAll.push(g); + else if (u) raw.robotUsers.push(u); + continue; + } + if (g && u) raw.pairs.push(`${g}:${u}`); + else if (g) raw.groupAll.push(g); + else if (u) raw.users.push(u); + } + + if (typeof app.setCacheAsync === 'function') { + await app.setCacheAsync(cacheKey, raw, BLOCK_CACHE_TTL_SECONDS); + } + return toSets(raw); + } + /** * 加载当前仓库的屏蔽用户ID集合(供 AI 判断真人接管)。 * 口径与 isBlocked() 一致:仓库群忽略不带群ID的屏蔽记录(仅带 group_id 的记录才算命中), * 避免货主群/快递群等场景的用户级屏蔽连带把仓库群用户标记为「已屏蔽」。 + * 机器人屏蔽仅用于拦截机器人自身的回灌消息,不参与真人接管判断,故排除。 * * @param {number} warehouseId 仓库ID。 * @return {Promise>} 屏蔽用户ID集合。 @@ -732,7 +799,7 @@ class InboxProcessorService extends Service { const { InboxBlock } = ctx.model; const rows = await InboxBlock.findAll({ attributes: [ 'group_id', 'user_id' ], - where: { warehouse_id: warehouseId }, + where: { warehouse_id: warehouseId, is_robot: 0 }, raw: true, }); @@ -752,13 +819,14 @@ class InboxProcessorService extends Service { * - 仅带 user_id 的全局用户屏蔽(`*:用户`)在仓库群内不生效——仓库群是内部群, * 此类屏蔽多来自货主群/快递群等外部场景,不应连带跳过仓库群消息; * 仓库群内由机器人发起的屏蔽([屏蔽] 指令)会写入当前群 group_id,故仍按带群ID记录生效。 + * - 机器人屏蔽(is_robot=1)不受上面的仓库群例外影响:机器人自身回信被桥接回灌成入站消息时 + * 会形成自问自答死循环,仅带 user_id 的机器人屏蔽按仓库维度全群生效。 * - 无群ID的消息(如私聊)不受此例外影响。 * * @return {Promise} 是否已屏蔽。 */ async isBlocked() { const { ctx } = this; - const app = ctx.app; const groupId = String(ctx.inboxContext?.group_id || '').trim(); const userId = String(ctx.inboxContext?.user_id || '').trim(); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); @@ -766,36 +834,20 @@ class InboxProcessorService extends Service { if (!groupId && !userId) return false; try { - // 1. 尝试从缓存读取屏蔽列表 - const cacheKey = `inbox:block:${warehouseId}`; - let blockedSet = await app.getCacheAsync(cacheKey); + const sets = await this.loadBlockSets(warehouseId); - if (!blockedSet || !(blockedSet instanceof Set)) { - // 2. 缓存未命中,查库并填入缓存 - const { InboxBlock } = ctx.model; - const rows = await InboxBlock.findAll({ - attributes: [ 'group_id', 'user_id' ], - where: { warehouse_id: warehouseId }, - raw: true, - }); - - blockedSet = new Set(); - for (const row of rows) { - const g = String(row.group_id || '').trim(); - const u = String(row.user_id || '').trim(); - if (g && u) blockedSet.add(`${g}:${u}`); - if (g && !u) blockedSet.add(`${g}:*`); - if (!g && u) blockedSet.add(`*:${u}`); - } - - // TTL 5 分钟 - await app.setCacheAsync(cacheKey, blockedSet, 300); + // 1. 机器人屏蔽优先,且不受「仓库群忽略用户级屏蔽」例外影响 + if (userId && sets.robotUsers.has(userId)) { + ctx.logger.info(`[inbox processor] 命中机器人屏蔽(按仓库全群生效) user_id=${userId}`); + return true; } + if (groupId && userId && sets.robotPairs.has(`${groupId}:${userId}`)) return true; + if (groupId && sets.robotGroupAll.has(groupId)) return true; - // 3. 检查当前消息是否命中屏蔽规则 - if (groupId && userId && blockedSet.has(`${groupId}:${userId}`)) return true; - if (groupId && blockedSet.has(`${groupId}:*`)) return true; - if (userId && blockedSet.has(`*:${userId}`)) { + // 2. 普通屏蔽 + if (groupId && userId && sets.pairs.has(`${groupId}:${userId}`)) return true; + if (groupId && sets.groupAll.has(groupId)) return true; + if (userId && sets.users.has(userId)) { // 仓库群忽略不带群ID的用户级屏蔽(见方法注释) if (groupId && await this.isWarehouseGroup(groupId, warehouseId)) { ctx.logger.info(`[inbox processor] 仓库群忽略不带群ID的用户屏蔽 group_id=${groupId} user_id=${userId}`); @@ -813,16 +865,23 @@ class InboxProcessorService extends Service { /** * 失效屏蔽缓存,在新增屏蔽记录后调用。 + * 同时清理旧版 Set 结构的缓存键,避免升级后残留脏缓存。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 无返回值。 */ async invalidateBlockCache(warehouseId) { const { ctx } = this; - try { - await ctx.app.setCacheAsync(`inbox:block:${warehouseId}`, null, 0); - } catch (error) { - ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败: ${error.message}`); + const keys = [ + `${BLOCK_CACHE_KEY_PREFIX}${warehouseId}`, + `${LEGACY_BLOCK_CACHE_KEY_PREFIX}${warehouseId}`, + ]; + for (const key of keys) { + try { + await ctx.app.setCacheAsync(key, null, 0); + } catch (error) { + ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败 key=${key}: ${error.message}`); + } } } diff --git a/database/migrations/20261119160000-add-is-robot-to-wms-inbox-block.js b/database/migrations/20261119160000-add-is-robot-to-wms-inbox-block.js new file mode 100644 index 0000000..3833373 --- /dev/null +++ b/database/migrations/20261119160000-add-is-robot-to-wms-inbox-block.js @@ -0,0 +1,34 @@ +'use strict'; + +const TABLE_NAME = 'wms_inbox_block'; + +/** + * 屏蔽表新增「是否机器人账号」标记。 + * + * 背景:仓库群(internal group)会忽略「仅用户级(无群ID)」的屏蔽记录,避免外部群的 + * 用户级屏蔽连带跳过内部群消息;但机器人自身回信被桥接回灌成入站消息时会形成自问自答 + * 死循环(生产实测单群 500+ 条/小时),这类屏蔽必须不受仓库群例外影响。 + * + * 故新增 is_robot:is_robot=1 的记录在任意群(含仓库群)都生效, + * 且仅带 user_id 时按仓库维度全局生效。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const cols = await queryInterface.describeTable(TABLE_NAME); + if (cols.is_robot) return; + + await queryInterface.addColumn(TABLE_NAME, 'is_robot', { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否机器人账号:机器人屏蔽在仓库群同样生效(仓库群默认忽略仅用户级屏蔽)', + }); + }, + + down: async queryInterface => { + const cols = await queryInterface.describeTable(TABLE_NAME); + if (!cols.is_robot) return; + + await queryInterface.removeColumn(TABLE_NAME, 'is_robot'); + }, +};