-
-
Notifications
You must be signed in to change notification settings - Fork 436
Improve body size estimation #734
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Richienb
wants to merge
5
commits into
sindresorhus:main
Choose a base branch
from
Richienb:better-body-size
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+187
−26
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,7 @@ | ||
| import type {Options} from '../types/options.js'; | ||
| import {usualFormBoundarySize} from '../core/constants.js'; | ||
| import {initialFormSize, formBoundarySize} from '../core/constants.js'; | ||
|
|
||
| const encoder = new TextEncoder(); | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/ban-types | ||
| export const getBodySize = (body?: BodyInit | null): number => { | ||
|
|
@@ -8,14 +10,19 @@ export const getBodySize = (body?: BodyInit | null): number => { | |
| } | ||
|
|
||
| if (body instanceof FormData) { | ||
| // This is an approximation, as FormData size calculation is not straightforward | ||
| let size = 0; | ||
| let size = initialFormSize; | ||
|
|
||
| for (const [key, value] of body) { | ||
| size += usualFormBoundarySize; | ||
| size += new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"`).length; | ||
| size += formBoundarySize; | ||
| size += encoder.encode(key).byteLength; | ||
|
|
||
| if (value instanceof Blob) { | ||
| size += encoder.encode(`; filename="${value.name ?? 'blob'}"`).byteLength; | ||
| size += encoder.encode(`\r\nContent-Type: ${value.type || 'application/octet-stream'}`).byteLength; | ||
|
Comment on lines
+20
to
+21
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Another improvement I want to make is use difference calculations instead of hard-coding these strings |
||
| } | ||
|
|
||
| size += typeof value === 'string' | ||
| ? new TextEncoder().encode(value).length | ||
| ? encoder.encode(value).byteLength | ||
| : value.size; | ||
| } | ||
|
|
||
|
|
@@ -26,29 +33,16 @@ export const getBodySize = (body?: BodyInit | null): number => { | |
| return body.size; | ||
| } | ||
|
|
||
| if (body instanceof ArrayBuffer) { | ||
| if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) { | ||
| return body.byteLength; | ||
| } | ||
|
|
||
| if (typeof body === 'string') { | ||
| return new TextEncoder().encode(body).length; | ||
| return encoder.encode(body).byteLength; | ||
| } | ||
|
|
||
| if (body instanceof URLSearchParams) { | ||
| return new TextEncoder().encode(body.toString()).length; | ||
| } | ||
|
|
||
| if ('byteLength' in body) { | ||
| return (body).byteLength; | ||
| } | ||
|
|
||
| if (typeof body === 'object' && body !== null) { | ||
| try { | ||
| const jsonString = JSON.stringify(body); | ||
| return new TextEncoder().encode(jsonString).length; | ||
| } catch { | ||
| return 0; | ||
| } | ||
| return encoder.encode(body.toString()).byteLength; | ||
| } | ||
|
|
||
| return 0; // Default case, unable to determine size | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import test, {type ExecutionContext} from 'ava'; | ||
| import {getBodySize} from '../source/utils/body.js'; | ||
| import {createLargeBlob} from './helpers/create-large-file.js'; | ||
|
|
||
| async function testBodySize(t: ExecutionContext, body: unknown) { | ||
| const actualSize = getBodySize(body); | ||
| const expectedBytes = await new Response(body).arrayBuffer(); | ||
| const expectedSize = expectedBytes.byteLength; | ||
| const expectedText = new TextDecoder().decode(expectedBytes); | ||
|
|
||
| t.is(actualSize, expectedSize, `\`${expectedText}\` predicted body size (${actualSize}) not actual size ${expectedSize}`); | ||
| } | ||
|
|
||
| const encoder = new TextEncoder(); | ||
| const encoded = encoder.encode('unicorn'); | ||
| const encoded2 = encoder.encode('abcd'); | ||
| const encoded4 = encoder.encode('abcdefgh'); | ||
| const encoded8 = encoder.encode('abcdefghabcdefgh'); | ||
|
|
||
| // Test all supported body types (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#setting_a_body) | ||
| test('string', async t => { | ||
| await testBodySize(t, 'unicorn'); | ||
| }); | ||
|
|
||
| test('multi-byte string', async t => { | ||
| await testBodySize(t, '😍'); | ||
| }); | ||
|
|
||
| test('ArrayBuffer', async t => { | ||
| await testBodySize(t, encoded.buffer); | ||
| }); | ||
|
|
||
| test('TypedArray', async t => { | ||
| await testBodySize(t, encoded); | ||
| await testBodySize(t, new Uint8Array(encoded)); | ||
| await testBodySize(t, new Uint8ClampedArray(encoded)); | ||
| await testBodySize(t, new Int8Array(encoded)); | ||
|
|
||
| await testBodySize(t, new Uint16Array(encoded2.buffer)); | ||
| await testBodySize(t, new Int16Array(encoded2.buffer)); | ||
|
|
||
| await testBodySize(t, new Uint32Array(encoded4.buffer)); | ||
| await testBodySize(t, new Int32Array(encoded4.buffer)); | ||
| await testBodySize(t, new Float32Array(encoded4.buffer)); | ||
|
|
||
| await testBodySize(t, new Float64Array(encoded8.buffer)); | ||
|
|
||
| await testBodySize(t, new BigInt64Array(encoded8.buffer)); | ||
| await testBodySize(t, new BigUint64Array(encoded8.buffer)); | ||
| }); | ||
|
|
||
| test('DataView', async t => { | ||
| await testBodySize(t, new DataView(encoded.buffer)); | ||
| }); | ||
|
|
||
| test('Blob', async t => { | ||
| // Test with different combinations of parameters, file type, content type, filename, etc. | ||
| await testBodySize(t, new Blob(['unicorn'], {type: 'text/plain'})); | ||
| await testBodySize(t, new Blob(['unicorn'], {type: 'customtype'})); | ||
| await testBodySize(t, new Blob(['unicorn'])); | ||
| }); | ||
|
|
||
| test('File', async t => { | ||
| await testBodySize(t, new File(['unicorn'], 'unicorn.txt', {type: 'text/plain'})); | ||
| await testBodySize(t, new File(['unicorn'], 'unicorn.txt')); | ||
| await testBodySize(t, new File(['😍'], '😍.txt')); | ||
| }); | ||
|
|
||
| test('URLSearchParams', async t => { | ||
| await testBodySize(t, new URLSearchParams({foo: 'bar', baz: 'qux 😍'})); | ||
| }); | ||
|
|
||
| test('FormData - string', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('field', 'value'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - multiple strings', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('field1', 'value1'); | ||
| formData.append('field2', 'value2'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - blob', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('file', new Blob(['test content'])); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - blob with filename', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('file', new Blob(['test content']), 'test.txt'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - multiple fields', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('file', new Blob(['test content']), 'test.txt'); | ||
| formData.append('field1', 'value1'); | ||
| formData.append('field2', 'value2'); | ||
| formData.append('emoji', '😍'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - blob from buffer', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('file', new Blob([encoded]), 'test.txt'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - blob with content type', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('file', new Blob(['test content'], {type: 'text/plain'}), 'test.txt'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - multiple blobs', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('file1', new Blob(['file content 1'], {type: 'text/plain'}), 'file1.txt'); | ||
| formData.append('file2', new Blob(['file content 2'], {type: 'text/plain'}), 'file2.txt'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - file', async t => { | ||
| const formData = new FormData(); | ||
| formData.append('file', new File(['test content'], 'test.txt', {type: 'text/plain'})); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test('FormData - large blob', async t => { | ||
| const largeBlob = createLargeBlob(10); // 10MB Blob | ||
| const formData = new FormData(); | ||
| formData.append('file', largeBlob, 'large-file.bin'); | ||
| await testBodySize(t, formData); | ||
| }); | ||
|
|
||
| test.failing('ReadableStream', async t => { | ||
| const stream = new ReadableStream({ | ||
| start(controller) { | ||
| controller.enqueue(encoder.encode('unicorn')); | ||
| controller.close(); | ||
| }, | ||
| }); | ||
|
|
||
| await testBodySize(t, stream); | ||
| }); | ||
|
|
||
| test('null and undefined (no body)', async t => { | ||
| await testBodySize(t, null); | ||
| await testBodySize(t, undefined); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we simplify this whole function by using a temporary response, like you did for forms?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using
Responseto get the size consumes the entire body, as opposed to using size/length properties which we currently do when possible.We don't want
kyto consume the entire request body twice, as opposed to the underlyingfetchAPI that doesn't do that. If we had to, and this might not be so bad, is we might as well pass our constructed buffer right on through to thefetchrequest.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right that we don't want to consume the stream if the body is a stream. But we can't get
totalBytesfor a stream anyway. So I was thinking if the body is a stream, short-circuit with a size of 0.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, that's what we already do - ReadableStreams pass right through and return 0.
What I'm referring to is ArrayBuffers, or Files/Blobs in FormData, which contain a size property, and are also iterable. The latter is done by
new Response, the former is what we do.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I know that we already skip size checks for streams. And you have maintained that with these changes, which is great. But that's why your reply about consuming the body is confusing to me. All non-stream body types are simple objects that are not permanently consumed the way streams are.
If you mean that you want to avoid extra iterations on the body, as in O(n) vs O(n*2) performance, I think that's reasonable. But our main problem at the moment is correctness, not performance, and the network is going to be the limiting factor for performance. IMO, if we can leverage
Responseto calculate the size, then we should.There are also performance optimizations we could make, like only using
Responseto calculate the size for complex types likeFormData. We could also re-use theArrayBufferthat it generates in the process.