undici 8.12.2 → 8.12.4

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 CHANGED
@@ -171,7 +171,7 @@ const response = await fetch('https://api.example.com/data');
171
171
  - Building isomorphic code that runs in browsers and Node.js
172
172
  - Publishing to npm and want to maximize compatibility with JS runtimes
173
173
  - Simple HTTP requests without advanced configuration
174
- - You're publishing to npm and you want to maximize compatiblity
174
+ - You're publishing to npm and you want to maximize compatibility
175
175
  - You don't depend on features from a specific version of undici
176
176
 
177
177
  #### Use Undici Module When:
@@ -205,7 +205,10 @@ added: v4.0.0
205
205
  -->
206
206
 
207
207
  * `options` {Object}
208
- * `origin` {string|URL} (optional) The origin to dispatch the request to.
208
+ * `origin` {string|URL} The origin to dispatch the request to. Optional for a
209
+ dispatcher that is already bound to a single origin, such as `Client` or
210
+ `Pool`, which then use their own origin. Required on `Agent`, which is not
211
+ bound to one origin and throws an `InvalidArgumentError` when it is missing.
209
212
  * `path` {string} The request path.
210
213
  * `method` {string} The HTTP method, e.g. `'GET'` or `'POST'`.
211
214
  * `body` {string|Buffer|Uint8Array|Readable|FormData|null} The request body.
@@ -341,8 +341,21 @@ backing store.
341
341
 
342
342
  **Parameters**
343
343
 
344
- * `opts` {CacheHandler.CacheOptions} (optional) See the
345
- [`CacheStore`](./CacheStore.md) documentation for accepted fields.
344
+ * `opts` {Object} (optional)
345
+ * `store` {CacheStore} The store that cached responses are kept in. See
346
+ [`CacheStore`](./CacheStore.md). **Default:** a new `MemoryCacheStore`.
347
+ * `methods` {string[]} The HTTP methods to cache. Only safe methods are
348
+ allowed (`GET`, `HEAD`, `OPTIONS`, `TRACE`) and at least one is required.
349
+ **Default:** `['GET']`.
350
+ * `cacheByDefault` {number} RFC 9111 allows caching responses that are not
351
+ explicitly marked as cacheable or not cacheable. Set this to cache such
352
+ responses. **Default:** `undefined`.
353
+ * `type` {string} Whether the cache is `'shared'` or `'private'`, which
354
+ decides how directives such as `s-maxage` and `private` are applied.
355
+ **Default:** `'shared'`.
356
+ * `origins` {(string|RegExp)[]} Only requests to these origins are cached.
357
+ Strings are compared case-insensitively. **Default:** `undefined` (all
358
+ origins are cached).
346
359
 
347
360
  **Returns:** {Dispatcher.DispatcherComposeInterceptor}
348
361
 
@@ -60,7 +60,7 @@ added: v6.7.0
60
60
  * `retryAfter` {boolean} When `true`, the delay between retries is inferred from
61
61
  the `Retry-After` response header when present. **Default:** `true`.
62
62
  * `methods` {string[]} HTTP methods that are eligible for retry.
63
- **Default:** `['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE']`.
63
+ **Default:** `['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE', 'QUERY']`.
64
64
  * `statusCodes` {number[]} HTTP status codes that trigger a retry.
65
65
  **Default:** `[500, 502, 503, 504, 429]`.
66
66
  * `errorCodes` {string[]} Transport error codes that trigger a retry.
@@ -85,7 +85,7 @@ changes:
85
85
  * `retryAfter` {boolean} When `true`, the delay before the next retry is inferred
86
86
  from the `Retry-After` response header when present. **Default:** `true`.
87
87
  * `methods` {string[]} HTTP methods that are eligible for retrying. **Default:**
88
- `['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE']`.
88
+ `['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE', 'QUERY']`.
89
89
  * `statusCodes` {number[]} HTTP status codes that trigger a retry. **Default:**
90
90
  `[500, 502, 503, 504, 429]`.
91
91
  * `errorCodes` {string[]} Network error codes that trigger a retry. **Default:**
@@ -155,7 +155,7 @@ const response = await fetch('https://api.example.com/data');
155
155
  - Building isomorphic code that runs in browsers and Node.js
