@depup/undici 7.24.3-depup.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.
Files changed (211) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -0
  3. package/changes.json +5 -0
  4. package/docs/docs/api/Agent.md +84 -0
  5. package/docs/docs/api/BalancedPool.md +99 -0
  6. package/docs/docs/api/CacheStorage.md +30 -0
  7. package/docs/docs/api/CacheStore.md +164 -0
  8. package/docs/docs/api/Client.md +285 -0
  9. package/docs/docs/api/ClientStats.md +27 -0
  10. package/docs/docs/api/Connector.md +115 -0
  11. package/docs/docs/api/ContentType.md +57 -0
  12. package/docs/docs/api/Cookies.md +101 -0
  13. package/docs/docs/api/Debug.md +62 -0
  14. package/docs/docs/api/DiagnosticsChannel.md +313 -0
  15. package/docs/docs/api/Dispatcher.md +1392 -0
  16. package/docs/docs/api/EnvHttpProxyAgent.md +159 -0
  17. package/docs/docs/api/Errors.md +49 -0
  18. package/docs/docs/api/EventSource.md +45 -0
  19. package/docs/docs/api/Fetch.md +52 -0
  20. package/docs/docs/api/GlobalInstallation.md +91 -0
  21. package/docs/docs/api/H2CClient.md +263 -0
  22. package/docs/docs/api/MockAgent.md +603 -0
  23. package/docs/docs/api/MockCallHistory.md +197 -0
  24. package/docs/docs/api/MockCallHistoryLog.md +43 -0
  25. package/docs/docs/api/MockClient.md +81 -0
  26. package/docs/docs/api/MockErrors.md +12 -0
  27. package/docs/docs/api/MockPool.md +555 -0
  28. package/docs/docs/api/Pool.md +84 -0
  29. package/docs/docs/api/PoolStats.md +35 -0
  30. package/docs/docs/api/ProxyAgent.md +229 -0
  31. package/docs/docs/api/RedirectHandler.md +96 -0
  32. package/docs/docs/api/RetryAgent.md +50 -0
  33. package/docs/docs/api/RetryHandler.md +118 -0
  34. package/docs/docs/api/RoundRobinPool.md +145 -0
  35. package/docs/docs/api/SnapshotAgent.md +616 -0
  36. package/docs/docs/api/Socks5ProxyAgent.md +274 -0
  37. package/docs/docs/api/Util.md +25 -0
  38. package/docs/docs/api/WebSocket.md +141 -0
  39. package/docs/docs/api/api-lifecycle.md +91 -0
  40. package/docs/docs/best-practices/client-certificate.md +64 -0
  41. package/docs/docs/best-practices/crawling.md +58 -0
  42. package/docs/docs/best-practices/mocking-request.md +190 -0
  43. package/docs/docs/best-practices/proxy.md +127 -0
  44. package/docs/docs/best-practices/undici-vs-builtin-fetch.md +137 -0
  45. package/docs/docs/best-practices/writing-tests.md +20 -0
  46. package/index-fetch.js +65 -0
  47. package/index.d.ts +3 -0
  48. package/index.js +234 -0
  49. package/lib/api/abort-signal.js +59 -0
  50. package/lib/api/api-connect.js +110 -0
  51. package/lib/api/api-pipeline.js +252 -0
  52. package/lib/api/api-request.js +214 -0
  53. package/lib/api/api-stream.js +209 -0
  54. package/lib/api/api-upgrade.js +111 -0
  55. package/lib/api/index.js +7 -0
  56. package/lib/api/readable.js +580 -0
  57. package/lib/cache/memory-cache-store.js +234 -0
  58. package/lib/cache/sqlite-cache-store.js +461 -0
  59. package/lib/core/connect.js +137 -0
  60. package/lib/core/constants.js +143 -0
  61. package/lib/core/diagnostics.js +225 -0
  62. package/lib/core/errors.js +477 -0
  63. package/lib/core/request.js +430 -0
  64. package/lib/core/socks5-client.js +407 -0
  65. package/lib/core/socks5-utils.js +203 -0
  66. package/lib/core/symbols.js +75 -0
  67. package/lib/core/tree.js +160 -0
  68. package/lib/core/util.js +972 -0
  69. package/lib/dispatcher/agent.js +158 -0
  70. package/lib/dispatcher/balanced-pool.js +219 -0
  71. package/lib/dispatcher/client-h1.js +1610 -0
  72. package/lib/dispatcher/client-h2.js +995 -0
  73. package/lib/dispatcher/client.js +654 -0
  74. package/lib/dispatcher/dispatcher-base.js +165 -0
  75. package/lib/dispatcher/dispatcher.js +48 -0
  76. package/lib/dispatcher/env-http-proxy-agent.js +146 -0
  77. package/lib/dispatcher/fixed-queue.js +135 -0
  78. package/lib/dispatcher/h2c-client.js +51 -0
  79. package/lib/dispatcher/pool-base.js +214 -0
  80. package/lib/dispatcher/pool.js +118 -0
  81. package/lib/dispatcher/proxy-agent.js +318 -0
  82. package/lib/dispatcher/retry-agent.js +35 -0
  83. package/lib/dispatcher/round-robin-pool.js +137 -0
  84. package/lib/dispatcher/socks5-proxy-agent.js +249 -0
  85. package/lib/encoding/index.js +33 -0
  86. package/lib/global.js +50 -0
  87. package/lib/handler/cache-handler.js +561 -0
  88. package/lib/handler/cache-revalidation-handler.js +124 -0
  89. package/lib/handler/decorator-handler.js +67 -0
  90. package/lib/handler/deduplication-handler.js +460 -0
  91. package/lib/handler/redirect-handler.js +238 -0
  92. package/lib/handler/retry-handler.js +394 -0
  93. package/lib/handler/unwrap-handler.js +100 -0
  94. package/lib/handler/wrap-handler.js +105 -0
  95. package/lib/interceptor/cache.js +495 -0
  96. package/lib/interceptor/decompress.js +259 -0
  97. package/lib/interceptor/deduplicate.js +117 -0
  98. package/lib/interceptor/dns.js +571 -0
  99. package/lib/interceptor/dump.js +112 -0
  100. package/lib/interceptor/redirect.js +21 -0
  101. package/lib/interceptor/response-error.js +95 -0
  102. package/lib/interceptor/retry.js +19 -0
  103. package/lib/llhttp/.gitkeep +0 -0
  104. package/lib/llhttp/constants.d.ts +195 -0
  105. package/lib/llhttp/constants.js +531 -0
  106. package/lib/llhttp/llhttp-wasm.js +15 -0
  107. package/lib/llhttp/llhttp_simd-wasm.js +15 -0
  108. package/lib/llhttp/utils.d.ts +2 -0
  109. package/lib/llhttp/utils.js +12 -0
  110. package/lib/mock/mock-agent.js +232 -0
  111. package/lib/mock/mock-call-history.js +248 -0
  112. package/lib/mock/mock-client.js +68 -0
  113. package/lib/mock/mock-errors.js +29 -0
  114. package/lib/mock/mock-interceptor.js +209 -0
  115. package/lib/mock/mock-pool.js +68 -0
  116. package/lib/mock/mock-symbols.js +31 -0
  117. package/lib/mock/mock-utils.js +480 -0
  118. package/lib/mock/pending-interceptors-formatter.js +43 -0
  119. package/lib/mock/snapshot-agent.js +353 -0
  120. package/lib/mock/snapshot-recorder.js +588 -0
  121. package/lib/mock/snapshot-utils.js +158 -0
  122. package/lib/util/cache.js +407 -0
  123. package/lib/util/date.js +653 -0
  124. package/lib/util/promise.js +28 -0
  125. package/lib/util/runtime-features.js +124 -0
  126. package/lib/util/stats.js +32 -0
  127. package/lib/util/timers.js +425 -0
  128. package/lib/web/cache/cache.js +864 -0
  129. package/lib/web/cache/cachestorage.js +152 -0
  130. package/lib/web/cache/util.js +45 -0
  131. package/lib/web/cookies/constants.js +12 -0
  132. package/lib/web/cookies/index.js +199 -0
  133. package/lib/web/cookies/parse.js +322 -0
  134. package/lib/web/cookies/util.js +282 -0
  135. package/lib/web/eventsource/eventsource-stream.js +399 -0
  136. package/lib/web/eventsource/eventsource.js +501 -0
  137. package/lib/web/eventsource/util.js +29 -0
  138. package/lib/web/fetch/LICENSE +21 -0
  139. package/lib/web/fetch/body.js +509 -0
  140. package/lib/web/fetch/constants.js +131 -0
  141. package/lib/web/fetch/data-url.js +596 -0
  142. package/lib/web/fetch/formdata-parser.js +575 -0
  143. package/lib/web/fetch/formdata.js +259 -0
  144. package/lib/web/fetch/global.js +40 -0
  145. package/lib/web/fetch/headers.js +719 -0
  146. package/lib/web/fetch/index.js +2378 -0
  147. package/lib/web/fetch/request.js +1115 -0
  148. package/lib/web/fetch/response.js +641 -0
  149. package/lib/web/fetch/util.js +1520 -0
  150. package/lib/web/infra/index.js +229 -0
  151. package/lib/web/subresource-integrity/Readme.md +9 -0
  152. package/lib/web/subresource-integrity/subresource-integrity.js +307 -0
  153. package/lib/web/webidl/index.js +1006 -0
  154. package/lib/web/websocket/connection.js +329 -0
  155. package/lib/web/websocket/constants.js +126 -0
  156. package/lib/web/websocket/events.js +331 -0
  157. package/lib/web/websocket/frame.js +133 -0
  158. package/lib/web/websocket/permessage-deflate.js +118 -0
  159. package/lib/web/websocket/receiver.js +450 -0
  160. package/lib/web/websocket/sender.js +109 -0
  161. package/lib/web/websocket/stream/websocketerror.js +104 -0
  162. package/lib/web/websocket/stream/websocketstream.js +497 -0
  163. package/lib/web/websocket/util.js +347 -0
  164. package/lib/web/websocket/websocket.js +739 -0
  165. package/package.json +163 -0
  166. package/scripts/strip-comments.js +10 -0
  167. package/types/README.md +6 -0
  168. package/types/agent.d.ts +32 -0
  169. package/types/api.d.ts +43 -0
  170. package/types/balanced-pool.d.ts +30 -0
  171. package/types/cache-interceptor.d.ts +179 -0
  172. package/types/cache.d.ts +36 -0
  173. package/types/client-stats.d.ts +15 -0
  174. package/types/client.d.ts +123 -0
  175. package/types/connector.d.ts +36 -0
  176. package/types/content-type.d.ts +21 -0
  177. package/types/cookies.d.ts +30 -0
  178. package/types/diagnostics-channel.d.ts +74 -0
  179. package/types/dispatcher.d.ts +279 -0
  180. package/types/env-http-proxy-agent.d.ts +22 -0
  181. package/types/errors.d.ts +177 -0
  182. package/types/eventsource.d.ts +66 -0
  183. package/types/fetch.d.ts +211 -0
  184. package/types/formdata.d.ts +108 -0
  185. package/types/global-dispatcher.d.ts +9 -0
  186. package/types/global-origin.d.ts +7 -0
  187. package/types/h2c-client.d.ts +73 -0
  188. package/types/handlers.d.ts +15 -0
  189. package/types/header.d.ts +160 -0
  190. package/types/index.d.ts +91 -0
  191. package/types/interceptors.d.ts +80 -0
  192. package/types/mock-agent.d.ts +68 -0
  193. package/types/mock-call-history.d.ts +111 -0
  194. package/types/mock-client.d.ts +27 -0
  195. package/types/mock-errors.d.ts +12 -0
  196. package/types/mock-interceptor.d.ts +94 -0
  197. package/types/mock-pool.d.ts +27 -0
  198. package/types/patch.d.ts +29 -0
  199. package/types/pool-stats.d.ts +19 -0
  200. package/types/pool.d.ts +41 -0
  201. package/types/proxy-agent.d.ts +29 -0
  202. package/types/readable.d.ts +68 -0
  203. package/types/retry-agent.d.ts +8 -0
  204. package/types/retry-handler.d.ts +125 -0
  205. package/types/round-robin-pool.d.ts +41 -0
  206. package/types/snapshot-agent.d.ts +109 -0
  207. package/types/socks5-proxy-agent.d.ts +25 -0
  208. package/types/util.d.ts +18 -0
  209. package/types/utility.d.ts +7 -0
  210. package/types/webidl.d.ts +347 -0
  211. package/types/websocket.d.ts +188 -0
