Debian Codegraph @

lib/dispatcher/client.js

raw
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 kHostAuthority,
56 kHTTP2InitialWindowSize,
57 kHTTP2ConnectionWindowSize,
58 kResume,
59 kPingInterval
60 } = require('../core/symbols.js')
61 const connectH1 = require('./client-h1.js')
62 const connectH2 = require('./client-h2.js')
63
64 const kClosedResolve = Symbol('kClosedResolve')
65
66 const getDefaultNodeMaxHeaderSize = http &&
67 http.maxHeaderSize &&
68 Number.isInteger(http.maxHeaderSize) &&
69 http.maxHeaderSize > 0
70 ? () => http.maxHeaderSize
71 : () => { throw new InvalidArgumentError('http module not available or http.maxHeaderSize invalid') }
72
73 const noop = () => { }
74
75 function getPipelining (client) {
76 return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1
77 }
78
79 // Protocol-aware dispatch ceiling. h1 RFC7230 pipelining is unrelated to h2
80 // stream multiplexing — over h2 the ceiling is the (server-confirmed)
81 // maxConcurrentStreams. Before a context is attached we use the h1
82 // pipelining factor; once h2 attaches the queued requests can drain in
83 // one batch up to maxConcurrentStreams.
84 function getMaxConcurrent (client) {
85 if (client[kHTTPContext]?.version === 'h2') {
86 return client[kMaxConcurrentStreams]
87 }
88 return getPipelining(client)
89 }
90
91 /**
92 * @type {import('../../types/client.js').default}
93 */
94 class Client extends DispatcherBase {
95 /**
96 *
97 * @param {string|URL} url
98 * @param {import('../../types/client.js').Client.Options} options
99 */
100 constructor (url, {
101 maxHeaderSize,
102 headersTimeout,
103 socketTimeout,
104 requestTimeout,
105 connectTimeout,
106 bodyTimeout,
107 idleTimeout,
108 keepAlive,
109 keepAliveTimeout,
110 maxKeepAliveTimeout,
111 keepAliveMaxTimeout,
112 keepAliveTimeoutThreshold,
113 socketPath,
114 pipelining,
115 tls,
116 strictContentLength,
117 maxCachedSessions,
118 connect,
119 maxRequestsPerClient,
120 localAddress,
121 maxResponseSize,
122 autoSelectFamily,
123 autoSelectFamilyAttemptTimeout,
124 // h2
125 maxConcurrentStreams,
126 allowH2,
127 useH2c,
128 initialWindowSize,
129 connectionWindowSize,
130 pingInterval,
131 webSocket
132 } = {}) {
133 if (keepAlive !== undefined) {
134 throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
135 }
136
137 if (socketTimeout !== undefined) {
138 throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
139 }
140
141 if (requestTimeout !== undefined) {
142 throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
143 }
144
145 if (idleTimeout !== undefined) {
146 throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
147 }
148
149 if (maxKeepAliveTimeout !== undefined) {
150 throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
151 }
152
153 if (maxHeaderSize != null) {
154 if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) {
155 throw new InvalidArgumentError('invalid maxHeaderSize')
156 }
157 } else {
158 // If maxHeaderSize is not provided, use the default value from the http module
159 // or if that is not available, throw an error.
160 maxHeaderSize = getDefaultNodeMaxHeaderSize()
161 }
162
163 if (socketPath != null && typeof socketPath !== 'string') {
164 throw new InvalidArgumentError('invalid socketPath')
165 }
166
167 if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
168 throw new InvalidArgumentError('invalid connectTimeout')
169 }
170
171 if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
172 throw new InvalidArgumentError('invalid keepAliveTimeout')
173 }
174
175 if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
176 throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
177 }
178
179 if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
180 throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
181 }
182
183 if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
184 throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
185 }
186
187 if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
188 throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
189 }
190
191 if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
192 throw new InvalidArgumentError('connect must be a function or an object')
193 }
194
195 if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
196 throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
197 }
198
199 if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
200 throw new InvalidArgumentError('localAddress must be valid string IP address')
201 }
202
203 if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
204 throw new InvalidArgumentError('maxResponseSize must be a positive number')
205 }
206
207 if (
208 autoSelectFamilyAttemptTimeout != null &&
209 (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
210 ) {
211 throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
212 }
213
214 // h2
215 if (allowH2 != null && typeof allowH2 !== 'boolean') {
216 throw new InvalidArgumentError('allowH2 must be a valid boolean value')
217 }
218
219 if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
220 throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')
221 }
222
223 if (useH2c != null && typeof useH2c !== 'boolean') {
224 throw new InvalidArgumentError('useH2c must be a valid boolean value')
225 }
226
227 if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) {
228 throw new InvalidArgumentError('initialWindowSize must be a positive integer, greater than 0')
229 }
230
231 if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) {
232 throw new InvalidArgumentError('connectionWindowSize must be a positive integer, greater than 0')
233 }
234
235 if (pingInterval != null && (typeof pingInterval !== 'number' || !Number.isInteger(pingInterval) || pingInterval < 0)) {
236 throw new InvalidArgumentError('pingInterval must be a positive integer, greater or equal to 0')
237 }
238
239 super({ webSocket })
240
241 if (typeof connect !== 'function') {
242 connect = buildConnector({
243 ...tls,
244 maxCachedSessions,
245 allowH2,
246 useH2c,
247 socketPath,
248 timeout: connectTimeout,
249 ...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
250 ...connect
251 })
252 } else {
253 const customConnect = connect
254 connect = (opts, callback) => customConnect({
255 ...opts,
256 ...(socketPath != null ? { socketPath } : null),
257 ...(allowH2 != null ? { allowH2 } : null)
258 }, callback)
259 }
260
261 this[kUrl] = util.parseOrigin(url)
262 this[kHostAuthority] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
263 this[kConnector] = connect
264 this[kPipelining] = pipelining != null ? pipelining : 1
265 this[kMaxHeadersSize] = maxHeaderSize
266 this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
267 this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
268 this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold
269 this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
270 this[kServerName] = null
271 this[kLocalAddress] = localAddress != null ? localAddress : null
272 this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
273 this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
274 this[kHostHeader] = `host: ${this[kHostAuthority]}\r\n`
275 this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
276 this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
277 this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
278 this[kMaxRequests] = maxRequestsPerClient
279 this[kClosedResolve] = null
280 this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
281 this[kHTTPContext] = null
282 // h2
283 this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
284 // HTTP/2 window sizes are set to higher defaults than Node.js core for better performance:
285 // - initialWindowSize: 262144 (256KB) vs Node.js default 65535 (64KB - 1)
286 // Allows more data to be sent before requiring acknowledgment, improving throughput
287 // especially on high-latency networks. This matches common production HTTP/2 servers.
288 // - connectionWindowSize: 524288 (512KB) vs Node.js default (none set)
289 // Provides better flow control for the entire connection across multiple streams.
290 this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144
291 this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288
292 this[kPingInterval] = pingInterval != null ? pingInterval : 60e3 // Default ping interval for h2 - 1 minute
293
294 // kQueue is built up of 3 sections separated by
295 // the kRunningIdx and kPendingIdx indices.
296 // | complete | running | pending |
297 // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
298 // kRunningIdx points to the first running element.
299 // kPendingIdx points to the first pending element.
300 // This implements a fast queue with an amortized
301 // time of O(1).
302
303 this[kQueue] = []
304 this[kRunningIdx] = 0
305 this[kPendingIdx] = 0
306
307 this[kResume] = (sync) => resume(this, sync)
308 this[kOnError] = (err) => onError(this, err)
309 }
310
311 get pipelining () {
312 return this[kPipelining]
313 }
314
315 set pipelining (value) {
316 this[kPipelining] = value
317 this[kResume](true)
318 }
319
320 get stats () {
321 return new ClientStats(this)
322 }
323
324 get [kPending] () {
325 return this[kQueue].length - this[kPendingIdx]
326 }
327
328 get [kRunning] () {
329 return this[kPendingIdx] - this[kRunningIdx]
330 }
331
332 get [kSize] () {
333 return this[kQueue].length - this[kRunningIdx]
334 }
335
336 get [kConnected] () {
337 return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed
338 }
339
340 get [kBusy] () {
341 // The `kPending > 0` check below is the gate Pool uses to decide whether
342 // to spin up an additional Client. For h1 that fan-out is correct —
343 // each socket only handles one pipelined request at a time. Once an h2
344 // context is attached we want concurrent dispatches to multiplex onto
345 // the shared session, so suppress that signal in the h2 case.
346 const allowsMux = this[kHTTPContext]?.version === 'h2'
347
348 return Boolean(
349 this[kHTTPContext]?.busy(null) ||
350 (this[kSize] >= (getMaxConcurrent(this) || 1)) ||
351 (this[kPending] > 0 && !allowsMux)
352 )
353 }
354
355 [kConnect] (cb) {
356 connect(this)
357 this.once('connect', cb)
358 }
359
360 [kDispatch] (opts, handler) {
361 const request = new Request(this[kUrl].origin, opts, handler)
362
363 this[kQueue].push(request)
364 if (this[kResuming]) {
365 // Do nothing.
366 } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
367 // Wait a tick in case stream/iterator is ended in the same tick.
368 this[kResuming] = 1
369 queueMicrotask(() => resume(this))
370 } else {
371 this[kResume](true)
372 }
373
374 if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
375 this[kNeedDrain] = 2
376 }
377
378 return this[kNeedDrain] < 2
379 }
380
381 [kClose] () {
382 // TODO: for H2 we need to gracefully flush the remaining enqueued
383 // request and close each stream.
384 return new Promise((resolve) => {
385 if (this[kSize]) {
386 this[kClosedResolve] = resolve
387 } else {
388 resolve(null)
389 }
390 })
391 }
392
393 [kDestroy] (err) {
394 return new Promise((resolve) => {
395 const requests = this[kQueue].splice(this[kPendingIdx])
396 for (let i = 0; i < requests.length; i++) {
397 const request = requests[i]
398 if (request != null) {
399 util.errorRequest(this, request, err)
400 }
401 }
402
403 const callback = () => {
404 if (this[kClosedResolve]) {
405 // TODO (fix): Should we error here with ClientDestroyedError?
406 this[kClosedResolve]()
407 this[kClosedResolve] = null
408 }
409 resolve(null)
410 }
411
412 if (this[kHTTPContext]) {
413 this[kHTTPContext].destroy(err, callback)
414 this[kHTTPContext] = null
415 } else {
416 queueMicrotask(callback)
417 }
418
419 this[kResume]()
420 })
421 }
422 }
423
424 function onError (client, err) {
425 if (
426 client[kRunning] === 0 &&
427 err.code !== 'UND_ERR_INFO' &&
428 err.code !== 'UND_ERR_SOCKET'
429 ) {
430 // Error is not caused by running request and not a recoverable
431 // socket error.
432
433 assert(client[kPendingIdx] === client[kRunningIdx])
434
435 const requests = client[kQueue].splice(client[kRunningIdx])
436
437 for (let i = 0; i < requests.length; i++) {
438 const request = requests[i]
439 if (request != null) {
440 util.errorRequest(client, request, err)
441 }
442 }
443 assert(client[kSize] === 0)
444 }
445 }
446
447 /**
448 * @param {Client} client
449 * @returns {void}
450 */
451 function connect (client) {
452 assert(!client[kConnecting])
453 assert(!client[kHTTPContext])
454
455 let { host, hostname, protocol, port } = client[kUrl]
456
457 // Resolve ipv6
458 if (hostname[0] === '[') {
459 const idx = hostname.indexOf(']')
460
461 assert(idx !== -1)
462 const ip = hostname.substring(1, idx)
463
464 assert(net.isIPv6(ip))
465 hostname = ip
466 }
467
468 client[kConnecting] = true
469
470 if (channels.beforeConnect.hasSubscribers) {
471 channels.beforeConnect.publish({
472 connectParams: {
473 host,
474 hostname,
475 protocol,
476 port,
477 version: client[kHTTPContext]?.version,
478 servername: client[kServerName],
479 localAddress: client[kLocalAddress]
480 },
481 connector: client[kConnector]
482 })
483 }
484
485 try {
486 client[kConnector]({
487 host,
488 hostname,
489 protocol,
490 port,
491 servername: client[kServerName],
492 localAddress: client[kLocalAddress]
493 }, (err, socket) => {
494 if (err) {
495 handleConnectError(client, err, { host, hostname, protocol, port })
496 client[kResume]()
497 return
498 }
499
500 if (client.destroyed) {
501 util.destroy(socket.on('error', noop), new ClientDestroyedError())
502 client[kResume]()
503 return
504 }
505
506 assert(socket)
507
508 try {
509 client[kHTTPContext] = socket.alpnProtocol === 'h2'
510 ? connectH2(client, socket)
511 : connectH1(client, socket)
512 } catch (err) {
513 socket.destroy().on('error', noop)
514 handleConnectError(client, err, { host, hostname, protocol, port })
515 client[kResume]()
516 return
517 }
518
519 client[kConnecting] = false
520
521 socket[kCounter] = 0
522 socket[kMaxRequests] = client[kMaxRequests]
523 socket[kClient] = client
524 socket[kError] = null
525
526 if (channels.connected.hasSubscribers) {
527 channels.connected.publish({
528 connectParams: {
529 host,
530 hostname,
531 protocol,
532 port,
533 version: client[kHTTPContext]?.version,
534 servername: client[kServerName],
535 localAddress: client[kLocalAddress]
536 },
537 connector: client[kConnector],
538 socket
539 })
540 }
541
542 client.emit('connect', client[kUrl], [client])
543 client[kResume]()
544 })
545 } catch (err) {
546 handleConnectError(client, err, { host, hostname, protocol, port })
547 client[kResume]()
548 }
549 }
550
551 function handleConnectError (client, err, { host, hostname, protocol, port }) {
552 if (client.destroyed) {
553 return
554 }
555
556 client[kConnecting] = false
557
558 if (channels.connectError.hasSubscribers) {
559 channels.connectError.publish({
560 connectParams: {
561 host,
562 hostname,
563 protocol,
564 port,
565 version: client[kHTTPContext]?.version,
566 servername: client[kServerName],
567 localAddress: client[kLocalAddress]
568 },
569 connector: client[kConnector],
570 error: err
571 })
572 }
573
574 if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
575 const running = client[kQueue].splice(client[kRunningIdx], client[kRunning])
576 client[kPendingIdx] = client[kRunningIdx]
577
578 for (let i = 0; i < running.length; i++) {
579 util.errorRequest(client, running[i], err)
580 }
581
582 while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
583 const request = client[kQueue].splice(client[kPendingIdx], 1)[0]
584 util.errorRequest(client, request, err)
585 }
586 } else {
587 onError(client, err)
588 }
589
590 client.emit('connectionError', client[kUrl], [client], err)
591 }
592
593 function emitDrain (client) {
594 client[kNeedDrain] = 0
595 client.emit('drain', client[kUrl], [client])
596 }
597
598 function resume (client, sync) {
599 if (client[kResuming] === 2) {
600 return
601 }
602
603 client[kResuming] = 2
604
605 _resume(client, sync)
606 client[kResuming] = 0
607
608 if (client[kRunningIdx] > 256) {
609 client[kQueue].splice(0, client[kRunningIdx])
610 client[kPendingIdx] -= client[kRunningIdx]
611 client[kRunningIdx] = 0
612 }
613 }
614
615 function _resume (client, sync) {
616 while (true) {
617 if (client.destroyed) {
618 assert(client[kPending] === 0)
619 return
620 }
621
622 if (client[kClosedResolve] && !client[kSize]) {
623 client[kClosedResolve]()
624 client[kClosedResolve] = null
625 return
626 }
627
628 if (client[kHTTPContext]) {
629 client[kHTTPContext].resume()
630 }
631
632 if (client[kBusy]) {
633 client[kNeedDrain] = 2
634 } else if (client[kNeedDrain] === 2) {
635 if (sync) {
636 client[kNeedDrain] = 1
637 queueMicrotask(() => emitDrain(client))
638 } else {
639 emitDrain(client)
640 }
641 continue
642 }
643
644 if (client[kPending] === 0) {
645 return
646 }
647
648 if (client[kRunning] >= (getMaxConcurrent(client) || 1)) {
649 return
650 }
651
652 const request = client[kQueue][client[kPendingIdx]]
653
654 if (request === null) {
655 return
656 }
657
658 if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
659 if (client[kRunning] > 0) {
660 return
661 }
662
663 client[kServerName] = request.servername
664 client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => {
665 client[kHTTPContext] = null
666 resume(client)
667 })
668 }
669
670 if (client[kConnecting]) {
671 return
672 }
673
674 if (!client[kHTTPContext]) {
675 connect(client)
676 return
677 }
678
679 if (client[kHTTPContext].destroyed) {
680 return
681 }
682
683 if (client[kHTTPContext].busy(request)) {
684 return
685 }
686
687 if (!request.aborted && client[kHTTPContext].write(request)) {
688 client[kPendingIdx]++
689 } else {
690 client[kQueue].splice(client[kPendingIdx], 1)
691 }
692 }
693 }
694
695 module.exports = Client