oms/backend/app/lib/openapiIdempotency.js
liufumingren eaf957ed14 feat(express): 外部打单快递接口、自定义快递编码与回 OMS 取号
- 外部打单平台快递接口:按账号同步平台模板、绑定快递编码、查看模板明细;打开列表只读库,仅「从平台同步数据」时拉取
- 系统管理新增自定义快递编码字典,订单改快递 / 物流下拉合并系统与自定义编码,推送奇门沿用订单上的编码
- 新增 OpenAPI deliveryorder.getwaybill:WMS 批量回取号(单次≤100、并发4、逐单结果),快递编码只取 WMS 报文,取消/作废/归档返回失败,已取号直接复用
- 新增 openapi_request_idempotency 请求级幂等:request_id 回放、报文摘要校验、30 分钟 stale 接管、7 天定时清理
- 外部打单平台订单按平台 fetch_waybill_no 下发 need_oms_waybill,推送时实时判定并回写单据
- 店铺、打单账号平台配置与「平台+编码→模板」绑定走 Redis 缓存,绑定/账号变更主动失效,避免批量推送与取号逐单查库

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-04 04:10:37 +08:00

199 lines
6.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const crypto = require('crypto');
const { stableStringify } = require('./wms/sign');
/**
* 对外 OpenAPI 请求幂等。
*
* 以 (app_key, method, request_id) 唯一:
* - 已完成(成功/失败)→ 直接回放上次保存的完整响应;
* - 处理中 → 返回 409,让调用方稍后重试(避免并发重复执行);
* - 同一 request_id 但报文不同 → 返回 400;
* - 超过 30 分钟仍处于处理中(进程异常退出等)→ 允许接管重跑。
*
* request_id 来源(按优先级):query.request_id / query.requestId / header X-Request-Id /
* body.request_id / body.requestId / body.request.request_id。
* 未传 request_id 时不启用幂等(保持原行为)。
*/
/** 幂等记录状态 */
const STATUS = {
PROCESSING: 0,
SUCCESS: 1,
FAILURE: 2,
};
/** 处理中的记录超过该时长视为异常中断,允许接管重跑 */
const STALE_MS = 30 * 60 * 1000;
/**
* 从请求中取幂等请求ID
* @param {Object} ctx egg context
* @return {string} request_id(未传时为空串)
*/
function extractRequestId(ctx) {
const query = ctx.query || {};
const body = ctx.request.body && typeof ctx.request.body === 'object' ? ctx.request.body : {};
const nested = body.request && typeof body.request === 'object' ? body.request : {};
const raw = query.request_id ||
query.requestId ||
ctx.get('x-request-id') ||
body.request_id ||
body.requestId ||
nested.request_id ||
nested.requestId;
return String(raw == null ? '' : raw).trim().slice(0, 100);
}
/**
* 请求报文摘要:app_key + method + 稳定序列化的 body
* @param {Object} params 参数
* @param {string} params.appKey app_key
* @param {string} params.method 方法名
* @param {*} params.body 请求报文
* @return {string} md5 摘要
*/
function buildRequestHash({ appKey, method, body }) {
return crypto
.createHash('md5')
.update(stableStringify({ app_key: appKey, method, body: body || {} }), 'utf8')
.digest('hex');
}
/**
* 解析已保存的响应报文
* @param {string} text 响应 JSON 文本
* @return {Object|null} 响应对象
*/
function parseResponse(text) {
if (!text) return null;
try {
return JSON.parse(text);
} catch {
return null;
}
}
/**
* 构造回放结果
* @param {Object} row 幂等记录
* @return {{httpStatus: number, body: Object|null}} 回放响应
*/
function buildReplay(row) {
return {
httpStatus: Number(row.http_status) || 200,
body: parseResponse(row.response_body),
};
}
/**
* 处理已存在的幂等记录
* @param {Object} ctx egg context
* @param {Object} row 幂等记录
* @param {Object} params 参数
* @param {string} params.requestId 请求ID
* @param {string} params.hash 报文摘要
* @param {Object} [params.api] 接口配置
* @param {Object} [params.warehouse] 仓库
* @return {Promise<Object>} { requestId, entry, replay }
*/
async function handleExisting(ctx, row, { requestId, hash, api, warehouse }) {
if (row.request_hash && row.request_hash !== hash) {
return { requestId, entry: null, replay: { invalid: true }, hash };
}
if (Number(row.status) === STATUS.SUCCESS || Number(row.status) === STATUS.FAILURE) {
return { requestId, entry: row, replay: buildReplay(row), hash };
}
const updatedAt = new Date(row.updated_at || row.created_at || Date.now()).getTime();
if (Date.now() - updatedAt < STALE_MS) {
return { requestId, entry: null, replay: { processing: true }, hash };
}
// 异常中断(进程退出等):接管后重新处理
await row.update({
status: STATUS.PROCESSING,
request_hash: hash,
http_status: null,
response_body: null,
principal_id: api ? api.principal_id : row.principal_id,
warehouse_id: warehouse ? warehouse.id : row.warehouse_id,
});
return { requestId, entry: row, replay: null, hash };
}
/**
* 开始处理:占用 request_id(或返回可回放的结果)
* @param {Object} ctx egg context
* @param {Object} params 参数
* @param {string} params.appKey app_key
* @param {string} params.method 方法名
* @param {*} params.body 请求报文
* @param {Object} [params.api] 接口配置
* @param {Object} [params.warehouse] 仓库
* @return {Promise<{requestId: string, entry: Object|null, replay: Object|null, hash: string}>} 处理上下文
*/
async function begin(ctx, { appKey, method, body, api, warehouse }) {
const requestId = extractRequestId(ctx);
if (!requestId) return { requestId: '', entry: null, replay: null, hash: '' };
const Model = ctx.model.OpenapiRequestIdempotency;
const hash = buildRequestHash({ appKey, method, body });
const where = { app_key: appKey, method, request_id: requestId };
const existing = await Model.findOne({ where });
if (existing) return handleExisting(ctx, existing, { requestId, hash, api, warehouse });
try {
const entry = await Model.create({
app_key: appKey,
method,
request_id: requestId,
request_hash: hash,
principal_id: api ? api.principal_id : null,
warehouse_id: warehouse ? warehouse.id : null,
status: STATUS.PROCESSING,
});
return { requestId, entry, replay: null, hash };
} catch (err) {
// 并发下唯一索引冲突:以先写入的为准
const exist = await Model.findOne({ where });
if (!exist) throw err;
return handleExisting(ctx, exist, { requestId, hash, api, warehouse });
}
}
/**
* 记录处理结果(供重试回放)
* @param {Object} ctx egg context
* @param {Object|null} state begin 返回的上下文
* @param {Object} result 结果
* @param {number} result.httpStatus HTTP 状态码
* @param {Object} result.body 完整响应报文
* @param {boolean} result.ok 业务是否成功
* @return {Promise<void>} 无
*/
async function finish(ctx, state, { httpStatus, body, ok }) {
if (!state || !state.entry) return;
try {
await state.entry.update({
status: ok ? STATUS.SUCCESS : STATUS.FAILURE,
http_status: httpStatus,
response_body: JSON.stringify(body),
});
} catch (err) {
ctx.logger.error('[openapi-idempotency] 写入结果失败:%s', err.message);
}
}
module.exports = {
begin,
finish,
extractRequestId,
buildRequestHash,
STATUS,
STALE_MS,
};