pi-dent-agent 0.2.9 → 0.2.10

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 (39) hide show
  1. package/lib/plugin-state.ts +484 -0
  2. package/lib/plugin-ui.ts +2 -0
  3. package/lib/script-runner.ts +8 -0
  4. package/lib/script-tool.ts +3 -0
  5. package/lib/script-worker.ts +78 -7
  6. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/CacheStore.md +11 -0
  7. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Client.md +1 -1
  8. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Connector.md +9 -2
  9. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Dispatcher.md +20 -0
  10. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Interceptors.md +13 -3
  11. package/node_modules/pi-web-access/node_modules/undici/docs/docs/best-practices/mocking-request.md +1 -1
  12. package/node_modules/pi-web-access/node_modules/undici/lib/api/abort-signal.js +55 -5
  13. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-connect.js +6 -2
  14. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-pipeline.js +7 -2
  15. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-request.js +12 -4
  16. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-stream.js +6 -2
  17. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-upgrade.js +6 -2
  18. package/node_modules/pi-web-access/node_modules/undici/lib/core/request.js +17 -0
  19. package/node_modules/pi-web-access/node_modules/undici/lib/core/symbols.js +3 -1
  20. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h1.js +24 -0
  21. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h2.js +11 -5
  22. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client.js +109 -2
  23. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher-base.js +6 -1
  24. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher.js +22 -1
  25. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool-base.js +72 -16
  26. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool.js +22 -9
  27. package/node_modules/pi-web-access/node_modules/undici/lib/handler/cache-handler.js +1 -1
  28. package/node_modules/pi-web-access/node_modules/undici/lib/handler/retry-handler.js +27 -1
  29. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/cache.js +9 -2
  30. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/decompress.js +0 -11
  31. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/deduplicate.js +4 -1
  32. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/redirect.js +4 -1
  33. package/node_modules/pi-web-access/node_modules/undici/lib/util/cache.js +1 -1
  34. package/node_modules/pi-web-access/node_modules/undici/lib/util/timers.js +1 -1
  35. package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/index.js +20 -1
  36. package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/util.js +2 -2
  37. package/node_modules/pi-web-access/node_modules/undici/package.json +3 -3
  38. package/node_modules/pi-web-access/node_modules/undici/types/retry-handler.d.ts +1 -1
  39. package/package.json +1 -1
@@ -78,7 +78,7 @@ const connector = buildConnector({ rejectUnauthorized: false })
78
78
 
