dump.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. 'use strict'
  2. const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
  3. const DecoratorHandler = require('../handler/decorator-handler')
  4. class DumpHandler extends DecoratorHandler {
  5. #maxSize = 1024 * 1024
  6. #dumped = false
  7. #size = 0
  8. #controller = null
  9. aborted = false
  10. reason = false
  11. constructor ({ maxSize, signal }, handler) {
  12. if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
  13. throw new InvalidArgumentError('maxSize must be a number greater than 0')
  14. }
  15. super(handler)
  16. this.#maxSize = maxSize ?? this.#maxSize
  17. // this.#handler = handler
  18. }
  19. #abort (reason) {
  20. this.aborted = true
  21. this.reason = reason
  22. }
  23. onRequestStart (controller, context) {
  24. controller.abort = this.#abort.bind(this)
  25. this.#controller = controller
  26. return super.onRequestStart(controller, context)
  27. }
  28. onResponseStart (controller, statusCode, headers, statusMessage) {
  29. const contentLength = headers['content-length']
  30. if (contentLength != null && contentLength > this.#maxSize) {
  31. throw new RequestAbortedError(
  32. `Response size (${contentLength}) larger than maxSize (${
  33. this.#maxSize
  34. })`
  35. )
  36. }
  37. if (this.aborted === true) {
  38. return true
  39. }
  40. return super.onResponseStart(controller, statusCode, headers, statusMessage)
  41. }
  42. onResponseError (controller, err) {
  43. if (this.#dumped) {
  44. return
  45. }
  46. err = this.#controller.reason ?? err
  47. super.onResponseError(controller, err)
  48. }
  49. onResponseData (controller, chunk) {
  50. this.#size = this.#size + chunk.length
  51. if (this.#size >= this.#maxSize) {
  52. this.#dumped = true
  53. if (this.aborted === true) {
  54. super.onResponseError(controller, this.reason)
  55. } else {
  56. super.onResponseEnd(controller, {})
  57. }
  58. }
  59. return true
  60. }
  61. onResponseEnd (controller, trailers) {
  62. if (this.#dumped) {
  63. return
  64. }
  65. if (this.#controller.aborted === true) {
  66. super.onResponseError(controller, this.reason)
  67. return
  68. }
  69. super.onResponseEnd(controller, trailers)
  70. }
  71. }
  72. function createDumpInterceptor (
  73. { maxSize: defaultMaxSize } = {
  74. maxSize: 1024 * 1024
  75. }
  76. ) {
  77. return dispatch => {
  78. return function Intercept (opts, handler) {
  79. const { dumpMaxSize = defaultMaxSize } = opts
  80. const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler)
  81. return dispatch(opts, dumpHandler)
  82. }
  83. }
  84. }
  85. module.exports = createDumpInterceptor