nstarter-http-request 0.1.1 → 0.1.3

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +9 -12
  3. package/dist/cjs/client.js +10 -15
  4. package/dist/cjs/client.js.map +1 -1
  5. package/dist/cjs/const/config.const.js +2 -2
  6. package/dist/cjs/const/config.const.js.map +1 -1
  7. package/dist/cjs/security/dns.validator.js +13 -0
  8. package/dist/cjs/security/dns.validator.js.map +1 -1
  9. package/dist/cjs/stream/index.js +6 -0
  10. package/dist/cjs/stream/index.js.map +1 -0
  11. package/dist/cjs/stream/metrics.transform.js +30 -0
  12. package/dist/cjs/stream/metrics.transform.js.map +1 -0
  13. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  14. package/dist/esm/client.js +11 -16
  15. package/dist/esm/client.js.map +1 -1
  16. package/dist/esm/const/config.const.js +2 -2
  17. package/dist/esm/const/config.const.js.map +1 -1
  18. package/dist/esm/security/dns.validator.js +13 -0
  19. package/dist/esm/security/dns.validator.js.map +1 -1
  20. package/dist/esm/stream/index.js +2 -0
  21. package/dist/esm/stream/index.js.map +1 -0
  22. package/dist/esm/stream/metrics.transform.js +26 -0
  23. package/dist/esm/stream/metrics.transform.js.map +1 -0
  24. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  25. package/dist/types/client.d.ts.map +1 -1
  26. package/dist/types/security/dns.validator.d.ts.map +1 -1
  27. package/dist/types/stream/index.d.ts +2 -0
  28. package/dist/types/stream/index.d.ts.map +1 -0
  29. package/dist/types/stream/metrics.transform.d.ts +18 -0
  30. package/dist/types/stream/metrics.transform.d.ts.map +1 -0
  31. package/package.json +1 -1
  32. package/src/client.ts +11 -17
  33. package/src/const/config.const.ts +2 -2
  34. package/src/security/dns.validator.ts +17 -0
  35. package/src/stream/index.ts +2 -0
  36. package/src/stream/metrics.transform.ts +32 -0
  37. package/docs/adapters.md +0 -53
  38. package/docs/configuration.md +0 -149
  39. package/docs/logging.md +0 -70
  40. package/docs/proxy.md +0 -44
  41. package/docs/security.md +0 -56
  42. package/docs/trace-context.md +0 -436
package/src/client.ts CHANGED
@@ -36,8 +36,10 @@ import {
36
36
  } from './utils';
37
37
  import {
38
38
  PassThrough,
39
+ pipeline,
39
40
  Readable
40
41
  } from 'node:stream';
42
+ import { MetricsTransform } from './stream';
41
43
 
42
44
  /**
43
45
  * HTTP 客户端
@@ -349,7 +351,6 @@ export class NsHttpClient implements IHttpClient {
349
351
  ttfb: number
350
352
  ): HttpResponse<T> {
351
353
  const stream = response.data as any;
352
- let bytesTransferred = 0;
353
354
 
354
355
  // 记录首次响应日志(流开始)
355
356
  this.logResponse(options, response, ttfb, {
@@ -366,20 +367,13 @@ export class NsHttpClient implements IHttpClient {
366
367
 
367
368
  // 所有适配器都返回 Node.js Readable
368
369
  const originalStream = stream as Readable;
370
+ const metrics = new MetricsTransform();
369
371
  const wrappedStream = new PassThrough();
370
372
 
371
- // 监听数据事件统计字节数
372
- originalStream.on('data', (chunk: Buffer) => {
373
- bytesTransferred += chunk.length;
374
- wrappedStream.write(chunk);
375
- });
376
-
377
- // 监听结束事件记录日志
378
- originalStream.on('end', () => {
373
+ // 监听 wrappedStream 的结束事件记录日志
374
+ wrappedStream.on('end', () => {
379
375
  const totalDuration = Date.now() - requestStartTime;
380
- wrappedStream.end();
381
-
382
- // 记录流完成日志
376
+ const bytesTransferred = metrics.getBytesTransferred();
383
377
  this.logStreamCompleted(
384
378
  options,
385
379
  response,
@@ -389,9 +383,10 @@ export class NsHttpClient implements IHttpClient {
389
383
  );
390
384
  });
391
385
 
392
- // 监听错误事件
393
- originalStream.on('error', (error: Error) => {
386
+ // 监听 wrappedStream 的错误事件记录日志
387
+ wrappedStream.on('error', (error: Error) => {
394
388
  const totalDuration = Date.now() - requestStartTime;
389
+ const bytesTransferred = metrics.getBytesTransferred();
395
390
  this.logger.error('Stream read error', {
396
391
  method: options.method,
397
392
  url: options.url,
@@ -400,11 +395,10 @@ export class NsHttpClient implements IHttpClient {
400
395
  bytesTransferred,
401
396
  error: error.message
402
397
  });
403
- wrappedStream.destroy(error);
404
398
  });
405
399
 
406
- // 使用 pipe 连接流
407
- originalStream.pipe(wrappedStream, { end: false });
400
+ // 使用 pipeline 连接流,自动处理错误传播和资源清理, 要求最后一个参数必须是回调函数
401
+ pipeline(originalStream, metrics, wrappedStream, () => {});
408
402
 
409
403
  // 返回包装后的响应
410
404
  return {
@@ -18,8 +18,8 @@ export const MAX_DNS_CACHE_TTL = 5 * 60 * 1000; // 300000ms (5 分钟)
18
18
  */
