This is an automated email from the ASF dual-hosted git repository.

jbonofre pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-java.git


The following commit(s) were added to refs/heads/main by this push:
     new 758fb56b8 GH-1268: [JDBC] Honor DriverManager login timeout (#1507)
758fb56b8 is described below

commit 758fb56b8e62707551881efc9441e9e9a882088d
Author: Abhishek Prajapati <[email protected]>
AuthorDate: Tue Nov 24 17:44:32 2026 +0530

    GH-1268: [JDBC] Honor DriverManager login timeout (#1507)
    
    ## What's Changed
    
    Honor the timeout configured through `DriverManager.setLoginTimeout`
    during Flight SQL JDBC connection establishment. The timeout covers the
    authentication handshake and initial session setup. Zero keeps the
    synchronous connection path without a login deadline.
    
    When the deadline expires, return `SQLTimeoutException` and cancel
    pending login RPCs. Release partially constructed clients, channels, and
    allocators on failure, and close a connection if it finishes after the
    caller has timed out.
    
    The JDBC login deadline and the Netty `connectTimeoutMs` socket setting
    are independent. DataSource login-timeout support is tracked separately
    in #1267.
    
    ## Testing
    
    - Reproduced the stalled authentication on upstream. The driver's
    two-second login timeout did not fire, and the regression test reached
    its 15-second guard.
    - Covered stalled authentication and session setup, cancellation and
    transport closure, successful connections with zero and positive
    timeouts, and cleanup after the deadline. The driver and client-handler
    test classes passed all 32 cases.
    - Maven verification passed on JDK 21 with 4,607 passing test executions
    and 73 skips across 14 modules. Checkstyle, Spotless, dependency
    analysis, and the shaded JAR build passed.
    - A standalone `DriverManager.getConnection` smoke test using the shaded
    JAR raised `SQLTimeoutException` in 1,022 ms with a one-second timeout.
    
    ## AI disclosure
    
    Codex assisted with diagnosis, implementation, tests, validation, and
    drafting this description.
    
    Closes #1268.
    
    Co-authored-by: Abhishek Prajapati 
<[email protected]>
---
 docs/source/flight_sql_jdbc_driver.rst             |   7 ++
 .../arrow/driver/jdbc/ArrowFlightConnection.java   |  77 ++++++-------
 .../driver/jdbc/ArrowFlightJdbcDataSource.java     |   2 +-
 .../arrow/driver/jdbc/ArrowFlightJdbcDriver.java   |  91 ++++++++++++++-
 .../jdbc/client/ArrowFlightSqlClientHandler.java   |  48 +++++---
 .../driver/jdbc/ArrowFlightJdbcDriverTest.java     | 126 ++++++++++++++++++++-
 .../client/ArrowFlightSqlClientHandlerTest.java    |   3 +
 7 files changed, 293 insertions(+), 61 deletions(-)

diff --git a/docs/source/flight_sql_jdbc_driver.rst 
b/docs/source/flight_sql_jdbc_driver.rst
index fe731fcaa..a685e2a79 100644
--- a/docs/source/flight_sql_jdbc_driver.rst
+++ b/docs/source/flight_sql_jdbc_driver.rst
@@ -195,6 +195,13 @@ DriverManager#getConnection()
 the username and password supplied on the URI supercede the username and
 password arguments to the function call.
 
+Use ``DriverManager.setLoginTimeout(seconds)`` to limit the time the driver
+waits for a connection, including the authentication handshake and initial
+session setup. On expiration, the driver cancels pending login RPCs and throws
+``SQLTimeoutException``. A value of zero disables the login timeout. The
+``connectTimeoutMs`` property separately controls the Netty socket connection
+timeout.
+
 OAuth 2.0 Authentication
 ========================
 
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
index 366223067..5338bfdc8 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
@@ -104,12 +104,18 @@ public final class ArrowFlightConnection extends 
AvaticaConnection {
       final Properties properties,
       final BufferAllocator allocator)
       throws SQLException {
-    url = replaceSemiColons(url);
-    final ArrowFlightConnectionConfigImpl config = new 
ArrowFlightConnectionConfigImpl(properties);
-    final ArrowFlightSqlClientHandler clientHandler =
-        createNewClientHandler(config, allocator, driver.getDriverVersion());
-    return new ArrowFlightConnection(
-        driver, factory, url, properties, config, allocator, clientHandler);
+    ArrowFlightSqlClientHandler clientHandler = null;
+    try {
+      url = replaceSemiColons(url);
+      final ArrowFlightConnectionConfigImpl config =
+          new ArrowFlightConnectionConfigImpl(properties);
+      clientHandler = createNewClientHandler(config, allocator, 
driver.getDriverVersion());
+      return new ArrowFlightConnection(
+          driver, factory, url, properties, config, allocator, clientHandler);
+    } catch (SQLException | RuntimeException | Error e) {
+      AutoCloseables.close(e, clientHandler, allocator);
+      throw e;
+    }
   }
 
   private static ArrowFlightSqlClientHandler createNewClientHandler(
@@ -117,40 +123,31 @@ public final class ArrowFlightConnection extends 
AvaticaConnection {
       final BufferAllocator allocator,
       final DriverVersion driverVersion)
       throws SQLException {
-    try {
-      return new ArrowFlightSqlClientHandler.Builder()
-          .withHost(config.getHost())
-          .withPort(config.getPort())
-          .withUsername(config.getUser())
-          .withPassword(config.getPassword())
-          .withTrustStorePath(config.getTrustStorePath())
-          .withTrustStorePassword(config.getTrustStorePassword())
-          .withSystemTrustStore(config.useSystemTrustStore())
-          .withTlsRootCertificates(config.getTlsRootCertificatesPath())
-          .withClientCertificate(config.getClientCertificatePath())
-          .withClientKey(config.getClientKeyPath())
-          .withBufferAllocator(allocator)
-          .withEncryption(config.useEncryption())
-          
.withDisableCertificateVerification(config.getDisableCertificateVerification())
-          .withHostnameOverride(config.getHostnameOverride())
-          .withToken(config.getToken())
-          .withCallOptions(config.toCallOption())
-          .withRetainCookies(config.retainCookies())
-          .withRetainAuth(config.retainAuth())
-          .withCatalog(config.getCatalog())
-          .withClientCache(config.useClientCache() ? new FlightClientCache() : 
null)
-          .withConnectTimeout(config.getConnectTimeout())
-          .withDriverVersion(driverVersion)
-          .withOAuthConfiguration(config.getOauthConfiguration())
-          .build();
-    } catch (final SQLException e) {
-      try {
-        allocator.close();
-      } catch (final Exception allocatorCloseEx) {
-        e.addSuppressed(allocatorCloseEx);
-      }
-      throw e;
-    }
+    return new ArrowFlightSqlClientHandler.Builder()
+        .withHost(config.getHost())
+        .withPort(config.getPort())
+        .withUsername(config.getUser())
+        .withPassword(config.getPassword())
+        .withTrustStorePath(config.getTrustStorePath())
+        .withTrustStorePassword(config.getTrustStorePassword())
+        .withSystemTrustStore(config.useSystemTrustStore())
+        .withTlsRootCertificates(config.getTlsRootCertificatesPath())
+        .withClientCertificate(config.getClientCertificatePath())
+        .withClientKey(config.getClientKeyPath())
+        .withBufferAllocator(allocator)
+        .withEncryption(config.useEncryption())
+        
.withDisableCertificateVerification(config.getDisableCertificateVerification())
+        .withHostnameOverride(config.getHostnameOverride())
+        .withToken(config.getToken())
+        .withCallOptions(config.toCallOption())
+        .withRetainCookies(config.retainCookies())
+        .withRetainAuth(config.retainAuth())
+        .withCatalog(config.getCatalog())
+        .withClientCache(config.useClientCache() ? new FlightClientCache() : 
null)
+        .withConnectTimeout(config.getConnectTimeout())
+        .withDriverVersion(driverVersion)
+        .withOAuthConfiguration(config.getOauthConfiguration())
+        .build();
   }
 
   void reset() throws SQLException {
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java
index 0b5d7fd36..068062a05 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java
@@ -87,7 +87,7 @@ public class ArrowFlightJdbcDataSource implements DataSource {
   public ArrowFlightConnection getConnection(final String username, final 
String password)
       throws SQLException {
     final Properties properties = getProperties(username, password);
-    return new ArrowFlightJdbcDriver().connect(config.url(), properties);
+    return new ArrowFlightJdbcDriver().connect(config.url(), properties, 0);
   }
 
   @Override
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java
index 12ef8030d..99d3b5815 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java
@@ -18,6 +18,7 @@ package org.apache.arrow.driver.jdbc;
 
 import static 
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.replaceSemiColons;
 
+import io.grpc.Context;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
@@ -25,11 +26,19 @@ import java.io.InputStreamReader;
 import java.io.Reader;
 import java.net.URI;
 import java.nio.charset.StandardCharsets;
+import java.sql.DriverManager;
 import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Properties;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.logging.Level;
 import java.util.logging.Logger;
 import 
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty;
 import org.apache.arrow.driver.jdbc.utils.UrlParser;
@@ -74,6 +83,11 @@ public class ArrowFlightJdbcDriver extends 
UnregisteredDriver {
   @Override
   public ArrowFlightConnection connect(final String url, final Properties info)
       throws SQLException {
+    return connect(url, info, DriverManager.getLoginTimeout());
+  }
+
+  ArrowFlightConnection connect(final String url, final Properties info, final 
int timeoutSeconds)
+      throws SQLException {
     final Properties properties = new Properties(info);
     if (info != null) {
       properties.putAll(info);
@@ -88,14 +102,89 @@ public class ArrowFlightJdbcDriver extends 
UnregisteredDriver {
       properties.putAll(propertiesFromUrl);
     }
 
+    final Properties connectionProperties = lowerCasePropertyKeys(properties);
+    if (timeoutSeconds <= 0) {
+      return openConnection(url, connectionProperties);
+    }
+    return connectWithTimeout(() -> openConnection(url, connectionProperties), 
timeoutSeconds);
+  }
+
+  private ArrowFlightConnection openConnection(final String url, final 
Properties properties)
+      throws SQLException {
     try {
       return ArrowFlightConnection.createNewConnection(
-          this, factory, url, lowerCasePropertyKeys(properties), new 
RootAllocator(Long.MAX_VALUE));
+          this, factory, url, properties, new RootAllocator(Long.MAX_VALUE));
     } catch (final FlightRuntimeException e) {
       throw new SQLException("Failed to connect.", e);
     }
   }
 
+  @VisibleForTesting
+  static ArrowFlightConnection connectWithTimeout(
+      final Callable<ArrowFlightConnection> connect, final int timeoutSeconds) 
throws SQLException {
+    final CompletableFuture<ArrowFlightConnection> result = new 
CompletableFuture<>();
+    // Closing the context cancels any in-flight login RPCs.
+    try (Context.CancellableContext context = 
Context.current().withCancellation()) {
+      final Thread worker =
+          new Thread(
+              context.wrap(
+                  () -> {
+                    if (result.isDone()) {
+                      return;
+                    }
+                    try {
+                      final ArrowFlightConnection connection = connect.call();
+                      // A timed-out attempt still owns any connection it 
manages to open.
+                      if (!result.complete(connection)) {
+                        closeAbandonedConnection(connection);
+                      }
+                    } catch (Exception | Error e) {
+                      result.completeExceptionally(e);
+                    }
+                  }),
+              "arrow-flight-jdbc-connect");
+      worker.setDaemon(true);
+      result.orTimeout(timeoutSeconds, TimeUnit.SECONDS);
+      worker.start();
+
+      try {
+        return result.get();
+      } catch (InterruptedException e) {
+        if (!result.completeExceptionally(e)) {
+          result.thenAcceptAsync(
+              connection -> context.run(() -> 
closeAbandonedConnection(connection)));
+        }
+        Thread.currentThread().interrupt();
+        throw new SQLException("Interrupted while connecting.", e);
+      } catch (ExecutionException e) {
+        final Throwable cause = e.getCause();
+        if (cause instanceof TimeoutException) {
+          throw new SQLTimeoutException(
+              "Login timed out after " + timeoutSeconds + " seconds.", cause);
+        }
+        if (cause instanceof SQLException sqlException) {
+          throw sqlException;
+        }
+        if (cause instanceof RuntimeException runtimeException) {
+          throw runtimeException;
+        }
+        if (cause instanceof Error error) {
+          throw error;
+        }
+        throw new SQLException("Failed to connect.", cause);
+      }
+    }
+  }
+
+  private static void closeAbandonedConnection(final ArrowFlightConnection 
connection) {
+    try {
+      connection.close();
+    } catch (SQLException | RuntimeException e) {
+      Logger.getLogger(ArrowFlightJdbcDriver.class.getPackageName())
+          .log(Level.WARNING, "Failed to close an abandoned flight SQL 
connection.", e);
+    }
+  }
+
   @Override
   protected String getFactoryClassName(final JdbcVersion jdbcVersion) {
     return ArrowFlightJdbcFactory.class.getName();
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
index 97108e599..9c168126a 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
@@ -17,6 +17,7 @@
 package org.apache.arrow.driver.jdbc.client;
 
 import com.google.common.collect.ImmutableMap;
+import io.grpc.ManagedChannel;
 import io.grpc.netty.NettyChannelBuilder;
 import io.netty.channel.ChannelOption;
 import java.io.IOException;
@@ -291,6 +292,19 @@ public final class ArrowFlightSqlClientHandler implements 
AutoCloseable {
 
   @Override
   public void close() throws SQLException {
+    try {
+      AutoCloseables.close(this::closeCatalogSession, sqlClient);
+    } catch (FlightRuntimeException fre) {
+      handleBenignCloseException(
+          fre, "Failed to clean up client resources.", "closing Flight SQL 
client");
+    } catch (SQLException e) {
+      throw e;
+    } catch (final Exception e) {
+      throw new SQLException("Failed to clean up client resources.", e);
+    }
+  }
+
+  private void closeCatalogSession() throws SQLException {
     if (catalog.isPresent()) {
       try {
         sqlClient.closeSession(new CloseSessionRequest(), getOptions());
@@ -299,14 +313,6 @@ public final class ArrowFlightSqlClientHandler implements 
AutoCloseable {
             fre, "Failed to close Flight SQL session.", "closing Flight SQL 
session");
       }
     }
-    try {
-      AutoCloseables.close(sqlClient);
-    } catch (FlightRuntimeException fre) {
-      handleBenignCloseException(
-          fre, "Failed to clean up client resources.", "closing Flight SQL 
client");
-    } catch (final Exception e) {
-      throw new SQLException("Failed to clean up client resources.", e);
-    }
   }
 
   /**
@@ -1125,6 +1131,7 @@ public final class ArrowFlightSqlClientHandler implements 
AutoCloseable {
       // itself.
       Set<FlightClientMiddleware.Factory> buildTimeMiddlewareFactories =
           new HashSet<>(this.middlewareFactories);
+      ManagedChannel channel = null;
       FlightClient client = null;
       boolean isUsingUserPasswordAuth = username != null && token == null;
 
@@ -1192,9 +1199,8 @@ public final class ArrowFlightSqlClientHandler implements 
AutoCloseable {
           channelBuilder.withOption(
               ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) 
connectTimeout.toMillis());
         }
-        client =
-            FlightGrpcUtils.createFlightClient(
-                allocator, channelBuilder.build(), clientBuilder.middleware());
+        channel = channelBuilder.build();
+        client = FlightGrpcUtils.createFlightClient(allocator, channel, 
clientBuilder.middleware());
         final ArrayList<CallOption> credentialOptions = new ArrayList<>();
         // Authentication priority: OAuth > token > username/password
         if (oauthConfig != null) {
@@ -1229,14 +1235,20 @@ public final class ArrowFlightSqlClientHandler 
implements AutoCloseable {
           | IOException
           | FlightRuntimeException e) {
         final SQLException originalException = new SQLException(e);
-        if (client != null) {
-          try {
-            client.close();
-          } catch (final InterruptedException interruptedException) {
-            originalException.addSuppressed(interruptedException);
-          }
-        }
+        closeFailedClient(originalException, client, channel);
         throw originalException;
+      } catch (RuntimeException | Error e) {
+        closeFailedClient(e, client, channel);
+        throw e;
+      }
+    }
+
+    private static void closeFailedClient(
+        Throwable failure, @Nullable FlightClient client, @Nullable 
ManagedChannel channel) {
+      if (client != null) {
+        AutoCloseables.close(failure, client);
+      } else if (channel != null) {
+        AutoCloseables.close(failure, channel::shutdownNow);
       }
     }
   }
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java
index 88fb9889b..878cff2d2 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java
@@ -21,24 +21,42 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
-
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+
+import io.grpc.Attributes;
+import io.grpc.MethodDescriptor;
+import io.grpc.Server;
+import io.grpc.ServerBuilder;
+import io.grpc.ServerCall;
+import io.grpc.ServerServiceDefinition;
+import io.grpc.ServerTransportFilter;
 import java.sql.Connection;
 import java.sql.Driver;
 import java.sql.DriverManager;
 import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
 import java.util.Collection;
 import java.util.Map;
 import java.util.Properties;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication;
 import 
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty;
 import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
+import org.apache.arrow.flight.impl.FlightServiceGrpc;
 import org.apache.arrow.memory.BufferAllocator;
 import org.apache.arrow.memory.RootAllocator;
 import org.apache.arrow.util.AutoCloseables;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.parallel.ResourceLock;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /** Tests for {@link ArrowFlightJdbcDriver}. */
 public class ArrowFlightJdbcDriverTest {
@@ -91,6 +109,112 @@ public class ArrowFlightJdbcDriverTest {
             instanceof ArrowFlightJdbcDriver);
   }
 
+  @ParameterizedTest(name = "connection setup with catalog={0}")
+  @ValueSource(booleans = {false, true})
+  @Timeout(15)
+  @ResourceLock("DriverManager.loginTimeout")
+  public void testDriverManagerLoginTimeoutCancelsConnectionSetup(boolean 
catalog)
+      throws Exception {
+    final CountDownLatch loginRpcStarted = new CountDownLatch(1);
+    final CountDownLatch loginRpcCancelled = new CountDownLatch(1);
+    final CountDownLatch transportClosed = new CountDownLatch(1);
+    final MethodDescriptor<?, ?> loginMethod =
+        catalog ? FlightServiceGrpc.getDoActionMethod() : 
FlightServiceGrpc.getHandshakeMethod();
+    final Server server =
+        ServerBuilder.forPort(0)
+            .addTransportFilter(
+                new ServerTransportFilter() {
+                  @Override
+                  public void transportTerminated(Attributes 
transportAttributes) {
+                    transportClosed.countDown();
+                  }
+                })
+            .addService(stalledLoginService(loginMethod, loginRpcStarted, 
loginRpcCancelled))
+            .build()
+            .start();
+    final int previousTimeout = DriverManager.getLoginTimeout();
+    try {
+      DriverManager.setLoginTimeout(2);
+      final String url =
+          "jdbc:arrow-flight-sql://localhost:" + server.getPort() + 
"?useEncryption=false";
+      final Properties properties = new Properties();
+      if (catalog) {
+        properties.setProperty("catalog", "test");
+      } else {
+        properties.setProperty("user", "user");
+        properties.setProperty("password", "pass");
+      }
+      // Other tests register additional Arrow drivers, which DriverManager 
would also try.
+      final Driver driver = DriverManager.getDriver(url);
+      assertThrows(SQLTimeoutException.class, () -> driver.connect(url, 
properties));
+      assertEquals(0, loginRpcStarted.getCount(), "The server should have 
received the login RPC");
+      assertTrue(loginRpcCancelled.await(5, TimeUnit.SECONDS), "The login RPC 
should be cancelled");
+      assertTrue(transportClosed.await(5, TimeUnit.SECONDS), "The client 
channel should close");
+    } finally {
+      DriverManager.setLoginTimeout(previousTimeout);
+      server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
+    }
+  }
+
+  private static <RequestT, ResponseT> ServerServiceDefinition 
stalledLoginService(
+      MethodDescriptor<RequestT, ResponseT> method,
+      CountDownLatch started,
+      CountDownLatch cancelled) {
+    return ServerServiceDefinition.builder(FlightServiceGrpc.SERVICE_NAME)
+        .addMethod(
+            method,
+            (call, headers) -> {
+              call.request(1);
+              started.countDown();
+              return new ServerCall.Listener<RequestT>() {
+                @Override
+                public void onCancel() {
+                  cancelled.countDown();
+                }
+              };
+            })
+        .build();
+  }
+
+  @ParameterizedTest
+  @ValueSource(ints = {0, 10})
+  @ResourceLock("DriverManager.loginTimeout")
+  public void testDriverManagerConnectsWithLoginTimeout(int loginTimeout) 
throws Exception {
+    final int previousTimeout = DriverManager.getLoginTimeout();
+    try {
+      DriverManager.setLoginTimeout(loginTimeout);
+      final String url =
+          "jdbc:arrow-flight-sql://localhost:"
+              + FLIGHT_SERVER_TEST_EXTENSION.getPort()
+              + "?useEncryption=false";
+      try (Connection connection = DriverManager.getConnection(url, "user1", 
"pass1")) {
+        assertTrue(connection.isValid(0));
+      }
+    } finally {
+      DriverManager.setLoginTimeout(previousTimeout);
+    }
+  }
+
+  @Test
+  public void testConnectionCompletedAfterLoginTimeoutIsClosed() throws 
Exception {
+    final ArrowFlightConnection connection = mock(ArrowFlightConnection.class);
+    final CountDownLatch finishConnecting = new CountDownLatch(1);
+    try {
+      assertThrows(
+          SQLTimeoutException.class,
+          () ->
+              ArrowFlightJdbcDriver.connectWithTimeout(
+                  () -> {
+                    assertTrue(finishConnecting.await(5, TimeUnit.SECONDS));
+                    return connection;
+                  },
+                  1));
+    } finally {
+      finishConnecting.countDown();
+    }
+    verify(connection, timeout(5000)).close();
+  }
+
   /**
    * Tests whether the {@link ArrowFlightJdbcDriver} returns null when 
provided with an unsupported
    * URL prefix.
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
index b44b310eb..4d37b9110 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java
@@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoInteractions;
 import static org.mockito.Mockito.when;
 
@@ -145,6 +146,7 @@ public class ArrowFlightSqlClientHandlerTest {
     } else {
       assertThrows(SQLException.class, sqlClientHandler::close);
     }
+    verify(sqlClient).close();
   }
 
   private static Object[] testCloseHandlesFlightRuntimeException() {
@@ -163,6 +165,7 @@ public class ArrowFlightSqlClientHandlerTest {
       new Object[] {false, unavailableError, true},
       new Object[] {true, unknownError, false},
       new Object[] {false, unknownError, false},
+      new Object[] {true, CallStatus.CANCELLED, false},
     };
   }
 }

Reply via email to