Skip to content

Commit 1d6abbc

Browse files
committed
Fix validateAfterActivity on the async client
`validateAfterActivity` is primarily a synchronous client feature, since it is necessary to attempt to read from the underlying socket in order to discover that the connection has been closed by the remote peer. The async client doesn't have this issue; the IOReactor is automatically notified when connections are closed and removes them from the pool (see `SingleCoreIOReactor::processClosedSessions`). For some reason, however, the async client's connection manager treats `validateAfterActivity` as a kind of connection TTL: if the connection has been idle longer than the `validateAfterActivity` config value, then the connection is closed immediately unless it is an HTTP/2 connection, in which case a PING frame is used to check for liveness. Since stale connections are removed from the pool automatically as mentioned above, this change simply removes this connection close behavior. A set of integration tests has been added to cover both clients.
1 parent 6e0a18f commit 1d6abbc

2 files changed

Lines changed: 293 additions & 4 deletions

File tree

Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
1+
/*
2+
* ====================================================================
3+
* Licensed to the Apache Software Foundation (ASF) under one
4+
* or more contributor license agreements. See the NOTICE file
5+
* distributed with this work for additional information
6+
* regarding copyright ownership. The ASF licenses this file
7+
* to you under the Apache License, Version 2.0 (the
8+
* "License"); you may not use this file except in compliance
9+
* with the License. You may obtain a copy of the License at
10+
*
11+
* http://www.apache.org/licenses/LICENSE-2.0
12+
*
13+
* Unless required by applicable law or agreed to in writing,
14+
* software distributed under the License is distributed on an
15+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16+
* KIND, either express or implied. See the License for the
17+
* specific language governing permissions and limitations
18+
* under the License.
19+
* ====================================================================
20+
*
21+
* This software consists of voluntary contributions made by many
22+
* individuals on behalf of the Apache Software Foundation. For more
23+
* information on the Apache Software Foundation, please see
24+
* <http://www.apache.org/>.
25+
*
26+
*/
27+
28+
package org.apache.hc.client5.testing;
29+
30+
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
31+
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
32+
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
33+
import org.apache.hc.client5.http.classic.methods.HttpGet;
34+
import org.apache.hc.client5.http.config.ConnectionConfig;
35+
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
36+
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
37+
import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
38+
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
39+
import org.apache.hc.client5.http.impl.classic.HttpClients;
40+
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
41+
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
42+
import org.apache.hc.client5.testing.TestValidateAfterInactivity.TcpReset;
43+
import org.apache.hc.core5.http.HttpHost;
44+
import org.apache.hc.core5.http.NoHttpResponseException;
45+
import org.junit.jupiter.api.AfterEach;
46+
import org.junit.jupiter.api.BeforeEach;
47+
import org.junit.jupiter.api.Nested;
48+
import org.junit.jupiter.api.Test;
49+
50+
import java.io.IOException;
51+
import java.net.InetSocketAddress;
52+
import java.net.SocketException;
53+
import java.net.StandardSocketOptions;
54+
import java.net.URI;
55+
import java.net.URISyntaxException;
56+
import java.nio.ByteBuffer;
57+
import java.nio.channels.AsynchronousCloseException;
58+
import java.nio.channels.ServerSocketChannel;
59+
import java.nio.channels.SocketChannel;
60+
import java.util.concurrent.ExecutionException;
61+
import java.util.concurrent.atomic.AtomicInteger;
62+
import java.util.concurrent.atomic.AtomicReference;
63+
64+
import static java.nio.charset.StandardCharsets.UTF_8;
65+
import static org.apache.hc.core5.util.TimeValue.MAX_VALUE;
66+
import static org.apache.hc.core5.util.TimeValue.ZERO_MILLISECONDS;
67+
import static org.junit.jupiter.api.Assertions.assertEquals;
68+
import static org.junit.jupiter.api.Assertions.assertThrows;
69+
70+
/**
71+
* Tests validateAfterInactivity behavior in both sync and async clients.
72+
*/
73+
class AbstractTestValidateAfterInactivity {
74+
final AtomicInteger connectionsEstablished = new AtomicInteger(0);
75+
final AtomicReference<SocketChannel> currentConnection = new AtomicReference<>();
76+
volatile ServerSocketChannel serverSocket;
77+
volatile int port;
78+
volatile Thread serverThread;
79+
80+
@BeforeEach
81+
void setup() throws Exception {
82+
serverSocket = ServerSocketChannel.open().bind(new InetSocketAddress(0));
83+
port = ((InetSocketAddress) serverSocket.getLocalAddress()).getPort();
84+
85+
serverThread = new Thread(this::runServer);
86+
serverThread.setDaemon(true);
87+
serverThread.start();
88+
}
89+
90+
@AfterEach
91+
void tearDown() throws Exception {
92+
final SocketChannel socket = currentConnection.getAndSet(null);
93+
if (socket != null) {
94+
socket.close();
95+
}
96+
97+
if (serverSocket != null) {
98+
serverSocket.close();
99+
}
100+
if (serverThread != null) {
101+
serverThread.interrupt();
102+
serverThread.join(1000);
103+
}
104+
}
105+
106+
@Test
107+
void testSyncClientWithStaleConnection() throws Exception {
108+
try (final CloseableHttpClient client = syncClient(false)) {
109+
sendPing(client);
110+
sendPing(client);
111+
assertEquals(1, connectionsEstablished.getAndSet(0));
112+
113+
closeServerEndOfConnection();
114+
115+
/*
116+
* There are two things that can happen when reusing a stale connection.
117+
*
118+
* If we manage to send off the request and then read the end of the TCP stream, we will get a
119+
* NoHttpResponseException. This corresponds to a TCP half-close: the server has only closed its own end of
120+
* the connection, not the client's, so theoretically the client could send (and the server could swallow)
121+
* an arbitrary amount of data.
122+
*
123+
* If we are unable to send the request at all, we will get a SocketException. This corresponds to a TCP
124+
* reset; there's no such thing as "TCP half-reset."
125+
*/
126+
final Class<? extends IOException> expectedException = this instanceof TcpReset ?
127+
SocketException.class : NoHttpResponseException.class;
128+
assertThrows(expectedException, () -> sendPing(client));
129+
assertEquals(0, connectionsEstablished.get());
130+
}
131+
}
132+
133+
@Test
134+
void testSyncClientWithValidateAfterInactivity() throws Exception {
135+
try (final CloseableHttpClient client = syncClient(true)) {
136+
sendPing(client);
137+
sendPing(client);
138+
assertEquals(1, connectionsEstablished.getAndSet(0));
139+
140+
closeServerEndOfConnection();
141+
142+
sendPing(client);
143+
assertEquals(1, connectionsEstablished.get());
144+
}
145+
}
146+
147+
@Test
148+
void testAsyncClientWithStaleConnection() throws Exception {
149+
testAsyncClient(false);
150+
}
151+
152+
@Test
153+
void testAsyncClientWithValidateAfterInactivity() throws Exception {
154+
testAsyncClient(true);
155+
}
156+
157+
private void testAsyncClient(final boolean validateAfterInactivity) throws Exception {
158+
try (final CloseableHttpAsyncClient client = asyncClient(validateAfterInactivity)) {
159+
sendPing(client);
160+
sendPing(client);
161+
assertEquals(1, connectionsEstablished.getAndSet(0));
162+
163+
closeServerEndOfConnection();
164+
165+
sendPing(client);
166+
assertEquals(1, connectionsEstablished.get());
167+
}
168+
}
169+
170+
protected void closeServerEndOfConnection() throws IOException, InterruptedException {
171+
currentConnection.get().close();
172+
173+
// It is impossible to guarantee that a connection from the connection pool will not be closed mid-request.
174+
// Even over localhost, closing a socket is inherently an asynchronous operation prone to race conditions.
175+
// Not only do we need to see the TCP `FIN` or `RST` in time, but also the IOReactor (in the case of the async
176+
// client) is asynchronously notified of the connection's closure; until processClosedSessions() runs, the stale
177+
// connection will remain in the thread pool.
178+
//
179+
// These sorts of inherent race condition are unrelated to what is being asserted in these tests: it is always
180+
// possible that a request will fail due to a closure race condition, but we want to ensure that connections
181+
// are not reused when we know *from the beginning* that they are already closed.
182+
Thread.sleep(50);
183+
}
184+
185+
private void sendPing(final CloseableHttpClient client) throws URISyntaxException, IOException {
186+
final HttpHost target = new HttpHost("localhost", port);
187+
final URI requestUri = new URI("/ping");
188+
189+
final String response = client.execute(target, new HttpGet(requestUri), new BasicHttpClientResponseHandler());
190+
191+
assertEquals("OK", response);
192+
}
193+
194+
private void sendPing(final CloseableHttpAsyncClient client) throws ExecutionException, InterruptedException {
195+
final HttpHost target = new HttpHost("localhost", port);
196+
final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(target).setPath("/ping").build();
197+
198+
final SimpleHttpResponse response = client.execute(request, null).get();
199+
200+
assertEquals(200, response.getCode());
201+
}
202+
203+
private void runServer() {
204+
try {
205+
while (!Thread.currentThread().isInterrupted() && serverSocket.isOpen()) {
206+
final SocketChannel socketChannel = serverSocket.accept();
207+
socketChannel.configureBlocking(true);
208+
connectionsEstablished.incrementAndGet();
209+
currentConnection.set(socketChannel);
210+
handleConnection(socketChannel);
211+
}
212+
} catch (final IOException e) {
213+
if (!Thread.currentThread().isInterrupted() && serverSocket.isOpen()) {
214+
System.err.println("Server error: " + e.getClass() + e.getMessage());
215+
}
216+
}
217+
}
218+
219+
private static void handleConnection(final SocketChannel socketChannel) throws IOException {
220+
try {
221+
final ByteBuffer buffer = ByteBuffer.allocate(4096);
222+
while (socketChannel.isOpen()) {
223+
buffer.clear();
224+
final int bytesRead = socketChannel.read(buffer);
225+
if (bytesRead <= 0) {
226+
return;
227+
}
228+
229+
final String response = "HTTP/1.1 200 OK\r\n" +
230+
"Content-Type: text/plain\r\n" +
231+
"Content-Length: 2\r\n" +
232+
"Connection: keep-alive\r\n" +
233+
"\r\n" +
234+
"OK";
235+
236+
final ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes(UTF_8));
237+
while (responseBuffer.hasRemaining()) {
238+
socketChannel.write(responseBuffer);
239+
}
240+
}
241+
} catch (final AsynchronousCloseException ignore) {
242+
// Connection closure was initiated on the server's end
243+
} catch (final IOException ex) {
244+
if (ex.getMessage().startsWith("Connection reset")) {
245+
System.err.println("Server saw connection closed by client");
246+
return;
247+
}
248+
throw ex;
249+
}
250+
}
251+
252+
private CloseableHttpClient syncClient(final boolean validateAfterInactivity) {
253+
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
254+
connManager.setDefaultConnectionConfig(getConnectionConfig(validateAfterInactivity));
255+
return HttpClients.custom()
256+
.setConnectionManager(connManager)
257+
.disableAutomaticRetries()
258+
.build();
259+
}
260+
261+
private CloseableHttpAsyncClient asyncClient(final boolean validateAfterInactivity) {
262+
final PoolingAsyncClientConnectionManager connManager = new PoolingAsyncClientConnectionManager();
263+
connManager.setDefaultConnectionConfig(getConnectionConfig(validateAfterInactivity));
264+
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
265+
.setConnectionManager(connManager)
266+
.disableAutomaticRetries()
267+
.build();
268+
client.start();
269+
return client;
270+
}
271+
272+
private static ConnectionConfig getConnectionConfig(final boolean validateAfterInactivity) {
273+
return ConnectionConfig.custom()
274+
.setTimeToLive(MAX_VALUE)
275+
.setValidateAfterInactivity(validateAfterInactivity ? ZERO_MILLISECONDS : MAX_VALUE)
276+
.build();
277+
}
278+
}
279+
280+
public class TestValidateAfterInactivity {
281+
@Nested
282+
class TcpClose extends AbstractTestValidateAfterInactivity {
283+
}
284+
285+
@Nested
286+
class TcpReset extends AbstractTestValidateAfterInactivity {
287+
@Override
288+
protected void closeServerEndOfConnection() throws IOException, InterruptedException {
289+
currentConnection.get().setOption(StandardSocketOptions.SO_LINGER, 0);
290+
super.closeServerEndOfConnection();
291+
}
292+
}
293+
}

httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManager.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -315,10 +315,6 @@ public void completed(final PoolEntry<HttpRoute, ManagedAsyncClientConnection> p
315315
})), Command.Priority.IMMEDIATE);
316316
return;
317317
}
318-
if (LOG.isDebugEnabled()) {
319-
LOG.debug("{} connection {} is closed", id, ConnPoolSupport.getId(connection));
320-
}
321-
poolEntry.discardConnection(CloseMode.IMMEDIATE);
322318
}
323319
}
324320
}

0 commit comments

Comments
 (0)