156
156
  - Publishing to npm and want to maximize compatibility with JS runtimes
157
157
  - Simple HTTP requests without advanced configuration
158
- - You're publishing to npm and you want to maximize compatiblity
158
+ - You're publishing to npm and you want to maximize compatibility
159
159
  - You don't depend on features from a specific version of undici
160
160
 
161
161
  #### Use Undici Module When:
@@ -6,7 +6,9 @@ const { zstdCompressSync, zstdDecompressSync } = require('node:zlib')
6
6
 
7
7
  let DatabaseSync
8
8
 
9
- const VERSION = 4
9
+ // Bump when entries written by an older cache policy are unsafe to reuse.
10
+ // Version 5 invalidates entries that may have been poisoned through redirects.
11
+ const VERSION = 5
10
12
 
11
13
  // 2gb
12
14
  const MAX_ENTRY_SIZE = 2 * 1000 * 1000 * 1000
@@ -18,6 +20,20 @@ const COMPRESS_THRESHOLD = 1024 * 1024
18
20
  // node:sqlite is available.
19
21
  const hasZstd = typeof zstdCompressSync === 'function' && typeof zstdDecompressSync === 'function'
20
22
 
23
+ // SQLite reports a database that another connection is writing as SQLITE_BUSY
24
+ // (5) or SQLITE_LOCKED (6).
25
+ // https://www.sqlite.org/rescode.html#busy
26
+ const SQLITE_BUSY = 5
27
+ const SQLITE_LOCKED = 6
28
+
29
+ /**
30
+ * @param {Error & { errcode?: number }} err
31
+ * @returns {boolean}
32
+ */
33
+ function isLockedError (err) {
34
+ return err?.errcode === SQLITE_BUSY || err?.errcode === SQLITE_LOCKED
35
+ }
36
+
21
37
  /**
22
38
  * @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore
23
39
  * @implements {CacheStore}
@@ -259,7 +275,7 @@ module.exports = class SqliteCacheStore {
259
275
  get (key) {
260
276
  assertCacheKey(key)
261
277
 
262
- const value = this.#findValue(key)
278
+ const value = this.#lockSafe(() => this.#findValue(key))
263
279
  return value
264
280
  ? {
265
281
  body: value.body
@@ -307,10 +323,10 @@ module.exports = class SqliteCacheStore {
307
323
  }
308
324
  }
309
325
 
310
- const existingValue = this.#findValue(key, true)
326
+ const existingValue = this.#lockSafe(() => this.#findValue(key, true))
311
327
  if (existingValue) {
312
328
  // Updating an existing response, let's overwrite it
313
- this.#updateValueQuery.run(
329
+ this.#lockSafe(() => this.#updateValueQuery.run(
314
330
  storedBody,
315
331
  compressed,
316
332
  value.deleteAt,
@@ -323,10 +339,10 @@ module.exports = class SqliteCacheStore {
323
339
  value.cachedAt,
324
340
  value.staleAt,
325
341
  existingValue.id
326
- )
342
+ ))
327
343
  } else {
328
344
  // New response, let's insert it
329
- this.#insertValueQuery.run(
345
+ this.#lockSafe(() => this.#insertValueQuery.run(
330
346
  url,
331
347
  key.method,
332
348
  storedBody,
@@ -340,7 +356,7 @@ module.exports = class SqliteCacheStore {
340
356
  value.vary ? JSON.stringify(value.vary) : null,
341
357
  value.cachedAt,
342
358
  value.staleAt
343
- )
359
+ ))
344
360
  this.#prune()
345
361
  }
346
362
  }
@@ -389,23 +405,53 @@ module.exports = class SqliteCacheStore {
389
405
  throw new TypeError(`expected key to be object, got ${typeof key}`)
390
406
  }
391
407
 
392
- this.#deleteByUrlQuery.run(this.#makeValueUrl(key))
408
+ this.#lockSafe(() => this.#deleteByUrlQuery.run(this.#makeValueUrl(key)))
409
+ }
410
+
411
+ /**
412
+ * Runs a database operation, skipping it when another connection holds the
413
+ * database lock.
414
+ *
415
+ * The cache store is meant to be shared between processes, and SQLite reports
416
+ * a concurrent writer as SQLITE_BUSY/SQLITE_LOCKED. Those errors are
417
+ * transient, and caching is best effort: the entry is skipped and the next
418
+ * request retries, rather than failing the request that triggered the write.
419
+ *
420
+ * @template T
421
+ * @param {() => T} fn
422
+ * @returns {T | undefined}
423
+ */
424
+ #lockSafe (fn) {
425
+ try {
426
+ return fn()
427
+ } catch (err) {
428
+ if (!isLockedError(err)) {
429
+ throw err
430
+ }
431
+
432
+ return undefined
433
+ }
393
434
  }
