@be-link/ecommerce-trade-service-node-sdk 0.1.56 → 0.1.58

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.
@@ -7,8 +7,8 @@ export default abstract class BaseService {
7
7
  /** URL一级路径 */
8
8
  protected abstract prefixUrl: string;
9
9
  /** 子网域名 */
10
- protected readonly natDevHost = "http://trade:8090/trade";
11
- protected readonly natProdHost = "http://trade:8090/trade";
10
+ protected readonly natDevHost = "http://192.168.58.117:8090/trade";
11
+ protected readonly natProdHost = "http://192.168.106.126:8090/trade";
12
12
  /** 公网域名 */
13
13
  protected readonly publicDevHost = "https://ecommerce-dev.wejourney.top/trade";
14
14
  protected readonly publicProdHost = "";
@@ -12,8 +12,8 @@ const string_1 = require("../utils/string");
12
12
  class BaseService {
13
13
  constructor() {
14
14
  /** 子网域名 */
15
- this.natDevHost = 'http://trade:8090/trade';
16
- this.natProdHost = 'http://trade:8090/trade';
15
+ this.natDevHost = 'http://192.168.58.117:8090/trade';
16
+ this.natProdHost = 'http://192.168.106.126:8090/trade';
17
17
  /** 公网域名 */
18
18
  this.publicDevHost = 'https://ecommerce-dev.wejourney.top/trade';
19
19
  this.publicProdHost = '';
@@ -312,9 +312,6 @@ export declare namespace PosOrderQueryService {
312
312
  };
313
313
  user: {
314
314
  userId: string;
315
- unionId: string;
316
- /** 用户昵称 */
317
- nickname?: string;
318
315
  memberLevel?: string;
319
316
  receiverName: string;
320
317
  receiverPhone: string;
@@ -329,9 +326,6 @@ export declare namespace PosOrderQueryService {
329
326
  };
330
327
  userDetail: {
331
328
  userId: string;
332
- unionId: string;
333
- /** 用户昵称 */
334
- nickname?: string;
335
329
  memberLevel?: string;
336
330
  receiverName: string;
337
331
  receiverPhone: string;
@@ -6,35 +6,16 @@ export declare namespace RosOrderQueryService {
6
6
  interface IOrderList {
7
7
  /** 查询条件 */
8
8
  conditions?: {
9
- /** 下单时间范围 */
10
- createdAt?: {
11
- start?: number;
12
- end?: number;
13
- };
14
- /** 退款操作时间范围 */
15
- operateTime?: {
16
- start?: number;
17
- end?: number;
18
- };
19
- /** 退款申请时间范围 */
20
- orderTime?: {
21
- start?: number;
22
- end?: number;
23
- };
24
- /** 退款订单状态列表 */
25
- statusList?: ENUM.ReverseOrderStatus[];
26
- /** 退款到账状态列表 */
27
- arrivalStatusList?: ENUM.ReverseArrivalStatus[];
28
- /** 退款方式列表 */
29
- wayList?: ENUM.ReverseRefundWay[];
30
- /** 退款类型列表 */
31
- typeList?: ENUM.ReverseRefundType[];
32
- /** 用户ID列表 */
33
- userIds?: string[];
34
- /** 正向订单ID列表 */
35
- orderIds?: string[];
36
- /** 门店ID列表 */
37
- storeIds?: string[];
9
+ createdAt: string;
10
+ operateTime: string;
11
+ orderTime: string;
12
+ status: ENUM.ReverseOrderStatus;
13
+ arrivalStatusList: ENUM.ReverseArrivalStatus[];
14
+ wayList: ENUM.ReverseRefundWay[];
15
+ typeList: ENUM.ReverseRefundType[];
16
+ userIds: string[];
17
+ orderIds: string[];
18
+ storeIds: string[];
38
19
  };
39
20
  /** 分页 */
40
21
  pagination: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@be-link/ecommerce-trade-service-node-sdk",
3
- "version": "0.1.56",
3
+ "version": "0.1.58",
4
4
  "description": "EcommerceTradeService Node.js SDK",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/types.d.ts CHANGED
@@ -154,7 +154,6 @@ export interface ITradeReverseOrder {
154
154
  isFullRefund: number;
155
155
  createdAt: number;
156
156
  updatedAt: number;
157
- orderItemIds: string[];
158
157
  }
159
158
  /** 资源扩展信息类型 */
160
159
  export interface IBizExtraInfo {
package/utils/http.d.ts CHANGED
@@ -9,3 +9,27 @@ declare module '@fastify/request-context' {
9
9
  }
10
10
  }
11
11
  export declare function callApi<T extends (...args: any[]) => Promise<any>>(url: string, request?: Parameters<T>[0]): Promise<Awaited<ReturnType<T>>>;
12
+ export declare function getConnectionStats(): {
13
+ activeRequests: number;
14
+ totalRequests: number;
15
+ peakActiveRequests: number;
16
+ httpSockets: {
17
+ total: number;
18
+ hosts: number;
19
+ details: NodeJS.ReadOnlyDict<import("net").Socket[]>;
20
+ };
21
+ httpsSockets: {
22
+ total: number;
23
+ hosts: number;
24
+ details: NodeJS.ReadOnlyDict<import("net").Socket[]>;
25
+ };
26
+ config: {
27
+ maxSockets: number;
28
+ maxTotalSockets: number;
29
+ requestTimeout: number;
30
+ note: string;
31
+ };
32
+ };
33
+ export declare function resetPeakStats(): void;
34
+ export declare function startMonitoring(interval?: number): void;
35
+ export declare function stopMonitoring(): void;
package/utils/http.js CHANGED
@@ -1,68 +1,120 @@
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
  };
38
5
  Object.defineProperty(exports, "__esModule", { value: true });
39
6
  exports.callApi = callApi;
7
+ exports.getConnectionStats = getConnectionStats;
8
+ exports.resetPeakStats = resetPeakStats;
9
+ exports.startMonitoring = startMonitoring;
10
+ exports.stopMonitoring = stopMonitoring;
40
11
  const axios_1 = __importDefault(require("axios"));
41
12
  const uuid_1 = require("uuid");
42
13
  const axios_retry_1 = __importDefault(require("axios-retry"));
43
14
  const request_context_1 = require("@fastify/request-context");
15
+ const http_1 = __importDefault(require("http"));
16
+ const https_1 = __importDefault(require("https"));
44
17
  const safe_stable_stringify_1 = __importDefault(require("safe-stable-stringify"));
18
+ // 针对高并发优化配置 - 支持2000并发
19
+ const HTTP_CONFIG = {
20
+ maxSockets: 2000, // 每个主机的最大socket连接数(支持2000并发)
21
+ maxFreeSockets: 1000, // 空闲socket保留数(50%复用率,提高连接复用效率)
22
+ maxTotalSockets: 3000, // 所有主机总socket数(单后端场景优化)
23
+ keepAliveMsecs: 30000, // 保持连接30秒(平衡资源占用和连接复用)
24
+ timeout: 3000, // socket超时3秒(高并发场景快速失败)
25
+ requestTimeout: 30000, // 请求超时3秒(快速释放资源,避免慢请求占用连接)
26
+ retryBaseDelay: 100, // 基础重试延迟100ms(给服务恢复时间)
27
+ logThreshold: 1000, // 日志采样率(每1000个请求采样1次,降低日志开销)
28
+ monitorInterval: 5000, // 监控日志间隔(毫秒)
29
+ };
30
+ // 配置 HTTP/HTTPS Agent 以支持高并发连接池和 keepAlive
31
+ const httpAgent = new http_1.default.Agent({
32
+ keepAlive: true,
33
+ keepAliveMsecs: HTTP_CONFIG.keepAliveMsecs,
34
+ maxSockets: HTTP_CONFIG.maxSockets,
35
+ maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
36
+ maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
37
+ timeout: HTTP_CONFIG.timeout,
38
+ scheduling: 'fifo', // 先进先出调度
39
+ });
40
+ const httpsAgent = new https_1.default.Agent({
41
+ keepAlive: true,
42
+ keepAliveMsecs: HTTP_CONFIG.keepAliveMsecs,
43
+ maxSockets: HTTP_CONFIG.maxSockets,
44
+ maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
45
+ maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
46
+ timeout: HTTP_CONFIG.timeout,
47
+ scheduling: 'fifo',
48
+ });
49
+ // 配置 axios 默认使用这些 agent
50
+ axios_1.default.defaults.httpAgent = httpAgent;
51
+ axios_1.default.defaults.httpsAgent = httpsAgent;
52
+ axios_1.default.defaults.timeout = HTTP_CONFIG.requestTimeout;
53
+ axios_1.default.defaults.maxRedirects = 3; // 限制重定向次数
54
+ axios_1.default.defaults.maxContentLength = 50 * 1024 * 1024; // 50MB 最大响应大小
55
+ // 高并发场景下的智能重试配置
45
56
  (0, axios_retry_1.default)(axios_1.default, {
46
- retries: 1,
47
57
  retryCondition(error) {
48
- return error.response?.status === 502;
58
+ // 重试临时错误和特定的网络错误
59
+ const status = error.response?.status;
60
+ const isNetworkError = error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT';
61
+ const isServerError = status === 502 || status === 503 || status === 504;
62
+ const isRateLimited = status === 429;
63
+ return isNetworkError || isServerError || isRateLimited;
49
64
  },
50
- retryDelay: (retryCount) => {
51
- console.info(`retryCount: ${retryCount}, retryDelay: ${retryCount * 500}`);
52
- return retryCount * 500;
53
- },
54
- onRetry(retryCount, error, requestConfig) {
55
- console.info(`retryCount: ${retryCount}, onRetry: ${error.message}, requestHeader: ${(0, safe_stable_stringify_1.default)(requestConfig.headers)}`);
65
+ retryDelay: (retryCount, error) => {
66
+ // 指数退避 + 抖动
67
+ const status = error.response?.status;
68
+ // 如果是限流错误,延迟更长
69
+ if (status === 429) {
70
+ const retryAfter = error.response?.headers['retry-after'];
71
+ if (retryAfter) {
72
+ return parseInt(retryAfter) * 1000;
73
+ }
74
+ return 1000 + Math.random() * 1000; // 1-2秒
75
+ }
76
+ // 指数退避:100ms, 200ms, 400ms...
77
+ const exponentialDelay = HTTP_CONFIG.retryBaseDelay * Math.pow(2, retryCount - 1);
78
+ const jitter = Math.random() * 50; // 0-50ms 抖动
79
+ return Math.min(exponentialDelay + jitter, 2000); // 最多延迟2秒
56
80
  },
81
+ shouldResetTimeout: true, // 重试时重置超时
57
82
  });
83
+ // 连接池状态监控
84
+ let requestCount = 0;
85
+ let activeRequests = 0;
86
+ let peakActiveRequests = 0; // 峰值并发
87
+ // 注意:已移除应用层并发队列限制,完全依赖底层socket连接池控制
88
+ // 这样可以避免应用层排队等待,充分利用socket连接池的并发能力
58
89
  async function callApi(url, request) {
59
- const requestId = request_context_1.requestContext.get('requestId') || request_context_1.requestContext.get('traceMessageId') || (0, uuid_1.v4)();
60
- const pandoraUserId = request_context_1.requestContext.get('pandoraUserId') || '';
61
- const beLinkUserId = request_context_1.requestContext.get('beLinkUserId') || '';
62
- const pandoraRoleId = request_context_1.requestContext.get('pandoraRoleId') || '';
63
- const realIp = request_context_1.requestContext.get('realIp') || '';
90
+ // 不再等待应用层队列,直接发起请求,由底层socket连接池控制并发
91
+ const currentRequestId = ++requestCount;
92
+ activeRequests++;
93
+ // 记录峰值并发
94
+ if (activeRequests > peakActiveRequests) {
95
+ peakActiveRequests = activeRequests;
96
+ }
97
+ // 批量获取请求上下文,减少函数调用开销
98
+ const ctx = request_context_1.requestContext.get('requestId') ? request_context_1.requestContext : null;
99
+ const requestId = ctx?.get('requestId') || ctx?.get('traceMessageId') || (0, uuid_1.v4)();
100
+ const pandoraUserId = ctx?.get('pandoraUserId') || '';
101
+ const beLinkUserId = ctx?.get('beLinkUserId') || '';
102
+ const pandoraRoleId = ctx?.get('pandoraRoleId') || '';
103
+ const realIp = ctx?.get('realIp') || '';
104
+ // 采样日志决策(提前计算,避免重复判断)
105
+ const shouldLog = currentRequestId % HTTP_CONFIG.logThreshold === 0;
106
+ const startTime = shouldLog ? Date.now() : 0;
64
107
  try {
65
- console.info(`准备发起ecommerce-trade-service请求[${requestId}]: ${url}, 参数: ${(0, safe_stable_stringify_1.default)(request)}`);
108
+ if (shouldLog) {
109
+ console.log((0, safe_stable_stringify_1.default)({
110
+ message: '发起HTTP请求',
111
+ currentRequestId,
112
+ activeRequests,
113
+ requestId,
114
+ url,
115
+ type: 'http_request_start',
116
+ }));
117
+ }
66
118
  const response = await axios_1.default.post(url, request, {
67
119
  headers: {
68
120
  'x-request-id': requestId,
@@ -70,42 +122,160 @@ async function callApi(url, request) {
70
122
  'x-belink-userid': beLinkUserId,
71
123
  'x-belink-pandora-roleid': pandoraRoleId,
72
124
  'x-real-ip': realIp,
125
+ Connection: 'keep-alive',
73
126
  },
127
+ timeout: HTTP_CONFIG.requestTimeout,
128
+ httpAgent,
129
+ httpsAgent,
74
130
  });
131
+ if (shouldLog) {
132
+ const duration = Date.now() - startTime;
133
+ if (duration > 3000) {
134
+ console.log((0, safe_stable_stringify_1.default)({
135
+ message: '请求完成',
136
+ currentRequestId,
137
+ duration: `${duration}ms`,
138
+ activeRequests,
139
+ type: 'http_request_complete',
140
+ }));
141
+ }
142
+ }
75
143
  const responseData = response.data;
76
144
  return responseData.data;
77
145
  }
78
146
  catch (error) {
79
147
  const axiosError = error;
148
+ const duration = startTime ? Date.now() - startTime : 0;
149
+ // 错误始终记录(但简化输出)
150
+ console.error((0, safe_stable_stringify_1.default)({
151
+ message: '请求失败',
152
+ currentRequestId,
153
+ url,
154
+ duration: `${duration}ms`,
155
+ activeRequests,
156
+ errorMessage: axiosError.message,
157
+ type: 'http_request_failed',
158
+ }));
80
159
  if (axiosError.response) {
81
160
  const response = axiosError.response;
82
161
  const data = response.data;
83
- console.error(`ecommerce-trade-service 异常: ${axiosError.message},requestId: ${requestId}`);
84
- console.info('响应信息', data.message);
85
- console.error('异常堆栈', (0, safe_stable_stringify_1.default)(error.stack));
86
- // throw new Error(data.errorType + ' - ' + data.message)
87
- throw error;
162
+ console.error((0, safe_stable_stringify_1.default)({
163
+ message: '响应异常',
164
+ status: response.status,
165
+ errorMessage: data?.message || axiosError.message,
166
+ type: 'http_response_error',
167
+ }));
88
168
  }
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)}`);
169
+ throw error;
170
+ }
171
+ finally {
172
+ // 记录请求完成,减少活跃计数
173
+ activeRequests--;
174
+ }
175
+ }
176
+ // 导出监控函数
177
+ function getConnectionStats() {
178
+ const stats = {
179
+ // 当前状态
180
+ activeRequests,
181
+ totalRequests: requestCount,
182
+ // 峰值指标
183
+ peakActiveRequests,
184
+ // Socket连接池状态(这是真正的并发控制点)
185
+ httpSockets: {
186
+ total: Object.keys(httpAgent.sockets).reduce((sum, host) => sum + (httpAgent.sockets[host]?.length || 0), 0),
187
+ hosts: Object.keys(httpAgent.sockets).length,
188
+ details: httpAgent.sockets,
189
+ },
190
+ httpsSockets: {
191
+ total: Object.keys(httpsAgent.sockets).reduce((sum, host) => sum + (httpsAgent.sockets[host]?.length || 0), 0),
192
+ hosts: Object.keys(httpsAgent.sockets).length,
193
+ details: httpsAgent.sockets,
194
+ },
195
+ // 配置信息
196
+ config: {
197
+ maxSockets: HTTP_CONFIG.maxSockets,
198
+ maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
199
+ requestTimeout: HTTP_CONFIG.requestTimeout,
200
+ note: '已移除应用层并发队列限制,完全依赖socket连接池',
201
+ },
202
+ };
203
+ return stats;
204
+ }
205
+ // 重置峰值统计(可用于定期重置)
206
+ function resetPeakStats() {
207
+ peakActiveRequests = activeRequests;
208
+ console.log((0, safe_stable_stringify_1.default)({
209
+ message: '峰值统计已重置',
210
+ type: 'stats_reset',
211
+ }));
212
+ }
213
+ // 定期监控日志
214
+ let monitorTimer = null;
215
+ function startMonitoring(interval = HTTP_CONFIG.monitorInterval) {
216
+ if (monitorTimer) {
217
+ console.log((0, safe_stable_stringify_1.default)({
218
+ message: '监控已在运行中',
219
+ type: 'monitor_already_running',
220
+ }));
221
+ return;
222
+ }
223
+ console.log((0, safe_stable_stringify_1.default)({
224
+ message: '启动并发监控',
225
+ interval: `${interval}ms`,
226
+ type: 'monitor_start',
227
+ }));
228
+ monitorTimer = setInterval(() => {
229
+ const stats = getConnectionStats();
230
+ // 只在有活动时打印
231
+ if (stats.totalRequests === 0) {
232
+ return;
104
233
  }
105
- catch (error) {
106
- console.info(`error: ${(0, safe_stable_stringify_1.default)(error)}`);
234
+ // 检测异常情况(基于socket连接池使用率)
235
+ const httpSocketsUsage = stats.httpSockets.total / HTTP_CONFIG.maxSockets;
236
+ const httpsSocketsUsage = stats.httpsSockets.total / HTTP_CONFIG.maxSockets;
237
+ const maxSocketUsage = Math.max(httpSocketsUsage, httpsSocketsUsage);
238
+ // Socket连接池使用率超过80%视为瓶颈
239
+ const hasIssue = maxSocketUsage > 0.8;
240
+ if (hasIssue) {
241
+ console.warn((0, safe_stable_stringify_1.default)({
242
+ message: '并发监控检测到瓶颈',
243
+ 当前并发: stats.activeRequests,
244
+ 峰值并发: stats.peakActiveRequests,
245
+ 总请求数: stats.totalRequests,
246
+ HTTP_Sockets: `${stats.httpSockets.total}/${HTTP_CONFIG.maxSockets} (${Math.round(httpSocketsUsage * 100)}%)`,
247
+ HTTPS_Sockets: `${stats.httpsSockets.total}/${HTTP_CONFIG.maxSockets} (${Math.round(httpsSocketsUsage * 100)}%)`,
248
+ 建议: 'Socket连接池接近饱和,考虑提高maxSockets配置',
249
+ type: 'monitor_bottleneck_detected',
250
+ }));
107
251
  }
108
- console.error(`ecommerce-trade-service 未知异常: ${axiosError.message}`, error.stack);
109
- throw error;
252
+ else if (stats.totalRequests % 10000 === 0) {
253
+ // 每1万次请求打印一次正常状态
254
+ console.log((0, safe_stable_stringify_1.default)({
255
+ message: '并发监控运行正常',
256
+ 总请求: stats.totalRequests,
257
+ 当前并发: stats.activeRequests,
258
+ 峰值并发: stats.peakActiveRequests,
259
+ HTTP_Sockets使用率: `${Math.round(httpSocketsUsage * 100)}%`,
260
+ HTTPS_Sockets使用率: `${Math.round(httpsSocketsUsage * 100)}%`,
261
+ type: 'monitor_normal',
262
+ }));
263
+ }
264
+ }, interval);
265
+ }
266
+ function stopMonitoring() {
267
+ if (monitorTimer) {
268
+ clearInterval(monitorTimer);
269
+ monitorTimer = null;
270
+ console.log((0, safe_stable_stringify_1.default)({
271
+ message: '监控已停止',
272
+ type: 'monitor_stop',
273
+ }));
110
274
  }
111
275
  }
276
+ // 自动启动监控(可选,如果不想自动启动可以注释掉)
277
+ if (process.env.NODE_ENV !== 'test') {
278
+ setTimeout(() => {
279
+ startMonitoring();
280
+ }, 3000); // 延迟3秒启动,避免服务启动时的干扰
281
+ }