Files
SnowLuma/.pnpm-store/v11/files/22/80e0347febae9a1556d402ded583444be359fe777f07c86651dfeed8e18275388409e38fccdd3077e19bc46fad9bbc8eb4628f6715b3d53b7351287cf3dd8a
TanTan 2a69b23b47
Dev Build / cleanup (push) Canceled after 0s
Dev Build / typecheck (push) Canceled after 0s
Dev Build / build (linux-arm64, ubuntu-24.04-arm, linux-arm64) (push) Canceled after 0s
Dev Build / build (linux-x64, ubuntu-latest, linux-x64) (push) Canceled after 0s
Dev Build / build (win-x64, windows-latest, win32-x64) (push) Canceled after 0s
Dev Build / dispatch-dev-docker (push) Canceled after 0s
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

100 lines
2.4 KiB
Plaintext

'use strict'
const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
const DecoratorHandler = require('../handler/decorator-handler')
class DumpHandler extends DecoratorHandler {
#maxSize = 1024 * 1024
#dumped = false
#size = 0
aborted = false
reason = false
constructor ({ maxSize, signal }, handler) {
if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
throw new InvalidArgumentError('maxSize must be a number greater than 0')
}
super(handler)
this.#maxSize = maxSize ?? this.#maxSize
// this.#handler = handler
}
#abort (reason) {
this.aborted = true
this.reason = reason
}
onRequestStart (controller, context) {
controller.abort = this.#abort.bind(this)
return super.onRequestStart(controller, context)
}
onResponseStart (controller, statusCode, headers, statusMessage) {
const contentLength = headers['content-length']
if (contentLength != null && contentLength > this.#maxSize) {
throw new RequestAbortedError(
`Response size (${contentLength}) larger than maxSize (${
this.#maxSize
})`
)
}
if (this.aborted === true) {
return true
}
return super.onResponseStart(controller, statusCode, headers, statusMessage)
}
onResponseError (controller, err) {
super.onResponseError(controller, this.aborted === true ? this.reason : err)
}
onResponseData (controller, chunk) {
this.#size = this.#size + chunk.length
if (this.#size > this.#maxSize) {
throw new RequestAbortedError(
`Response size (${this.#size}) larger than maxSize (${this.#maxSize})`
)
}
if (this.#size === this.#maxSize) {
this.#dumped = true
}
return true
}
onResponseEnd (controller, trailers) {
if (this.aborted === true) {
super.onResponseError(controller, this.reason)
return
}
super.onResponseEnd(controller, this.#dumped ? {} : trailers)
}
}
function createDumpInterceptor (
{ maxSize: defaultMaxSize } = {
maxSize: 1024 * 1024
}
) {
return dispatch => {
return function Intercept (opts, handler) {
const { dumpMaxSize = defaultMaxSize } = opts
const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler)
return dispatch(opts, dumpHandler)
}
}
}
module.exports = createDumpInterceptor