undici 7.6.0 → 7.7.0
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/docs/docs/api/Dispatcher.md +1 -1
- package/docs/docs/api/H2CClient.md +262 -0
- package/index.js +2 -0
- package/lib/core/connect.js +2 -78
- package/lib/core/util.js +78 -2
- package/lib/dispatcher/client-h2.js +1 -0
- package/lib/dispatcher/h2c-client.js +122 -0
- package/package.json +2 -2
- package/types/dispatcher.d.ts +5 -3
- package/types/h2c-client.d.ts +75 -0
- package/types/index.d.ts +3 -1
|
@@ -194,7 +194,7 @@ Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls wo
|
|
|
194
194
|
* **method** `string`
|
|
195
195
|
* **reset** `boolean` (optional) - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header,otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards.
|
|
196
196
|
* **body** `string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null` (optional) - Default: `null`
|
|
197
|
-
* **headers** `UndiciHeaders
|
|
197
|
+
* **headers** `UndiciHeaders` (optional) - Default: `null`.
|
|
198
198
|
* **query** `Record<string, any> | null` (optional) - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead.
|
|
199
199
|
* **idempotent** `boolean` (optional) - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed.
|
|
200
200
|
* **blocking** `boolean` (optional) - Default: `method !== 'HEAD'` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received.
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# Class: H2CClient
|
|
2
|
+
|
|
3
|
+
Extends: `undici.Dispatcher`
|
|
4
|
+
|
|
5
|
+
A basic H2C client.
|
|
6
|
+
|
|
7
|
+
**Example**
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
const { createServer } = require('node:http2')
|
|
11
|
+
const { once } = require('node:events')
|
|
12
|
+
const { H2CClient } = require('undici')
|
|
13
|
+
|
|
14
|
+
const server = createServer((req, res) => {
|
|
15
|
+
res.writeHead(200)
|
|
16
|
+
res.end('Hello, world!')
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
server.listen()
|
|
20
|
+
once(server, 'listening').then(() => {
|
|
21
|
+
const client = new H2CClient(`http://localhost:${server.address().port}/`)
|
|
22
|
+
|
|
23
|
+
const response = await client.request({ path: '/', method: 'GET' })
|
|
24
|
+
console.log(response.statusCode) // 200
|
|
25
|
+
response.body.text.then((text) => {
|
|
26
|
+
console.log(text) // Hello, world!
|
|
27
|
+
})
|
|
28
|
+
})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## `new H2CClient(url[, options])`
|
|
32
|
+
|
|
33
|
+
Arguments:
|
|
34
|
+
|
|
35
|
+
- **url** `URL | string` - Should only include the **protocol, hostname, and port**. It only supports `http` protocol.
|
|
36
|
+
- **options** `H2CClientOptions` (optional)
|
|
37
|
+
|
|
38
|
+
Returns: `H2CClient`
|
|
39
|
+
|
|
40
|
+
### Parameter: `H2CClientOptions`
|
|
41
|
+
|
|
42
|
+
- **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. Please note the `timeout` will be reset if you keep writing data to the socket everytime.
|
|
43
|
+
- **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds.
|
|
44
|
+
- **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by _keep-alive_ hints from the server. Defaults to 10 minutes.
|
|
45
|
+
- **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by _keep-alive_ hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds.
|
|
46
|
+
- **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `2e3` - A number of milliseconds subtracted from server _keep-alive_ hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds.
|
|
47
|
+
- **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB.
|
|
48
|
+
- **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable.
|
|
49
|
+
- **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
|
|
50
|
+
- **pipelining** `number | null` (optional) - Default to `maxConcurrentStreams` - The amount of concurrent requests sent over a single HTTP/2 session in accordance with [RFC-7540](https://httpwg.org/specs/rfc7540.html#StreamsLayer) Stream specification. Streams can be closed up by remote server at any time.
|
|
51
|
+
- **connect** `ConnectOptions | null` (optional) - Default: `null`.
|
|
52
|
+
- **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body.
|
|
53
|
+
- **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version.
|
|
54
|
+
- **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details.
|
|
55
|
+
|
|
56
|
+
#### Parameter: `H2CConnectOptions`
|
|
57
|
+
|
|
58
|
+
- **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe.
|
|
59
|
+
- **timeout** `number | null` (optional) - In milliseconds, Default `10e3`.
|
|
60
|
+
- **servername** `string | null` (optional)
|
|
61
|
+
- **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled
|
|
62
|
+
- **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds
|
|
63
|
+
|
|
64
|
+
### Example - Basic Client instantiation
|
|
65
|
+
|
|
66
|
+
This will instantiate the undici H2CClient, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`.
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
"use strict";
|
|
70
|
+
import { H2CClient } from "undici";
|
|
71
|
+
|
|
72
|
+
const client = new H2CClient("http://localhost:3000");
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Instance Methods
|
|
76
|
+
|
|
77
|
+
### `H2CClient.close([callback])`
|
|
78
|
+
|
|
79
|
+
Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise).
|
|
80
|
+
|
|
81
|
+
### `H2CClient.destroy([error, callback])`
|
|
82
|
+
|
|
83
|
+
Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise).
|
|
84
|
+
|
|
85
|
+
Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided).
|
|
86
|
+
|
|
87
|
+
### `H2CClient.connect(options[, callback])`
|
|
88
|
+
|
|
89
|
+
See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback).
|
|
90
|
+
|
|
91
|
+
### `H2CClient.dispatch(options, handlers)`
|
|
92
|
+
|
|
93
|
+
Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler).
|
|
94
|
+
|
|
95
|
+
### `H2CClient.pipeline(options, handler)`
|
|
96
|
+
|
|
97
|
+
See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler).
|
|
98
|
+
|
|
99
|
+
### `H2CClient.request(options[, callback])`
|
|
100
|
+
|
|
101
|
+
See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
|
|
102
|
+
|
|
103
|
+
### `H2CClient.stream(options, factory[, callback])`
|
|
104
|
+
|
|
105
|
+
See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback).
|
|
106
|
+
|
|
107
|
+
### `H2CClient.upgrade(options[, callback])`
|
|
108
|
+
|
|
109
|
+
See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback).
|
|
110
|
+
|
|
111
|
+
## Instance Properties
|
|
112
|
+
|
|
113
|
+
### `H2CClient.closed`
|
|
114
|
+
|
|
115
|
+
- `boolean`
|
|
116
|
+
|
|
117
|
+
`true` after `H2CClient.close()` has been called.
|
|
118
|
+
|
|
119
|
+
### `H2CClient.destroyed`
|
|
120
|
+
|
|
121
|
+
- `boolean`
|
|
122
|
+
|
|
123
|
+
`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed.
|
|
124
|
+
|
|
125
|
+
### `H2CClient.pipelining`
|
|
126
|
+
|
|
127
|
+
- `number`
|
|
128
|
+
|
|
129
|
+
Property to get and set the pipelining factor.
|
|
130
|
+
|
|
131
|
+
## Instance Events
|
|
132
|
+
|
|
133
|
+
### Event: `'connect'`
|
|
134
|
+
|
|
135
|
+
See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect).
|
|
136
|
+
|
|
137
|
+
Parameters:
|
|
138
|
+
|
|
139
|
+
- **origin** `URL`
|
|
140
|
+
- **targets** `Array<Dispatcher>`
|
|
141
|
+
|
|
142
|
+
Emitted when a socket has been created and connected. The client will connect once `client.size > 0`.
|
|
143
|
+
|
|
144
|
+
#### Example - Client connect event
|
|
145
|
+
|
|
146
|
+
```js
|
|
147
|
+
import { createServer } from "node:http2";
|
|
148
|
+
import { H2CClient } from "undici";
|
|
149
|
+
import { once } from "events";
|
|
150
|
+
|
|
151
|
+
const server = createServer((request, response) => {
|
|
152
|
+
response.end("Hello, World!");
|
|
153
|
+
}).listen();
|
|
154
|
+
|
|
155
|
+
await once(server, "listening");
|
|
156
|
+
|
|
157
|
+
const client = new H2CClient(`http://localhost:${server.address().port}`);
|
|
158
|
+
|
|
159
|
+
client.on("connect", (origin) => {
|
|
160
|
+
console.log(`Connected to ${origin}`); // should print before the request body statement
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
try {
|
|
164
|
+
const { body } = await client.request({
|
|
165
|
+
path: "/",
|
|
166
|
+
method: "GET",
|
|
167
|
+
});
|
|
168
|
+
body.setEncoding("utf-8");
|
|
169
|
+
body.on("data", console.log);
|
|
170
|
+
client.close();
|
|
171
|
+
server.close();
|
|
172
|
+
} catch (error) {
|
|
173
|
+
console.error(error);
|
|
174
|
+
client.close();
|
|
175
|
+
server.close();
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### Event: `'disconnect'`
|
|
180
|
+
|
|
181
|
+
See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect).
|
|
182
|
+
|
|
183
|
+
Parameters:
|
|
184
|
+
|
|
185
|
+
- **origin** `URL`
|
|
186
|
+
- **targets** `Array<Dispatcher>`
|
|
187
|
+
- **error** `Error`
|
|
188
|
+
|
|
189
|
+
Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`.
|
|
190
|
+
|
|
191
|
+
#### Example - Client disconnect event
|
|
192
|
+
|
|
193
|
+
```js
|
|
194
|
+
import { createServer } from "node:http2";
|
|
195
|
+
import { H2CClient } from "undici";
|
|
196
|
+
import { once } from "events";
|
|
197
|
+
|
|
198
|
+
const server = createServer((request, response) => {
|
|
199
|
+
response.destroy();
|
|
200
|
+
}).listen();
|
|
201
|
+
|
|
202
|
+
await once(server, "listening");
|
|
203
|
+
|
|
204
|
+
const client = new H2CClient(`http://localhost:${server.address().port}`);
|
|
205
|
+
|
|
206
|
+
client.on("disconnect", (origin) => {
|
|
207
|
+
console.log(`Disconnected from ${origin}`);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
try {
|
|
211
|
+
await client.request({
|
|
212
|
+
path: "/",
|
|
213
|
+
method: "GET",
|
|
214
|
+
});
|
|
215
|
+
} catch (error) {
|
|
216
|
+
console.error(error.message);
|
|
217
|
+
client.close();
|
|
218
|
+
server.close();
|
|
219
|
+
}
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
### Event: `'drain'`
|
|
223
|
+
|
|
224
|
+
Emitted when pipeline is no longer busy.
|
|
225
|
+
|
|
226
|
+
See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain).
|
|
227
|
+
|
|
228
|
+
#### Example - Client drain event
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
import { createServer } from "node:http2";
|
|
232
|
+
import { H2CClient } from "undici";
|
|
233
|
+
import { once } from "events";
|
|
234
|
+
|
|
235
|
+
const server = createServer((request, response) => {
|
|
236
|
+
response.end("Hello, World!");
|
|
237
|
+
}).listen();
|
|
238
|
+
|
|
239
|
+
await once(server, "listening");
|
|
240
|
+
|
|
241
|
+
const client = new H2CClient(`http://localhost:${server.address().port}`);
|
|
242
|
+
|
|
243
|
+
client.on("drain", () => {
|
|
244
|
+
console.log("drain event");
|
|
245
|
+
client.close();
|
|
246
|
+
server.close();
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
const requests = [
|
|
250
|
+
client.request({ path: "/", method: "GET" }),
|
|
251
|
+
client.request({ path: "/", method: "GET" }),
|
|
252
|
+
client.request({ path: "/", method: "GET" }),
|
|
253
|
+
];
|
|
254
|
+
|
|
255
|
+
await Promise.all(requests);
|
|
256
|
+
|
|
257
|
+
console.log("requests completed");
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### Event: `'error'`
|
|
261
|
+
|
|
262
|
+
Invoked for users errors such as throwing in the `onError` handler.
|
package/index.js
CHANGED
|
@@ -8,6 +8,7 @@ const Agent = require('./lib/dispatcher/agent')
|
|
|
8
8
|
const ProxyAgent = require('./lib/dispatcher/proxy-agent')
|
|
9
9
|
const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')
|
|
10
10
|
const RetryAgent = require('./lib/dispatcher/retry-agent')
|
|
11
|
+
const H2CClient = require('./lib/dispatcher/h2c-client')
|
|
11
12
|
const errors = require('./lib/core/errors')
|
|
12
13
|
const util = require('./lib/core/util')
|
|
13
14
|
const { InvalidArgumentError } = errors
|
|
@@ -33,6 +34,7 @@ module.exports.Agent = Agent
|
|
|
33
34
|
module.exports.ProxyAgent = ProxyAgent
|
|
34
35
|
module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
|
|
35
36
|
module.exports.RetryAgent = RetryAgent
|
|
37
|
+
module.exports.H2CClient = H2CClient
|
|
36
38
|
module.exports.RetryHandler = RetryHandler
|
|
37
39
|
|
|
38
40
|
module.exports.DecoratorHandler = DecoratorHandler
|
package/lib/core/connect.js
CHANGED
|
@@ -3,10 +3,7 @@
|
|
|
3
3
|
const net = require('node:net')
|
|
4
4
|
const assert = require('node:assert')
|
|
5
5
|
const util = require('./util')
|
|
6
|
-
const { InvalidArgumentError
|
|
7
|
-
const timers = require('../util/timers')
|
|
8
|
-
|
|
9
|
-
function noop () {}
|
|
6
|
+
const { InvalidArgumentError } = require('./errors')
|
|
10
7
|
|
|
11
8
|
let tls // include tls conditionally since it is not always available
|
|
12
9
|
|
|
@@ -106,7 +103,6 @@ function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, sess
|
|
|
106
103
|
servername,
|
|
107
104
|
session,
|
|
108
105
|
localAddress,
|
|
109
|
-
// TODO(HTTP/2): Add support for h2c
|
|
110
106
|
ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
|
|
111
107
|
socket: httpSocket, // upgrade socket connection
|
|
112
108
|
port,
|
|
@@ -138,7 +134,7 @@ function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, sess
|
|
|
138
134
|
socket.setKeepAlive(true, keepAliveInitialDelay)
|
|
139
135
|
}
|
|
140
136
|
|
|
141
|
-
const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port })
|
|
137
|
+
const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port })
|
|
142
138
|
|
|
143
139
|
socket
|
|
144
140
|
.setNoDelay(true)
|
|
@@ -165,76 +161,4 @@ function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, sess
|
|
|
165
161
|
}
|
|
166
162
|
}
|
|
167
163
|
|
|
168
|
-
/**
|
|
169
|
-
* @param {WeakRef<net.Socket>} socketWeakRef
|
|
170
|
-
* @param {object} opts
|
|
171
|
-
* @param {number} opts.timeout
|
|
172
|
-
* @param {string} opts.hostname
|
|
173
|
-
* @param {number} opts.port
|
|
174
|
-
* @returns {() => void}
|
|
175
|
-
*/
|
|
176
|
-
const setupConnectTimeout = process.platform === 'win32'
|
|
177
|
-
? (socketWeakRef, opts) => {
|
|
178
|
-
if (!opts.timeout) {
|
|
179
|
-
return noop
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
let s1 = null
|
|
183
|
-
let s2 = null
|
|
184
|
-
const fastTimer = timers.setFastTimeout(() => {
|
|
185
|
-
// setImmediate is added to make sure that we prioritize socket error events over timeouts
|
|
186
|
-
s1 = setImmediate(() => {
|
|
187
|
-
// Windows needs an extra setImmediate probably due to implementation differences in the socket logic
|
|
188
|
-
s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts))
|
|
189
|
-
})
|
|
190
|
-
}, opts.timeout)
|
|
191
|
-
return () => {
|
|
192
|
-
timers.clearFastTimeout(fastTimer)
|
|
193
|
-
clearImmediate(s1)
|
|
194
|
-
clearImmediate(s2)
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
: (socketWeakRef, opts) => {
|
|
198
|
-
if (!opts.timeout) {
|
|
199
|
-
return noop
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
let s1 = null
|
|
203
|
-
const fastTimer = timers.setFastTimeout(() => {
|
|
204
|
-
// setImmediate is added to make sure that we prioritize socket error events over timeouts
|
|
205
|
-
s1 = setImmediate(() => {
|
|
206
|
-
onConnectTimeout(socketWeakRef.deref(), opts)
|
|
207
|
-
})
|
|
208
|
-
}, opts.timeout)
|
|
209
|
-
return () => {
|
|
210
|
-
timers.clearFastTimeout(fastTimer)
|
|
211
|
-
clearImmediate(s1)
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* @param {net.Socket} socket
|
|
217
|
-
* @param {object} opts
|
|
218
|
-
* @param {number} opts.timeout
|
|
219
|
-
* @param {string} opts.hostname
|
|
220
|
-
* @param {number} opts.port
|
|
221
|
-
*/
|
|
222
|
-
function onConnectTimeout (socket, opts) {
|
|
223
|
-
// The socket could be already garbage collected
|
|
224
|
-
if (socket == null) {
|
|
225
|
-
return
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
let message = 'Connect Timeout Error'
|
|
229
|
-
if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
|
|
230
|
-
message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`
|
|
231
|
-
} else {
|
|
232
|
-
message += ` (attempted address: ${opts.hostname}:${opts.port},`
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
message += ` timeout: ${opts.timeout}ms)`
|
|
236
|
-
|
|
237
|
-
util.destroy(socket, new ConnectTimeoutError(message))
|
|
238
|
-
}
|
|
239
|
-
|
|
240
164
|
module.exports = buildConnector
|
package/lib/core/util.js
CHANGED
|
@@ -9,7 +9,8 @@ const { Blob } = require('node:buffer')
|
|
|
9
9
|
const nodeUtil = require('node:util')
|
|
10
10
|
const { stringify } = require('node:querystring')
|
|
11
11
|
const { EventEmitter: EE } = require('node:events')
|
|
12
|
-
const
|
|
12
|
+
const timers = require('../util/timers')
|
|
13
|
+
const { InvalidArgumentError, ConnectTimeoutError } = require('./errors')
|
|
13
14
|
const { headerNameLowerCasedRecord } = require('./constants')
|
|
14
15
|
const { tree } = require('./tree')
|
|
15
16
|
|
|
@@ -28,6 +29,8 @@ class BodyAsyncIterable {
|
|
|
28
29
|
}
|
|
29
30
|
}
|
|
30
31
|
|
|
32
|
+
function noop () {}
|
|
33
|
+
|
|
31
34
|
/**
|
|
32
35
|
* @param {*} body
|
|
33
36
|
* @returns {*}
|
|
@@ -837,6 +840,78 @@ function errorRequest (client, request, err) {
|
|
|
837
840
|
}
|
|
838
841
|
}
|
|
839
842
|
|
|
843
|
+
/**
|
|
844
|
+
* @param {WeakRef<net.Socket>} socketWeakRef
|
|
845
|
+
* @param {object} opts
|
|
846
|
+
* @param {number} opts.timeout
|
|
847
|
+
* @param {string} opts.hostname
|
|
848
|
+
* @param {number} opts.port
|
|
849
|
+
* @returns {() => void}
|
|
850
|
+
*/
|
|
851
|
+
const setupConnectTimeout = process.platform === 'win32'
|
|
852
|
+
? (socketWeakRef, opts) => {
|
|
853
|
+
if (!opts.timeout) {
|
|
854
|
+
return noop
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
let s1 = null
|
|
858
|
+
let s2 = null
|
|
859
|
+
const fastTimer = timers.setFastTimeout(() => {
|
|
860
|
+
// setImmediate is added to make sure that we prioritize socket error events over timeouts
|
|
861
|
+
s1 = setImmediate(() => {
|
|
862
|
+
// Windows needs an extra setImmediate probably due to implementation differences in the socket logic
|
|
863
|
+
s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts))
|
|
864
|
+
})
|
|
865
|
+
}, opts.timeout)
|
|
866
|
+
return () => {
|
|
867
|
+
timers.clearFastTimeout(fastTimer)
|
|
868
|
+
clearImmediate(s1)
|
|
869
|
+
clearImmediate(s2)
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
: (socketWeakRef, opts) => {
|
|
873
|
+
if (!opts.timeout) {
|
|
874
|
+
return noop
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
let s1 = null
|
|
878
|
+
const fastTimer = timers.setFastTimeout(() => {
|
|
879
|
+
// setImmediate is added to make sure that we prioritize socket error events over timeouts
|
|
880
|
+
s1 = setImmediate(() => {
|
|
881
|
+
onConnectTimeout(socketWeakRef.deref(), opts)
|
|
882
|
+
})
|
|
883
|
+
}, opts.timeout)
|
|
884
|
+
return () => {
|
|
885
|
+
timers.clearFastTimeout(fastTimer)
|
|
886
|
+
clearImmediate(s1)
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* @param {net.Socket} socket
|
|
892
|
+
* @param {object} opts
|
|
893
|
+
* @param {number} opts.timeout
|
|
894
|
+
* @param {string} opts.hostname
|
|
895
|
+
* @param {number} opts.port
|
|
896
|
+
*/
|
|
897
|
+
function onConnectTimeout (socket, opts) {
|
|
898
|
+
// The socket could be already garbage collected
|
|
899
|
+
if (socket == null) {
|
|
900
|
+
return
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
let message = 'Connect Timeout Error'
|
|
904
|
+
if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
|
|
905
|
+
message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`
|
|
906
|
+
} else {
|
|
907
|
+
message += ` (attempted address: ${opts.hostname}:${opts.port},`
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
message += ` timeout: ${opts.timeout}ms)`
|
|
911
|
+
|
|
912
|
+
destroy(socket, new ConnectTimeoutError(message))
|
|
913
|
+
}
|
|
914
|
+
|
|
840
915
|
const kEnumerableProperty = Object.create(null)
|
|
841
916
|
kEnumerableProperty.enumerable = true
|
|
842
917
|
|
|
@@ -908,5 +983,6 @@ module.exports = {
|
|
|
908
983
|
nodeMajor,
|
|
909
984
|
nodeMinor,
|
|
910
985
|
safeHTTPMethods: Object.freeze(['GET', 'HEAD', 'OPTIONS', 'TRACE']),
|
|
911
|
-
wrapRequestBody
|
|
986
|
+
wrapRequestBody,
|
|
987
|
+
setupConnectTimeout
|
|
912
988
|
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
const { connect } = require('node:net')
|
|
3
|
+
|
|
4
|
+
const { kClose, kDestroy } = require('../core/symbols')
|
|
5
|
+
const { InvalidArgumentError } = require('../core/errors')
|
|
6
|
+
const util = require('../core/util')
|
|
7
|
+
|
|
8
|
+
const Client = require('./client')
|
|
9
|
+
const DispatcherBase = require('./dispatcher-base')
|
|
10
|
+
|
|
11
|
+
class H2CClient extends DispatcherBase {
|
|
12
|
+
#client = null
|
|
13
|
+
|
|
14
|
+
constructor (origin, clientOpts) {
|
|
15
|
+
super()
|
|
16
|
+
|
|
17
|
+
if (typeof origin === 'string') {
|
|
18
|
+
origin = new URL(origin)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (origin.protocol !== 'http:') {
|
|
22
|
+
throw new InvalidArgumentError(
|
|
23
|
+
'h2c-client: Only h2c protocol is supported'
|
|
24
|
+
)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const { connect, maxConcurrentStreams, pipelining, ...opts } =
|
|
28
|
+
clientOpts ?? {}
|
|
29
|
+
let defaultMaxConcurrentStreams = 100
|
|
30
|
+
let defaultPipelining = 100
|
|
31
|
+
|
|
32
|
+
if (
|
|
33
|
+
maxConcurrentStreams != null &&
|
|
34
|
+
Number.isInteger(maxConcurrentStreams) &&
|
|
35
|
+
maxConcurrentStreams > 0
|
|
36
|
+
) {
|
|
37
|
+
defaultMaxConcurrentStreams = maxConcurrentStreams
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) {
|
|
41
|
+
defaultPipelining = pipelining
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (defaultPipelining > defaultMaxConcurrentStreams) {
|
|
45
|
+
throw new InvalidArgumentError(
|
|
46
|
+
'h2c-client: pipelining cannot be greater than maxConcurrentStreams'
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
this.#client = new Client(origin, {
|
|
51
|
+
...opts,
|
|
52
|
+
connect: this.#buildConnector(connect),
|
|
53
|
+
maxConcurrentStreams: defaultMaxConcurrentStreams,
|
|
54
|
+
pipelining: defaultPipelining,
|
|
55
|
+
allowH2: true
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
#buildConnector (connectOpts) {
|
|
60
|
+
return (opts, callback) => {
|
|
61
|
+
const timeout = connectOpts?.connectOpts ?? 10e3
|
|
62
|
+
const { hostname, port, pathname } = opts
|
|
63
|
+
const socket = connect({
|
|
64
|
+
...opts,
|
|
65
|
+
host: hostname,
|
|
66
|
+
port,
|
|
67
|
+
pathname
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
// Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
|
|
71
|
+
if (opts.keepAlive == null || opts.keepAlive) {
|
|
72
|
+
const keepAliveInitialDelay =
|
|
73
|
+
opts.keepAliveInitialDelay == null ? 60e3 : opts.keepAliveInitialDelay
|
|
74
|
+
socket.setKeepAlive(true, keepAliveInitialDelay)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
socket.alpnProtocol = 'h2'
|
|
78
|
+
|
|
79
|
+
const clearConnectTimeout = util.setupConnectTimeout(
|
|
80
|
+
new WeakRef(socket),
|
|
81
|
+
{ timeout, hostname, port }
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
socket
|
|
85
|
+
.setNoDelay(true)
|
|
86
|
+
.once('connect', function () {
|
|
87
|
+
queueMicrotask(clearConnectTimeout)
|
|
88
|
+
|
|
89
|
+
if (callback) {
|
|
90
|
+
const cb = callback
|
|
91
|
+
callback = null
|
|
92
|
+
cb(null, this)
|
|
93
|
+
}
|
|
94
|
+
})
|
|
95
|
+
.on('error', function (err) {
|
|
96
|
+
queueMicrotask(clearConnectTimeout)
|
|
97
|
+
|
|
98
|
+
if (callback) {
|
|
99
|
+
const cb = callback
|
|
100
|
+
callback = null
|
|
101
|
+
cb(err)
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
return socket
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
dispatch (opts, handler) {
|
|
110
|
+
return this.#client.dispatch(opts, handler)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async [kClose] () {
|
|
114
|
+
await this.#client.close()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async [kDestroy] () {
|
|
118
|
+
await this.#client.destroy()
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = H2CClient
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "undici",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.7.0",
|
|
4
4
|
"description": "An HTTP/1.1 client, written from scratch for Node.js",
|
|
5
5
|
"homepage": "https://undici.nodejs.org",
|
|
6
6
|
"bugs": {
|
|
@@ -80,7 +80,7 @@
|
|
|
80
80
|
"test:fuzzing": "node test/fuzzing/fuzzing.test.js",
|
|
81
81
|
"test:fetch": "npm run build:node && borp --timeout 180000 --expose-gc --concurrency 1 -p \"test/fetch/*.js\" && npm run test:webidl && npm run test:busboy",
|
|
82
82
|
"test:h2": "npm run test:h2:core && npm run test:h2:fetch",
|
|
83
|
-
"test:h2:core": "borp -p \"test
|
|
83
|
+
"test:h2:core": "borp -p \"test/+(http2|h2)*.js\"",
|
|
84
84
|
"test:h2:fetch": "npm run build:node && borp -p \"test/fetch/http2*.js\"",
|
|
85
85
|
"test:interceptors": "borp -p \"test/interceptors/*.js\"",
|
|
86
86
|
"test:jest": "cross-env NODE_V8_COVERAGE= jest",
|
package/types/dispatcher.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ type AbortSignal = unknown
|
|
|
12
12
|
|
|
13
13
|
export default Dispatcher
|
|
14
14
|
|
|
15
|
+
export type UndiciHeaders = Record<string, string | string[]> | IncomingHttpHeaders | string[] | Iterable<[string, string | string[] | undefined]> | null
|
|
16
|
+
|
|
15
17
|
/** Dispatcher is the core API used to dispatch requests. */
|
|
16
18
|
declare class Dispatcher extends EventEmitter {
|
|
17
19
|
/** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */
|
|
@@ -103,7 +105,7 @@ declare namespace Dispatcher {
|
|
|
103
105
|
/** Default: `null` */
|
|
104
106
|
body?: string | Buffer | Uint8Array | Readable | null | FormData;
|
|
105
107
|
/** Default: `null` */
|
|
106
|
-
headers?:
|
|
108
|
+
headers?: UndiciHeaders;
|
|
107
109
|
/** Query string params to be embedded in the request URL. Default: `null` */
|
|
108
110
|
query?: Record<string, any>;
|
|
109
111
|
/** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */
|
|
@@ -127,7 +129,7 @@ declare namespace Dispatcher {
|
|
|
127
129
|
origin: string | URL;
|
|
128
130
|
path: string;
|
|
129
131
|
/** Default: `null` */
|
|
130
|
-
headers?:
|
|
132
|
+
headers?: UndiciHeaders;
|
|
131
133
|
/** Default: `null` */
|
|
132
134
|
signal?: AbortSignal | EventEmitter | null;
|
|
133
135
|
/** This argument parameter is passed through to `ConnectData` */
|
|
@@ -164,7 +166,7 @@ declare namespace Dispatcher {
|
|
|
164
166
|
/** Default: `'GET'` */
|
|
165
167
|
method?: string;
|
|
166
168
|
/** Default: `null` */
|
|
167
|
-
headers?:
|
|
169
|
+
headers?: UndiciHeaders;
|
|
168
170
|
/** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */
|
|
169
171
|
protocol?: string;
|
|
170
172
|
/** Default: `null` */
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { URL } from 'url'
|
|
2
|
+
import Dispatcher from './dispatcher'
|
|
3
|
+
import buildConnector from './connector'
|
|
4
|
+
|
|
5
|
+
type H2ClientOptions = Omit<Dispatcher.ConnectOptions, 'origin'>
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A basic H2C client, mapped on top a single TCP connection. Pipelining is disabled by default.
|
|
9
|
+
*/
|
|
10
|
+
export class H2CClient extends Dispatcher {
|
|
11
|
+
constructor (url: string | URL, options?: H2CClient.Options)
|
|
12
|
+
/** Property to get and set the pipelining factor. */
|
|
13
|
+
pipelining: number
|
|
14
|
+
/** `true` after `client.close()` has been called. */
|
|
15
|
+
closed: boolean
|
|
16
|
+
/** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */
|
|
17
|
+
destroyed: boolean
|
|
18
|
+
|
|
19
|
+
// Override dispatcher APIs.
|
|
20
|
+
override connect (
|
|
21
|
+
options: H2ClientOptions
|
|
22
|
+
): Promise<Dispatcher.ConnectData>
|
|
23
|
+
override connect (
|
|
24
|
+
options: H2ClientOptions,
|
|
25
|
+
callback: (err: Error | null, data: Dispatcher.ConnectData) => void
|
|
26
|
+
): void
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export declare namespace H2CClient {
|
|
30
|
+
export interface Options {
|
|
31
|
+
/** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
|
|
32
|
+
maxHeaderSize?: number;
|
|
33
|
+
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
|
|
34
|
+
headersTimeout?: number;
|
|
35
|
+
/** TODO */
|
|
36
|
+
connectTimeout?: number;
|
|
37
|
+
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
|
|
38
|
+
bodyTimeout?: number;
|
|
39
|
+
/** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */
|
|
40
|
+
keepAliveTimeout?: number;
|
|
41
|
+
/** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */
|
|
42
|
+
keepAliveMaxTimeout?: number;
|
|
43
|
+
/** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */
|
|
44
|
+
keepAliveTimeoutThreshold?: number;
|
|
45
|
+
/** TODO */
|
|
46
|
+
socketPath?: string;
|
|
47
|
+
/** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */
|
|
48
|
+
pipelining?: number;
|
|
49
|
+
/** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */
|
|
50
|
+
strictContentLength?: boolean;
|
|
51
|
+
/** TODO */
|
|
52
|
+
maxCachedSessions?: number;
|
|
53
|
+
/** TODO */
|
|
54
|
+
maxRedirections?: number;
|
|
55
|
+
/** TODO */
|
|
56
|
+
connect?: Omit<Partial<buildConnector.BuildOptions>, 'allowH2'> | buildConnector.connector;
|
|
57
|
+
/** TODO */
|
|
58
|
+
maxRequestsPerClient?: number;
|
|
59
|
+
/** TODO */
|
|
60
|
+
localAddress?: string;
|
|
61
|
+
/** Max response body size in bytes, -1 is disabled */
|
|
62
|
+
maxResponseSize?: number;
|
|
63
|
+
/** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */
|
|
64
|
+
autoSelectFamily?: boolean;
|
|
65
|
+
/** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */
|
|
66
|
+
autoSelectFamilyAttemptTimeout?: number;
|
|
67
|
+
/**
|
|
68
|
+
* @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
|
|
69
|
+
* @default 100
|
|
70
|
+
*/
|
|
71
|
+
maxConcurrentStreams?: number
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export default H2CClient
|
package/types/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { RedirectHandler, DecoratorHandler } from './handlers'
|
|
|
6
6
|
|
|
7
7
|
import BalancedPool from './balanced-pool'
|
|
8
8
|
import Client from './client'
|
|
9
|
+
import H2CClient from './h2c-client'
|
|
9
10
|
import buildConnector from './connector'
|
|
10
11
|
import errors from './errors'
|
|
11
12
|
import Agent from './agent'
|
|
@@ -32,7 +33,7 @@ export * from './content-type'
|
|
|
32
33
|
export * from './cache'
|
|
33
34
|
export { Interceptable } from './mock-interceptor'
|
|
34
35
|
|
|
35
|
-
export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, MockClient, MockPool, MockAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent }
|
|
36
|
+
export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, MockClient, MockPool, MockAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient }
|
|
36
37
|
export default Undici
|
|
37
38
|
|
|
38
39
|
declare namespace Undici {
|
|
@@ -43,6 +44,7 @@ declare namespace Undici {
|
|
|
43
44
|
const RetryHandler: typeof import ('./retry-handler').default
|
|
44
45
|
const BalancedPool: typeof import('./balanced-pool').default
|
|
45
46
|
const Client: typeof import('./client').default
|
|
47
|
+
const H2CClient: typeof import('./h2c-client').default
|
|
46
48
|
const buildConnector: typeof import('./connector').default
|
|
47
49
|
const errors: typeof import('./errors').default
|
|
48
50
|
const Agent: typeof import('./agent').default
|