Skip to content
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

perf(fetch): Improve fetch of detaurl #2479

Merged
merged 20 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
88 changes: 43 additions & 45 deletions lib/fetch/dataURL.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const assert = require('assert')
const { atob } = require('buffer')
const { isomorphicDecode } = require('./util')

const encoder = new TextEncoder()
Expand All @@ -8,7 +7,8 @@ const encoder = new TextEncoder()
* @see https://mimesniff.spec.whatwg.org/#http-token-code-point
*/
const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
const HTTP_WHITESPACE_REGEX = /[\u000A|\u000D|\u0009|\u0020]/ // eslint-disable-line
const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line
/**
* @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
*/
Expand All @@ -26,7 +26,7 @@ function dataURLProcessor (dataURL) {
let input = URLSerializer(dataURL, true)

// 3. Remove the leading "data:" string from input.
input = input.slice(5)
input = input.substring(5)

// 4. Let position point at the start of input.
const position = { position: 0 }
Expand Down Expand Up @@ -59,7 +59,7 @@ function dataURLProcessor (dataURL) {
position.position++

// 9. Let encodedBody be the remainder of input.
const encodedBody = input.slice(mimeTypeLength + 1)
const encodedBody = input.substring(mimeTypeLength + 1)

// 10. Let body be the percent-decoding of encodedBody.
let body = stringPercentDecode(encodedBody)
Expand Down Expand Up @@ -165,11 +165,11 @@ function collectASequenceOfCodePointsFast (char, input, position) {

if (idx === -1) {
position.position = input.length
return input.slice(start)
return input.substring(start)
}

position.position = idx
return input.slice(start, position.position)
return input.substring(start, position.position)
}

// https://url.spec.whatwg.org/#string-percent-decode
Expand All @@ -182,20 +182,25 @@ function stringPercentDecode (input) {
return percentDecode(bytes)
}

function isHexCharByte (byte) {
return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66)
}

// https://url.spec.whatwg.org/#percent-decode
/** @param {Uint8Array} input */
function percentDecode (input) {
// 1. Let output be an empty byte sequence.
/** @type {number[]} */
const output = []

const length = input.length
/** @type {Uint8Array} */
const output = new Uint8Array(length)
let j = 0
// 2. For each byte byte in input:
for (let i = 0; i < input.length; i++) {
for (let i = 0; i < length; ++i) {
const byte = input[i]

// 1. If byte is not 0x25 (%), then append byte to output.
if (byte !== 0x25) {
output.push(byte)
output[j++] = byte

// 2. Otherwise, if byte is 0x25 (%) and the next two bytes
// after byte in input are not in the ranges
Expand All @@ -204,9 +209,9 @@ function percentDecode (input) {
// to output.
} else if (
byte === 0x25 &&
!/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
!(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))
) {
output.push(0x25)
output[j++] = 0x25

// 3. Otherwise:
} else {
Expand All @@ -216,15 +221,15 @@ function percentDecode (input) {
const bytePoint = Number.parseInt(nextTwoBytes, 16)

// 2. Append a byte whose value is bytePoint to output.
output.push(bytePoint)
output[j++] = bytePoint

// 3. Skip the next two bytes in input.
i += 2
}
}

// 3. Return output.
return Uint8Array.from(output)
return length === j ? output : output.subarray(0, j)
}

// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
Expand Down Expand Up @@ -404,7 +409,7 @@ function parseMIMEType (input) {
/** @param {string} data */
function forgivingBase64 (data) {
// 1. Remove all ASCII whitespace from data.
data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line

// 2. If data’s code point length divides by 4 leaving
// no remainder, then:
Expand All @@ -429,14 +434,8 @@ function forgivingBase64 (data) {
return 'failure'
}

const binary = atob(data)
const bytes = new Uint8Array(binary.length)

for (let byte = 0; byte < binary.length; byte++) {
bytes[byte] = binary.charCodeAt(byte)
}

return bytes
const buffer = Buffer.from(data, 'base64')
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
KhafraDev marked this conversation as resolved.
Show resolved Hide resolved
}

// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
Expand Down Expand Up @@ -515,7 +514,7 @@ function collectAnHTTPQuotedString (input, position, extractValue) {

// 7. Return the code points from positionStart to position,
// inclusive, within input.
return input.slice(positionStart, position.position)
return input.substring(positionStart, position.position)
}

/**
Expand Down Expand Up @@ -564,55 +563,54 @@ function serializeAMimeType (mimeType) {

/**
* @see https://fetch.spec.whatwg.org/#http-whitespace
* @param {string} char
* @param {number} char
*/
function isHTTPWhiteSpace (char) {
return char === '\r' || char === '\n' || char === '\t' || char === ' '
// "\r\n\t "
return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020
}

/**
* @see https://fetch.spec.whatwg.org/#http-whitespace
* @param {string} str
* @param {boolean} [leading=true]
* @param {boolean} [trailing=true]
*/
function removeHTTPWhitespace (str, leading = true, trailing = true) {
let lead = 0
let trail = str.length - 1

let i = 0; let j = str.length
if (leading) {
for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
while (j > i && isHTTPWhiteSpace(str.charCodeAt(i))) --i
}

if (trailing) {
for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
while (j > i && isHTTPWhiteSpace(str.charCodeAt(j - 1))) --j
}

return str.slice(lead, trail + 1)
return i === 0 && j === str.length ? str : str.substring(i, j)
}

/**
* @see https://infra.spec.whatwg.org/#ascii-whitespace
* @param {string} char
* @param {number} char
*/
function isASCIIWhitespace (char) {
return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
// "\r\n\t\f "
return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020
}

/**
* @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
* @param {string} str
* @param {boolean} [leading=true]
* @param {boolean} [trailing=true]
*/
function removeASCIIWhitespace (str, leading = true, trailing = true) {
let lead = 0
let trail = str.length - 1

let i = 0; let j = str.length
if (leading) {
for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
while (j > i && isASCIIWhitespace(str.charCodeAt(i))) --i
}

if (trailing) {
for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
while (j > i && isASCIIWhitespace(str.charCodeAt(j - 1))) --j
}

return str.slice(lead, trail + 1)
return i === 0 && j === str.length ? str : str.substring(i, j)
}

module.exports = {
Expand Down
36 changes: 29 additions & 7 deletions lib/fetch/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -904,8 +904,6 @@ function isReadableStreamLike (stream) {
)
}

const MAXIMUM_ARGUMENT_LENGTH = 65535

/**
* @see https://infra.spec.whatwg.org/#isomorphic-decode
* @param {number[]|Uint8Array} input
Expand All @@ -914,12 +912,36 @@ function isomorphicDecode (input) {
// 1. To isomorphic decode a byte sequence input, return a string whose code point
// length is equal to input’s length and whose code points have the same values
// as the values of input’s bytes, in the same order.

if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
return String.fromCharCode(...input)
const length = input.length
if ((2 << 15) - 1 > length) {
return String.fromCharCode.apply(null, input)
}

return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
let result = ''; let i = 0
if ('buffer' in input) {
let addition = (2 << 15) - 1
while (i < length) {
if (i + addition > length) {
addition = length - i
}
result += String.fromCharCode.apply(null, input.subarray(i, i += addition))
}
return result
}
// FIXME: Is there really a case here?
while (i + 32 < length) {
result += String.fromCharCode(
input[i], input[i + 1], input[i + 2], input[i + 3], input[i + 4], input[i + 5], input[i + 6], input[i + 7],
input[i + 8], input[i + 9], input[i + 10], input[i + 11], input[i + 12], input[i + 13], input[i + 14], input[i + 15],
input[i + 16], input[i + 17], input[i + 18], input[i + 19], input[i + 20], input[i + 21], input[i + 22], input[i + 23],
input[i + 24], input[i + 25], input[i + 26], input[i + 27], input[i + 28], input[i + 29], input[i + 30], input[i + 31]
)
i += 32
tsctx marked this conversation as resolved.
Show resolved Hide resolved
}
// Decode the remaining characters.
while (i < length) {
result += String.fromCharCode(input[i++])
}
return result
}

/**
Expand Down