diff --git a/src/jsc/bindings/webcore/FetchHeaders.cpp b/src/jsc/bindings/webcore/FetchHeaders.cpp index 016bd82c4977..033903e5e8f8 100644 --- a/src/jsc/bindings/webcore/FetchHeaders.cpp +++ b/src/jsc/bindings/webcore/FetchHeaders.cpp @@ -213,11 +213,7 @@ ExceptionOr FetchHeaders::fill(const Init& headerInit) ExceptionOr FetchHeaders::fill(const FetchHeaders& otherHeaders) { if (this->size() == 0) { - HTTPHeaderMap headers; - headers.commonHeaders().appendVector(otherHeaders.m_headers.commonHeaders()); - headers.uncommonHeaders().appendVector(otherHeaders.m_headers.uncommonHeaders()); - headers.getSetCookieHeaders().appendVector(otherHeaders.m_headers.getSetCookieHeaders()); - setInternalHeaders(WTF::move(headers)); + m_headers = otherHeaders.m_headers; m_updateCounter++; return {}; } diff --git a/src/jsc/bindings/webcore/HTTPHeaderMap.cpp b/src/jsc/bindings/webcore/HTTPHeaderMap.cpp index 4ce2c1b0fcb3..de653441fc8f 100644 --- a/src/jsc/bindings/webcore/HTTPHeaderMap.cpp +++ b/src/jsc/bindings/webcore/HTTPHeaderMap.cpp @@ -76,10 +76,43 @@ String lowercaseHeaderName(const String& name) return result; } +// Linear scan stays faster than hashing for the handful-of-headers case that +// dominates real traffic. Past this many distinct uncommon names, build a hash +// index so get/set/append/has stay O(1) instead of degrading to O(N) per call. +static constexpr unsigned uncommonHeadersIndexThreshold = 64; + HTTPHeaderMap::HTTPHeaderMap() { } +size_t HTTPHeaderMap::findUncommonHeaderIndex(const StringView name) const +{ + if (!m_uncommonHeadersIndex) { + unsigned size = m_uncommonHeaders.size(); + if (size <= uncommonHeadersIndexThreshold) { + return m_uncommonHeaders.findIf([&](auto& header) { + return equalIgnoringASCIICase(header.key, name); + }); + } + auto index = makeUnique(); + index->reserveInitialCapacity(size); + for (unsigned i = 0; i < size; ++i) + index->add(m_uncommonHeaders[i].key, i); + m_uncommonHeadersIndex = WTF::move(index); + } + + auto it = m_uncommonHeadersIndex->find(name); + return it != m_uncommonHeadersIndex->end() ? it->value : notFound; +} + +void HTTPHeaderMap::appendUncommonHeader(const String& name, const String& value) +{ + unsigned index = m_uncommonHeaders.size(); + m_uncommonHeaders.append(UncommonHeader { name, value }); + if (m_uncommonHeadersIndex) + m_uncommonHeadersIndex->add(m_uncommonHeaders[index].key, index); +} + HTTPHeaderMap HTTPHeaderMap::isolatedCopy() const& { HTTPHeaderMap map; @@ -112,6 +145,8 @@ size_t HTTPHeaderMap::memoryCost() const size_t cost = m_commonHeaders.size() * sizeof(CommonHeader); cost += m_uncommonHeaders.size() * sizeof(UncommonHeader); cost += m_setCookieHeaders.size() * sizeof(String); + if (m_uncommonHeadersIndex) + cost += m_uncommonHeadersIndex->capacity() * (sizeof(String) + sizeof(unsigned)); for (auto& header : m_commonHeaders) cost += header.value.sizeInBytes(); @@ -128,9 +163,7 @@ size_t HTTPHeaderMap::memoryCost() const String HTTPHeaderMap::getUncommonHeader(const StringView name) const { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); return index != notFound ? m_uncommonHeaders[index].value : String(); } @@ -168,36 +201,30 @@ void HTTPHeaderMap::set(const String& name, const String& value) void HTTPHeaderMap::setUncommonHeader(const String& name, const String& value) { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); else m_uncommonHeaders[index].value = value; } void HTTPHeaderMap::addUncommonHeader(const String& name, const String& value) { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); else m_uncommonHeaders[index].value = makeString(m_uncommonHeaders[index].value, ", "_s, value); } void HTTPHeaderMap::addUncommonHeaderCloneName(const StringView name, const String& value) { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) { std::span ptr; auto nameCopy = WTF::String::createUninitialized(name.length(), ptr); memcpy(ptr.data(), name.span8().data(), name.length()); - m_uncommonHeaders.append(UncommonHeader { nameCopy, value }); + appendUncommonHeader(nameCopy, value); } else m_uncommonHeaders[index].value = makeString(m_uncommonHeaders[index].value, ", "_s, value); } @@ -209,11 +236,9 @@ void HTTPHeaderMap::add(const String& name, const String& value) add(headerName, value); return; } - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); if (index == notFound) - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); else m_uncommonHeaders[index].value = makeString(m_uncommonHeaders[index].value, ", "_s, value); } @@ -229,7 +254,7 @@ void HTTPHeaderMap::append(const String& name, const String& value) else m_commonHeaders.append(CommonHeader { headerName, value }); } else { - m_uncommonHeaders.append(UncommonHeader { name, value }); + appendUncommonHeader(name, value); } } @@ -248,9 +273,7 @@ bool HTTPHeaderMap::contains(const StringView name) const if (findHTTPHeaderName(name, headerName)) return contains(headerName); - return m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }) != notFound; + return findUncommonHeaderIndex(name) != notFound; } bool HTTPHeaderMap::remove(const StringView name) @@ -270,9 +293,19 @@ bool HTTPHeaderMap::removeUncommonHeader(const StringView name) ASSERT(!findHTTPHeaderName(name, headerName)); #endif - return m_uncommonHeaders.removeFirstMatching([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); + if (index == notFound) + return false; + + m_uncommonHeaders.removeAt(index); + if (m_uncommonHeadersIndex) { + m_uncommonHeadersIndex->remove(name); + for (auto& entry : *m_uncommonHeadersIndex) { + if (entry.value > index) + --entry.value; + } + } + return true; } String HTTPHeaderMap::get(HTTPHeaderName name) const @@ -313,9 +346,7 @@ HTTPHeaderMap::HeaderIndex HTTPHeaderMap::indexOf(HTTPHeaderName name) const HTTPHeaderMap::HeaderIndex HTTPHeaderMap::indexOf(const String& name) const { - auto index = m_uncommonHeaders.findIf([&](auto& header) { - return equalIgnoringASCIICase(header.key, name); - }); + auto index = findUncommonHeaderIndex(name); return (HeaderIndex) { .index = index, .isCommon = false }; } diff --git a/src/jsc/bindings/webcore/HTTPHeaderMap.h b/src/jsc/bindings/webcore/HTTPHeaderMap.h index 4f617d07d475..fd5a469da158 100644 --- a/src/jsc/bindings/webcore/HTTPHeaderMap.h +++ b/src/jsc/bindings/webcore/HTTPHeaderMap.h @@ -27,7 +27,10 @@ #pragma once #include "HTTPHeaderNames.h" +#include #include +#include +#include #include namespace WebCore { @@ -170,6 +173,23 @@ class HTTPHeaderMap { WEBCORE_EXPORT HTTPHeaderMap(); + HTTPHeaderMap(const HTTPHeaderMap &other) + : m_commonHeaders(other.m_commonHeaders) + , m_uncommonHeaders(other.m_uncommonHeaders) + , m_setCookieHeaders(other.m_setCookieHeaders) + { + } + HTTPHeaderMap(HTTPHeaderMap &&) = default; + HTTPHeaderMap &operator=(const HTTPHeaderMap &other) + { + m_commonHeaders = other.m_commonHeaders; + m_uncommonHeaders = other.m_uncommonHeaders; + m_setCookieHeaders = other.m_setCookieHeaders; + m_uncommonHeadersIndex = nullptr; + return *this; + } + HTTPHeaderMap &operator=(HTTPHeaderMap &&) = default; + // Gets a copy of the data suitable for passing to another thread. WEBCORE_EXPORT HTTPHeaderMap isolatedCopy() const &; WEBCORE_EXPORT HTTPHeaderMap isolatedCopy() &&; @@ -181,6 +201,7 @@ class HTTPHeaderMap { { m_commonHeaders.clear(); m_uncommonHeaders.clear(); + m_uncommonHeadersIndex = nullptr; } void shrinkToFit() @@ -233,7 +254,6 @@ class HTTPHeaderMap { const CommonHeadersVector &commonHeaders() const { return m_commonHeaders; } const UncommonHeadersVector &uncommonHeaders() const { return m_uncommonHeaders; } CommonHeadersVector &commonHeaders() { return m_commonHeaders; } - UncommonHeadersVector &uncommonHeaders() { return m_uncommonHeaders; } Vector &getSetCookieHeaders() { return m_setCookieHeaders; } const_iterator begin() const { return const_iterator(*this, m_commonHeaders.begin(), m_uncommonHeaders.begin(), m_setCookieHeaders.begin()); } @@ -274,11 +294,22 @@ class HTTPHeaderMap { void addUncommonHeaderCloneName(const StringView name, const String &value); private: + using UncommonHeadersIndex = HashMap; + WEBCORE_EXPORT String getUncommonHeader(const StringView name) const; + size_t findUncommonHeaderIndex(const StringView name) const; + void appendUncommonHeader(const String &name, const String &value); + CommonHeadersVector m_commonHeaders; UncommonHeadersVector m_uncommonHeaders; Vector m_setCookieHeaders; + + // Lazily built once m_uncommonHeaders grows past the point where a linear + // scan per lookup becomes quadratic in aggregate. The stored keys alias the + // String already held by the vector entry, so the index costs one bucket + // per name rather than a second copy of the name. + mutable std::unique_ptr m_uncommonHeadersIndex; }; template diff --git a/test/js/web/fetch/headers.test.ts b/test/js/web/fetch/headers.test.ts index b514a241674c..a69583ea132b 100644 --- a/test/js/web/fetch/headers.test.ts +++ b/test/js/web/fetch/headers.test.ts @@ -582,6 +582,83 @@ describe("Headers", () => { }); }); }); + describe("many distinct uncommon names", () => { + // Past a small threshold, HTTPHeaderMap builds a hash index over the + // uncommon-header vector so per-name lookups stay O(1). Exercise every + // mutation/lookup path across that boundary, including after delete() + // has shifted vector entries, so a stale index would return the wrong + // slot. + test("stays correct across get/has/set/append/delete", () => { + const N = 200; + const name = (i: number) => (i % 2 === 0 ? "x-" : "X-") + i; + const h = new Headers(); + for (let i = 0; i < N; i++) h.append(name(i), "v" + i); + expect(h.count).toBe(N); + + for (let i = 0; i < N; i++) { + expect(h.get("x-" + i)).toBe("v" + i); + expect(h.get("X-" + i)).toBe("v" + i); + expect(h.has("x-" + i)).toBe(true); + } + expect(h.get("x-" + N)).toBeNull(); + expect(h.has("x-" + N)).toBe(false); + + for (let i = 0; i < N; i += 3) h.set("X-" + i, "s" + i); + for (let i = 1; i < N; i += 3) h.append("x-" + i, "a" + i); + for (let i = 2; i < N; i += 3) h.delete("x-" + i); + for (let i = 0; i < N; i++) { + if (i % 3 === 0) expect(h.get("x-" + i)).toBe("s" + i); + else if (i % 3 === 1) expect(h.get("x-" + i)).toBe("v" + i + ", a" + i); + else { + expect(h.get("x-" + i)).toBeNull(); + expect(h.has("x-" + i)).toBe(false); + } + } + + const copy = new Headers(h); + for (let i = 0; i < N; i += 3) expect(copy.get("x-" + i)).toBe("s" + i); + + h.set("x-late", "z"); + h.append("x-late", "zz"); + expect(h.get("X-Late")).toBe("z, zz"); + }); + + // get()/has() on an uncommon name used to scan the whole vector, so the + // cost of a single lookup grew with the number of distinct names. Probe + // the last N names of an N-entry map and an 8N-entry map: with a linear + // scan the second run does ~15x the work (average scan depth ~7.5N vs + // ~N/2); with the hash index it is O(1) and both runs take the same time. + // ITER is sized so the baseline clears 1ms on a release build and the + // ratio self-calibrates across release/debug/ASAN without an absolute + // time budget. + test("per-name lookup is independent of distinct-name count", () => { + const N = 1500; + const ITER = 20000; + + const small = new Headers(); + for (let i = 0; i < N; i++) small.append("x-" + i, "v"); + const smallProbe: string[] = []; + for (let i = 0; i < N; i++) smallProbe.push("x-" + (N - 1 - i)); + + const large = new Headers(); + for (let i = 0; i < N * 8; i++) large.append("x-" + i, "v"); + const largeProbe: string[] = []; + for (let i = 0; i < N; i++) largeProbe.push("x-" + (N * 8 - 1 - i)); + + const time = (h: Headers, names: string[]) => { + const t = performance.now(); + for (let i = 0; i < ITER; i++) h.get(names[i % N]); + return performance.now() - t; + }; + + const tSmall = Math.min(time(small, smallProbe), time(small, smallProbe)); + const tLarge = Math.min(time(large, largeProbe), time(large, largeProbe)); + + expect(small.get("x-0")).toBe("v"); + expect(large.get("x-" + (N * 8 - 1))).toBe("v"); + expect(tLarge / tSmall).toBeLessThan(3); + }); + }); describe("count", () => { // @ts-ignore const it = typeof new Headers()?.count !== "undefined" ? test : test.skip;