perf(http): read a declared-length fetch body with arrayBuffer()
The chunked reader added for the incremental 413 (4d1639f) cut a Bun JSON
POST by more than half: 37.6k -> 11.7k req/s on jarvis. A well-formed
Content-Length inside the limit already bounds the body, because the
runtime frames it by that header, so arrayBuffer() is safe there and native
in Bun, Deno and workerd. byteLength is still checked for a Request built in
user code whose header and body disagree. Chunked uploads keep the bounded
read.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+31
No files matched your search
@@ -130,6 +130,20 @@ function readFetchBytes(
|
||||
return tooLarge(request, opts);
|
||||
}
|
||||
|
||||
// A well-formed declared length within the limit bounds the body already: the runtime's HTTP parser
|
||||
// frames it by that header, so `arrayBuffer()`, native in Bun, Deno and workerd, cannot overrun.
|
||||
// The reader loop below measured 4x slower on a Bun JSON POST. `byteLength` is still checked, for
|
||||
// a `Request` built in user code whose header and body disagree.
|
||||
if (/^\d+$/.test(request.headers.get('content-length') ?? '')) {
|
||||
return request
|
||||
.arrayBuffer()
|
||||
.then((buffer) =>
|
||||
buffer.byteLength > limit
|
||||
? tooLarge(request, opts)
|
||||
: { bytes: buffer.byteLength === 0 ? undefined : Buffer.from(buffer) },
|
||||
);
|
||||
}
|
||||
|
||||
// ponytail: one reader loop; a TransformStream byte-counter only if another consumer needs it
|
||||
return readBounded(request.body.getReader(), limit).then((bytes) =>
|
||||
bytes === null ? tooLarge(request, opts) : { bytes },
|
||||
|
||||
Reference in new issue
Block a user