Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 60 additions & 29 deletions src/jsc/bindings/webcore/HTTPHeaderMap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<UncommonHeadersIndex>();
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<ASCIICaseInsensitiveStringViewHashTranslator>(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;
Expand Down Expand Up @@ -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();

Expand All @@ -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();
}

Expand Down Expand Up @@ -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<Latin1Character> 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);
}
Expand All @@ -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);
}
Expand All @@ -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);
}
}

Expand All @@ -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)
Expand All @@ -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<ASCIICaseInsensitiveStringViewHashTranslator>(name);
for (auto& entry : *m_uncommonHeadersIndex) {
if (entry.value > index)
--entry.value;
}
}
return true;
}

String HTTPHeaderMap::get(HTTPHeaderName name) const
Expand Down Expand Up @@ -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 };
}

Expand Down
38 changes: 37 additions & 1 deletion src/jsc/bindings/webcore/HTTPHeaderMap.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
#pragma once

#include "HTTPHeaderNames.h"
#include <memory>
#include <utility>
#include <wtf/HashMap.h>
#include <wtf/text/StringHash.h>
#include <wtf/text/WTFString.h>

namespace WebCore {
Expand Down Expand Up @@ -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() &&;
Expand All @@ -181,6 +201,7 @@ class HTTPHeaderMap {
{
m_commonHeaders.clear();
m_uncommonHeaders.clear();
m_uncommonHeadersIndex = nullptr;
}

void shrinkToFit()
Expand Down Expand Up @@ -233,7 +254,11 @@ 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; }
UncommonHeadersVector &uncommonHeaders()
{
m_uncommonHeadersIndex = nullptr;
return m_uncommonHeaders;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Vector<String, 0> &getSetCookieHeaders() { return m_setCookieHeaders; }

const_iterator begin() const { return const_iterator(*this, m_commonHeaders.begin(), m_uncommonHeaders.begin(), m_setCookieHeaders.begin()); }
Expand Down Expand Up @@ -274,11 +299,22 @@ class HTTPHeaderMap {
void addUncommonHeaderCloneName(const StringView name, const String &value);

private:
using UncommonHeadersIndex = HashMap<String, unsigned, ASCIICaseInsensitiveHash>;

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<String, 0> 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<UncommonHeadersIndex> m_uncommonHeadersIndex;
};

template<class Encoder>
Expand Down
78 changes: 78 additions & 0 deletions test/js/web/fetch/headers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,84 @@ 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: if the lookup
// scales with entry count the second run is ~8x slower; with the hash
// index it is O(1) and both runs take the same time. The ratio is
// self-calibrating across release/debug/ASAN builds so no absolute time
// budget is needed.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
test("per-name lookup is independent of distinct-name count", () => {
const N = 1500;

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 < N; i++) h.get(names[i]);
return performance.now() - t;
};
const best = (h: Headers, names: string[]) => Math.min(time(h, names), time(h, names), time(h, names));

time(small, smallProbe);
time(large, largeProbe);
const tSmall = best(small, smallProbe);
const tLarge = best(large, largeProbe);

expect(small.get("x-0")).toBe("v");
expect(large.get("x-" + (N * 8 - 1))).toBe("v");
Comment thread
robobun marked this conversation as resolved.
Resolved
expect(tLarge / Math.max(tSmall, 1)).toBeLessThan(3);
});
});
describe("count", () => {
// @ts-ignore
const it = typeof new Headers()?.count !== "undefined" ? test : test.skip;
Expand Down
Loading