Repository navigation
Count a UTF-8 form body's length without encoding - #2423
Open
pavel-ptashyts wants to merge 1 commit into
Open
pavel-ptashyts wants to merge 1 commit into
pavel-ptashyts wants to merge 1 commit into
Conversation
When the caller sets Content-Length, NettyRequestSender checks it before taking a pooled connection, and for a form body it learned the length by url-encoding the params into a pooled StringBuilder and copying that into a byte array. newNettyRequest then encodes the same params again for the body, so every attempt encoded the form twice. For UTF-8, the default, the length of the encoded form follows from the params alone: Utf8UrlEncoder keeps a fixed set of ASCII chars, writes a space as '+' and any other code point as %XX per UTF-8 byte, and its output is ASCII. The check now counts that instead. Other charsets keep the old path. A matching, mismatching or malformed header fails exactly as before, with the same message. String bodies are left alone: String.getBytes is an array copy for ASCII text, and counting UTF-8 bytes char by char was 3 to 6 times slower there, on JDK 11 and 25. Claude Code on behalf of Pavel Ptashyts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
When the caller sets a
Content-Lengthheader,NettyRequestSender.sendRequestcallsNettyRequestFactory.checkContentLength(Request)before it takes a pooled connection (added in #2407, so that a request that cannot be built does not take a connection out of the pool). For a form body that check learned the length by building the body:urlEncodeFormParams(...).remaining()url-encodes every param into a pooledStringBuilderand copies it into abyte[].newNettyRequestthen encodes the same params again inbody(). So every attempt (first send, retry, redirect, auth replay) encoded the form twice and allocated the encoded body once more as garbage.Change
For UTF-8 (the default request charset),
checkContentLengthnow counts the encoded length from the params, followingUtf8UrlEncoder.encodeAndAppendFormElement: a char in its form-safe set (a-z A-Z 0-9 - . _ *) is 1, a space is 1 (+), any other ASCII char is 3 (%XX), and any other code point is 3 per byte of its UTF-8 form, with an unpaired surrogate taking 3 bytes as the encoder writes it; params are joined by&, and a null value has no=. The encoder's output is ASCII, so chars are bytes. Other charsets keep the old path (URLEncoder.encodeper field).The body is still built once per attempt in
body(), from the request, as before. Nothing is cached on theRequestor across attempts.String bodies are deliberately left alone
I also tried counting the UTF-8/ISO-8859-1/US-ASCII length of a
setBody(String)body char by char. It is exact and allocation-free, butString.getByteson an ASCII String is an intrinsic array copy, and no char loop I tried (plain loop, OR-reduction pre-scan, chunkedgetChars) came close, on JDK 11 or 25:getBytes(UTF_8).lengthTrading a short-lived allocation for 3 to 6 times the CPU on the most common body (ASCII JSON) is not a gain, so the String path is unchanged.
Preserved behaviour
Content-Lengthstill fails incheckContentLength, before a pooled connection is taken, with the sameIllegalArgumentExceptionand message.CONNECThandling, body precedence (stillbody()'s order), charset semantics and header validation are untouched; the only change is how the form length is obtained in the preflight.NettyRequestFactory. Revapi passes.Benchmark
New
ContentLengthPreflightBenchmarkruns the realcheckContentLength(Request)for a request with a matching header.lengthis the text length in chars before encoding (the 200-char Cyrillic form encodes to about 1,200 bytes). The same benchmark was run againstmain'sNettyRequestFactory(before) and this branch (after). JDK 11.0.33,-f 1 -wi 3 -i 5 -prof gc,-Xmx256m; the host was shared with other builds, so take times as indicative. B/op is deterministic.The String rows are the control and do not change. The gain only applies to requests with a form body and an explicit
Content-Length, which is not a common combination; for those, the preflight goes from a full second encoding to a scan.Tests
NettyRequestFactoryContentLengthTest(new):urlEncodeFormParams(params, charset).remaining()for every char U+0000..U+FFFF as name and value (UTF-8), and, for UTF-8, ISO-8859-1, US-ASCII, UTF-16 and windows-1252, for ASCII, Latin-1, Cyrillic, CJK, surrogate pairs, unpaired surrogates in every position, null values and 1,000 seeded random param pairs;+n,n, n,abc) header is rejected with the same message, for String and form bodies, ASCII and multi-byte text, UTF-8 and ISO-8859-1.The existing
CallerContentLengthTest,NettyRequestFactoryStringBodyTestandHttpUtilsTestpass unchanged. The new test also passes on JDK 25.Gate:
mvnw.cmd -B -ntp -Dgpg.skip=true clean verifyon JDK 11.0.33 (Corretto): BUILD SUCCESS, 2,510 tests, 0 failures, 0 errors, 47 skipped; Revapi passed.AI disclosure
Claude Code on behalf of Pavel Ptashyts. The commit carries a
Co-Authored-Bytrailer perAGENTS.md.🤖 Generated with Claude Code