19
19
  export const DEFAULT_SECURITY_CONFIG: SecurityConfig = {
20
20
  rejectUnauthorized: true,
21
- enableDnsValidation: true,
22
- enableIpValidation: true,
21
+ enableDnsValidation: false,
22
+ enableIpValidation: false,
23
23
  allowPrivateIp: false,
24
24
  whitelist: [],
25
25
  blacklist: [],
@@ -73,6 +73,23 @@ export class DnsValidator {
73
73
  // IPv6 解析失败
74
74
  }
75
75
 
76
+ // resolve4/resolve6 不拼接 search 域,在 ACK 等带集群后缀的环境会 ENOTFOUND;
77
+ // 失败时回退到 lookup(走 getaddrinfo,会按 resolv.conf 拼 search),与建连时行为一致
78
+ if (addresses.length === 0) {
79
+ try {
80
+ const lookupResult = await CommonUtils.withTimeout(
81
+ dns.lookup(hostname, { all: true }),
82
+ this.resolveTimeout,
83
+ 'DNS lookup timed out'
84
+ );
85
+ for (const { address } of lookupResult) {
86
+ addresses.push(address);
87
+ }
88
+ } catch {
89
+ // lookup 也失败,下面统一抛错
90
+ }
91
+ }
92
+
76
93
  if (addresses.length === 0) {
77
94
  throw new Error(`Unable to resolve hostname: ${ hostname }`);
78
95
  }
@@ -0,0 +1,2 @@
1
+ export { MetricsTransform } from './metrics.transform';
2
+
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 流处理工具类
3
+ */
4
+
5
+ import { Transform } from 'node:stream';
6
+
7
+ /**
8
+ * 统计流数据大小的 Transform 流
9
+ */
10
+ export class MetricsTransform extends Transform {
11
+ private bytesTransferred: number;
12
+
13
+ constructor() {
14
+ super();
15
+ this.bytesTransferred = 0;
16
+ }
17
+
18
+ public _transform(chunk: Buffer, encoding: string, callback: () => void): void {
19
+ this.bytesTransferred += chunk.length;
20
+ this.push(chunk);
21
+ callback();
22
+ }
23
+
24
+ /**
25
+ * 获取已传输的字节数
26
+ * @returns 已传输的字节数
27
+ */
28
+ public getBytesTransferred(): number {
29
+ return this.bytesTransferred;
30
+ }
31
+ }
32
+
package/docs/adapters.md DELETED
@@ -1,53 +0,0 @@
1
- # 适配器切换
2
-
3
- ## 支持的适配器
4
-
5
- 本库支持多种 HTTP 客户端适配器,你可以根据场景选择最适合的:
6
-
7
- - **Axios** - 适合通用场景,功能丰富,生态完善
8
- - **Undici** - Node.js 原生高性能 HTTP 客户端,适合高并发场景
9
-
10
- ## 切换适配器
11
-
12
- ```typescript
13
- import { EClientAdapter } from 'nstarter-http-request';
14
-
15
- // 使用 Axios 适配器(适合通用场景)
16
- const axiosClient = new NsHttpClient().withAdapter(EClientAdapter.axios);
17
-
18
- // 使用 Undici 适配器(高性能,Node.js 原生)
19
- const undiciClient = new NsHttpClient().withAdapter(EClientAdapter.undici);
20
- ```
21
-
22
- ## 在初始化时指定适配器
23
-
24
- ```typescript
25
- import { NsHttpClient, EClientAdapter } from 'nstarter-http-request';
26
-
27
- // 创建客户端实例时指定适配器
28
- const client = new NsHttpClient({
29
- adapter: EClientAdapter.axios,
30
- security: {
31
- enableDnsValidation: true,
32
- enableIpValidation: true,
33
- allowPrivateIp: false
34
- }
35
- });
36
- ```
37
-
38
- ## 适配器选择建议
39
-
40
- ### 使用 Axios 的场景
41
-
42
- - 需要丰富的配置选项
43
- - 需要拦截器功能
44
- - 需要广泛的浏览器兼容性(通过 polyfill)
45
- - 团队熟悉 Axios API
46
-
47
- ### 使用 Undici 的场景
48
-
49
- - 需要极致性能
50
- - 高并发场景
51
- - 纯 Node.js 环境
52
- - 希望减少依赖体积
53
-
@@ -1,149 +0,0 @@
1
- # 完整配置示例
2
-
3
- 以下是一个包含所有配置选项的完整示例:
4
-
5
- ```typescript
6
- import { NsHttpClient, EClientAdapter } from 'nstarter-http-request';
7
-
8
- const client = new NsHttpClient({
9
- // 适配器配置
10
- adapter: EClientAdapter.axios,
11
-
12
- // 安全配置
13
- security: {
14
- rejectUnauthorized: true, // 是否验证 SSL 证书(生产环境建议 true)
15
- enableDnsValidation: true, // 开启 DNS 验证
16
- enableIpValidation: true, // 开启 IP 验证
17
- allowPrivateIp: false, // 是否允许访问私有 IP(内网地址)
18
- whitelist: [ // 域名白名单
19
- 'trusted.com', '*.trusted.com', // 匹配根域名和一级子域名
20
- 'api.example.com' // 仅匹配该域名
21
- ],
22
- blacklist: [ // 域名黑名单
23
- 'malicious.com', '*.malicious.com', // 根域名和一级子域名
24
- 'unsafe.net'
25
- ],
26
- dnsCacheTtl: 60000, // DNS 缓存 TTL(毫秒,默认 60 秒)
27
- dnsCacheMaxSize: 500 // DNS 缓存最大条目数(默认 500,使用 LRU 淘汰策略)
28
- },
29
-
30
- // 日志配置
31
- logging: {
32
- enabled: true, // 是否启用日志
33
- logRequestBody: true, // 是否记录请求体
34
- logResponseBody: true, // 是否记录响应体
35
- bodyMaxLength: 1024 * 1024, // 请求/响应体最大记录长度(字节,默认 1MB)
36
- logger: customLogger, // 自定义日志记录器(可选,实现 ILogger 接口)
37
- httpLogger: customHttpLogger, // 自定义 HTTP 日志记录器(可选,实现 IHttpClientLogger 接口)
38
- filter: { // 日志过滤配置
39
- methods: ['POST', 'PUT'], // 只记录指定 HTTP 方法
40
- urlPatterns: [ // 只记录匹配的 URL(支持正则)
41
- /\/api\//,
42
- 'https://api.example.com'
43
- ],
44
- scenarios: ['payment'], // 只记录指定业务场景
45
- statusCodes: [404, 500], // 只记录指定状态码
46
- statusCodeRanges: [ // 只记录指定状态码范围
47
- { min: 400, max: 499 }, // 客户端错误
48
- { min: 500, max: 599 } // 服务端错误
49
- ],
50
- onlyFailed: false, // 是否只记录失败请求
51
- onlySuccess: false, // 是否只记录成功请求
52
- minDuration: 100, // 只记录耗时超过指定毫秒的请求
53
- customFilter: (options) => { // 自定义过滤函数
54
- return options.request.method === 'POST';
55
- }
56
- }
57
- },
58
-
59
- // 请求配置
60
- request: {
61
- timeout: 30000, // 请求超时(毫秒,默认 30 秒)
62
- retries: 3, // 重试次数(默认 0)
63
- retryDelay: 1000, // 重试延迟(毫秒,默认 1 秒)
64
- maxRedirects: 5, // 最大重定向次数(默认 5)
65
- maxRequestBodySize: 10 * 1024 * 1024, // 最大请求体大小(字节,默认 10MB)
66
- maxResponseBodySize: 50 * 1024 * 1024, // 最大响应体大小(字节,默认 50MB)
67
- proxy: { // HTTP 代理配置(可选,不同于正向代理)
68
- host: 'proxy.example.com',
69
- port: 8080,
70
- protocol: 'http', // 'http' | 'https'
71
- auth: { // 代理认证(可选)
72
- username: 'user',
73
- password: 'pass'
74
- }
75
- }
76
- }
77
- });
78
- ```
79
-
80
- ## 配置说明
81
-
82
- ### 适配器配置
83
-
84
- - `adapter`: 指定使用的 HTTP 客户端适配器,可选值:`EClientAdapter.axios` 或 `EClientAdapter.undici`
85
-
86
- ### 安全配置
87
-
88
- 详细说明请参考 [安全配置文档](./security.md)
89
-
90
- ### 日志配置
91
-
92
- 详细说明请参考 [日志配置文档](./logging.md)
93
-
94
- ### 请求配置
95
-
96
- - `timeout`: 请求超时时间(毫秒)
97
- - `retries`: 请求失败时的重试次数
98
- - `retryDelay`: 重试延迟时间(毫秒)
99
- - `maxRedirects`: 最大重定向次数
100
- - `maxRequestBodySize`: 最大请求体大小限制(字节)
101
- - `maxResponseBodySize`: 最大响应体大小限制(字节)
102
- - `proxy`: HTTP 代理配置(注意:这与正向代理不同,详见 [代理配置文档](./proxy.md))
103
-
104
- ## 默认配置值
105
-
106
- 以下是所有配置项的默认值,如果你不指定某个配置项,将使用以下默认值:
107
-
108
- ### 适配器配置
109
-
110
- | 配置项 | 默认值 | 说明 |
111
- |--------|--------|------|
112
- | `adapter` | `EClientAdapter.axios` | 默认使用 Axios 适配器 |
113
-
114
- ### 安全配置
115
-
116
- | 配置项 | 默认值 | 说明 |
117
- |--------|--------|------|
118
- | `rejectUnauthorized` | `true` | 默认验证 SSL 证书(生产环境建议保持为 true) |
119
- | `enableDnsValidation` | `true` | 默认启用 DNS 验证 |
120
- | `enableIpValidation` | `true` | 默认启用 IP 验证 |
121
- | `allowPrivateIp` | `false` | 默认禁止访问私有 IP(内网地址) |
122
- | `whitelist` | `[]` | 默认无白名单 |
123
- | `blacklist` | `[]` | 默认无黑名单 |
124
- | `dnsCacheTtl` | `60000` | DNS 缓存 TTL,默认 60 秒(60000 毫秒) |
125
- | `dnsCacheMaxSize` | `500` | DNS 缓存最大条目数,默认 500,使用 LRU 淘汰策略 |
126
-
127
- > **注意**:DNS 缓存最大 TTL 限制为 5 分钟(300000 毫秒),即使设置更大的值也会被限制为 5 分钟,避免过长的缓存时间导致内存积压。
128
-
129
- ### 日志配置
130
-
131
- | 配置项 | 默认值 | 说明 |
132
- |--------|--------|------|
133
- | `enabled` | `true` | 默认启用日志 |
134
- | `logRequestBody` | `true` | 默认记录请求体 |
135
- | `logResponseBody` | `true` | 默认记录响应体 |
136
- | `bodyMaxLength` | `1048576` | 请求/响应体最大记录长度,默认 1MB(1024 * 1024 字节) |
137
-
138
- ### 请求配置
139
-
140
- | 配置项 | 默认值 | 说明 |
141
- |--------|--------|------|
142
- | `timeout` | `30000` | 请求超时时间,默认 30 秒(30000 毫秒) |
143
- | `retries` | `0` | 默认不重试 |
144
- | `retryDelay` | `1000` | 重试延迟时间,默认 1 秒(1000 毫秒) |
145
- | `maxRedirects` | `5` | 最大重定向次数,默认 5 次 |
146
- | `maxRequestBodySize` | `10485760` | 最大请求体大小,默认 10MB(10 * 1024 * 1024 字节) |
147
- | `maxResponseBodySize` | `52428800` | 最大响应体大小,默认 50MB(50 * 1024 * 1024 字节) |
148
- | `proxy` | `undefined` | 默认不使用 HTTP 代理 |
149
-
package/docs/logging.md DELETED
@@ -1,70 +0,0 @@
1
- # 日志配置详解
2
-
3
- ## 自定义日志记录器
4
-
5
- ```typescript
6
- import { ILogger } from 'nstarter-http-request';
7
-
8
- const customLogger: ILogger = {
9
- debug: (msg, meta) => console.debug(msg, meta),
10
- info: (msg, meta) => console.info(msg, meta),
11
- warn: (msg, meta) => console.warn(msg, meta),
12
- error: (msg, meta) => console.error(msg, meta)
13
- };
14
-
15
- const client = new NsHttpClient({
16
- logging: { logger: customLogger }
17
- });
18
- ```
19
-
20
- ## 日志过滤
21
-
22
- ```typescript
23
- const client = new NsHttpClient({
24
- logging: {
25
- enabled: true,
26
- filter: {
27
- // 只记录失败的 POST 请求
28
- methods: ['POST'],
29
- onlyFailed: true,
30
- minDuration: 1000 // 且耗时超过 1 秒
31
- }
32
- }
33
- });
34
- ```
35
-
36
- ## 完整日志配置示例
37
-
38
- ```typescript
39
- const client = new NsHttpClient({
40
- // 日志配置
41
- logging: {
42
- enabled: true, // 是否启用日志
43
- logRequestBody: true, // 是否记录请求体
44
- logResponseBody: true, // 是否记录响应体
45
- bodyMaxLength: 1024 * 1024, // 请求/响应体最大记录长度(字节,默认 1MB)
46
- logger: customLogger, // 自定义日志记录器(可选,实现 ILogger 接口)
47
- httpLogger: customHttpLogger, // 自定义 HTTP 日志记录器(可选,实现 IHttpClientLogger 接口)
48
- filter: { // 日志过滤配置
49
- methods: ['POST', 'PUT'], // 只记录指定 HTTP 方法
50
- urlPatterns: [ // 只记录匹配的 URL(支持正则)
51
- /\/api\//,
52
- 'https://api.example.com'
53
- ],
54
- scenarios: ['payment'], // 只记录指定业务场景
55
- statusCodes: [404, 500], // 只记录指定状态码
56
- statusCodeRanges: [ // 只记录指定状态码范围
57
- { min: 400, max: 499 }, // 客户端错误
58
- { min: 500, max: 599 } // 服务端错误
59
- ],
60
- onlyFailed: false, // 是否只记录失败请求
61
- onlySuccess: false, // 是否只记录成功请求
62
- minDuration: 100, // 只记录耗时超过指定毫秒的请求
63
- customFilter: (options) => { // 自定义过滤函数
64
- return options.request.method === 'POST';
65
- }
66
- }
67
- }
68
- });
69
- ```
70
-
package/docs/proxy.md DELETED
@@ -1,44 +0,0 @@
1
- # 正向代理配置
2
-
3
- ## 基础使用
4
-
5
- ```typescript
6
- const client = new NsHttpClient()
7
- .withForwardProxy({
8
- enabled: true,
9
- http_proxy: 'http://proxy.example.com:8080',
10
- https_proxy: 'https://proxy.example.com:8443',
11
- no_proxy: [ // 不使用代理的域名(支持传统模式)
12
- 'localhost', // 精确匹配
13
- '127.0.0.1', // 精确匹配
14
- '.internal.com', // 后缀匹配(匹配所有子域名)
15
- '.local', // 后缀匹配
16
- '192.168.' // 前缀匹配(IP地址)
17
- ]
18
- });
19
- ```
20
-
21
- ## no_proxy 支持的模式
22
-
23
- - `example.com` - 精确匹配该域名
24
- - `.example.com` - 后缀匹配,匹配所有以 `.example.com` 结尾的域名(包括子域名)
25
- - `192.168.` - 前缀匹配,主要用于 IP 地址范围匹配
26
-
27
- ## HTTP 代理配置(不同于正向代理)
28
-
29
- ```typescript
30
- const client = new NsHttpClient({
31
- request: {
32
- proxy: { // HTTP 代理配置(可选,不同于正向代理)
33
- host: 'proxy.example.com',
34
- port: 8080,
35
- protocol: 'http', // 'http' | 'https'
36
- auth: { // 代理认证(可选)
37
- username: 'user',
38
- password: 'pass'
39
- }
40
- }
41
- }
42
- });
43
- ```
44
-
package/docs/security.md DELETED
@@ -1,56 +0,0 @@
1
- # 安全配置详解
2
-
3
- ## SSL 证书验证
4
-
5
- ```typescript
6
- const client = new NsHttpClient({
7
- security: {
8
- rejectUnauthorized: true // 生产环境必须为 true,开发环境可设为 false
9
- }
10
- });
11
- ```
12
-
13
- ## SSRF 防护
14
-
15
- ```typescript
16
- const client = new NsHttpClient({
17
- security: {
18
- enableDnsValidation: true, // 启用 DNS 解析验证
19
- enableIpValidation: true, // 启用 IP 地址验证
20
- allowPrivateIp: false, // 禁止访问内网 IP(10.x.x.x, 192.168.x.x, 127.x.x.x 等)
21
- whitelist: [ // 白名单(支持以下模式)
22
- 'api.example.com', // 1. 精确匹配
23
- '*.safe.com', // 2. 通配符匹配(只匹配一级子域名)
24
- 'trusted.com', '*.trusted.com' // 3. 组合使用:匹配根域名和一级子域名
25
- ],
26
- blacklist: ['malicious.com', '*.malicious.com'] // 黑名单:根域名 + 一级子域名
27
- }
28
- });
29
- ```
30
-
31
- ## 支持的域名模式
32
-
33
- | 模式 | 匹配规则 | 示例 |
34
- |------|---------|------|
35
- | `example.com` | 精确匹配 | ✅ `example.com`<br>❌ `api.example.com` |
36
- | `*.example.com` | 通配符匹配<br>只匹配一级子域名(不含根域名) | ❌ `example.com`<br>✅ `api.example.com`<br>✅ `www.example.com`<br>❌ `v2.api.example.com`(多级不匹配) |
37
- | 组合使用<br>`['example.com', '*.example.com']` | 精确匹配 + 通配符匹配<br>匹配根域名和一级子域名 | ✅ `example.com`<br>✅ `api.example.com`<br>✅ `www.example.com`<br>❌ `v2.api.example.com`(多级不匹配) |
38
-
39
- ## DNS 缓存机制
40
-
41
- 为提升性能,DNS 解析结果会被缓存。缓存使用 [lru-cache](https://www.npmjs.com/package/lru-cache) 实现,具有以下特性:
42
-
43
- - ✅ **TTL 自动过期**:缓存条目到期后自动释放内存
44
- - ✅ **LRU 淘汰策略**:缓存满时自动淘汰最近最少使用的条目
45
- - ✅ **容量限制**:默认最多缓存 500 个域名解析结果
46
- - ✅ **可配置**:支持自定义 TTL 和缓存容量
47
-
48
- ```typescript
49
- const client = new NsHttpClient({
50
- security: {
51
- dnsCacheTtl: 60000, // 缓存时间:60 秒(默认)
52
- dnsCacheMaxSize: 500 // 最大缓存条目数(默认)
53
- }
54
- });
55
- ```
56
-