@be-link/ecommerce-promotion-service-node-sdk 0.1.14 → 0.1.16

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@be-link/ecommerce-promotion-service-node-sdk",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "EcommercePromotionService Node.js SDK",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/utils/http.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  declare module '@fastify/request-context' {
2
2
  interface RequestContextData {
3
- requestId?: string;
3
+ requestId: string;
4
4
  traceMessageId?: string;
5
5
  pandoraUserId?: string;
6
6
  beLinkUserId?: string;
@@ -9,25 +9,3 @@ 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;
package/utils/http.js CHANGED
@@ -4,27 +4,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.callApi = callApi;
7
- exports.getConnectionStats = getConnectionStats;
8
- exports.resetPeakStats = resetPeakStats;
9
7
  const axios_1 = __importDefault(require("axios"));
10
8
  const uuid_1 = require("uuid");
11
9
  const axios_retry_1 = __importDefault(require("axios-retry"));
12
10
  const request_context_1 = require("@fastify/request-context");
13
- const safe_stable_stringify_1 = __importDefault(require("safe-stable-stringify"));
14
11
  const http_1 = __importDefault(require("http"));
15
12
  const https_1 = __importDefault(require("https"));
16
- // 针对高并发优化配置 - 支持高并发场景
13
+ // HTTP 连接池配置 - 支持 2000 QPS(响应时间 2秒)
17
14
  const HTTP_CONFIG = {
18
- maxSockets: 2000, // 每个主机的最大socket连接数(支持2000并发)
19
- maxFreeSockets: 1000, // 空闲socket保留数(50%复用率,提高连接复用效率)
20
- maxTotalSockets: 3000, // 所有主机总socket数(单后端场景优化)
21
- keepAliveMsecs: 30000, // 保持连接30秒(平衡资源占用和连接复用)
22
- timeout: 8000, // socket超时3秒(高并发场景快速失败)
23
- requestTimeout: 3000, // 请求超时3秒(快速释放资源,避免慢请求占用连接)
24
- retries: 1, // 重试1次(减少重试,避免高并发时加重后端压力)
25
- retryBaseDelay: 100, // 基础重试延迟100ms(给服务恢复时间)
26
- logThreshold: 1000, // 日志采样率(每1000个请求采样1次,降低日志开销)
27
- monitorInterval: 5000, // 监控日志间隔(毫秒)
15
+ maxSockets: 3000, // 每个 host 最大并发连接数
16
+ maxFreeSockets: 1000, // 保持空闲连接数(减少连接重建开销)
17
+ maxTotalSockets: 10000, // 所有 host 总连接数上限(支持多个服务同时调用)
18
+ keepAliveMsecs: 60000, // 保持连接60秒
19
+ timeout: 5000, // socket超时5秒
20
+ requestTimeout: 5000, // 请求超时5秒
21
+ retries: 0, // 不重试(失败直接返回)
22
+ retryBaseDelay: 200, // 基础重试延迟200ms
28
23
  };
29
24
  // 配置 HTTP/HTTPS Agent 以支持高并发连接池和 keepAlive
30
25
  const httpAgent = new http_1.default.Agent({
@@ -34,7 +29,7 @@ const httpAgent = new http_1.default.Agent({
34
29
  maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
35
30
  maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
36
31
  timeout: HTTP_CONFIG.timeout,
37
- scheduling: 'fifo', // 先进先出调度
32
+ scheduling: 'lifo', // 后进先出调度(优先复用热连接,提高连接复用效率)
38
33
  });
39
34
  const httpsAgent = new https_1.default.Agent({
40
35
  keepAlive: true,
@@ -43,7 +38,7 @@ const httpsAgent = new https_1.default.Agent({
43
38
  maxFreeSockets: HTTP_CONFIG.maxFreeSockets,
44
39
  maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
45
40
  timeout: HTTP_CONFIG.timeout,
46
- scheduling: 'fifo',
41
+ scheduling: 'lifo', // 后进先出调度(优先复用热连接,提高连接复用效率)
47
42
  });
48
43
  // 配置 axios 默认使用这些 agent
49
44
  axios_1.default.defaults.httpAgent = httpAgent;
@@ -57,10 +52,16 @@ axios_1.default.defaults.maxContentLength = 50 * 1024 * 1024; // 50MB 最大响
57
52
  retryCondition(error) {
58
53
  // 重试临时错误和特定的网络错误
59
54
  const status = error.response?.status;
60
- const isNetworkError = error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT';
55
+ const isNetworkError = error.code === 'ECONNRESET' ||
56
+ error.code === 'ETIMEDOUT' ||
57
+ error.code === 'ECONNREFUSED' ||
58
+ error.code === 'ENOTFOUND' ||
59
+ error.code === 'ENETUNREACH' ||
60
+ error.code === 'EAI_AGAIN';
61
61
  const isServerError = status === 502 || status === 503 || status === 504;
62
62
  const isRateLimited = status === 429;
63
- return isNetworkError || isServerError || isRateLimited;
63
+ const isTimeout = error.code === 'ECONNABORTED' || error.message?.includes('timeout');
64
+ return isNetworkError || isServerError || isRateLimited || isTimeout;
64
65
  },
65
66
  retryDelay: (retryCount, error) => {
66
67
  // 指数退避 + 抖动
@@ -73,138 +74,34 @@ axios_1.default.defaults.maxContentLength = 50 * 1024 * 1024; // 50MB 最大响
73
74
  }
74
75
  return 1000 + Math.random() * 1000; // 1-2秒
75
76
  }
76
- // 指数退避:100ms, 200ms, 400ms...
77
+ // 指数退避:200ms, 400ms, 800ms...
77
78
  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
79
+ const jitter = Math.random() * 100; // 0-100ms 抖动
80
+ return Math.min(exponentialDelay + jitter, 3000); // 最多延迟3
80
81
  },
81
82
  shouldResetTimeout: true, // 重试时重置超时
82
83
  });
83
- // 连接池状态监控
84
- let requestCount = 0;
85
- let activeRequests = 0;
86
- let peakActiveRequests = 0; // 峰值并发
87
84
  async function callApi(url, request) {
88
- // 不再等待应用层队列,直接发起请求,由底层socket连接池控制并发
89
- const currentRequestId = ++requestCount;
90
- activeRequests++;
91
- // 记录峰值并发
92
- if (activeRequests > peakActiveRequests) {
93
- peakActiveRequests = activeRequests;
94
- }
95
- // 批量获取请求上下文,减少函数调用开销
85
+ // 获取请求上下文
96
86
  const ctx = request_context_1.requestContext.get('requestId') ? request_context_1.requestContext : null;
97
87
  const requestId = ctx?.get('requestId') || ctx?.get('traceMessageId') || (0, uuid_1.v4)();
98
88
  const pandoraUserId = ctx?.get('pandoraUserId') || '';
99
89
  const beLinkUserId = ctx?.get('beLinkUserId') || '';
100
90
  const pandoraRoleId = ctx?.get('pandoraRoleId') || '';
101
91
  const realIp = ctx?.get('realIp') || '';
102
- // 采样日志决策(提前计算,避免重复判断)
103
- const shouldLog = currentRequestId % HTTP_CONFIG.logThreshold === 0;
104
- const startTime = shouldLog ? Date.now() : 0;
105
- try {
106
- if (shouldLog) {
107
- console.log((0, safe_stable_stringify_1.default)({
108
- message: '发起HTTP请求',
109
- currentRequestId,
110
- activeRequests,
111
- requestId,
112
- url,
113
- type: 'http_request_start',
114
- }));
115
- }
116
- const response = await axios_1.default.post(url, request || {}, {
117
- headers: {
118
- 'x-request-id': requestId,
119
- 'x-belink-pandora-userid': pandoraUserId,
120
- 'x-belink-userid': beLinkUserId,
121
- 'x-belink-pandora-roleid': pandoraRoleId,
122
- 'x-real-ip': realIp,
123
- Connection: 'keep-alive',
124
- },
125
- timeout: HTTP_CONFIG.requestTimeout,
126
- httpAgent,
127
- httpsAgent,
128
- });
129
- if (shouldLog) {
130
- const duration = Date.now() - startTime;
131
- if (duration > 3000) {
132
- console.log((0, safe_stable_stringify_1.default)({
133
- message: '请求完成',
134
- currentRequestId,
135
- duration: `${duration}ms`,
136
- activeRequests,
137
- type: 'http_request_complete',
138
- }));
139
- }
140
- }
141
- const responseData = response.data;
142
- return responseData.data;
143
- }
144
- catch (error) {
145
- const axiosError = error;
146
- const duration = startTime ? Date.now() - startTime : 0;
147
- // 错误始终记录(但简化输出)
148
- console.error((0, safe_stable_stringify_1.default)({
149
- message: '请求失败',
150
- currentRequestId,
151
- url,
152
- duration: `${duration}ms`,
153
- activeRequests,
154
- errorMessage: axiosError.message,
155
- type: 'http_request_failed',
156
- }));
157
- if (axiosError.response) {
158
- const response = axiosError.response;
159
- const data = response.data;
160
- console.error((0, safe_stable_stringify_1.default)({
161
- message: '响应异常',
162
- status: response.status,
163
- errorMessage: data?.message || axiosError.message,
164
- type: 'http_response_error',
165
- }));
166
- }
167
- throw error;
168
- }
169
- finally {
170
- // 记录请求完成,减少活跃计数
171
- activeRequests--;
172
- }
173
- }
174
- // 导出监控函数
175
- function getConnectionStats() {
176
- const stats = {
177
- // 当前状态
178
- activeRequests,
179
- totalRequests: requestCount,
180
- // 峰值指标
181
- peakActiveRequests,
182
- // Socket连接池状态(这是真正的并发控制点)
183
- httpSockets: {
184
- total: Object.keys(httpAgent.sockets).reduce((sum, host) => sum + (httpAgent.sockets[host]?.length || 0), 0),
185
- hosts: Object.keys(httpAgent.sockets).length,
186
- details: httpAgent.sockets,
187
- },
188
- httpsSockets: {
189
- total: Object.keys(httpsAgent.sockets).reduce((sum, host) => sum + (httpsAgent.sockets[host]?.length || 0), 0),
190
- hosts: Object.keys(httpsAgent.sockets).length,
191
- details: httpsAgent.sockets,
92
+ const response = await axios_1.default.post(url, request, {
93
+ headers: {
94
+ 'x-request-id': requestId,
95
+ 'x-belink-pandora-userid': pandoraUserId,
96
+ 'x-belink-userid': beLinkUserId,
97
+ 'x-belink-pandora-roleid': pandoraRoleId,
98
+ 'x-real-ip': realIp,
99
+ Connection: 'keep-alive',
192
100
  },
193
- // 配置信息
194
- config: {
195
- maxSockets: HTTP_CONFIG.maxSockets,
196
- maxTotalSockets: HTTP_CONFIG.maxTotalSockets,
197
- requestTimeout: HTTP_CONFIG.requestTimeout,
198
- note: '已移除应用层并发队列限制,完全依赖socket连接池',
199
- },
200
- };
201
- return stats;
202
- }
203
- // 重置峰值统计(可用于定期重置)
204
- function resetPeakStats() {
205
- peakActiveRequests = activeRequests;
206
- console.log((0, safe_stable_stringify_1.default)({
207
- message: '峰值统计已重置',
208
- type: 'stats_reset',
209
- }));
101
+ timeout: HTTP_CONFIG.requestTimeout,
102
+ httpAgent,
103
+ httpsAgent,
104
+ });
105
+ const responseData = response.data;
106
+ return responseData.data;
210
107
  }