79
79
  const client = new Client('https://localhost:3000', {
80
80
  connect (opts, cb) {
81
- connector(opts, (err, socket) => {
81
+ return connector(opts, (err, socket) => {
82
82
  if (err) {
83
83
  cb(err)
84
84
  } else if (/* assertion */ false) {
@@ -124,6 +124,13 @@ targets or a [`tls.TLSSocket`][] for `https:` targets, applies TCP keep-alive an
124
124
  the connect timeout, and invokes `callback` once the socket connects or errors.
125
125
  The socket is also returned synchronously.
126
126
 
127
+ undici uses the returned socket to cancel a connection attempt that no request
128
+ needs any more: once every request waiting for it is aborted, the socket is
129
+ destroyed and the next request opens a new connection instead of waiting for
130
+ it. A connector that wraps another one should return the socket it gets back,
131
+ as the examples on this page do. If it returns nothing, the attempt runs until
132
+ it connects or fails.
133
+
127
134
  When connecting over TLS, established sessions are cached (subject to
128
135
  `maxCachedSessions`) and reused for subsequent connections to the same
129
136
  `servername` or `hostname`.
@@ -141,7 +148,7 @@ const connector = buildConnector({ rejectUnauthorized: false })
141
148
 
142
149
  const client = new Client('https://localhost:3000', {
143
150
  connect (opts, cb) {
144
- connector(opts, (err, socket) => {
151
+ return connector(opts, (err, socket) => {
145
152
  if (err) {
146
153
  cb(err)
147
154
  } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) {
@@ -705,6 +705,26 @@ The order of the interceptors matters: the last interceptor in the chain is the
705
705
  first to be called. Forking the chain of interceptors can lead to unexpected
706
706
  results.
707
707
 
708
+ Because interceptors wrap each other, ordering is the end-user's responsibility.
709
+ Certain built-in interceptors are order-sensitive and will throw an
710
+ `InvalidArgumentError` if composed in an unsafe order. In particular, the
711
+ `cache` interceptor must be composed **after** the `redirect` interceptor. When
712
+ `cache` is composed before `redirect`, the cache handler is wrapped *above* the
713
+ redirect handler, so it never observes the redirect history and its
714
+ cross-origin / credential-bearing redirect guards are silently disabled.
715
+ This allows an attacker-controlled or cross-principal redirect response to be
716
+ stored under the trusted origin's cache key and replayed to unrelated callers
717
+ (see GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26 and
718
+ GHSA-7XG3-FPHP-28HG).
719
+
720
+ ```js
721
+ // Correct: cache is composed after redirect.
722
+ new Agent().compose(interceptors.redirect({ maxRedirections: 5 }), interceptors.cache({}))
723
+
724
+ // Throws an InvalidArgumentError: cache composed before redirect.
725
+ new Agent().compose(interceptors.cache({}), interceptors.redirect({ maxRedirections: 5 }))
726
+ ```
727
+
708
728
  ```text
709
729
  compose([interceptor1, interceptor2, interceptor3])
710
730
 
@@ -204,9 +204,6 @@ and `x-compress`, is left untouched, matching `fetch()`. As required by
204
204
  [RFC 9659](https://www.rfc-editor.org/rfc/rfc9659.html), a `zstd` frame that
205
205
  requires a window size larger than 8 MB fails to decode.
206
206
 
207
- > **Experimental:** This interceptor is experimental and subject to change.
208
- > A one-time `ExperimentalWarning` is emitted on first use.
209
-
210
207
  **Parameters**
211
208
 
212
209
  * `opts` {Object} (optional)
@@ -359,12 +356,25 @@ backing store.
359
356
 
360
357
  **Returns:** {Dispatcher.DispatcherComposeInterceptor}
361
358
 
359
+ > **Ordering:** the `cache` interceptor must be composed **after** the
360
+ > `redirect` interceptor. When `cache` is composed before `redirect`, the cache
361
+ > handler is wrapped above the redirect handler, so it never observes the
362
+ > redirect history and its cross-origin / credential-bearing redirect guards are
363
+ > silently disabled, which lets an attacker-controlled or cross-principal
364
+ > redirect response be stored under the trusted origin's cache key and replayed
365
+ > to unrelated callers (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32,
366
+ > GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG). `compose()` throws an
367
+ > `InvalidArgumentError` for this unsafe order. The `deduplicate` interceptor
368
+ > participates in the same redirect-history contract and may be placed before or
369
+ > after `redirect`, as long as `cache` follows `redirect`.
370
+
362
371
  **Example**
363
372
 
364
373
  ```js
365
374
  import { Agent, interceptors, cacheStores } from 'undici'
366
375
 
367
376
  const agent = new Agent().compose(
377
+ interceptors.redirect({ maxRedirections: 5 }),
368
378
  interceptors.cache({ store: new cacheStores.MemoryCacheStore() })
369
379
  )
370
380
  ```
@@ -61,7 +61,7 @@ const success = await bankTransfer('1234567890', '100')
61
61
 
62
62
  assert.deepEqual(success, { message: 'transaction processed' })
63
63
 
64
- // if you dont want to check whether the body or the headers contain the same value
64
+ // if you don't want to check whether the body or the headers contain the same value
65
65
  // just remove it from interceptor
66
66
  mockPool.intercept({
67
67
  path: '/bank-transfer',
@@ -2,15 +2,17 @@
2
2
 
3
3
  const { addAbortListener } = require('../core/util')
4
4
  const { RequestAbortedError } = require('../core/errors')
5
+ const { kQueuedAbort } = require('../core/symbols')
5
6
 
6
7
  const kListener = Symbol('kListener')
7
8
  const kSignal = Symbol('kSignal')
8
9
 
9
10
  function abort (self) {
11
+ // Keep the reason even when abort is set: a queued request that cannot be
12
+ // taken out of its queue is aborted once it starts.
13
+ self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
10
14
  if (self.abort) {
11
- self.abort(self[kSignal]?.reason)
12
- } else {
13
- self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
15
+ self.abort(self.reason)
14
16
  }
15
17
  removeSignal(self)
16
18
  }
@@ -26,7 +28,7 @@ function addSignal (self, signal) {
26
28
  }
27
29
 
28
30
  if (signal.aborted) {
29
- abort(self)
31
+ self.reason = signal.reason ?? new RequestAbortedError()
30
32
  return
31
33
  }
32
34
 
@@ -53,7 +55,55 @@ function removeSignal (self) {
53
55
  self[kListener] = null
54
56
  }
55
57
 
58
+ // Dispatchers call the kQueuedAbort hook while a request waits for a
59
+ // connection, with a function that takes it out of their queue. Until the
60
+ // request starts, the handler's abort calls that function.
61
+ //
62
+ // A retry or a redirect dispatches the same handler again after an earlier
63
+ // attempt started. The handler's abort then also calls the controller of that
64
+ // attempt: it does nothing once the attempt is over, and still reaches a
65
+ // response that a retry resumes.
66
+ function queuedAbortHook (handler) {
67
+ // The abort set by onRequestStart, and the one this hook installed last.
68
+ let started = null
69
+ let installed = null
70
+ return (cancel) => {
71
+ if (handler.reason) {
72
+ cancel(handler.reason)
73
+ return
74
+ }
75
+
76
+ if (handler.abort !== installed) {
77
+ started = handler.abort
78
+ }
79
+
80
+ if (started === null) {
81
+ installed = cancel
82
+ } else {
83
+ const abortStarted = started
84
+ installed = (reason) => {
85
+ abortStarted(reason)
86
+ cancel(reason)
87
+ }
88
+ }
89
+ handler.abort = installed
90
+ }
91
+ }
92
+
93
+ // Dispatches a request whose options carry a signal. Requests without a signal
94
+ // are dispatched directly and never reach this function.
95
+ function dispatchWithSignal (dispatcher, opts, handler) {
96
+ if (handler.reason) {
97
+ // Already aborted: fail without dispatching, so no connection is opened.
98
+ handler.onResponseError(null, handler.reason)
99
+ return
100
+ }
101
+
102
+ dispatcher.dispatch({ ...opts, [kQueuedAbort]: queuedAbortHook(handler) }, handler)
103
+ }
104
+
56
105
  module.exports = {
57
106
  addSignal,
58
- removeSignal
107
+ removeSignal,
108
+ dispatchWithSignal
59
109
  }
@@ -4,7 +4,7 @@ const assert = require('node:assert')
4
4
  const { AsyncResource } = require('node:async_hooks')
5
5
  const { InvalidArgumentError, SocketError } = require('../core/errors')
6
6
  const util = require('../core/util')
7
- const { addSignal, removeSignal } = require('./abort-signal')
7
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
8
8
 
9
9
  class ConnectHandler extends AsyncResource {
10
10
  constructor (opts, callback) {
@@ -99,7 +99,11 @@ function connect (opts, callback) {
99
99
  try {
100
100
  const connectHandler = new ConnectHandler(opts, callback)
101
101
  const connectOptions = { ...opts, method: 'CONNECT' }
102
- this.dispatch(connectOptions, connectHandler)
102
+ if (opts.signal == null) {
103
+ this.dispatch(connectOptions, connectHandler)
104
+ } else {
105
+ dispatchWithSignal(this, connectOptions, connectHandler)
106
+ }
103
107
  } catch (err) {
104
108
  if (typeof callback !== 'function') {
105
109
  throw err
@@ -14,7 +14,7 @@ const {
14
14
  } = require('../core/errors')
15
15
  const util = require('../core/util')
16
16
  const { kBodyUsed } = require('../core/symbols')
17
- const { addSignal, removeSignal } = require('./abort-signal')
17
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
18
18
 
19
19
  function noop () {}
20
20
 
@@ -255,7 +255,12 @@ class PipelineHandler extends AsyncResource {
255
255
  function pipeline (opts, handler) {
256
256
  try {
257
257
  const pipelineHandler = new PipelineHandler(opts, handler)
258
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
258
+ const pipelineOpts = { ...opts, body: pipelineHandler.req }
259
+ if (opts.signal == null) {
260
+ this.dispatch(pipelineOpts, pipelineHandler)
261
+ } else {
262
+ dispatchWithSignal(this, pipelineOpts, pipelineHandler)
263
+ }
259
264
  return pipelineHandler.ret
260
265
  } catch (err) {
261
266
  return new PassThrough().destroy(err)
@@ -5,6 +5,7 @@ const { AsyncResource } = require('node:async_hooks')
5
5
  const { Readable } = require('./readable')
6
6
  const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
7
7
  const util = require('../core/util')
8
+ const { dispatchWithSignal } = require('./abort-signal')
8
9
 
9
10
  function noop () {}
10
11
 
@@ -37,6 +38,11 @@ class RequestHandler extends AsyncResource {
37
38
  throw new InvalidArgumentError('invalid onInfo callback')
38
39
  }
39
40
 
41
+ // Reject before dispatching: onRequestStart only runs once a connection is established.
42
+ if (signal?.aborted) {
43
+ throw signal.reason ?? new RequestAbortedError()
44
+ }
45
+
40
46
  super('UNDICI_REQUEST')
41
47
  } catch (err) {
42
48
  if (util.isStream(body)) {
@@ -60,9 +66,7 @@ class RequestHandler extends AsyncResource {
60
66
  this.reason = null
61
67
  this.removeAbortListener = null
62
68
 
63
- if (signal?.aborted) {
64
- this.reason = signal.reason ?? new RequestAbortedError()
65
- } else if (signal) {
69
+ if (signal) {
66
70
  this.removeAbortListener = util.addAbortListener(signal, () => {
67
71
  this.reason = signal.reason ?? new RequestAbortedError()
68
72
  if (this.res) {
@@ -230,7 +234,11 @@ function request (opts, callback) {
230
234
  try {
231
235
  const handler = new RequestHandler(opts, callback)
232
236
 
233
- this.dispatch(opts, handler)
237
+ if (opts.signal == null) {
238
+ this.dispatch(opts, handler)
239
+ } else {
240
+ dispatchWithSignal(this, opts, handler)
241
+ }
234
242
  } catch (err) {
235
243
  if (typeof callback !== 'function') {
236
244
  throw err
@@ -4,7 +4,7 @@ const assert = require('node:assert')
4
4
  const { AsyncResource } = require('node:async_hooks')
5
5
  const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors')
6
6
  const util = require('../core/util')
7
- const { addSignal, removeSignal } = require('./abort-signal')
7
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
8
8
 
9
9
  function noop () {}
10
10
 
@@ -257,7 +257,11 @@ function stream (opts, factory, callback) {
257
257
  try {
258
258
  const handler = new StreamHandler(opts, factory, callback)
259
259
 
260
- this.dispatch(opts, handler)
260
+ if (opts.signal == null) {
261
+ this.dispatch(opts, handler)
262
+ } else {
263
+ dispatchWithSignal(this, opts, handler)
264
+ }
261
265
  } catch (err) {
262
266
  if (typeof callback !== 'function') {
263
267
  throw err
@@ -5,7 +5,7 @@ const { AsyncResource } = require('node:async_hooks')
5
5
  const assert = require('node:assert')
6
6
  const util = require('../core/util')
7
7
  const { kHTTP2Stream } = require('../core/symbols')
8
- const { addSignal, removeSignal } = require('./abort-signal')
8
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
9
9
 
10
10
  class UpgradeHandler extends AsyncResource {
11
11
  constructor (opts, callback) {
@@ -108,7 +108,11 @@ function upgrade (opts, callback) {
108
108
  method: opts.method || 'GET',
109
109
  upgrade: opts.protocol || 'Websocket'
110
110
  }
111
- this.dispatch(upgradeOpts, upgradeHandler)
111
+ if (opts.signal == null) {
112
+ this.dispatch(upgradeOpts, upgradeHandler)
113
+ } else {
114
+ dispatchWithSignal(this, upgradeOpts, upgradeHandler)
115
+ }
112
116
  } catch (err) {
113
117
  if (typeof callback !== 'function') {
114
118
  throw err
@@ -47,6 +47,8 @@ const kHandler = Symbol('handler')
47
47
  const kController = Symbol('controller')
48
48
  const kResume = Symbol('resume')
49
49
 
50
+ function noop () {}
51
+
50
52
  class RequestController {
51
53
  #paused = false
52
54
  #reason = null
@@ -463,12 +465,26 @@ class Request {
463
465
  }
464
466
  }
465
467
 
468
+ // Fails a request that was aborted before it reached a connection. The
469
+ // handler gets an aborted controller, so wrappers such as RetryHandler can
470
+ // tell a caller abort apart from a retryable connection failure.
471
+ onQueuedAbort (reason) {
472
+ this[kController] = createAbortedController(reason)
473
+ return this.onResponseError(reason)
474
+ }
475
+
466
476
  addHeader (key, value) {
467
477
  processHeader(this, key, value)
468
478
  return this
469
479
  }
470
480
  }
471
481
 
482
+ function createAbortedController (reason) {
483
+ const controller = new RequestController(noop)
484
+ controller.abort(reason)
485
+ return controller
486
+ }
487
+
472
488
  function processHeader (request, key, val) {
473
489
  if (val && (typeof val === 'object' && !Array.isArray(val))) {
474
490
  throw new InvalidArgumentError(`invalid ${key} header`)
@@ -580,3 +596,4 @@ function isUndiciFormData (body) {
580
596
  }
581
597
 
582
598
  module.exports = Request
599
+ module.exports.createAbortedController = createAbortedController
@@ -60,6 +60,7 @@ module.exports = {
60
60
  kMaxResponseSize: Symbol('max response size'),
61
61
  kHTTP2Session: Symbol('http2Session'),
62
62
  kHTTP2Options: Symbol('http2 options'),
63
+ kQueuedAbort: Symbol('queued abort'),
63
64
  kHTTP2SessionState: Symbol('http2Session state'),
64
65
  kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
65
66
  kConstruct: Symbol('constructable'),
@@ -77,5 +78,6 @@ module.exports = {
77
78
  kNoProxyAgent: Symbol('no proxy agent'),
78
79
  kHttpProxyAgent: Symbol('http proxy agent'),
79
80
  kHttpsProxyAgent: Symbol('https proxy agent'),
80
- kSocks5ProxyAgent: Symbol('socks5 proxy agent')
81
+ kSocks5ProxyAgent: Symbol('socks5 proxy agent'),
82
+ kInterceptorKind: Symbol('interceptor kind')
81
83
  }
@@ -67,6 +67,7 @@ const removeAllListeners = util.removeAllListeners
67
67
  const kIdleSocketValidation = Symbol('kIdleSocketValidation')
68
68
  const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
69
69
  const kSocketUsed = Symbol('kSocketUsed')
70
+ const kIdleSince = Symbol('kIdleSince')
70
71
  const kTypeOfService = Symbol('kTypeOfService')
71
72
 
72
73
  let extractBody
@@ -1107,6 +1108,19 @@ function scheduleIdleSocketValidation (client, socket) {
1107
1108
  })
1108
1109
  }
1109
1110
 
1111
+ /**
1112
+ * kIdleSince is recorded when the keep-alive timer is armed, so this never
1113
+ * expires a socket before that timer is due.
1114
+ * @param {import('net').Socket} socket
1115
+ * @returns {boolean}
1116
+ */
1117
+ function isIdleSocketExpired (socket) {
1118
+ const parser = socket[kParser]
1119
+ return parser.timeoutType === TIMEOUT_KEEP_ALIVE &&
1120
+ parser.timeoutValue > 0 &&
1121
+ performance.now() - socket[kIdleSince] >= parser.timeoutValue
1122
+ }
1123
+
1110
1124
  /**
1111
1125
  * @param {import('./client.js')} client
1112
1126
  */
@@ -1124,6 +1138,15 @@ function resumeH1 (client) {
1124
1138
  socket[kNoRef] = false
1125
1139
  }
1126
1140
 
1141
+ // The keep-alive timer cannot fire while the event loop is blocked, and a
1142
+ // request dispatched from the poll phase passes the idle socket validation
1143
+ // below before that timer or a FIN received during the block is processed.
1144
+ // Check the clock so that an expired socket is not reused.
1145
+ if (client[kRunning] === 0 && client[kPending] > 0 && isIdleSocketExpired(socket)) {
1146
+ util.destroy(socket, new InformationalError('socket idle timeout'))
1147
+ return
1148
+ }
1149
+
1127
1150
  if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
1128
1151
  if (socket[kIdleSocketValidation] === 0) {
1129
1152
  scheduleIdleSocketValidation(client, socket)
@@ -1152,6 +1175,7 @@ function resumeH1 (client) {
1152
1175
 
1153
1176
  if (client[kSize] === 0) {
1154
1177
  if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
1178
+ socket[kIdleSince] = performance.now()
1155
1179
  socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
1156
1180
  }
1157
1181
  } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
@@ -91,6 +91,7 @@ const {
91
91
  HTTP2_HEADER_STATUS,
92
92
  HTTP2_HEADER_PROTOCOL,
93
93
  NGHTTP2_NO_ERROR,
94
+ NGHTTP2_PROTOCOL_ERROR,
94
95
  NGHTTP2_REFUSED_STREAM
95
96
  }
96
97
  } = http2
@@ -1684,11 +1685,16 @@ function onError (err) {
1684
1685
  // noop error sink so that re-delivery cannot go unhandled.
1685
1686
  stream.on('error', noop)
1686
1687
 
1687
- // Node's HTTP/2 implementation can turn an incomplete Content-Length body
1688
- // into a protocol stream error instead of emitting 'end'. Prefer the
1689
- // content-length mismatch error when the received byte count proves it.
1690
- if (state.responseContentLength != null && state.bytesRead !== state.responseContentLength) {
1691
- err = new ResponseContentLengthMismatchError()
1688
+ // Node may report Content-Length violations as protocol errors.
1689
+ if (
1690
+ (err.code === 'ERR_HTTP2_ERROR' ||
1691
+ (err.code === 'ERR_HTTP2_STREAM_ERROR' && stream.rstCode === NGHTTP2_PROTOCOL_ERROR)) &&
1692
+ state.responseContentLength != null &&
1693
+ state.bytesRead !== state.responseContentLength
1694
+ ) {
1695
+ const mismatch = new ResponseContentLengthMismatchError()
1696
+ mismatch.cause = err
1697
+ err = mismatch
1692
1698
  }
1693
1699
 
1694
1700
  if (typeof stream.rstCode === 'number' && stream.rstCode !== NGHTTP2_NO_ERROR) {
@@ -55,12 +55,14 @@ const {
55
55
  kHostAuthority,
56
56
  kResume,
57
57
  kHTTP2Options,
58
- kUseMilo
58
+ kUseMilo,
59
+ kQueuedAbort
59
60
  } = require('../core/symbols.js')
60
61
  const connectH1 = require('./client-h1.js')
61
62
  const connectH2 = require('./client-h2.js')
62
63
 
63
64
  const kClosedResolve = Symbol('kClosedResolve')
65
+ const kCancelConnect = Symbol('kCancelConnect')
64
66
 
65
67
  const getDefaultNodeMaxHeaderSize = http &&
66
68
  http.maxHeaderSize &&
@@ -322,6 +324,7 @@ class Client extends DispatcherBase {
322
324
  this[kClosedResolve] = null
323
325
  this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
324
326
  this[kHTTPContext] = null
327
+ this[kCancelConnect] = null
325
328
  // h2
326
329
  this[kHTTP2Options] = {
327
330
  pingInterval: h2Options?.pingInterval ?? pingInterval ?? 60e3,
@@ -402,6 +405,8 @@ class Client extends DispatcherBase {
402
405
 
403
406
  [kConnect] (cb) {
404
407
  connect(this)
408
+ // Asked for explicitly: keep it even if no request waits for it.
409
+ this[kCancelConnect] = null
405
410
  this.once('connect', cb)
406
411
  }
407
412
 
@@ -419,6 +424,15 @@ class Client extends DispatcherBase {
419
424
  this[kResume](true)
420
425
  }
421
426
 
427
+ if (request.abort === null && !request.aborted) {
428
+ // The request is still waiting for a connection: if its handler listens
429
+ // to a signal, give it a way to take the request out of the queue.
430
+ const onQueued = opts[kQueuedAbort]
431
+ if (onQueued !== undefined) {
432
+ onQueued((reason) => abortPendingRequest(this, request, reason))
433
+ }
434
+ }
435
+
422
436
  if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
423
437
  this[kNeedDrain] = 2
424
438
  }
@@ -469,6 +483,56 @@ class Client extends DispatcherBase {
469
483
  }
470
484
  }
471
485
 
486
+ function failQueuedRequest (client, request, reason) {
487
+ try {
488
+ request.onQueuedAbort(reason)
489
+ assert(request.aborted)
490
+ } catch (err) {
491
+ client.emit('error', err)
492
+ }
493
+ }
494
+
495
+ function abortPendingRequest (client, request, reason) {
496
+ // The request already settled, or it started and its handler owns the abort.
497
+ if (request.aborted || request.abort !== null) {
498
+ return
499
+ }
500
+
501
+ const queue = client[kQueue]
502
+ const idx = queue.indexOf(request, client[kPendingIdx])
503
+ if (idx === -1) {
504
+ return
505
+ }
506
+
507
+ // _resume() may be handing this request to the connection right now, before
508
+ // onRequestStart runs. Leave it there: the handler aborts it once it starts.
509
+ if (idx === client[kPendingIdx] && client[kResuming] === 2) {
510
+ return
511
+ }
512
+
513
+ queue.splice(idx, 1)
514
+ failQueuedRequest(client, request, reason)
515
+
516
+ // The client may no longer be busy: emit 'drain' so a Pool can use it again.
517
+ client[kResume](true)
518
+
519
+ if (client[kCancelConnect] !== null && client[kSize] === 0) {
520
+ // The drain is emitted in a microtask: check once a Pool had the chance to
521
+ // hand this client the requests it queued.
522
+ queueMicrotask(() => cancelUnusedConnect(client))
523
+ }
524
+ }
525
+
526
+ // A connection attempt that no request waits for only holds a connection slot,
527
+ // until it connects or times out. Destroy it, so the next request starts a new
528
+ // one instead of waiting for it.
529
+ function cancelUnusedConnect (client) {
530
+ const cancel = client[kCancelConnect]
531
+ if (cancel !== null && client[kSize] === 0) {
532
+ cancel(new InformationalError('no request waits for this connection'))
533
+ }
534
+ }
535
+
472
536
  function onError (client, err) {
473
537
  if (
474
538
  client[kRunning] === 0 &&
@@ -515,6 +579,9 @@ function connect (client) {
515
579
 
516
580
  client[kConnecting] = true
517
581
 
582
+ let calledBack = false
583
+ let cancelled = false
584
+
518
585
  if (channels.beforeConnect.hasSubscribers) {
519
586
  channels.beforeConnect.publish({
520
587
  connectParams: {
@@ -531,7 +598,7 @@ function connect (client) {
531
598
  }
532
599
 
533
600
  try {
534
- client[kConnector]({
601
+ const connecting = client[kConnector]({
535
602
  host,
536
603
  hostname,
537
604
  protocol,
@@ -539,6 +606,17 @@ function connect (client) {
539
606
  servername: client[kServerName],
540
607
  localAddress: client[kLocalAddress]
541
608
  }, (err, socket) => {
609
+ calledBack = true
610
+
611
+ if (cancelled) {
612
+ if (socket) {
613
+ util.destroy(socket.on('error', noop))
614
+ }
615
+ return
616
+ }
617
+
618
+ client[kCancelConnect] = null
619
+
542
620
  if (err) {
543
621
  handleConnectError(client, err, { host, hostname, protocol, port })
544
622
  client[kResume]()
@@ -590,6 +668,35 @@ function connect (client) {
590
668
  client.emit('connect', client[kUrl], [client])
591
669
  client[kResume]()
592
670
  })
671
+
672
+ // The attempt can only be cancelled through the socket the connector
673
+ // returns. The built-in connector returns it; custom connectors may not.
674
+ if (!calledBack && util.isStream(connecting)) {
675
+ client[kCancelConnect] = (err) => {
676
+ cancelled = true
677
+ client[kCancelConnect] = null
678
+ client[kConnecting] = false
679
+
680
+ // Not a 'connectionError': that would make a Pool retire this client.
681
+ if (channels.connectError.hasSubscribers) {
682
+ channels.connectError.publish({
683
+ connectParams: {
684
+ host,
685
+ hostname,
686
+ protocol,
687
+ port,
688
+ version: client[kHTTPContext]?.version,
689
+ servername: client[kServerName],
690
+ localAddress: client[kLocalAddress]
691
+ },
692
+ connector: client[kConnector],
693
+ error: err
694
+ })
695
+ }
696
+
697
+ util.destroy(connecting.on('error', noop), err)
698
+ }
699
+ }
593
700
  } catch (err) {
594
701
  handleConnectError(client, err, { host, hostname, protocol, port })
595
702
  client[kResume]()
@@ -190,7 +190,12 @@ class DispatcherBase extends Dispatcher {
190
190
 
191
191
  handler.onResponseError(null, err)
192
192
 
193
- return false
193
+ // The request failed synchronously: no work was queued on this
194
+ // dispatcher, no capacity was consumed and no 'drain' event will
195
+ // ever follow. Returning false would make callers (e.g. Pool)
196
+ // mark this dispatcher as busy waiting for a drain that never
197
+ // comes, permanently taking it out of rotation.
198
+ return true
194
199
  }
195
200
  }
196
201
  }