19 KiB
站内信(Inbox)模块设计方案
状态: 📋 设计中
设计日期: 2026-08-03
设计人: wms-test-agent
模块:app/service/inbox/,独立文件模块
表: 1 张 —wms_inbox_message
一、概念
消息推送状态追踪表。不重复存储消息内容(消息体由 IM 回调 / API 请求各自管理),只记录谁发来的、要推到哪、推送状态。收件(inbound)和回信(outbound)共表,direction + parent_id 形成对话链。
inbound(外部 → WMS) outbound(WMS → 外部)
┌──────────────────────┐ ┌──────────────────────┐
│ IM 回调 / API push │ │ 系统回信 / 工单通知 │
└──────────┬───────────┘ └──────────┬───────────┘
│ │
▼ ▼
┌─────────────────────────────────────────┐
│ wms_inbox_message(同一张表) │
│ │
│ direction: inbound │ outbound │
│ parent_id: NULL │ parent_id: 原消息ID │
│ │
│ "IM msg_001 → API app_10 → success" │
│ "WMS 回复 → 企微 Bot → success" │
└─────────────────────────────────────────┘
│
▼ setImmediate async push
dispatch → HTTP POST / Bot API
二、数据库表
wms_inbox_message
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
id |
BIGINT UNSIGNED |
✅ | AUTO | 主键 |
ext_id |
VARCHAR(128) |
✅ | — | 外部唯一消息主键(IM msgId / API requestId 等),唯一索引,幂等去重 |
warehouse_id |
BIGINT UNSIGNED |
✅ | — | 所属仓库 |
store_id |
BIGINT UNSIGNED |
— | NULL | 关联货主 |
direction |
VARCHAR(10) |
✅ | inbound |
inbound=外部→WMS 收件 / outbound=WMS→外部 回信 |
parent_id |
BIGINT UNSIGNED |
— | NULL | 关联消息 ID(回信时指向原消息,形成对话链) |
来源 / 目标
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
source_type |
VARCHAR(20) |
✅ | im / api |
source_extra |
VARCHAR(100) |
— | 附加信息(IM 平台 / API app_id) |
target_type |
VARCHAR(20) |
✅ | im / api |
target_channel |
VARCHAR(50) |
✅ | 目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook |
target_url |
VARCHAR(500) |
✅ | 推送目标 URL(IM Bot webhook 地址 / API 回调地址) |
安全设计:
target_url不含 secret。IM Bot URL 中 token 已内嵌,API 推送时 secret 从ApiApp.self_app_secret查。- 出站签名:推送到仓库开放 API 时,使用与该仓库 ApiApp 相同的 MD5 签名算法(
canonicalQuery + self_app_secret + bodySign),接收方用同一app_key验证。IM 通道则使用各自 Bot 的原生鉴权。
inbound vs outbound 的 source/target 语义:
inbound(外部→WMS):source=外部来源 target=WMS 内部要转发到的渠道 outbound(WMS→外部):source=WMS 内部 target=要推送到的外部渠道
| ref_code | VARCHAR(100) | — | 外部引用编码,推送/回执时原样携带 |
| ext_data | JSON | — | 外部透传数据,外部传入任意 JSON,WMS 不解析,回信时原样返回 |
| flags | JSON | — | 处理标记,外部传入控制 WMS 处理行为,见下表 |
flags支持的标记:{ "skip_ai_parse": true, // 跳过智能解析(内部员工发信时设为 true) "skip_auto_reply": true, // 跳过自动回复 "skip_forward": true // 仅存档,不转发 }外部不传 → 默认全部开启(智能解析 + 自动回复 + 转发)。内部系统调用
inbox.push时按需关闭特定行为。
推送状态
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
push_status |
TINYINT(4) |
✅ | 0 | 0=待推送 1=推送中 2=已送达 3=失败 |
push_started_at |
DATETIME |
— | NULL | 开始推送时间(僵尸检测:超 5 分钟仍为 1 → 重置为 0) |
retry_count |
INT(11) |
✅ | 0 | 已重试次数 |
push_response |
JSON |
— | NULL | 目标响应(http_status, body, error) |
pushed_at |
DATETIME |
— | NULL | 推送完成时间 |
防重机制:
push_status字段本身即状态流转,不需要额外流转表。使用乐观锁UPDATE SET push_status=1 WHERE push_status=0保证单条消息不会被重复取走。push_started_at用于进程崩溃后的僵尸恢复。
关联(后续)
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
work_order_id |
BIGINT UNSIGNED |
— | 🔮 关联工单 |
work_order_no |
VARCHAR(50) |
— | 🔮 工单号 |
时间
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
created_at |
DATETIME |
✅ | CURRENT_TIMESTAMP | |
updated_at |
DATETIME |
✅ | CURRENT_TIMESTAMP ON UPDATE | |
deleted_at |
DATETIME |
— | NULL | 软删除 |
索引
| 索引名 | 字段 | 用途 |
|---|---|---|
PRIMARY |
id |
— |
uk_ext_id |
ext_id UNIQUE |
外部幂等去重 |
idx_warehouse_status |
warehouse_id, push_status |
按仓库+状态查询 |
idx_warehouse_direction |
warehouse_id, direction, created_at |
收件/回信列表 |
idx_parent |
parent_id |
对话链查询 |
idx_created_at |
created_at |
时间范围 |
ext_id唯一键防碰撞:不同来源的消息 ID 可能重复(IM msgId 与 API requestId 撞车)。入库时按来源加前缀:IM 消息: ext_id = `im:wecom:${msg.msgId}` API 消息: ext_id = `api:${apiAppId}:${body.requestId}` 系统回信: ext_id = `sys:${uuid}`前缀保证不同来源的消息不会因 ID 相同而误判为重复。
容量规划:
BIGINT UNSIGNED主键容量无限。单表 InnoDB 建议 ≤ 5000 万行。以 100 仓 × 日均 5000 条 = 日 50 万条计,达到上限需 ~100 天。届时加PARTITION BY HASH(warehouse_id) PARTITIONS 16即可水平扩展,无需分库分表,代码零改动。
安全边界(强制)
| 边界 | 规则 |
|---|---|
| warehouse_id 归属 | 禁止外部传入。IM 路径从回调解析获取,API 路径从验签后 ctx.warehouseId 获取 |
| ext_id 前缀 | im:{platform}:{msgId} / api:{appId}:{requestId} / sys:{uuid},receiver 入站时统一格式 |
| target_url SSRF | 仅允许 https://,禁止内网 IP(127.0.0.1/10.x/172.16-31.x/192.168.x) |
| dispatch 超时 | HTTP 请求超时 10s,超时视为失败进入重试 |
| setImmediate 异常 | try/catch 包裹,异常写入 push_response.error,push_status=3 |
| target_channel 校验 | dispatch[channel] 不存在时返回明确错误,不静默丢弃 |
| 僵尸恢复 | 启动时 + 每 5 分钟定时执行 UPDATE push_status=0 WHERE push_status=1 AND push_started_at < NOW()-5MIN |
| 推送 body 大小 | 限制 64KB,超限拒绝写入 |
三、推送流程
receiver.receive()
│
├─ 1. 幂等检查(ext_id 已存在 → 直接返回)
├─ 2. INSERT(push_status=0)
└─ 3. setImmediate(() => asyncPush(record))
│
├─ UPDATE push_status=1(推送中)
├─ dispatch(target_channel, target_url)
│ ├─ 成功 → UPDATE push_status=2, pushed_at=NOW()
│ └─ 失败 → retry_count++
│ ├─ < 3 次 → setTimeout(delay, asyncPush) 指数退避重试
│ └─ ≥ 3 次 → UPDATE push_status=3(终态)
└─ 返回
指数退避:30s → 60s → 120s,最多重试 3 次。
关键:不依赖定时任务轮询,利用 Node.js 事件循环的 setImmediate + setTimeout 在同一个进程内异步完成推送与重试。
四、两个接收入口
IM 消息入站
企微/钉钉/飞书 Bot 回调 → receiver.receive({
// warehouse_id 由 IM 回调解析 / 签名验证后从上下文获取,不外部传入
source_type: 'im',
ext_id: `im:wecom:${msg.msgId}`,
source_extra: 'wecom',
target_type: 'api',
target_channel: 'warehouse_api',
target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx',
ref_code: msg.userId,
ext_data: { conversation_id: msg.conversationId },
flags: {},
warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入
})
仓库 API 消息入站
POST /warehouse?method=inbox.push → receiver.receive({
// warehouse_id 由仓库 API 验签后从 ApiApp 解析,不外部传入
source_type: 'api',
ext_id: `api:${ctx.apiAppId}:${body.requestId}`,
source_extra: String(ctx.apiAppId),
target_type: 'im',
target_channel: body.targetChannel || 'wecom',
target_url: body.targetUrl,
ref_code: body.refCode,
ext_data: body.extData,
flags: body.flags || {},
warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入
})
系统回信(outbound)
WMS 内部(工单通知/状态更新)→ receiver.reply({
parent_id: 1, // 原消息 ID
target_type: 'im',
target_channel: 'wecom',
target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx',
ref_code: 'TICKET-001',
ext_data: { ... }, // 继承原消息 ext_data
warehouse_id: ctx.warehouseId, // ← WMS 内部上下文
})
// 自动写入 direction=outbound, parent_id=1
// 推送成功后,可通过 inbox.thread 查完整对话链
五、API
5.1 内部管理 (inbox.*)
| method | 说明 |
|---|---|
inbox.list |
消息列表(direction 区分收件/回信) |
inbox.detail |
消息详情(含 push_response) |
inbox.thread |
对话链(原消息 + 所有回信) |
inbox.reply |
系统回信(写入 outbound 记录 + 异步推送) |
inbox.retry |
手动重推 |
inbox.stats |
推送统计 |
5.2 仓库 API (inbox.push)
POST /warehouse?method=inbox.push
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
body.sourceType |
string |
✅ | 来源类型:im / api |
body.sourceChannel |
string |
— | 来源渠道(IM 平台 / API 标识) |
body.requestId |
string |
✅ | 来源请求 ID(组成 ext_id) |
body.targetChannel |
string |
✅ | 目标渠道 |
body.targetUrl |
string |
✅ | 推送目标 URL |
body.refCode |
string |
— | 引用编码 |
body.extData |
object |
— | 透传数据 |
body.flags |
object |
— | 处理标记 { skip_ai_parse, skip_auto_reply, skip_forward } |
body.storeId |
number |
— | 关联货主 |
六、异步推送实现
不启动独立 consumer,利用 Egg.js / Node.js 原生异步能力:
// receiver.js
async receive(data) {
// 1. 幂等检查
const exist = await this.ctx.model.InboxMessage.findOne({
where: { ext_id: data.ext_id },
});
if (exist) return { ok: true, id: exist.id, ext_id: data.ext_id };
// 2. 写入记录
const record = await this.ctx.model.InboxMessage.create({
ext_id: data.ext_id,
warehouse_id: data.warehouse_id,
source_type: data.source_type,
source_extra: data.source_extra,
target_type: data.target_type,
target_channel: data.target_channel,
target_url: data.target_url,
ref_code: data.ref_code,
ext_data: data.ext_data,
flags: data.flags || {},
push_status: 0,
});
// 3. 异步后台推送(不阻塞响应)
setImmediate(() => this.asyncPush(record));
return { ok: true, id: record.id, ext_id: data.ext_id };
}
async asyncPush(record, attempt = 0) {
// 乐观锁:仅 push_status=0 时可取走,防重
const [ updated ] = await InboxMessage.update(
{ push_status: 1, push_started_at: new Date() },
{ where: { id: record.id, push_status: attempt === 0 ? 0 : 3 } }
);
if (!updated) return; // 已被其他进程取走
try {
// API 渠道:用仓库 ApiApp 生成 MD5 签名,接收方同密钥验证
const payload = { ref_code: record.ref_code, ext_data: record.ext_data };
const signedUrl = record.target_type === 'api'
? await this.signRequest(record, payload)
: record.target_url;
const res = await this.ctx.service.inbox.dispatch[record.target_channel].push(
signedUrl, payload
);
await record.update({
push_status: 2,
push_response: { http_status: res.status, body: res.data },
pushed_at: new Date(),
});
} catch (err) {
const next = attempt + 1;
await record.update({ push_status: 3, retry_count: next, push_response: { error: err.message } });
if (next < 3) {
const delay = 30000 * Math.pow(2, attempt); // 30s → 60s → 120s
setTimeout(() => this.asyncPush(record, next), delay);
}
}
}
不需要:定时任务、消息队列、独立 worker 进程。
僵尸恢复:进程崩溃导致
push_status=1的记录卡死时,启动时执行UPDATE SET push_status=0 WHERE push_status=1 AND push_started_at < NOW() - INTERVAL 5 MINUTE即可复活。
出站签名:推送到
target_type=api时,使用仓库 ApiApp 的self_app_secret生成 MD5 签名附加到 URL query:signedUrl = target_url + '?app_key=' + apiApp.self_app_key + '×tamp=' + now + '&sign=' + md5(queryString + self_app_secret + md5(body))接收方(仓库开放侧)可用同一
app_key调用apiSignLib.verifyRequestSign()验证。IM 通道(wecom/dingtalk/feishu)使用各自 Bot 原生鉴权,不走此签名。
七、模块结构
分层原则:API 入口只做校验与签名,统一委托 app/service/inbox/ 处理写库与推送逻辑。methods/ 仅放接口定义,不放业务代码。
入口层(校验 + 签名) 统一处理层(写库 + 推送) 数据层
────────────────────────── ────────────────────────── ──────
app/controller/ app/service/inbox/ app/model/
im.js ─────────────┐ ┌─ receiver.js inbox_message.js
warehouse.js ──────┤ │ 统一接收(幂等去重) ↑
├──调用──→ │ 写库(INSERT) │
app/service/im.js ─┘ │ 异步推送(setImmediate) │
│ │ 重试(setTimeout 指数退避) │
│ │ │
│ ├─ index.js │
│ │ 列表/详情/重推/统计 │
│ │ │
│ └─ dispatch/ │
│ base.js ← 统一出站:查 ApiApp、取密钥、签名、发 HTTP │
│ webhook.js ← 继承 base,HTTP POST │
│ wecom.js ← 继承 base,企微 Bot │
│ dingtalk.js ← 继承 base,钉钉 Bot │
│ feishu.js ← 继承 base,飞书 Bot │
│ │
methods/ (仅接口定义,不放逻辑) │
warehouse.json ← inbox.push 参数声明 │
system.json ← inbox.* 参数声明 │
关键:
app/service/inbox/是独立的统一处理目录,所有写库、推送、重试逻辑集中在此。后续新增渠道只需在dispatch/下加一个文件,不影响其他层。
统一出站基类 dispatch/base.js
所有渠道 dispatch 继承此基类,统一处理查密钥、签名、发 HTTP:
// dispatch/base.js
class OutboundBase {
constructor(ctx) { this.ctx = ctx; }
// 获取仓库 ApiApp 密钥(IM 渠道无需签名,返回 null)
async getApiApp(warehouseId) {
return await this.ctx.service.systems.apiSign.getApiAppConfigByAppKey(
/* appKey from warehouse */, WAREHOUSE_INTERFACE_TYPE_ID
);
}
// 生成 MD5 签名(复用 apiSignLib)
signRequest(url, body, secret) {
const query = { app_key: secret.appKey, timestamp: Math.floor(Date.now() / 1000) };
const { sign } = apiSignLib.signRequest({ query, body, selfAppSecret: secret.selfAppSecret });
return `${url}?app_key=${query.app_key}×tamp=${query.timestamp}&sign=${sign}`;
}
// 统一发送(子类可覆盖签名逻辑)
async post(url, body) { /* axios/post */ }
// 子类必须实现
async push(record) { throw new Error('子类实现'); }
}
调用链:
receiver.asyncPush()→dispatch[channel].push(record)→ 基类signRequest()+post()→ 外部。各渠道只关注消息格式转换,签名和 HTTP 由基类统一处理。
与现有系统集成
app/controller/im.js(已有)
→ IM 回调签名校验后 → ctx.service.inbox.receiver.receive({ source_type: 'im', ... })
app/controller/warehouse.js(已有)
→ method=inbox.push → ctx.service.inbox.receiver.receive({ source_type: 'api', ... })
methods/warehouse.json(修改)
→ 新增 inbox.push 方法定义,注册到 warehouse 开放接口方法列表
八、文件变更清单
| 文件 | 操作 |
|---|---|
database/migrations/{ts}-create-inbox-message.js |
新增 DDL |
app/model/inbox_message.js |
新增 |
app/service/inbox/index.js |
新增 |
app/service/inbox/receiver.js |
新增(统一接收 + 写库 + 异步推送入口) |
app/service/inbox/dispatch/base.js |
新增(统一出站:查密钥 + 签名 + HTTP) |
app/service/inbox/dispatch/webhook.js |
新增(HTTP POST 推送) |
app/service/inbox/dispatch/wecom.js |
新增(企微 Bot) |
app/service/inbox/dispatch/dingtalk.js |
新增(钉钉 Bot) |
app/service/inbox/dispatch/feishu.js |
新增(飞书 Bot) |
app/controller/inbox.js |
新增 |
methods/warehouse.json |
新增 inbox.push |
methods/system.json |
新增 inbox.* |