diff --git a/client/src/jmh/java/org/asynchttpclient/bench/ContentLengthPreflightBenchmark.java b/client/src/jmh/java/org/asynchttpclient/bench/ContentLengthPreflightBenchmark.java new file mode 100644 index 000000000..5f761f734 --- /dev/null +++ b/client/src/jmh/java/org/asynchttpclient/bench/ContentLengthPreflightBenchmark.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2026 AsyncHttpClient Project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asynchttpclient.bench; + +import org.asynchttpclient.Request; +import org.asynchttpclient.RequestBuilder; +import org.asynchttpclient.netty.request.NettyRequestFactory; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.nio.charset.Charset; +import java.util.concurrent.TimeUnit; + +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.asynchttpclient.util.HttpUtils.urlEncodeFormParams; + +/** + * The check NettyRequestSender runs on a caller's {@code Content-Length} header before it takes a pooled connection, + * for a String or form body. The body itself is built again for the request, so any encoding done by the check is + * done twice per attempt. Run the same benchmark before and after a change to the check. + */ +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +public class ContentLengthPreflightBenchmark { + + @Param({"string", "form"}) + public String body; + + // In chars of the text before encoding. + @Param({"200", "65536"}) + public int length; + + /** + * ascii: 7-bit text; multibyte: Cyrillic text, 2 bytes per char in UTF-8 and 6 chars per char in a form. + */ + @Param({"ascii", "multibyte"}) + public String text; + + private Request request; + private MethodHandle checkContentLength; + + @Setup(Level.Trial) + public void setup() throws Exception { + String unit = "ascii".equals(text) ? "{\"id\":12345,\"name\":\"value\"} " : "\u043f\u0440\u0438\u0432\u0435\u0442 "; + StringBuilder sb = new StringBuilder(length + unit.length()); + while (sb.length() < length) { + sb.append(unit); + } + sb.setLength(length); + String content = sb.toString(); + Charset charset = UTF_8; + + RequestBuilder builder = new RequestBuilder("POST").setUrl("http://localhost/").setCharset(charset); + long bodyLength; + if ("string".equals(body)) { + builder.setBody(content); + bodyLength = content.getBytes(charset).length; + } else { + builder.addFormParam("field", content); + bodyLength = urlEncodeFormParams(builder.build().getFormParams(), charset).remaining(); + } + request = builder.setHeader(CONTENT_LENGTH, bodyLength).build(); + + Method method = NettyRequestFactory.class.getDeclaredMethod("checkContentLength", Request.class); + method.setAccessible(true); + checkContentLength = MethodHandles.lookup().unreflect(method); + } + + @Benchmark + public void checkContentLength() throws Throwable { + checkContentLength.invokeExact(request); + } +} diff --git a/client/src/main/java/org/asynchttpclient/netty/request/NettyRequestFactory.java b/client/src/main/java/org/asynchttpclient/netty/request/NettyRequestFactory.java index 2302384aa..f3b25d3c1 100755 --- a/client/src/main/java/org/asynchttpclient/netty/request/NettyRequestFactory.java +++ b/client/src/main/java/org/asynchttpclient/netty/request/NettyRequestFactory.java @@ -30,6 +30,7 @@ import io.netty.handler.codec.http.cookie.ClientCookieEncoder; import io.netty.util.AsciiString; import org.asynchttpclient.AsyncHttpClientConfig; +import org.asynchttpclient.Param; import org.asynchttpclient.Realm; import org.asynchttpclient.Request; import org.asynchttpclient.netty.request.body.NettyBody; @@ -77,6 +78,7 @@ import static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING; import static io.netty.handler.codec.http.HttpHeaderNames.UPGRADE; import static io.netty.handler.codec.http.HttpHeaderNames.USER_AGENT; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.asynchttpclient.util.AuthenticatorUtils.perRequestAuthorizationHeader; import static org.asynchttpclient.util.AuthenticatorUtils.perRequestProxyAuthorizationHeader; import static org.asynchttpclient.util.HttpUtils.ACCEPT_ALL_HEADER_VALUE; @@ -321,7 +323,7 @@ static void checkContentLength(Request request) { streamContentLength(request, -1); return; } else if (isNonEmpty(request.getFormParams())) { - length = urlEncodeFormParams(request.getFormParams(), request.getCharset()).remaining(); + length = formBodyLength(request.getFormParams(), request.getCharset()); } else if (isNonEmpty(request.getBodyParts())) { length = UNKNOWN_LENGTH; } else if (request.getFile() != null) { @@ -340,6 +342,46 @@ static void checkContentLength(Request request) { checkContentLength(request, length); } + // The length of urlEncodeFormParams(params, charset), counted without encoding for UTF-8. It follows + // Utf8UrlEncoder.encodeAndAppendFormElement, whose output is ASCII: one byte per char. + static long formBodyLength(List params, @Nullable Charset charset) { + if (!UTF_8.equals(charset)) { + return urlEncodeFormParams(params, charset).remaining(); + } + // The '&' between the params. + long length = params.size() - 1; + for (Param param : params) { + length += formFieldLength(param.getName()); + String value = param.getValue(); + if (value != null) { + length += 1 + formFieldLength(value); + } + } + return length; + } + + private static long formFieldLength(String field) { + long length = 0; + int c; + for (int i = 0; i < field.length(); i += Character.charCount(c)) { + c = Character.codePointAt(field, i); + if (c < 0x80) { + // Left as it is, or a space as '+'; any other byte as %XX. + length += isFormSafe(c) || c == ' ' ? 1 : 3; + } else { + // %XX for each byte of the code point's UTF-8 form; an unpaired surrogate takes 3 bytes. + length += c < 0x800 ? 6 : c < 0x10000 ? 9 : 12; + } + } + return length; + } + + // Utf8UrlEncoder's FORM_URL_ENCODED_SAFE_CHARS. + private static boolean isFormSafe(int c) { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' + || c == '-' || c == '.' || c == '_' || c == '*'; + } + // A file that is not there fails when its body is built, with its own error. private static long fileLength(File file, long length) { return file.isFile() ? length : UNKNOWN_LENGTH; diff --git a/client/src/test/java/org/asynchttpclient/netty/request/NettyRequestFactoryContentLengthTest.java b/client/src/test/java/org/asynchttpclient/netty/request/NettyRequestFactoryContentLengthTest.java new file mode 100644 index 000000000..641d18322 --- /dev/null +++ b/client/src/test/java/org/asynchttpclient/netty/request/NettyRequestFactoryContentLengthTest.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2026 AsyncHttpClient Project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asynchttpclient.netty.request; + +import org.asynchttpclient.Param; +import org.asynchttpclient.Request; +import org.asynchttpclient.RequestBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.stream.Stream; + +import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.US_ASCII; +import static java.nio.charset.StandardCharsets.UTF_16; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.asynchttpclient.util.HttpUtils.urlEncodeFormParams; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * The preflight check of a caller's {@code Content-Length} header counts the length of a UTF-8 form body without + * encoding it. The count must be the length of the bytes the body is built from, and the check must fail as before. + */ +public class NettyRequestFactoryContentLengthTest { + + private static final Charset WINDOWS_1252 = Charset.forName("windows-1252"); + private static final List CHARSETS = List.of(UTF_8, ISO_8859_1, US_ASCII, UTF_16, WINDOWS_1252); + + // Every kind of char an encoder treats apart: ASCII, Latin-1, the 2- and 3-byte UTF-8 ranges, a surrogate pair, + // and unpaired surrogates at either end and next to each other. + private static final String[] TEXTS = { + "", + "plain ascii text", + "a b&c=d+e%f*g-h.i_j~k", + "caf\u00e9 cr\u00e8me", + "\u043f\u0440\u0438\u0432\u0435\u0442", + "\u20ac \u4e2d\u6587 \uffff", + "x\ud83d\ude00y", + "\ud83d\ude00", + "a\ud800", + "\ud800a", + "\udc00", + "\udc00\ud800", + "\ud800\ud800\udc00", + "\ud800\udc00\udc00", + "\u0000\u007f\u0080\u00ff\u0100\u07ff\u0800", + }; + + @Test + public void formBodyLengthIsTheLengthOfItsBytes() { + for (Charset charset : CHARSETS) { + for (String name : TEXTS) { + for (String value : TEXTS) { + assertFormBodyLength(List.of(new Param(name, value)), charset); + assertFormBodyLength(List.of(new Param(name, null), new Param(value, name)), charset); + } + } + List texts = randomTexts(); + for (int i = 0; i + 1 < texts.size(); i += 2) { + assertFormBodyLength(List.of(new Param(texts.get(i), texts.get(i + 1)), new Param("k", null)), charset); + } + } + } + + @Test + public void formBodyLengthIsTheLengthOfItsBytesForEveryChar() { + for (int c = 0; c <= 0xFFFF; c++) { + String text = String.valueOf((char) c); + assertFormBodyLength(List.of(new Param(text, text)), UTF_8); + } + } + + static Stream bodies() { + List arguments = new ArrayList<>(); + for (Charset charset : List.of(UTF_8, ISO_8859_1)) { + for (String text : List.of("ascii body text", "caf\u00e9 \u00e4\u00f6\u00fc")) { + arguments.add(Arguments.of("string", charset, text)); + arguments.add(Arguments.of("form", charset, text)); + } + } + return arguments.stream(); + } + + @ParameterizedTest(name = "{0} {1} {2}") + @MethodSource("bodies") + public void matchingContentLengthIsAccepted(String kind, Charset charset, String text) { + long length = encodedLength(kind, charset, text); + assertDoesNotThrow(() -> NettyRequestFactory.checkContentLength(request(kind, charset, text, String.valueOf(length)))); + } + + @ParameterizedTest(name = "{0} {1} {2}") + @MethodSource("bodies") + public void mismatchingContentLengthIsRejected(String kind, Charset charset, String text) { + long length = encodedLength(kind, charset, text); + for (long header : new long[]{0, length - 1, length + 1}) { + Request request = request(kind, charset, text, String.valueOf(header)); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> NettyRequestFactory.checkContentLength(request)); + assertEquals("Content-Length header " + header + " does not match the body's length " + length, e.getMessage()); + } + } + + @ParameterizedTest(name = "{0} {1} {2}") + @MethodSource("bodies") + public void malformedContentLengthIsRejected(String kind, Charset charset, String text) { + long length = encodedLength(kind, charset, text); + for (String header : List.of("+" + length, length + ", " + length, "abc")) { + Request request = request(kind, charset, text, header); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> NettyRequestFactory.checkContentLength(request)); + assertEquals("Content-Length header [" + header + "] is not a length", e.getMessage()); + } + } + + private static void assertFormBodyLength(List params, Charset charset) { + assertEquals(urlEncodeFormParams(params, charset).remaining(), NettyRequestFactory.formBodyLength(params, charset), + () -> charset + " " + params); + } + + private static long encodedLength(String kind, Charset charset, String text) { + return "string".equals(kind) + ? text.getBytes(charset).length + : urlEncodeFormParams(List.of(new Param("field", text)), charset).remaining(); + } + + private static Request request(String kind, Charset charset, String text, String contentLength) { + RequestBuilder builder = new RequestBuilder("POST").setUrl("http://localhost/").setCharset(charset); + if ("string".equals(kind)) { + builder.setBody(text); + } else { + builder.addFormParam("field", text); + } + return builder.setHeader(CONTENT_LENGTH, contentLength).build(); + } + + private static List randomTexts() { + char[] alphabet = {'a', ' ', '&', '*', '~', '\u00e9', '\u0430', '\u20ac', '\ud83d', '\ude00', '\ud800', '\udfff'}; + Random random = new Random(42); + List texts = new ArrayList<>(); + for (int i = 0; i < 2000; i++) { + char[] chars = new char[random.nextInt(12)]; + for (int j = 0; j < chars.length; j++) { + chars[j] = alphabet[random.nextInt(alphabet.length)]; + } + texts.add(new String(chars)); + } + return texts; + } + +}