Skip to content

Commit dc807ba

Browse files
committed
perf: dump immediatly if known size exceeds limit
1 parent c90af4a commit dc807ba

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

lib/api/api-request.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,8 @@ class RequestHandler extends AsyncResource {
9191

9292
const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
9393
const contentType = parsedHeaders['content-type']
94-
const body = new Readable({ resume, abort, contentType, highWaterMark })
94+
const contentLength = parsedHeaders['content-length']
95+
const body = new Readable({ resume, abort, contentType, contentLength, highWaterMark })
9596

9697
this.callback = null
9798
this.res = body

lib/api/readable.js

+11-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ const { ReadableStreamFrom } = require('../core/util')
1111
const kConsume = Symbol('kConsume')
1212
const kReading = Symbol('kReading')
1313
const kBody = Symbol('kBody')
14-
const kAbort = Symbol('abort')
14+
const kAbort = Symbol('kAbort')
1515
const kContentType = Symbol('kContentType')
16+
const kContentLength = Symbol('kContentLength')
1617

1718
const noop = () => {}
1819

@@ -21,6 +22,7 @@ module.exports = class BodyReadable extends Readable {
2122
resume,
2223
abort,
2324
contentType = '',
25+
contentLength,
2426
highWaterMark = 64 * 1024 // Same as nodejs fs streams.
2527
}) {
2628
super({
@@ -29,12 +31,15 @@ module.exports = class BodyReadable extends Readable {
2931
highWaterMark
3032
})
3133

34+
contentLength = contentLength != null ? Number(contentLength) : null
35+
3236
this._readableState.dataEmitted = false
3337

3438
this[kAbort] = abort
3539
this[kConsume] = null
3640
this[kBody] = null
3741
this[kContentType] = contentType
42+
this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null
3843

3944
// Is stream being consumed through Readable API?
4045
// This is an optimization so that we avoid checking
@@ -146,7 +151,7 @@ module.exports = class BodyReadable extends Readable {
146151
}
147152

148153
async dump (opts) {
149-
let limit = Number.isFinite(opts?.limit) ? opts.limit : 262144
154+
let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024
150155
const signal = opts?.signal
151156

152157
if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) {
@@ -160,6 +165,10 @@ module.exports = class BodyReadable extends Readable {
160165
}
161166

162167
return await new Promise((resolve, reject) => {
168+
if (this[kContentLength] > limit) {
169+
this.destroy(new AbortError())
170+
}
171+
163172
const onAbort = () => {
164173
this.destroy(signal.reason ?? new AbortError())
165174
}

0 commit comments

Comments
 (0)