@@ -0,0 +1,654 @@
1
+ 'use strict'
2
+
3
+ const assert = require('node:assert')
4
+ const net = require('node:net')
5
+ const http = require('node:http')
6
+ const util = require('../core/util.js')
7
+ const { ClientStats } = require('../util/stats.js')
8
+ const { channels } = require('../core/diagnostics.js')
9
+ const Request = require('../core/request.js')
10
+ const DispatcherBase = require('./dispatcher-base')
11
+ const {
12
+ InvalidArgumentError,
13
+ InformationalError,
14
+ ClientDestroyedError
15
+ } = require('../core/errors.js')
16
+ const buildConnector = require('../core/connect.js')
17
+ const {
18
+ kUrl,
19
+ kServerName,
20
+ kClient,
21
+ kBusy,
22
+ kConnect,
23
+ kResuming,
24
+ kRunning,
25
+ kPending,
26
+ kSize,
27
+ kQueue,
28
+ kConnected,
29
+ kConnecting,
30
+ kNeedDrain,
31
+ kKeepAliveDefaultTimeout,
32
+ kHostHeader,
33
+ kPendingIdx,
34
+ kRunningIdx,
35
+ kError,
36
+ kPipelining,
37
+ kKeepAliveTimeoutValue,
38
+ kMaxHeadersSize,
39
+ kKeepAliveMaxTimeout,
40
+ kKeepAliveTimeoutThreshold,
41
+ kHeadersTimeout,
42
+ kBodyTimeout,
43
+ kStrictContentLength,
44
+ kConnector,
45
+ kMaxRequests,
46
+ kCounter,
47
+ kClose,
48
+ kDestroy,
49
+ kDispatch,
50
+ kLocalAddress,
51
+ kMaxResponseSize,
52
+ kOnError,
53
+ kHTTPContext,
54
+ kMaxConcurrentStreams,
55
+ kHTTP2InitialWindowSize,
56
+ kHTTP2ConnectionWindowSize,
57
+ kResume,
58
+ kPingInterval
59
+ } = require('../core/symbols.js')
60
+ const connectH1 = require('./client-h1.js')
61
+ const connectH2 = require('./client-h2.js')
62
+
63
+ const kClosedResolve = Symbol('kClosedResolve')
64
+
65
+ const getDefaultNodeMaxHeaderSize = http &&
66
+ http.maxHeaderSize &&
67
+ Number.isInteger(http.maxHeaderSize) &&
68
+ http.maxHeaderSize > 0
69
+ ? () => http.maxHeaderSize
70
+ : () => { throw new InvalidArgumentError('http module not available or http.maxHeaderSize invalid') }
71
+
72
+ const noop = () => { }
73
+
74
+ function getPipelining (client) {
75
+ return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1
76
+ }
77
+
78
+ /**
79
+ * @type {import('../../types/client.js').default}
80
+ */
81
+ class Client extends DispatcherBase {
82
+ /**
83
+ *
84
+ * @param {string|URL} url
85
+ * @param {import('../../types/client.js').Client.Options} options
86
+ */
87
+ constructor (url, {
88
+ maxHeaderSize,
89
+ headersTimeout,
90
+ socketTimeout,
91
+ requestTimeout,
92
+ connectTimeout,
93
+ bodyTimeout,
94
+ idleTimeout,
95
+ keepAlive,
96
+ keepAliveTimeout,
97
+ maxKeepAliveTimeout,
98
+ keepAliveMaxTimeout,
99
+ keepAliveTimeoutThreshold,
100
+ socketPath,
101
+ pipelining,
102
+ tls,
103
+ strictContentLength,
104
+ maxCachedSessions,
105
+ connect,
106
+ maxRequestsPerClient,
107
+ localAddress,
108
+ maxResponseSize,
109
+ autoSelectFamily,
110
+ autoSelectFamilyAttemptTimeout,
111
+ // h2
112
+ maxConcurrentStreams,
113
+ allowH2,
114
+ useH2c,
115
+ initialWindowSize,
116
+ connectionWindowSize,
117
+ pingInterval
118
+ } = {}) {
119
+ if (keepAlive !== undefined) {
120
+ throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
121
+ }
122
+
123
+ if (socketTimeout !== undefined) {
124
+ throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
125
+ }
126
+
127
+ if (requestTimeout !== undefined) {
128
+ throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
129
+ }
130
+
131
+ if (idleTimeout !== undefined) {
132
+ throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
133
+ }
134
+
135
+ if (maxKeepAliveTimeout !== undefined) {
136
+ throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
137
+ }
138
+
139
+ if (maxHeaderSize != null) {
140
+ if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) {
141
+ throw new InvalidArgumentError('invalid maxHeaderSize')
142
+ }
143
+ } else {
144
+ // If maxHeaderSize is not provided, use the default value from the http module
145
+ // or if that is not available, throw an error.
146
+ maxHeaderSize = getDefaultNodeMaxHeaderSize()
147
+ }
148
+
149
+ if (socketPath != null && typeof socketPath !== 'string') {
150
+ throw new InvalidArgumentError('invalid socketPath')
151
+ }
152
+
153
+ if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
154
+ throw new InvalidArgumentError('invalid connectTimeout')
155
+ }
156
+
157
+ if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
158
+ throw new InvalidArgumentError('invalid keepAliveTimeout')
159
+ }
160
+
161
+ if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
162
+ throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
163
+ }
164
+
165
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
166
+ throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
167
+ }
168
+
169
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
170
+ throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
171
+ }
172
+
173
+ if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
174
+ throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
175
+ }
176
+
177
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
178
+ throw new InvalidArgumentError('connect must be a function or an object')
179
+ }
180
+
181
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
182
+ throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
183
+ }
184
+
185
+ if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
186
+ throw new InvalidArgumentError('localAddress must be valid string IP address')
187
+ }
188
+
189
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
190
+ throw new InvalidArgumentError('maxResponseSize must be a positive number')
191
+ }
192
+
193
+ if (
194
+ autoSelectFamilyAttemptTimeout != null &&
195
+ (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
196
+ ) {
197
+ throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
198
+ }
199
+
200
+ // h2
201
+ if (allowH2 != null && typeof allowH2 !== 'boolean') {
202
+ throw new InvalidArgumentError('allowH2 must be a valid boolean value')
203
+ }
204
+
205
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
206
+ throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')
207
+ }
208
+
209
+ if (useH2c != null && typeof useH2c !== 'boolean') {
210
+ throw new InvalidArgumentError('useH2c must be a valid boolean value')
211
+ }
212
+
213
+ if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) {
214
+ throw new InvalidArgumentError('initialWindowSize must be a positive integer, greater than 0')
215
+ }
216
+
217
+ if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) {
218
+ throw new InvalidArgumentError('connectionWindowSize must be a positive integer, greater than 0')
219
+ }
220
+
221
+ if (pingInterval != null && (typeof pingInterval !== 'number' || !Number.isInteger(pingInterval) || pingInterval < 0)) {
222
+ throw new InvalidArgumentError('pingInterval must be a positive integer, greater or equal to 0')
223
+ }
224
+
225
+ super()
226
+
227
+ if (typeof connect !== 'function') {
228
+ connect = buildConnector({
229
+ ...tls,
230
+ maxCachedSessions,
231
+ allowH2,
232
+ useH2c,
233
+ socketPath,
234
+ timeout: connectTimeout,
235
+ ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
236
+ ...connect
237
+ })
238
+ } else if (socketPath != null) {
239
+ const customConnect = connect
240
+ connect = (opts, callback) => customConnect({ ...opts, socketPath }, callback)
241
+ }
242
+
243
+ this[kUrl] = util.parseOrigin(url)
244
+ this[kConnector] = connect
245
+ this[kPipelining] = pipelining != null ? pipelining : 1
246
+ this[kMaxHeadersSize] = maxHeaderSize
247
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
248
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
249
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold
250
+ this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
251
+ this[kServerName] = null
252
+ this[kLocalAddress] = localAddress != null ? localAddress : null
253
+ this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
254
+ this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
255
+ this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
256
+ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
257
+ this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
258
+ this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
259
+ this[kMaxRequests] = maxRequestsPerClient
260
+ this[kClosedResolve] = null
261
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
262
+ this[kHTTPContext] = null
263
+ // h2
264
+ this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
265
+ // HTTP/2 window sizes are set to higher defaults than Node.js core for better performance:
266
+ // - initialWindowSize: 262144 (256KB) vs Node.js default 65535 (64KB - 1)
267
+ // Allows more data to be sent before requiring acknowledgment, improving throughput
268
+ // especially on high-latency networks. This matches common production HTTP/2 servers.
269
+ // - connectionWindowSize: 524288 (512KB) vs Node.js default (none set)
270
+ // Provides better flow control for the entire connection across multiple streams.
271
+ this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144
272
+ this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288
273
+ this[kPingInterval] = pingInterval != null ? pingInterval : 60e3 // Default ping interval for h2 - 1 minute
274
+
275
+ // kQueue is built up of 3 sections separated by
276
+ // the kRunningIdx and kPendingIdx indices.
277
+ // | complete | running | pending |
278
+ // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
279
+ // kRunningIdx points to the first running element.
280
+ // kPendingIdx points to the first pending element.
281
+ // This implements a fast queue with an amortized
282
+ // time of O(1).
283
+
284
+ this[kQueue] = []
285
+ this[kRunningIdx] = 0
286
+ this[kPendingIdx] = 0
287
+
288
+ this[kResume] = (sync) => resume(this, sync)
289
+ this[kOnError] = (err) => onError(this, err)
290
+ }
291
+
292
+ get pipelining () {
293
+ return this[kPipelining]
294
+ }
295
+
296
+ set pipelining (value) {
297
+ this[kPipelining] = value
298
+ this[kResume](true)
299
+ }
300
+
301
+ get stats () {
302
+ return new ClientStats(this)
303
+ }
304
+
305
+ get [kPending] () {
306
+ return this[kQueue].length - this[kPendingIdx]
307
+ }
308
+
309
+ get [kRunning] () {
310
+ return this[kPendingIdx] - this[kRunningIdx]
311
+ }
312
+
313
+ get [kSize] () {
314
+ return this[kQueue].length - this[kRunningIdx]
315
+ }
316
+
317
+ get [kConnected] () {
318
+ return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed
319
+ }
320
+
321
+ get [kBusy] () {
322
+ return Boolean(
323
+ this[kHTTPContext]?.busy(null) ||
324
+ (this[kSize] >= (getPipelining(this) || 1)) ||
325
+ this[kPending] > 0
326
+ )
327
+ }
328
+
329
+ [kConnect] (cb) {
330
+ connect(this)
331
+ this.once('connect', cb)
332
+ }
333
+
334
+ [kDispatch] (opts, handler) {
335
+ const request = new Request(this[kUrl].origin, opts, handler)
336
+
337
+ this[kQueue].push(request)
338
+ if (this[kResuming]) {
339
+ // Do nothing.
340
+ } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
341
+ // Wait a tick in case stream/iterator is ended in the same tick.
342
+ this[kResuming] = 1
343
+ queueMicrotask(() => resume(this))
344
+ } else {
345
+ this[kResume](true)
346
+ }
347
+
348
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
349
+ this[kNeedDrain] = 2
350
+ }
351
+
352
+ return this[kNeedDrain] < 2
353
+ }
354
+
355
+ [kClose] () {
356
+ // TODO: for H2 we need to gracefully flush the remaining enqueued
357
+ // request and close each stream.
358
+ return new Promise((resolve) => {
359
+ if (this[kSize]) {
360
+ this[kClosedResolve] = resolve
361
+ } else {
362
+ resolve(null)
363
+ }
364
+ })
365
+ }
366
+
367
+ [kDestroy] (err) {
368
+ return new Promise((resolve) => {
369
+ const requests = this[kQueue].splice(this[kPendingIdx])
370
+ for (let i = 0; i < requests.length; i++) {
371
+ const request = requests[i]
372
+ util.errorRequest(this, request, err)
373
+ }
374
+
375
+ const callback = () => {
376
+ if (this[kClosedResolve]) {
377
+ // TODO (fix): Should we error here with ClientDestroyedError?
378
+ this[kClosedResolve]()
379
+ this[kClosedResolve] = null
380
+ }
381
+ resolve(null)
382
+ }
383
+
384
+ if (this[kHTTPContext]) {
385
+ this[kHTTPContext].destroy(err, callback)
386
+ this[kHTTPContext] = null
387
+ } else {
388
+ queueMicrotask(callback)
389
+ }
390
+
391
+ this[kResume]()
392
+ })
393
+ }
394
+ }
395
+
396
+ function onError (client, err) {
397
+ if (
398
+ client[kRunning] === 0 &&
399
+ err.code !== 'UND_ERR_INFO' &&
400
+ err.code !== 'UND_ERR_SOCKET'
401
+ ) {
402
+ // Error is not caused by running request and not a recoverable
403
+ // socket error.
404
+
405
+ assert(client[kPendingIdx] === client[kRunningIdx])
406
+
407
+ const requests = client[kQueue].splice(client[kRunningIdx])
408
+
409
+ for (let i = 0; i < requests.length; i++) {
410
+ const request = requests[i]
411
+ util.errorRequest(client, request, err)
412
+ }
413
+ assert(client[kSize] === 0)
414
+ }
415
+ }
416
+
417
+ /**
418
+ * @param {Client} client
419
+ * @returns {void}
420
+ */
421
+ function connect (client) {
422
+ assert(!client[kConnecting])
423
+ assert(!client[kHTTPContext])
424
+
425
+ let { host, hostname, protocol, port } = client[kUrl]
426
+
427
+ // Resolve ipv6
428
+ if (hostname[0] === '[') {
429
+ const idx = hostname.indexOf(']')
430
+
431
+ assert(idx !== -1)
432
+ const ip = hostname.substring(1, idx)
433
+
434
+ assert(net.isIPv6(ip))
435
+ hostname = ip
436
+ }
437
+
438
+ client[kConnecting] = true
439
+
440
+ if (channels.beforeConnect.hasSubscribers) {
441
+ channels.beforeConnect.publish({
442
+ connectParams: {
443
+ host,
444
+ hostname,
445
+ protocol,
446
+ port,
447
+ version: client[kHTTPContext]?.version,
448
+ servername: client[kServerName],
449
+ localAddress: client[kLocalAddress]
450
+ },
451
+ connector: client[kConnector]
452
+ })
453
+ }
454
+
455
+ client[kConnector]({
456
+ host,
457
+ hostname,
458
+ protocol,
459
+ port,
460
+ servername: client[kServerName],
461
+ localAddress: client[kLocalAddress]
462
+ }, (err, socket) => {
463
+ if (err) {
464
+ handleConnectError(client, err, { host, hostname, protocol, port })
465
+ client[kResume]()
466
+ return
467
+ }
468
+
469
+ if (client.destroyed) {
470
+ util.destroy(socket.on('error', noop), new ClientDestroyedError())
471
+ client[kResume]()
472
+ return
473
+ }
474
+
475
+ assert(socket)
476
+
477
+ try {
478
+ client[kHTTPContext] = socket.alpnProtocol === 'h2'
479
+ ? connectH2(client, socket)
480
+ : connectH1(client, socket)
481
+ } catch (err) {
482
+ socket.destroy().on('error', noop)
483
+ handleConnectError(client, err, { host, hostname, protocol, port })
484
+ client[kResume]()
485
+ return
486
+ }
487
+
488
+ client[kConnecting] = false
489
+
490
+ socket[kCounter] = 0
491
+ socket[kMaxRequests] = client[kMaxRequests]
492
+ socket[kClient] = client
493
+ socket[kError] = null
494
+
495
+ if (channels.connected.hasSubscribers) {
496
+ channels.connected.publish({
497
+ connectParams: {
498
+ host,
499
+ hostname,
500
+ protocol,
501
+ port,
502
+ version: client[kHTTPContext]?.version,
503
+ servername: client[kServerName],
504
+ localAddress: client[kLocalAddress]
505
+ },
506
+ connector: client[kConnector],
507
+ socket
508
+ })
509
+ }
510
+
511
+ client.emit('connect', client[kUrl], [client])
512
+ client[kResume]()
513
+ })
514
+ }
515
+
516
+ function handleConnectError (client, err, { host, hostname, protocol, port }) {
517
+ if (client.destroyed) {
518
+ return
519
+ }
520
+
521
+ client[kConnecting] = false
522
+
523
+ if (channels.connectError.hasSubscribers) {
524
+ channels.connectError.publish({
525
+ connectParams: {
526
+ host,
527
+ hostname,
528
+ protocol,
529
+ port,
530
+ version: client[kHTTPContext]?.version,
531
+ servername: client[kServerName],
532
+ localAddress: client[kLocalAddress]
533
+ },
534
+ connector: client[kConnector],
535
+ error: err
536
+ })
537
+ }
538
+
539
+ if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
540
+ assert(client[kRunning] === 0)
541
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
542
+ const request = client[kQueue][client[kPendingIdx]++]
543
+ util.errorRequest(client, request, err)
544
+ }
545
+ } else {
546
+ onError(client, err)
547
+ }
548
+
549
+ client.emit('connectionError', client[kUrl], [client], err)
550
+ }
551
+
552
+ function emitDrain (client) {
553
+ client[kNeedDrain] = 0
554
+ client.emit('drain', client[kUrl], [client])
555
+ }
556
+
557
+ function resume (client, sync) {
558
+ if (client[kResuming] === 2) {
559
+ return
560
+ }
561
+
562
+ client[kResuming] = 2
563
+
564
+ _resume(client, sync)
565
+ client[kResuming] = 0
566
+
567
+ if (client[kRunningIdx] > 256) {
568
+ client[kQueue].splice(0, client[kRunningIdx])
569
+ client[kPendingIdx] -= client[kRunningIdx]
570
+ client[kRunningIdx] = 0
571
+ }
572
+ }
573
+
574
+ function _resume (client, sync) {
575
+ while (true) {
576
+ if (client.destroyed) {
577
+ assert(client[kPending] === 0)
578
+ return
579
+ }
580
+
581
+ if (client[kClosedResolve] && !client[kSize]) {
582
+ client[kClosedResolve]()
583
+ client[kClosedResolve] = null
584
+ return
585
+ }
586
+
587
+ if (client[kHTTPContext]) {
588
+ client[kHTTPContext].resume()
589
+ }
590
+
591
+ if (client[kBusy]) {
592
+ client[kNeedDrain] = 2
593
+ } else if (client[kNeedDrain] === 2) {
594
+ if (sync) {
595
+ client[kNeedDrain] = 1
596
+ queueMicrotask(() => emitDrain(client))
597
+ } else {
598
+ emitDrain(client)
599
+ }
600
+ continue
601
+ }
602
+
603
+ if (client[kPending] === 0) {
604
+ return
605
+ }
606
+
607
+ if (client[kRunning] >= (getPipelining(client) || 1)) {
608
+ return
609
+ }
610
+
611
+ const request = client[kQueue][client[kPendingIdx]]
612
+
613
+ if (request === null) {
614
+ return
615
+ }
616
+
617
+ if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
618
+ if (client[kRunning] > 0) {
619
+ return
620
+ }
621
+
622
+ client[kServerName] = request.servername
623
+ client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => {
624
+ client[kHTTPContext] = null
625
+ resume(client)
626
+ })
627
+ }
628
+
629
+ if (client[kConnecting]) {
630
+ return
631
+ }
632
+
633
+ if (!client[kHTTPContext]) {
634
+ connect(client)
635
+ return
636
+ }
637
+
638
+ if (client[kHTTPContext].destroyed) {
639
+ return
640
+ }
641
+
642
+ if (client[kHTTPContext].busy(request)) {
643
+ return
644
+ }
645
+
646
+ if (!request.aborted && client[kHTTPContext].write(request)) {
647
+ client[kPendingIdx]++
648
+ } else {
649
+ client[kQueue].splice(client[kPendingIdx], 1)
650
+ }
651
+ }
652
+ }
653
+
654
+ module.exports = Client