oms/backend/app/lib/openapiIdempotency.js
liufumingren 4c2cfe1793 修复取号回调的订单级幂等与重放
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 17:16:14 +08:00

218 lines
7.0 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),
};
}
/**
* 处理已存在的幂等记录
*
* 只有「已成功」的记录才回放:失败结果不缓存,允许调用方用同一 request_id 重新处理
* (deliveryorder.getwaybill 的逐单重复保护由 waybill_fetch_idempotencies 按订单、
* 快递编码和包裹序号完成)。
* @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) {
return { requestId, entry: row, replay: buildReplay(row), hash };
}
const updatedAt = new Date(row.updated_at || row.created_at || Date.now()).getTime();
const finished = Number(row.status) === STATUS.FAILURE;
if (!finished && 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 });
}
}
/**
* 记录处理结果(供重试回放)
*
* 仅「成功且可回放」的结果落库;失败或明确不可回放(如占位响应、部分订单失败)时删除占用,
* 让同一 request_id 的下次调用重新执行(取号重复保护由订单级幂等保证)。
* @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 业务是否成功
* @param {boolean} [result.replayable] 是否允许回放,默认 true
* @return {Promise<void>} 无
*/
async function finish(ctx, state, { httpStatus, body, ok, replayable = true }) {
if (!state || !state.entry) return;
if (!ok || !replayable) {
try {
await state.entry.destroy();
} catch (err) {
ctx.logger.error('[openapi-idempotency] 清除不可回放记录失败:%s', err.message);
}
return;
}
try {
await state.entry.update({
status: STATUS.SUCCESS,
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,
};