api-request.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. this.runInAsyncScope(callback, null, null, {
  101. statusCode,
  102. headers,
  103. trailers: this.trailers,
  104. opaque,
  105. body: res,
  106. context
  107. })
  108. }
  109. }
  110. onData (chunk) {
  111. return this.res.push(chunk)
  112. }
  113. onComplete (trailers) {
  114. util.parseHeaders(trailers, this.trailers)
  115. this.res.push(null)
  116. }
  117. onError (err) {
  118. const { res, callback, body, opaque } = this
  119. if (callback) {
  120. // TODO: Does this need queueMicrotask?
  121. this.callback = null
  122. queueMicrotask(() => {
  123. this.runInAsyncScope(callback, null, err, { opaque })
  124. })
  125. }
  126. if (res) {
  127. this.res = null
  128. // Ensure all queued handlers are invoked before destroying res.
  129. queueMicrotask(() => {
  130. util.destroy(res.on('error', noop), err)
  131. })
  132. }
  133. if (body) {
  134. this.body = null
  135. if (util.isStream(body)) {
  136. body.on('error', noop)
  137. util.destroy(body, err)
  138. }
  139. }
  140. if (this.removeAbortListener) {
  141. this.removeAbortListener()
  142. this.removeAbortListener = null
  143. }
  144. }
  145. }
  146. function request (opts, callback) {
  147. if (callback === undefined) {
  148. return new Promise((resolve, reject) => {
  149. request.call(this, opts, (err, data) => {
  150. return err ? reject(err) : resolve(data)
  151. })
  152. })
  153. }
  154. try {
  155. const handler = new RequestHandler(opts, callback)
  156. this.dispatch(opts, handler)
  157. } catch (err) {
  158. if (typeof callback !== 'function') {
  159. throw err
  160. }
  161. const opaque = opts?.opaque
  162. queueMicrotask(() => callback(err, { opaque }))
  163. }
  164. }
  165. module.exports = request
  166. module.exports.RequestHandler = RequestHandler