394
435
 
395
436
  #prune () {
396
- if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) {
397
- return 0
437
+ if (Number.isFinite(this.#maxCount)) {
438
+ // A locked database cannot be measured, so skip pruning instead of
439
+ // failing the write that triggered it.
440
+ const size = this.#lockSafe(() => this.size)
441
+ if (size === undefined || size <= this.#maxCount) {
442
+ return 0
443
+ }
398
444
  }
399
445
 
400
446
  {
401
- const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes
447
+ const removed = this.#lockSafe(() => this.#deleteExpiredValuesQuery.run(Date.now()).changes)
402
448
  if (removed) {
403
449
  return removed
404
450
  }
405
451
  }
406
452
 
407
453
  {
408
- const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes
454
+ const removed = this.#lockSafe(() => this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes)
409
455
  if (removed) {
410
456
  return removed
411
457
  }
@@ -83,7 +83,9 @@ function lazyllhttp () {
83
83
 
84
84
  // We disable wasm SIMD on older versions of Node.js on ppc64 that are broken on Power >=9 architectures.
85
85
  let useWasmSIMD = true
86
- if (process.arch === 'ppc64') {
86
+ if (process.arch === 'riscv64') {
87
+ useWasmSIMD = false
88
+ } else if (process.arch === 'ppc64') {
87
89
  const [major, minor] = process.versions.node.split('.').map(n => parseInt(n, 10))
88
90
  if (major < 24 || (major === 24 && minor < 12)) {
89
91
  useWasmSIMD = false
@@ -47,7 +47,6 @@ const {
47
47
  const { channels } = require('../core/diagnostics.js')
48
48
 
49
49
  const kOpenStreams = Symbol('open streams')
50
- const kRequestStreamId = Symbol('request stream id')
51
50
  const kRequestStream = Symbol('request stream')
52
51
  const kRequestStreamCleanup = Symbol('request stream cleanup')
53
52
  const kRequestStreamState = Symbol('request stream state')
@@ -61,6 +60,15 @@ const kRefusedStreamRetry = Symbol('refused stream retry')
61
60
  // event loop.
62
61
  const MAX_GOAWAY_REPLAY_ATTEMPTS = 1
63
62
 
63
+ // RFC 9113 section 6.2. node:http2 reports frame types as raw numbers.
64
+ const HTTP2_FRAME_TYPE_HEADERS = 1
65
+
66
+ // Lower bound on how long a liveness PING may take to be acked. Stream
67
+ // timeouts can be tiny (tens of ms), while an ack on a live connection can take
68
+ // longer than that on a loaded event loop; without a floor a slow but healthy
69
+ // connection would be torn down.
70
+ const MIN_PROBE_TIMEOUT = 1e3
71
+
64
72
  let extractBody
65
73
 
66
74
  /** @type {import('http2')} */
@@ -127,7 +135,9 @@ function getGoAwayPendingIdx (client, lastStreamID) {
127
135
  continue
128
136
  }
129
137
 
130
- if (typeof request[kRequestStreamId] !== 'number' || request[kRequestStreamId] > maxAcceptedStreamID) {
138
+ // A pending stream may not have had an ID when it was bound to the request.
139
+ const streamId = request[kRequestStream]?.id
140
+ if (typeof streamId !== 'number' || streamId > maxAcceptedStreamID) {
131
141
  return i
132
142
  }
133
143
  }
@@ -136,7 +146,6 @@ function getGoAwayPendingIdx (client, lastStreamID) {
136
146
  }
137
147
 
138
148
  function detachRequestFromStream (request) {
139
- request[kRequestStreamId] = null
140
149
  request[kRequestStream] = null
141
150
  request[kRequestStreamCleanup] = null
142
151
  }
@@ -146,7 +155,6 @@ function bindRequestToStream (request, stream, cleanup) {
146
155
  const previousStream = request[kRequestStream]
147
156
  detachRequestFromStream(request)
148
157
  previousCleanup?.(previousStream)
149
- request[kRequestStreamId] = stream.id
150
158
  request[kRequestStream] = stream
151
159
  request[kRequestStreamCleanup] = cleanup
152
160
  }
@@ -247,8 +255,14 @@ function severRequestStream (stream) {
247
255
  closeStreamSession(stream)
248
256
  }
249
257
 
258
+ // #5936: Node can still deliver a session-level error to a native stream
259
+ // after undici has stopped tracking it (e.g. on idle session teardown). Keep
260
+ // a persistent noop error sink so the 'error' event is never emitted with no
261
+ // listener, which would crash the process. A single sink is enough even if
262
+ // one was already attached by the onError path, so clear it first.
250
263
  if (!stream.destroyed && !stream.closed) {
251
- stream.once('error', noop)
264
+ stream.off('error', noop)
265
+ stream.on('error', noop)
252
266
  }
253
267
  }
254
268
 
@@ -277,6 +291,9 @@ function connectH2 (client, socket) {
277
291
  // Armed while the peer advertises MAX_CONCURRENT_STREAMS = 0 and we have
278
292
  // work that cannot start. See setNoStreamsTimeout.
279
293
  noStreamsTimeout: null,
294
+ // Armed while a PING checks whether the peer is still there after a
295
+ // stream timed out. See probeHttp2Session.
296
+ probeTimeout: null,
280
297
  // Sockets start out ref'd. Session ref/unref proxies to the socket, so a
281
298
  // single cached flag lets us skip redundant uv ref/unref calls, provided
282
299
  // every ref/unref of the session or its socket goes through
@@ -361,6 +378,11 @@ function connectH2 (client, socket) {
361
378
  return true
362
379
  }
363
380
 
381
+ // Do not open streams on a connection that may be dead.
382
+ if (session[kHTTP2SessionState].probeTimeout != null) {
383
+ return true
384
+ }
385
+
364
386
  if (client[kRunning] >= client[kMaxConcurrentStreams]) {
365
387
  return true
366
388
  }
@@ -494,6 +516,60 @@ function onNoStreamsTimeout (session) {
494
516
  resetHttp2Session(session, err)
495
517
  }
496
518
 
519
+ // A stream timeout only resets that stream, unlike HTTP/1.1 which destroys the
520
+ // socket. If the connection itself silently died (dropped by a NAT or load
521
+ // balancer, a hung peer), every new stream would time out in turn and the
522
+ // session would never be replaced. Ask the peer for a PING ack within the
523
+ // timeout that just fired (but at least MIN_PROBE_TIMEOUT): if it answers, only
524
+ // that request was slow; if not, drop the session so queued requests move to a
525
+ // fresh connection.
526
+ function probeHttp2Session (session, timeout) {
527
+ const state = session[kHTTP2SessionState]
528
+
529
+ if (state.probeTimeout != null || session.closed || session.destroyed) {
530
+ return
531
+ }
532
+
533
+ try {
534
+ session.ping(onHttp2ProbeAck.bind(session))
535
+ } catch {
536
+ // The session is going away on its own.
537
+ return
538
+ }
539
+
540
+ state.probeTimeout = setTimeout(onHttp2ProbeTimeout, Math.max(timeout, MIN_PROBE_TIMEOUT), session).unref()
541
+ }
542
+
543
+ function clearHttp2ProbeTimeout (session) {
544
+ const state = session[kHTTP2SessionState]
545
+
546
+ if (state?.probeTimeout != null) {
547
+ clearTimeout(state.probeTimeout)
548
+ state.probeTimeout = null
549
+ }
550
+ }
551
+
552
+ function onHttp2ProbeAck () {
553
+ if (this[kHTTP2SessionState].probeTimeout == null) {
554
+ return
555
+ }
556
+
557
+ clearHttp2ProbeTimeout(this)
558
+ this[kClient][kResume]()
559
+ }
560
+
561
+ function onHttp2ProbeTimeout (session) {
562
+ session[kHTTP2SessionState].probeTimeout = null
563
+
564
+ if (session.closed || session.destroyed) {
565
+ return
566
+ }
567
+
568
+ const err = new SocketError('HTTP/2: connection unresponsive', util.getSocketInfo(session[kSocket]))
569
+ session[kError] = err
570
+ resetHttp2Session(session, err)
571
+ }
572
+
497
573
  function clearHttp2IdleTimeout (session) {
498
574
  const state = session[kHTTP2SessionState]
499
575
 
@@ -664,16 +740,18 @@ function onHttp2SessionGoAway (errorCode, lastStreamID) {
664
740
  }
665
741
  }
666
742
 
667
- for (let i = 0; i < streamsToClose.length; i++) {
668
- closeStream(streamsToClose[i])
669
- }
670
-
671
743
  if (pendingIdx !== previousPendingIdx) {
672
744
  const remainingPendingRequests = client[kQueue].slice(previousPendingIdx)
673
745
  client[kQueue].length = pendingIdx
674
746
  client[kQueue].push(...retriableRequests, ...remainingPendingRequests)
675
747
  }
676
748
 
749
+ // Publish the rebuilt queue and detach the session before closing anything.
750
+ // A synchronous sibling HEADERS frameError can requeue an accepted-but-unsent
751
+ // request and resume the client. It must see the final indices and must not
752
+ // dispatch its retry on the session that is being retired.
753
+ client[kPendingIdx] = pendingIdx
754
+
677
755
  if (client[kHTTP2Session] === this) {
678
756
  client[kSocket] = null
679
757
  client[kHTTPContext] = null
@@ -686,13 +764,16 @@ function onHttp2SessionGoAway (errorCode, lastStreamID) {
686
764
 
687
765
  clearHttp2IdleTimeout(this)
688
766
  clearNoStreamsTimeout(this)
767
+ clearHttp2ProbeTimeout(this)
768
+
769
+ for (let i = 0; i < streamsToClose.length; i++) {
770
+ closeStream(streamsToClose[i])
771
+ }
689
772
 
690
773
  if (!this.closed && !this.destroyed) {
691
774
  this.close()
692
775
  }
693
776
 
694
- client[kPendingIdx] = pendingIdx
695
-
696
777
  client.emit('disconnect', client[kUrl], [client], err)
697
778
 
698
779
  client[kResume]()
@@ -711,6 +792,7 @@ function onHttp2SessionClose () {
711
792
 
712
793
  clearHttp2IdleTimeout(this)
713
794
  clearNoStreamsTimeout(this)
795
+ clearHttp2ProbeTimeout(this)
714
796
 
715
797
  if (state.ping.interval != null) {
716
798
  clearInterval(state.ping.interval)
@@ -798,8 +880,8 @@ function closeStreamSession (stream) {
798
880
  }
799
881
 
800
882
  function onUpgradeStreamClose () {
801
- this.off('error', noop)
802
-
883
+ // #5936: Retain the noop error sink so a session-level error delivered to
884
+ // this stream after undici detaches it cannot crash via an unhandled 'error'.
803
885
  const state = this[kRequestStreamState]
804
886
  this[kRequestStreamState] = null
805
887
 
@@ -903,8 +985,11 @@ function releaseUpgradeStream (stream) {
903
985
 
904
986
  removeUpgradeStreamListeners(stream)
905
987
 
988
+ // #5936: removeUpgradeStreamListeners() dropped the noop sink; re-attach a
989
+ // persistent one so a late session-level error on this (possibly still native
990
+ // tracked) stream cannot crash via an unhandled 'error'.
906
991
  if (!stream.destroyed && !stream.closed) {
907
- stream.once('error', noop)
992
+ stream.on('error', noop)
908
993
  }
909
994
  }
910
995
 
@@ -1337,12 +1422,14 @@ function releaseRequestStream (stream) {
1337
1422
  detachRequestFromStream(request)
1338
1423
  }
1339
1424
 
1340
- // A closed or destroyed stream cannot emit further events; leaving the
1341
- // listeners in place saves the removal scans (they are collected with
1342
- // the stream). All handlers bail out when the stream state is gone.
1425
+ // #5936: Node can deliver a session-level error to a released stream before
1426
+ // its native handle is dropped (e.g. on idle session teardown). Attach a
1427
+ // persistent noop error sink so a late 'error' always has a listener and
1428
+ // cannot crash the process. A closed/destroyed stream cannot emit further
1429
+ // events and is no longer tracked natively, so skip the listener teardown.
1343
1430
  if (!stream.destroyed && !stream.closed) {
1344
1431
  removeRequestStreamListeners(stream)
1345
- stream.once('error', noop)
1432
+ stream.on('error', noop)
1346
1433
  }
1347
1434
  }
1348
1435
 
@@ -1537,10 +1624,43 @@ function retryRefusedStream (stream, state) {
1537
1624
  // SHOULD NOT automatically retry the same request more than once.
1538
1625
  request[kRefusedStreamRetry] = true
1539
1626
 
1627
+ // The peer only reset this stream, so the HTTP/2 session remains usable for
1628
+ // the retry.
1629
+ requeueStreamRequest(client, state)
1630
+
1631
+ return true
1632
+ }
1633
+
1634
+ // nghttp2 refuses to send the HEADERS of a stream opened before a GOAWAY was
1635
+ // received but flushed after it. The peer never saw the request, so it can be
1636
+ // replayed on a new connection whatever its method. A GOAWAY whose
1637
+ // lastStreamID covers the stream (e.g. 2^31-1, a graceful shutdown notice)
1638
+ // leaves the stream attached to the session, so this is the only signal.
1639
+ function retryUnsentStream (state) {
1640
+ const { client, request, session } = state
1641
+
1642
+ if (
1643
+ !session[kReceivedGoAway] ||
1644
+ state.responseReceived ||
1645
+ request.aborted ||
1646
+ request.completed ||
1647
+ !canReplayRequest(request) ||
1648
+ !registerGoAwayRefusal(request)
1649
+ ) {
1650
+ return false
1651
+ }
1652
+
1653
+ requeueStreamRequest(client, state)
1654
+
1655
+ return true
1656
+ }
1657
+
1658
+ function requeueStreamRequest (client, state) {
1659
+ const { request } = state
1660
+
1540
1661
  // Detach the failed attempt before moving the request back to the pending
1541
- // queue. The peer only reset this stream, so the HTTP/2 session remains
1542
- // usable for the retry. Severing also drops the 'close' listener, so the
1543
- // abandoned stream cannot later complete the retried request.
1662
+ // queue. Severing also drops the 'close' listener, so the abandoned stream
1663
+ // cannot later complete the retried request.
1544
1664
  detachRequestStreamForClose(request)
1545
1665
  state.stream = null
1546
1666
  state.requestFinalized = true
@@ -1548,8 +1668,6 @@ function retryRefusedStream (stream, state) {
1548
1668
  completeRequest(client, request)
1549
1669
  client[kQueue].splice(client[kPendingIdx], 0, request)
1550
1670
  client[kResume]()
1551
-
1552
- return true
1553
1671
  }
1554
1672
 
1555
1673
  function onError (err) {
@@ -1561,6 +1679,10 @@ function onError (err) {
1561
1679
  }
1562
1680
 
1563
1681
  stream.off('error', onError)
1682
+ // #5936: The stream has already errored, but Node may destroy it again with a
1683
+ // session-level error before the native handle is released. Keep a persistent
1684
+ // noop error sink so that re-delivery cannot go unhandled.
1685
+ stream.on('error', noop)
1564
1686
 
1565
1687
  // Node's HTTP/2 implementation can turn an incomplete Content-Length body
1566
1688
  // into a protocol stream error instead of emitting 'end'. Prefer the
@@ -1592,6 +1714,11 @@ function onFrameError (type, code) {
1592
1714
  }
1593
1715
 
1594
1716
  stream.off('frameError', onFrameError)
1717
+
1718
+ if (type === HTTP2_FRAME_TYPE_HEADERS && retryUnsentStream(state)) {
1719
+ return
1720
+ }
1721
+
1595
1722
  state.abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`))
1596
1723
  }
1597
1724
 
@@ -1610,9 +1737,14 @@ function onTimeout () {
1610
1737
  // Remove self so timeout doesn't fire again after we handle it
1611
1738
  stream.off('timeout', onTimeout)
1612
1739
 
1613
- const err = state.responseReceived
1614
- ? new BodyTimeoutError(`HTTP/2: "stream timeout after ${state.bodyTimeout}"`)
1615
- : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${state.headersTimeout}"`)
1740
+ const { responseReceived, session, bodyTimeout, headersTimeout } = state
1741
+ const err = responseReceived
1742
+ ? new BodyTimeoutError(`HTTP/2: "stream timeout after ${bodyTimeout}"`)
1743
+ : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${headersTimeout}"`)
1744
+
1745
+ // Probe before aborting: completing the request resumes the queue, which
1746
+ // must not open new streams until the peer has proven it is alive.
1747
+ probeHttp2Session(session, responseReceived ? bodyTimeout : headersTimeout)
1616
1748
  state.abort(err)
1617
1749
  }
1618
1750
 
@@ -52,7 +52,8 @@ const EVENT_HEADERS_SIZE = 19
52
52
  let miloPackage
53
53
 
54
54
  // We disable wasm SIMD on ppc64 as it seems to be broken on Power 9 architectures.
55
- let useWasmSIMD = process.arch !== 'ppc64'
55
+ // We disable wasm SIMD on riscv64 as it seems to be broken on there as well.
56
+ let useWasmSIMD = (process.arch !== 'riscv64' && process.arch !== 'ppc64')
56
57
  // The Env Variable UNDICI_NO_WASM_SIMD allows explicitly overriding the default behavior.
57
58
  if (process.env.UNDICI_NO_WASM_SIMD === '1') {
58
59
  useWasmSIMD = false
@@ -1,5 +1,6 @@
1
1
  'use strict'
2
2
 
3
+ const { AsyncResource } = require('node:async_hooks')
3
4
  const { PoolStats } = require('../util/stats.js')
4
5
  const DispatcherBase = require('./dispatcher-base')
5
6
  const FixedQueue = require('./fixed-queue')
@@ -26,6 +27,22 @@ const kRetiring = Symbol('retiring clients')
26
27
  // Closes every live client, including clients that have been
27
28
  // taken out of rotation but are still finishing their own
28
29
  // requests.
30
+ // Requests that wait in the Pool queue are dispatched later from whichever
31
+ // callback drains the queue (another request's connect, drain, ...). Capture
32
+ // the caller's async context so Client#dispatch, and the diagnostics channel
33
+ // events it publishes, still run in it.
34
+ class QueuedRequest extends AsyncResource {
35
+ constructor (opts, handler) {
36
+ super('UNDICI_POOL_QUEUED_REQUEST')
37
+ this.opts = opts
38
+ this.handler = handler
39
+ }
40
+
41
+ dispatch (dispatcher) {
42
+ return this.runInAsyncScope(dispatcher.dispatch, dispatcher, this.opts, this.handler)
43
+ }
44
+ }
45
+
29
46
  function closeClients (pool) {
30
47
  const closeAll = []
31
48
  for (let i = 0; i < pool[kClients].length; i++) {
@@ -69,7 +86,7 @@ class PoolBase extends DispatcherBase {
69
86
  break
70
87
  }
71
88
  this[kQueued]--
72
- needDrain = !client.dispatch(item.opts, item.handler)
89
+ needDrain = !item.dispatch(client)
73
90
  }
74
91
 
75
92
  client[kNeedDrain] = needDrain
@@ -114,7 +131,7 @@ class PoolBase extends DispatcherBase {
114
131
  const item = queue.shift()
115
132
  this[kQueued]--
116
133
 
117
- if (!dispatcher.dispatch(item.opts, item.handler)) {
134
+ if (!item.dispatch(dispatcher)) {
118
135
  dispatcher[kNeedDrain] = true
119
136
  this[kOnClientBusy](dispatcher)
120
137
  hasDispatcher = this[kHasDispatcher]()
@@ -228,7 +245,7 @@ class PoolBase extends DispatcherBase {
228
245
 
229
246
  if (!dispatcher) {
230
247
  this[kNeedDrain] = true
231
- this[kQueue].push({ opts, handler })
248
+ this[kQueue].push(new QueuedRequest(opts, handler))
232
249
  this[kQueued]++
233
250
  } else if (!dispatcher.dispatch(opts, handler)) {
234
251
  dispatcher[kNeedDrain] = true