@be-link/ecommerce-trade-service-node-sdk 0.1.66 → 0.1.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/enums.js +1 -1
- package/modules/pos/orderQuery/types.d.ts +1 -1
- package/package.json +1 -1
- package/types.d.ts +1 -0
- package/utils/http.js +259 -72
package/enums.js
CHANGED
|
@@ -435,7 +435,7 @@ var ENUM_CN;
|
|
|
435
435
|
};
|
|
436
436
|
/** 退款方式中文映射 */
|
|
437
437
|
ENUM_CN.ReverseRefundWay = {
|
|
438
|
-
[ENUM.ReverseRefundWay.USER_MANUAL]: '
|
|
438
|
+
[ENUM.ReverseRefundWay.USER_MANUAL]: '商家审核退款',
|
|
439
439
|
[ENUM.ReverseRefundWay.FAST]: '极速退款',
|
|
440
440
|
[ENUM.ReverseRefundWay.MERCHANT_MANUAL]: '商家主动退款',
|
|
441
441
|
};
|
|
@@ -91,7 +91,7 @@ export declare namespace PosOrderQueryService {
|
|
|
91
91
|
orderIds?: string[];
|
|
92
92
|
sourceList?: ENUM.OrderSource[];
|
|
93
93
|
statusList?: ENUM.OrderStatus[];
|
|
94
|
-
|
|
94
|
+
isVerifyCoupon?: boolean;
|
|
95
95
|
refundStatusList?: ENUM.OrderRefundStatus[];
|
|
96
96
|
productPickList?: string[];
|
|
97
97
|
productDispatchList?: string[];
|
package/package.json
CHANGED
package/types.d.ts
CHANGED
package/utils/http.js
CHANGED
|
@@ -1,37 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
2
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
4
|
};
|
|
@@ -41,28 +8,109 @@ const axios_1 = __importDefault(require("axios"));
|
|
|
41
8
|
const uuid_1 = require("uuid");
|
|
42
9
|
const axios_retry_1 = __importDefault(require("axios-retry"));
|
|
43
10
|
const request_context_1 = require("@fastify/request-context");
|
|
11
|
+
const http_1 = __importDefault(require("http"));
|
|
12
|
+
const https_1 = __importDefault(require("https"));
|
|
44
13
|
const safe_stable_stringify_1 = __importDefault(require("safe-stable-stringify"));
|
|
14
|
+
// 针对高并发优化配置 - 支持2000并发
|
|
15
|
+
const HTTP_CONFIG = {
|
|
16
|
+
maxSockets: 3000, // 每个主机的最大socket连接数(支持2000并发)
|
|
17
|
+
maxFreeSockets: 1000, // 空闲socket保留数(50%复用率,提高连接复用效率)
|
|
18
|
+
maxTotalSockets: 10000, // 所有主机总socket数(单后端场景优化)
|
|
19
|
+
keepAliveMsecs: 30000, // 保持连接30秒(平衡资源占用和连接复用)
|
|
20
|
+
timeout: 5000, // socket超时3秒(高并发场景快速失败)
|
|
21
|
+
requestTimeout: 5000, // 请求超时5秒(快速释放资源,避免慢请求占用连接)
|
|
22
|
+
retryBaseDelay: 200, // 基础重试延迟100ms(给服务恢复时间)
|
|
23
|
+
logThreshold: 1000, // 日志采样率(每1000个请求采样1次,降低日志开销)
|
|
24
|
+
monitorInterval: 5000, // 监控日志间隔(毫秒)
|
|
25
|
+
};
|
|
26
|
+
// 配置 HTTP/HTTPS Agent 以支持高并发连接池和 keepAlive
|
|
27
|
+
const httpAgent = new http_1.default.Agent({
|
|
28
|
+
keepAlive: true,
|
|
29
|
+
keepAliveMsecs: HTTP_CONFIG.keepAliveMsecs,
|
|
30
|
+
maxSockets: HTTP_CONFIG.maxSockets,
|
|
31
|
+
maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
|
|
32
|
+
maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
|
|
33
|
+
timeout: HTTP_CONFIG.timeout,
|
|
34
|
+
scheduling: 'fifo', // 先进先出调度
|
|
35
|
+
});
|
|
36
|
+
const httpsAgent = new https_1.default.Agent({
|
|
37
|
+
keepAlive: true,
|
|
38
|
+
keepAliveMsecs: HTTP_CONFIG.keepAliveMsecs,
|
|
39
|
+
maxSockets: HTTP_CONFIG.maxSockets,
|
|
40
|
+
maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
|
|
41
|
+
maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
|
|
42
|
+
timeout: HTTP_CONFIG.timeout,
|
|
43
|
+
scheduling: 'fifo',
|
|
44
|
+
});
|
|
45
|
+
// 配置 axios 默认使用这些 agent
|
|
46
|
+
axios_1.default.defaults.httpAgent = httpAgent;
|
|
47
|
+
axios_1.default.defaults.httpsAgent = httpsAgent;
|
|
48
|
+
axios_1.default.defaults.timeout = HTTP_CONFIG.requestTimeout;
|
|
49
|
+
axios_1.default.defaults.maxRedirects = 3; // 限制重定向次数
|
|
50
|
+
axios_1.default.defaults.maxContentLength = 50 * 1024 * 1024; // 50MB 最大响应大小
|
|
51
|
+
// 高并发场景下的智能重试配置
|
|
45
52
|
(0, axios_retry_1.default)(axios_1.default, {
|
|
46
|
-
retries: 1,
|
|
47
53
|
retryCondition(error) {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
54
|
+
// 重试临时错误和特定的网络错误
|
|
55
|
+
const status = error.response?.status;
|
|
56
|
+
const isNetworkError = error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT';
|
|
57
|
+
const isServerError = status === 502 || status === 503 || status === 504;
|
|
58
|
+
const isRateLimited = status === 429;
|
|
59
|
+
return isNetworkError || isServerError || isRateLimited;
|
|
53
60
|
},
|
|
54
|
-
|
|
55
|
-
|
|
61
|
+
retryDelay: (retryCount, error) => {
|
|
62
|
+
// 指数退避 + 抖动
|
|
63
|
+
const status = error.response?.status;
|
|
64
|
+
// 如果是限流错误,延迟更长
|
|
65
|
+
if (status === 429) {
|
|
66
|
+
const retryAfter = error.response?.headers['retry-after'];
|
|
67
|
+
if (retryAfter) {
|
|
68
|
+
return parseInt(retryAfter) * 1000;
|
|
69
|
+
}
|
|
70
|
+
return 1000 + Math.random() * 1000; // 1-2秒
|
|
71
|
+
}
|
|
72
|
+
// 指数退避:100ms, 200ms, 400ms...
|
|
73
|
+
const exponentialDelay = HTTP_CONFIG.retryBaseDelay * Math.pow(2, retryCount - 1);
|
|
74
|
+
const jitter = Math.random() * 50; // 0-50ms 抖动
|
|
75
|
+
return Math.min(exponentialDelay + jitter, 2000); // 最多延迟2秒
|
|
56
76
|
},
|
|
77
|
+
shouldResetTimeout: true, // 重试时重置超时
|
|
57
78
|
});
|
|
79
|
+
// 连接池状态监控
|
|
80
|
+
let requestCount = 0;
|
|
81
|
+
let activeRequests = 0;
|
|
82
|
+
let peakActiveRequests = 0; // 峰值并发
|
|
83
|
+
// 注意:已移除应用层并发队列限制,完全依赖底层socket连接池控制
|
|
84
|
+
// 这样可以避免应用层排队等待,充分利用socket连接池的并发能力
|
|
58
85
|
async function callApi(url, request) {
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
86
|
+
// 不再等待应用层队列,直接发起请求,由底层socket连接池控制并发
|
|
87
|
+
const currentRequestId = ++requestCount;
|
|
88
|
+
activeRequests++;
|
|
89
|
+
// 记录峰值并发
|
|
90
|
+
if (activeRequests > peakActiveRequests) {
|
|
91
|
+
peakActiveRequests = activeRequests;
|
|
92
|
+
}
|
|
93
|
+
// 批量获取请求上下文,减少函数调用开销
|
|
94
|
+
const ctx = request_context_1.requestContext.get('requestId') ? request_context_1.requestContext : null;
|
|
95
|
+
const requestId = ctx?.get('requestId') || ctx?.get('traceMessageId') || (0, uuid_1.v4)();
|
|
96
|
+
const pandoraUserId = ctx?.get('pandoraUserId') || '';
|
|
97
|
+
const beLinkUserId = ctx?.get('beLinkUserId') || '';
|
|
98
|
+
const pandoraRoleId = ctx?.get('pandoraRoleId') || '';
|
|
99
|
+
const realIp = ctx?.get('realIp') || '';
|
|
100
|
+
// 采样日志决策(提前计算,避免重复判断)
|
|
101
|
+
const shouldLog = currentRequestId % HTTP_CONFIG.logThreshold === 0;
|
|
102
|
+
const startTime = shouldLog ? Date.now() : 0;
|
|
64
103
|
try {
|
|
65
|
-
|
|
104
|
+
if (shouldLog) {
|
|
105
|
+
console.log((0, safe_stable_stringify_1.default)({
|
|
106
|
+
message: '发起HTTP请求',
|
|
107
|
+
currentRequestId,
|
|
108
|
+
activeRequests,
|
|
109
|
+
requestId,
|
|
110
|
+
url,
|
|
111
|
+
type: 'http_request_start',
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
66
114
|
const response = await axios_1.default.post(url, request, {
|
|
67
115
|
headers: {
|
|
68
116
|
'x-request-id': requestId,
|
|
@@ -70,42 +118,181 @@ async function callApi(url, request) {
|
|
|
70
118
|
'x-belink-userid': beLinkUserId,
|
|
71
119
|
'x-belink-pandora-roleid': pandoraRoleId,
|
|
72
120
|
'x-real-ip': realIp,
|
|
121
|
+
Connection: 'keep-alive',
|
|
73
122
|
},
|
|
123
|
+
timeout: HTTP_CONFIG.requestTimeout,
|
|
124
|
+
httpAgent,
|
|
125
|
+
httpsAgent,
|
|
74
126
|
});
|
|
127
|
+
if (shouldLog) {
|
|
128
|
+
const duration = Date.now() - startTime;
|
|
129
|
+
if (duration > 3000) {
|
|
130
|
+
console.log((0, safe_stable_stringify_1.default)({
|
|
131
|
+
message: '请求完成',
|
|
132
|
+
currentRequestId,
|
|
133
|
+
duration: `${duration}ms`,
|
|
134
|
+
activeRequests,
|
|
135
|
+
type: 'http_request_complete',
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
75
139
|
const responseData = response.data;
|
|
76
140
|
return responseData.data;
|
|
77
141
|
}
|
|
78
142
|
catch (error) {
|
|
79
143
|
const axiosError = error;
|
|
144
|
+
const duration = startTime ? Date.now() - startTime : 0;
|
|
145
|
+
// 错误始终记录(但简化输出)
|
|
146
|
+
console.error((0, safe_stable_stringify_1.default)({
|
|
147
|
+
message: '请求失败',
|
|
148
|
+
currentRequestId,
|
|
149
|
+
url,
|
|
150
|
+
duration: `${duration}ms`,
|
|
151
|
+
activeRequests,
|
|
152
|
+
errorMessage: axiosError.message,
|
|
153
|
+
type: 'http_request_failed',
|
|
154
|
+
}));
|
|
80
155
|
if (axiosError.response) {
|
|
81
156
|
const response = axiosError.response;
|
|
82
157
|
const data = response.data;
|
|
83
|
-
console.error(
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
158
|
+
console.error((0, safe_stable_stringify_1.default)({
|
|
159
|
+
message: '响应异常',
|
|
160
|
+
status: response.status,
|
|
161
|
+
errorMessage: data?.message || axiosError.message,
|
|
162
|
+
type: 'http_response_error',
|
|
163
|
+
}));
|
|
88
164
|
}
|
|
89
|
-
// 调用dns模块解析url
|
|
90
|
-
const dns = await Promise.resolve().then(() => __importStar(require('dns')));
|
|
91
|
-
const dnsPromise = new Promise((resolve, reject) => {
|
|
92
|
-
const lookupRes = dns.lookup(url, (err, address) => {
|
|
93
|
-
if (err) {
|
|
94
|
-
console.error(err.message);
|
|
95
|
-
reject(err);
|
|
96
|
-
}
|
|
97
|
-
console.info(`lookup: ${(0, safe_stable_stringify_1.default)(lookupRes)}`);
|
|
98
|
-
resolve(address);
|
|
99
|
-
});
|
|
100
|
-
});
|
|
101
|
-
try {
|
|
102
|
-
const address = await dnsPromise;
|
|
103
|
-
console.info(`address: ${(0, safe_stable_stringify_1.default)(address)}`);
|
|
104
|
-
}
|
|
105
|
-
catch (error) {
|
|
106
|
-
console.info(`error: ${(0, safe_stable_stringify_1.default)(error)}`);
|
|
107
|
-
}
|
|
108
|
-
console.error(`ecommerce-trade-service 未知异常: ${axiosError.message}`, error.stack);
|
|
109
165
|
throw error;
|
|
110
166
|
}
|
|
167
|
+
finally {
|
|
168
|
+
// 记录请求完成,减少活跃计数
|
|
169
|
+
activeRequests--;
|
|
170
|
+
}
|
|
111
171
|
}
|
|
172
|
+
// 导出监控函数
|
|
173
|
+
// export function getConnectionStats() {
|
|
174
|
+
// const stats = {
|
|
175
|
+
// // 当前状态
|
|
176
|
+
// activeRequests,
|
|
177
|
+
// totalRequests: requestCount,
|
|
178
|
+
// // 峰值指标
|
|
179
|
+
// peakActiveRequests,
|
|
180
|
+
// // Socket连接池状态(这是真正的并发控制点)
|
|
181
|
+
// httpSockets: {
|
|
182
|
+
// total: Object.keys(httpAgent.sockets).reduce(
|
|
183
|
+
// (sum, host) => sum + (httpAgent.sockets[host]?.length || 0),
|
|
184
|
+
// 0,
|
|
185
|
+
// ),
|
|
186
|
+
// hosts: Object.keys(httpAgent.sockets).length,
|
|
187
|
+
// details: httpAgent.sockets,
|
|
188
|
+
// },
|
|
189
|
+
// httpsSockets: {
|
|
190
|
+
// total: Object.keys(httpsAgent.sockets).reduce(
|
|
191
|
+
// (sum, host) => sum + (httpsAgent.sockets[host]?.length || 0),
|
|
192
|
+
// 0,
|
|
193
|
+
// ),
|
|
194
|
+
// hosts: Object.keys(httpsAgent.sockets).length,
|
|
195
|
+
// details: httpsAgent.sockets,
|
|
196
|
+
// },
|
|
197
|
+
// // 配置信息
|
|
198
|
+
// config: {
|
|
199
|
+
// maxSockets: HTTP_CONFIG.maxSockets,
|
|
200
|
+
// maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
|
|
201
|
+
// requestTimeout: HTTP_CONFIG.requestTimeout,
|
|
202
|
+
// note: '已移除应用层并发队列限制,完全依赖socket连接池',
|
|
203
|
+
// },
|
|
204
|
+
// }
|
|
205
|
+
// return stats
|
|
206
|
+
// }
|
|
207
|
+
// 重置峰值统计(可用于定期重置)
|
|
208
|
+
// export function resetPeakStats() {
|
|
209
|
+
// peakActiveRequests = activeRequests
|
|
210
|
+
// console.log(
|
|
211
|
+
// stringify({
|
|
212
|
+
// message: '峰值统计已重置',
|
|
213
|
+
// type: 'stats_reset',
|
|
214
|
+
// }),
|
|
215
|
+
// )
|
|
216
|
+
// }
|
|
217
|
+
// // 定期监控日志
|
|
218
|
+
// let monitorTimer: NodeJS.Timeout | null = null
|
|
219
|
+
// export function startMonitoring(interval: number = HTTP_CONFIG.monitorInterval) {
|
|
220
|
+
// if (monitorTimer) {
|
|
221
|
+
// console.log(
|
|
222
|
+
// stringify({
|
|
223
|
+
// message: '监控已在运行中',
|
|
224
|
+
// type: 'monitor_already_running',
|
|
225
|
+
// }),
|
|
226
|
+
// )
|
|
227
|
+
// return
|
|
228
|
+
// }
|
|
229
|
+
// console.log(
|
|
230
|
+
// stringify({
|
|
231
|
+
// message: '启动并发监控',
|
|
232
|
+
// interval: `${interval}ms`,
|
|
233
|
+
// type: 'monitor_start',
|
|
234
|
+
// }),
|
|
235
|
+
// )
|
|
236
|
+
// monitorTimer = setInterval(() => {
|
|
237
|
+
// const stats = getConnectionStats()
|
|
238
|
+
// // 只在有活动时打印
|
|
239
|
+
// if (stats.totalRequests === 0) {
|
|
240
|
+
// return
|
|
241
|
+
// }
|
|
242
|
+
// // 检测异常情况(基于socket连接池使用率)
|
|
243
|
+
// const httpSocketsUsage = stats.httpSockets.total / HTTP_CONFIG.maxSockets
|
|
244
|
+
// const httpsSocketsUsage = stats.httpsSockets.total / HTTP_CONFIG.maxSockets
|
|
245
|
+
// const maxSocketUsage = Math.max(httpSocketsUsage, httpsSocketsUsage)
|
|
246
|
+
// // Socket连接池使用率超过80%视为瓶颈
|
|
247
|
+
// const hasIssue = maxSocketUsage > 0.8
|
|
248
|
+
// if (hasIssue) {
|
|
249
|
+
// console.warn(
|
|
250
|
+
// stringify({
|
|
251
|
+
// message: '并发监控检测到瓶颈',
|
|
252
|
+
// 当前并发: stats.activeRequests,
|
|
253
|
+
// 峰值并发: stats.peakActiveRequests,
|
|
254
|
+
// 总请求数: stats.totalRequests,
|
|
255
|
+
// HTTP_Sockets: `${stats.httpSockets.total}/${HTTP_CONFIG.maxSockets} (${Math.round(
|
|
256
|
+
// httpSocketsUsage * 100,
|
|
257
|
+
// )}%)`,
|
|
258
|
+
// HTTPS_Sockets: `${stats.httpsSockets.total}/${HTTP_CONFIG.maxSockets} (${Math.round(
|
|
259
|
+
// httpsSocketsUsage * 100,
|
|
260
|
+
// )}%)`,
|
|
261
|
+
// 建议: 'Socket连接池接近饱和,考虑提高maxSockets配置',
|
|
262
|
+
// type: 'monitor_bottleneck_detected',
|
|
263
|
+
// }),
|
|
264
|
+
// )
|
|
265
|
+
// } else if (stats.totalRequests % 10000 === 0) {
|
|
266
|
+
// // 每1万次请求打印一次正常状态
|
|
267
|
+
// console.log(
|
|
268
|
+
// stringify({
|
|
269
|
+
// message: '并发监控运行正常',
|
|
270
|
+
// 总请求: stats.totalRequests,
|
|
271
|
+
// 当前并发: stats.activeRequests,
|
|
272
|
+
// 峰值并发: stats.peakActiveRequests,
|
|
273
|
+
// HTTP_Sockets使用率: `${Math.round(httpSocketsUsage * 100)}%`,
|
|
274
|
+
// HTTPS_Sockets使用率: `${Math.round(httpsSocketsUsage * 100)}%`,
|
|
275
|
+
// type: 'monitor_normal',
|
|
276
|
+
// }),
|
|
277
|
+
// )
|
|
278
|
+
// }
|
|
279
|
+
// }, interval)
|
|
280
|
+
// }
|
|
281
|
+
// export function stopMonitoring() {
|
|
282
|
+
// if (monitorTimer) {
|
|
283
|
+
// clearInterval(monitorTimer)
|
|
284
|
+
// monitorTimer = null
|
|
285
|
+
// console.log(
|
|
286
|
+
// stringify({
|
|
287
|
+
// message: '监控已停止',
|
|
288
|
+
// type: 'monitor_stop',
|
|
289
|
+
// }),
|
|
290
|
+
// )
|
|
291
|
+
// }
|
|
292
|
+
// }
|
|
293
|
+
// // 自动启动监控(可选,如果不想自动启动可以注释掉)
|
|
294
|
+
// if (process.env.NODE_ENV !== 'test') {
|
|
295
|
+
// setTimeout(() => {
|
|
296
|
+
// startMonitoring()
|
|
297
|
+
// }, 3000) // 延迟3秒启动,避免服务启动时的干扰
|
|
298
|
+
// }
|