Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* 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 io.netty.handler.codec.http.cookie.DefaultCookie;
import org.asynchttpclient.AsyncCompletionHandlerBase;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;
import org.asynchttpclient.cookie.ThreadSafeCookieStore;
import org.asynchttpclient.exception.FilterException;
import org.asynchttpclient.filter.FilterContext;
import org.asynchttpclient.filter.RequestFilter;
import org.asynchttpclient.uri.Uri;
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 org.openjdk.jmh.annotations.TearDown;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static org.asynchttpclient.Dsl.asyncHttpClient;
import static org.asynchttpclient.Dsl.config;

/**
* Measures {@code DefaultAsyncHttpClient.executeRequest} up to the request filters, for a request whose URL has a
* cookie in the client's cookie store ({@code storedCookie}) and for one whose URL has none ({@code noStoredCookie}).
* The difference between the two is what adding the stored cookies to the request costs.
* <p>
* A filter ends each call by throwing a preallocated exception, so nothing reaches the network; the failed future
* that {@code executeRequest} then builds is the same in both arms.
*/
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class StoredCookieRequestBenchmark {

private static final FilterException STOP = new FilterException("stop");

@Param({"4", "16"})
public int headerCount;

private AsyncHttpClient client;
private Request withStoredCookie;
private Request withoutStoredCookie;
private AsyncCompletionHandlerBase handler;

@Setup(Level.Trial)
public void setup() {
ThreadSafeCookieStore cookieStore = new ThreadSafeCookieStore();
DefaultCookie session = new DefaultCookie("SESSION", "0123456789abcdef0123456789abcdef");
session.setPath("/");
cookieStore.add(Uri.create("https://api.example.com/"), session);

RequestFilter stop = new RequestFilter() {
@Override
public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException {
throw STOP;
}
};
client = asyncHttpClient(config().setCookieStore(cookieStore).addRequestFilter(stop));
withStoredCookie = request("https://api.example.com/v1/items?page=2&size=50");
withoutStoredCookie = request("https://other.example.org/v1/items?page=2&size=50");
handler = new AsyncCompletionHandlerBase() {
@Override
public void onThrowable(Throwable t) {
}
};
}

private Request request(String url) {
RequestBuilder builder = new RequestBuilder("GET").setUrl(url);
for (int i = 0; i < headerCount; i++) {
builder.addHeader("X-Header-" + i, "value-" + i);
}
return builder.build();
}

@TearDown(Level.Trial)
public void tearDown() throws IOException {
client.close();
}

@Benchmark
public ListenableFuture<Response> storedCookie() {
return client.executeRequest(withStoredCookie, handler);
}

@Benchmark
public ListenableFuture<Response> noStoredCookie() {
return client.executeRequest(withoutStoredCookie, handler);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
Expand All @@ -50,6 +52,7 @@
import static org.asynchttpclient.util.HttpConstants.Methods.POST;
import static org.asynchttpclient.util.HttpConstants.Methods.PUT;
import static org.asynchttpclient.util.HttpConstants.Methods.TRACE;
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;

/**
* Default and threadsafe implementation of {@link AsyncHttpClient}.
Expand Down Expand Up @@ -233,11 +236,7 @@ public <T> ListenableFuture<T> executeRequest(Request request, AsyncHandler<T> h
try {
List<Cookie> cookies = config.getCookieStore().get(request.getUri());
if (!cookies.isEmpty()) {
RequestBuilder requestBuilder = request.toBuilder();
for (Cookie cookie : cookies) {
requestBuilder.addCookieIfUnset(cookie);
}
request = requestBuilder.build();
request = addCookiesIfUnset(request, cookies);
}
} catch (Exception e) {
handler.onThrowable(e);
Expand Down Expand Up @@ -275,6 +274,44 @@ public ListenableFuture<Response> executeRequest(RequestBuilder requestBuilder)
return executeRequest(requestBuilder.build());
}

/**
* Adds each stored cookie whose name the request does not carry yet, keeping the first of a name. A
* {@link DefaultRequest} is copied with only its cookie list replaced, which leaves its URI as built; any other
* {@link Request} goes through {@link Request#toBuilder()}, as it may override what the builder copies.
*/
private static Request addCookiesIfUnset(Request request, List<Cookie> storedCookies) {
if (request.getClass() != DefaultRequest.class) {
RequestBuilder requestBuilder = request.toBuilder();
for (Cookie cookie : storedCookies) {
requestBuilder.addCookieIfUnset(cookie);
}
return requestBuilder.build();
}

// A DefaultRequest from the public constructor may carry null, which the builder path treated as empty.
List<Cookie> requestCookies = isNonEmpty(request.getCookies()) ? request.getCookies() : Collections.emptyList();
List<Cookie> cookies = null;
for (Cookie cookie : storedCookies) {
if (!hasCookieNamed(cookies == null ? requestCookies : cookies, cookie.name())) {
if (cookies == null) {
cookies = new ArrayList<>(requestCookies.size() + storedCookies.size());
cookies.addAll(requestCookies);
}
cookies.add(cookie);
}
}
return cookies == null ? request : ((DefaultRequest) request).withCookies(cookies);
}

private static boolean hasCookieNamed(List<Cookie> cookies, String name) {
for (Cookie cookie : cookies) {
if (cookie.name().equals(name)) {
return true;
}
}
return false;
}

private <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) {
try {
return requestSender.sendRequest(request, asyncHandler, null);
Expand Down
13 changes: 13 additions & 0 deletions client/src/main/java/org/asynchttpclient/DefaultRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,19 @@ public DefaultRequest(String method,
this.nameResolver = nameResolver;
}

/**
* Returns a request that differs from this one only by its cookies. Unlike a round trip through
* {@link #toBuilder()}, the URI is kept as built rather than encoded again, so a request built with URL
* encoding disabled is sent as written, and the other fields are shared rather than copied.
*/
DefaultRequest withCookies(List<Cookie> cookies) {
return new DefaultRequest(method, uri, address, localAddress, headers, cookies, byteData, compositeByteData,
stringData, byteBufferData, byteBufData, streamData, bodyGenerator, formParams, bodyParts, virtualHost,
proxyServer, realm, file, followRedirect, requestTimeout, readTimeout, rangeOffset, charset,
channelPoolPartitioning, nameResolver, useAbsoluteRequestDeadline, refuseSchemeDowngradeOnRedirect,
refuseCrossOriginBodyOnRedirect);
}

@Override
public String getUrl() {
return uri.toUrl();
Expand Down
Loading
Loading