@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 +1 -1
- package/utils/http.d.ts +1 -23
- package/utils/http.js +37 -140
package/package.json
CHANGED
package/utils/http.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
declare module '@fastify/request-context' {
|
|
2
2
|
interface RequestContextData {
|
|
3
|
-
requestId
|
|
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:
|
|
19
|
-
maxFreeSockets: 1000, //
|
|
20
|
-
maxTotalSockets:
|
|
21
|
-
keepAliveMsecs:
|
|
22
|
-
timeout:
|
|
23
|
-
requestTimeout:
|
|
24
|
-
retries:
|
|
25
|
-
retryBaseDelay:
|
|
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: '
|
|
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: '
|
|
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' ||
|
|
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
|
-
|
|
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
|
-
// 指数退避:
|
|
77
|
+
// 指数退避:200ms, 400ms, 800ms...
|
|
77
78
|
const exponentialDelay = HTTP_CONFIG.retryBaseDelay * Math.pow(2, retryCount - 1);
|
|
78
|
-
const jitter = Math.random() *
|
|
79
|
-
return Math.min(exponentialDelay + jitter,
|
|
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
|
-
//
|
|
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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
|
}
|