undici 8.7.0 → 8.9.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/README.md +5 -0
- package/docs/docs/api/Client.md +4 -0
- package/docs/docs/api/Dispatcher.md +6 -0
- package/docs/docs/api/Interceptors.md +59 -0
- package/docs/docs/api/MockAgent.md +27 -0
- package/docs/docs/api/MockPool.md +28 -1
- package/docs/docs/index.md +5 -0
- package/lib/cache/memory-cache-store.js +54 -9
- package/lib/cache/sqlite-cache-store.js +7 -1
- package/lib/core/request.js +13 -2
- package/lib/core/util.js +6 -1
- package/lib/dispatcher/agent.js +3 -3
- package/lib/dispatcher/client-h1.js +42 -8
- package/lib/dispatcher/client-h2.js +34 -43
- package/lib/global.js +36 -16
- package/lib/handler/cache-handler.js +269 -61
- package/lib/handler/cache-revalidation-handler.js +13 -3
- package/lib/handler/redirect-handler.js +5 -2
- package/lib/handler/retry-handler.js +30 -4
- package/lib/interceptor/cache.js +159 -52
- package/lib/interceptor/decompress.js +9 -2
- package/lib/mock/mock-interceptor.js +25 -7
- package/lib/mock/mock-utils.js +39 -10
- package/lib/util/cache.js +372 -68
- package/lib/util/date.js +23 -6
- package/lib/web/cookies/util.js +78 -8
- package/lib/web/fetch/body.js +2 -1
- package/lib/web/fetch/response.js +1 -3
- package/package.json +2 -2
- package/types/client.d.ts +2 -2
- package/types/dispatcher.d.ts +3 -3
- package/types/mock-interceptor.d.ts +5 -1
package/README.md
CHANGED
|
@@ -408,6 +408,11 @@ For more information about their behavior, please reference the body mixin from
|
|
|
408
408
|
|
|
409
409
|
This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site.
|
|
410
410
|
|
|
411
|
+
For the top-level APIs below, the `url` argument supplies the request origin and
|
|
412
|
+
path. Do not pass `origin` or `path` in the second `options` argument. The linked
|
|
413
|
+
`Dispatcher` option types include those fields because dispatcher methods are
|
|
414
|
+
lower-level APIs that do not receive a separate `url` argument.
|
|
415
|
+
|
|
411
416
|
### `undici.request([url, options]): Promise`
|
|
412
417
|
|
|
413
418
|
Arguments:
|
package/docs/docs/api/Client.md
CHANGED
|
@@ -49,6 +49,10 @@ added: v1.0.0
|
|
|
49
49
|
* `headersTimeout` {number|null} The timeout, in milliseconds, the parser
|
|
50
50
|
waits to receive the complete HTTP headers before the request times out. Use
|
|
51
51
|
`0` to disable it entirely. **Default:** `300e3`.
|
|
52
|
+
HTTP/1.1 headers/body parser timeouts are not guaranteed to fire with exact
|
|
53
|
+
millisecond precision: delays up to 1000ms use native timers, while larger
|
|
54
|
+
delays use undici's lower-overhead fast timers with a target resolution
|
|
55
|
+
around 500ms.
|
|
52
56
|
* `connectTimeout` {number|null} The timeout, in milliseconds, for
|
|
53
57
|
establishing a socket connection. Use `0` to disable it entirely.
|
|
54
58
|
**Default:** `10e3`.
|
|
@@ -228,6 +228,10 @@ added: v4.0.0
|
|
|
228
228
|
* `bodyTimeout` {number|null} The time, in milliseconds, after which the request
|
|
229
229
|
times out while receiving body data. Monitors the time between body chunks.
|
|
230
230
|
Use `0` to disable it entirely. Defaults to 300 seconds.
|
|
231
|
+
HTTP/1.1 headers/body parser timeouts are not guaranteed to fire with exact
|
|
232
|
+
millisecond precision: delays up to 1000ms use native timers, while larger
|
|
233
|
+
delays use undici's lower-overhead fast timers with a target resolution
|
|
234
|
+
around 500ms.
|
|
231
235
|
* `reset` {boolean} Whether the request should establish a keep-alive
|
|
232
236
|
connection. **Default:** `false`.
|
|
233
237
|
* `expectContinue` {boolean} For HTTP/2, appends the `expect: 100-continue`
|
|
@@ -729,6 +733,8 @@ await client.request({ path: '/', method: 'GET' })
|
|
|
729
733
|
```
|
|
730
734
|
|
|
731
735
|
For the full list of built-in interceptors provided by undici, see [Interceptors](Interceptors.md).
|
|
736
|
+
For an example of a custom interceptor that wraps handler callbacks, see
|
|
737
|
+
[Custom interceptors](Interceptors.md#custom-interceptors).
|
|
732
738
|
|
|
733
739
|
### Event: `'connect'`
|
|
734
740
|
|
|
@@ -32,6 +32,65 @@ const client = new Client('https://example.com').compose(
|
|
|
32
32
|
|
|
33
33
|
---
|
|
34
34
|
|
|
35
|
+
## Custom interceptors
|
|
36
|
+
|
|
37
|
+
Custom interceptors use the same shape as
|
|
38
|
+
[`dispatcher.compose()`](./Dispatcher.md#dispatchercomposeinterceptors-interceptor):
|
|
39
|
+
an interceptor takes a `dispatch` function and returns another dispatch-like
|
|
40
|
+
function with the same `(options, handler)` signature.
|
|
41
|
+
|
|
42
|
+
When an interceptor wraps the handler, forward the callbacks that it does not
|
|
43
|
+
handle itself. The complete handler callback list is documented under
|
|
44
|
+
[`dispatcher.dispatch(options, handler)`](./Dispatcher.md#dispatcherdispatchoptions-handler).
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import { Agent } from 'undici'
|
|
48
|
+
|
|
49
|
+
const timingInterceptor = dispatch => {
|
|
50
|
+
return (options, handler) => {
|
|
51
|
+
const started = performance.now()
|
|
52
|
+
|
|
53
|
+
return dispatch(options, {
|
|
54
|
+
...handler,
|
|
55
|
+
onResponseStart (controller, statusCode, headers, statusMessage) {
|
|
56
|
+
const duration = Math.round(performance.now() - started)
|
|
57
|
+
const method = options.method ?? 'GET'
|
|
58
|
+
const origin = options.origin ?? ''
|
|
59
|
+
|
|
60
|
+
console.log(`${method} ${origin}${options.path} -> ${statusCode} in ${duration}ms`)
|
|
61
|
+
|
|
62
|
+
return handler.onResponseStart?.(
|
|
63
|
+
controller,
|
|
64
|
+
statusCode,
|
|
65
|
+
headers,
|
|
66
|
+
statusMessage
|
|
67
|
+
)
|
|
68
|
+
},
|
|
69
|
+
onResponseError (controller, error) {
|
|
70
|
+
const duration = Math.round(performance.now() - started)
|
|
71
|
+
|
|
72
|
+
console.error(`request failed after ${duration}ms`, error)
|
|
73
|
+
|
|
74
|
+
return handler.onResponseError?.(controller, error)
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const dispatcher = new Agent().compose(timingInterceptor)
|
|
81
|
+
|
|
82
|
+
const { body } = await dispatcher.request({
|
|
83
|
+
origin: 'https://example.com',
|
|
84
|
+
path: '/',
|
|
85
|
+
method: 'GET'
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
await body.dump()
|
|
89
|
+
await dispatcher.close()
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
35
94
|
## `interceptors.dump([opts])`
|
|
36
95
|
|
|
37
96
|
Reads and discards the response body up to a configurable size limit. Useful
|
|
@@ -17,6 +17,13 @@ registered on the {MockClient} or {MockPool} instances returned by
|
|
|
17
17
|
`MockAgent` is set as the dispatcher (for example through
|
|
18
18
|
[`setGlobalDispatcher()`][] or a per-request `dispatcher` option).
|
|
19
19
|
|
|
20
|
+
> [!NOTE]
|
|
21
|
+
> [`setGlobalDispatcher()`][] only affects undici APIs that use the global
|
|
22
|
+
> dispatcher, such as `request()` and `fetch()`. It does not replace or
|
|
23
|
+
> monkeypatch {Pool} or {Client} instances that were created separately. To test
|
|
24
|
+
> code that accepts or creates a pool/client directly, pass the {MockPool} or
|
|
25
|
+
> {MockClient} returned by [`mockAgent.get(origin)`][] into that code.
|
|
26
|
+
|
|
20
27
|
```mjs
|
|
21
28
|
import { MockAgent } from 'undici'
|
|
22
29
|
|
|
@@ -139,6 +146,26 @@ for await (const data of body) {
|
|
|
139
146
|
}
|
|
140
147
|
```
|
|
141
148
|
|
|
149
|
+
```mjs displayName="Testing code that accepts a pool"
|
|
150
|
+
import { MockAgent } from 'undici'
|
|
151
|
+
|
|
152
|
+
async function getStatus (pool) {
|
|
153
|
+
const { statusCode } = await pool.request({
|
|
154
|
+
path: '/foo',
|
|
155
|
+
method: 'GET'
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
return statusCode
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const mockAgent = new MockAgent()
|
|
162
|
+
const mockPool = mockAgent.get('http://localhost:3000')
|
|
163
|
+
|
|
164
|
+
mockPool.intercept({ path: '/foo', method: 'GET' }).reply(200)
|
|
165
|
+
|
|
166
|
+
console.log(await getStatus(mockPool)) // 200
|
|
167
|
+
```
|
|
168
|
+
|
|
142
169
|
```mjs displayName="Returning a MockClient"
|
|
143
170
|
import { MockAgent, request } from 'undici'
|
|
144
171
|
|
|
@@ -136,7 +136,8 @@ The reply behaviour of a matching request is defined through the returned
|
|
|
136
136
|
computing all reply options dynamically rather than just the body.
|
|
137
137
|
* `callback` {Function} A `(opts: MockResponseCallbackOptions) =>
|
|
138
138
|
{ statusCode, data, responseOptions }` function invoked with the incoming
|
|
139
|
-
request.
|
|
139
|
+
request. The callback may be asynchronous; a returned promise is awaited
|
|
140
|
+
and must resolve to the same shape.
|
|
140
141
|
* Returns: {MockScope}
|
|
141
142
|
* `replyWithError(error)` {Function} Defines an error for a matching request to
|
|
142
143
|
throw.
|
|
@@ -263,6 +264,32 @@ for await (const data of body) {
|
|
|
263
264
|
}
|
|
264
265
|
```
|
|
265
266
|
|
|
267
|
+
```mjs displayName="Reply with an asynchronous options callback"
|
|
268
|
+
import { readFile } from 'node:fs/promises'
|
|
269
|
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
|
270
|
+
|
|
271
|
+
const mockAgent = new MockAgent()
|
|
272
|
+
setGlobalDispatcher(mockAgent)
|
|
273
|
+
|
|
274
|
+
const mockPool = mockAgent.get('http://localhost:3000')
|
|
275
|
+
|
|
276
|
+
mockPool.intercept({
|
|
277
|
+
path: '/fixture',
|
|
278
|
+
method: 'GET'
|
|
279
|
+
}).reply(async ({ path }) => ({
|
|
280
|
+
statusCode: 200,
|
|
281
|
+
data: await readFile(new URL('./fixture.json', import.meta.url))
|
|
282
|
+
}))
|
|
283
|
+
|
|
284
|
+
const { statusCode, body } = await request('http://localhost:3000/fixture')
|
|
285
|
+
|
|
286
|
+
console.log('response received', statusCode) // response received 200
|
|
287
|
+
|
|
288
|
+
for await (const data of body) {
|
|
289
|
+
console.log('data', data.toString('utf8')) // contents of fixture.json
|
|
290
|
+
}
|
|
291
|
+
```
|
|
292
|
+
|
|
266
293
|
```mjs displayName="Multiple intercepts"
|
|
267
294
|
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
|
268
295
|
|
package/docs/docs/index.md
CHANGED
|
@@ -410,6 +410,11 @@ For more information about their behavior, please reference the body mixin from
|
|
|
410
410
|
|
|
411
411
|
This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site.
|
|
412
412
|
|
|
413
|
+
For the top-level APIs below, the `url` argument supplies the request origin and
|
|
414
|
+
path. Do not pass `origin` or `path` in the second `options` argument. The linked
|
|
415
|
+
`Dispatcher` option types include those fields because dispatcher methods are
|
|
416
|
+
lower-level APIs that do not receive a separate `url` argument.
|
|
417
|
+
|
|
413
418
|
### `undici.request([url, options])`
|
|
414
419
|
|
|
415
420
|
* `url` {string|URL|UrlObject}
|
|
@@ -218,17 +218,62 @@ class MemoryCacheStore extends EventEmitter {
|
|
|
218
218
|
}
|
|
219
219
|
|
|
220
220
|
function findEntry (key, entries, now) {
|
|
221
|
-
|
|
222
|
-
entry
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
221
|
+
for (let i = 0; i < entries.length; i++) {
|
|
222
|
+
const entry = entries[i]
|
|
223
|
+
if (
|
|
224
|
+
entry.deleteAt > now &&
|
|
225
|
+
entry.method === key.method &&
|
|
226
|
+
varyMatches(key, entry)
|
|
227
|
+
) {
|
|
228
|
+
return entry
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function varyMatches (key, entry) {
|
|
234
|
+
if (entry.vary == null) {
|
|
235
|
+
return true
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
for (const headerName in entry.vary) {
|
|
239
|
+
if (Object.hasOwn(entry.vary, headerName) && !headerValueEquals(key.headers?.[headerName], entry.vary[headerName])) {
|
|
240
|
+
return false
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return true
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* @param {string|string[]|null|undefined} lhs
|
|
249
|
+
* @param {string|string[]|null|undefined} rhs
|
|
250
|
+
* @returns {boolean}
|
|
251
|
+
*/
|
|
252
|
+
function headerValueEquals (lhs, rhs) {
|
|
253
|
+
if (lhs == null && rhs == null) {
|
|
254
|
+
return true
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
if ((lhs == null && rhs != null) ||
|
|
258
|
+
(lhs != null && rhs == null)) {
|
|
259
|
+
return false
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (Array.isArray(lhs) && Array.isArray(rhs)) {
|
|
263
|
+
if (lhs.length !== rhs.length) {
|
|
264
|
+
return false
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
for (let i = 0; i < lhs.length; i++) {
|
|
268
|
+
if (lhs[i] !== rhs[i]) {
|
|
269
|
+
return false
|
|
227
270
|
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return true
|
|
274
|
+
}
|
|
228
275
|
|
|
229
|
-
|
|
230
|
-
}))
|
|
231
|
-
))
|
|
276
|
+
return lhs === rhs
|
|
232
277
|
}
|
|
233
278
|
|
|
234
279
|
module.exports = MemoryCacheStore
|
|
@@ -456,7 +456,13 @@ function headerValueEquals (lhs, rhs) {
|
|
|
456
456
|
return false
|
|
457
457
|
}
|
|
458
458
|
|
|
459
|
-
|
|
459
|
+
for (let i = 0; i < lhs.length; i++) {
|
|
460
|
+
if (lhs[i] !== rhs[i]) {
|
|
461
|
+
return false
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
return true
|
|
460
466
|
}
|
|
461
467
|
|
|
462
468
|
return lhs === rhs
|
package/lib/core/request.js
CHANGED
|
@@ -173,7 +173,7 @@ class Request {
|
|
|
173
173
|
|
|
174
174
|
this.method = method
|
|
175
175
|
|
|
176
|
-
this.typeOfService = typeOfService
|
|
176
|
+
this.typeOfService = typeOfService
|
|
177
177
|
|
|
178
178
|
this.abort = null
|
|
179
179
|
|
|
@@ -472,7 +472,13 @@ function processHeader (request, key, val) {
|
|
|
472
472
|
} else if (typeof val[i] === 'object') {
|
|
473
473
|
throw new InvalidArgumentError(`invalid ${key} header`)
|
|
474
474
|
} else {
|
|
475
|
-
|
|
475
|
+
// Coerce primitives (and reject unsafe coercions such as functions
|
|
476
|
+
// with a crafted toString/Symbol.toPrimitive).
|
|
477
|
+
const str = `${val[i]}`
|
|
478
|
+
if (!isValidHeaderValue(str)) {
|
|
479
|
+
throw new InvalidArgumentError(`invalid ${key} header`)
|
|
480
|
+
}
|
|
481
|
+
arr.push(str)
|
|
476
482
|
}
|
|
477
483
|
}
|
|
478
484
|
val = arr
|
|
@@ -483,7 +489,12 @@ function processHeader (request, key, val) {
|
|
|
483
489
|
} else if (val === null) {
|
|
484
490
|
val = ''
|
|
485
491
|
} else {
|
|
492
|
+
// Coerce primitives (and reject unsafe coercions such as functions
|
|
493
|
+
// with a crafted toString/Symbol.toPrimitive).
|
|
486
494
|
val = `${val}`
|
|
495
|
+
if (!isValidHeaderValue(val)) {
|
|
496
|
+
throw new InvalidArgumentError(`invalid ${key} header`)
|
|
497
|
+
}
|
|
487
498
|
}
|
|
488
499
|
|
|
489
500
|
if (headerName === 'host') {
|
package/lib/core/util.js
CHANGED
|
@@ -370,7 +370,12 @@ function destroy (stream, err) {
|
|
|
370
370
|
stream.socket = null
|
|
371
371
|
}
|
|
372
372
|
|
|
373
|
-
|
|
373
|
+
try {
|
|
374
|
+
stream.destroy(err)
|
|
375
|
+
} catch {
|
|
376
|
+
// stream.destroy may throw on managed sockets (e.g., http2).
|
|
377
|
+
// Silently ignore — the socket lifecycle is handled by the subsystem.
|
|
378
|
+
}
|
|
374
379
|
} else if (err) {
|
|
375
380
|
queueMicrotask(() => {
|
|
376
381
|
stream.emit('error', err)
|
package/lib/dispatcher/agent.js
CHANGED
|
@@ -107,15 +107,15 @@ class Agent extends DispatcherBase {
|
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
let hasOrigin = false
|
|
110
|
-
for (const
|
|
111
|
-
if (
|
|
110
|
+
for (const k of this[kClients].keys()) {
|
|
111
|
+
if (k === origin || k === `${origin}#http1-only`) {
|
|
112
112
|
hasOrigin = true
|
|
113
113
|
break
|
|
114
114
|
}
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
if (!hasOrigin) {
|
|
118
|
-
this[kOrigins].delete(
|
|
118
|
+
this[kOrigins].delete(origin)
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
121
|
|
|
@@ -10,6 +10,7 @@ const {
|
|
|
10
10
|
RequestContentLengthMismatchError,
|
|
11
11
|
ResponseContentLengthMismatchError,
|
|
12
12
|
RequestAbortedError,
|
|
13
|
+
InvalidArgumentError,
|
|
13
14
|
HeadersTimeoutError,
|
|
14
15
|
HeadersOverflowError,
|
|
15
16
|
SocketError,
|
|
@@ -60,6 +61,7 @@ const removeAllListeners = util.removeAllListeners
|
|
|
60
61
|
const kIdleSocketValidation = Symbol('kIdleSocketValidation')
|
|
61
62
|
const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
|
|
62
63
|
const kSocketUsed = Symbol('kSocketUsed')
|
|
64
|
+
const kTypeOfService = Symbol('kTypeOfService')
|
|
63
65
|
|
|
64
66
|
let extractBody
|
|
65
67
|
|
|
@@ -1050,7 +1052,7 @@ function onSocketClose () {
|
|
|
1050
1052
|
|
|
1051
1053
|
function clearIdleSocketValidation (socket) {
|
|
1052
1054
|
if (socket[kIdleSocketValidationTimeout]) {
|
|
1053
|
-
|
|
1055
|
+
clearImmediate(socket[kIdleSocketValidationTimeout])
|
|
1054
1056
|
socket[kIdleSocketValidationTimeout] = null
|
|
1055
1057
|
}
|
|
1056
1058
|
|
|
@@ -1059,14 +1061,14 @@ function clearIdleSocketValidation (socket) {
|
|
|
1059
1061
|
|
|
1060
1062
|
function scheduleIdleSocketValidation (client, socket) {
|
|
1061
1063
|
socket[kIdleSocketValidation] = 1
|
|
1062
|
-
socket[kIdleSocketValidationTimeout] =
|
|
1064
|
+
socket[kIdleSocketValidationTimeout] = setImmediate(() => {
|
|
1063
1065
|
socket[kIdleSocketValidationTimeout] = null
|
|
1064
1066
|
socket[kIdleSocketValidation] = 2
|
|
1065
1067
|
|
|
1066
1068
|
if (client[kSocket] === socket && !socket.destroyed) {
|
|
1067
1069
|
client[kResume]()
|
|
1068
1070
|
}
|
|
1069
|
-
}
|
|
1071
|
+
})
|
|
1070
1072
|
socket[kIdleSocketValidationTimeout].unref?.()
|
|
1071
1073
|
}
|
|
1072
1074
|
|
|
@@ -1134,6 +1136,32 @@ function shouldSendContentLength (method) {
|
|
|
1134
1136
|
return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
|
|
1135
1137
|
}
|
|
1136
1138
|
|
|
1139
|
+
function setTypeOfService (socket, request) {
|
|
1140
|
+
if (typeof socket.setTypeOfService !== 'function') {
|
|
1141
|
+
return
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
const typeOfService = request.typeOfService
|
|
1145
|
+
|
|
1146
|
+
if (typeOfService === undefined) {
|
|
1147
|
+
return
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
const currentTypeOfService = socket[kTypeOfService]
|
|
1151
|
+
|
|
1152
|
+
if (currentTypeOfService === typeOfService) {
|
|
1153
|
+
return
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
try {
|
|
1157
|
+
socket.setTypeOfService(typeOfService)
|
|
1158
|
+
socket[kTypeOfService] = typeOfService
|
|
1159
|
+
} catch {
|
|
1160
|
+
// QoS marking is best-effort. setTypeOfService() can throw synchronously on
|
|
1161
|
+
// some platforms depending on socket state, but that must not abort the request.
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1137
1165
|
/**
|
|
1138
1166
|
* @param {import('./client.js')} client
|
|
1139
1167
|
* @param {import('../core/request.js')} request
|
|
@@ -1173,8 +1201,16 @@ function writeH1 (client, request) {
|
|
|
1173
1201
|
}
|
|
1174
1202
|
body = bodyStream.stream
|
|
1175
1203
|
contentLength = bodyStream.length
|
|
1176
|
-
} else if (util.isBlobLike(body) && request.contentType == null
|
|
1177
|
-
|
|
1204
|
+
} else if (util.isBlobLike(body) && request.contentType == null) {
|
|
1205
|
+
const contentType = body.type
|
|
1206
|
+
if (contentType) {
|
|
1207
|
+
const contentTypeValue = `${contentType}`
|
|
1208
|
+
if (!util.isValidHeaderValue(contentTypeValue)) {
|
|
1209
|
+
util.errorRequest(client, request, new InvalidArgumentError('invalid content-type header'))
|
|
1210
|
+
return false
|
|
1211
|
+
}
|
|
1212
|
+
headers.push('content-type', contentTypeValue)
|
|
1213
|
+
}
|
|
1178
1214
|
}
|
|
1179
1215
|
|
|
1180
1216
|
if (body && typeof body.read === 'function') {
|
|
@@ -1265,9 +1301,7 @@ function writeH1 (client, request) {
|
|
|
1265
1301
|
socket[kBlocking] = true
|
|
1266
1302
|
}
|
|
1267
1303
|
|
|
1268
|
-
|
|
1269
|
-
socket.setTypeOfService(request.typeOfService)
|
|
1270
|
-
}
|
|
1304
|
+
setTypeOfService(socket, request)
|
|
1271
1305
|
|
|
1272
1306
|
let header = `${method} ${path} HTTP/1.1\r\n`
|
|
1273
1307
|
|
|
@@ -157,9 +157,10 @@ function completeRequest (client, request, resetPendingIdx = false) {
|
|
|
157
157
|
const queue = client[kQueue]
|
|
158
158
|
const runningIdx = client[kRunningIdx]
|
|
159
159
|
|
|
160
|
-
// In-order completion:
|
|
161
|
-
// The client's resume loop compacts
|
|
160
|
+
// In-order completion: clear the request and advance without splicing.
|
|
161
|
+
// The client's resume loop compacts cleared slots once the index grows.
|
|
162
162
|
if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request) {
|
|
163
|
+
queue[runningIdx] = null
|
|
163
164
|
client[kRunningIdx] = runningIdx + 1
|
|
164
165
|
return
|
|
165
166
|
}
|
|
@@ -246,7 +247,6 @@ function connectH2 (client, socket) {
|
|
|
246
247
|
|
|
247
248
|
util.addListener(session, 'error', onHttp2SessionError)
|
|
248
249
|
util.addListener(session, 'frameError', onHttp2FrameError)
|
|
249
|
-
util.addListener(session, 'end', onHttp2SessionEnd)
|
|
250
250
|
util.addListener(session, 'goaway', onHttp2SessionGoAway)
|
|
251
251
|
util.addListener(session, 'close', onHttp2SessionClose)
|
|
252
252
|
util.addListener(session, 'remoteSettings', onHttp2RemoteSettings)
|
|
@@ -322,16 +322,6 @@ function connectH2 (client, socket) {
|
|
|
322
322
|
// Don't dispatch an upgrade until all preceding requests have completed.
|
|
323
323
|
// Possibly, we do not have remote settings confirmed yet.
|
|
324
324
|
if ((request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false) return true
|
|
325
|
-
// Request with stream or iterator body can error while other requests
|
|
326
|
-
// are inflight and indirectly error those as well.
|
|
327
|
-
// Ensure this doesn't happen by waiting for inflight
|
|
328
|
-
// to complete before dispatching.
|
|
329
|
-
|
|
330
|
-
// Request with stream or iterator body cannot be retried.
|
|
331
|
-
// Ensure that no other requests are inflight and
|
|
332
|
-
// could cause failure.
|
|
333
|
-
if (util.bodyLength(request.body) !== 0 &&
|
|
334
|
-
(util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) return true
|
|
335
325
|
} else {
|
|
336
326
|
return (request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false
|
|
337
327
|
}
|
|
@@ -505,12 +495,6 @@ function onHttp2FrameError (type, code, id) {
|
|
|
505
495
|
}
|
|
506
496
|
}
|
|
507
497
|
|
|
508
|
-
function onHttp2SessionEnd () {
|
|
509
|
-
const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))
|
|
510
|
-
this.destroy(err)
|
|
511
|
-
util.destroy(this[kSocket], err)
|
|
512
|
-
}
|
|
513
|
-
|
|
514
498
|
/**
|
|
515
499
|
* This is the root cause of #3011
|
|
516
500
|
* We need to handle GOAWAY frames properly, and trigger the session close
|
|
@@ -654,7 +638,7 @@ function onHttp2SocketError (err) {
|
|
|
654
638
|
return
|
|
655
639
|
}
|
|
656
640
|
|
|
657
|
-
this[kClient][kOnError](err)
|
|
641
|
+
this[kHTTP2Session]?.[kClient]?.[kOnError](err)
|
|
658
642
|
}
|
|
659
643
|
|
|
660
644
|
function onHttp2SocketEnd () {
|
|
@@ -688,20 +672,24 @@ function onUpgradeStreamClose () {
|
|
|
688
672
|
closeStreamSession(this)
|
|
689
673
|
}
|
|
690
674
|
|
|
691
|
-
|
|
675
|
+
// Idempotent terminal cleanup, called from both 'end' and 'close': the
|
|
676
|
+
// null-state guard no-ops the later call.
|
|
677
|
+
function completeRequestStream () {
|
|
692
678
|
const state = this[kRequestStreamState]
|
|
693
679
|
|
|
694
|
-
if (state) {
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
680
|
+
if (state == null) {
|
|
681
|
+
return
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// Release the stream first so request references are cleared,
|
|
685
|
+
// then complete the response with trailers if available.
|
|
686
|
+
releaseRequestStream(this)
|
|
698
687
|
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
finalizeRequest(state)
|
|
702
|
-
}
|
|
688
|
+
if (state.pendingEnd && !state.request.aborted && !state.request.completed) {
|
|
689
|
+
state.request.onResponseEnd(state.trailers || {})
|
|
703
690
|
}
|
|
704
691
|
|
|
692
|
+
finalizeRequest(state)
|
|
705
693
|
closeStreamSession(this)
|
|
706
694
|
this[kRequestStreamState] = null
|
|
707
695
|
}
|
|
@@ -943,14 +931,14 @@ function writeH2 (client, request) {
|
|
|
943
931
|
// close() alone leaves cleanup waiting on the 'close' event; on a busy,
|
|
944
932
|
// long-lived multiplexed session that event can fail to fire, leaving the
|
|
945
933
|
// native Http2Stream (and the whole request graph it pins) alive for the
|
|
946
|
-
// session's life. Destroy the stream to release the handle
|
|
947
|
-
// deterministically
|
|
948
|
-
//
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
}
|
|
934
|
+
// session's life. Destroy the stream synchronously to release the handle
|
|
935
|
+
// deterministically. Deferring the destroy (e.g. via setImmediate) leaks
|
|
936
|
+
// the same way when the event loop is stalled and the callback never runs
|
|
937
|
+
// under abort churn (#5558); close() has already queued the RST_STREAM
|
|
938
|
+
// frame on the native session, so a synchronous destroy still sends it.
|
|
939
|
+
if (!stream.destroyed) {
|
|
940
|
+
util.destroy(stream)
|
|
941
|
+
}
|
|
954
942
|
|
|
955
943
|
// We move the running index to the next request
|
|
956
944
|
client[kOnError](err)
|
|
@@ -1137,7 +1125,7 @@ function writeH2 (client, request) {
|
|
|
1137
1125
|
}
|
|
1138
1126
|
|
|
1139
1127
|
stream[kHTTP2Session] = session
|
|
1140
|
-
stream.on('close',
|
|
1128
|
+
stream.on('close', completeRequestStream)
|
|
1141
1129
|
|
|
1142
1130
|
bindRequestToStream(request, stream, releaseRequestStream)
|
|
1143
1131
|
if (expectContinue) {
|
|
@@ -1280,13 +1268,16 @@ function onEnd () {
|
|
|
1280
1268
|
|
|
1281
1269
|
stream.off('end', onEnd)
|
|
1282
1270
|
|
|
1283
|
-
//
|
|
1284
|
-
//
|
|
1285
|
-
// onTrailers (which may fire after 'end' on Windows) can
|
|
1286
|
-
// store trailers first.
|
|
1271
|
+
// onTrailers (which may fire after 'end' on Windows) has already stored
|
|
1272
|
+
// trailers on the state by now, so completing here still delivers them.
|
|
1287
1273
|
if (state.responseReceived) {
|
|
1288
1274
|
if (!request.aborted && !request.completed) {
|
|
1289
1275
|
state.pendingEnd = true
|
|
1276
|
+
|
|
1277
|
+
// Complete on 'end': a blocked event loop can keep the stream's 'close'
|
|
1278
|
+
// from firing, stranding its buffers until OOM. Idempotent, so a later
|
|
1279
|
+
// 'close' no-ops.
|
|
1280
|
+
completeRequestStream.call(stream)
|
|
1290
1281
|
}
|
|
1291
1282
|
} else {
|
|
1292
1283
|
// Stream ended without receiving a response - this is an error
|
|
@@ -1357,7 +1348,7 @@ function onTrailers (trailers) {
|
|
|
1357
1348
|
return
|
|
1358
1349
|
}
|
|
1359
1350
|
|
|
1360
|
-
// Store trailers for
|
|
1351
|
+
// Store trailers for completeRequestStream to use when completing
|
|
1361
1352
|
state.trailers = trailers
|
|
1362
1353
|
}
|
|
1363
1354
|
|