anshumg commented on code in PR #5322:
URL: https://github.com/apache/solr/pull/5322#discussion_r4781539652


##########
solr/solrj-jetty/src/test/org/apache/solr/client/solrj/jetty/HttpJettySolrClientTest.java:
##########
@@ -936,5 +941,192 @@ private static void assertIsTimeout(Throwable t) {
     assertThat(t.getMessage(), containsStringIgnoringCase("Timeout"));
   }
 
+  private static final long CONNECTION_MAX_DURATION_MS = 50;
+
+  /** How long to keep sending requests before giving up on seeing a replaced 
connection. */
+  private static final long CONNECTION_REPLACED_DEADLINE_MS = 100 * 
CONNECTION_MAX_DURATION_MS;
+
+  @Test
+  public void testConnectionMaxDurationIsApplied() throws Exception {
+    for (boolean useHttp1_1 : new boolean[] {false, true}) {
+      try (var client =
+          new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+              .useHttp1_1(useHttp1_1)
+              .withConnectionMaxDuration(CONNECTION_MAX_DURATION_MS, 
TimeUnit.MILLISECONDS)
+              .build()) {
+        queryDefaultCollection(client);
+        assertEquals(
+            "useHttp1_1=" + useHttp1_1,
+            CONNECTION_MAX_DURATION_MS,
+            connectionPool(client).getMaxDuration());
+      }
+    }
+  }
+
+  @Test
+  public void testConnectionReplacedAfterMaxDuration() throws Exception {
+    for (boolean useHttp1_1 : new boolean[] {false, true}) {
+      try (var client =
+          new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+              .useHttp1_1(useHttp1_1)
+              .withConnectionMaxDuration(CONNECTION_MAX_DURATION_MS, 
TimeUnit.MILLISECONDS)
+              .build()) {
+        queryDefaultCollection(client);
+        Connection first = idleConnection(client);
+        new TimeOut(CONNECTION_REPLACED_DEADLINE_MS, TimeUnit.MILLISECONDS, 
TimeSource.NANO_TIME)
+            .waitFor(
+                "connection was not replaced, useHttp1_1=" + useHttp1_1,
+                () -> {
+                  queryDefaultCollection(client);
+                  return idleConnection(client) != first;
+                });
+      }
+    }
+  }
+
+  @Test
+  public void testConnectionReusedWithoutMaxDuration() throws Exception {
+    for (boolean useHttp1_1 : new boolean[] {false, true}) {
+      try (var client =
+          new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+              .useHttp1_1(useHttp1_1)
+              .build()) {
+        queryDefaultCollection(client);
+        Connection first = idleConnection(client);
+        queryDefaultCollection(client);
+        assertSame("useHttp1_1=" + useHttp1_1, first, idleConnection(client));
+        assertEquals(0, connectionPool(client).getMaxDuration());
+      }
+    }
+  }
+
+  @Test
+  public void testConnectionMaxDurationWithHttpClient() {
+    try (var seed = new 
HttpJettySolrClient.Builder(solrTestRule.getBaseUrl()).build()) {
+      expectThrows(
+          IllegalArgumentException.class,
+          () ->
+              new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+                  .withHttpClient(seed)
+                  .withConnectionMaxDuration(CONNECTION_MAX_DURATION_MS, 
TimeUnit.MILLISECONDS)
+                  .build());
+    }
+  }
+
+  private static final int MAX_HTTP2_CONNECTIONS = 8;
+
+  @Test
+  public void testMaxHttp2ConnectionsPerHost() throws Exception {
+    try (var client =
+        new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+            .useHttp1_1(false)
+            .withMaxHttp2ConnectionsPerHost(MAX_HTTP2_CONNECTIONS)
+            .build()) {
+      queryDefaultCollection(client);
+      assertEquals(MAX_HTTP2_CONNECTIONS, 
client.getHttpClient().getMaxConnectionsPerDestination());
+      assertEquals(MAX_HTTP2_CONNECTIONS, 
connectionPool(client).getMaxConnectionCount());
+    }
+    try (var client =
+        new 
HttpJettySolrClient.Builder(solrTestRule.getBaseUrl()).useHttp1_1(false).build())
 {
+      queryDefaultCollection(client);
+      assertEquals(
+          HttpJettySolrClient.DEFAULT_MAX_HTTP2_CONNECTIONS_PER_HOST,
+          connectionPool(client).getMaxConnectionCount());
+    }
+  }
+
+  @Test
+  public void testMaxHttp2ConnectionsPerHostIgnoredForHttp1() {
+    try (var client =
+        new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+            .useHttp1_1(true)
+            .withMaxHttp2ConnectionsPerHost(MAX_HTTP2_CONNECTIONS)
+            .build()) {
+      assertEquals(
+          new HttpClient().getMaxConnectionsPerDestination(),
+          client.getHttpClient().getMaxConnectionsPerDestination());
+    }
+  }
+
+  @Test
+  public void testMaxHttp2ConnectionsPerHostValidation() {
+    var builder = new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl());
+    expectThrows(IllegalArgumentException.class, () -> 
builder.withMaxHttp2ConnectionsPerHost(0));
+  }
+
+  private static final long CONNECTION_IDLE_TIMEOUT_MS = 200;
+
+  /** How long to wait for the client to close an idle connection. */
+  private static final long CONNECTION_CLOSED_DEADLINE_MS = 50 * 
CONNECTION_IDLE_TIMEOUT_MS;
+
+  @Test
+  public void testConnectionIdleTimeoutClosesIdleConnections() throws 
Exception {
+    for (boolean useHttp1_1 : new boolean[] {false, true}) {
+      try (var client =
+          new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+              .useHttp1_1(useHttp1_1)
+              .withConnectionIdleTimeout(CONNECTION_IDLE_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)
+              .build()) {
+        assertEquals(CONNECTION_IDLE_TIMEOUT_MS, 
client.getHttpClient().getIdleTimeout());
+        queryDefaultCollection(client);
+        new TimeOut(CONNECTION_CLOSED_DEADLINE_MS, TimeUnit.MILLISECONDS, 
TimeSource.NANO_TIME)
+            .waitFor(
+                "idle connection was not closed, useHttp1_1=" + useHttp1_1,
+                () -> connectionPool(client).getConnectionCount() == 0);
+        queryDefaultCollection(client);
+      }
+    }
+  }
+
+  @Test
+  public void testNoConnectionIdleTimeoutByDefault() {
+    try (var client = new 
HttpJettySolrClient.Builder(solrTestRule.getBaseUrl()).build()) {
+      assertEquals(-1, client.getHttpClient().getIdleTimeout());
+    }
+  }
+
+  @Test
+  public void testConnectionOptionsWithHttpClient() {
+    try (var seed = new 
HttpJettySolrClient.Builder(solrTestRule.getBaseUrl()).build()) {
+      expectThrows(
+          IllegalArgumentException.class,
+          () ->
+              new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+                  .withHttpClient(seed)
+                  .withMaxHttp2ConnectionsPerHost(MAX_HTTP2_CONNECTIONS)
+                  .build());
+      expectThrows(
+          IllegalArgumentException.class,
+          () ->
+              new HttpJettySolrClient.Builder(solrTestRule.getBaseUrl())
+                  .withHttpClient(seed)
+                  .withConnectionIdleTimeout(CONNECTION_IDLE_TIMEOUT_MS, 
TimeUnit.MILLISECONDS)
+                  .build());
+    }
+  }
+
+  private static void queryDefaultCollection(HttpJettySolrClient client) {
+    try {
+      client.query(DEFAULT_COLLECTION, new SolrQuery("*:*"));
+    } catch (SolrServerException | IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private static AbstractConnectionPool connectionPool(HttpJettySolrClient 
client) {
+    List<Destination> destinations = client.getHttpClient().getDestinations();
+    assertEquals(1, destinations.size());
+    return (AbstractConnectionPool) destinations.get(0).getConnectionPool();
+  }
+
+  /** The pooled connection the next request would use, without opening a new 
one. */
+  private static Connection idleConnection(HttpJettySolrClient client) {
+    AbstractConnectionPool pool = connectionPool(client);
+    Connection connection = pool.acquire(false);
+    assertNotNull("no idle connection in " + pool, connection);

Review Comment:
   I think testConnectionReplacedAfterMaxDuration can fail intermittently on 
busy (slow :/ ?)  CI machines, even when max duration works correctly.
   
   `idleConnection()` checks the pool with `pool.acquire(false)`, but that call 
isn't read-only. 
   In Jetty 12.1, `AbstractConnectionPool.activate()` checks the connection's 
age on every acquire. If the connection has passed `maxDuration`, Jetty removes 
and closes it on the spot. With no other connection in the pool, and 
_create=false_, acquire returns _null_, and the `assertNotNull` fails.
   
   Each poll acquires twice: once in `queryDefaultCollection(client)` and once 
in `idleConnection(client)`. So if the connection's 50 ms expiry falls between 
the query's acquire and the helper's acquire, the helper retires it and the 
test fails with "_no idle connection in ...._". 
   
   The same can happen at the initial first capture if query `#1` takes longer 
than 50 ms. `TimeOut.waitFor` doesn't catch exceptions from the condition, so 
this fails the test immediately instead of retrying.
   
   I thought a longer maxDuration might help here but sadly it doesn't fully 
remove this. The connection still expires at some point during the polling, and 
the race happens whenever that point falls inside the query window. 
   A reliable way to see it: add a Thread.sleep(60) between 
queryDefaultCollection(client) and idleConnection(client). It's a simulation 
confirming that this is indeed an issue, but the probability of this getting 
triggered might be lower than my math suggests.
   
   Since a `null` from `acquire(false)` is a normal result when max duration is 
set, one option is to let the check return null and poll again:
   
   ```
   private static Connection idleConnectionOrNull(HttpJettySolrClient client) {
     AbstractConnectionPool pool = connectionPool(client);
     Connection connection = pool.acquire(false);
     if (connection != null) {
       pool.release(connection);
     }
     return connection;
   }
   ```
   
   Then the condition becomes 
   `current != null && current != first`
   and capturing first retries until it gets a connection. The test still fails 
if max duration is broken, because first is reused until the deadline. 
Separately, a max duration of a few hundred ms, with the deadline scaled to 
match, would make it more tolerant of slow machines. Today the deadline is 100 
* the max duration.
   
   It's worth running this test repeatedly (e.g. -Ptests.iters=50) to see how 
often it fails as written. I'll try this out too, but something for you to also 
check.
   
   You could use this 
   ```
   ./gradlew -p solr/solrj-jetty test --tests 
"HttpJettySolrClientTest.testConnectionReplacedAfterMaxDuration" 
-Ptests.iters=50```



##########
solr/solrj-jetty/src/java/org/apache/solr/client/solrj/jetty/HttpJettySolrClient.java:
##########
@@ -1131,6 +1162,62 @@ public HttpJettySolrClient.Builder 
withKeyStoreReloadInterval(long interval, Tim
       return this;
     }
 
+    /**
+     * Set the maximum time a pooled connection may be used for. Once a 
connection is older than
+     * this, it is closed instead of being reused, and a new connection is 
opened when needed. This
+     * applies to both HTTP/1.1 and HTTP/2 connections. If unset, 0 or less, 
connections are reused
+     * for as long as they stay open.
+     *
+     * @param duration Maximum connection lifetime
+     * @param unit The unit for the duration
+     * @return This builder
+     */
+    public HttpJettySolrClient.Builder withConnectionMaxDuration(long 
duration, TimeUnit unit) {
+      this.connectionMaxDurationMillis = unit.toMillis(duration);
+      if (this.connectionMaxDurationMillis == 0 && duration > 0) {
+        this.connectionMaxDurationMillis = 1L;
+      }
+      return this;
+    }
+
+    /**
+     * Set the maximum number of HTTP/2 connections opened per destination. 
Requests are multiplexed
+     * over these connections. Has no effect when using HTTP/1.1; see {@link
+     * #withMaxConnectionsPerHost(int)} for that. Defaults to {@value
+     * HttpJettySolrClient#DEFAULT_MAX_HTTP2_CONNECTIONS_PER_HOST}.
+     *
+     * @param max Maximum HTTP/2 connections per destination, at least 1
+     * @return This builder
+     */
+    public HttpJettySolrClient.Builder withMaxHttp2ConnectionsPerHost(int max) 
{
+      if (max < 1) {
+        throw new IllegalArgumentException(
+            "maxHttp2ConnectionsPerHost must be at least 1, got " + max);
+      }
+      this.maxHttp2ConnectionsPerHost = max;
+      return this;
+    }
+
+    /**
+     * Set how long a connection may go without any traffic before it is 
closed. This applies to
+     * both HTTP/1.1 and HTTP/2 connections. It is separate from {@link 
#withIdleTimeout(long,
+     * TimeUnit)}, which limits how long a single request may wait for data. 
Set it above the
+     * longest expected wait for a response: an HTTP/2 connection that sees no 
traffic for this long
+     * is closed even while a request on it is waiting. If unset, 0 or less, 
idle connections are
+     * not closed by the client.
+     *
+     * @param timeout Idle timeout for connections
+     * @param unit The unit for the timeout
+     * @return This builder
+     */
+    public HttpJettySolrClient.Builder withConnectionIdleTimeout(long timeout, 
TimeUnit unit) {

Review Comment:
   The javadoc warning is accurate, but the impact is wider than one request. 
With HTTP/2, once the connection has had no traffic for this long, Jetty closes 
the whole connection. Waiting for a response counts as no traffic, so every 
request still waiting on that connection will fail instead of just the slow one.
   
   The per-request idle timeout defaults to 600s. So setting, say, 
`withConnectionIdleTimeout(60, TimeUnit.SECONDS)` alone would quietly cap 
HTTP/2 requests at about 60s.
   
   Could we warn (or reject) at build time when, with HTTP/2, this is at or 
below the per-request idle timeout? At the least, the docs could mention that 
other in-flight requests fail too.



##########
solr/solrj-jetty/src/java/org/apache/solr/client/solrj/jetty/HttpJettySolrClient.java:
##########
@@ -290,7 +296,23 @@ private HttpClient createHttpClient(Builder builder) {
       HTTP2Client http2client = new HTTP2Client(clientConnector);
       transport = new HttpClientTransportOverHTTP2(http2client);
       httpClient = new HttpClient(transport);
-      httpClient.setMaxConnectionsPerDestination(4);
+      httpClient.setMaxConnectionsPerDestination(
+          builder.maxHttp2ConnectionsPerHost != null
+              ? builder.maxHttp2ConnectionsPerHost
+              : DEFAULT_MAX_HTTP2_CONNECTIONS_PER_HOST);
+    }
+
+    if (builder.connectionMaxDurationMillis != null && 
builder.connectionMaxDurationMillis > 0) {
+      long maxDurationMillis = builder.connectionMaxDurationMillis;
+      ConnectionPool.Factory poolFactory = 
transport.getConnectionPoolFactory();
+      transport.setConnectionPoolFactory(
+          destination -> {
+            ConnectionPool pool = poolFactory.newConnectionPool(destination);
+            if (pool instanceof AbstractConnectionPool abstractPool) {

Review Comment:
   would be good to add an else section here with a warning that highlights 
that the `setMaxDuratrion` is being ignored. This works right now as the 
current pools are AbstractConnectionPool.



##########
changelog/unreleased/SOLR-18643-jetty-client-connection-options.yml:
##########
@@ -0,0 +1,13 @@
+title: >
+  HttpJettySolrClient.Builder can now set the maximum lifetime of pooled 
connections
+  (withConnectionMaxDuration), the number of HTTP/2 connections per host 
(withMaxHttp2ConnectionsPerHost,
+  previously fixed at 4) and an idle timeout for connections 
(withConnectionIdleTimeout).
+type: added
+authors:
+  - name: Siju Varghese
+    nick: sijuv
+links:
+  - name: SOLR-18643

Review Comment:
   There's something off here and I've left a note on the JIRA as there's a 
seemingly unrelated commit associated with the same JIRA in the changelog + 
commit history. I'm pretty sure this PR belongs to the JIRA, but just something 
to fix.
   cc @gerlowskija 



##########
solr/solrj-jetty/src/java/org/apache/solr/client/solrj/jetty/HttpJettySolrClient.java:
##########
@@ -1203,7 +1290,10 @@ private boolean hasHttpClientBuildingOptions() {
           || proxyHost != null
           || sslConfig != null
           || cookieStore != null
-          || keyStoreReloadIntervalSecs != null;
+          || keyStoreReloadIntervalSecs != null
+          || connectionMaxDurationMillis != null
+          || maxHttp2ConnectionsPerHost != null
+          || connectionIdleTimeoutMillis != null;

Review Comment:
   Considering the javadoc says 0 or less means unset, it's worth it to reflect 
that in the code else it'll create issues.
   
   ```suggestion
             || (connectionMaxDurationMillis != null && 
connectionMaxDurationMillis > 0)
             || maxHttp2ConnectionsPerHost != null
             || (connectionIdleTimeoutMillis != null && 
connectionIdleTimeoutMillis > 0);
   ```
   The formatting might be a bit off, so please check.
   



##########
solr/solrj-jetty/src/java/org/apache/solr/client/solrj/jetty/HttpJettySolrClient.java:
##########
@@ -290,7 +296,23 @@ private HttpClient createHttpClient(Builder builder) {
       HTTP2Client http2client = new HTTP2Client(clientConnector);
       transport = new HttpClientTransportOverHTTP2(http2client);
       httpClient = new HttpClient(transport);
-      httpClient.setMaxConnectionsPerDestination(4);
+      httpClient.setMaxConnectionsPerDestination(
+          builder.maxHttp2ConnectionsPerHost != null
+              ? builder.maxHttp2ConnectionsPerHost
+              : DEFAULT_MAX_HTTP2_CONNECTIONS_PER_HOST);
+    }
+
+    if (builder.connectionMaxDurationMillis != null && 
builder.connectionMaxDurationMillis > 0) {
+      long maxDurationMillis = builder.connectionMaxDurationMillis;
+      ConnectionPool.Factory poolFactory = 
transport.getConnectionPoolFactory();
+      transport.setConnectionPoolFactory(
+          destination -> {
+            ConnectionPool pool = poolFactory.newConnectionPool(destination);
+            if (pool instanceof AbstractConnectionPool abstractPool) {
+              abstractPool.setMaxDuration(maxDurationMillis);
+            }

Review Comment:
   ```suggestion
               } else {
               log.warn(
                     "Connection max duration not applied: {} is not an 
AbstractConnectionPool",
                     pool.getClass().getName());
               }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to