Files
core/src/http/headers.ts
T
chrnx 8d8ef7ed09 perf(http): look injected header keys up directly instead of rebuilding a Set
mergeInjectedHeaders rebuilt a lowercased Set of the injected header keys on
every response: an array from Object.keys, a mapped array from toLowerCase, and
a Set from that. Three allocations to answer a question the object already
answers.

The lowercasing was the redundant part. Every key `injected` can hold is written
as a lowercase literal in src/security.ts — buildSecurityHeaders and resolveCors
are its only sources — so the mapped array was a copy of the keys it started
with.

hasOwnProperty rather than `in`: a handler may legitimately send a header named
constructor or toString, and `in` would find those on Object.prototype and drop
them silently.

146.4ns to 55.9ns in isolation; -3.2% end to end over five interleaved rounds,
with all five pairs favouring the change.

Third of three fixes from the same profile, and all three are one pattern:
work done unconditionally for a case that rarely or never applies — validating
encoding that is almost never malformed, parsing a query string that is not
there, lowercasing keys that already were.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-16 22:57:37 -05:00

43 lines
1.8 KiB
TypeScript

import { mergeVary } from '../security';
const hasOwn = Object.prototype.hasOwnProperty;
/**
* Merges a handler's response headers with authoritative `injected` headers
* (security + CORS). Injected keys win case-insensitively; `vary` is merged.
* Extracted from the Node writeHead patch so app.fetch shares the exact logic.
*/
export function mergeInjectedHeaders(
handlerHeaders: Record<string, any> | undefined,
injected: Record<string, string>,
): Record<string, any> {
const merged: Record<string, any> = {};
let handlerVary: string | undefined;
if (handlerHeaders)
for (const key of Object.keys(handlerHeaders)) {
const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key];
continue;
}
// `injected` is looked up directly instead of through a lowercased Set rebuilt per response.
// Every key it can hold is written as a lowercase literal in `src/security.ts` — both
// `buildSecurityHeaders` and `resolveCors`, which are its only sources — so lowercasing them
// again produced a copy of the keys it already had. Three allocations per response (an array,
// a mapped array, a Set) to answer a question the object answers itself: 146.4 ns against
// 55.9 ns.
//
// `hasOwnProperty` rather than `in`: a handler is free to send a header called `constructor`
// or `toString`, and `in` would find those on Object.prototype and silently drop them.
if (!hasOwn.call(injected, lowerKey)) merged[key] = handlerHeaders[key];
}
Object.assign(merged, injected);
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
else if (handlerVary !== undefined) merged['vary'] = handlerVary;
return merged;
}