api-request.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. 'use strict'
  2. const assert = require('node:assert')
  3. const { AsyncResource } = require('node:async_hooks')
  4. const { Readable } = require('./readable')
  5. const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
  6. const util = require('../core/util')
  7. function noop () {}
  8. class RequestHandler extends AsyncResource {
  9. constructor (opts, callback) {
  10. if (!opts || typeof opts !== 'object') {
  11. throw new InvalidArgumentError('invalid opts')
  12. }
  13. const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts
  14. try {
  15. if (typeof callback !== 'function') {
  16. throw new InvalidArgumentError('invalid callback')
  17. }
  18. if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
  19. throw new InvalidArgumentError('invalid highWaterMark')
  20. }
  21. if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
  22. throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
  23. }
  24. if (method === 'CONNECT') {
  25. throw new InvalidArgumentError('invalid method')
  26. }
  27. if (onInfo && typeof onInfo !== 'function') {
  28. throw new InvalidArgumentError('invalid onInfo callback')
  29. }
  30. super('UNDICI_REQUEST')
  31. } catch (err) {
  32. if (util.isStream(body)) {
  33. util.destroy(body.on('error', noop), err)
  34. }
  35. throw err
  36. }
  37. this.method = method
  38. this.responseHeaders = responseHeaders || null
  39. this.opaque = opaque || null
  40. this.callback = callback
  41. this.res = null
  42. this.abort = null
  43. this.body = body
  44. this.trailers = {}
  45. this.context = null
  46. this.onInfo = onInfo || null
  47. this.highWaterMark = highWaterMark
  48. this.reason = null
  49. this.removeAbortListener = null
  50. if (signal?.aborted) {
  51. this.reason = signal.reason ?? new RequestAbortedError()
  52. } else if (signal) {
  53. this.removeAbortListener = util.addAbortListener(signal, () => {
  54. this.reason = signal.reason ?? new RequestAbortedError()
  55. if (this.res) {
  56. util.destroy(this.res.on('error', noop), this.reason)
  57. } else if (this.abort) {
  58. this.abort(this.reason)
  59. }
  60. })
  61. }
  62. }
  63. onConnect (abort, context) {
  64. if (this.reason) {
  65. abort(this.reason)
  66. return
  67. }
  68. assert(this.callback)
  69. this.abort = abort
  70. this.context = context
  71. }
  72. onHeaders (statusCode, rawHeaders, resume, statusMessage) {
  73. const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
  74. const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
  75. if (statusCode < 200) {
  76. if (this.onInfo) {
  77. this.onInfo({ statusCode, headers })
  78. }
  79. return
  80. }
  81. const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
  82. const contentType = parsedHeaders['content-type']
  83. const contentLength = parsedHeaders['content-length']
  84. const res = new Readable({
  85. resume,
  86. abort,
  87. contentType,
  88. contentLength: this.method !== 'HEAD' && contentLength
  89. ? Number(contentLength)
  90. : null,
  91. highWaterMark
  92. })
  93. if (this.removeAbortListener) {
  94. res.on('close', this.removeAbortListener)
  95. this.removeAbortListener = null
  96. }
  97. this.callback = null
  98. this.res = res
  99. if (callback !== null) {
  100. try {
  101. this.runInAsyncScope(callback, null, null, {
  102. statusCode,
  103. statusText: statusMessage,
  104. headers,
  105. trailers: this.trailers,
  106. opaque,
  107. body: res,
  108. context
  109. })
  110. } catch (err) {
  111. // If the callback throws synchronously, we need to handle it
  112. // Remove reference to res to allow res being garbage collected
  113. this.res = null
  114. // Destroy the response stream
  115. util.destroy(res.on('error', noop), err)
  116. // Use queueMicrotask to re-throw the error so it reaches uncaughtException
  117. queueMicrotask(() => {
  118. throw err
  119. })
  120. }
  121. }
  122. }
  123. onData (chunk) {
  124. return this.res.push(chunk)
  125. }
  126. onComplete (trailers) {
  127. util.parseHeaders(trailers, this.trailers)
  128. this.res.push(null)
  129. }
  130. onError (err) {
  131. const { res, callback, body, opaque } = this
  132. if (callback) {
  133. // TODO: Does this need queueMicrotask?
  134. this.callback = null
  135. queueMicrotask(() => {
  136. this.runInAsyncScope(callback, null, err, { opaque })
  137. })
  138. }
  139. if (res) {
  140. this.res = null
  141. // Ensure all queued handlers are invoked before destroying res.
  142. queueMicrotask(() => {
  143. util.destroy(res.on('error', noop), err)
  144. })
  145. }
  146. if (body) {
  147. this.body = null
  148. if (util.isStream(body)) {
  149. body.on('error', noop)
  150. util.destroy(body, err)
  151. }
  152. }
  153. if (this.removeAbortListener) {
  154. this.removeAbortListener()
  155. this.removeAbortListener = null
  156. }
  157. }
  158. }
  159. function request (opts, callback) {
  160. if (callback === undefined) {
  161. return new Promise((resolve, reject) => {
  162. request.call(this, opts, (err, data) => {
  163. return err ? reject(err) : resolve(data)
  164. })
  165. })
  166. }
  167. try {
  168. const handler = new RequestHandler(opts, callback)
  169. this.dispatch(opts, handler)
  170. } catch (err) {
  171. if (typeof callback !== 'function') {
  172. throw err
  173. }
  174. const opaque = opts?.opaque
  175. queueMicrotask(() => callback(err, { opaque }))
  176. }
  177. }
  178. module.exports = request
  179. module.exports.RequestHandler = RequestHandler