Repository navigation
Conversation
|
Review requested:
|
76c8e14 to
62327c4
Compare
|
Local results from a release build of this branch vs Correctness
Micros (3 runs, ops/s) A JS lookup table for all token lengths and for header-value checks was a regression (V8 regex is faster past ~10 bytes). Latest commit keeps regex for values and for tokens longer than 10, and uses the table for
HTTP/2 So the measurable end-to-end win is the small- |
There was a problem hiding this comment.
Pull request overview
This PR optimizes Node.js HTTP/1.1 and HTTP/2 hot paths around header validation/serialization and write coalescing to reduce per-request overhead in writeHead()/end() and small-body responses.
Changes:
- HTTP/1: faster header-name token validation, cached lenient-validation, reused prebuilt status lines, avoided common-case
toLowerCase(), and added header/body write coalescing (including a combined chunkedend()write). - HTTP/1 server: avoid forcing
req.headersconstruction when checking forContent-Length/Transfer-Encodingby scanningrawHeaders. - HTTP/2: reduce lowercasing overhead in header processing and reserve outgoing send storage to reduce reallocations.
Reviewed changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| test/parallel/test-http-response-cork.js | Updates expectations to allow fewer socket.write() calls due to new coalescing behavior. |
| test/parallel/test-http-common.js | Adds more checkInvalidHeaderChar() test cases for strict vs lenient validation. |
| test/parallel/test-http-chunked-end-coalesce.js | New test validating wire format when chunked res.end() is coalesced into a single write. |
| src/node_http2.cc | Reserves outgoing HTTP/2 storage in send path to reduce reallocations. |
| lib/internal/http2/util.js | Refactors nghttp2 header string building to reduce lowercasing/closure overhead and uses Set for strict single-value checks. |
| lib/internal/http2/core.js | Avoids unconditional toLowerCase() in response header array scanning. |
| lib/_http_server.js | Prebuilds HTTP/1.1 status lines and avoids unnecessary statusMessage validation for defaults; uses req._hasBodyHeaders() for optimizeEmptyRequests. |
| lib/_http_outgoing.js | Coalesces headers with small bodies; adds combined chunked end() fast path; caches lenient-header-validation result; reduces common-case toLowerCase(). |
| lib/_http_incoming.js | Adds IncomingMessage.prototype._hasBodyHeaders() scanning rawHeaders to avoid constructing req.headers. |
| lib/_http_common.js | Speeds up checkIsHttpToken() by using a lookup table for short names and regex for longer ones. |
π‘ Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| } | ||
|
|
||
| write_(this, chunk, encoding, null, true); | ||
| write_(this, chunk, encoding, onFinish.bind(undefined, this), true); |
There was a problem hiding this comment.
Fixed. On the chunk path the user callback is now queued with queueEndCallback() before write_(), so a synchronous socket.write() (for example assignSocket() plus a custom Writable) cannot run onFinish() first and then treat the callback as already finished.
Covered by the new assignSocket() + sync end('hello', cb) case in test/parallel/test-http-outgoing-message-write-callback.js.
|
Follow-up: incoming header bytes now stay off the JS string heap until something actually reads them.
A first attempt used a
I am not updating the |
Codecov Reportβ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #65332 +/- ##
==========================================
- Coverage 90.52% 90.50% -0.03%
==========================================
Files 805 805
Lines 285669 286151 +482
Branches 55151 55257 +106
==========================================
+ Hits 258616 258991 +375
- Misses 17173 17263 +90
- Partials 9880 9897 +17
π New features to boost your workflow:
|
| header = header.toLowerCase(); | ||
| break; | ||
| } | ||
| } |
There was a problem hiding this comment.
What impact does this actually have? I'd prefer not to micro-optimize these things if the benefit is only marginal. The more we micro-optimize this stuff the more difficult maintenance becomes.
There was a problem hiding this comment.
Agreed β the HTTP/2 header benches were within noise. Reverted this to an unconditional toLowerCase().
| const c = key.charCodeAt(i); | ||
| if (c >= 65 && c <= 90) | ||
| return key.toLowerCase(); | ||
| } |
There was a problem hiding this comment.
This is an example of what I mean, this is introducing duplication that is more difficult to maintain.
There was a problem hiding this comment.
Removed asciiToLowerIfNeeded. buildNgHeaderString uses toLowerCase() again; the only leftover from that pass is the hoisted processor / SafeSet cleanup, which is not a second lowercasing helper.
| const len = name.length; | ||
| if (len === 14) { | ||
| if (name === 'Content-Length' || name === 'content-length' || | ||
| name === 'CONTENT-LENGTH' || name.toLowerCase() === 'content-length') { |
There was a problem hiding this comment.
Is there any evidence that the all-caps variations here are used often enough to warrant special casing? I've never seen it used in practice.
There was a problem hiding this comment.
No evidence they are common enough. Dropped the CONTENT-LENGTH / TRANSFER-ENCODING special cases. The materialized fallback still checks Title-Case, lowercase, and toLowerCase().
| // Packed incoming headers: magic + count + flags + (nlen, vlen, name, value)* | ||
| // Kept as a Buffer so JS strings are created only when rawHeaders / headers | ||
| // are actually read. Avoids a native BaseObject per request. | ||
| constexpr uint32_t kNativeHeadersMagic = 0x5244484E; // 'NHDR' |
There was a problem hiding this comment.
I think you have an endianness bug here.
There was a problem hiding this comment.
Yes. The packed uint32_ts were memcpy'd in host order, while JS always read them as little-endian, which is what failed on s390x and AIX.
They are now written and read with explicit LE helpers (WriteU32LE / ReadU32LE). Magic 0x5244484E is the LE encoding of ASCII NHDR on every arch.
| constexpr uint32_t kNativeHeaderFlagContentLength = 1 << 2; | ||
| constexpr uint32_t kNativeHeaderFlagTransferEncoding = 1 << 3; | ||
| constexpr uint32_t kNativeHeaderFlagTE = 1 << 4; | ||
| constexpr size_t kNativeHeadersPrefix = 12; |
There was a problem hiding this comment.
It would be better to export these to the js side to avoid having to define two different sets
There was a problem hiding this comment.
Exported from C++ on HTTPParser: kNativeHeadersMagic, kNativeHeaderFlag*, kNativeHeadersCountOffset, kNativeHeadersFlagsOffset, and kNativeHeadersPrefix. JS reads those instead of keeping a second copy.
| }, | ||
| }); | ||
|
|
||
| ObjectDefineProperty(IncomingMessage.prototype, 'rawHeaders', { |
There was a problem hiding this comment.
This is an observable change (data property -> prototype property) making this potentially semver-major
There was a problem hiding this comment.
The constructor still does this.rawHeaders = [], so a fresh IncomingMessage keeps an own data property.
When headers arrive packed, _setNativeHeaders installs an own accessor that materializes into an own writable data property on first get or set. It is not a prototype getter.
| calculateLenientFlags, | ||
| prepareError, | ||
| kSkipPendingData, | ||
| unpackHeaderList, |
There was a problem hiding this comment.
Is this actually used anywhere? I couldn't find it if it is.
There was a problem hiding this comment.
It was only used by test/parallel/test-http-parser.js. Removed the export; that test now materializes via internalBinding('http_parser').nativeHeadersToArray.
jasnell
left a comment
There was a problem hiding this comment.
Coverage regressions and endianness bug, at the very least, need to be looked at before this lands. There are a number of questionable changes here (noted in comments);
|
Addressed the review notes in the latest commits on this branch:
Replies are on the individual threads. |
|
commits are missing appropriate |
After #65802, Host/Expect/body checks still allocate toLowerCase() copies and Expect/HTTP/1.0 TE still read req.headers. Compare names without allocating, read those values from rawHeaders, intern parser header names, and skip Title-Case toLowerCase on common outgoing fields. Refs: #65802 Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Assisted-by: a closed-source coding agent PR-URL: #66120 Refs: #65332 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
After nodejs#65802, Host/Expect/body checks still allocate toLowerCase() copies and Expect/HTTP/1.0 TE still read req.headers. Compare names without allocating, read those values from rawHeaders, intern parser header names, and skip Title-Case toLowerCase on common outgoing fields. Refs: nodejs#65802 Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Assisted-by: a closed-source coding agent PR-URL: nodejs#66120 Refs: nodejs#65332 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
After #65802, Host/Expect/body checks still allocate toLowerCase() copies and Expect/HTTP/1.0 TE still read req.headers. Compare names without allocating, read those values from rawHeaders, intern parser header names, and skip Title-Case toLowerCase on common outgoing fields. Refs: #65802 Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Assisted-by: a closed-source coding agent PR-URL: #66120 Refs: #65332 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
After #65802, Host/Expect/body checks still allocate toLowerCase() copies and Expect/HTTP/1.0 TE still read req.headers. Compare names without allocating, read those values from rawHeaders, intern parser header names, and skip Title-Case toLowerCase on common outgoing fields. Refs: #65802 Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Assisted-by: a closed-source coding agent PR-URL: #66120 Refs: #65332 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
After #65802, Host/Expect/body checks still allocate toLowerCase() copies and Expect/HTTP/1.0 TE still read req.headers. Compare names without allocating, read those values from rawHeaders, intern parser header names, and skip Title-Case toLowerCase on common outgoing fields. Refs: #65802 Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Assisted-by: a closed-source coding agent PR-URL: #66120 Refs: #65332 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
After #65802, Host/Expect/body checks still allocate toLowerCase() copies and Expect/HTTP/1.0 TE still read req.headers. Compare names without allocating, read those values from rawHeaders, intern parser header names, and skip Title-Case toLowerCase on common outgoing fields. Refs: #65802 Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Assisted-by: a closed-source coding agent PR-URL: #66120 Refs: #65332 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
After #65802, Host/Expect/body checks still allocate toLowerCase() copies and Expect/HTTP/1.0 TE still read req.headers. Compare names without allocating, read those values from rawHeaders, intern parser header names, and skip Title-Case toLowerCase on common outgoing fields. Refs: #65802 Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Assisted-by: a closed-source coding agent PR-URL: #66120 Refs: #65332 Reviewed-By: Robert Nagy <ronagy@icloud.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Rebase onto the internal/http split. Lenient-validation caching and default status-line caching already landed; this keeps the remaining hot-path work: - Check HTTP tokens of length <= 10 with the lookup table. - Coalesce a small body with the header block, and send a chunked end(chunk) as one latin1 write when the header block is still pending. - Recognize the usual Title-Case header names without toLowerCase(). - Keep incoming header bytes packed until rawHeaders or headers is read. - Skip the parser body when a request is dumped. - Hoist HTTP/2 header-string processing off a per-call closure and reserve outgoing session storage. Assisted-by: Cursor Signed-off-by: Yagiz Nizipli <yagiz@nizipli.com> Co-authored-by: Yagiz Nizipli <anonrig@users.noreply.github.com>
37317f2 to
62f65f6
Compare
This speeds up the HTTP/1 and HTTP/2 hot paths that show up in
writeHead()/end(), small-body writes, and HTTP/2 header serialization.HTTP/1
Connection,Keep-Alive). Longer names stay on the regex path; a JS table overthose lengths is slower than V8's regex.
OutgoingMessagelenient-validation and skipstatusMessagevalidation for the built-in reason phrases.
HTTP/1.1 <code> <reason>\r\nstatus lines.toLowerCase()for the common Title-Case / lowercase spellingsof
Connection,Content-Length,Transfer-Encoding, and friends.Bufferbodies into onesocket.write().res.end(chunk)is used withTransfer-Encoding: chunkedandheaders have not been flushed, send headers + last chunk + terminator
in a single write (headers copied as latin1 so obs-text is preserved).
rawHeaders/
headersmaterialize JS strings only when read. The default serverHost / Expect / body-header checks use flag bits and do not build
req.headers.IncomingMessage._dump()/ dumped bodies skipBuffer::Copyviaparser.setSkipBody().HTTP/2
toLowerCase()when header names are already lowercase.buildNgHeaderStringprocessing off a per-call closure.Setfor sensitive / strict single-value header checks.nghttp2_session_mem_sendchunks.These are incremental, behavior-preserving changes. They do not move
end-to-end
benchmark/http/simple.jsby 50%. Localwrknumbers vsupstream/main(same machine, release build, 2x 5s) for the JS write /validation work:
check_is_http_tokenforConnectionis about +21%. Header-valuevalidation stays on regex (a JS
Uint8Arrayscan was 30β50% slower).The packed-header follow-up keeps bytes off the JS string heap until
something actually reads
rawHeaders/headers. A per-request nativeBaseObjectwas slower than creating the string array, so the bytes livein one Buffer with flag bits for Host / Expect / body headers.
Tests
checkInvalidHeaderCharcases intest/parallel/test-http-common.js.test/parallel/test-http-chunked-end-coalesce.jschecks the wireformat of coalesced chunked
end()(string, buffer, UTF-8, trailers,unusual
Content-Lengthcasing, latin1 header values).test/parallel/test-http-native-headers.jschecks lazy Host / Expectlookups and materialization on
req.headersaccess.Local: 405/405
test/parallel/test-http-*(HTTP/1) passed against arelease build of the packed-headers tree. Earlier 776/776
test-http*/test-https*/test-http2*passed on the same branchbefore the Buffer packing tweak.